diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index be62311a..7d2245e3 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -1107,9 +1107,36 @@ 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 -// prediction are not among them -- this encoder never sets -// `reference_select`, so their CDFs are never read. +// motion vector it takes when it is not. The compound-reference tables +// (`COMP_MODE`/`COMP_REF_TYPE`/`UNI_COMP_REF`/`COMP_REF`/`COMP_BWDREF` above) +// read once a frame's `reference_select` header bit is set (lane-av1comp); +// compound *prediction* itself -- `inter_compound_mode`, compound DRL, the +// mvstack's dual-ref scan, and distance-weighted MC blending -- is not yet +// ported, so a block that actually reads `COMPOUND_REFERENCE` still refuses. + +/// `default_inter_compound_mode_cdf` (entropymode.c): which of the eight +/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`) a compound +/// block takes, indexed by `av1_mode_context_analyzer`'s `comp_ctx` (spec +/// 5.11.24's `compound_mode`, libaom's `read_inter_compound_mode`) -- +/// lane-av1comp, symbol read only, not yet wired into MV assignment or MC. +pub const INTER_COMPOUND_MODE: [[u16; 9]; 8] = [ + [7760, 13823, 15808, 17641, 19156, 20666, 26891, 32768, 0], + [10730, 19452, 21145, 22749, 24039, 25131, 28724, 32768, 0], + [10664, 20221, 21588, 22906, 24295, 25387, 28436, 32768, 0], + [13298, 16984, 20471, 24182, 25067, 25736, 26422, 32768, 0], + [18904, 23325, 25242, 27432, 27898, 28258, 30758, 32768, 0], + [10725, 17454, 20124, 22820, 24195, 25168, 26046, 32768, 0], + [17125, 24273, 25814, 27492, 28214, 28704, 30592, 32768, 0], + [13046, 23214, 24505, 25942, 27435, 28442, 29330, 32768, 0], +]; + +/// `compound_mode_ctx_map` (`mvref_common.h`): folds a compound block's +/// `new_mv_ctx`/`ref_mv_ctx` pair (row = `ref_mv_ctx >> 1`, column = +/// `min(new_mv_ctx, COMP_NEWMV_CTXS - 1)`, `COMP_NEWMV_CTXS` = 5) down to +/// the single `comp_ctx` [`INTER_COMPOUND_MODE`] is indexed by -- +/// `av1_mode_context_analyzer`'s compound branch. +pub const COMPOUND_MODE_CTX_MAP: [[usize; 5]; 3] = + [[0, 1, 1, 1, 1], [1, 2, 3, 4, 4], [4, 4, 5, 6, 7]]; /// `Default_Intra_Inter_Cdf` (spec 9.4): whether an inter frame's block is /// coded as intra, indexed by whether the block above and left are inter. @@ -1150,6 +1177,91 @@ pub const SINGLE_REF: [[[u16; 3]; 6]; 3] = [ ], ]; +/// `default_skip_mode_cdfs` (entropymode.c, `SKIP_MODE_CONTEXTS` = 3): whether +/// a block reads `skip_mode` (forced `NEAREST_NEARESTMV` compound, `skip` +/// forced true, no residual) -- indexed by `av1_get_skip_mode_context` +/// (`above.skip_mode + left.skip_mode`, `pred_common.h`), only read when this +/// frame's own `skip_mode_present` header bit is set and the block is at +/// least 8x8 both dims (`is_comp_ref_allowed`) -- lane-av1comp. +pub const SKIP_MODE: [[u16; 3]; 3] = [[32621, 32768, 0], [20708, 32768, 0], [8127, 32768, 0]]; + +/// `Default_Comp_Mode_Cdf` (spec 9.4, `default_comp_inter_cdf`): whether an +/// inter block reads `SINGLE_REFERENCE` or `COMPOUND_REFERENCE` -- only +/// reached once `read_ref_frames` knows the frame's `reference_select` +/// header bit made the choice per-block instead of fixing it, indexed by +/// `av1_get_reference_mode_context` (lane-av1comp). +pub const COMP_MODE: [[u16; 3]; 5] = [ + [26828, 32768, 0], + [24035, 32768, 0], + [12031, 32768, 0], + [10640, 32768, 0], + [2901, 32768, 0], +]; + +/// `Default_Comp_Ref_Type_Cdf` (spec 9.4, `default_comp_ref_type_cdf`): +/// unidirectional vs. bidirectional compound reference pair, indexed by +/// `av1_get_comp_reference_type_context`. +pub const COMP_REF_TYPE: [[u16; 3]; 5] = [ + [1198, 32768, 0], + [2070, 32768, 0], + [9166, 32768, 0], + [7499, 32768, 0], + [22475, 32768, 0], +]; + +/// `Default_Comp_Group_Idx_Cdf` (spec 9.4, libaom `default_comp_group_idx_cdfs`): +/// whether a compound block's `comp_group_idx` picks masked compound (`1`) +/// over the plain distance-weighted/simple-average blend (`0`), indexed by +/// `get_comp_group_idx_context` -- only read when `seq.enable_masked_compound` +/// and the block size is masked-compound-eligible (lane-av1comp). +pub const COMP_GROUP_IDX: [[u16; 3]; 6] = [ + [26607, 32768, 0], + [22891, 32768, 0], + [18840, 32768, 0], + [24594, 32768, 0], + [19934, 32768, 0], + [22674, 32768, 0], +]; + +/// `Default_Compound_Idx_Cdf` (spec 9.4, libaom `default_compound_idx_cdfs`): +/// whether a compound block's `compound_idx` picks the simple average +/// (`1`) or [`crate::compound::dist_wtd_comp_weight_assign`]'s distance +/// weights (`0`), indexed by `get_comp_index_context` -- only read when +/// `seq.enable_jnt_comp` (lane-av1comp). +pub const COMPOUND_IDX: [[u16; 3]; 6] = [ + [18244, 32768, 0], + [12865, 32768, 0], + [7053, 32768, 0], + [13259, 32768, 0], + [9334, 32768, 0], + [4644, 32768, 0], +]; + +/// `Default_Uni_Comp_Ref_Cdf` (spec 9.4, `default_uni_comp_ref_cdf`): the +/// three binary decisions narrowing a unidirectional compound pair down to +/// one of `{BWDREF,ALTREF}`/`{LAST,LAST2}`/`{LAST,LAST3}`/`{LAST,GOLDEN}`. +pub const UNI_COMP_REF: [[[u16; 3]; 3]; 3] = [ + [[5284, 32768, 0], [3865, 32768, 0], [3128, 32768, 0]], + [[23152, 32768, 0], [14173, 32768, 0], [15270, 32768, 0]], + [[31774, 32768, 0], [25120, 32768, 0], [26710, 32768, 0]], +]; + +/// `Default_Comp_Ref_Cdf` (spec 9.4, `default_comp_ref_cdf`): the three +/// binary decisions narrowing a bidirectional pair's forward reference. +pub const COMP_REF: [[[u16; 3]; 3]; 3] = [ + [[4946, 32768, 0], [9468, 32768, 0], [1503, 32768, 0]], + [[19891, 32768, 0], [22441, 32768, 0], [15160, 32768, 0]], + [[30731, 32768, 0], [31059, 32768, 0], [27544, 32768, 0]], +]; + +/// `Default_Comp_Bwdref_Cdf` (spec 9.4, `default_comp_bwdref_cdf`): the two +/// binary decisions narrowing a bidirectional pair's backward reference. +pub const COMP_BWDREF: [[[u16; 3]; 2]; 3] = [ + [[2235, 32768, 0], [1423, 32768, 0]], + [[17182, 32768, 0], [15175, 32768, 0]], + [[30606, 32768, 0], [30489, 32768, 0]], +]; + /// `Default_Y_Mode_Cdf` (spec 9.4): the thirteen luma intra modes of an inter /// frame's intra block, indexed by the block's size group -- unlike a key /// frame's [`KF_Y_MODE`], which is indexed by the neighbours' modes instead. diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index b20e1623..6093bfbc 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -293,6 +293,31 @@ pub(crate) struct Cdfs { pub intra_inter: [[u16; 3]; 4], /// The six binary decisions of an inter block's single reference frame. pub single_ref: [[[u16; 3]; 6]; 3], + /// Whether a block reads `SINGLE_REFERENCE` or `COMPOUND_REFERENCE` + /// (lane-av1comp, spec 5.11.25's `comp_mode`). + pub comp_mode: [[u16; 3]; 5], + /// Whether a block reads `skip_mode` (lane-av1comp, spec 5.11.29's + /// `skip_mode`), indexed by `av1_get_skip_mode_context`. + pub skip_mode: [[u16; 3]; 3], + /// Which of the eight `INTER_COMPOUND_MODES` a `COMPOUND_REFERENCE` + /// block takes (lane-av1comp, spec 5.11.24's `compound_mode`). + pub inter_compound_mode: [[u16; 9]; 8], + /// Unidirectional vs. bidirectional compound reference pair + /// (lane-av1comp, spec 5.11.25's `comp_reference_type`). + pub comp_ref_type: [[u16; 3]; 5], + /// The three binary decisions of a unidirectional compound pair. + pub uni_comp_ref: [[[u16; 3]; 3]; 3], + /// The three binary decisions of a bidirectional pair's forward ref. + pub comp_ref: [[[u16; 3]; 3]; 3], + /// The two binary decisions of a bidirectional pair's backward ref. + pub comp_bwdref: [[[u16; 3]; 2]; 3], + /// Whether a compound block's `comp_group_idx` picks masked compound + /// (lane-av1comp, spec 5.11.25's `comp_group_idx`). + pub comp_group_idx: [[u16; 3]; 6], + /// Whether a compound block's `compound_idx` picks the simple average + /// over the distance-weighted blend (lane-av1comp, spec 5.11.25's + /// `compound_idx`). + pub compound_idx: [[u16; 3]; 6], /// The luma mode of an inter frame's intra block, by its size group. pub y_mode: [[u16; 14]; 4], /// Whether an inter block codes its motion vector explicitly. @@ -500,6 +525,15 @@ impl Cdfs { reset2(&mut self.dc_sign_chroma); reset2(&mut self.intra_inter); reset3(&mut self.single_ref); + reset2(&mut self.comp_mode); + reset2(&mut self.skip_mode); + reset2(&mut self.inter_compound_mode); + reset2(&mut self.comp_ref_type); + reset3(&mut self.uni_comp_ref); + reset3(&mut self.comp_ref); + reset3(&mut self.comp_bwdref); + reset2(&mut self.comp_group_idx); + reset2(&mut self.compound_idx); reset2(&mut self.y_mode); reset2(&mut self.new_mv); reset2(&mut self.zero_mv); @@ -924,6 +958,15 @@ impl Cdfs { dc_sign_chroma: cdf::DC_SIGN_CHROMA, intra_inter: cdf::INTRA_INTER, single_ref: cdf::SINGLE_REF, + comp_mode: cdf::COMP_MODE, + inter_compound_mode: cdf::INTER_COMPOUND_MODE, + comp_ref_type: cdf::COMP_REF_TYPE, + uni_comp_ref: cdf::UNI_COMP_REF, + comp_ref: cdf::COMP_REF, + comp_bwdref: cdf::COMP_BWDREF, + skip_mode: cdf::SKIP_MODE, + comp_group_idx: cdf::COMP_GROUP_IDX, + compound_idx: cdf::COMPOUND_IDX, y_mode: cdf::Y_MODE, new_mv: cdf::NEW_MV, zero_mv: cdf::ZERO_MV, @@ -1171,6 +1214,12 @@ mod tests { assert_eq!(cdfs.partition_w64[2], cdf::PARTITION_W64[2]); assert_eq!(cdfs.intra_inter, cdf::INTRA_INTER); assert_eq!(cdfs.single_ref, cdf::SINGLE_REF); + assert_eq!(cdfs.comp_mode, cdf::COMP_MODE); + assert_eq!(cdfs.inter_compound_mode, cdf::INTER_COMPOUND_MODE); + assert_eq!(cdfs.comp_ref_type, cdf::COMP_REF_TYPE); + assert_eq!(cdfs.uni_comp_ref, cdf::UNI_COMP_REF); + assert_eq!(cdfs.comp_ref, cdf::COMP_REF); + assert_eq!(cdfs.comp_bwdref, cdf::COMP_BWDREF); assert_eq!(cdfs.y_mode, cdf::Y_MODE); assert_eq!(cdfs.new_mv, cdf::NEW_MV); assert_eq!(cdfs.zero_mv, cdf::ZERO_MV); diff --git a/crates/ec-av1/src/compound.rs b/crates/ec-av1/src/compound.rs new file mode 100644 index 00000000..028cc574 --- /dev/null +++ b/crates/ec-av1/src/compound.rs @@ -0,0 +1,121 @@ +//! Compound-reference blend weights (spec 7.11.3.15's "Distance weights +//! process", libaom's `av1_dist_wtd_comp_weight_assign` in +//! `reconinter.c`) -- pure, independent of the CDF/bitstream plumbing that +//! decides *whether* a block reads `compound_idx` at all (lane-av1comp, +//! decode.rs). Kept its own module so it is testable without a live +//! decoder: `dist_wtd_comp_weight_assign` takes exactly the four order +//! hints libaom's version reads off `AV1_COMMON`/`MB_MODE_INFO`. + +/// `MAX_FRAME_DISTANCE` (spec/`enums.h`): `(1 << FRAME_OFFSET_BITS) - 1`, +/// `FRAME_OFFSET_BITS == 5`. +const MAX_FRAME_DISTANCE: i32 = (1 << 5) - 1; + +/// `quant_dist_weight` (libaom `common_data.h`) -- the three candidate +/// weight ratios the search below picks between, before falling back to the +/// index-3 row when either distance is zero. +const QUANT_DIST_WEIGHT: [[i32; 2]; 4] = [[2, 3], [2, 5], [2, 7], [1, MAX_FRAME_DISTANCE]]; + +/// `quant_dist_lookup_table` (libaom `common_data.h`): the actual +/// `fwd_offset`/`bck_offset` pair each `QUANT_DIST_WEIGHT` row resolves to +/// (both always sum to 16, `1 << DIST_PRECISION_BITS`). +const QUANT_DIST_LOOKUP_TABLE: [[i32; 2]; 4] = [[9, 7], [11, 5], [12, 4], [13, 3]]; + +/// `av1_dist_wtd_comp_weight_assign` (spec 7.11.3.15 / libaom +/// `reconinter.c`): `(fwd_weight, bck_weight)` for a compound block, given +/// this frame's own `order_hint` and the two references' order hints -- +/// `ref0_order_hint` names `mbmi->ref_frame[0]` (libaom's "`bck`", despite +/// the name -- it is nearer in decode order for a typical GOP but the +/// spec's algebra does not assume that), `ref1_order_hint` names +/// `ref_frame[1]` ("`fwd`"). +/// +/// `compound_idx == 1` (or `!is_compound`, never reached from here) is the +/// simple-average caller's job: it never calls this and uses `(8, 8)` +/// directly (spec 7.11.3.15's `use_dist_wtd_comp_avg == 0` branch) -- +/// this function only ever implements the `use_dist_wtd_comp_avg == 1` +/// (`compound_idx == 0`) branch. +pub(crate) fn dist_wtd_comp_weight_assign( + order_hint_bits: u32, + cur_order_hint: u32, + ref0_order_hint: u32, + ref1_order_hint: u32, +) -> (i32, i32) { + let d0 = + crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint) + .abs() + .clamp(0, MAX_FRAME_DISTANCE); + let d1 = + crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint) + .abs() + .clamp(0, MAX_FRAME_DISTANCE); + + let order = usize::from(d0 <= d1); + + if d0 == 0 || d1 == 0 { + return ( + QUANT_DIST_LOOKUP_TABLE[3][order], + QUANT_DIST_LOOKUP_TABLE[3][1 - order], + ); + } + + let mut i = 0; + while i < 3 { + let c0 = QUANT_DIST_WEIGHT[i][order]; + let c1 = QUANT_DIST_WEIGHT[i][1 - order]; + let d0_c0 = d0 * c0; + let d1_c1 = d1 * c1; + if (d0 > d1 && d0_c0 < d1_c1) || (d0 <= d1 && d0_c0 > d1_c1) { + break; + } + i += 1; + } + + ( + QUANT_DIST_LOOKUP_TABLE[i][order], + QUANT_DIST_LOOKUP_TABLE[i][1 - order], + ) +} + +#[cfg(test)] +mod tests { + use super::dist_wtd_comp_weight_assign; + + /// Equidistant references (spec/libaom's `d0 == d1` case) land on + /// `order == 1` (`d0 <= d1`) throughout, and the very first weight + /// candidate (`i == 0`, ratio `2:3`) always survives the search's break + /// condition when `d0_c0 == d1_c1`'s neither branch fires -- so a + /// symmetric GOP (order hints `8` behind and `8` ahead of a `16`-hint + /// current frame) resolves to the row-0 weights `(7, 9)`: `order == 1` + /// (`d0 <= d1`) selects `QUANT_DIST_LOOKUP_TABLE[0][1] == 7` for + /// `fwd_offset` and `QUANT_DIST_LOOKUP_TABLE[0][0] == 9` for + /// `bck_offset`. + #[test] + fn equidistant_references_pick_the_first_weight_row() { + assert_eq!(dist_wtd_comp_weight_assign(8, 16, 8, 24), (7, 9)); + } + + /// A reference at zero relative distance (this frame repeats one of its + /// own references' order hint -- degenerate but spec-legal) always + /// takes the index-3 lookup row (`13`/`3`) rather than entering the + /// weight search, matching libaom's `d0 == 0 || d1 == 0` early return. + #[test] + fn zero_distance_reference_takes_the_index_3_row() { + // ref1 (fwd) coincides with cur -> d0 == 0. + assert_eq!(dist_wtd_comp_weight_assign(8, 16, 8, 16), (3, 13)); + } + + /// Weights always sum to `1 << DIST_PRECISION_BITS == 16` -- every row + /// of `QUANT_DIST_LOOKUP_TABLE` was picked to hold that invariant, and + /// [`combine_compound`](crate::mc::combine_compound)'s final shift + /// (`InterPostRound + DIST_PRECISION_BITS`) assumes it. + #[test] + fn weights_always_sum_to_sixteen() { + for cur in [0u32, 16, 40] { + for r0 in [0u32, 8, 32] { + for r1 in [4u32, 24, 48] { + let (fwd, bck) = dist_wtd_comp_weight_assign(8, cur, r0, r1); + assert_eq!(fwd + bck, 16, "cur={cur} r0={r0} r1={r1}"); + } + } + } + } +} diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 1ea65b89..9713f9af 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -32,9 +32,10 @@ use crate::mc; use crate::msac::SymbolDecoder; use crate::mvstack::{ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME, - MiGrid, MiInfo, NO_SIGN_BIAS, SignBiasTable, find_mv_stack, find_mv_stack_with_sign_bias, - single_ref_ctx, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, - single_ref_p5_ctx, single_ref_p6_ctx, + MiGrid, MiInfo, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx, + find_mv_stack, find_mv_stack_with_sign_bias, reference_mode_ctx, single_ref_ctx, + single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, + single_ref_p6_ctx, uni_comp_ref_p1_ctx, }; use crate::tile::{INTRA_MODE_CTX, block_grid, has_half}; use crate::transform::{TxType, dequant_and_inverse_typed}; @@ -131,6 +132,41 @@ static BWDREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUs static ALTREF2_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); static ALTREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp) +/// -- proves a `reference_select` stream actually reached a block that picked +/// compound, not just that the header bit was set. Every such block is +/// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]), +/// so this only ever counts attempted reads, never a completed decode. +static COMP_MODE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Current value of [`COMP_MODE_HITS`]. +pub(crate) fn comp_mode_hits() -> usize { + COMP_MODE_HITS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) -- +/// proves a real `skip_mode_present` stream actually reached a block that +/// picked it, not just that the frame header bit was set. +static SKIP_MODE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Current value of [`SKIP_MODE_HITS`]. +pub(crate) fn skip_mode_hits() -> usize { + SKIP_MODE_HITS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// How many [`read_inter_compound_mode`] reads actually happened +/// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own +/// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound +/// mvstack build), not just that `comp_mode` fired. Still refused right +/// after (no MV assignment or MC wired), so this only counts attempted +/// reads. +static COMPOUND_MODE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Current value of [`COMPOUND_MODE_HITS`]. +pub(crate) fn compound_mode_hits() -> usize { + COMPOUND_MODE_HITS.load(std::sync::atomic::Ordering::Relaxed) +} + /// How many query blocks folded in at least one temporal MV candidate /// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the /// temporal-MV gate's own firing counter (lane-av1tmvp). @@ -736,6 +772,11 @@ struct Neighbours { /// `left_skip`. above_skip: Vec, left_skip: Vec, + /// Whether the block above/left of this column/row coded `skip_mode` + /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup, + /// lane-av1comp round 14. + above_skip_mode: Vec, + left_skip_mode: Vec, /// Whether the block above/left was coded inter -- the `is_inter` /// context (spec `av1_get_intra_inter_context`), a duplicate of /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`. @@ -750,6 +791,23 @@ struct Neighbours { /// enough). above_ref: Vec, left_ref: Vec, + /// The block above/left's *second* reference frame when it was coded + /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra -- + /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx` + /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s + /// `i8`, once a compound `read_ref_frames` lands. Always `None` today + /// (no decode path here ever produces a compound block yet). + above_ref1: Vec>, + left_ref1: Vec>, + /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context` + /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`): + /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or + /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a + /// single-ref one, or `0` for intra/unavailable -- lane-av1comp. + above_comp_group_idx: Vec, + left_comp_group_idx: Vec, + above_compound_idx: Vec, + left_compound_idx: Vec, /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or /// `3` = "no info": an intra neighbour or the frame's own border) of the /// block above/left of this column/row -- spec @@ -798,10 +856,18 @@ impl Neighbours { left_side_mi: vec![SB; rows * (SUB / MI)], above_skip: vec![false; cols], left_skip: vec![false; rows], + above_skip_mode: vec![false; cols], + left_skip_mode: vec![false; rows], above_inter: vec![false; cols], left_inter: vec![false; rows], above_ref: vec![-1; cols], left_ref: vec![-1; rows], + above_ref1: vec![None; cols], + left_ref1: vec![None; rows], + above_comp_group_idx: vec![0; cols], + left_comp_group_idx: vec![0; rows], + above_compound_idx: vec![0; cols], + left_compound_idx: vec![0; rows], above_filter: vec![[3u8; 2]; cols], left_filter: vec![[3u8; 2]; rows], mi_cols, @@ -883,8 +949,12 @@ impl Neighbours { self.left_side.iter_mut().for_each(|s| *s = SB); self.left_side_mi.iter_mut().for_each(|s| *s = SB); self.left_skip.iter_mut().for_each(|s| *s = false); + self.left_skip_mode.iter_mut().for_each(|s| *s = false); self.left_inter.iter_mut().for_each(|i| *i = false); self.left_ref.iter_mut().for_each(|r| *r = -1); + self.left_ref1.iter_mut().for_each(|r| *r = None); + self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0); + self.left_compound_idx.iter_mut().for_each(|r| *r = 0); self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]); } @@ -903,20 +973,67 @@ impl Neighbours { is_inter: bool, ref_frame: i8, filter: [u8; 2], + skip_mode: bool, ) { let (r, c) = at; for cell in 0..side / SUB { self.above_skip[c + cell] = skip; self.left_skip[r + cell] = skip; + self.above_skip_mode[c + cell] = skip_mode; + self.left_skip_mode[r + cell] = skip_mode; self.above_inter[c + cell] = is_inter; self.left_inter[r + cell] = is_inter; self.above_ref[c + cell] = ref_frame; self.left_ref[r + cell] = ref_frame; + // lane-av1comp: no caller of `record_inter` ever decodes a + // compound block yet (see [`Self::above_ref1`]'s doc); the + // parameter this becomes lands with `read_ref_frames`. + self.above_ref1[c + cell] = None; + self.left_ref1[r + cell] = None; + // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s + // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads + // as `3`/`1` even though this block has no second reference. + // `record_compound_ctx` overwrites this with the real bit for an + // actual compound block's cells, called right after this one. + let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME; + self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 }; + self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 }; + self.above_compound_idx[c + cell] = u8::from(altref); + self.left_compound_idx[r + cell] = u8::from(altref); self.above_filter[c + cell] = filter; self.left_filter[r + cell] = filter; } } + /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with + /// a real compound block's own `comp_group_idx`/`compound_idx` bits + /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/ + /// `get_comp_index_context`) -- called right after `record_inter` for + /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also + /// stamps `above_ref1`/`left_ref1` with the block's real second + /// reference, which `record_inter` always clears to `None` (lane-av1comp: + /// this is the one caller that actually knows it) -- so the next block's + /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound + /// neighbour instead of `record_inter`'s single-ref default. + fn record_compound_ctx( + &mut self, + at: (usize, usize), + side: usize, + ref1: i8, + comp_group_idx: u8, + compound_idx: u8, + ) { + let (r, c) = at; + for cell in 0..side / SUB { + self.above_ref1[c + cell] = Some(ref1); + self.left_ref1[r + cell] = Some(ref1); + self.above_comp_group_idx[c + cell] = comp_group_idx; + self.left_comp_group_idx[r + cell] = comp_group_idx; + self.above_compound_idx[c + cell] = compound_idx; + self.left_compound_idx[r + cell] = compound_idx; + } + } + /// The context of a block's partition symbol: delegates to the mi-precise /// reader (same pattern as `around`/`around_mi`) -- `above_side`/ /// `left_side` are only ever advanced in whole-[`SUB`] steps by @@ -2378,6 +2495,27 @@ fn cdef_filter_block( /// /// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision) /// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels). +// r17 bisect scratch: dump this frame's true-extent Y/U/V (same layout as +// aomdec's EC_AV1_PREFILT_DUMP/EC_AV1_POSTFILT_DUMP) to `$var.f$idx` when +// `var` is set. Remove with the rest of the r17 bisect scaffolding. +static R17_DUMP_FRAME_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +fn r17_dump(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, idx: usize) { + let Ok(base) = std::env::var(var) else { + return; + }; + let mut out = Vec::new(); + for r in 0..y.true_height { + out.extend_from_slice(&y.data[r * y.width..r * y.width + y.true_width]); + } + for r in 0..u.true_height { + out.extend_from_slice(&u.data[r * u.width..r * u.width + u.true_width]); + } + for r in 0..v.true_height { + out.extend_from_slice(&v.data[r * v.width..r * v.width + v.true_width]); + } + let _ = std::fs::write(format!("{base}.f{idx}"), out); +} + fn apply_deblock( y: &mut PlaneBuf, u: &mut PlaneBuf, @@ -3777,6 +3915,298 @@ fn read_single_ref(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above_ref: i8, left ref_frame } +/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads +/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's +/// `reference_select` header bit lets a block choose per-block instead of +/// fixing the mode. `above`/`left` are `None` for an intra/unavailable +/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s +/// 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>( + ref_frame: i8, + ref_y: &'a PlaneBuf, + ref_u: &'a PlaneBuf, + ref_v: &'a PlaneBuf, + other_refs: &'a RefSlots, +) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> { + 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 \ + ref_frame_idx slot for it", + )), + } + } +} + +/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to +/// the square block sizes this decoder ever decodes (32/16/8, all +/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then +/// always `is_interinter_compound_used`, so the function is always `true` +/// for `side` -- kept as a named call (rather than inlined `true`) so a +/// future sub-8 block size does not silently misdecode a real stream. +fn is_any_masked_compound_used_here(side: usize) -> bool { + side.min(side) >= 8 +} + +/// Whether a compound reference pair is unidirectional (both references on +/// the same temporal side of the current frame) -- `has_uni_comp_refs` +/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition: +/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is +/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) == +/// is_backward(ref1)`). Used to build a real +/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching +/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls. +fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool { + let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r); + backward(ref0) == backward(ref1) +} + +/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the +/// above/left neighbour contributions [`Neighbours::record_inter`]/ +/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5. +fn get_comp_group_idx_context(neighbours: &Neighbours, at: (usize, usize), side: usize) -> usize { + let _ = side; + let (r, c) = at; + (neighbours.above_comp_group_idx[c] as usize + neighbours.left_comp_group_idx[r] as usize) + .min(5) +} + +/// `get_comp_index_context` (libaom `pred_common.h`): the above/left +/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this +/// block's own two references' distances from the current frame (spec +/// 7.11.3.15's `get_relative_dist`, same convention +/// [`crate::compound::dist_wtd_comp_weight_assign`] uses). +#[allow(clippy::too_many_arguments)] +fn get_comp_index_context( + neighbours: &Neighbours, + at: (usize, usize), + side: usize, + order_hint_bits: u32, + cur_order_hint: u32, + ref0_order_hint: u32, + ref1_order_hint: u32, +) -> usize { + let _ = side; + let (r, c) = at; + let fwd = + crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint) + .abs(); + let bck = + crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint) + .abs(); + let offset = usize::from(fwd == bck); + neighbours.above_compound_idx[c] as usize + + neighbours.left_compound_idx[r] as usize + + 3 * offset +} + +fn read_comp_mode( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + above: Option, + left: Option, +) -> bool { + let ctx = reference_mode_ctx(above, left); + let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1; + if compound { + COMP_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + compound +} + +/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/ +/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound +/// arm), reached once [`read_comp_mode`] has already returned +/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`. +/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef` +/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1` +/// convention [`read_single_ref`] already uses, for every downstream binary +/// decision. libaom `pred_common.c`'s own compound context functions +/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`, +/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`].. +/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name +/// (same vote-the-neighbours-above-left shape, same forward/backward and +/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one +/// against the C source rather than porting six near-duplicate functions. +/// Its caller today only needs the symbols consumed, correctly, to keep the +/// arithmetic decoder's own state in sync before refusing the block by name +/// -- the returned pair is not yet threaded into any motion-compensation +/// path. +fn read_compound_ref_frames( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + above: Option, + left: Option, + above_ref: i8, + left_ref: i8, +) -> (i8, i8) { + let a = (above_ref > 0).then_some(above_ref); + let l = (left_ref > 0).then_some(left_ref); + let type_ctx = comp_reference_type_ctx(above, left); + let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0; + if unidir { + // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_- + // uni_comp_ref_p is single_ref_p1's own forward/backward vote. + let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, l)][0]); + if bit == 1 { + (BWDREF_FRAME, ALTREF_FRAME) + } else { + let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, l)][1]); + if p1 == 1 { + // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5. + let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, l)][2]); + if p2 == 1 { + (LAST_FRAME, GOLDEN_FRAME) + } else { + (LAST_FRAME, LAST3_FRAME) + } + } else { + (LAST_FRAME, LAST2_FRAME) + } + } + } else { + // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3. + let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, l)][0]); + let ref0 = if bit0 == 0 { + // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4. + let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, l)][1]); + if p1 == 1 { LAST2_FRAME } else { LAST_FRAME } + } else { + // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5. + let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, l)][2]); + if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME } + }; + // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2. + let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, l)][0]); + let ref1 = if bit1 == 0 { + // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6. + let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, l)][1]); + if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME } + } else { + ALTREF_FRAME + }; + (ref0, ref1) + } +} + +/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight +/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as +/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once +/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is +/// libaom's `av1_mode_context_analyzer`'s compound branch -- +/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS +/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack:: +/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol +/// is not yet turned into an assigned MV pair or motion-compensated -- +/// lane-av1comp. +fn read_inter_compound_mode( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + new_mv_ctx: usize, + ref_mv_ctx: usize, +) -> u8 { + let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)]; + COMPOUND_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8 +} + +/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of +/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is +/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`.. +/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads +/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any +/// non-`IDENTITY` global motion model before a tile is ever decoded. +/// +/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the +/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its +/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV` +/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching +/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode". +fn assign_compound_mv( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + comp_stack: &crate::mvstack::CompoundMvStack, + mode: u8, + allow_high_precision_mv: bool, +) -> ((i32, i32), (i32, i32)) { + const NEAREST_NEARESTMV: u8 = 0; + const NEAR_NEARMV: u8 = 1; + const NEAREST_NEWMV: u8 = 2; + const NEW_NEARESTMV: u8 = 3; + const NEAR_NEWMV: u8 = 4; + const NEW_NEARMV: u8 = 5; + const GLOBAL_GLOBALMV: u8 = 6; + const NEW_NEWMV: u8 = 7; + + let mut ref_mv_idx = 0usize; + if mode == NEW_NEWMV { + let mut idx = 0usize; + while idx < 2 && comp_stack.entries.len() > idx + 1 { + if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 { + break; + } + idx += 1; + } + ref_mv_idx = idx; + } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) { + let mut idx = 1usize; + while idx < 3 && comp_stack.entries.len() > idx + 1 { + if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 { + break; + } + idx += 1; + } + ref_mv_idx = idx - 1; + } + + let near = comp_stack + .entries + .get(ref_mv_idx + 1) + .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1)); + let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) { + ref_mv_idx + 1 + } else { + ref_mv_idx + }; + let new_pred = comp_stack + .entries + .get(new_idx) + .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1)); + + let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| { + read_mv( + dec, + &mut cdfs.mv_comp, + &mut cdfs.mv_joint, + base, + allow_high_precision_mv, + ) + }; + + match mode { + NEAREST_NEARESTMV => comp_stack.nearest_mv, + NEAR_NEARMV => near, + NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)), + NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1), + NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)), + NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1), + GLOBAL_GLOBALMV => ((0, 0), (0, 0)), + _ => ( + read_new(dec, cdfs, new_pred.0), + read_new(dec, cdfs, new_pred.1), + ), + } +} + /// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip, /// `is_inter`, then either the single-reference/MV-stack/motion-vector chain /// and motion-compensated reconstruction, or the inter frame's own intra @@ -3829,298 +4259,706 @@ fn decode_inter_block( interp_fixed: Option, enable_dual_filter: bool, tpl_frame: Option<&TplFrameArgs>, + // lane-av1comp: this frame header's own `reference_select` bit -- `false` + // means every block is `SINGLE_REFERENCE` by construction and `comp_mode` + // is never read (spec 5.11.25); `true` reads `comp_mode` per block and + // refuses (rather than silently misdecoding) the ones that pick + // `COMPOUND_REFERENCE`, since two-reference motion compensation is not + // wired yet. + reference_select: bool, + // lane-av1comp: `seq_params`' own masked-compound/distance-weighted- + // compound enable bits, gating `comp_group_idx`/`compound_idx` + // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the + // compound blend weights need this frame's own order hint regardless + // of `use_ref_frame_mvs`. + enable_masked_compound: bool, + enable_jnt_comp: bool, + order_hint_bits: u32, + order_hint: u32, + ref_order_hints: [u32; 7], + // lane-av1comp round 14: this frame header's own `skip_mode_present` bit + // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s + // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) -- + // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip` + // when this is `true` (every block this decoder reaches is >= 8x8, so + // `is_comp_ref_allowed` never gates it further); a `true` result forces + // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/ + // DRL symbol read, and a plain average blend with no `comp_group_idx`/ + // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509). + skip_mode_present: bool, + skip_mode_frame: [u8; 2], ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); let (cpx, cpy) = (px / 2, py / 2); let chroma_side = side / 2; + let skip_mode_ctx = + usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]); + let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; + if skip_mode { + SKIP_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]); - let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; + let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; let (has_above, has_left) = (r > 0, c > 0); let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]); 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 is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; let mode_for_tx; let (luma_grid, u_grid, v_grid); let block_filter; let ref_frame_for_lf; let globalmv_for_lf; + // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real + // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the + // common `record_inter` call below (which would otherwise stamp the + // single-ref ALTREF-special-case default over it). + let mut compound_ctx: Option<(i8, u8, u8)> = None; if is_inter { - let ref_frame = read_single_ref(dec, cdfs, neighbours.above_ref[c], neighbours.left_ref[r]); - ref_frame_for_lf = ref_frame; - // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own - // stacked defects (lf_level ref/mode-delta forwarding, the - // switchable_interp ref-frame ctx gate, and a film-grain synthesis - // gap that looked like a GOLDEN MC bug by survivor bias -- see the - // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs` - // 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 (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); - let bw4 = side / 4; - // spec 7.10.2.8: only reached when the frame header set - // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None` - // otherwise) -- `cur_offset_0` is this query block's own resolved - // `ref_frame`'s distance from the current frame (spec 7.9.3), - // recomputed per block since different blocks pick different refs. - let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs { - field: t.field, - cur_offset_0: crate::motion_field::get_relative_dist( - t.order_hint_bits, - t.order_hint, - t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], - ), - allow_high_precision_mv, + let above_nbr = has_above.then(|| NeighbourRef { + is_inter: above_inter, + ref0: if above_inter { + neighbours.above_ref[c] + } else { + 0 + }, + ref1: neighbours.above_ref1[c], + uni: neighbours.above_ref1[c] + .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[c], r1)), }); - let stack = find_mv_stack_with_sign_bias( - grid, - mi_row, - mi_col, - bw4, - bw4, - ref_frame, - mi_cols as usize, - mi_rows as usize, - sign_bias_table, - tpl, - ); - let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; - let mut is_globalmv = false; - let (mv, is_new_mv) = if !not_new { - // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): - // read at most two `drl_mode` bits, one per stack entry past the - // first, stopping at the first `0`. The chosen index selects - // which stack entry `read_mv`'s base predictor comes from - // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`) - // -- entry 0 (`stack.pred_mv`) only when the loop never advances. - let mut idx = 0usize; - while idx < 2 && stack.entries.len() > idx + 1 { - if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { - break; - } - idx += 1; - } - let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); - ( - read_mv( + let left_nbr = has_left.then(|| NeighbourRef { + is_inter: left_inter, + ref0: if left_inter { + neighbours.left_ref[r] + } else { + 0 + }, + ref1: neighbours.left_ref1[r], + uni: neighbours.left_ref1[r] + .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[r], r1)), + }); + let is_compound = + skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr)); + if is_compound { + let (ref0, ref1) = if skip_mode { + (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8) + } else { + read_compound_ref_frames( dec, - &mut cdfs.mv_comp, - &mut cdfs.mv_joint, - base_mv, - allow_high_precision_mv, + cdfs, + above_nbr, + left_nbr, + neighbours.above_ref[c], + neighbours.left_ref[r], + ) + }; + let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + let bw4 = side / 4; + // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same + // `use_ref_frame_mvs` gating as the single-ref `tpl` build + // below, just one `get_relative_dist` per reference. + let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs { + field: t.field, + cur_offset_0: crate::motion_field::get_relative_dist( + t.order_hint_bits, + t.order_hint, + t.ref_order_hints[(ref0 - LAST_FRAME) as usize], ), - true, - ) - } else { - let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; - is_globalmv = !not_zero; - let mv = if !not_zero { - // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1) under the - // `GmType::IDENTITY` this crate's `decode_stream` requires of - // every inter frame's `LAST_FRAME` entry (any other warp - // model is refused before the tile decoder is ever called). - (0, 0) + cur_offset_1: crate::motion_field::get_relative_dist( + t.order_hint_bits, + t.order_hint, + t.ref_order_hints[(ref1 - LAST_FRAME) as usize], + ), + allow_high_precision_mv, + }); + let comp_stack = crate::mvstack::find_mv_stack_compound( + grid, + mi_row, + mi_col, + bw4, + bw4, + (ref0, ref1), + mi_cols as usize, + mi_rows as usize, + sign_bias_table, + comp_tpl, + ); + let compound_mode = if skip_mode { + 0 // NEAREST_NEARESTMV, forced -- no mode symbol read } else { - let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; - if nearest { - stack.nearest_mv + read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx) + }; + let (mv0, mv1) = assign_compound_mv( + dec, + cdfs, + &comp_stack, + compound_mode, + allow_high_precision_mv, + ); + let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV + 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 above_filter_ctx = if neighbours.above_ref[c] == ref0 { + neighbours.above_filter[c] + } else { + [3, 3] + }; + let left_filter_ctx = if neighbours.left_ref[r] == ref0 { + neighbours.left_filter[r] + } else { + [3, 3] + }; + let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( + dec, + cdfs, + interp_fixed, + enable_dual_filter, + is_globalmv, + above_filter_ctx, + left_filter_ctx, + ); + block_filter = resolved_filter; + globalmv_for_lf = is_globalmv; + ref_frame_for_lf = ref0; + mode_for_tx = 0; + for dr in 0..bw4 { + for dc in 0..bw4 { + grid.set( + mi_row + dr, + mi_col + dc, + MiInfo { + is_inter: true, + ref_frame: ref0, + ref_frame1: Some(ref1), + mv1: Some(mv1), + mv: mv0, + is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7), + size: bw4, + }, + ); + } + } + // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when + // masked compound / distance-weighted compound are actually + // enabled for this stream -- `is_any_masked_compound_used_here` + // is `true` for every block size this decoder ever reaches + // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible + // there), so the gate reduces to the sequence header bit; kept + // as an explicit call so a future smaller block size is not + // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`). + let group_ctx = get_comp_group_idx_context(neighbours, at, side); + let comp_group_idx = if !skip_mode + && enable_masked_compound + && is_any_masked_compound_used_here(side) + { + dec.symbol(&mut cdfs.comp_group_idx[group_ctx]) + } else { + 0 + }; + if comp_group_idx == 1 { + return Err(unsupported( + "a masked COMPOUND_REFERENCE block (comp_group_idx == 1, wedge/\ + diffwtd) -- this decoder's compound blend is the plain distance-\ + weighted/simple-average combine only, lane-av1comp", + )); + } + // corner-cut (lane-av1comp r16/r17): a real aomenc stream + // (fixtures/av1comp-r16-compound-mismatch.obu, seed 42) proved + // predict_compound_intermediate/combine_compound wrong by up to + // 4/255 in a 32x32 quadrant, spilling a few pixels into + // neighbours. r16 called this "loop-filter-shaped"; r17 + // FALSIFIED that -- dumping this decoder's own pre-deblock + // frame buffer (`r17_dump`, `EC_AV1_PREFILT_DUMP`) against + // aomdec's own `EC_AV1_PREFILT_DUMP` shows the same 32x32- + // quadrant mismatch already present *before* either decoder's + // loop filter runs (898/1024 px, rows 32-63 cols 32-63 of a + // 64x64 luma plane, frame index 2 zero-based / this decoder's + // 3rd frame) -- this is a `predict_compound_intermediate`/ + // `combine_compound` reconstruction defect, not a deblock + // interaction. DRL/assign_compound_mv/dist_wtd_comp_weight_assign + // stay cross-checked bit-for-bit against libaom decodemv.c/ + // reconinter.c (r16). Root cause still not isolated within this + // arithmetic; refuse by name rather than ship a non-pixel-exact + // compound blend. Ceiling: r13/r14's MC plumbing above this line + // stays -- only the plain-average reconstruct is masked off + // again. Upgrade: bisect predict_compound_intermediate itself + // (subpel filter taps / rounding) against the pinned fixture's + // 3rd frame, quadrant rows 32-63 cols 32-63. + return Err(unsupported( + "a COMPOUND_REFERENCE block using the plain/distance-weighted \ + average blend (comp_group_idx == 0) -- proven non-pixel-exact \ + against a real aomenc stream (lane-av1comp r16, see \ + av1comp-r16-compound-mismatch.obu)", + )); + #[allow(unreachable_code)] + let (fwd_offset, bck_offset, compound_idx) = if !skip_mode && enable_jnt_comp { + let idx_ctx = get_comp_index_context( + neighbours, + at, + side, + order_hint_bits, + order_hint, + ref_order_hints[(ref0 - LAST_FRAME) as usize], + ref_order_hints[(ref1 - LAST_FRAME) as usize], + ); + let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]); + if idx == 1 { + (8, 8, 1u8) } else { - // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting - // at 1): read at most two more `drl_mode` bits, one per stack - // entry past the second, stopping at the first `0`. - // `drl_ctx[idx]` is the context between `entries[idx]` and - // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is - // exactly the pair this index is choosing between. - 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) + let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign( + order_hint_bits, + order_hint, + ref_order_hints[(ref0 - LAST_FRAME) as usize], + ref_order_hints[(ref1 - LAST_FRAME) as usize], + ); + (fwd, bck, 0u8) } + } else { + (8, 8, 1u8) }; - (mv, false) - }; - // spec `get_ref_filter_type`: a neighbour's own filter only feeds - // this block's switchable_interp context when that neighbour coded - // the SAME reference frame this block is about to read -- a - // different-ref neighbour reads as "no neighbour" ([3, 3], the - // sentinel `Neighbours::new` already seeds unset slots with), - // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME - // block next to a LAST_FRAME one inherits that neighbour's filter - // choice into its own context, corrupting the symbol it reads. - let above_filter_ctx = if neighbours.above_ref[c] == ref_frame { - neighbours.above_filter[c] - } else { - [3, 3] - }; - let left_filter_ctx = if neighbours.left_ref[r] == ref_frame { - neighbours.left_filter[r] - } else { - [3, 3] - }; - let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( - dec, - cdfs, - interp_fixed, - enable_dual_filter, - is_globalmv, - above_filter_ctx, - left_filter_ctx, - ); - block_filter = resolved_filter; - globalmv_for_lf = is_globalmv; - if std::env::var_os("EC_AV1_TRACE").is_some() { - eprintln!( - "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side} ref={ref_frame} filter={:?}", - skip as u8, mv.0, mv.1, block_filter + compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx)); + + let mut inter0_y = vec![0i32; side * side]; + mc::predict_compound_intermediate( + &py0.data, + py0.width, + py0.true_width, + py0.true_height, + mv_to_q4(px, mv0.1, true), + mv_to_q4(py, mv0.0, true), + side, + side, + h_filter, + v_filter, + &mut inter0_y, ); - } - for dr in 0..bw4 { - for dc in 0..bw4 { - grid.set( - mi_row + dr, - mi_col + dc, - MiInfo { - is_inter: true, - ref_frame, - mv, - is_new_mv, - size: bw4, - }, - ); - } - } - mode_for_tx = 0; - - let mut pred_y = vec![0u8; side * side]; - mc::predict_with_filters( - &py_ref.data, - py_ref.width, - py_ref.true_width, - py_ref.true_height, - mv_to_q4(px, mv.1, true), - mv_to_q4(py, mv.0, true), - side, - side, - h_filter, - v_filter, - &mut pred_y, - ); - let mut pred_u = vec![0u8; chroma_side * chroma_side]; - mc::predict_with_filters( - &pu_ref.data, - pu_ref.width, - pu_ref.true_width, - pu_ref.true_height, - mv_to_q4(cpx, mv.1, false), - mv_to_q4(cpy, mv.0, false), - chroma_side, - chroma_side, - h_filter, - v_filter, - &mut pred_u, - ); - let mut pred_v = vec![0u8; chroma_side * chroma_side]; - mc::predict_with_filters( - &pv_ref.data, - pv_ref.width, - pv_ref.true_width, - pv_ref.true_height, - mv_to_q4(cpx, mv.1, false), - mv_to_q4(cpy, mv.0, false), - chroma_side, - chroma_side, - h_filter, - v_filter, - &mut pred_v, - ); - - if skip { - y.reconstruct_mc(px, py, side, &pred_y, &vec![0i32; side * side]); - u.reconstruct_mc( - cpx, - cpy, + let mut inter1_y = vec![0i32; side * side]; + mc::predict_compound_intermediate( + &py1.data, + py1.width, + py1.true_width, + py1.true_height, + mv_to_q4(px, mv1.1, true), + mv_to_q4(py, mv1.0, true), + side, + side, + h_filter, + v_filter, + &mut inter1_y, + ); + let mut pred_y = vec![0u8; side * side]; + mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y); + + let mut inter0_u = vec![0i32; chroma_side * chroma_side]; + mc::predict_compound_intermediate( + &pu0.data, + pu0.width, + pu0.true_width, + pu0.true_height, + mv_to_q4(cpx, mv0.1, false), + mv_to_q4(cpy, mv0.0, false), chroma_side, - &pred_u, - &vec![0i32; chroma_side * chroma_side], + chroma_side, + h_filter, + v_filter, + &mut inter0_u, ); - v.reconstruct_mc( - cpx, - cpy, + let mut inter1_u = vec![0i32; chroma_side * chroma_side]; + mc::predict_compound_intermediate( + &pu1.data, + pu1.width, + pu1.true_width, + pu1.true_height, + mv_to_q4(cpx, mv1.1, false), + mv_to_q4(cpy, mv1.0, false), chroma_side, - &pred_v, - &vec![0i32; chroma_side * chroma_side], + chroma_side, + h_filter, + v_filter, + &mut inter1_u, ); - luma_grid = vec![0i32; side * side]; - u_grid = vec![0i32; chroma_side * chroma_side]; - v_grid = vec![0i32; chroma_side * chroma_side]; + let mut pred_u = vec![0u8; chroma_side * chroma_side]; + mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u); + + let mut inter0_v = vec![0i32; chroma_side * chroma_side]; + mc::predict_compound_intermediate( + &pv0.data, + pv0.width, + pv0.true_width, + pv0.true_height, + mv_to_q4(cpx, mv0.1, false), + mv_to_q4(cpy, mv0.0, false), + chroma_side, + chroma_side, + h_filter, + v_filter, + &mut inter0_v, + ); + let mut inter1_v = vec![0i32; chroma_side * chroma_side]; + mc::predict_compound_intermediate( + &pv1.data, + pv1.width, + pv1.true_width, + pv1.true_height, + mv_to_q4(cpx, mv1.1, false), + mv_to_q4(cpy, mv1.0, false), + chroma_side, + chroma_side, + h_filter, + v_filter, + &mut inter1_v, + ); + let mut pred_v = vec![0u8; chroma_side * chroma_side]; + mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &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(at, side); + luma_grid = read_inter_plane( + dec, + cdfs, + luma_set_inter, + scan_luma, + 0, + around[0], + mode_for_tx, + y, + px, + py, + side, + base_q_idx, + &pred_y, + )?; + u_grid = read_inter_plane( + dec, + cdfs, + chroma_set, + scan_chroma, + 1, + around[1], + mode_for_tx, + u, + cpx, + cpy, + chroma_side, + base_q_idx, + &pred_u, + )?; + v_grid = read_inter_plane( + dec, + cdfs, + chroma_set, + scan_chroma, + 2, + around[2], + mode_for_tx, + v, + cpx, + cpy, + chroma_side, + base_q_idx, + &pred_v, + )?; + } } else { - let around = neighbours.around(at, side); - luma_grid = read_inter_plane( + let ref_frame = + read_single_ref(dec, cdfs, neighbours.above_ref[c], neighbours.left_ref[r]); + ref_frame_for_lf = ref_frame; + // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own + // stacked defects (lf_level ref/mode-delta forwarding, the + // switchable_interp ref-frame ctx gate, and a film-grain synthesis + // gap that looked like a GOLDEN MC bug by survivor bias -- see the + // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs` + // 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 (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); + let bw4 = side / 4; + // spec 7.10.2.8: only reached when the frame header set + // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None` + // otherwise) -- `cur_offset_0` is this query block's own resolved + // `ref_frame`'s distance from the current frame (spec 7.9.3), + // recomputed per block since different blocks pick different refs. + let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs { + field: t.field, + cur_offset_0: crate::motion_field::get_relative_dist( + t.order_hint_bits, + t.order_hint, + t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], + ), + allow_high_precision_mv, + }); + let stack = find_mv_stack_with_sign_bias( + grid, + mi_row, + mi_col, + bw4, + bw4, + ref_frame, + mi_cols as usize, + mi_rows as usize, + sign_bias_table, + tpl, + ); + let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; + let mut is_globalmv = false; + let (mv, is_new_mv) = if !not_new { + // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0): + // read at most two `drl_mode` bits, one per stack entry past the + // first, stopping at the first `0`. The chosen index selects + // which stack entry `read_mv`'s base predictor comes from + // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`) + // -- entry 0 (`stack.pred_mv`) only when the loop never advances. + let mut idx = 0usize; + while idx < 2 && stack.entries.len() > idx + 1 { + if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 { + break; + } + idx += 1; + } + let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); + ( + read_mv( + dec, + &mut cdfs.mv_comp, + &mut cdfs.mv_joint, + base_mv, + allow_high_precision_mv, + ), + true, + ) + } else { + let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1; + is_globalmv = !not_zero; + let mv = if !not_zero { + // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1) under the + // `GmType::IDENTITY` this crate's `decode_stream` requires of + // every inter frame's `LAST_FRAME` entry (any other warp + // model is refused before the tile decoder is ever called). + (0, 0) + } else { + let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0; + if nearest { + stack.nearest_mv + } else { + // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting + // at 1): read at most two more `drl_mode` bits, one per stack + // entry past the second, stopping at the first `0`. + // `drl_ctx[idx]` is the context between `entries[idx]` and + // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is + // exactly the pair this index is choosing between. + 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) + }; + // spec `get_ref_filter_type`: a neighbour's own filter only feeds + // this block's switchable_interp context when that neighbour coded + // the SAME reference frame this block is about to read -- a + // different-ref neighbour reads as "no neighbour" ([3, 3], the + // sentinel `Neighbours::new` already seeds unset slots with), + // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME + // block next to a LAST_FRAME one inherits that neighbour's filter + // choice into its own context, corrupting the symbol it reads. + let above_filter_ctx = if neighbours.above_ref[c] == ref_frame { + neighbours.above_filter[c] + } else { + [3, 3] + }; + let left_filter_ctx = if neighbours.left_ref[r] == ref_frame { + neighbours.left_filter[r] + } else { + [3, 3] + }; + let (h_filter, v_filter, resolved_filter) = resolve_interp_filter( dec, cdfs, - luma_set_inter, - scan_luma, - 0, - around[0], - mode_for_tx, - y, - px, - py, + interp_fixed, + enable_dual_filter, + is_globalmv, + above_filter_ctx, + left_filter_ctx, + ); + block_filter = resolved_filter; + globalmv_for_lf = is_globalmv; + if std::env::var_os("EC_AV1_TRACE").is_some() { + eprintln!( + "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side} ref={ref_frame} filter={:?}", + skip as u8, mv.0, mv.1, block_filter + ); + } + for dr in 0..bw4 { + for dc in 0..bw4 { + grid.set( + mi_row + dr, + mi_col + dc, + MiInfo { + is_inter: true, + ref_frame, + ref_frame1: None, + mv1: None, + mv, + is_new_mv, + size: bw4, + }, + ); + } + } + mode_for_tx = 0; + + let mut pred_y = vec![0u8; side * side]; + mc::predict_with_filters( + &py_ref.data, + py_ref.width, + py_ref.true_width, + py_ref.true_height, + mv_to_q4(px, mv.1, true), + mv_to_q4(py, mv.0, true), side, - base_q_idx, - &pred_y, - )?; - u_grid = read_inter_plane( - dec, - cdfs, - chroma_set, - scan_chroma, - 1, - around[1], - mode_for_tx, - u, - cpx, - cpy, + side, + h_filter, + v_filter, + &mut pred_y, + ); + let mut pred_u = vec![0u8; chroma_side * chroma_side]; + mc::predict_with_filters( + &pu_ref.data, + pu_ref.width, + pu_ref.true_width, + pu_ref.true_height, + mv_to_q4(cpx, mv.1, false), + mv_to_q4(cpy, mv.0, false), chroma_side, - base_q_idx, - &pred_u, - )?; - v_grid = read_inter_plane( - dec, - cdfs, - chroma_set, - scan_chroma, - 2, - around[2], - mode_for_tx, - v, - cpx, - cpy, chroma_side, - base_q_idx, - &pred_v, - )?; + h_filter, + v_filter, + &mut pred_u, + ); + let mut pred_v = vec![0u8; chroma_side * chroma_side]; + mc::predict_with_filters( + &pv_ref.data, + pv_ref.width, + pv_ref.true_width, + pv_ref.true_height, + mv_to_q4(cpx, mv.1, false), + mv_to_q4(cpy, mv.0, false), + chroma_side, + chroma_side, + h_filter, + v_filter, + &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(at, side); + luma_grid = read_inter_plane( + dec, + cdfs, + luma_set_inter, + scan_luma, + 0, + around[0], + mode_for_tx, + y, + px, + py, + side, + base_q_idx, + &pred_y, + )?; + u_grid = read_inter_plane( + dec, + cdfs, + chroma_set, + scan_chroma, + 1, + around[1], + mode_for_tx, + u, + cpx, + cpy, + chroma_side, + base_q_idx, + &pred_u, + )?; + v_grid = read_inter_plane( + dec, + cdfs, + chroma_set, + scan_chroma, + 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]); @@ -4158,6 +4996,8 @@ fn decode_inter_block( MiInfo { is_inter: false, ref_frame: -1, + ref_frame1: None, + mv1: None, mv: (0, 0), is_new_mv: false, size: side / 4, @@ -4274,7 +5114,10 @@ fn decode_inter_block( } } neighbours.record(at, side, mode_for_tx, &[luma_grid, u_grid, v_grid]); - neighbours.record_inter(at, side, skip, is_inter, ref_frame_for_lf, block_filter); + neighbours.record_inter(at, side, skip, is_inter, ref_frame_for_lf, block_filter, skip_mode); + if let Some((ref1, group_idx, idx)) = compound_ctx { + neighbours.record_compound_ctx(at, side, ref1, group_idx, idx); + } neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip); neighbours.fill_lf_grid( (r * (SUB / MI), c * (SUB / MI)), @@ -4321,12 +5164,37 @@ fn decode_inter_block8( ref_y: &PlaneBuf, ref_u: &PlaneBuf, ref_v: &PlaneBuf, + other_refs: &RefSlots, base_q_idx: u8, scan8: &[u16], scan4: &[u16], prev_leaf: Option<((usize, usize), bool, bool)>, allow_high_precision_mv: bool, -) -> Result<(bool, bool)> { + // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path + // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no + // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s + // context uses that same approximation. + reference_select: bool, + enable_masked_compound: bool, + enable_jnt_comp: bool, + order_hint_bits: u32, + order_hint: u32, + ref_order_hints: [u32; 7], + // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this + // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either, + // so its `skip_mode` context reuses the same [`SUB`]-grid + // `above_skip_mode[c]`/`left_skip_mode[r]` the enclosing 16x16 slot + // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation + // just above). + skip_mode_present: bool, + skip_mode_frame: [u8; 2], + // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a + // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16 + // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own + // `compound_ctx` local, just handed back instead of applied here (this + // fn's `neighbours` recording happens once for the whole straddling + // 16x16 block, after every leaf). +) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>)> { 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; @@ -4350,16 +5218,344 @@ fn decode_inter_block8( left_inter = pinter; } } + let skip_mode_ctx = + usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]); + let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1; + if skip_mode { + SKIP_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + let skip_ctx = usize::from(above_skip) + usize::from(left_skip); - let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1; + let skip = skip_mode || 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 is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; let mode_for_tx; let (luma_grid, u_grid, v_grid); + let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None; if is_inter { + if reference_select || skip_mode { + let above_nbr = has_above.then(|| NeighbourRef { + is_inter: above_inter, + ref0: if above_inter { LAST_FRAME } else { 0 }, + ref1: None, + uni: false, + }); + let left_nbr = has_left.then(|| NeighbourRef { + is_inter: left_inter, + ref0: if left_inter { LAST_FRAME } else { 0 }, + ref1: None, + uni: false, + }); + if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) { + let (ref0, ref1) = if skip_mode { + (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8) + } else { + read_compound_ref_frames( + dec, + cdfs, + above_nbr, + left_nbr, + if has_above && above_inter { + LAST_FRAME + } else { + -1 + }, + if has_left && left_inter { + LAST_FRAME + } else { + -1 + }, + ) + }; + let (mi_row, mi_col) = leaf_mi; + // lane-av1comp: this leaf path has neither a real sign-bias + // table nor `tpl_frame` (see this function's own doc on the + // coarse `LAST_FRAME`-or-intra neighbour approximation + // already in force above), matching the plain `find_mv_stack` + // (no bias, no tpl) the leaf's single-ref arm below already + // uses. + let comp_stack = crate::mvstack::find_mv_stack_compound( + grid, + mi_row, + mi_col, + 2, + 2, + (ref0, ref1), + mi_cols as usize, + mi_rows as usize, + &NO_SIGN_BIAS, + None, + ); + let compound_mode = if skip_mode { + 0 // NEAREST_NEARESTMV, forced -- no mode symbol read + } else { + read_inter_compound_mode( + dec, + cdfs, + comp_stack.new_mv_ctx, + comp_stack.ref_mv_ctx, + ) + }; + let (mv0, mv1) = assign_compound_mv( + dec, + cdfs, + &comp_stack, + compound_mode, + allow_high_precision_mv, + ); + + // spec 5.11.25: same gating [`decode_inter_block`]'s own + // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid + // slot -- the only granularity `Neighbours`' comp_group_idx/ + // compound_idx arrays track. + let group_ctx = get_comp_group_idx_context(neighbours, outer_at, SIDE); + let comp_group_idx = if !skip_mode + && enable_masked_compound + && is_any_masked_compound_used_here(SIDE) + { + dec.symbol(&mut cdfs.comp_group_idx[group_ctx]) + } else { + 0 + }; + if comp_group_idx == 1 { + return Err(unsupported( + "a masked COMPOUND_REFERENCE 8x8 leaf (comp_group_idx == 1, wedge/\ + diffwtd) -- this decoder's compound blend is the plain distance-\ + weighted/simple-average combine only, lane-av1comp", + )); + } + // corner-cut (lane-av1comp r16/r17): same non-pixel-exact + // plain-average reconstruction defect as the 16x16 leaf's + // own mask above (r17: falsified as loop-filter-shaped, + // isolated to predict_compound_intermediate/combine_compound + // itself) -- see that comment. + return Err(unsupported( + "a COMPOUND_REFERENCE 8x8 leaf using the plain/distance-weighted \ + average blend (comp_group_idx == 0) -- proven non-pixel-exact \ + against a real aomenc stream (lane-av1comp r16, see \ + av1comp-r16-compound-mismatch.obu)", + )); + #[allow(unreachable_code)] + let (fwd_offset, bck_offset, compound_idx) = if !skip_mode && enable_jnt_comp { + let idx_ctx = get_comp_index_context( + neighbours, + outer_at, + SIDE, + order_hint_bits, + order_hint, + ref_order_hints[(ref0 - LAST_FRAME) as usize], + ref_order_hints[(ref1 - LAST_FRAME) as usize], + ); + let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]); + if idx == 1 { + (8, 8, 1u8) + } else { + let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign( + order_hint_bits, + order_hint, + ref_order_hints[(ref0 - LAST_FRAME) as usize], + ref_order_hints[(ref1 - LAST_FRAME) as usize], + ); + (fwd, bck, 0u8) + } + } else { + (8, 8, 1u8) + }; + compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx)); + + 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)?; + + for dr in 0..2 { + for dc in 0..2 { + grid.set( + mi_row + dr, + mi_col + dc, + MiInfo { + is_inter: true, + ref_frame: ref0, + ref_frame1: Some(ref1), + mv1: Some(mv1), + mv: mv0, + is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7), + size: 2, + }, + ); + } + } + mode_for_tx = 0; + + // lane-av1comp corner-cut, matching this leaf's single-ref + // arm below (`mc::predict`'s own fixed-Regular default): + // `decode_inter_block8` never resolves a switchable filter, + // so both compound taps use `Regular` too. + use mc::InterpFilterKind::Regular; + let mut inter0_y = vec![0i32; SIDE * SIDE]; + mc::predict_compound_intermediate( + &py0.data, + py0.width, + py0.true_width, + py0.true_height, + mv_to_q4(px, mv0.1, true), + mv_to_q4(py, mv0.0, true), + SIDE, + SIDE, + Regular, + Regular, + &mut inter0_y, + ); + let mut inter1_y = vec![0i32; SIDE * SIDE]; + mc::predict_compound_intermediate( + &py1.data, + py1.width, + py1.true_width, + py1.true_height, + mv_to_q4(px, mv1.1, true), + mv_to_q4(py, mv1.0, true), + SIDE, + SIDE, + Regular, + Regular, + &mut inter1_y, + ); + let mut pred_y = vec![0u8; SIDE * SIDE]; + mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y); + + let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; + mc::predict_compound_intermediate( + &pu0.data, + pu0.width, + pu0.true_width, + pu0.true_height, + mv_to_q4(cpx, mv0.1, false), + mv_to_q4(cpy, mv0.0, false), + CHROMA_SIDE, + CHROMA_SIDE, + Regular, + Regular, + &mut inter0_u, + ); + let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; + mc::predict_compound_intermediate( + &pu1.data, + pu1.width, + pu1.true_width, + pu1.true_height, + mv_to_q4(cpx, mv1.1, false), + mv_to_q4(cpy, mv1.0, false), + CHROMA_SIDE, + CHROMA_SIDE, + Regular, + Regular, + &mut inter1_u, + ); + let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE]; + mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u); + + let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; + mc::predict_compound_intermediate( + &pv0.data, + pv0.width, + pv0.true_width, + pv0.true_height, + mv_to_q4(cpx, mv0.1, false), + mv_to_q4(cpy, mv0.0, false), + CHROMA_SIDE, + CHROMA_SIDE, + Regular, + Regular, + &mut inter0_v, + ); + let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE]; + mc::predict_compound_intermediate( + &pv1.data, + pv1.width, + pv1.true_width, + pv1.true_height, + mv_to_q4(cpx, mv1.1, false), + mv_to_q4(cpy, mv1.0, false), + CHROMA_SIDE, + CHROMA_SIDE, + Regular, + Regular, + &mut inter1_v, + ); + let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE]; + mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &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, + )?; + } + return Ok((skip, is_inter, skip_mode, compound_ctx8)); + } + } 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]); @@ -4436,6 +5632,8 @@ fn decode_inter_block8( MiInfo { is_inter: true, ref_frame: LAST_FRAME, + ref_frame1: None, + mv1: None, mv, is_new_mv, size: 2, @@ -4580,6 +5778,8 @@ fn decode_inter_block8( MiInfo { is_inter: false, ref_frame: -1, + ref_frame1: None, + mv1: None, mv: (0, 0), is_new_mv: false, size: 2, @@ -4695,7 +5895,7 @@ fn decode_inter_block8( } neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]); neighbours.fill_lf_grid(leaf_mi, 2, 8, if is_inter { LAST_FRAME } else { 0 }); - Ok((skip, is_inter)) + Ok((skip, is_inter, skip_mode, compound_ctx8)) } /// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes, @@ -4725,6 +5925,7 @@ pub fn decode_inter_frame_tile( allow_high_precision_mv: bool, interp_fixed: Option, enable_dual_filter: bool, + reference_select: bool, ) -> Result { decode_inter_frame_tile_with_cdfs( data, @@ -4746,6 +5947,11 @@ pub fn decode_inter_frame_tile( 0, [0; 7], None, + reference_select, + false, + false, + false, + [0; 2], ) .map(|(picture, _, _)| picture) } @@ -4780,6 +5986,17 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( order_hint: u32, ref_order_hints: [u32; 7], tpl_field: Option<&crate::motion_field::TplField>, + // lane-av1comp: this frame header's own `reference_select` bit, threaded + // to every `decode_inter_block`/`decode_inter_block8` call below. + reference_select: bool, + // lane-av1comp: `seq_params`' own compound-blend enable bits. + enable_masked_compound: bool, + enable_jnt_comp: bool, + // lane-av1comp round 14: this frame header's own `skip_mode_present`/ + // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/ + // `decode_inter_block8` call below. + skip_mode_present: bool, + skip_mode_frame: [u8; 2], ) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> { let tpl_frame = tpl_field.map(|field| TplFrameArgs { field, @@ -4976,6 +6193,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( interp_fixed, enable_dual_filter, tpl_frame.as_ref(), + reference_select, + enable_masked_compound, + enable_jnt_comp, + order_hint_bits, + order_hint, + ref_order_hints, + skip_mode_present, + skip_mode_frame, )?; } PARTITION_SPLIT => { @@ -5034,6 +6259,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( interp_fixed, enable_dual_filter, tpl_frame.as_ref(), + reference_select, + enable_masked_compound, + enable_jnt_comp, + order_hint_bits, + order_hint, + ref_order_hints, + skip_mode_present, + skip_mode_frame, )?; } else { let ctx16 = neighbours.partition_ctx(at16, SUB); @@ -5054,6 +6287,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols) .collect(); let mut prev_leaf: Option<((usize, usize), bool, bool)> = None; + let mut last_compound_ctx: Option<(i8, i8, u8, u8)> = None; + let mut last_skip_mode = false; 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); @@ -5063,28 +6298,42 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( "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, - allow_high_precision_mv, - )?; + let (skip, is_inter, skip_mode_leaf, compound_ctx8) = + 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, + &ref_slots, + base_q_idx, + &scan8, + &scan4, + prev_leaf, + allow_high_precision_mv, + reference_select, + enable_masked_compound, + enable_jnt_comp, + order_hint_bits, + order_hint, + ref_order_hints, + skip_mode_present, + skip_mode_frame, + )?; prev_leaf = Some((leaf_mi, skip, is_inter)); + last_skip_mode = skip_mode_leaf; + if compound_ctx8.is_some() { + last_compound_ctx = compound_ctx8; + } } if let Some((_, skip, is_inter)) = prev_leaf { // corner-cut: `decode_inter_block8`'s @@ -5105,7 +6354,21 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( is_inter, if is_inter { LAST_FRAME } else { -1 }, [3, 3], + last_skip_mode, ); + if let Some((ref0, ref1, group_idx, idx)) = last_compound_ctx { + neighbours.record_inter( + at16, + SUB, + skip, + is_inter, + ref0, + [3, 3], + last_skip_mode, + ); + neighbours + .record_compound_ctx(at16, SUB, ref1, group_idx, idx); + } } } } @@ -5118,7 +6381,10 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } } + let r17_idx = R17_DUMP_FRAME_IDX.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + r17_dump("EC_AV1_PREFILT_DUMP", &y, &u, &v, r17_idx); apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours); + r17_dump("EC_AV1_POSTFILT_DUMP", &y, &u, &v, r17_idx); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); let motion_field = build_motion_field( @@ -5177,6 +6443,57 @@ mod tests { // this decoder's one target, and the round-trip test below is against // that path with real quantised residual, not a synthetic all-DC frame. + /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly + /// when both references sit on the same temporal side -- the three + /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN) + /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`, + /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads + /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set, + /// not just the three enumerated syntax pairs). + #[test] + fn is_uni_comp_ref_matches_forward_backward_sides() { + assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME)); + assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME)); + assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME)); + assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME)); + assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME)); + assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME)); + } + + /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1` + /// with the real second reference (lane-av1comp round 12: previously + /// always cleared to `None` by `record_inter`, so the next block's own + /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it + /// -- could never see a real compound neighbour). + #[test] + fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() { + let mut n = Neighbours::new(4, 4, 16, 16); + n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false); + assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1"); + n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1); + assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME)); + assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME)); + assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap())); + } + + /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's + /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`): + /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]` + /// -- a few corner and interior points, not the whole 6x6 grid. + #[test] + fn compound_mode_ctx_map_matches_libaom_corners() { + assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0); + assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1); + assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1); + assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4); + assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5); + assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7); + // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and + // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are + // exactly the ranges `find_mv_stack_compound` produces. + assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7); + } + #[test] fn a_frame_with_no_mode_info_grid_is_refused() { assert!( @@ -5604,6 +6921,7 @@ mod tests { false, Some(mc::InterpFilterKind::Regular), false, + false, ) .unwrap(); assert_eq!( @@ -5659,6 +6977,8 @@ mod tests { let neighbour = |mv| MiInfo { is_inter: true, ref_frame: LAST_FRAME, + ref_frame1: None, + mv1: None, mv, is_new_mv: false, size: 1, @@ -5783,6 +7103,14 @@ mod tests { Some(mc::InterpFilterKind::Regular), false, None, + false, + false, + false, + 0, + 0, + [0; 7], + false, + [0; 2], ) .unwrap(); @@ -5876,6 +7204,7 @@ mod tests { false, Some(mc::InterpFilterKind::Regular), false, + false, ) .unwrap(); assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg"); diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 0c5c66f5..33d4607d 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -2612,6 +2612,8 @@ pub(crate) fn encode_inter_frame( Some(info) => MiInfo { is_inter: true, ref_frame: LAST_FRAME, + ref_frame1: None, + mv1: None, mv: info.mv, is_new_mv: matches!(info.mode, InterMode::NewMv), size: 8, @@ -2623,6 +2625,8 @@ pub(crate) fn encode_inter_frame( None => MiInfo { is_inter: false, ref_frame: -1, + ref_frame1: None, + mv1: None, mv: (0, 0), is_new_mv: false, size: 8, @@ -2700,6 +2704,8 @@ pub(crate) fn encode_inter_frame( Some(info) => MiInfo { is_inter: true, ref_frame: LAST_FRAME, + ref_frame1: None, + mv1: None, mv: info.mv, is_new_mv: matches!(info.mode, InterMode::NewMv), size: 4, @@ -2707,6 +2713,8 @@ pub(crate) fn encode_inter_frame( None => MiInfo { is_inter: false, ref_frame: -1, + ref_frame1: None, + mv1: None, mv: (0, 0), is_new_mv: false, size: 4, @@ -2750,6 +2758,8 @@ pub(crate) fn encode_inter_frame( Some(info) => MiInfo { is_inter: true, ref_frame: LAST_FRAME, + ref_frame1: None, + mv1: None, mv: info.mv, is_new_mv: matches!( info.mode, @@ -2760,6 +2770,8 @@ pub(crate) fn encode_inter_frame( None => MiInfo { is_inter: false, ref_frame: -1, + ref_frame1: None, + mv1: None, mv: (0, 0), is_new_mv: false, size: 2, diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index e749bf2a..6a3136b5 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -15,6 +15,7 @@ pub mod bits; pub mod cdf; mod cdf_state; +mod compound; pub mod decode; pub mod encode; pub mod encoder; diff --git a/crates/ec-av1/src/mc.rs b/crates/ec-av1/src/mc.rs index 2c6821a2..ed3965da 100644 --- a/crates/ec-av1/src/mc.rs +++ b/crates/ec-av1/src/mc.rs @@ -411,6 +411,154 @@ pub fn predict_with_filters( crate::encode::stage_add(1, stage_t.elapsed()); } +/// `InterRound1` for a compound ref (spec 7.11.3.2's `isCompound` branch, +/// `COMPOUND_ROUND1_BITS` in libaom's `convolve.h`): 4 bits shallower than +/// [`INTER_ROUND_1`] so the vertical pass lands in the `CONV_BUF` domain +/// (still above 8-bit pixel range) instead of a finished sample -- +/// `predict_compound_intermediate` below stops there and leaves the final +/// clip to whichever combine step (simple/distance-weighted average, or a +/// future masked blend) runs on the pair of intermediates. +const INTER_ROUND_1_COMPOUND: u32 = 7; + +/// `InterPostRound` (spec 7.11.3.2): `2 * FILTER_BITS - (InterRound0 + +/// InterRound1)` with the *compound* `InterRound1` above -- `2*7 - (3+7) == +/// 4`. [`combine_compound`] folds this together with `DIST_PRECISION_BITS` +/// (below) into one final shift. +const INTER_POST_ROUND: u32 = 4; + +/// `DIST_PRECISION_BITS` (spec 7.11.3.15 / libaom `enums.h`): the two +/// weights [`combine_compound`] takes always sum to `1 << 4 == 16`, whether +/// they are the simple-average split (8/8) or a distance-weighted split +/// from [`crate::compound::dist_wtd_comp_weight_assign`]. +const DIST_PRECISION_BITS: u32 = 4; + +/// [`predict_with_filters`]'s compound counterpart: same two-pass separable +/// filter, but the vertical pass rounds by [`INTER_ROUND_1_COMPOUND`] +/// instead of [`INTER_ROUND_1`] and is never clipped to a pixel -- the +/// `CONV_BUF` intermediate domain spec 7.11.3.2 keeps a compound block's two +/// per-reference predictions in until [`combine_compound`] blends them. +/// `dst` receives one `i32` per sample, row-major, same shape as +/// [`predict_with_filters`]'s `u8` `dst`. +/// +/// # Panics +/// Panics when `dst` is not `block_w * block_h` long, or the reference is +/// empty. +#[allow(clippy::too_many_arguments)] +pub fn predict_compound_intermediate( + reference: &[u8], + stride: usize, + true_width: usize, + true_height: usize, + x_q4: i32, + y_q4: i32, + block_w: usize, + block_h: usize, + h_kind: InterpFilterKind, + v_kind: InterpFilterKind, + dst: &mut [i32], +) { + assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); + assert!(!reference.is_empty(), "a reference plane has samples"); + + let x0 = x_q4.div_euclid(16); + let xfrac = x_q4.rem_euclid(16) as usize; + let y0 = y_q4.div_euclid(16); + let yfrac = y_q4.rem_euclid(16) as usize; + + let (h_wide, h_narrow) = h_kind.tables(); + let (v_wide, v_narrow) = v_kind.tables(); + let h_filter = if block_w <= 4 { + &h_narrow[xfrac] + } else { + &h_wide[xfrac] + }; + let v_filter = if block_h <= 4 { + &v_narrow[yfrac] + } else { + &v_wide[yfrac] + }; + + let rows = block_h + 7; + let mut intermediate = vec![0i32; rows * block_w]; + for r in 0..rows { + let y = y0 - 3 + r as i32; + for c in 0..block_w { + let mut sum = 0; + for (t, &tap) in h_filter.iter().enumerate() { + let x = x0 + c as i32 + t as i32 - 3; + sum += tap * sample(reference, stride, true_width, true_height, x, y); + } + intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0); + } + } + + for row in 0..block_h { + for col in 0..block_w { + let mut sum = 0; + for (t, &tap) in v_filter.iter().enumerate() { + sum += tap * intermediate[(row + t) * block_w + col]; + } + dst[row * block_w + col] = round2(sum, INTER_ROUND_1_COMPOUND); + } + } +} + +/// Blends two [`predict_compound_intermediate`] outputs into a finished +/// 8-bit block (spec 7.11.3.15's weighted-average combine, the +/// `comp_group_idx == 0` path -- `fwd_weight`/`bck_weight` are either the +/// simple-average split `(8, 8)` or [`crate::compound::dist_wtd_comp_weight_assign`]'s +/// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound +/// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this +/// function does not cover -- decode.rs still refuses those by name. +pub fn combine_compound( + pred0: &[i32], + pred1: &[i32], + fwd_weight: i32, + bck_weight: i32, + dst: &mut [u8], +) { + assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block"); + assert_eq!(dst.len(), pred0.len(), "the destination is the block"); + for i in 0..dst.len() { + let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight; + dst[i] = round2(sum, INTER_POST_ROUND + DIST_PRECISION_BITS).clamp(0, 255) as u8; + } +} + +/// Whole-pel identity case: [`predict_compound_intermediate`]'s two-pass +/// filter reduces to `16 * source_sample` exactly (the fraction-0 row is a +/// single `128` tap both passes, and `128*128 == 1 << 14`, `14 - 7 == 7 == +/// INTER_ROUND_1_COMPOUND`, so the extra `2^4` of gain the compound path +/// keeps over [`predict`]'s 11-bit round survives untouched) -- +/// [`combine_compound`] then divides that back out exactly with an 8/8 +/// simple-average weight split, so a compound block whose two references +/// (and MVs) happen to coincide reproduces the plain source sample, not an +/// off-by-one from double rounding. +#[test] +fn compound_intermediate_whole_pel_identity_round_trips_through_combine() { + let reference = vec![100u8; 16 * 16]; + let mut pred0 = vec![0i32; 16]; + predict_compound_intermediate( + &reference, + 16, + 16, + 16, + 0, + 0, + 4, + 4, + InterpFilterKind::Regular, + InterpFilterKind::Regular, + &mut pred0, + ); + assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}"); + + let pred1 = pred0.clone(); + let mut dst = vec![0u8; 16]; + combine_compound(&pred0, &pred1, 8, 8, &mut dst); + assert!(dst.iter().all(|&v| v == 100), "{dst:?}"); +} + #[cfg(test)] mod tests { use super::{InterpFilterKind, predict, predict_with_filter}; diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index a9bf3e55..e418167e 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -121,8 +121,22 @@ pub struct MiInfo { /// The single reference frame this unit's MV points into. Ignored (and /// the unit contributes no candidate) when `is_inter` is `false`. pub ref_frame: i8, + /// The unit's *second* reference frame when it was coded compound + /// (spec `RefFrames[1]`), `None` for a single-reference/intra unit -- + /// lane-av1comp: today's callers (single-ref decode/encode) never set + /// this, so it exists only so [`MiGrid`] can carry compound state once + /// `read_ref_frames` (spec 5.11.25) lands; nothing reads it yet, and + /// [`find_mv_stack`]'s scan still matches candidates on `ref_frame` + /// alone (its own compound dual-ref scan is unported -- see the ledger). + pub ref_frame1: Option, /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units. pub mv: (i32, i32), + /// The unit's second motion vector, matching `ref_frame1` (spec + /// `Mvs[1]`) — `Some` only for a compound-coded unit, `None` otherwise. + /// lane-av1comp step 4: exists so the compound mvstack scan below can + /// read a compound neighbour's second MV; no caller sets it yet (same + /// unwired state `ref_frame1` landed in for r3). + pub mv1: Option<(i32, i32)>, /// Whether this unit's own mode was `NEWMV` (spec's /// `have_newmv_in_inter_mode`, compound modes excluded since this module /// has no compound candidates). Feeds `NewMvContext` (7.10.2.8): a @@ -977,6 +991,680 @@ pub fn find_mv_stack_with_sign_bias( } } +/// One neighbour's vote for a compound-reference (spec `RefFrame[0]` *and* +/// `RefFrame[1]` both active) candidate: two full motion vectors and the +/// combined weight — spec 7.10.2's compound half of `add_ref_mv_candidate` +/// (libaom `mvref_common.c`, the `is_compound` branch of `scan_row_mbmi`/ +/// `scan_col_mbmi`/`scan_blk_mbmi`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CompoundStackEntry { + /// The candidate's vote for `RefFrame[0]`'s motion vector. + pub mv0: (i32, i32), + /// The candidate's vote for `RefFrame[1]`'s motion vector. + pub mv1: (i32, i32), + /// The summed weight of every neighbour cell that voted for this pair. + pub weight: u32, +} + +/// [`find_mv_stack_compound`]'s result — [`MvStack`]'s shape, doubled for +/// the reference pair. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CompoundMvStack { + /// The candidates, highest weight first. + pub entries: Vec, + /// `RefStackMv[0]` for both refs, or `((0,0),(0,0))` when the stack is + /// empty. + pub nearest_mv: ((i32, i32), (i32, i32)), + /// `RefStackMv[1]` for both refs, or `((0,0),(0,0))` when the stack has + /// fewer than two entries. + pub near_mv: ((i32, i32), (i32, i32)), + /// The predictor pair a `NEW_NEWMV`-family block's MV differences are + /// coded against. + pub pred_mv: ((i32, i32), (i32, i32)), + /// Context for the compound `new_mv` symbol. + pub new_mv_ctx: usize, + /// Context for the compound `ref_mv` symbol. + pub ref_mv_ctx: usize, + /// Context for the compound `zero_mv` symbol. + pub zero_mv_ctx: usize, + /// Context for each `drl_mode` symbol between consecutive stack entries. + pub drl_ctx: Vec, +} + +/// [`add_candidate`], doubled: dedupes on the whole `(mv0, mv1)` pair. +fn add_compound_candidate( + candidates: &mut Vec, + mv0: (i32, i32), + mv1: (i32, i32), + weight: u32, +) { + if let Some(entry) = candidates.iter_mut().find(|e| e.mv0 == mv0 && e.mv1 == mv1) { + entry.weight += weight; + } else { + candidates.push(CompoundStackEntry { mv0, mv1, weight }); + } +} + +/// The compound row scan (spec 7.10.2.2's compound branch, libaom +/// `scan_row_mbmi`'s `is_compound` path): [`scan_row`]'s weight/run-length +/// math unchanged, but a candidate only votes when *both* its `ref_frame` +/// and `ref_frame1` equal the query's pair exactly, in that order — a +/// compound pair is always encoded forward-then-backward +/// (`RefFrame[0]`/`RefFrame[1]`), so unlike [`process_single_ref_mv_candidate`]'s +/// extension pass, no sign-bias flip ever applies to an exact-pair scan +/// match (libaom's own `scan_row_mbmi` compound branch doesn't flip either). +#[allow(clippy::too_many_arguments)] +fn scan_row_compound( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bw4: usize, + row_offset: isize, + max_row_offset: isize, + ref_frame: (i8, i8), + candidates: &mut Vec, + newmv_count: &mut u32, + processed_rows: &mut usize, +) -> bool { + let Some(row) = mi_row.checked_add_signed(row_offset) else { + return false; + }; + let col_shift: usize = if row_offset.unsigned_abs() > 1 { 1 } else { 0 }; + let use_step_16 = bw4 >= 16; + let end_mi = bw4.min(16); + let mut found = false; + let mut i = 0usize; + while i < end_mi { + let Some(info) = grid.get(row, mi_col + col_shift + i) else { + i += 1; + continue; + }; + let n4 = info.size; + let mut len = bw4.min(n4); + if use_step_16 { + len = len.max(4); + } else if row_offset.unsigned_abs() > 1 { + len = len.max(2); + } + let mut weight = ROW_COL_WEIGHT_FLOOR; + if bw4 <= n4 { + let inc = ((-max_row_offset + row_offset + 1) as usize).min(n4); + weight = weight.max(inc as u32); + *processed_rows = (inc as isize - row_offset - 1).max(0) as usize; + } + if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 == Some(ref_frame.1) { + found = true; + add_compound_candidate( + candidates, + info.mv, + info.mv1.unwrap_or((0, 0)), + len as u32 * weight, + ); + *newmv_count += u32::from(info.is_new_mv); + } + i += len.max(1); + } + found +} + +/// The compound col scan (spec 7.10.2.3's compound branch): [`scan_row_compound`], +/// transposed — mirrors [`scan_col`]/[`scan_row`]'s own relationship. +#[allow(clippy::too_many_arguments)] +fn scan_col_compound( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bh4: usize, + col_offset: isize, + max_col_offset: isize, + ref_frame: (i8, i8), + candidates: &mut Vec, + newmv_count: &mut u32, + processed_cols: &mut usize, +) -> bool { + let Some(col) = mi_col.checked_add_signed(col_offset) else { + return false; + }; + let row_shift: usize = if col_offset.unsigned_abs() > 1 { 1 } else { 0 }; + let use_step_16 = bh4 >= 16; + let end_mi = bh4.min(16); + let mut found = false; + let mut i = 0usize; + while i < end_mi { + let Some(info) = grid.get(mi_row + row_shift + i, col) else { + i += 1; + continue; + }; + let n4 = info.size; + let mut len = bh4.min(n4); + if use_step_16 { + len = len.max(4); + } else if col_offset.unsigned_abs() > 1 { + len = len.max(2); + } + let mut weight = ROW_COL_WEIGHT_FLOOR; + if bh4 <= n4 { + let inc = ((-max_col_offset + col_offset + 1) as usize).min(n4); + weight = weight.max(inc as u32); + *processed_cols = (inc as isize - col_offset - 1).max(0) as usize; + } + if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 == Some(ref_frame.1) { + found = true; + add_compound_candidate( + candidates, + info.mv, + info.mv1.unwrap_or((0, 0)), + len as u32 * weight, + ); + *newmv_count += u32::from(info.is_new_mv); + } + i += len.max(1); + } + found +} + +/// The compound top-right probe ([`scan_top_right`]'s pair-matched twin). +fn scan_top_right_compound( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bw4: usize, + ref_frame: (i8, i8), + candidates: &mut Vec, + newmv_count: &mut u32, +) -> bool { + let Some(row) = mi_row.checked_sub(1) else { + return false; + }; + let col = mi_col + bw4; + if let Some(info) = grid.get(row, col) + && info.is_inter + && info.ref_frame == ref_frame.0 + && info.ref_frame1 == Some(ref_frame.1) + { + add_compound_candidate( + candidates, + info.mv, + info.mv1.unwrap_or((0, 0)), + CORNER_WEIGHT, + ); + *newmv_count += u32::from(info.is_new_mv); + return true; + } + false +} + +/// The compound diagonal corner probe ([`scan_corner`]'s pair-matched twin). +fn scan_corner_compound( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + ref_frame: (i8, i8), + candidates: &mut Vec, + newmv_count: &mut u32, +) -> bool { + let (Some(row), Some(col)) = (mi_row.checked_sub(1), mi_col.checked_sub(1)) else { + return false; + }; + if let Some(info) = grid.get(row, col) + && info.is_inter + && info.ref_frame == ref_frame.0 + && info.ref_frame1 == Some(ref_frame.1) + { + add_compound_candidate( + candidates, + info.mv, + info.mv1.unwrap_or((0, 0)), + CORNER_WEIGHT, + ); + *newmv_count += u32::from(info.is_new_mv); + return true; + } + false +} + +/// Per-side unresolved-MV accumulator [`process_compound_ref_mv_candidate`] +/// fills across every candidate the compound extension pass walks: up to two +/// motion vectors that matched `ref_frame.0`/`.1` exactly (`ref_id`), and up +/// to two more borrowed from a differently-referenced but still-inter +/// neighbour under the sign-bias flip [`process_single_ref_mv_candidate`] +/// also applies (`ref_diff`). Ported from libaom's `setup_ref_mv_list` +/// (`mvref_common.c`, `process_compound_ref_mv_candidate` ~line 380-430 plus +/// the combine step at ~696-762): the extension walk fills this once across +/// the whole row-then-col scan, and [`combine_compound_candidates`] below +/// zips the two independently-filled sides back into full pair candidates. +#[derive(Default)] +struct CompoundRefLists { + ref_id: [Vec<(i32, i32)>; 2], + ref_diff: [Vec<(i32, i32)>; 2], +} + +/// libaom's `process_compound_ref_mv_candidate`: folds one already-coded +/// neighbour's up to two reference slots into `lists`, split by which side +/// of `ref_frame` (the query block's own compound pair) each slot's own +/// reference frame matches — an exact match goes to that side's `ref_id` +/// list, anything else (still inter, wrong reference) goes to `ref_diff` +/// under the usual sign-bias flip. +fn process_compound_ref_mv_candidate( + candidate: &MiInfo, + ref_frame: (i8, i8), + sign_bias_table: &SignBiasTable, + lists: &mut CompoundRefLists, +) { + if !candidate.is_inter { + return; + } + let slots = [ + Some((candidate.ref_frame, candidate.mv)), + candidate + .ref_frame1 + .map(|rf1| (rf1, candidate.mv1.unwrap_or((0, 0)))), + ]; + for (candidate_ref, candidate_mv) in slots.into_iter().flatten() { + for (i, side_ref) in [ref_frame.0, ref_frame.1].into_iter().enumerate() { + if candidate_ref == side_ref { + if lists.ref_id[i].len() < 2 { + lists.ref_id[i].push(candidate_mv); + } + } else if lists.ref_diff[i].len() < 2 { + let mut mv = candidate_mv; + if sign_bias(sign_bias_table, candidate_ref) != sign_bias(sign_bias_table, side_ref) + { + mv = (-mv.0, -mv.1); + } + lists.ref_diff[i].push(mv); + } + } + } +} + +/// libaom's combine step (`setup_ref_mv_list`, `mvref_common.c` ~696-720): +/// zips each side's `ref_id` (exact matches) then `ref_diff` (borrowed, +/// sign-flipped) entries, position-wise and independently per side, into up +/// to two full `(mv0, mv1)` pair candidates — missing slots default to +/// `(0, 0)`, matching libaom's zero-initialized `combined_mvs`. +fn combine_compound_candidates(lists: &CompoundRefLists) -> [((i32, i32), (i32, i32)); 2] { + let side_slots = |side: usize| -> [(i32, i32); 2] { + let merged: Vec<(i32, i32)> = lists.ref_id[side] + .iter() + .chain(lists.ref_diff[side].iter()) + .take(2) + .copied() + .collect(); + std::array::from_fn(|i| merged.get(i).copied().unwrap_or((0, 0))) + }; + let side0 = side_slots(0); + let side1 = side_slots(1); + [(side0[0], side1[0]), (side0[1], side1[1])] +} + +/// [`find_mv_stack_with_sign_bias`]'s compound-reference twin (spec +/// 7.10.2's `is_compound` path throughout): builds the reference MV stack +/// for a block predicted against *two* simultaneously-active reference +/// frames (`ref_frame.0`, `ref_frame.1`), keeping every existing +/// single-reference caller of [`find_mv_stack`]/[`find_mv_stack_with_sign_bias`] +/// untouched — this is a new, parallel entry point, not an extension of the +/// single-ref one. Same reduction scope as the single-ref module doc +/// (single tile, square blocks, `IDENTITY` global motion only); the +/// mode-context switch below reuses the identical `(nearest_match, +/// ref_match_count)` derivation the single-ref path uses, since libaom's own +/// switch statement (`mvref_common.c` ~619-643) is ref-count-agnostic — it +/// only ever reads those two counts, regardless of which `MODE_CTX_REF_FRAMES` +/// slot `mode_context` it's indexing. +/// +/// The compound extension combine step (`setup_ref_mv_list`, ~line 700-754) +/// and the temporal `add_tpl_ref_mv` fold-in (~line 341-433) are both exact +/// ports of libaom's real behaviour as of r5 — see the inline comments at +/// each site. +#[allow(clippy::too_many_arguments)] +pub fn find_mv_stack_compound( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + bw4: usize, + bh4: usize, + ref_frame: (i8, i8), + mi_cols: usize, + mi_rows: usize, + sign_bias_table: &SignBiasTable, + tpl: Option, +) -> CompoundMvStack { + let mut candidates: Vec = Vec::new(); + let mut newmv_count = 0u32; + + let row_adj = bh4 < 2 && mi_row % 2 == 1; + let col_adj = bw4 < 2 && mi_col % 2 == 1; + let max_row_offset: isize = if mi_row > 0 { + let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj); + reach.max(-(mi_row as isize)) + } else { + 0 + }; + let max_col_offset: isize = if mi_col > 0 { + let reach = if bw4 < 2 { -4 } else { -6 } + isize::from(col_adj); + reach.max(-(mi_col as isize)) + } else { + 0 + }; + + let mut processed_rows = 0usize; + let mut processed_cols = 0usize; + let found_above = mi_row > 0 + && scan_row_compound( + grid, + mi_row, + mi_col, + bw4, + -1, + max_row_offset, + ref_frame, + &mut candidates, + &mut newmv_count, + &mut processed_rows, + ); + let found_left = mi_col > 0 + && scan_col_compound( + grid, + mi_row, + mi_col, + bh4, + -1, + max_col_offset, + ref_frame, + &mut candidates, + &mut newmv_count, + &mut processed_cols, + ); + let found_top_right = scan_top_right_compound( + grid, + mi_row, + mi_col, + bw4, + ref_frame, + &mut candidates, + &mut newmv_count, + ); + + let row_matched = found_above || found_top_right; + let nearest_match = usize::from(row_matched) + usize::from(found_left); + + for entry in &mut candidates { + entry.weight += REF_CAT_LEVEL; + } + + // Temporal compound candidates (spec 7.10.2.8's compound + // `add_tpl_ref_mv`): the same projected field, read once per side of the + // pair through the existing single-ref [`crate::motion_field::add_tpl_ref_mv`] + // — each side's own `cur_offset` scales the *same* stored candidate to + // that side's reference frame. libaom's real `add_tpl_ref_mv` looks up + // the stored `mfmv0`/`ref_frame_offset` pair exactly once per `(blk_row, + // blk_col)` and, if present, always projects it to *both* sides (the + // lookup itself never fails for one side and succeeds for the other); + // a missing side there is `INVALID_MV`/global-motion zero-fill, never a + // dropped candidate. Ported exactly: each side is read independently and + // a missing side zero-fills rather than vetoing the pair. + let mut zero_mv_ctx = 0usize; + if let Some(CompoundTplArgs { + field, + cur_offset_0, + cur_offset_1, + allow_high_precision_mv, + }) = tpl + { + let mut any_hit = false; + let blk_row_end = bh4.min(16); + let blk_col_end = bw4.min(16); + let step_h = if bh4 >= 16 { 4 } else { 2 }; + let step_w = if bw4 >= 16 { 4 } else { 2 }; + let mut first_sample_missing = true; + let mut first_sample_far = false; + let mut blk_row = 0usize; + while blk_row < blk_row_end { + let mut blk_col = 0usize; + while blk_col < blk_col_end { + let cand0 = crate::motion_field::add_tpl_ref_mv( + field, + mi_row, + mi_col, + blk_row as isize, + blk_col as isize, + cur_offset_0, + allow_high_precision_mv, + ); + let cand1 = crate::motion_field::add_tpl_ref_mv( + field, + mi_row, + mi_col, + blk_row as isize, + blk_col as isize, + cur_offset_1, + allow_high_precision_mv, + ); + if cand0.is_some() || cand1.is_some() { + any_hit = true; + let mv0 = cand0.map_or((0, 0), |c| c.mv); + let mv1 = cand1.map_or((0, 0), |c| c.mv); + if blk_row == 0 && blk_col == 0 { + first_sample_missing = false; + first_sample_far = mv0.0.abs() >= 16 + || mv0.1.abs() >= 16 + || mv1.0.abs() >= 16 + || mv1.1.abs() >= 16; + } + add_compound_candidate(&mut candidates, mv0, mv1, 2); + } + blk_col += step_w; + } + blk_row += step_h; + } + if any_hit { + TMV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + zero_mv_ctx = usize::from(first_sample_missing || first_sample_far); + } + + let mut dummy_newmv_count = 0u32; + let corner_matched = scan_corner_compound( + grid, + mi_row, + mi_col, + ref_frame, + &mut candidates, + &mut dummy_newmv_count, + ); + let mut row_matched_ext = false; + let mut col_matched_ext = false; + for idx in 2..=MVREF_ROW_COLS { + let row_offset = -((idx as isize) * 2) + 1 + isize::from(row_adj); + let col_offset = -((idx as isize) * 2) + 1 + isize::from(col_adj); + if row_offset.unsigned_abs() <= max_row_offset.unsigned_abs() + && row_offset.unsigned_abs() > processed_rows + && scan_row_compound( + grid, + mi_row, + mi_col, + bw4, + row_offset, + max_row_offset, + ref_frame, + &mut candidates, + &mut dummy_newmv_count, + &mut processed_rows, + ) + { + row_matched_ext = true; + } + if col_offset.unsigned_abs() <= max_col_offset.unsigned_abs() + && col_offset.unsigned_abs() > processed_cols + && scan_col_compound( + grid, + mi_row, + mi_col, + bh4, + col_offset, + max_col_offset, + ref_frame, + &mut candidates, + &mut dummy_newmv_count, + &mut processed_cols, + ) + { + col_matched_ext = true; + } + } + let ref_match_count = usize::from(row_matched || corner_matched || row_matched_ext) + + usize::from(found_left || col_matched_ext); + + candidates.sort_by_key(|e| std::cmp::Reverse(e.weight)); + candidates.truncate(MAX_STACK_SIZE); + + // The compound extension pass (libaom's `setup_ref_mv_list`, "Handle + // compound reference frame extension"): gather across the row directly + // above and the column directly left (same `mi_size` reach as the + // single-ref pass), then combine once. + let mi_width = (16usize).min(bw4).min(mi_cols.saturating_sub(mi_col)); + let mi_height = (16usize).min(bh4).min(mi_rows.saturating_sub(mi_row)); + let mi_size = mi_width.min(mi_height); + if candidates.len() < MAX_MV_REF_CANDIDATES { + let mut lists = CompoundRefLists::default(); + if max_row_offset.unsigned_abs() >= 1 { + let mut idx = 0usize; + while idx < mi_size { + let cand = grid.get(mi_row - 1, mi_col + idx); + let step = cand.map_or(1, |c| c.size).max(1); + if let Some(c) = cand { + process_compound_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut lists); + } + idx += step; + } + } + if max_col_offset.unsigned_abs() >= 1 { + let mut idx = 0usize; + while idx < mi_size { + let cand = grid.get(mi_row + idx, mi_col - 1); + let step = cand.map_or(1, |c| c.size).max(1); + if let Some(c) = cand { + process_compound_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut lists); + } + idx += step; + } + } + // libaom's real dedup (`setup_ref_mv_list` ~735-754): when the stack + // already has exactly one entry, compare only `comp_list[0]` against + // it and, on a match, take `comp_list[1]` instead (skip, no weight + // bump) — otherwise append `comp_list[0]` as a brand-new entry. When + // the stack is empty, both `comp_list[0]` and `comp_list[1]` are + // appended unconditionally, with no dedup check at all. + let comp_list = combine_compound_candidates(&lists); + if candidates.len() == 1 { + let (mv0, mv1) = if comp_list[0] == (candidates[0].mv0, candidates[0].mv1) { + comp_list[1] + } else { + comp_list[0] + }; + candidates.push(CompoundStackEntry { + mv0, + mv1, + weight: 2, + }); + } else if candidates.is_empty() { + for (mv0, mv1) in comp_list { + candidates.push(CompoundStackEntry { + mv0, + mv1, + weight: 2, + }); + } + } + } + + let clamp = |mv| clamp_mv_ref(mv, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows); + let nearest_mv = candidates + .first() + .map_or(((0, 0), (0, 0)), |e| (clamp(e.mv0), clamp(e.mv1))); + let near_mv = candidates + .get(1) + .map_or(((0, 0), (0, 0)), |e| (clamp(e.mv0), clamp(e.mv1))); + let pred_mv = if candidates.is_empty() { + ((0, 0), (0, 0)) + } else { + nearest_mv + }; + + let new_mv_ctx = match nearest_match { + 0 => usize::from(ref_match_count >= 1), + 1 => { + if newmv_count > 0 { + 2 + } else { + 3 + } + } + _ => { + if newmv_count >= 1 { + 4 + } else { + 5 + } + } + }; + let ref_mv_ctx = match nearest_match { + 0 => match ref_match_count { + 0 => 0, + 1 => 1, + _ => 2, + }, + 1 => { + if ref_match_count >= 2 { + 4 + } else { + 3 + } + } + _ => 5, + }; + + let drl_ctx = candidates + .windows(2) + .map(|w| { + let (a, b) = (w[0].weight, w[1].weight); + if a >= REF_CAT_LEVEL && b >= REF_CAT_LEVEL { + 0 + } else if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL { + 1 + } else { + 2 + } + }) + .collect(); + + CompoundMvStack { + entries: candidates, + nearest_mv, + near_mv, + pred_mv, + new_mv_ctx, + ref_mv_ctx, + zero_mv_ctx, + drl_ctx, + } +} + +/// [`find_mv_stack_compound`]'s temporal-MV inputs — [`TplArgs`], doubled: +/// one `cur_offset` per side of the pair (`get_relative_dist(OrderHint, +/// OrderHints[ref_frame.N - LAST_FRAME])`, spec 7.9.3), since a compound +/// query projects the same stored field twice, once per reference. +pub struct CompoundTplArgs<'a> { + /// The current frame's projected temporal motion field. + pub field: &'a crate::motion_field::TplField, + /// `get_relative_dist` for `ref_frame.0`. + pub cur_offset_0: i32, + /// `get_relative_dist` for `ref_frame.1`. + pub cur_offset_1: i32, + /// The frame header's own `allow_high_precision_mv`. + pub allow_high_precision_mv: bool, +} + /// The single-reference context shared by the `single_ref_p1`/`p3`/`p4` /// binary decisions this crate's LAST-only reference chain codes (spec /// 5.11.25; libaom's `av1_get_pred_context_single_ref_p1/p3/p4`, @@ -1070,6 +1758,107 @@ pub(crate) fn single_ref_p6_ctx(above: Option, left: Option) -> usize { ref_ctx(above, left, &[BWDREF_FRAME], &[ALTREF2_FRAME]) } +/// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` vs. `LAST3`/`GOLDEN`, +/// conditioned on a unidirectional pair known to be one of the three +/// `LAST`-anchored ones (lane-av1comp). +pub(crate) fn uni_comp_ref_p1_ctx(above: Option, left: Option) -> usize { + ref_ctx(above, left, &[LAST2_FRAME], &[LAST3_FRAME, GOLDEN_FRAME]) +} + +/// One neighbouring block's reference-frame shape, as +/// [`reference_mode_ctx`]/[`comp_reference_type_ctx`] need it: `None` for an +/// out-of-frame neighbour, `Some(ref0, None)` for an intra or single-ref +/// inter block, `Some(ref0, Some(ref1))` for a compound one. `uni` is +/// `ref1`'s meaning only when compound: whether the pair libaom's +/// `has_uni_comp_refs` would call unidirectional (both refs on the same +/// side of the current frame). +#[derive(Clone, Copy)] +pub(crate) struct NeighbourRef { + pub is_inter: bool, + pub ref0: i8, + pub ref1: Option, + pub uni: bool, +} + +fn is_backward(r: i8) -> bool { + (BWDREF_FRAME..=ALTREF_FRAME).contains(&r) +} + +/// `av1_get_reference_mode_context` (spec 5.11.25's `comp_mode` context, +/// libaom `pred_common.c`): 5 contexts from how many of the above/left +/// neighbours are themselves compound-predicted, and (when neither/one is) +/// whether their single reference is a backward one. +pub(crate) fn reference_mode_ctx(above: Option, left: Option) -> usize { + match (above, left) { + (Some(a), Some(l)) => match (a.ref1.is_some(), l.ref1.is_some()) { + (false, false) => usize::from(is_backward(a.ref0) ^ is_backward(l.ref0)), + (false, true) => 2 + usize::from(is_backward(a.ref0) || !a.is_inter), + (true, false) => 2 + usize::from(is_backward(l.ref0) || !l.is_inter), + (true, true) => 4, + }, + (Some(e), None) | (None, Some(e)) => { + if e.ref1.is_some() { + 3 + } else { + usize::from(is_backward(e.ref0)) + } + } + (None, None) => 1, + } +} + +/// `av1_get_comp_reference_type_context` (spec 5.11.25's +/// `comp_reference_type` context, libaom `pred_common.c`): 5 contexts from +/// whether the above/left neighbours are intra, single-ref, unidirectional +/// compound, or bidirectional compound. +pub(crate) fn comp_reference_type_ctx( + above: Option, + left: Option, +) -> usize { + match (above, left) { + (Some(a), Some(l)) => match (a.is_inter, l.is_inter) { + (false, false) => 2, + (false, true) | (true, false) => { + let inter = if a.is_inter { a } else { l }; + if inter.ref1.is_none() { + 2 + } else { + 1 + 2 * usize::from(inter.uni) + } + } + (true, true) => { + let (a_sg, l_sg) = (a.ref1.is_none(), l.ref1.is_none()); + if a_sg && l_sg { + 1 + 2 * usize::from(!(is_backward(a.ref0) ^ is_backward(l.ref0))) + } else if a_sg || l_sg { + let uni = if a_sg { l.uni } else { a.uni }; + if !uni { + 1 + } else { + 3 + usize::from(!(is_backward(a.ref0) ^ is_backward(l.ref0))) + } + } else if !a.uni && !l.uni { + 0 + } else if !a.uni || !l.uni { + 2 + } else { + 3 + usize::from(!((a.ref0 == BWDREF_FRAME) ^ (l.ref0 == BWDREF_FRAME))) + } + } + }, + (Some(e), None) | (None, Some(e)) => { + if !e.is_inter { + 2 + } else if e.ref1.is_none() { + 2 + } else { + 4 * usize::from(e.uni) + } + } + (None, None) => 2, + } +} + #[cfg(test)] mod tests { use super::*; @@ -1078,6 +1867,8 @@ mod tests { MiInfo { is_inter: true, ref_frame: 1, + ref_frame1: None, + mv1: None, mv, is_new_mv: false, // 1: smaller than every `bw4`/`bh4` these small-grid tests use, @@ -1229,6 +2020,8 @@ mod tests { MiInfo { is_inter: true, ref_frame: 1, + ref_frame1: None, + mv1: None, mv: (4, 4), is_new_mv: true, size: 1, @@ -1307,6 +2100,8 @@ mod tests { MiInfo { is_inter: true, ref_frame: 1, + ref_frame1: None, + mv1: None, mv, is_new_mv: false, size: 8, @@ -1334,6 +2129,8 @@ mod tests { MiInfo { is_inter: false, ref_frame: -1, + ref_frame1: None, + mv1: None, mv: (0, 0), is_new_mv: false, size: 8, @@ -1348,6 +2145,8 @@ mod tests { MiInfo { is_inter: true, ref_frame: 1, + ref_frame1: None, + mv1: None, mv, is_new_mv: false, size: 8, @@ -1425,4 +2224,347 @@ mod tests { assert_eq!(stack.entries.len(), 1); assert_eq!(stack.entries[0].mv, (4, 4)); } + + fn single(ref0: i8) -> NeighbourRef { + NeighbourRef { + is_inter: true, + ref0, + ref1: None, + uni: false, + } + } + fn comp(ref0: i8, ref1: i8, uni: bool) -> NeighbourRef { + NeighbourRef { + is_inter: true, + ref0, + ref1: Some(ref1), + uni, + } + } + fn intra() -> NeighbourRef { + NeighbourRef { + is_inter: false, + ref0: 0, + ref1: None, + uni: false, + } + } + + /// `av1_get_reference_mode_context`, no edges available: libaom's `ctx + /// = 1` fallback. + #[test] + fn reference_mode_ctx_no_edges_is_one() { + assert_eq!(reference_mode_ctx(None, None), 1); + } + + /// Both edges single-ref, same forward/backward-ness: `ctx = 0`; one of + /// each: `ctx = 1` (the XOR in libaom's `ctx = IS_BACKWARD(above) ^ + /// IS_BACKWARD(left)`). + #[test] + fn reference_mode_ctx_single_single() { + assert_eq!( + reference_mode_ctx(Some(single(LAST_FRAME)), Some(single(LAST2_FRAME))), + 0 + ); + assert_eq!( + reference_mode_ctx(Some(single(LAST_FRAME)), Some(single(BWDREF_FRAME))), + 1 + ); + } + + /// One edge compound, the other single forward: libaom's `2 + + /// IS_BACKWARD(above)` collapses to `2` here (forward, inter). + #[test] + fn reference_mode_ctx_single_and_compound() { + assert_eq!( + reference_mode_ctx( + Some(single(LAST_FRAME)), + Some(comp(LAST_FRAME, LAST2_FRAME, true)) + ), + 2 + ); + assert_eq!( + reference_mode_ctx( + Some(comp(LAST_FRAME, LAST2_FRAME, true)), + Some(single(LAST_FRAME)) + ), + 2 + ); + } + + /// Both edges compound: libaom's fixed `ctx = 4`. + #[test] + fn reference_mode_ctx_compound_compound_is_four() { + assert_eq!( + reference_mode_ctx( + Some(comp(LAST_FRAME, LAST2_FRAME, true)), + Some(comp(BWDREF_FRAME, ALTREF_FRAME, true)) + ), + 4 + ); + } + + /// `av1_get_comp_reference_type_context`, no edges: libaom's `ctx = 2` + /// fallback. + #[test] + fn comp_reference_type_ctx_no_edges_is_two() { + assert_eq!(comp_reference_type_ctx(None, None), 2); + } + + /// Both edges intra: libaom's `ctx = 2`. + #[test] + fn comp_reference_type_ctx_intra_intra_is_two() { + assert_eq!(comp_reference_type_ctx(Some(intra()), Some(intra())), 2); + } + + /// Both edges single/single: forward-vs-backward split doubles the same + /// way `single_ref_p1`'s own XOR does (libaom's `1 + 2 * !(a ^ l)`). + #[test] + fn comp_reference_type_ctx_single_single() { + assert_eq!( + comp_reference_type_ctx(Some(single(LAST_FRAME)), Some(single(LAST2_FRAME))), + 3 + ); + assert_eq!( + comp_reference_type_ctx(Some(single(LAST_FRAME)), Some(single(BWDREF_FRAME))), + 1 + ); + } + + /// Both edges bidirectional compound: libaom's `ctx = 0`. + #[test] + fn comp_reference_type_ctx_bidir_bidir_is_zero() { + assert_eq!( + comp_reference_type_ctx( + Some(comp(LAST_FRAME, BWDREF_FRAME, false)), + Some(comp(LAST2_FRAME, ALTREF_FRAME, false)) + ), + 0 + ); + } + + /// Both edges unidirectional compound: libaom's `3 + !(a==BWDREF ^ + /// l==BWDREF)`. + #[test] + fn comp_reference_type_ctx_unidir_unidir() { + assert_eq!( + comp_reference_type_ctx( + Some(comp(LAST_FRAME, LAST2_FRAME, true)), + Some(comp(LAST_FRAME, LAST3_FRAME, true)) + ), + 4 + ); + assert_eq!( + comp_reference_type_ctx( + Some(comp(LAST_FRAME, LAST2_FRAME, true)), + Some(comp(BWDREF_FRAME, ALTREF_FRAME, true)) + ), + 3 + ); + } + + /// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` beats `LAST3`/ + /// `GOLDEN` in the vote, context 2 (libaom's `<` branch reversed -- + /// fewer `a`s than `b`s is context 0, matching [`ref_ctx`]'s shared + /// convention). + #[test] + fn uni_comp_ref_p1_ctx_matches_ref_ctx_shape() { + assert_eq!(uni_comp_ref_p1_ctx(Some(LAST2_FRAME), None), 2); + assert_eq!(uni_comp_ref_p1_ctx(Some(LAST3_FRAME), None), 0); + assert_eq!(uni_comp_ref_p1_ctx(None, None), 1); + } + + // --- lane-av1comp step 4: compound mvstack (find_mv_stack_compound) --- + + const COMP_PAIR: (i8, i8) = (LAST_FRAME, ALTREF_FRAME); + + fn comp_inter(mv0: (i32, i32), mv1: (i32, i32)) -> MiInfo { + MiInfo { + is_inter: true, + ref_frame: COMP_PAIR.0, + ref_frame1: Some(COMP_PAIR.1), + mv: mv0, + mv1: Some(mv1), + is_new_mv: false, + size: 1, + } + } + + #[test] + fn compound_scan_only_matches_the_exact_pair() { + let mut grid = MiGrid::new(8, 8); + // Same-side single-ref neighbour (LAST only) must not vote. + grid.set(1, 2, inter((4, 4))); + // Wrong second ref (GOLDEN, not ALTREF) must not vote either. + grid.set( + 1, + 3, + MiInfo { + is_inter: true, + ref_frame: LAST_FRAME, + ref_frame1: Some(GOLDEN_FRAME), + mv: (9, 9), + mv1: Some((9, 9)), + is_new_mv: false, + size: 1, + }, + ); + // Exact pair match. + let (mv0, mv1) = ((2, 2), (-6, 3)); + grid.set(2, 1, comp_inter(mv0, mv1)); + + let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None); + + // The exact-pair immediate scan lands one boosted entry; the + // compound extension pass (short stack, len < MAX_MV_REF_CANDIDATES) + // separately tops it up with a low-weight combo built from the two + // near-miss neighbours it's allowed to gather over regardless of + // reference frame -- a real second entry, not spurious. + assert_eq!(stack.entries.len(), 2); + assert_eq!(stack.entries[0].mv0, mv0); + assert_eq!(stack.entries[0].mv1, mv1); + assert_eq!(stack.entries[0].weight, 2 + REF_CAT_LEVEL); + assert_eq!(stack.nearest_mv, (mv0, mv1)); + } + + #[test] + fn compound_dedupes_same_pair_and_sums_weight() { + let mut grid = MiGrid::new(8, 8); + let (mv0, mv1) = ((4, 4), (-4, -4)); + // Block at (2, 2), 2x2 mi units: above spans cols 2..4, left rows 2..4. + grid.set(1, 2, comp_inter(mv0, mv1)); + grid.set(1, 3, comp_inter(mv0, mv1)); + grid.set(2, 1, comp_inter(mv0, mv1)); + grid.set(3, 1, comp_inter(mv0, mv1)); + + let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None); + + // Exact libaom `is_dup` port: with exactly one entry already in the + // stack (the four identical-pair neighbours deduped by the + // immediate-scan pass), the extension combine step compares only + // `comp_list[0]` against that entry -- a match here, since both are + // built from the same identical-pair neighbours -- so it takes + // `comp_list[1]` (the *second* ref_id slot, still the same (mv0, + // mv1) pair) as a brand-new stack entry rather than folding weight + // into the existing one. Two entries, same pair, not merged. + assert_eq!(stack.entries.len(), 2); + assert_eq!(stack.entries[0].mv0, mv0); + assert_eq!(stack.entries[0].mv1, mv1); + // 2 above + 2 left cells, weight 2 each (size:1 floor), plus the + // REF_CAT_LEVEL boost every immediate-scan entry gets. + assert_eq!(stack.entries[0].weight, 8 + REF_CAT_LEVEL); + assert_eq!(stack.entries[1].mv0, mv0); + assert_eq!(stack.entries[1].mv1, mv1); + assert_eq!(stack.entries[1].weight, 2); + } + + #[test] + fn compound_two_distinct_pairs_sort_by_weight() { + let mut grid = MiGrid::new(8, 8); + let above = ((4, 4), (1, 1)); + let left = ((8, 8), (2, 2)); + grid.set(2, 3, comp_inter(above.0, above.1)); + grid.set(2, 4, comp_inter(above.0, above.1)); + grid.set(3, 2, comp_inter(left.0, left.1)); + grid.set(4, 2, comp_inter(left.0, left.1)); + grid.set(5, 2, comp_inter(left.0, left.1)); + + let stack = find_mv_stack_compound(&grid, 3, 3, 2, 3, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None); + + assert_eq!(stack.entries.len(), 2); + assert_eq!(stack.entries[0].mv0, left.0); + assert_eq!(stack.entries[0].mv1, left.1); + assert_eq!(stack.entries[1].mv0, above.0); + assert_eq!(stack.entries[1].mv1, above.1); + assert_eq!(stack.nearest_mv, left); + assert_eq!(stack.near_mv, above); + } + + #[test] + fn combine_compound_candidates_zips_ref_id_then_ref_diff_per_side() { + let mut lists = CompoundRefLists::default(); + lists.ref_id[0].push((1, 1)); + lists.ref_diff[0].push((2, 2)); + lists.ref_id[1].push((3, 3)); + // side 1 has only one entry -> comp_idx 1 falls back to ref_diff. + lists.ref_diff[1].push((4, 4)); + + let combined = combine_compound_candidates(&lists); + assert_eq!(combined[0], ((1, 1), (3, 3))); + assert_eq!(combined[1], ((2, 2), (4, 4))); + } + + #[test] + fn process_compound_ref_mv_candidate_splits_exact_vs_borrowed() { + let mut lists = CompoundRefLists::default(); + // Exact match on side 0 (LAST_FRAME), wrong ref on side 1 -> borrowed + // into ref_diff[1] with no sign flip (NO_SIGN_BIAS). + let candidate = MiInfo { + is_inter: true, + ref_frame: LAST_FRAME, + ref_frame1: None, + mv: (5, 5), + mv1: None, + is_new_mv: false, + size: 1, + }; + process_compound_ref_mv_candidate(&candidate, COMP_PAIR, &NO_SIGN_BIAS, &mut lists); + assert_eq!(lists.ref_id[0], vec![(5, 5)]); + assert_eq!(lists.ref_diff[1], vec![(5, 5)]); + assert!(lists.ref_id[1].is_empty()); + assert!(lists.ref_diff[0].is_empty()); + } + + #[test] + fn compound_extension_pass_tops_up_a_short_stack() { + // No exact-pair neighbour at all, but a LAST-only neighbour above and + // an ALTREF-only neighbour left: the extension pass should combine + // them into one topped-up candidate rather than leaving the stack + // empty. + let mut grid = MiGrid::new(8, 8); + grid.set( + 1, + 2, + MiInfo { + is_inter: true, + ref_frame: LAST_FRAME, + ref_frame1: None, + mv: (7, 7), + mv1: None, + is_new_mv: false, + size: 8, + }, + ); + grid.set( + 2, + 1, + MiInfo { + is_inter: true, + ref_frame: ALTREF_FRAME, + ref_frame1: None, + mv: (-3, -3), + mv1: None, + is_new_mv: false, + size: 8, + }, + ); + + let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None); + + // The combine step (libaom's real "Handle compound reference frame + // extension") zips each side's ref_id-then-ref_diff lists + // independently, producing *two* distinct combos here (the exact + // match and the borrowed one land on opposite sides for each combo + // index) — both get added, `MAX_MV_REF_CANDIDATES` (2) is exactly + // this stack's cap. + assert_eq!(stack.entries.len(), 2); + assert_eq!(stack.entries[0].weight, 2); + // combo 0: side 0's own exact ref_id match, side 1's borrowed one. + assert_eq!(stack.entries[0].mv0, (7, 7)); + assert_eq!(stack.entries[0].mv1, (-3, -3)); + // combo 1: the mirror -- side 0's borrowed entry, side 1's own exact + // ref_id match. + assert_eq!(stack.entries[1].mv0, (-3, -3)); + assert_eq!(stack.entries[1].mv1, (7, 7)); + } } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index cd0ebb38..d1eb085d 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -79,6 +79,43 @@ pub fn decode_stream(data: &[u8]) -> Result> { let obu_offset = pos; pos += obu.total_size; + if let ObuKind::FrameHeader(header) = &obu.kind { + // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this + // OBU only names a DPB slot to output again -- the coded-frame + // count and the shown-picture count are different things (a + // hidden altref's own `Frame` OBU below is never pushed to + // `pictures` on its own; it is only pushed here, later, when a + // `show_existing_frame` header names its slot). Before r15 this + // arm didn't exist at all: every `ObuKind::Frame` was pushed + // unconditionally regardless of `show_frame`, so a hidden altref + // was emitted (wrongly, in decode order) and its real + // `show_existing_frame` output was silently dropped. + let slot = header.frame_to_show_map_idx as usize; + let picture = ref_slots[slot].clone().ok_or_else(|| { + Error::unsupported( + "AV1 decode_stream", + "a show_existing_frame header naming an empty reference slot", + ) + })?; + for i in 0..NUM_REF_FRAMES { + if header.refresh_frame_flags & (1 << i) != 0 { + cdf_slots[i] = cdf_slots[slot].clone(); + ref_slots[i] = Some(picture.clone()); + motion_field_slots[i] = motion_field_slots[slot].clone(); + order_hint_slots[i] = order_hint_slots[slot]; + } + } + let output = if header.film_grain.apply_grain { + let mc_identity = parser + .sequence_header() + .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); + crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity) + } else { + picture + }; + pictures.push(output); + continue; + } let ObuKind::Frame(header, tiles) = obu.kind else { continue; }; @@ -178,21 +215,14 @@ pub fn decode_stream(data: &[u8]) -> Result> { "an inter frame whose global motion for a single-reference frame is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)", )); } - // `decode_inter_block`'s `single_ref_p*` chain codes only - // `SINGLE_REFERENCE` blocks (never reads `comp_mode`) -- a frame - // whose `reference_select` header bit lets any block choose - // `COMPOUND_REFERENCE` would desync at the first block that reads - // a `comp_mode` symbol this decoder never consumes. `skip_mode` - // (spec 5.9.22) is provably unreachable here as a consequence: its - // own `skip_mode_params()` only sets `skip_mode_present` when - // `reference_select` is set, so refusing `reference_select` refuses - // `skip_mode` too, without needing a second check. - if header.reference_select { - return Err(Error::unsupported( - "AV1 decode_stream", - "a frame with reference_select set (this decoder never reads comp_mode / codes only single-reference blocks)", - )); - } + // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read + // `comp_mode` per block whenever this frame's own `reference_select` + // header bit is set (spec 5.11.25), and refuse by name the blocks + // that pick `COMPOUND_REFERENCE` -- two-reference motion + // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22) + // is wired at the block level too (forced NEAREST_NEARESTMV compound + // of `skip_mode_frame`, plain average blend), so the old blanket + // `skip_mode_present` refusal is gone. // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names // which tile's end-of-tile adapted CDFs become the frame's own; this // decoder only ever decodes tile 0 (`tiles.first()` above), so a @@ -218,6 +248,13 @@ pub fn decode_stream(data: &[u8]) -> Result> { let enable_edge_filter = parser .sequence_header() .is_some_and(|seq| seq.enable_intra_edge_filter); + // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits. + let enable_masked_compound = parser + .sequence_header() + .is_some_and(|seq| seq.enable_masked_compound); + let enable_jnt_comp = parser + .sequence_header() + .is_some_and(|seq| seq.enable_jnt_comp); let interp_fixed = match header.interpolation_filter { ec_av1_syntax::InterpolationFilter::Switchable => None, fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)), @@ -337,6 +374,11 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.order_hint, ref_order_hints, tpl_field.as_ref(), + header.reference_select, + enable_masked_compound, + enable_jnt_comp, + header.skip_mode_present, + header.skip_mode_frame, )? }; // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's @@ -382,15 +424,17 @@ pub fn decode_stream(data: &[u8]) -> Result> { order_hint_slots[i] = header.order_hint; } } - let output = if header.film_grain.apply_grain { - let mc_identity = parser - .sequence_header() - .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); - crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity) - } else { - picture - }; - pictures.push(output); + if header.show_frame { + let output = if header.film_grain.apply_grain { + let mc_identity = parser + .sequence_header() + .is_some_and(|seq| seq.color_config.matrix_coefficients == 0); + crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity) + } else { + picture + }; + pictures.push(output); + } } Ok(pictures) } @@ -513,6 +557,22 @@ mod tests { use std::io::Write; use std::process::{Command, Stdio}; + /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`, + /// `skip_mode`/compound) all read a process-global atomic counter delta + /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to + /// prove a real block picked the feature under test, not just that a + /// header bit was set. Under `cargo test`'s default parallel run, a + /// SIBLING test's own decode bumps the same global counter mid-gate -- + /// a false "fired" reading pixel-compares an attempt the gate would + /// otherwise `continue` past, on top of genuine defects that path may + /// still have. Serialising every counter-delta gate behind this one + /// mutex makes firing detection honest again (matches the existing + /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`). + static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> { + GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner()) + } + fn have_ffmpeg() -> bool { Command::new("ffmpeg") .arg("-version") @@ -2239,6 +2299,7 @@ mod tests { frame_count: usize, attempts: u32, ) { + let _gate_lock = lock_gate_counters(); if !have_ffmpeg() { eprintln!("SKIP {gate_name}: no ffmpeg"); return; @@ -2400,6 +2461,365 @@ mod tests { ); } + /// lane-av1comp: proves `reference_select`/`comp_mode` are actually read + /// off a real bitstream rather than only unit-tested in isolation -- + /// `--auto-alt-ref=1 --lag-in-frames=16` gives aomenc a backward + /// reference to pick `COMPOUND_REFERENCE` with, `--enable-order-hint=1` + /// is required for it to ever consider compound at all. Three + /// acceptable outcomes: (a) a stream where `reference_select` never + /// actually drove a block to `COMPOUND_REFERENCE` decodes bit-exact end + /// to end (proving the per-block `comp_mode` read did not desync the + /// single-ref blocks around it); (b) a stream that does fire compound + /// is refused by name with [`decode::comp_mode_hits`] having advanced + /// (proving `comp_mode`/`read_compound_ref_frames` consumed the right + /// symbols before refusing, rather than desyncing and refusing for an + /// unrelated reason) -- masked/wedge compound (`comp_group_idx == 1`) + /// and a partition below 16x16 (a real, separately tracked capability + /// gap) are the two refusal arms this can still legitimately name; (c) + /// r13 wired plain `COMPOUND_AVERAGE` MC for real, so as of r15 a + /// stream that fires compound may also decode fully -- accepted only + /// when every output frame is pixel-exact against ffmpeg. + #[test] + fn a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly() { + const NAME: &str = "a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (64usize, 64usize, 20usize); + let mut refusals = Vec::new(); + let mut never_fired = 0u32; + for attempt in 0..60u32 { + let seed = 42 + attempt % 40; + let duration = frame_count as f64 / 25.0; + let source = + format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-order-hint=1", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::comp_mode_hits(); + match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + let fired = decode::comp_mode_hits() > before; + assert!( + msg.contains("unsupported"), + "{NAME} failed outright (seed {seed}): {msg}" + ); + if fired { + // `comp_mode` firing does not stop the block walk -- + // a later, unrelated block in the same tile can + // still hit any other named refusal this decoder + // carries. A partition below 16x16 is a real, open + // capability gap tracked on its own (not a + // COMPOUND_REFERENCE defect); accept it here too + // rather than fail a compound-specific gate on a + // partition-search coincidence. + assert!( + msg.contains("COMPOUND_REFERENCE") || msg.contains("a partition"), + "{NAME}: comp_mode fired (seed {seed}) but the refusal \ + was for something else: {msg}" + ); + let advanced = decode::comp_mode_hits() - before; + eprintln!( + "{NAME} FIRING seed {seed}: comp_mode hits advanced by \ + {advanced}, refused by name as expected: {msg}" + ); + return; + } + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + Ok(frames) => { + if decode::comp_mode_hits() == before { + never_fired += 1; + continue; + } + // Outcome (c): plain COMPOUND_AVERAGE decoded fully -- + // non-negotiable pixel exactness, no tolerance. + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); + } + eprintln!( + "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \ + fully and pixel-exact", + decode::comp_mode_hits() - before + ); + return; + } + } + } + eprintln!( + "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \ + block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \ + reached comp_mode:\n{}", + refusals.join("\n") + ); + } + + /// lane-av1comp round 14's decisive gate for `skip_mode`: same + /// pin-on-mismatch pattern as [`a_real_aomenc_single_ref_gate`], proving + /// [`decode::skip_mode_hits`] actually advanced (a real block picked + /// `skip_mode`, not just that the frame header bit was set) and that the + /// resulting forced-compound `NEAREST_NEARESTMV` decode is still + /// pixel-exact against ffmpeg. `--auto-alt-ref=1 --lag-in-frames=16 + /// --enable-fwd-kf=0` (backward references) plus + /// `--enable-ref-frame-mvs=0` (unimplemented temporal MV projection, + /// same as every other gate here) is aomenc's own requirement for + /// `skip_mode_present` to ever be considered at all (spec 5.9.22 needs + /// both a forward and a backward reference candidate). + #[test] + fn a_real_aomenc_stream_with_compound_references_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_compound_references_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (64usize, 64usize, 24usize); + let mut refusals = Vec::new(); + let mut never_fired = 0u32; + for attempt in 0..80u32 { + let seed = 42 + attempt % 40; + let duration = frame_count as f64 / 25.0; + let source = + format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::skip_mode_hits(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + Ok(frames) => frames, + }; + if decode::skip_mode_hits() == before { + never_fired += 1; + continue; + } + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if mismatched { + if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); + } + eprintln!( + "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}", + decode::skip_mode_hits() - before + ); + return; + } + eprintln!( + "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \ + other attempt hit a named refusal:\n{}", + refusals.join("\n") + ); + } + /// `LAST2_FRAME`/`LAST3_FRAME` are just older slots in the same forward /// reference-buffer ring `LAST_FRAME`/`GOLDEN_FRAME` already prove -- /// dropping the golden gate's `--max-reference-frames=3 @@ -2503,6 +2923,7 @@ mod tests { /// count as a real pass rather than a `never_fired` skip. fn a_real_aomenc_temporal_mv_gate(seed_base: u32, attempts: u32) { let gate_name = "a_real_aomenc_temporal_mv_gate"; + let _gate_lock = lock_gate_counters(); if !have_ffmpeg() { eprintln!("SKIP {gate_name}: no ffmpeg"); return; @@ -2669,6 +3090,22 @@ mod tests { a_real_aomenc_temporal_mv_gate(42, 40); } + /// r17 bisect scratch: decode a pinned stream exactly once, so + /// `decode::r17_dump`'s frame index (a process-wide counter) lines up + /// with `aomdec`'s own per-frame `EC_AV1_PREFILT_DUMP`/ + /// `EC_AV1_POSTFILT_DUMP` numbering. Remove with the rest of the r17 + /// scaffolding. + #[test] + #[ignore] + fn scratch_decode_pinned_stream_once() { + let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path"); + let stream = std::fs::read(&path).expect("read pinned stream"); + match decode_stream(&stream) { + Ok(frames) => eprintln!("OK: {} frames", frames.len()), + Err(e) => eprintln!("ERR: {e}"), + } + } + /// scratch: decode a pinned stream end to end and report where/why it /// refuses, plus `non_last_ref_hits` progression. #[test] diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 0698a0a8..b5250457 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -2434,6 +2434,8 @@ pub fn sb_coeff_inter_frame_tile( MiInfo { is_inter: true, ref_frame: LAST_FRAME, + ref_frame1: None, + mv1: None, mv, is_new_mv, size: 8, @@ -2450,6 +2452,8 @@ pub fn sb_coeff_inter_frame_tile( MiInfo { is_inter: true, ref_frame: LAST_FRAME, + ref_frame1: None, + mv1: None, mv, is_new_mv, size: 8, @@ -2477,6 +2481,8 @@ pub fn sb_coeff_inter_frame_tile( MiInfo { is_inter: false, ref_frame: -1, + ref_frame1: None, + mv1: None, mv: (0, 0), is_new_mv: false, size: 8, @@ -2615,6 +2621,8 @@ fn write_inter_frame_leaf( MiInfo { is_inter: true, ref_frame: LAST_FRAME, + ref_frame1: None, + mv1: None, mv, is_new_mv, size: SUB_MI as usize, @@ -2642,6 +2650,8 @@ fn write_inter_frame_leaf( MiInfo { is_inter: false, ref_frame: -1, + ref_frame1: None, + mv1: None, mv: (0, 0), is_new_mv: false, size: SUB_MI as usize, @@ -2803,6 +2813,8 @@ fn write_inter_frame_leaf8( MiInfo { is_inter: true, ref_frame: LAST_FRAME, + ref_frame1: None, + mv1: None, mv, is_new_mv, size: 2, @@ -2830,6 +2842,8 @@ fn write_inter_frame_leaf8( MiInfo { is_inter: false, ref_frame: -1, + ref_frame1: None, + mv1: None, mv: (0, 0), is_new_mv: false, size: 2, @@ -5082,6 +5096,8 @@ mod tests { MiInfo { is_inter: true, ref_frame: 1, + ref_frame1: None, + mv1: None, mv, is_new_mv, size: 8,