diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index a0c3d6f9..2ad3038a 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -12963,7 +12963,6 @@ struct PlaneBuf<'a> { /// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already /// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/ /// `ALTREF2`/`ALTREF`). -type RefSlots<'a> = [Option<(&'a PlaneBuf<'a>, &'a PlaneBuf<'a>, &'a PlaneBuf<'a>)>; 8]; impl PlaneBuf<'_> { /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/ @@ -23163,27 +23162,124 @@ fn read_single_ref( /// own doc. Called from [`decode_inter_block`] once its own `reference_select` /// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same /// way with a coarser (`LAST_FRAME`-only) neighbour shape. -/// Resolves a compound reference's own planes -- the same `ref_frame == -/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup -/// [`decode_inter_block`]'s single-ref path already does, factored out so -/// the compound path can call it twice (lane-av1comp). -fn ref_planes<'a>( +/// lane-twostage: this frame's references as DIMENSIONS now and PIXELS on +/// demand. An inter tile's parse reads reference SIZES (`mc::scale_factor`) +/// but touches no reference PIXEL until its first prediction -- measured 4.2% +/// of a 4K tile's parse into it -- so the pictures are resolved here, at the +/// first [`ref_planes`] call, rather than at frame entry. On the threaded +/// path that resolution is a WAIT on the producing frame's pixels, which is +/// what lets a consumer parse while its references are still being filtered. +pub(crate) struct RefPix<'p> { + /// `(width, height)` per `ref_frame` index (`LAST_FRAME` = 1). `None` is + /// a slot this frame may not use: empty, or -- for a non-`LAST_FRAME` + /// slot -- not the same size as `LAST_FRAME`'s own picture (spec 7.9's + /// compatible-size rule, the filter the eager `owned_refs` array applied). + dims: [Option<(usize, usize)>; 8], + src: RefSrc<'p>, + bufs: std::sync::OnceLock<[Option<(PlaneBuf<'p>, PlaneBuf<'p>, PlaneBuf<'p>)>; 8]>, +} + +/// Where a [`RefPix`] gets its pictures: already in hand, or behind a wait +/// the caller owns (`stream.rs`'s reference promises). +enum RefSrc<'p> { + Ready([Option<&'p Picture>; 8]), + Lazy(&'p (dyn Fn() -> Result<[Option<&'p Picture>; 8]> + Send + Sync + 'p)), +} + +/// `LAST_FRAME`'s own index in a [`RefPix`] (spec 6.10.24). +const LAST_REF: usize = 1; + +impl<'p> RefPix<'p> { + /// References already decoded: the single-threaded path and the test + /// entry points, where [`ref_planes`] never waits. + pub(crate) fn ready(refs: [Option<&'p Picture>; 8]) -> Self { + let dims = Self::compatible(std::array::from_fn(|i| { + refs[i].map(|p| (p.width, p.height)) + })); + Self { dims, src: RefSrc::Ready(refs), bufs: std::sync::OnceLock::new() } + } + + /// References whose sizes are known (from their producers' headers) but + /// whose pixels `wait` still has to produce. + pub(crate) fn lazy( + dims: [Option<(usize, usize)>; 8], + wait: &'p (dyn Fn() -> Result<[Option<&'p Picture>; 8]> + Send + Sync + 'p), + ) -> Self { + Self { dims: Self::compatible(dims), src: RefSrc::Lazy(wait), bufs: std::sync::OnceLock::new() } + } + + /// Spec 7.9's compatible-size rule: a non-`LAST_FRAME` slot at a + /// different size than `LAST_FRAME`'s is treated as absent, exactly as + /// the eager `owned_refs.filter(..)` did. + fn compatible(mut dims: [Option<(usize, usize)>; 8]) -> [Option<(usize, usize)>; 8] { + let last = dims[LAST_REF]; + for (i, d) in dims.iter_mut().enumerate() { + if i != LAST_REF && *d != last { + *d = None; + } + } + dims + } + + /// This slot's picture size, without touching its pixels. + pub(crate) fn dims(&self, ref_frame: i8) -> Option<(usize, usize)> { + self.dims.get(ref_frame as usize).copied().flatten() + } + + /// Every usable slot's three planes, resolving (and, on the threaded + /// path, waiting for) the pictures on the first call. + fn planes(&self) -> Result<&[Option<(PlaneBuf<'p>, PlaneBuf<'p>, PlaneBuf<'p>)>; 8]> { + if let Some(bufs) = self.bufs.get() { + return Ok(bufs); + } + let pics = match &self.src { + RefSrc::Ready(refs) => *refs, + RefSrc::Lazy(wait) => wait()?, + }; + let dims = self.dims; + let bufs = std::array::from_fn(|i| { + dims[i].and(pics[i]).map(|g| { + ( + whole_plane(&g.y, g.width, g.height), + whole_plane(&g.u, g.width / 2, g.height / 2), + whole_plane(&g.v, g.width / 2, g.height / 2), + ) + }) + }); + let _ = self.bufs.set(bufs); + Ok(self.bufs.get().expect("the plane array was just set")) + } +} + +/// A whole reference plane as a [`PlaneBuf`]: no tile window, no margin. +fn whole_plane(data: &[u16], width: usize, height: usize) -> PlaneBuf<'_> { + PlaneBuf { + data: std::borrow::Cow::Borrowed(data), + width, + height, + true_width: width, + true_height: height, + tile_x0: 0, + tile_y0: 0, + tile_x1: width, + tile_y1: height, + } +} + +/// Resolves a reference's own planes -- the `ref_frame -> picture` lookup +/// [`decode_inter_block`]'s single-ref path does, factored out so the +/// compound path can call it twice (lane-av1comp), and the point where +/// lane-twostage's pixel wait happens. +fn ref_planes<'a, 'p>( ref_frame: i8, - ref_y: &'a PlaneBuf<'a>, - ref_u: &'a PlaneBuf<'a>, - ref_v: &'a PlaneBuf<'a>, - other_refs: &'a RefSlots, -) -> Result<(&'a PlaneBuf<'a>, &'a PlaneBuf<'a>, &'a PlaneBuf<'a>)> { - if ref_frame == LAST_FRAME { - Ok((ref_y, ref_u, ref_v)) - } else { - match other_refs[ref_frame as usize] { - Some((ry, ru, rv)) => Ok((ry, ru, rv)), - None => Err(unsupported( - "a reference frame selected with no picture at this frame's own \ + refpix: &'a RefPix<'p>, +) -> Result<(&'a PlaneBuf<'p>, &'a PlaneBuf<'p>, &'a PlaneBuf<'p>)> { + match refpix.planes()?.get(ref_frame as usize).and_then(Option::as_ref) { + Some((y, u, v)) => Ok((y, u, v)), + None => Err(unsupported( + "a reference frame selected with no picture at this frame's own \ ref_frame_idx slot for it", - )), - } + )), } } @@ -23897,10 +23993,7 @@ fn obmc_blend( py: usize, cpx: usize, cpy: usize, - ref_y: &PlaneBuf<'_>, - ref_u: &PlaneBuf<'_>, - ref_v: &PlaneBuf<'_>, - other_refs: &RefSlots, + refpix: &RefPix<'_>, interp_fixed: Option, // lane-scaledref r1: this frame's own coded luma width -- each OBMC // neighbour is re-predicted against ITS OWN reference, which may be @@ -24011,7 +24104,7 @@ fn obmc_blend( ); let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?; ec_obmc_trace("above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind); - let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?; + let (ny, nu, nv) = ref_planes(nb.ref_frame, refpix)?; let nb_scale = mc::scale_factor(ny.width, frame_width); if mi_col + off4 + span4 > mi_cols { OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1)); @@ -24047,7 +24140,7 @@ fn obmc_blend( ); let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?; ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind); - let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?; + let (ny, nu, nv) = ref_planes(nb.ref_frame, refpix)?; let nb_scale = mc::scale_factor(ny.width, frame_width); if mi_row + off4 + span4 > mi_rows { OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1)); @@ -24480,16 +24573,13 @@ fn decode_inter_block( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, - ref_y: &PlaneBuf<'_>, - ref_u: &PlaneBuf<'_>, - ref_v: &PlaneBuf<'_>, + refpix: &RefPix<'_>, // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]` // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME` // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the // slot's still empty (an error-resilient stream, or too early in the // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below. - other_refs: &RefSlots, sign_bias_table: &SignBiasTable, // lane-gm r2: this frame header's own `global_motion` table (spec // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table` @@ -24901,8 +24991,8 @@ fn decode_inter_block( if gm_nontrans_models && !gm_nontrans { GM_NONTRANS_SMALL_SIDE_HITS.with(|c| c.set(c.get() + 1)); } - let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?; - let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?; + let (py0, pu0, pv0) = ref_planes(ref0, refpix)?; + let (py1, pu1, pv1) = ref_planes(ref1, refpix)?; // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from @@ -24944,7 +25034,7 @@ fn decode_inter_block( // scaled (superres) is predicted translationally while its // sibling may still warp. let ref_unscaled = |rf: i8| { - ref_planes(rf, ref_y, ref_u, ref_v, other_refs) + ref_planes(rf, refpix) .is_ok_and(|(py, _, _)| { mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE }) @@ -26025,19 +26115,7 @@ fn decode_inter_block( // below same as every other non-`LAST_FRAME` reference. lane-av1refs // widens this from GOLDEN alone to every reference `read_single_ref` // can name. - let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME { - (ref_y, ref_u, ref_v) - } else { - match other_refs[ref_frame as usize] { - Some((ry, ru, rv)) => (ry, ru, rv), - None => { - return Err(unsupported( - "a reference frame selected with no picture at this frame's own \ - ref_frame_idx slot for it", - )); - } - } - }; + let (py_ref, pu_ref, pv_ref) = ref_planes(ref_frame, refpix)?; let (mi_row, mi_col) = (rmi, cmi); // lane-rect r2: the mv stack must be queried with the block's @@ -26834,10 +26912,7 @@ fn decode_inter_block( py, cpx, cpy, - ref_y, - ref_u, - ref_v, - other_refs, + refpix, interp_fixed, frame_width, &mut pred_y, @@ -26866,7 +26941,7 @@ fn decode_inter_block( // reference was scaled, which silently left the whole-block // prediction in place instead of refusing. It scales off the // PREVIOUS strip's own reference, not this block's. - let (prev_y_plane, prev_u, prev_v_plane) = ref_planes(prev_ref, ref_y, ref_u, ref_v, other_refs)?; + let (prev_y_plane, prev_u, prev_v_plane) = ref_planes(prev_ref, refpix)?; let prev_scale = mc::scale_factor(prev_y_plane.width, frame_width); for (src, dst) in [(prev_u, &mut pred_u), (prev_v_plane, &mut pred_v)] { let mut piece = vec![0u16; piece_w * piece_h]; @@ -28267,10 +28342,7 @@ fn decode_inter_sub8_split4( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, - ref_y: &PlaneBuf<'_>, - ref_u: &PlaneBuf<'_>, - ref_v: &PlaneBuf<'_>, - other_refs: &RefSlots, + refpix: &RefPix<'_>, sign_bias_table: &SignBiasTable, global_motion: &[ec_av1_syntax::WarpParams; 7], base_q_idx: u8, @@ -28388,7 +28460,7 @@ fn decode_inter_sub8_split4( neighbours.left_ref[rmi], neighbours.left_ref1[rmi], ); - let (sref_y, _sref_u, _sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?; + let (sref_y, _sref_u, _sref_v) = ref_planes(ref_frame, refpix)?; // lane-t900 r28: refusal lifted -- this sub-block's own reference may // be scaled (superres); spec 7.11.3.3's walk is per reference, and // each of the group's pieces (luma and its 2x2 chroma) carries its @@ -28658,7 +28730,7 @@ fn decode_inter_sub8_split4( continue; }; let (piece_ref_y, sref_u, sref_v) = - ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?; + ref_planes(ref_frame, refpix)?; let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width); let (ox, oy) = if mixed { (cpx, cpy) @@ -29222,10 +29294,7 @@ fn decode_inter_sub8_rect2( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, - ref_y: &PlaneBuf<'_>, - ref_u: &PlaneBuf<'_>, - ref_v: &PlaneBuf<'_>, - other_refs: &RefSlots, + refpix: &RefPix<'_>, sign_bias_table: &SignBiasTable, global_motion: &[ec_av1_syntax::WarpParams; 7], base_q_idx: u8, @@ -29361,7 +29430,7 @@ fn decode_inter_sub8_rect2( neighbours.left_ref[rmi], neighbours.left_ref1[rmi], ); - let (sref_y, _, _) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?; + let (sref_y, _, _) = ref_planes(ref_frame, refpix)?; // lane-t900 r28: refusal lifted -- see the split arm above. let luma_scale = mc::scale_factor(sref_y.width, frame_width); if luma_scale != mc::REF_NO_SCALE { @@ -29673,7 +29742,7 @@ fn decode_inter_sub8_rect2( continue; }; let (piece_ref_y, sref_u, sref_v) = - ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?; + ref_planes(ref_frame, refpix)?; let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width); let (ox, oy) = if mixed { (cpx, cpy) @@ -29827,10 +29896,7 @@ fn decode_inter_block8( y: &mut PlaneBuf<'static>, u: &mut PlaneBuf<'static>, v: &mut PlaneBuf<'static>, - ref_y: &PlaneBuf<'_>, - ref_u: &PlaneBuf<'_>, - ref_v: &PlaneBuf<'_>, - other_refs: &RefSlots, + refpix: &RefPix<'_>, base_q_idx: u8, scan8: &[u16], scan4: &[u16], @@ -30292,8 +30358,8 @@ fn decode_inter_block8( COMPOUND8_FILTER_HITS.with(|c| c.set(c.get() + 1)); } - let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?; - let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?; + let (py0, pu0, pv0) = ref_planes(ref0, refpix)?; + let (py1, pu1, pv1) = ref_planes(ref1, refpix)?; let scale0 = mc::scale_factor(py0.width, frame_width); let scale1 = mc::scale_factor(py1.width, frame_width); if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE { @@ -30346,7 +30412,7 @@ fn decode_inter_block8( // lane-t900 r28: same per-slot `allow_warp` scale bail-out as // the 16x16-and-bigger compound path above. let leaf_ref_unscaled = |rf: i8| { - ref_planes(rf, ref_y, ref_u, ref_v, other_refs) + ref_planes(rf, refpix) .is_ok_and(|(py, _, _)| { mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE }) @@ -30721,7 +30787,7 @@ fn decode_inter_block8( neighbours.left_ref1[rmi], ); leaf_refs = (ref_frame, None); - let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?; + let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, refpix)?; let (mi_row, mi_col) = leaf_mi; // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS @@ -31156,10 +31222,7 @@ fn decode_inter_block8( py, cpx, cpy, - ref_y, - ref_u, - ref_v, - other_refs, + refpix, interp_fixed, frame_width, &mut pred_y, @@ -31861,8 +31924,7 @@ pub(crate) fn decode_inter_frame_tile( base_q_idx: u8, frame_width: u32, frame_height: u32, - reference: &Picture, - other_refs: [Option<&Picture>; 8], + refpix: &RefPix<'_>, cdef: &CdefParams, loop_filter: &LoopFilterParams, allow_high_precision_mv: bool, @@ -31885,8 +31947,7 @@ pub(crate) fn decode_inter_frame_tile( crate::quant::QuantDeltas::default(), frame_width, frame_height, - reference, - other_refs, + refpix, cdef, loop_filter, &LoopRestorationParams::default(), @@ -31918,7 +31979,9 @@ pub(crate) fn decode_inter_frame_tile( // `enable_filter_intra`: this crate's own encoder never writes the // sequence bit (`encode.rs`), so no intra-in-inter block of a stream // reaching this entry point reads a `use_filter_intra` symbol. - false, fctx, + false, + None, + fctx, ) .map(|(picture, _, _)| picture) } @@ -31938,8 +32001,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( deltas: crate::quant::QuantDeltas, frame_width: u32, frame_height: u32, - reference: &Picture, - other_refs: [Option<&Picture>; 8], + refpix: &RefPix<'_>, cdef: &CdefParams, loop_filter: &LoopFilterParams, lr: &LoopRestorationParams, @@ -32006,8 +32068,18 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // (spec 5.5.2), stashed in a thread-local with `tx_select` rather than // threaded through `decode_inter_block`'s fifty parameters -- read by the // intra-in-inter arms' `read_filter_intra_mode_info`. - enable_filter_intra: bool, fctx: &crate::decode::FrameCtx, -) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> { + enable_filter_intra: bool, + // lane-twostage: called with this frame's own end-of-tile CDFs, motion + // field and picture size the moment its last tile symbol is read -- + // BEFORE its filters run, so a frame that references this one can start + // parsing while this one is still being deblocked/CDEF'd/restored (it + // waits for the pixels themselves at its first prediction). `None`, and + // the motion field comes back in the return tuple as it always did: + // the single-threaded path, and a superres frame (whose final width is + // only known after the upscale). + stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>, + fctx: &crate::decode::FrameCtx, +) -> Result<(Picture, Cdfs, Option)> { set_inter_tx_mode(tx_select, reduced_tx_set, enable_filter_intra, fctx); let tpl_frame = tpl_field.map(|field| TplFrameArgs { field, @@ -32037,7 +32109,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // refused every same-size reference (class av1-truesize-lane: true // frame size vs mi-rounded). Height must still MATCH: AV1 superres // never scales height, and no path here has a vertical scaling pass. - if reference.height != frame_height as usize { + if refpix.dims(1).is_none_or(|(_, h)| h != frame_height as usize) { return Err(unsupported( "a reference picture whose height does not match this frame's own true size", )); @@ -32050,90 +32122,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]); let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK); - let ref_y = PlaneBuf { - data: std::borrow::Cow::Borrowed(&reference.y), - width: reference.width, - height: reference.height, - true_width: reference.width, - true_height: reference.height, - tile_x0: 0, - tile_y0: 0, - tile_x1: reference.width, - tile_y1: reference.height, - }; - let ref_u = PlaneBuf { - data: std::borrow::Cow::Borrowed(&reference.u), - width: reference.width / 2, - height: reference.height / 2, - true_width: reference.width / 2, - true_height: reference.height / 2, - tile_x0: 0, - tile_y0: 0, - tile_x1: reference.width / 2, - tile_y1: reference.height / 2, - }; - let ref_v = PlaneBuf { - data: std::borrow::Cow::Borrowed(&reference.v), - width: reference.width / 2, - height: reference.height / 2, - true_width: reference.width / 2, - true_height: reference.height / 2, - tile_x0: 0, - tile_y0: 0, - tile_x1: reference.width / 2, - tile_y1: reference.height / 2, - }; - // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx` - // names a live DPB slot for (lane-av1refs: generalised from the old - // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal, - // now per-reference). `decode_inter_block` refuses by name when the - // block it is decoding selects an index that is still `None` here - // (spec 7.9 requires every *active* reference be a compatible size; - // an inactive one this frame never selects is simply left `None`). - let owned_refs: [Option<(PlaneBuf<'_>, PlaneBuf<'_>, PlaneBuf<'_>)>; 8] = std::array::from_fn(|i| { - other_refs[i] - .filter(|g| g.width == reference.width && g.height == reference.height) - .map(|g| { - ( - PlaneBuf { - data: std::borrow::Cow::Borrowed(&g.y), - width: g.width, - height: g.height, - true_width: g.width, - true_height: g.height, - tile_x0: 0, - tile_y0: 0, - tile_x1: g.width, - tile_y1: g.height, - }, - PlaneBuf { - data: std::borrow::Cow::Borrowed(&g.u), - width: g.width / 2, - height: g.height / 2, - true_width: g.width / 2, - true_height: g.height / 2, - tile_x0: 0, - tile_y0: 0, - tile_x1: g.width / 2, - tile_y1: g.height / 2, - }, - PlaneBuf { - data: std::borrow::Cow::Borrowed(&g.v), - width: g.width / 2, - height: g.height / 2, - true_width: g.width / 2, - true_height: g.height / 2, - tile_x0: 0, - tile_y0: 0, - tile_x1: g.width / 2, - tile_y1: g.height / 2, - }, - ) - }) - }); - let ref_slots: RefSlots = - std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c))); - let mut y = PlaneBuf { data: std::borrow::Cow::Owned(fresh_plane(width * height)), width, @@ -32494,10 +32482,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -32567,10 +32552,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, base_q_idx, &scan8, &scan4, @@ -32869,10 +32851,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -33040,10 +33019,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -33190,10 +33166,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -33301,10 +33274,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -33388,10 +33358,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -33632,11 +33599,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // 7.11.3.3's scaled walk. The counter is what // proves a gate actually reached a scaled // leaf rather than a same-size reference. - if ref_y.width != frame_width as usize - || ref_slots.iter().flatten().any(|(py, _, _)| { - py.width != frame_width as usize + if (1..8).any(|rf| { + refpix.dims(rf).is_some_and(|(w, _)| { + w != frame_width as usize }) - { + }) { SCALED_LEAF8_HITS.with(|c| c.set(c.get() + 1)); } let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option)> = Vec::new(); @@ -33659,10 +33626,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -33700,10 +33664,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -33739,10 +33700,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, base_q_idx, &scan8, &scan4, @@ -33836,10 +33794,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -33889,10 +33844,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -33943,10 +33895,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34007,10 +33956,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34063,10 +34009,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34120,10 +34063,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34176,10 +34116,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34234,10 +34171,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34287,10 +34221,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34340,10 +34271,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34395,10 +34323,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34448,10 +34373,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34501,10 +34423,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34557,10 +34476,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34606,10 +34522,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34659,10 +34572,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, - &ref_slots, + refpix, &sign_bias_table, &global_motion, base_q_idx, @@ -34766,6 +34676,28 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } } crate::timeline::recon_done(); + // lane-twostage: the motion field is built from the mode-info grid alone + // (no pixel), so it moves up here with the CDFs -- everything a + // consuming frame's SETUP needs, published before this frame's filters. + let mut motion_field = Some(build_motion_field( + &grid, + mi_cols as usize, + mi_rows as usize, + order_hint, + order_hint_bits, + ref_order_hints, + fctx, + )); + if let Some(stage1) = stage1 + && superres(fctx).is_none() + { + stage1( + result_cdfs.clone(), + motion_field.take().expect("the motion field was just built"), + frame_width as usize, + frame_height as usize, + ); + } // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against @@ -34912,15 +34844,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } crate::timeline::filters_done(); - let motion_field = build_motion_field( - &grid, - mi_cols as usize, - mi_rows as usize, - order_hint, - order_hint_bits, - ref_order_hints, - fctx, - ); let (fw, fh) = (lr_w, frame_height as usize); // An upscaled frame is already at its final size with no mi-aligned @@ -35772,27 +35695,25 @@ mod tests { fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() { const REFUSAL: &str = "a reference frame selected with no picture at this frame's own ref_frame_idx slot"; - let plane = PlaneBuf { - data: std::borrow::Cow::Owned(vec![0u16; 16]), + let pic = Picture { width: 4, height: 4, - true_width: 4, - true_height: 4, - tile_x0: 0, - tile_y0: 0, - tile_x1: 4, - tile_y1: 4, + y: vec![0u16; 16], + u: vec![0u16; 4], + v: vec![0u16; 4], }; - let empty: RefSlots = [None; 8]; + let mut refs: [Option<&Picture>; 8] = [None; 8]; + refs[1] = Some(&pic); + let refpix = RefPix::ready(refs); for ref_frame in [LAST2_FRAME, LAST3_FRAME, GOLDEN_FRAME, BWDREF_FRAME, ALTREF2_FRAME, ALTREF_FRAME] { - let err = match ref_planes(ref_frame, &plane, &plane, &plane, &empty) { + let err = match ref_planes(ref_frame, &refpix) { Ok(_) => panic!("ref {ref_frame}: an empty slot resolved to a picture"), Err(e) => e.to_string(), }; assert!(err.contains(REFUSAL), "ref {ref_frame}: expected {REFUSAL:?}, got: {err}"); } // `LAST_FRAME` never consults the slots: `decode_stream` checked it. - let Ok((y, _, _)) = ref_planes(LAST_FRAME, &plane, &plane, &plane, &empty) else { + let Ok((y, _, _)) = ref_planes(LAST_FRAME, &refpix) else { panic!("LAST_FRAME resolves to the frame's own reference planes") }; assert_eq!(y.width, 4); @@ -36581,9 +36502,7 @@ mod tests { &mut y, &mut u, &mut v, - &ref_y, - &ref_u, - &ref_v, + refpix, &[None; 8], &NO_SIGN_BIAS, &[ec_av1_syntax::WarpParams::default(); 7], diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index b4a0bfab..774fd9a6 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -343,7 +343,12 @@ pub fn frames_dispatched() -> usize { /// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated /// object -- so a slot costs an `Arc` clone instead of a picture copy. struct SlotValue { - picture: std::sync::Arc, + /// lane-twostage: this frame's FILTERED pixels, still being produced + /// when the rest of this value is published. + pixels: std::sync::Arc>>, + /// The size those pixels will have, known from the tile decode. + width: usize, + height: usize, cdfs: Cdfs, motion_field: crate::motion_field::MotionField, seg_map: Vec, @@ -371,18 +376,18 @@ struct SlotValue { /// Each dispatched frame gets its own thread, so a blocked waiter never holds /// a resource its producer needs. A producer that errors or panics marks its /// promise `Failed`, so no consumer can wait for a value that never comes. -struct SlotPromise { - state: std::sync::Mutex, +struct SlotPromise> { + state: std::sync::Mutex>, ready: std::sync::Condvar, } -enum PromiseState { +enum PromiseState { Pending, - Ready(std::sync::Arc), + Ready(T), Failed, } -impl SlotPromise { +impl SlotPromise { fn pending() -> std::sync::Arc { std::sync::Arc::new(Self { state: std::sync::Mutex::new(PromiseState::Pending), @@ -391,18 +396,29 @@ impl SlotPromise { } /// A slot filled by a frame the parsing thread decoded itself. - fn ready(value: std::sync::Arc) -> std::sync::Arc { + fn ready(value: T) -> std::sync::Arc { std::sync::Arc::new(Self { state: std::sync::Mutex::new(PromiseState::Ready(value)), ready: std::sync::Condvar::new(), }) } - fn fulfil(&self, value: std::sync::Arc) { + fn fulfil(&self, value: T) { *self.state.lock().expect("slot promise") = PromiseState::Ready(value); self.ready.notify_all(); } + /// lane-twostage: fulfils only a promise the stage-1 sink did not + /// already fill (a superres frame, or a key frame, whose meta is + /// published here as it always was). + fn fulfil_if_pending(&self, value: impl FnOnce() -> T) { + let mut state = self.state.lock().expect("slot promise"); + if matches!(*state, PromiseState::Pending) { + *state = PromiseState::Ready(value()); + } + self.ready.notify_all(); + } + fn fail(&self) { let mut state = self.state.lock().expect("slot promise"); if matches!(*state, PromiseState::Pending) { @@ -412,7 +428,7 @@ impl SlotPromise { } /// Blocks until the producing frame has published this slot. - fn wait(&self) -> Result> { + fn wait(&self) -> Result { let mut state = self.state.lock().expect("slot promise"); loop { match &*state { @@ -643,16 +659,17 @@ pub fn decode_stream_with_threads( jobs.submit(move || { let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let value = promise.wait()?; + let shown_picture = value.pixels.wait()?; let output = if grain.apply_grain && !no_grain() { std::sync::Arc::new(crate::film_grain::apply_grain( - &value.picture, + &shown_picture, &grain, seq.mc_identity, u32::from(seq.bit_depth), &crate::decode::FrameCtx::new(), )) } else { - std::sync::Arc::clone(&value.picture) + std::sync::Arc::clone(&shown_picture) }; Ok((output, decode_idx, true)) })) @@ -871,6 +888,12 @@ pub fn decode_stream_with_threads( crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown); jobs.submit(move || { let promise = produces; + // lane-twostage: stage 2 -- this frame's filtered pixels. Its + // consumers hold this promise from the moment stage 1 (CDFs, + // segment map, motion field, size) is published at the tile + // boundary, and wait on it at their first prediction. + let pixels: std::sync::Arc>> = + SlotPromise::pending(); let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { crate::timeline::start(decode_idx); // The wait happens HERE, off the parsing thread, and only @@ -893,6 +916,71 @@ pub fn decode_stream_with_threads( // Fresh per-thread state: every field this path reads is // written from this frame's own header before it is read. let fctx = crate::decode::FrameCtx::new(); + // lane-twostage: the pictures behind this frame's own + // references, waited for at the first `ref_planes` call + // inside the tile decode rather than here. + let ref_metas: [Option>; 8] = + std::array::from_fn(|i| { + if i == 0 { + None + } else { + resolved + .get(header.ref_frame_idx[i - 1] as usize) + .cloned() + .flatten() + } + }); + let pix_cell: std::sync::OnceLock< + [Option>; 8], + > = std::sync::OnceLock::new(); + let wait_pixels = || -> Result<[Option<&Picture>; 8]> { + if pix_cell.get().is_none() { + let mut pics: [Option>; 8] = + Default::default(); + for (i, meta) in ref_metas.iter().enumerate() { + if let Some(meta) = meta { + let slot = header.ref_frame_idx[i - 1] as usize; + let t0 = crate::timeline::now(); + pics[i] = Some(meta.pixels.wait()?); + crate::timeline::ref_wait( + decode_idx, + slot, + dep_owner[slot], + crate::timeline::now().saturating_sub(t0), + ); + } + } + let _ = pix_cell.set(pics); + } + let pics = pix_cell.get().expect("the pictures were just set"); + Ok(std::array::from_fn(|i| pics[i].as_deref())) + }; + let refpix = decode::RefPix::lazy( + std::array::from_fn(|i| { + ref_metas[i].as_ref().map(|m| (m.width, m.height)) + }), + &wait_pixels, + ); + // Stage 1: published at this frame's tile boundary, before + // its filters run (`take_segment_ids` copies the map, so + // the filters that read it are unaffected). + let stage1 = |cdfs: Cdfs, + motion_field: crate::motion_field::MotionField, + width: usize, + height: usize| { + if let Some(promise) = &promise { + promise.fulfil(std::sync::Arc::new(SlotValue { + pixels: pixels.clone(), + width, + height, + cdfs, + motion_field, + seg_map: decode::take_segment_ids(&fctx), + order_hint: header.order_hint, + })); + crate::timeline::slot_fulfil(); + } + }; // spec 7.9's `av1_setup_motion_field` runs inside // `RefSnapshot::take`, i.e. here, after those waits -- // it reads the referenced slots' saved motion fields. @@ -901,7 +989,7 @@ pub fn decode_stream_with_threads( let snap = RefSnapshot::take( &header, seq, - std::array::from_fn(|i| resolved[i].as_ref().map(|v| &*v.picture)), + &refpix, std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)), std::array::from_fn(|i| { resolved[i].as_ref().map(|v| v.seg_map.as_slice()) @@ -918,19 +1006,35 @@ pub fn decode_stream_with_threads( decode_idx, shown_idx, dump.as_deref(), + // lane-twostage kill switch: `EC_AV1_TWO_STAGE=0` + // publishes a frame's meta where it always was + // (after its filters), for bisecting a mismatch. + crate::envflags::var("EC_AV1_TWO_STAGE") + .is_ok_and(|v| v == "0") + .then_some(()) + .map_or(Some(&stage1 as &dyn Fn(_, _, _, _)), |()| None), )?; // Publish before grain synthesis: every frame waiting on // this slot can start the moment the clean picture exists // (spec 7.18.3.1 -- the bank never stores grain). let picture = std::sync::Arc::new(out.picture); + pixels.fulfil(picture.clone()); if let Some(promise) = &promise { - promise.fulfil(std::sync::Arc::new(SlotValue { - picture: picture.clone(), - cdfs: out.stored_cdfs, - motion_field: out.motion_field, - seg_map: out.seg_map, - order_hint: header.order_hint, - })); + // Only a frame whose stage-1 sink never fired (a + // superres frame) still has meta to publish here. + promise.fulfil_if_pending(|| { + std::sync::Arc::new(SlotValue { + pixels: pixels.clone(), + width: picture.width, + height: picture.height, + cdfs: out.stored_cdfs, + motion_field: out.motion_field.expect( + "a frame that published no stage 1 carries its motion field back", + ), + seg_map: out.seg_map, + order_hint: header.order_hint, + }) + }); crate::timeline::slot_fulfil(); } // Grain is synthesised for OUTPUT only: a hidden frame is @@ -957,10 +1061,13 @@ pub fn decode_stream_with_threads( }); // A frame nobody can decode must not leave its consumers // waiting for a slot that will never be filled. - if reply.is_err() - && let Some(promise) = &promise - { - promise.fail(); + if reply.is_err() { + // Neither stage may leave a consumer waiting for a value + // that will never come. + if let Some(promise) = &promise { + promise.fail(); + } + pixels.fail(); } let _ = tx.send((job_seq, true, reply)); }); @@ -979,10 +1086,21 @@ pub fn decode_stream_with_threads( } continue; } + // lane-twostage: the inline path's references are decoded already, + // so its handle never waits. + let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| { + if i == 0 { + None + } else { + ref_slots + .get(header.ref_frame_idx[i - 1] as usize) + .and_then(|p| p.as_deref()) + } + })); let snap = RefSnapshot::take( &header, seq, - std::array::from_fn(|i| ref_slots[i].as_deref()), + &inline_refpix, std::array::from_fn(|i| cdf_slots[i].as_ref()), std::array::from_fn(|i| seg_map_slots[i].as_deref()), &std::array::from_fn(|i| motion_field_slots[i].as_ref()), @@ -1003,7 +1121,10 @@ pub fn decode_stream_with_threads( pictures_decoded, pictures_shown, final_dump.as_deref(), + None, )?; + let motion_field = + motion_field.expect("the inline path passes no stage-1 sink"); pictures_decoded += 1; // lane-pool1: one allocation, then every slot store and the output // itself are refcount bumps instead of plane copies. @@ -1014,7 +1135,9 @@ pub fn decode_stream_with_threads( // already resolved, since the picture exists right here. if header.refresh_frame_flags != 0 { let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue { - picture: std::sync::Arc::clone(&picture), + pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)), + width: picture.width, + height: picture.height, cdfs: stored_cdfs, motion_field, seg_map: decoded_seg_map, @@ -1131,8 +1254,9 @@ impl SeqFlags { /// banks `decode_stream_with` owns -- taken on the parsing thread, before any /// later frame can overwrite a slot, so a frame can be decoded anywhere. pub(crate) struct RefSnapshot<'a> { - /// The 8 DPB slots, indexed by slot (NOT by `ref_frame_idx`). - pub(crate) refs: [Option<&'a Picture>; NUM_REF_FRAMES], + /// lane-twostage: this frame's references, indexed by `ref_frame` + /// (`LAST_FRAME` = 1) -- sizes now, pixels at the first prediction. + pub(crate) refpix: &'a decode::RefPix<'a>, /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the /// second case is the refusal [`decode_frame`] raises where it always @@ -1155,7 +1279,7 @@ impl<'a> RefSnapshot<'a> { fn take( header: &FrameHeader, seq: SeqFlags, - refs: [Option<&'a Picture>; NUM_REF_FRAMES], + refpix: &'a decode::RefPix<'a>, cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES], seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES], motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES], @@ -1189,7 +1313,7 @@ impl<'a> RefSnapshot<'a> { ); } Self { - refs, + refpix, primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()), prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)), tpl_field, @@ -1206,10 +1330,27 @@ impl<'a> RefSnapshot<'a> { pub(crate) struct FrameOutput { pub(crate) picture: Picture, pub(crate) stored_cdfs: Cdfs, - pub(crate) motion_field: crate::motion_field::MotionField, + /// lane-twostage: `None` when this frame handed its motion field to the + /// stage-1 sink at its tile boundary instead of carrying it back here. + pub(crate) motion_field: Option, pub(crate) seg_map: Vec, } +/// Spec 7.20's own `save_cdfs`: what a frame's `refresh_frame_flags` slots +/// keep -- the frame's INITIAL table when `disable_frame_end_update_cdf`, +/// otherwise the adapted end-of-tile table with every symbol counter zeroed +/// (libaom `av1_reset_cdf_symbol_counters`). lane-twostage: shared with the +/// stage-1 publish, which hands a consumer the same table it always got. +fn stored_cdfs_for(header: &FrameHeader, end_cdfs: Cdfs, started_from: Option) -> Cdfs { + if header.disable_frame_end_update_cdf { + started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx))) + } else { + let mut end_cdfs = end_cdfs; + end_cdfs.reset_counts(); + end_cdfs + } +} + /// lane-thread2: one coded frame, decoded from its header, its tile payload /// and a snapshot of the reference banks -- and from nothing else. Lifted /// verbatim out of [`decode_stream_with`]'s loop so that the same code can @@ -1233,6 +1374,8 @@ fn decode_frame( decode_idx: usize, shown_idx: usize, final_dump: Option<&str>, + // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`. + stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>, ) -> Result { if header.segmentation.enabled { for segment in 0..MAX_SEGMENTS { @@ -1568,15 +1711,16 @@ fn decode_frame( // never a projection source, and never spends a `ref_stamp`. true, ); - (picture, end_cdfs, motion_field) + (picture, end_cdfs, Some(motion_field)) } else { let last_slot = header.ref_frame_idx[0] as usize; - let reference = snap.refs[last_slot].ok_or_else(|| { - Error::unsupported( + let _ = last_slot; + if snap.refpix.dims(1).is_none() { + return Err(Error::unsupported( "AV1 decode_stream", "an inter frame with no key frame before it", - ) - })?; + )); + } // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i` // (spec 7.8/7.20). Any of them having no picture yet is not a // stream error on its own: `decode_inter_block` only needs a @@ -1589,20 +1733,26 @@ fn decode_frame( if header.force_integer_mv { decode::note_force_integer_mv_frame(); } - let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| { - if ref_frame == 0 { - None - } else { - snap.refs - .get(header.ref_frame_idx[ref_frame - 1] as usize) - .copied() - .flatten() - } - }); // spec 7.9's own driver, `av1_setup_motion_field`: only run when // this frame's header actually asks for temporal candidates -- // `find_mv_stack_with_sign_bias` reproduces its old always-`None` // behaviour bit for bit when this is `None` (see its own doc). + // lane-twostage: the stage-1 sink is handed the table a consumer + // would have read out of the slot, not the raw end-of-tile one. + let started_from_stage1 = started_from.clone(); + let stage1_adapter = stage1.map(|sink| { + move |end_cdfs: Cdfs, + motion_field: crate::motion_field::MotionField, + width: usize, + height: usize| { + sink( + stored_cdfs_for(header, end_cdfs, started_from_stage1.clone()), + motion_field, + width, + height, + ) + } + }); let tpl_field = &snap.tpl_field; let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs( &tile_bufs, @@ -1619,8 +1769,7 @@ fn decode_frame( }, header.frame_width, header.frame_height, - reference, - other_refs, + snap.refpix, &header.cdef, &header.loop_filter, &header.loop_restoration, @@ -1647,7 +1796,11 @@ fn decode_frame( header.allow_warped_motion, header.allow_screen_content_tools, header.delta, - enable_filter_intra, fctx, + enable_filter_intra, + stage1_adapter + .as_ref() + .map(|f| f as &dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)), + fctx, )?; (picture, end_cdfs, motion_field) }; @@ -1657,16 +1810,7 @@ fn decode_frame( // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's // *initial* table into the slots it refreshes, not the adapted // end-of-tile one. - let stored_cdfs = if header.disable_frame_end_update_cdf { - started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx))) - } else { - // Spec 7.20 `save_cdfs` (libaom `av1_reset_cdf_symbol_counters`): - // the adapted table is saved with every symbol counter zeroed, - // not with the counts the tile's own decode left behind. - let mut end_cdfs = end_cdfs; - end_cdfs.reset_counts(); - end_cdfs - }; + let stored_cdfs = stored_cdfs_for(header, end_cdfs, started_from); if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") { use std::io::Write; if let Ok(mut f) = std::fs::OpenOptions::new()