diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index 8c382ab5..f0ec78f7 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -1043,6 +1043,15 @@ pub const INTER_TX_TYPE_SET3_32: [u16; 3] = [748, 32768, 0]; /// DCT_DCT, index one of `Tx_Type_Inter_Inv_Set3`, same as the 32x32 table. pub const INTER_TX_TYPE_SET3_16: [u16; 3] = [1998, 32768, 0]; +/// `Default_Inter_Ext_Tx_Cdf`'s `TX_SET_INTER_3` row for `TX_8X8` (spec 9.4): +/// the transform type of an `is_inter` 8x8 luma transform under +/// `reduced_tx_set` -- an 8x8 leaf under a straddling 16x16 block +/// (lane-av1inter8), the same two-symbol set [`INTER_TX_TYPE_SET3_16`] and +/// [`INTER_TX_TYPE_SET3_32`] read at their own sizes, just its own default +/// probability and adaptation state (libaom `entropymode.c`'s +/// `default_inter_ext_tx_cdf[EXT_TX_SET_DCT_IDTX][TX_8X8]`). +pub const INTER_TX_TYPE_SET3_8: [u16; 3] = [4167, 32768, 0]; + // The inter-frame tables below (spec 9.4) support the syntax an inter block // needs: whether it is coded as intra at all, which reference frame and // motion vector it takes when it is not. Compound reference and compound diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 6c831036..5a82f5b3 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -37,9 +37,20 @@ pub(crate) enum TxbSet { /// reads, but its own two-symbol `tx_type` table rather than `Luma16`'s /// five-symbol, mode-indexed one. Luma16Inter, - /// The 8x8 luma transform of an 8x8 leaf under a straddling 16x16 block - /// (lane-av1-rect): intra-only, so no `Luma8Inter` counterpart exists yet. + /// The 8x8 luma transform of an intra 8x8 leaf under a straddling 16x16 + /// block (lane-av1-rect). An `is_inter` leaf reads + /// [`Luma8Inter`](TxbSet::Luma8Inter) instead. Luma8, + /// The 8x8 luma transform of an `is_inter` 8x8 leaf under a straddling + /// 16x16 block (lane-av1inter8): the same coefficient tables + /// [`Luma8`](TxbSet::Luma8) reads, but `get_tx_set` (spec 5.11.48) + /// returns `TX_SET_INTER_3` at this size too under this encoder's + /// always-on `reduced_tx_set` -- the same two-symbol alphabet + /// [`Luma16Inter`](TxbSet::Luma16Inter) carries, just its own CDF (libaom + /// `default_inter_ext_tx_cdf[EXT_TX_SET_DCT_IDTX][TX_8X8]`, a distinct + /// adapted table from the 16x16 and 32x32 sizes' own entries in the same + /// set, per `entropymode.c`). + Luma8Inter, /// The 8x8 transform of a chroma plane of a 16x16 block. Chroma8, /// The 4x4 transform of a chroma plane of an 8x8 leaf (lane-av1-rect). @@ -217,6 +228,10 @@ pub(crate) struct Cdfs { /// `reduced_tx_set` (spec `TX_SET_INTER_3`, `TX_16X16` row) -- not /// indexed by mode, same as [`Self::inter_tx_type_32`]. pub inter_tx_type_16: [u16; 3], + /// The transform type of an `is_inter` 8x8 luma transform under + /// `reduced_tx_set` (spec `TX_SET_INTER_3`, `TX_8X8` row) -- not indexed + /// by mode, same as [`Self::inter_tx_type_32`] (lane-av1inter8). + pub inter_tx_type_8: [u16; 3], /// The DC sign of a chroma coefficient, shared by both chroma sets. pub dc_sign_chroma: [[u16; 3]; 3], /// Whether an inter frame's block is coded as intra. @@ -638,6 +653,7 @@ impl Cdfs { intra_tx_type_8: cdf::INTRA_TX_TYPE_SET2_8, inter_tx_type_32: cdf::INTER_TX_TYPE_SET3_32, inter_tx_type_16: cdf::INTER_TX_TYPE_SET3_16, + inter_tx_type_8: cdf::INTER_TX_TYPE_SET3_8, dc_sign_chroma: cdf::DC_SIGN_CHROMA, intra_inter: cdf::INTRA_INTER, single_ref: cdf::SINGLE_REF, @@ -722,6 +738,17 @@ impl Cdfs { dc_sign: &mut self.dc_sign_luma, tx_type: Some(self.intra_tx_type_8[mode].as_mut_slice()), }, + TxbSet::Luma8Inter => TxbTables { + side: 8, + txb_skip: &mut self.txb_skip_luma_8, + eob_pt: &mut self.eob_pt_64_luma, + eob_extra: &mut self.eob_extra_luma_8, + base: &mut self.base_luma_8, + base_eob: &mut self.base_eob_luma_8, + br: &mut self.br_luma_8, + dc_sign: &mut self.dc_sign_luma, + tx_type: Some(self.inter_tx_type_8.as_mut_slice()), + }, TxbSet::Chroma8 => TxbTables { side: 8, txb_skip: &mut self.txb_skip_chroma_8, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 3b72f7d2..3d79027d 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -2011,6 +2011,371 @@ fn decode_inter_block( Ok(()) } +/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block +/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s +/// exact symbol order: its own skip flag, intra/inter choice and (when +/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack +/// window, or (when intra) `Y_MODE`, then its own luma and two chroma +/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`], +/// same as [`decode_leaf8`]'s coefficient layer but with +/// motion-compensated prediction instead of intra prediction when inter. +/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's +/// skip/intra-inter context, overridden by `prev_leaf` exactly as +/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays +/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag +/// and intra/inter choice, for the next leaf or the caller's final +/// write-back. +#[allow(clippy::too_many_arguments)] +fn decode_inter_block8( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + grid: &mut MiGrid, + mi_cols: u32, + mi_rows: u32, + outer_at: (usize, usize), + leaf_mi: (usize, usize), + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + ref_y: &PlaneBuf, + ref_u: &PlaneBuf, + ref_v: &PlaneBuf, + base_q_idx: u8, + scan8: &[u16], + scan4: &[u16], + prev_leaf: Option<((usize, usize), bool, bool)>, +) -> Result<(bool, bool)> { + const LAST_FRAME: i8 = 1; + /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`). + const SIZE_GROUP_8: usize = 1; + + let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI); + let (cpx, cpy) = (px / 2, py / 2); + const SIDE: usize = 8; + const CHROMA_SIDE: usize = 4; + + let (r, c) = outer_at; + let mut above_skip = neighbours.above_skip[c]; + let mut left_skip = neighbours.left_skip[r]; + let mut above_inter = neighbours.above_inter[c]; + let mut left_inter = neighbours.left_inter[r]; + if let Some(((pr, pc), pskip, pinter)) = prev_leaf { + if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 { + above_skip = pskip; + above_inter = pinter; + } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 { + left_skip = pskip; + left_inter = pinter; + } + } + let skip_ctx = usize::from(above_skip) + usize::from(left_skip); + let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; + + let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0); + let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); + let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; + + let mode_for_tx; + let (luma_grid, u_grid, v_grid); + if is_inter { + let sr_ctx = single_ref_ctx(above_inter || left_inter); + let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]); + let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]); + let p4 = dec.symbol(&mut cdfs.single_ref[sr_ctx][3]); + if (p1, p3, p4) != (0, 0, 0) { + return Err(unsupported( + "a reference frame other than LAST_FRAME (round 2)", + )); + } + + let (mi_row, mi_col) = leaf_mi; + let stack = find_mv_stack( + grid, + mi_row, + mi_col, + 2, + 2, + LAST_FRAME, + mi_cols as usize, + mi_rows as usize, + ); + + let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; + let (mv, is_new_mv) = if !not_new { + if stack.entries.len() > 1 { + dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]); + } + ( + read_mv(dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, stack.pred_mv), + true, + ) + } else { + let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; + if !not_zero { + return Err(unsupported("GLOBALMV (round 3)")); + } + let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; + let mv = if nearest { + stack.nearest_mv + } else { + let mut idx = 1usize; + while idx < 3 && stack.entries.len() > idx + 1 { + if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { + break; + } + idx += 1; + } + stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) + }; + (mv, false) + }; + for dr in 0..2 { + for dc in 0..2 { + grid.set( + mi_row + dr, + mi_col + dc, + MiInfo { + is_inter: true, + ref_frame: LAST_FRAME, + mv, + is_new_mv, + size: 2, + }, + ); + } + } + mode_for_tx = 0; + + let mut pred_y = vec![0u8; SIDE * SIDE]; + mc::predict( + &ref_y.data, + ref_y.width, + ref_y.true_width, + ref_y.true_height, + mv_to_q4(px, mv.1, true), + mv_to_q4(py, mv.0, true), + SIDE, + SIDE, + &mut pred_y, + ); + let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE]; + mc::predict( + &ref_u.data, + ref_u.width, + ref_u.true_width, + ref_u.true_height, + mv_to_q4(cpx, mv.1, false), + mv_to_q4(cpy, mv.0, false), + CHROMA_SIDE, + CHROMA_SIDE, + &mut pred_u, + ); + let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE]; + mc::predict( + &ref_v.data, + ref_v.width, + ref_v.true_width, + ref_v.true_height, + mv_to_q4(cpx, mv.1, false), + mv_to_q4(cpy, mv.0, false), + CHROMA_SIDE, + CHROMA_SIDE, + &mut pred_v, + ); + + if skip { + y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]); + u.reconstruct_mc( + cpx, + cpy, + CHROMA_SIDE, + &pred_u, + &vec![0i32; CHROMA_SIDE * CHROMA_SIDE], + ); + v.reconstruct_mc( + cpx, + cpy, + CHROMA_SIDE, + &pred_v, + &vec![0i32; CHROMA_SIDE * CHROMA_SIDE], + ); + luma_grid = vec![0i32; SIDE * SIDE]; + u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; + v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; + } else { + let around = neighbours.around_mi(leaf_mi, 8); + luma_grid = read_inter_plane( + dec, + cdfs, + TxbSet::Luma8Inter, + scan8, + 0, + around[0], + mode_for_tx, + y, + px, + py, + SIDE, + base_q_idx, + &pred_y, + )?; + u_grid = read_inter_plane( + dec, + cdfs, + TxbSet::Chroma4, + scan4, + 1, + around[1], + mode_for_tx, + u, + cpx, + cpy, + CHROMA_SIDE, + base_q_idx, + &pred_u, + )?; + v_grid = read_inter_plane( + dec, + cdfs, + TxbSet::Chroma4, + scan4, + 2, + around[2], + mode_for_tx, + v, + cpx, + cpy, + CHROMA_SIDE, + base_q_idx, + &pred_v, + )?; + } + } else { + let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]); + if mode >= 13 { + return Err(unsupported( + "an intra mode this decoder does not code (round 2)", + )); + } + if (V_PRED..=D67_PRED).contains(&mode) { + let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]); + if angle != ANGLE_DELTA_ZERO { + return Err(unsupported( + "a nonzero angle delta (this encoder never writes one)", + )); + } + } + let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]); + if uv_mode != DC_PRED { + return Err(unsupported( + "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)", + )); + } + mode_for_tx = mode; + let (mi_row, mi_col) = leaf_mi; + for dr in 0..2 { + for dc in 0..2 { + grid.set( + mi_row + dr, + mi_col + dc, + MiInfo { + is_inter: false, + ref_frame: -1, + mv: (0, 0), + is_new_mv: false, + size: 2, + }, + ); + } + } + + let reach = Reach::of(SIDE, px, py, y.width, y.height); + if skip { + y.reconstruct(px, py, SIDE, mode, reach, &vec![0i32; SIDE * SIDE], None); + u.reconstruct( + cpx, + cpy, + CHROMA_SIDE, + DC_PRED, + Reach::none(), + &vec![0i32; CHROMA_SIDE * CHROMA_SIDE], + None, + ); + v.reconstruct( + cpx, + cpy, + CHROMA_SIDE, + DC_PRED, + Reach::none(), + &vec![0i32; CHROMA_SIDE * CHROMA_SIDE], + None, + ); + luma_grid = vec![0i32; SIDE * SIDE]; + u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; + v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; + } else { + let around = neighbours.around_mi(leaf_mi, 8); + luma_grid = read_plane( + dec, + cdfs, + TxbSet::Luma8, + scan8, + 0, + around[0], + mode, + mode, + reach, + y, + px, + py, + SIDE, + TX8, + base_q_idx, + None, + )?; + u_grid = read_plane( + dec, + cdfs, + TxbSet::Chroma4, + scan4, + 1, + around[1], + mode, + DC_PRED, + Reach::none(), + u, + cpx, + cpy, + CHROMA_SIDE, + TX4, + base_q_idx, + None, + )?; + v_grid = read_plane( + dec, + cdfs, + TxbSet::Chroma4, + scan4, + 2, + around[2], + mode, + DC_PRED, + Reach::none(), + v, + cpx, + cpy, + CHROMA_SIDE, + TX4, + base_q_idx, + None, + )?; + } + } + neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]); + Ok((skip, is_inter)) +} + /// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes, /// against `reference` (the previous frame's own decoded picture, at this /// frame's true size -- a decoder's single-slot DPB, matching what this @@ -2093,6 +2458,7 @@ pub fn decode_inter_frame_tile( let scan32 = default_scan(TX32); let scan16 = default_scan(TX16); let scan8 = default_scan(TX8); + let scan4 = default_scan(TX4); let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); let mut dec = SymbolDecoder::new(data); @@ -2189,44 +2555,101 @@ pub fn decode_inter_frame_tile( has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols), has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows), ); - if !has_cols16 || !has_rows16 { + if !has_cols16 && !has_rows16 { return Err(unsupported( - "a 16x16 inter block the true frame edge cuts through (round 2)", + "a 16x16 inter block whose true edge cuts through both \ + axes needs a rectangular transform this decoder does \ + not code yet", )); } let at16 = (sr, sc); - let ctx16 = neighbours.partition_ctx(at16, SUB); - let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]); - if part16 != PARTITION_NONE { - return Err(unsupported( - "a partition below 16x16 (this encoder never writes one)", - )); + if has_cols16 && has_rows16 { + let ctx16 = neighbours.partition_ctx(at16, SUB); + let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]); + if part16 != PARTITION_NONE { + return Err(unsupported( + "a partition below 16x16 (this encoder never writes one)", + )); + } + decode_inter_block( + &mut dec, + &mut cdfs, + &mut neighbours, + &mut grid, + at16, + SUB, + mi_cols, + mi_rows, + &mut y, + &mut u, + &mut v, + &ref_y, + &ref_u, + &ref_v, + base_q_idx, + TxbSet::Luma16, + TxbSet::Luma16Inter, + TxbSet::Chroma8, + TX16, + TX8, + &scan16, + &scan8, + 2, + )?; + } else { + let ctx16 = neighbours.partition_ctx(at16, SUB); + if has_cols16 { + dec.symbol_fixed(&gather( + &cdfs.partition_w16[ctx16], + VERT_ALIKE, + )); + } else { + dec.symbol_fixed(&gather( + &cdfs.partition_w16[ctx16], + HORZ_ALIKE, + )); + } + let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); + let leaf_positions: Vec<(u32, u32)> = (0..4) + .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2)) + .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols) + .collect(); + let mut prev_leaf: Option<((usize, usize), bool, bool)> = None; + for (mr, mc) in leaf_positions { + let leaf_mi = (mr as usize, mc as usize); + let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); + let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]); + if part8 != PARTITION_NONE { + return Err(unsupported( + "a partition below 8x8 (this encoder never writes one)", + )); + } + let (skip, is_inter) = decode_inter_block8( + &mut dec, + &mut cdfs, + &mut neighbours, + &mut grid, + mi_cols, + mi_rows, + at16, + leaf_mi, + &mut y, + &mut u, + &mut v, + &ref_y, + &ref_u, + &ref_v, + base_q_idx, + &scan8, + &scan4, + prev_leaf, + )?; + prev_leaf = Some((leaf_mi, skip, is_inter)); + } + if let Some((_, skip, is_inter)) = prev_leaf { + neighbours.record_inter(at16, SUB, skip, is_inter); + } } - decode_inter_block( - &mut dec, - &mut cdfs, - &mut neighbours, - &mut grid, - at16, - SUB, - mi_cols, - mi_rows, - &mut y, - &mut u, - &mut v, - &ref_y, - &ref_u, - &ref_v, - base_q_idx, - TxbSet::Luma16, - TxbSet::Luma16Inter, - TxbSet::Chroma8, - TX16, - TX8, - &scan16, - &scan8, - 2, - )?; } } _ => { diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index c0fb7bc9..762f3f8a 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1162,26 +1162,39 @@ fn code_square( ) } -/// Codes one 16x16 leaf of a straddling 32x32 quadrant as whichever costs -/// least of intra ([`code_square`], unchanged) or `NEARESTMV` against -/// `reference` at `stack.nearest_mv` -- the same NEARESTMV candidate -/// [`search_inter_block`] prices for a whole 32x32 block, just at this leaf's -/// own 16x16 side and through [`TxbSet::Luma16Inter`]. `NEWMV` (a motion -/// search of its own) is not attempted here: these leaves only ever fill the -/// sliver of real content a true edge lands in the middle of a 32x32 block, -/// not a leaf worth a full search, so `NEARESTMV`-or-intra is this function's -/// deliberate first cut (see `write_inter_frame_leaf`'s doc comment). +/// Codes one leaf of a straddling quadrant as whichever costs least of intra +/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at +/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`] +/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a +/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under +/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`] +/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not +/// attempted here: these leaves only ever fill the sliver of real content a +/// true edge lands in the middle of a larger block, not a leaf worth a full +/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut +/// (see `write_inter_frame_leaf`'s doc comment). #[allow(clippy::too_many_arguments)] fn code_square_inter( luma: &mut Plane, chroma: &mut [Plane; 2], (x, y): (usize, usize), + side: usize, search: &Search, mode_bits: &[f64; 13], reference: &Picture, stack: &MvStack, ) -> BlockCoeffs { - let (intra_block, intra_cost) = code_square(luma, chroma, (x, y), SUB, search, mode_bits); + let (intra_block, intra_cost) = code_square(luma, chroma, (x, y), side, search, mode_bits); + let luma_set = if side == 8 { + TxbSet::Luma8Inter + } else { + TxbSet::Luma16Inter + }; + let chroma_set = if side == 8 { + TxbSet::Chroma4 + } else { + TxbSet::Chroma8 + }; let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); @@ -1215,7 +1228,7 @@ fn code_square_inter( luma, x, y, - SUB, + side, mv, true, ref_luma.0, @@ -1225,13 +1238,13 @@ fn code_square_inter( false, search.base_q_idx, search.deadzone, - TxbSet::Luma16Inter, + luma_set, ); let u = mc_trial( &chroma[0], x / 2, y / 2, - SUB / 2, + side / 2, mv, false, ref_u.0, @@ -1241,13 +1254,13 @@ fn code_square_inter( false, search.base_q_idx, search.deadzone, - TxbSet::Chroma8, + chroma_set, ); let v = mc_trial( &chroma[1], x / 2, y / 2, - SUB / 2, + side / 2, mv, false, ref_v.0, @@ -1257,7 +1270,7 @@ fn code_square_inter( false, search.base_q_idx, search.deadzone, - TxbSet::Chroma8, + chroma_set, ); let skip = luma_trial.levels.iter().all(|&l| l == 0) && u.levels.iter().all(|&l| l == 0) @@ -1291,13 +1304,13 @@ fn code_square_inter( // branches), which is what made 8-mi geometry a true no-op instead of // one that only held when every neighbour happened to be inter. if inter_cost < intra_cost { - luma.commit(x, y, SUB, &luma_trial); - chroma[0].commit(x / 2, y / 2, SUB / 2, &u); - chroma[1].commit(x / 2, y / 2, SUB / 2, &v); + luma.commit(x, y, side, &luma_trial); + chroma[0].commit(x / 2, y / 2, side / 2, &u); + chroma[1].commit(x / 2, y / 2, side / 2, &v); BlockCoeffs { - luma: coeffs(&luma_trial.levels, SUB), - u: coeffs(&u.levels, SUB / 2), - v: coeffs(&v.levels, SUB / 2), + luma: coeffs(&luma_trial.levels, side), + u: coeffs(&u.levels, side / 2), + v: coeffs(&v.levels, side / 2), mode: DC_PRED as u8, skip, eight: None, @@ -2606,75 +2619,139 @@ pub(crate) fn encode_inter_frame( && (sc as u32) * crate::tile::SUB_MI < header.mi_cols }) .collect(); - // A 16x16 leaf the true edge itself cuts through needs a - // rectangular (HORZ/VERT) transform this writer does not - // code, same refusal as the key frame search's - // `split_legal` check. - if let Some(&(sr, sc)) = sub_positions.iter().find(|&&(sr, sc)| { - !crate::tile::has_half( - sc as u32 * crate::tile::SUB_MI, - crate::tile::SUB_MI, - header.mi_cols, - ) || !crate::tile::has_half( - sr as u32 * crate::tile::SUB_MI, - crate::tile::SUB_MI, - header.mi_rows, - ) - }) { - return Err(Error::unsupported( - "AV1 encode", - format!( - "the 16x16 block at ({sc},{sr}) straddles the true frame \ - edge in a way that needs a rectangular (HORZ/VERT) \ - transform this encoder does not code yet" - ), - )); - } // Each leaf searches intra against its own `NEARESTMV` // candidate (`code_square_inter`), same real-inter choice // `search_inter_block` makes for a whole 32x32 block, at - // this leaf's own 4x4-mi mv-stack window. + // this leaf's own 4x4-mi mv-stack window -- unless the + // leaf's own half itself straddles the true edge, which + // it codes as two (or one, at a true corner) 8x8 leaves + // (`crate::tile::write_leaf8`'s inter counterpart), + // mirroring the key frame search's straddling-16x16 + // handling above (lane-av1inter8). let mut leaves = Vec::with_capacity(sub_positions.len()); for (sr, sc) in sub_positions { - let (x, y) = (sc * SUB, sr * SUB); - let (mi_row, mi_col) = (sr * 4, sc * 4); - let stack = find_mv_stack( - &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, - ); - let block = code_square_inter( - &mut luma, - &mut chroma, - (x, y), - &search, - &mode_bits_table, - reference, - &stack, + let (has_cols16, has_rows16) = ( + crate::tile::has_half( + sc as u32 * crate::tile::SUB_MI, + crate::tile::SUB_MI, + header.mi_cols, + ), + crate::tile::has_half( + sr as u32 * crate::tile::SUB_MI, + crate::tile::SUB_MI, + header.mi_rows, + ), ); - for dr in 0..4 { - for dc in 0..4 { - grid.set( - mi_row + dr, - mi_col + dc, - match block.inter { - Some(info) => MiInfo { - is_inter: true, - ref_frame: LAST_FRAME, - mv: info.mv, - is_new_mv: matches!(info.mode, InterMode::NewMv), - size: 4, - }, - None => MiInfo { - is_inter: false, - ref_frame: -1, - mv: (0, 0), - is_new_mv: false, - size: 4, + if !has_cols16 && !has_rows16 { + return Err(Error::unsupported( + "AV1 encode", + format!( + "the 16x16 block at ({sc},{sr}) straddles the true \ + frame edge in a way that needs a rectangular \ + (HORZ/VERT) transform this encoder does not code yet" + ), + )); + } + if has_cols16 && has_rows16 { + let (x, y) = (sc * SUB, sr * SUB); + let (mi_row, mi_col) = (sr * 4, sc * 4); + let stack = find_mv_stack( + &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, + ); + let block = code_square_inter( + &mut luma, + &mut chroma, + (x, y), + SUB, + &search, + &mode_bits_table, + reference, + &stack, + ); + for dr in 0..4 { + for dc in 0..4 { + grid.set( + mi_row + dr, + mi_col + dc, + match block.inter { + Some(info) => MiInfo { + is_inter: true, + ref_frame: LAST_FRAME, + mv: info.mv, + is_new_mv: matches!(info.mode, InterMode::NewMv), + size: 4, + }, + None => MiInfo { + is_inter: false, + ref_frame: -1, + mv: (0, 0), + is_new_mv: false, + size: 4, + }, }, - }, + ); + } + } + leaves.push(block); + } else { + let (x_sub, y_sub) = (sc * SUB, sr * SUB); + let (mi_row0, mi_col0) = (sr * 4, sc * 4); + let mut eight = Vec::with_capacity(2); + for i in 0..4 { + let leaf_x = x_sub + (i % 2) * 8; + let leaf_y = y_sub + (i / 2) * 8; + if leaf_x >= luma.true_width || leaf_y >= luma.true_height { + continue; + } + let (mi_row, mi_col) = + (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2); + let stack = find_mv_stack( + &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows, + ); + let leaf = code_square_inter( + &mut luma, + &mut chroma, + (leaf_x, leaf_y), + 8, + &search, + &mode_bits_table, + reference, + &stack, ); + for dr in 0..2 { + for dc in 0..2 { + grid.set( + mi_row + dr, + mi_col + dc, + match leaf.inter { + Some(info) => MiInfo { + is_inter: true, + ref_frame: LAST_FRAME, + mv: info.mv, + is_new_mv: matches!( + info.mode, + InterMode::NewMv + ), + size: 2, + }, + None => MiInfo { + is_inter: false, + ref_frame: -1, + mv: (0, 0), + is_new_mv: false, + size: 2, + }, + }, + ); + } + } + eight.push(leaf); } + leaves.push(BlockCoeffs { + eight: Some(eight), + ..BlockCoeffs::default() + }); } - leaves.push(block); } blocks[r32 * cols + c32] = Quadrant::Split(leaves); } @@ -3317,29 +3394,26 @@ mod tests { /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16 /// leaf's own half (`has_half` at the SUB level) itself straddles the - /// true edge on one axis only. lane-av1-rect r7 wires the key frame + /// true edge on one axis only. lane-av1-rect r7 wired the key frame /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly - /// this case, so the key frame path no longer *refuses* it; the inter - /// frame path (`sb_coeff_inter_frame_tile`) was not part of this round's - /// wiring and still has no leaf-8 generation, so it must still refuse. - /// This only proves the encoder does not error out -- the leaf-8 stream - /// it produces is NOT yet proven decoder-clean (see - /// `a_single_axis_straddle_round_trips_through_ffmpeg`, currently - /// `#[ignore]`d on a genuine dav1d desync at the smaller 40x32 case). + /// this case; lane-av1inter8 extends the same leaf-8 path to inter + /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s + /// straddling-16x16 branch), so an inter frame no longer refuses this + /// size either. This only proves the encoder does not error out -- see + /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the + /// decoder-clean proof (a 3-frame sequence, so the inter path is + /// actually exercised). #[test] - fn key_frame_encodes_the_inter_frame_still_refuses_at_half_straddle_size() { + fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() { let (width, height) = (640usize, 360usize); let picture = Picture::grey(width, height); encode_key_frame(&picture, 100, 0.5).expect("key frame now codes the mod-32==8 straddle"); - // `encode_sequence`'s second frame is the inter path: same size, - // still refused -- that machinery was not wired this round. + // `encode_sequence`'s second frame is the inter path: same size, now + // wired the same way. let pictures = vec![picture.clone(), picture]; - let inter_err = encode_sequence(&pictures, 100, 0.5).unwrap_err(); - assert!( - inter_err.to_string().contains("rectangular"), - "inter frame refusal: {inter_err}" - ); + encode_sequence(&pictures, 100, 0.5) + .expect("inter frame now codes the mod-32==8 straddle too"); } /// The r15 fix at production size: three 640x360 key frames (inter is @@ -3367,6 +3441,33 @@ mod tests { } } + /// The 640x360 straddle class, but through the inter path an actual + /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)): + /// proves the leaf-8 inter stream this round wires up is not just + /// encoder-clean (the test above) but decoder-clean against ffmpeg too. + #[test] + fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() { + if !have_ffmpeg() { + eprintln!( + "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg" + ); + return; + } + let (width, height) = (640usize, 360usize); + let pictures: Vec = (0..4) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); + assert_eq!(encoded.frames.len(), 4); + let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4); + assert_eq!(decoded.len(), 4, "decoded frame count"); + for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { + assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); + assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); + assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); + } + } + /// One frame of a real clip, scaled to a whole number of 32x32 blocks. fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { let out = Command::new("ffmpeg") diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 4ac159ab..0698a0a8 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -2165,6 +2165,7 @@ pub fn sb_coeff_inter_frame_tile( let scan32 = default_scan(TX32); let scan16 = default_scan(TX16); let scan8 = default_scan(TX8); + let scan4 = default_scan(TX4); let zero_grids = [ vec![0i32; TX32 * TX32], vec![0i32; TX16 * TX16], @@ -2268,38 +2269,102 @@ pub fn sb_coeff_inter_frame_tile( (false, false) => {} } for (leaf, (sr, sc)) in sub_blocks.iter().zip(sub_positions) { - // A 16x16 leaf the true frame edge itself cuts - // through needs a rectangular transform this - // writer does not code yet -- same refusal as - // `sb_coeff_key_frame_tile`'s SUB level, just - // named for an inter-frame leaf. + // A 16x16 leaf whose own half straddles the true + // frame edge on both axes needs a rectangular + // transform this writer does not code yet; one + // axis only is two (or, at a true corner, one) + // 8x8 leaves (lane-av1inter8), same split the key + // frame search takes at this geometry. let (has_cols16, has_rows16) = ( has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols), has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows), ); - if !has_cols16 || !has_rows16 { + if !has_cols16 && !has_rows16 { return Err(Error::unsupported( "AV1 tile", - "a 16x16 inter-frame block the true frame edge cuts \ - through needs a rectangular transform this writer \ + "a 16x16 inter-frame block whose true edge cuts through \ + both axes needs a rectangular transform this writer \ does not code yet", )); } let at16 = (sr, sc); - let ctx16 = neighbours.partition_ctx(at16, SUB); - enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx16]); - write_inter_frame_leaf( - &mut enc, - &mut cdfs, - &mut neighbours, - &mut grid, - mi_cols, - mi_rows, - leaf, - at16, - &scan16, - &scan8, - )?; + if has_cols16 && has_rows16 { + let ctx16 = neighbours.partition_ctx(at16, SUB); + enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx16]); + write_inter_frame_leaf( + &mut enc, + &mut cdfs, + &mut neighbours, + &mut grid, + mi_cols, + mi_rows, + leaf, + at16, + &scan16, + &scan8, + )?; + } else { + let ctx16 = neighbours.partition_ctx(at16, SUB); + if has_cols16 { + enc.symbol_fixed( + 1, + &gather(&cdfs.partition_w16[ctx16], VERT_ALIKE), + ); + } else { + enc.symbol_fixed( + 1, + &gather(&cdfs.partition_w16[ctx16], HORZ_ALIKE), + ); + } + let leaves = leaf.eight.as_ref().ok_or_else(|| { + Error::unsupported( + "AV1 tile", + "a 16x16 inter-frame block the true frame edge cuts \ + through needs its `eight` leaves populated", + ) + })?; + let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); + let leaf_positions: Vec<(u32, u32)> = (0..4) + .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2)) + .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols) + .collect(); + if leaves.len() != leaf_positions.len() { + return Err(Error::unsupported( + "AV1 tile", + "a straddling 16x16 inter-frame block needs one \ + `eight` entry per 8x8 leaf inside the true frame", + )); + } + let mut prev_leaf: Option<((usize, usize), bool, bool)> = None; + for (leaf8, (mr, mc)) in leaves.iter().zip(leaf_positions) { + let leaf_mi = (mr as usize, mc as usize); + let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); + enc.symbol(PARTITION_NONE, &mut cdfs.partition_w8[leaf_ctx]); + let (skip, is_inter) = write_inter_frame_leaf8( + &mut enc, + &mut cdfs, + &mut neighbours, + &mut grid, + mi_cols, + mi_rows, + leaf8, + at16, + leaf_mi, + &scan8, + &scan4, + prev_leaf, + )?; + prev_leaf = Some((leaf_mi, skip, is_inter)); + } + // Same write-back-once-from-the-last-leaf rule + // as the key frame search's `write_leaf8` + // caller (r15): the SUB-grid skip/inter arrays + // are otherwise left stale for the next + // 16x16 slot. + if let Some((_, skip, is_inter)) = prev_leaf { + neighbours.record_inter(at16, SUB, skip, is_inter); + } + } } continue; } @@ -2618,6 +2683,194 @@ fn write_inter_frame_leaf( Ok(()) } +/// Writes one 8x8 leaf of a straddling 16x16 inter-frame block +/// (lane-av1inter8): its own skip flag, intra/inter choice and (when inter) +/// `NEARESTMV`/`NEWMV` chain, or (when intra) `Y_MODE`, then its own luma and +/// two chroma transform blocks -- coded exactly like +/// [`write_inter_frame_leaf`] but through [`TxbSet::Luma8Inter`]/ +/// [`TxbSet::Chroma4`] and at this leaf's own 2x2-mi mv-stack window, reading +/// its skip/intra-inter context from the *enclosing* 16x16 slot's +/// [`Neighbours`] arrays (`outer_at`, in [`SUB`]-grid units) unless +/// `prev_leaf` names this straddling block's own first leaf as the true +/// mi-adjacent neighbour -- the same override [`write_leaf8`] applies to its +/// mode context, needed for the same reason: `Neighbours`' above/left arrays +/// only resolve to [`SUB`] granularity, too coarse for the second leaf of a +/// straddling 16x16 to see the first. `Y_MODE`'s own context (`Size_Group`) +/// is not neighbour-dependent, unlike the key frame path's `kf_y_mode`, so no +/// override is needed there. Hands back this leaf's own skip flag and +/// intra/inter choice, which is what the next leaf (or the caller's final +/// write-back, mirroring `write_leaf8`'s caller) reads. +#[allow(clippy::too_many_arguments)] +fn write_inter_frame_leaf8( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + grid: &mut MiGrid, + mi_cols: u32, + mi_rows: u32, + block: &BlockCoeffs, + outer_at: (usize, usize), + leaf_mi: (usize, usize), + scan8: &Vec, + scan4: &Vec, + prev_leaf: Option<((usize, usize), bool, bool)>, +) -> Result<(bool, bool)> { + if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES { + return Err(Error::unsupported( + "AV1 tile", + format!( + "intra mode {} is not one of the thirteen this writer codes", + block.mode + ), + )); + } + /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s + /// `size_group_lookup[BLOCK_8X8]`) for this leaf's own size. + const SIZE_GROUP_8: usize = 1; + /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3), same as the 16x16/32x32 + /// branches. + const LAST_FRAME: i8 = 1; + + let (r, c) = outer_at; + let mut above_skip = neighbours.above_skip[c]; + let mut left_skip = neighbours.left_skip[r]; + let mut above_inter = neighbours.above_inter[c]; + let mut left_inter = neighbours.left_inter[r]; + if let Some(((pr, pc), pskip, pinter)) = prev_leaf { + if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 { + above_skip = pskip; + above_inter = pinter; + } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 { + left_skip = pskip; + left_inter = pinter; + } + } + let skip_ctx = usize::from(above_skip) + usize::from(left_skip); + enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); + + let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0); + let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); + let is_inter = block.inter.is_some(); + enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]); + + let mode_for_tx; + if let Some(info) = block.inter { + let sr_ctx = single_ref_ctx(above_inter || left_inter); + enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward + enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2 + enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST + + let (mi_row, mi_col) = leaf_mi; + let stack = find_mv_stack( + grid, + mi_row, + mi_col, + 2, + 2, + LAST_FRAME, + mi_cols as usize, + mi_rows as usize, + ); + + let is_new_mv = matches!(info.mode, InterMode::NewMv); + if is_new_mv { + enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV + } else { + enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new + enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero + enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV + } + if is_new_mv && stack.entries.len() > 1 { + enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]); + } + let mv = if is_new_mv { + write_mv( + enc, + &mut cdfs.mv_comp, + &mut cdfs.mv_joint, + info.mv, + stack.pred_mv, + )?; + info.mv + } else { + stack.nearest_mv + }; + for dr in 0..2 { + for dc in 0..2 { + grid.set( + mi_row + dr, + mi_col + dc, + MiInfo { + is_inter: true, + ref_frame: LAST_FRAME, + mv, + is_new_mv, + size: 2, + }, + ); + } + } + mode_for_tx = 0; + } else { + let mode = usize::from(block.mode); + enc.symbol(mode, &mut cdfs.y_mode[SIZE_GROUP_8]); + if (V_PRED..=D67_PRED).contains(&mode) { + enc.symbol(ANGLE_DELTA_ZERO, &mut cdfs.angle_delta[mode - V_PRED]); + } + enc.symbol(DC_PRED, &mut cdfs.uv_mode_cfl[mode]); + mode_for_tx = mode; + // Intra: no vote, but still a coded cell -- mvstack's extended-scan + // coverage must see it (module doc). + let (mi_row, mi_col) = leaf_mi; + for dr in 0..2 { + for dc in 0..2 { + grid.set( + mi_row + dr, + mi_col + dc, + MiInfo { + is_inter: false, + ref_frame: -1, + mv: (0, 0), + is_new_mv: false, + size: 2, + }, + ); + } + } + } + + let planes = if is_inter { + [TxbSet::Luma8Inter, TxbSet::Chroma4, TxbSet::Chroma4] + } else { + [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4] + }; + if block.skip { + let zero_grids = [ + vec![0i32; TX8 * TX8], + vec![0i32; TX4 * TX4], + vec![0i32; TX4 * TX4], + ]; + neighbours.record_mi(leaf_mi, 8, &zero_grids); + } else { + let grids = [ + level_grid(&block.luma, TX8)?, + level_grid(&block.u, TX4)?, + level_grid(&block.v, TX4)?, + ]; + write_block_planes( + enc, + cdfs, + &planes, + &grids, + &[scan8, scan4, scan4], + &neighbours.around_mi(leaf_mi, 8), + mode_for_tx, + ); + neighbours.record_mi(leaf_mi, 8, &grids); + } + Ok((block.skip, is_inter)) +} + #[cfg(test)] mod tests { use super::*;