forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1comp': compound-reference symbol chain, skip_mode decode, show_existing_frame output

Browse files at this commit

0b7c4774e0542d7312a7e8fd575c03cef8538aaaAhmet Kaan GümüşParent: 27fdcbd80caed5
17 rounds. Compound refs read fully (comp_mode through per-side MV assign,
comp_group_idx/compound_idx, DRL) in both block paths; skip_mode decoded
(forced NEAREST_NEARESTMV of the SkipModeFrame pair); show_existing_frame
now outputs the named slot instead of emitting hidden altrefs in decode
order. Compound MC blend is implemented but masked by a named refusal:
a real-stream reconstruction defect (one 32x32 quadrant, pre-deblock,
loop filter cross-checked clean) is pinned with live r17_dump scaffolding
and stays a lane away from unmasking.

10 changed files +3679 -312

crates/ec-av1/src/cdf.rsmodified+115 -3
@@ -1107,9 +1107,36 @@ pub const INTER_TX_TYPE_SET3_8: [u16; 3] = [4167, 32768, 0];
11071107
11081108 // The inter-frame tables below (spec 9.4) support the syntax an inter block
11091109 // needs: whether it is coded as intra at all, which reference frame and
1110-// motion vector it takes when it is not. Compound reference and compound
1111-// prediction are not among them -- this encoder never sets
1112-// `reference_select`, so their CDFs are never read.
1110+// motion vector it takes when it is not. The compound-reference tables
1111+// (`COMP_MODE`/`COMP_REF_TYPE`/`UNI_COMP_REF`/`COMP_REF`/`COMP_BWDREF` above)
1112+// read once a frame's `reference_select` header bit is set (lane-av1comp);
1113+// compound *prediction* itself -- `inter_compound_mode`, compound DRL, the
1114+// mvstack's dual-ref scan, and distance-weighted MC blending -- is not yet
1115+// ported, so a block that actually reads `COMPOUND_REFERENCE` still refuses.
1116+
1117+/// `default_inter_compound_mode_cdf` (entropymode.c): which of the eight
1118+/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`) a compound
1119+/// block takes, indexed by `av1_mode_context_analyzer`'s `comp_ctx` (spec
1120+/// 5.11.24's `compound_mode`, libaom's `read_inter_compound_mode`) --
1121+/// lane-av1comp, symbol read only, not yet wired into MV assignment or MC.
1122+pub const INTER_COMPOUND_MODE: [[u16; 9]; 8] = [
1123+ [7760, 13823, 15808, 17641, 19156, 20666, 26891, 32768, 0],
1124+ [10730, 19452, 21145, 22749, 24039, 25131, 28724, 32768, 0],
1125+ [10664, 20221, 21588, 22906, 24295, 25387, 28436, 32768, 0],
1126+ [13298, 16984, 20471, 24182, 25067, 25736, 26422, 32768, 0],
1127+ [18904, 23325, 25242, 27432, 27898, 28258, 30758, 32768, 0],
1128+ [10725, 17454, 20124, 22820, 24195, 25168, 26046, 32768, 0],
1129+ [17125, 24273, 25814, 27492, 28214, 28704, 30592, 32768, 0],
1130+ [13046, 23214, 24505, 25942, 27435, 28442, 29330, 32768, 0],
1131+];
1132+
1133+/// `compound_mode_ctx_map` (`mvref_common.h`): folds a compound block's
1134+/// `new_mv_ctx`/`ref_mv_ctx` pair (row = `ref_mv_ctx >> 1`, column =
1135+/// `min(new_mv_ctx, COMP_NEWMV_CTXS - 1)`, `COMP_NEWMV_CTXS` = 5) down to
1136+/// the single `comp_ctx` [`INTER_COMPOUND_MODE`] is indexed by --
1137+/// `av1_mode_context_analyzer`'s compound branch.
1138+pub const COMPOUND_MODE_CTX_MAP: [[usize; 5]; 3] =
1139+ [[0, 1, 1, 1, 1], [1, 2, 3, 4, 4], [4, 4, 5, 6, 7]];
11131140
11141141 /// `Default_Intra_Inter_Cdf` (spec 9.4): whether an inter frame's block is
11151142 /// 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] = [
11501177 ],
11511178 ];
11521179
1180+/// `default_skip_mode_cdfs` (entropymode.c, `SKIP_MODE_CONTEXTS` = 3): whether
1181+/// a block reads `skip_mode` (forced `NEAREST_NEARESTMV` compound, `skip`
1182+/// forced true, no residual) -- indexed by `av1_get_skip_mode_context`
1183+/// (`above.skip_mode + left.skip_mode`, `pred_common.h`), only read when this
1184+/// frame's own `skip_mode_present` header bit is set and the block is at
1185+/// least 8x8 both dims (`is_comp_ref_allowed`) -- lane-av1comp.
1186+pub const SKIP_MODE: [[u16; 3]; 3] = [[32621, 32768, 0], [20708, 32768, 0], [8127, 32768, 0]];
1187+
1188+/// `Default_Comp_Mode_Cdf` (spec 9.4, `default_comp_inter_cdf`): whether an
1189+/// inter block reads `SINGLE_REFERENCE` or `COMPOUND_REFERENCE` -- only
1190+/// reached once `read_ref_frames` knows the frame's `reference_select`
1191+/// header bit made the choice per-block instead of fixing it, indexed by
1192+/// `av1_get_reference_mode_context` (lane-av1comp).
1193+pub const COMP_MODE: [[u16; 3]; 5] = [
1194+ [26828, 32768, 0],
1195+ [24035, 32768, 0],
1196+ [12031, 32768, 0],
1197+ [10640, 32768, 0],
1198+ [2901, 32768, 0],
1199+];
1200+
1201+/// `Default_Comp_Ref_Type_Cdf` (spec 9.4, `default_comp_ref_type_cdf`):
1202+/// unidirectional vs. bidirectional compound reference pair, indexed by
1203+/// `av1_get_comp_reference_type_context`.
1204+pub const COMP_REF_TYPE: [[u16; 3]; 5] = [
1205+ [1198, 32768, 0],
1206+ [2070, 32768, 0],
1207+ [9166, 32768, 0],
1208+ [7499, 32768, 0],
1209+ [22475, 32768, 0],
1210+];
1211+
1212+/// `Default_Comp_Group_Idx_Cdf` (spec 9.4, libaom `default_comp_group_idx_cdfs`):
1213+/// whether a compound block's `comp_group_idx` picks masked compound (`1`)
1214+/// over the plain distance-weighted/simple-average blend (`0`), indexed by
1215+/// `get_comp_group_idx_context` -- only read when `seq.enable_masked_compound`
1216+/// and the block size is masked-compound-eligible (lane-av1comp).
1217+pub const COMP_GROUP_IDX: [[u16; 3]; 6] = [
1218+ [26607, 32768, 0],
1219+ [22891, 32768, 0],
1220+ [18840, 32768, 0],
1221+ [24594, 32768, 0],
1222+ [19934, 32768, 0],
1223+ [22674, 32768, 0],
1224+];
1225+
1226+/// `Default_Compound_Idx_Cdf` (spec 9.4, libaom `default_compound_idx_cdfs`):
1227+/// whether a compound block's `compound_idx` picks the simple average
1228+/// (`1`) or [`crate::compound::dist_wtd_comp_weight_assign`]'s distance
1229+/// weights (`0`), indexed by `get_comp_index_context` -- only read when
1230+/// `seq.enable_jnt_comp` (lane-av1comp).
1231+pub const COMPOUND_IDX: [[u16; 3]; 6] = [
1232+ [18244, 32768, 0],
1233+ [12865, 32768, 0],
1234+ [7053, 32768, 0],
1235+ [13259, 32768, 0],
1236+ [9334, 32768, 0],
1237+ [4644, 32768, 0],
1238+];
1239+
1240+/// `Default_Uni_Comp_Ref_Cdf` (spec 9.4, `default_uni_comp_ref_cdf`): the
1241+/// three binary decisions narrowing a unidirectional compound pair down to
1242+/// one of `{BWDREF,ALTREF}`/`{LAST,LAST2}`/`{LAST,LAST3}`/`{LAST,GOLDEN}`.
1243+pub const UNI_COMP_REF: [[[u16; 3]; 3]; 3] = [
1244+ [[5284, 32768, 0], [3865, 32768, 0], [3128, 32768, 0]],
1245+ [[23152, 32768, 0], [14173, 32768, 0], [15270, 32768, 0]],
1246+ [[31774, 32768, 0], [25120, 32768, 0], [26710, 32768, 0]],
1247+];
1248+
1249+/// `Default_Comp_Ref_Cdf` (spec 9.4, `default_comp_ref_cdf`): the three
1250+/// binary decisions narrowing a bidirectional pair's forward reference.
1251+pub const COMP_REF: [[[u16; 3]; 3]; 3] = [
1252+ [[4946, 32768, 0], [9468, 32768, 0], [1503, 32768, 0]],
1253+ [[19891, 32768, 0], [22441, 32768, 0], [15160, 32768, 0]],
1254+ [[30731, 32768, 0], [31059, 32768, 0], [27544, 32768, 0]],
1255+];
1256+
1257+/// `Default_Comp_Bwdref_Cdf` (spec 9.4, `default_comp_bwdref_cdf`): the two
1258+/// binary decisions narrowing a bidirectional pair's backward reference.
1259+pub const COMP_BWDREF: [[[u16; 3]; 2]; 3] = [
1260+ [[2235, 32768, 0], [1423, 32768, 0]],
1261+ [[17182, 32768, 0], [15175, 32768, 0]],
1262+ [[30606, 32768, 0], [30489, 32768, 0]],
1263+];
1264+
11531265 /// `Default_Y_Mode_Cdf` (spec 9.4): the thirteen luma intra modes of an inter
11541266 /// frame's intra block, indexed by the block's size group -- unlike a key
11551267 /// frame's [`KF_Y_MODE`], which is indexed by the neighbours' modes instead.
crates/ec-av1/src/cdf_state.rsmodified+49 -0
@@ -293,6 +293,31 @@ pub(crate) struct Cdfs {
293293 pub intra_inter: [[u16; 3]; 4],
294294 /// The six binary decisions of an inter block's single reference frame.
295295 pub single_ref: [[[u16; 3]; 6]; 3],
296+ /// Whether a block reads `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`
297+ /// (lane-av1comp, spec 5.11.25's `comp_mode`).
298+ pub comp_mode: [[u16; 3]; 5],
299+ /// Whether a block reads `skip_mode` (lane-av1comp, spec 5.11.29's
300+ /// `skip_mode`), indexed by `av1_get_skip_mode_context`.
301+ pub skip_mode: [[u16; 3]; 3],
302+ /// Which of the eight `INTER_COMPOUND_MODES` a `COMPOUND_REFERENCE`
303+ /// block takes (lane-av1comp, spec 5.11.24's `compound_mode`).
304+ pub inter_compound_mode: [[u16; 9]; 8],
305+ /// Unidirectional vs. bidirectional compound reference pair
306+ /// (lane-av1comp, spec 5.11.25's `comp_reference_type`).
307+ pub comp_ref_type: [[u16; 3]; 5],
308+ /// The three binary decisions of a unidirectional compound pair.
309+ pub uni_comp_ref: [[[u16; 3]; 3]; 3],
310+ /// The three binary decisions of a bidirectional pair's forward ref.
311+ pub comp_ref: [[[u16; 3]; 3]; 3],
312+ /// The two binary decisions of a bidirectional pair's backward ref.
313+ pub comp_bwdref: [[[u16; 3]; 2]; 3],
314+ /// Whether a compound block's `comp_group_idx` picks masked compound
315+ /// (lane-av1comp, spec 5.11.25's `comp_group_idx`).
316+ pub comp_group_idx: [[u16; 3]; 6],
317+ /// Whether a compound block's `compound_idx` picks the simple average
318+ /// over the distance-weighted blend (lane-av1comp, spec 5.11.25's
319+ /// `compound_idx`).
320+ pub compound_idx: [[u16; 3]; 6],
296321 /// The luma mode of an inter frame's intra block, by its size group.
297322 pub y_mode: [[u16; 14]; 4],
298323 /// Whether an inter block codes its motion vector explicitly.
@@ -500,6 +525,15 @@ impl Cdfs {
500525 reset2(&mut self.dc_sign_chroma);
501526 reset2(&mut self.intra_inter);
502527 reset3(&mut self.single_ref);
528+ reset2(&mut self.comp_mode);
529+ reset2(&mut self.skip_mode);
530+ reset2(&mut self.inter_compound_mode);
531+ reset2(&mut self.comp_ref_type);
532+ reset3(&mut self.uni_comp_ref);
533+ reset3(&mut self.comp_ref);
534+ reset3(&mut self.comp_bwdref);
535+ reset2(&mut self.comp_group_idx);
536+ reset2(&mut self.compound_idx);
503537 reset2(&mut self.y_mode);
504538 reset2(&mut self.new_mv);
505539 reset2(&mut self.zero_mv);
@@ -924,6 +958,15 @@ impl Cdfs {
924958 dc_sign_chroma: cdf::DC_SIGN_CHROMA,
925959 intra_inter: cdf::INTRA_INTER,
926960 single_ref: cdf::SINGLE_REF,
961+ comp_mode: cdf::COMP_MODE,
962+ inter_compound_mode: cdf::INTER_COMPOUND_MODE,
963+ comp_ref_type: cdf::COMP_REF_TYPE,
964+ uni_comp_ref: cdf::UNI_COMP_REF,
965+ comp_ref: cdf::COMP_REF,
966+ comp_bwdref: cdf::COMP_BWDREF,
967+ skip_mode: cdf::SKIP_MODE,
968+ comp_group_idx: cdf::COMP_GROUP_IDX,
969+ compound_idx: cdf::COMPOUND_IDX,
927970 y_mode: cdf::Y_MODE,
928971 new_mv: cdf::NEW_MV,
929972 zero_mv: cdf::ZERO_MV,
@@ -1171,6 +1214,12 @@ mod tests {
11711214 assert_eq!(cdfs.partition_w64[2], cdf::PARTITION_W64[2]);
11721215 assert_eq!(cdfs.intra_inter, cdf::INTRA_INTER);
11731216 assert_eq!(cdfs.single_ref, cdf::SINGLE_REF);
1217+ assert_eq!(cdfs.comp_mode, cdf::COMP_MODE);
1218+ assert_eq!(cdfs.inter_compound_mode, cdf::INTER_COMPOUND_MODE);
1219+ assert_eq!(cdfs.comp_ref_type, cdf::COMP_REF_TYPE);
1220+ assert_eq!(cdfs.uni_comp_ref, cdf::UNI_COMP_REF);
1221+ assert_eq!(cdfs.comp_ref, cdf::COMP_REF);
1222+ assert_eq!(cdfs.comp_bwdref, cdf::COMP_BWDREF);
11741223 assert_eq!(cdfs.y_mode, cdf::Y_MODE);
11751224 assert_eq!(cdfs.new_mv, cdf::NEW_MV);
11761225 assert_eq!(cdfs.zero_mv, cdf::ZERO_MV);
crates/ec-av1/src/compound.rsadded+121 -0
@@ -0,0 +1,121 @@
1+//! Compound-reference blend weights (spec 7.11.3.15's "Distance weights
2+//! process", libaom's `av1_dist_wtd_comp_weight_assign` in
3+//! `reconinter.c`) -- pure, independent of the CDF/bitstream plumbing that
4+//! decides *whether* a block reads `compound_idx` at all (lane-av1comp,
5+//! decode.rs). Kept its own module so it is testable without a live
6+//! decoder: `dist_wtd_comp_weight_assign` takes exactly the four order
7+//! hints libaom's version reads off `AV1_COMMON`/`MB_MODE_INFO`.
8+
9+/// `MAX_FRAME_DISTANCE` (spec/`enums.h`): `(1 << FRAME_OFFSET_BITS) - 1`,
10+/// `FRAME_OFFSET_BITS == 5`.
11+const MAX_FRAME_DISTANCE: i32 = (1 << 5) - 1;
12+
13+/// `quant_dist_weight` (libaom `common_data.h`) -- the three candidate
14+/// weight ratios the search below picks between, before falling back to the
15+/// index-3 row when either distance is zero.
16+const QUANT_DIST_WEIGHT: [[i32; 2]; 4] = [[2, 3], [2, 5], [2, 7], [1, MAX_FRAME_DISTANCE]];
17+
18+/// `quant_dist_lookup_table` (libaom `common_data.h`): the actual
19+/// `fwd_offset`/`bck_offset` pair each `QUANT_DIST_WEIGHT` row resolves to
20+/// (both always sum to 16, `1 << DIST_PRECISION_BITS`).
21+const QUANT_DIST_LOOKUP_TABLE: [[i32; 2]; 4] = [[9, 7], [11, 5], [12, 4], [13, 3]];
22+
23+/// `av1_dist_wtd_comp_weight_assign` (spec 7.11.3.15 / libaom
24+/// `reconinter.c`): `(fwd_weight, bck_weight)` for a compound block, given
25+/// this frame's own `order_hint` and the two references' order hints --
26+/// `ref0_order_hint` names `mbmi->ref_frame[0]` (libaom's "`bck`", despite
27+/// the name -- it is nearer in decode order for a typical GOP but the
28+/// spec's algebra does not assume that), `ref1_order_hint` names
29+/// `ref_frame[1]` ("`fwd`").
30+///
31+/// `compound_idx == 1` (or `!is_compound`, never reached from here) is the
32+/// simple-average caller's job: it never calls this and uses `(8, 8)`
33+/// directly (spec 7.11.3.15's `use_dist_wtd_comp_avg == 0` branch) --
34+/// this function only ever implements the `use_dist_wtd_comp_avg == 1`
35+/// (`compound_idx == 0`) branch.
36+pub(crate) fn dist_wtd_comp_weight_assign(
37+ order_hint_bits: u32,
38+ cur_order_hint: u32,
39+ ref0_order_hint: u32,
40+ ref1_order_hint: u32,
41+) -> (i32, i32) {
42+ let d0 =
43+ crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
44+ .abs()
45+ .clamp(0, MAX_FRAME_DISTANCE);
46+ let d1 =
47+ crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
48+ .abs()
49+ .clamp(0, MAX_FRAME_DISTANCE);
50+
51+ let order = usize::from(d0 <= d1);
52+
53+ if d0 == 0 || d1 == 0 {
54+ return (
55+ QUANT_DIST_LOOKUP_TABLE[3][order],
56+ QUANT_DIST_LOOKUP_TABLE[3][1 - order],
57+ );
58+ }
59+
60+ let mut i = 0;
61+ while i < 3 {
62+ let c0 = QUANT_DIST_WEIGHT[i][order];
63+ let c1 = QUANT_DIST_WEIGHT[i][1 - order];
64+ let d0_c0 = d0 * c0;
65+ let d1_c1 = d1 * c1;
66+ if (d0 > d1 && d0_c0 < d1_c1) || (d0 <= d1 && d0_c0 > d1_c1) {
67+ break;
68+ }
69+ i += 1;
70+ }
71+
72+ (
73+ QUANT_DIST_LOOKUP_TABLE[i][order],
74+ QUANT_DIST_LOOKUP_TABLE[i][1 - order],
75+ )
76+}
77+
78+#[cfg(test)]
79+mod tests {
80+ use super::dist_wtd_comp_weight_assign;
81+
82+ /// Equidistant references (spec/libaom's `d0 == d1` case) land on
83+ /// `order == 1` (`d0 <= d1`) throughout, and the very first weight
84+ /// candidate (`i == 0`, ratio `2:3`) always survives the search's break
85+ /// condition when `d0_c0 == d1_c1`'s neither branch fires -- so a
86+ /// symmetric GOP (order hints `8` behind and `8` ahead of a `16`-hint
87+ /// current frame) resolves to the row-0 weights `(7, 9)`: `order == 1`
88+ /// (`d0 <= d1`) selects `QUANT_DIST_LOOKUP_TABLE[0][1] == 7` for
89+ /// `fwd_offset` and `QUANT_DIST_LOOKUP_TABLE[0][0] == 9` for
90+ /// `bck_offset`.
91+ #[test]
92+ fn equidistant_references_pick_the_first_weight_row() {
93+ assert_eq!(dist_wtd_comp_weight_assign(8, 16, 8, 24), (7, 9));
94+ }
95+
96+ /// A reference at zero relative distance (this frame repeats one of its
97+ /// own references' order hint -- degenerate but spec-legal) always
98+ /// takes the index-3 lookup row (`13`/`3`) rather than entering the
99+ /// weight search, matching libaom's `d0 == 0 || d1 == 0` early return.
100+ #[test]
101+ fn zero_distance_reference_takes_the_index_3_row() {
102+ // ref1 (fwd) coincides with cur -> d0 == 0.
103+ assert_eq!(dist_wtd_comp_weight_assign(8, 16, 8, 16), (3, 13));
104+ }
105+
106+ /// Weights always sum to `1 << DIST_PRECISION_BITS == 16` -- every row
107+ /// of `QUANT_DIST_LOOKUP_TABLE` was picked to hold that invariant, and
108+ /// [`combine_compound`](crate::mc::combine_compound)'s final shift
109+ /// (`InterPostRound + DIST_PRECISION_BITS`) assumes it.
110+ #[test]
111+ fn weights_always_sum_to_sixteen() {
112+ for cur in [0u32, 16, 40] {
113+ for r0 in [0u32, 8, 32] {
114+ for r1 in [4u32, 24, 48] {
115+ let (fwd, bck) = dist_wtd_comp_weight_assign(8, cur, r0, r1);
116+ assert_eq!(fwd + bck, 16, "cur={cur} r0={r0} r1={r1}");
117+ }
118+ }
119+ }
120+ }
121+}
crates/ec-av1/src/decode.rsmodified+1614 -285

Diff too large; view file

@@ -32,9 +32,10 @@ use crate::mc;
3232 use crate::msac::SymbolDecoder;
3333 use crate::mvstack::{
3434 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
35- MiGrid, MiInfo, NO_SIGN_BIAS, SignBiasTable, find_mv_stack, find_mv_stack_with_sign_bias,
36- single_ref_ctx, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
37- single_ref_p5_ctx, single_ref_p6_ctx,
35+ MiGrid, MiInfo, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
36+ find_mv_stack, find_mv_stack_with_sign_bias, reference_mode_ctx, single_ref_ctx,
37+ single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
38+ single_ref_p6_ctx, uni_comp_ref_p1_ctx,
3839 };
3940 use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
4041 use crate::transform::{TxType, dequant_and_inverse_typed};
@@ -131,6 +132,41 @@ static BWDREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUs
131132 static ALTREF2_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
132133 static ALTREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
133134
135+/// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
136+/// -- proves a `reference_select` stream actually reached a block that picked
137+/// compound, not just that the header bit was set. Every such block is
138+/// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
139+/// so this only ever counts attempted reads, never a completed decode.
140+static COMP_MODE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
141+
142+/// Current value of [`COMP_MODE_HITS`].
143+pub(crate) fn comp_mode_hits() -> usize {
144+ COMP_MODE_HITS.load(std::sync::atomic::Ordering::Relaxed)
145+}
146+
147+/// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
148+/// proves a real `skip_mode_present` stream actually reached a block that
149+/// picked it, not just that the frame header bit was set.
150+static SKIP_MODE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
151+
152+/// Current value of [`SKIP_MODE_HITS`].
153+pub(crate) fn skip_mode_hits() -> usize {
154+ SKIP_MODE_HITS.load(std::sync::atomic::Ordering::Relaxed)
155+}
156+
157+/// How many [`read_inter_compound_mode`] reads actually happened
158+/// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
159+/// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
160+/// mvstack build), not just that `comp_mode` fired. Still refused right
161+/// after (no MV assignment or MC wired), so this only counts attempted
162+/// reads.
163+static COMPOUND_MODE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
164+
165+/// Current value of [`COMPOUND_MODE_HITS`].
166+pub(crate) fn compound_mode_hits() -> usize {
167+ COMPOUND_MODE_HITS.load(std::sync::atomic::Ordering::Relaxed)
168+}
169+
134170 /// How many query blocks folded in at least one temporal MV candidate
135171 /// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
136172 /// temporal-MV gate's own firing counter (lane-av1tmvp).
@@ -736,6 +772,11 @@ struct Neighbours {
736772 /// `left_skip`.
737773 above_skip: Vec<bool>,
738774 left_skip: Vec<bool>,
775+ /// Whether the block above/left of this column/row coded `skip_mode`
776+ /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
777+ /// lane-av1comp round 14.
778+ above_skip_mode: Vec<bool>,
779+ left_skip_mode: Vec<bool>,
739780 /// Whether the block above/left was coded inter -- the `is_inter`
740781 /// context (spec `av1_get_intra_inter_context`), a duplicate of
741782 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
@@ -750,6 +791,23 @@ struct Neighbours {
750791 /// enough).
751792 above_ref: Vec<i8>,
752793 left_ref: Vec<i8>,
794+ /// The block above/left's *second* reference frame when it was coded
795+ /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
796+ /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
797+ /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
798+ /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
799+ /// (no decode path here ever produces a compound block yet).
800+ above_ref1: Vec<Option<i8>>,
801+ left_ref1: Vec<Option<i8>>,
802+ /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
803+ /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
804+ /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
805+ /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
806+ /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
807+ above_comp_group_idx: Vec<u8>,
808+ left_comp_group_idx: Vec<u8>,
809+ above_compound_idx: Vec<u8>,
810+ left_compound_idx: Vec<u8>,
753811 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
754812 /// `3` = "no info": an intra neighbour or the frame's own border) of the
755813 /// block above/left of this column/row -- spec
@@ -798,10 +856,18 @@ impl Neighbours {
798856 left_side_mi: vec![SB; rows * (SUB / MI)],
799857 above_skip: vec![false; cols],
800858 left_skip: vec![false; rows],
859+ above_skip_mode: vec![false; cols],
860+ left_skip_mode: vec![false; rows],
801861 above_inter: vec![false; cols],
802862 left_inter: vec![false; rows],
803863 above_ref: vec![-1; cols],
804864 left_ref: vec![-1; rows],
865+ above_ref1: vec![None; cols],
866+ left_ref1: vec![None; rows],
867+ above_comp_group_idx: vec![0; cols],
868+ left_comp_group_idx: vec![0; rows],
869+ above_compound_idx: vec![0; cols],
870+ left_compound_idx: vec![0; rows],
805871 above_filter: vec![[3u8; 2]; cols],
806872 left_filter: vec![[3u8; 2]; rows],
807873 mi_cols,
@@ -883,8 +949,12 @@ impl Neighbours {
883949 self.left_side.iter_mut().for_each(|s| *s = SB);
884950 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
885951 self.left_skip.iter_mut().for_each(|s| *s = false);
952+ self.left_skip_mode.iter_mut().for_each(|s| *s = false);
886953 self.left_inter.iter_mut().for_each(|i| *i = false);
887954 self.left_ref.iter_mut().for_each(|r| *r = -1);
955+ self.left_ref1.iter_mut().for_each(|r| *r = None);
956+ self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
957+ self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
888958 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
889959 }
890960
@@ -903,20 +973,67 @@ impl Neighbours {
903973 is_inter: bool,
904974 ref_frame: i8,
905975 filter: [u8; 2],
976+ skip_mode: bool,
906977 ) {
907978 let (r, c) = at;
908979 for cell in 0..side / SUB {
909980 self.above_skip[c + cell] = skip;
910981 self.left_skip[r + cell] = skip;
982+ self.above_skip_mode[c + cell] = skip_mode;
983+ self.left_skip_mode[r + cell] = skip_mode;
911984 self.above_inter[c + cell] = is_inter;
912985 self.left_inter[r + cell] = is_inter;
913986 self.above_ref[c + cell] = ref_frame;
914987 self.left_ref[r + cell] = ref_frame;
988+ // lane-av1comp: no caller of `record_inter` ever decodes a
989+ // compound block yet (see [`Self::above_ref1`]'s doc); the
990+ // parameter this becomes lands with `read_ref_frames`.
991+ self.above_ref1[c + cell] = None;
992+ self.left_ref1[r + cell] = None;
993+ // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
994+ // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
995+ // as `3`/`1` even though this block has no second reference.
996+ // `record_compound_ctx` overwrites this with the real bit for an
997+ // actual compound block's cells, called right after this one.
998+ let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
999+ self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
1000+ self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
1001+ self.above_compound_idx[c + cell] = u8::from(altref);
1002+ self.left_compound_idx[r + cell] = u8::from(altref);
9151003 self.above_filter[c + cell] = filter;
9161004 self.left_filter[r + cell] = filter;
9171005 }
9181006 }
9191007
1008+ /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
1009+ /// a real compound block's own `comp_group_idx`/`compound_idx` bits
1010+ /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
1011+ /// `get_comp_index_context`) -- called right after `record_inter` for
1012+ /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
1013+ /// stamps `above_ref1`/`left_ref1` with the block's real second
1014+ /// reference, which `record_inter` always clears to `None` (lane-av1comp:
1015+ /// this is the one caller that actually knows it) -- so the next block's
1016+ /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
1017+ /// neighbour instead of `record_inter`'s single-ref default.
1018+ fn record_compound_ctx(
1019+ &mut self,
1020+ at: (usize, usize),
1021+ side: usize,
1022+ ref1: i8,
1023+ comp_group_idx: u8,
1024+ compound_idx: u8,
1025+ ) {
1026+ let (r, c) = at;
1027+ for cell in 0..side / SUB {
1028+ self.above_ref1[c + cell] = Some(ref1);
1029+ self.left_ref1[r + cell] = Some(ref1);
1030+ self.above_comp_group_idx[c + cell] = comp_group_idx;
1031+ self.left_comp_group_idx[r + cell] = comp_group_idx;
1032+ self.above_compound_idx[c + cell] = compound_idx;
1033+ self.left_compound_idx[r + cell] = compound_idx;
1034+ }
1035+ }
1036+
9201037 /// The context of a block's partition symbol: delegates to the mi-precise
9211038 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
9221039 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
@@ -2378,6 +2495,27 @@ fn cdef_filter_block(
23782495 ///
23792496 /// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
23802497 /// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
2498+// r17 bisect scratch: dump this frame's true-extent Y/U/V (same layout as
2499+// aomdec's EC_AV1_PREFILT_DUMP/EC_AV1_POSTFILT_DUMP) to `$var.f$idx` when
2500+// `var` is set. Remove with the rest of the r17 bisect scaffolding.
2501+static R17_DUMP_FRAME_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2502+fn r17_dump(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, idx: usize) {
2503+ let Ok(base) = std::env::var(var) else {
2504+ return;
2505+ };
2506+ let mut out = Vec::new();
2507+ for r in 0..y.true_height {
2508+ out.extend_from_slice(&y.data[r * y.width..r * y.width + y.true_width]);
2509+ }
2510+ for r in 0..u.true_height {
2511+ out.extend_from_slice(&u.data[r * u.width..r * u.width + u.true_width]);
2512+ }
2513+ for r in 0..v.true_height {
2514+ out.extend_from_slice(&v.data[r * v.width..r * v.width + v.true_width]);
2515+ }
2516+ let _ = std::fs::write(format!("{base}.f{idx}"), out);
2517+}
2518+
23812519 fn apply_deblock(
23822520 y: &mut PlaneBuf,
23832521 u: &mut PlaneBuf,
@@ -3777,6 +3915,298 @@ fn read_single_ref(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, above_ref: i8, left
37773915 ref_frame
37783916 }
37793917
3918+/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
3919+/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
3920+/// `reference_select` header bit lets a block choose per-block instead of
3921+/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
3922+/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
3923+/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
3924+/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
3925+/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
3926+/// Resolves a compound reference's own planes -- the same `ref_frame ==
3927+/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
3928+/// [`decode_inter_block`]'s single-ref path already does, factored out so
3929+/// the compound path can call it twice (lane-av1comp).
3930+fn ref_planes<'a>(
3931+ ref_frame: i8,
3932+ ref_y: &'a PlaneBuf,
3933+ ref_u: &'a PlaneBuf,
3934+ ref_v: &'a PlaneBuf,
3935+ other_refs: &'a RefSlots,
3936+) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
3937+ if ref_frame == LAST_FRAME {
3938+ Ok((ref_y, ref_u, ref_v))
3939+ } else {
3940+ match other_refs[ref_frame as usize] {
3941+ Some((ry, ru, rv)) => Ok((ry, ru, rv)),
3942+ None => Err(unsupported(
3943+ "a reference frame selected with no picture at this frame's own \
3944+ ref_frame_idx slot for it",
3945+ )),
3946+ }
3947+ }
3948+}
3949+
3950+/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
3951+/// the square block sizes this decoder ever decodes (32/16/8, all
3952+/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
3953+/// always `is_interinter_compound_used`, so the function is always `true`
3954+/// for `side` -- kept as a named call (rather than inlined `true`) so a
3955+/// future sub-8 block size does not silently misdecode a real stream.
3956+fn is_any_masked_compound_used_here(side: usize) -> bool {
3957+ side.min(side) >= 8
3958+}
3959+
3960+/// Whether a compound reference pair is unidirectional (both references on
3961+/// the same temporal side of the current frame) -- `has_uni_comp_refs`
3962+/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
3963+/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
3964+/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
3965+/// is_backward(ref1)`). Used to build a real
3966+/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
3967+/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
3968+fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
3969+ let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
3970+ backward(ref0) == backward(ref1)
3971+}
3972+
3973+/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
3974+/// above/left neighbour contributions [`Neighbours::record_inter`]/
3975+/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
3976+fn get_comp_group_idx_context(neighbours: &Neighbours, at: (usize, usize), side: usize) -> usize {
3977+ let _ = side;
3978+ let (r, c) = at;
3979+ (neighbours.above_comp_group_idx[c] as usize + neighbours.left_comp_group_idx[r] as usize)
3980+ .min(5)
3981+}
3982+
3983+/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
3984+/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
3985+/// block's own two references' distances from the current frame (spec
3986+/// 7.11.3.15's `get_relative_dist`, same convention
3987+/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
3988+#[allow(clippy::too_many_arguments)]
3989+fn get_comp_index_context(
3990+ neighbours: &Neighbours,
3991+ at: (usize, usize),
3992+ side: usize,
3993+ order_hint_bits: u32,
3994+ cur_order_hint: u32,
3995+ ref0_order_hint: u32,
3996+ ref1_order_hint: u32,
3997+) -> usize {
3998+ let _ = side;
3999+ let (r, c) = at;
4000+ let fwd =
4001+ crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
4002+ .abs();
4003+ let bck =
4004+ crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
4005+ .abs();
4006+ let offset = usize::from(fwd == bck);
4007+ neighbours.above_compound_idx[c] as usize
4008+ + neighbours.left_compound_idx[r] as usize
4009+ + 3 * offset
4010+}
4011+
4012+fn read_comp_mode(
4013+ dec: &mut SymbolDecoder,
4014+ cdfs: &mut Cdfs,
4015+ above: Option<NeighbourRef>,
4016+ left: Option<NeighbourRef>,
4017+) -> bool {
4018+ let ctx = reference_mode_ctx(above, left);
4019+ let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
4020+ if compound {
4021+ COMP_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4022+ }
4023+ compound
4024+}
4025+
4026+/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
4027+/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
4028+/// arm), reached once [`read_comp_mode`] has already returned
4029+/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
4030+/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
4031+/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
4032+/// convention [`read_single_ref`] already uses, for every downstream binary
4033+/// decision. libaom `pred_common.c`'s own compound context functions
4034+/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
4035+/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
4036+/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
4037+/// (same vote-the-neighbours-above-left shape, same forward/backward and
4038+/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
4039+/// against the C source rather than porting six near-duplicate functions.
4040+/// Its caller today only needs the symbols consumed, correctly, to keep the
4041+/// arithmetic decoder's own state in sync before refusing the block by name
4042+/// -- the returned pair is not yet threaded into any motion-compensation
4043+/// path.
4044+fn read_compound_ref_frames(
4045+ dec: &mut SymbolDecoder,
4046+ cdfs: &mut Cdfs,
4047+ above: Option<NeighbourRef>,
4048+ left: Option<NeighbourRef>,
4049+ above_ref: i8,
4050+ left_ref: i8,
4051+) -> (i8, i8) {
4052+ let a = (above_ref > 0).then_some(above_ref);
4053+ let l = (left_ref > 0).then_some(left_ref);
4054+ let type_ctx = comp_reference_type_ctx(above, left);
4055+ let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
4056+ if unidir {
4057+ // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
4058+ // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
4059+ let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, l)][0]);
4060+ if bit == 1 {
4061+ (BWDREF_FRAME, ALTREF_FRAME)
4062+ } else {
4063+ let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, l)][1]);
4064+ if p1 == 1 {
4065+ // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
4066+ let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, l)][2]);
4067+ if p2 == 1 {
4068+ (LAST_FRAME, GOLDEN_FRAME)
4069+ } else {
4070+ (LAST_FRAME, LAST3_FRAME)
4071+ }
4072+ } else {
4073+ (LAST_FRAME, LAST2_FRAME)
4074+ }
4075+ }
4076+ } else {
4077+ // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
4078+ let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, l)][0]);
4079+ let ref0 = if bit0 == 0 {
4080+ // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
4081+ let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, l)][1]);
4082+ if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
4083+ } else {
4084+ // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
4085+ let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, l)][2]);
4086+ if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
4087+ };
4088+ // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
4089+ let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, l)][0]);
4090+ let ref1 = if bit1 == 0 {
4091+ // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
4092+ let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, l)][1]);
4093+ if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
4094+ } else {
4095+ ALTREF_FRAME
4096+ };
4097+ (ref0, ref1)
4098+ }
4099+}
4100+
4101+/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
4102+/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
4103+/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
4104+/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
4105+/// libaom's `av1_mode_context_analyzer`'s compound branch --
4106+/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
4107+/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
4108+/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
4109+/// is not yet turned into an assigned MV pair or motion-compensated --
4110+/// lane-av1comp.
4111+fn read_inter_compound_mode(
4112+ dec: &mut SymbolDecoder,
4113+ cdfs: &mut Cdfs,
4114+ new_mv_ctx: usize,
4115+ ref_mv_ctx: usize,
4116+) -> u8 {
4117+ let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
4118+ COMPOUND_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4119+ dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
4120+}
4121+
4122+/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
4123+/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
4124+/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
4125+/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
4126+/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
4127+/// non-`IDENTITY` global motion model before a tile is ever decoded.
4128+///
4129+/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
4130+/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
4131+/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
4132+/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
4133+/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
4134+fn assign_compound_mv(
4135+ dec: &mut SymbolDecoder,
4136+ cdfs: &mut Cdfs,
4137+ comp_stack: &crate::mvstack::CompoundMvStack,
4138+ mode: u8,
4139+ allow_high_precision_mv: bool,
4140+) -> ((i32, i32), (i32, i32)) {
4141+ const NEAREST_NEARESTMV: u8 = 0;
4142+ const NEAR_NEARMV: u8 = 1;
4143+ const NEAREST_NEWMV: u8 = 2;
4144+ const NEW_NEARESTMV: u8 = 3;
4145+ const NEAR_NEWMV: u8 = 4;
4146+ const NEW_NEARMV: u8 = 5;
4147+ const GLOBAL_GLOBALMV: u8 = 6;
4148+ const NEW_NEWMV: u8 = 7;
4149+
4150+ let mut ref_mv_idx = 0usize;
4151+ if mode == NEW_NEWMV {
4152+ let mut idx = 0usize;
4153+ while idx < 2 && comp_stack.entries.len() > idx + 1 {
4154+ if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
4155+ break;
4156+ }
4157+ idx += 1;
4158+ }
4159+ ref_mv_idx = idx;
4160+ } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
4161+ let mut idx = 1usize;
4162+ while idx < 3 && comp_stack.entries.len() > idx + 1 {
4163+ if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
4164+ break;
4165+ }
4166+ idx += 1;
4167+ }
4168+ ref_mv_idx = idx - 1;
4169+ }
4170+
4171+ let near = comp_stack
4172+ .entries
4173+ .get(ref_mv_idx + 1)
4174+ .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
4175+ let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
4176+ ref_mv_idx + 1
4177+ } else {
4178+ ref_mv_idx
4179+ };
4180+ let new_pred = comp_stack
4181+ .entries
4182+ .get(new_idx)
4183+ .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
4184+
4185+ let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
4186+ read_mv(
4187+ dec,
4188+ &mut cdfs.mv_comp,
4189+ &mut cdfs.mv_joint,
4190+ base,
4191+ allow_high_precision_mv,
4192+ )
4193+ };
4194+
4195+ match mode {
4196+ NEAREST_NEARESTMV => comp_stack.nearest_mv,
4197+ NEAR_NEARMV => near,
4198+ NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
4199+ NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
4200+ NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
4201+ NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
4202+ GLOBAL_GLOBALMV => ((0, 0), (0, 0)),
4203+ _ => (
4204+ read_new(dec, cdfs, new_pred.0),
4205+ read_new(dec, cdfs, new_pred.1),
4206+ ),
4207+ }
4208+}
4209+
37804210 /// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
37814211 /// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
37824212 /// and motion-compensated reconstruction, or the inter frame's own intra
@@ -3829,298 +4259,706 @@ fn decode_inter_block(
38294259 interp_fixed: Option<mc::InterpFilterKind>,
38304260 enable_dual_filter: bool,
38314261 tpl_frame: Option<&TplFrameArgs>,
4262+ // lane-av1comp: this frame header's own `reference_select` bit -- `false`
4263+ // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
4264+ // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
4265+ // refuses (rather than silently misdecoding) the ones that pick
4266+ // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
4267+ // wired yet.
4268+ reference_select: bool,
4269+ // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
4270+ // compound enable bits, gating `comp_group_idx`/`compound_idx`
4271+ // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
4272+ // compound blend weights need this frame's own order hint regardless
4273+ // of `use_ref_frame_mvs`.
4274+ enable_masked_compound: bool,
4275+ enable_jnt_comp: bool,
4276+ order_hint_bits: u32,
4277+ order_hint: u32,
4278+ ref_order_hints: [u32; 7],
4279+ // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
4280+ // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
4281+ // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
4282+ // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
4283+ // when this is `true` (every block this decoder reaches is >= 8x8, so
4284+ // `is_comp_ref_allowed` never gates it further); a `true` result forces
4285+ // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
4286+ // DRL symbol read, and a plain average blend with no `comp_group_idx`/
4287+ // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
4288+ skip_mode_present: bool,
4289+ skip_mode_frame: [u8; 2],
38324290 ) -> Result<()> {
38334291 let (r, c) = at;
38344292 let (px, py) = (c * SUB, r * SUB);
38354293 let (cpx, cpy) = (px / 2, py / 2);
38364294 let chroma_side = side / 2;
38374295
4296+ let skip_mode_ctx =
4297+ usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
4298+ let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
4299+ if skip_mode {
4300+ SKIP_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4301+ }
4302+
38384303 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
3839- let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
4304+ let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
38404305
38414306 let (has_above, has_left) = (r > 0, c > 0);
38424307 let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]);
38434308 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
3844- let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
4309+ let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
38454310
38464311 let mode_for_tx;
38474312 let (luma_grid, u_grid, v_grid);
38484313 let block_filter;
38494314 let ref_frame_for_lf;
38504315 let globalmv_for_lf;
4316+ // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
4317+ // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
4318+ // common `record_inter` call below (which would otherwise stamp the
4319+ // single-ref ALTREF-special-case default over it).
4320+ let mut compound_ctx: Option<(i8, u8, u8)> = None;
38514321 if is_inter {
3852- let ref_frame = read_single_ref(dec, cdfs, neighbours.above_ref[c], neighbours.left_ref[r]);
3853- ref_frame_for_lf = ref_frame;
3854- // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
3855- // stacked defects (lf_level ref/mode-delta forwarding, the
3856- // switchable_interp ref-frame ctx gate, and a film-grain synthesis
3857- // gap that looked like a GOLDEN MC bug by survivor bias -- see the
3858- // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
3859- // below same as every other non-`LAST_FRAME` reference. lane-av1refs
3860- // widens this from GOLDEN alone to every reference `read_single_ref`
3861- // can name.
3862- let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
3863- (ref_y, ref_u, ref_v)
3864- } else {
3865- match other_refs[ref_frame as usize] {
3866- Some((ry, ru, rv)) => (ry, ru, rv),
3867- None => {
3868- return Err(unsupported(
3869- "a reference frame selected with no picture at this frame's own \
3870- ref_frame_idx slot for it",
3871- ));
3872- }
3873- }
3874- };
3875-
3876- let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
3877- let bw4 = side / 4;
3878- // spec 7.10.2.8: only reached when the frame header set
3879- // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
3880- // otherwise) -- `cur_offset_0` is this query block's own resolved
3881- // `ref_frame`'s distance from the current frame (spec 7.9.3),
3882- // recomputed per block since different blocks pick different refs.
3883- let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
3884- field: t.field,
3885- cur_offset_0: crate::motion_field::get_relative_dist(
3886- t.order_hint_bits,
3887- t.order_hint,
3888- t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
3889- ),
3890- allow_high_precision_mv,
4322+ let above_nbr = has_above.then(|| NeighbourRef {
4323+ is_inter: above_inter,
4324+ ref0: if above_inter {
4325+ neighbours.above_ref[c]
4326+ } else {
4327+ 0
4328+ },
4329+ ref1: neighbours.above_ref1[c],
4330+ uni: neighbours.above_ref1[c]
4331+ .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[c], r1)),
38914332 });
3892- let stack = find_mv_stack_with_sign_bias(
3893- grid,
3894- mi_row,
3895- mi_col,
3896- bw4,
3897- bw4,
3898- ref_frame,
3899- mi_cols as usize,
3900- mi_rows as usize,
3901- sign_bias_table,
3902- tpl,
3903- );
3904- let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
3905- let mut is_globalmv = false;
3906- let (mv, is_new_mv) = if !not_new {
3907- // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
3908- // read at most two `drl_mode` bits, one per stack entry past the
3909- // first, stopping at the first `0`. The chosen index selects
3910- // which stack entry `read_mv`'s base predictor comes from
3911- // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
3912- // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
3913- let mut idx = 0usize;
3914- while idx < 2 && stack.entries.len() > idx + 1 {
3915- if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
3916- break;
3917- }
3918- idx += 1;
3919- }
3920- let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
3921- (
3922- read_mv(
4333+ let left_nbr = has_left.then(|| NeighbourRef {
4334+ is_inter: left_inter,
4335+ ref0: if left_inter {
4336+ neighbours.left_ref[r]
4337+ } else {
4338+ 0
4339+ },
4340+ ref1: neighbours.left_ref1[r],
4341+ uni: neighbours.left_ref1[r]
4342+ .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[r], r1)),
4343+ });
4344+ let is_compound =
4345+ skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
4346+ if is_compound {
4347+ let (ref0, ref1) = if skip_mode {
4348+ (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
4349+ } else {
4350+ read_compound_ref_frames(
39234351 dec,
3924- &mut cdfs.mv_comp,
3925- &mut cdfs.mv_joint,
3926- base_mv,
3927- allow_high_precision_mv,
4352+ cdfs,
4353+ above_nbr,
4354+ left_nbr,
4355+ neighbours.above_ref[c],
4356+ neighbours.left_ref[r],
4357+ )
4358+ };
4359+ let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
4360+ let bw4 = side / 4;
4361+ // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
4362+ // `use_ref_frame_mvs` gating as the single-ref `tpl` build
4363+ // below, just one `get_relative_dist` per reference.
4364+ let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
4365+ field: t.field,
4366+ cur_offset_0: crate::motion_field::get_relative_dist(
4367+ t.order_hint_bits,
4368+ t.order_hint,
4369+ t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
39284370 ),
3929- true,
3930- )
3931- } else {
3932- let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
3933- is_globalmv = !not_zero;
3934- let mv = if !not_zero {
3935- // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1) under the
3936- // `GmType::IDENTITY` this crate's `decode_stream` requires of
3937- // every inter frame's `LAST_FRAME` entry (any other warp
3938- // model is refused before the tile decoder is ever called).
3939- (0, 0)
4371+ cur_offset_1: crate::motion_field::get_relative_dist(
4372+ t.order_hint_bits,
4373+ t.order_hint,
4374+ t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
4375+ ),
4376+ allow_high_precision_mv,
4377+ });
4378+ let comp_stack = crate::mvstack::find_mv_stack_compound(
4379+ grid,
4380+ mi_row,
4381+ mi_col,
4382+ bw4,
4383+ bw4,
4384+ (ref0, ref1),
4385+ mi_cols as usize,
4386+ mi_rows as usize,
4387+ sign_bias_table,
4388+ comp_tpl,
4389+ );
4390+ let compound_mode = if skip_mode {
4391+ 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
39404392 } else {
3941- let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
3942- if nearest {
3943- stack.nearest_mv
4393+ read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
4394+ };
4395+ let (mv0, mv1) = assign_compound_mv(
4396+ dec,
4397+ cdfs,
4398+ &comp_stack,
4399+ compound_mode,
4400+ allow_high_precision_mv,
4401+ );
4402+ let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
4403+ let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
4404+ let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
4405+ let above_filter_ctx = if neighbours.above_ref[c] == ref0 {
4406+ neighbours.above_filter[c]
4407+ } else {
4408+ [3, 3]
4409+ };
4410+ let left_filter_ctx = if neighbours.left_ref[r] == ref0 {
4411+ neighbours.left_filter[r]
4412+ } else {
4413+ [3, 3]
4414+ };
4415+ let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
4416+ dec,
4417+ cdfs,
4418+ interp_fixed,
4419+ enable_dual_filter,
4420+ is_globalmv,
4421+ above_filter_ctx,
4422+ left_filter_ctx,
4423+ );
4424+ block_filter = resolved_filter;
4425+ globalmv_for_lf = is_globalmv;
4426+ ref_frame_for_lf = ref0;
4427+ mode_for_tx = 0;
4428+ for dr in 0..bw4 {
4429+ for dc in 0..bw4 {
4430+ grid.set(
4431+ mi_row + dr,
4432+ mi_col + dc,
4433+ MiInfo {
4434+ is_inter: true,
4435+ ref_frame: ref0,
4436+ ref_frame1: Some(ref1),
4437+ mv1: Some(mv1),
4438+ mv: mv0,
4439+ is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
4440+ size: bw4,
4441+ },
4442+ );
4443+ }
4444+ }
4445+ // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
4446+ // masked compound / distance-weighted compound are actually
4447+ // enabled for this stream -- `is_any_masked_compound_used_here`
4448+ // is `true` for every block size this decoder ever reaches
4449+ // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
4450+ // there), so the gate reduces to the sequence header bit; kept
4451+ // as an explicit call so a future smaller block size is not
4452+ // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
4453+ let group_ctx = get_comp_group_idx_context(neighbours, at, side);
4454+ let comp_group_idx = if !skip_mode
4455+ && enable_masked_compound
4456+ && is_any_masked_compound_used_here(side)
4457+ {
4458+ dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
4459+ } else {
4460+ 0
4461+ };
4462+ if comp_group_idx == 1 {
4463+ return Err(unsupported(
4464+ "a masked COMPOUND_REFERENCE block (comp_group_idx == 1, wedge/\
4465+ diffwtd) -- this decoder's compound blend is the plain distance-\
4466+ weighted/simple-average combine only, lane-av1comp",
4467+ ));
4468+ }
4469+ // corner-cut (lane-av1comp r16/r17): a real aomenc stream
4470+ // (fixtures/av1comp-r16-compound-mismatch.obu, seed 42) proved
4471+ // predict_compound_intermediate/combine_compound wrong by up to
4472+ // 4/255 in a 32x32 quadrant, spilling a few pixels into
4473+ // neighbours. r16 called this "loop-filter-shaped"; r17
4474+ // FALSIFIED that -- dumping this decoder's own pre-deblock
4475+ // frame buffer (`r17_dump`, `EC_AV1_PREFILT_DUMP`) against
4476+ // aomdec's own `EC_AV1_PREFILT_DUMP` shows the same 32x32-
4477+ // quadrant mismatch already present *before* either decoder's
4478+ // loop filter runs (898/1024 px, rows 32-63 cols 32-63 of a
4479+ // 64x64 luma plane, frame index 2 zero-based / this decoder's
4480+ // 3rd frame) -- this is a `predict_compound_intermediate`/
4481+ // `combine_compound` reconstruction defect, not a deblock
4482+ // interaction. DRL/assign_compound_mv/dist_wtd_comp_weight_assign
4483+ // stay cross-checked bit-for-bit against libaom decodemv.c/
4484+ // reconinter.c (r16). Root cause still not isolated within this
4485+ // arithmetic; refuse by name rather than ship a non-pixel-exact
4486+ // compound blend. Ceiling: r13/r14's MC plumbing above this line
4487+ // stays -- only the plain-average reconstruct is masked off
4488+ // again. Upgrade: bisect predict_compound_intermediate itself
4489+ // (subpel filter taps / rounding) against the pinned fixture's
4490+ // 3rd frame, quadrant rows 32-63 cols 32-63.
4491+ return Err(unsupported(
4492+ "a COMPOUND_REFERENCE block using the plain/distance-weighted \
4493+ average blend (comp_group_idx == 0) -- proven non-pixel-exact \
4494+ against a real aomenc stream (lane-av1comp r16, see \
4495+ av1comp-r16-compound-mismatch.obu)",
4496+ ));
4497+ #[allow(unreachable_code)]
4498+ let (fwd_offset, bck_offset, compound_idx) = if !skip_mode && enable_jnt_comp {
4499+ let idx_ctx = get_comp_index_context(
4500+ neighbours,
4501+ at,
4502+ side,
4503+ order_hint_bits,
4504+ order_hint,
4505+ ref_order_hints[(ref0 - LAST_FRAME) as usize],
4506+ ref_order_hints[(ref1 - LAST_FRAME) as usize],
4507+ );
4508+ let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
4509+ if idx == 1 {
4510+ (8, 8, 1u8)
39444511 } else {
3945- // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
3946- // at 1): read at most two more `drl_mode` bits, one per stack
3947- // entry past the second, stopping at the first `0`.
3948- // `drl_ctx[idx]` is the context between `entries[idx]` and
3949- // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
3950- // exactly the pair this index is choosing between.
3951- let mut idx = 1usize;
3952- while idx < 3 && stack.entries.len() > idx + 1 {
3953- if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
3954- break;
3955- }
3956- idx += 1;
3957- }
3958- stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
4512+ let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
4513+ order_hint_bits,
4514+ order_hint,
4515+ ref_order_hints[(ref0 - LAST_FRAME) as usize],
4516+ ref_order_hints[(ref1 - LAST_FRAME) as usize],
4517+ );
4518+ (fwd, bck, 0u8)
39594519 }
4520+ } else {
4521+ (8, 8, 1u8)
39604522 };
3961- (mv, false)
3962- };
3963- // spec `get_ref_filter_type`: a neighbour's own filter only feeds
3964- // this block's switchable_interp context when that neighbour coded
3965- // the SAME reference frame this block is about to read -- a
3966- // different-ref neighbour reads as "no neighbour" ([3, 3], the
3967- // sentinel `Neighbours::new` already seeds unset slots with),
3968- // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
3969- // block next to a LAST_FRAME one inherits that neighbour's filter
3970- // choice into its own context, corrupting the symbol it reads.
3971- let above_filter_ctx = if neighbours.above_ref[c] == ref_frame {
3972- neighbours.above_filter[c]
3973- } else {
3974- [3, 3]
3975- };
3976- let left_filter_ctx = if neighbours.left_ref[r] == ref_frame {
3977- neighbours.left_filter[r]
3978- } else {
3979- [3, 3]
3980- };
3981- let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
3982- dec,
3983- cdfs,
3984- interp_fixed,
3985- enable_dual_filter,
3986- is_globalmv,
3987- above_filter_ctx,
3988- left_filter_ctx,
3989- );
3990- block_filter = resolved_filter;
3991- globalmv_for_lf = is_globalmv;
3992- if std::env::var_os("EC_AV1_TRACE").is_some() {
3993- eprintln!(
3994- "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={:?}",
3995- skip as u8, mv.0, mv.1, block_filter
4523+ compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
4524+
4525+ let mut inter0_y = vec![0i32; side * side];
4526+ mc::predict_compound_intermediate(
4527+ &py0.data,
4528+ py0.width,
4529+ py0.true_width,
4530+ py0.true_height,
4531+ mv_to_q4(px, mv0.1, true),
4532+ mv_to_q4(py, mv0.0, true),
4533+ side,
4534+ side,
4535+ h_filter,
4536+ v_filter,
4537+ &mut inter0_y,
39964538 );
3997- }
3998- for dr in 0..bw4 {
3999- for dc in 0..bw4 {
4000- grid.set(
4001- mi_row + dr,
4002- mi_col + dc,
4003- MiInfo {
4004- is_inter: true,
4005- ref_frame,
4006- mv,
4007- is_new_mv,
4008- size: bw4,
4009- },
4010- );
4011- }
4012- }
4013- mode_for_tx = 0;
4014-
4015- let mut pred_y = vec![0u8; side * side];
4016- mc::predict_with_filters(
4017- &py_ref.data,
4018- py_ref.width,
4019- py_ref.true_width,
4020- py_ref.true_height,
4021- mv_to_q4(px, mv.1, true),
4022- mv_to_q4(py, mv.0, true),
4023- side,
4024- side,
4025- h_filter,
4026- v_filter,
4027- &mut pred_y,
4028- );
4029- let mut pred_u = vec![0u8; chroma_side * chroma_side];
4030- mc::predict_with_filters(
4031- &pu_ref.data,
4032- pu_ref.width,
4033- pu_ref.true_width,
4034- pu_ref.true_height,
4035- mv_to_q4(cpx, mv.1, false),
4036- mv_to_q4(cpy, mv.0, false),
4037- chroma_side,
4038- chroma_side,
4039- h_filter,
4040- v_filter,
4041- &mut pred_u,
4042- );
4043- let mut pred_v = vec![0u8; chroma_side * chroma_side];
4044- mc::predict_with_filters(
4045- &pv_ref.data,
4046- pv_ref.width,
4047- pv_ref.true_width,
4048- pv_ref.true_height,
4049- mv_to_q4(cpx, mv.1, false),
4050- mv_to_q4(cpy, mv.0, false),
4051- chroma_side,
4052- chroma_side,
4053- h_filter,
4054- v_filter,
4055- &mut pred_v,
4056- );
4057-
4058- if skip {
4059- y.reconstruct_mc(px, py, side, &pred_y, &vec![0i32; side * side]);
4060- u.reconstruct_mc(
4061- cpx,
4062- cpy,
4539+ let mut inter1_y = vec![0i32; side * side];
4540+ mc::predict_compound_intermediate(
4541+ &py1.data,
4542+ py1.width,
4543+ py1.true_width,
4544+ py1.true_height,
4545+ mv_to_q4(px, mv1.1, true),
4546+ mv_to_q4(py, mv1.0, true),
4547+ side,
4548+ side,
4549+ h_filter,
4550+ v_filter,
4551+ &mut inter1_y,
4552+ );
4553+ let mut pred_y = vec![0u8; side * side];
4554+ mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
4555+
4556+ let mut inter0_u = vec![0i32; chroma_side * chroma_side];
4557+ mc::predict_compound_intermediate(
4558+ &pu0.data,
4559+ pu0.width,
4560+ pu0.true_width,
4561+ pu0.true_height,
4562+ mv_to_q4(cpx, mv0.1, false),
4563+ mv_to_q4(cpy, mv0.0, false),
40634564 chroma_side,
4064- &pred_u,
4065- &vec![0i32; chroma_side * chroma_side],
4565+ chroma_side,
4566+ h_filter,
4567+ v_filter,
4568+ &mut inter0_u,
40664569 );
4067- v.reconstruct_mc(
4068- cpx,
4069- cpy,
4570+ let mut inter1_u = vec![0i32; chroma_side * chroma_side];
4571+ mc::predict_compound_intermediate(
4572+ &pu1.data,
4573+ pu1.width,
4574+ pu1.true_width,
4575+ pu1.true_height,
4576+ mv_to_q4(cpx, mv1.1, false),
4577+ mv_to_q4(cpy, mv1.0, false),
40704578 chroma_side,
4071- &pred_v,
4072- &vec![0i32; chroma_side * chroma_side],
4579+ chroma_side,
4580+ h_filter,
4581+ v_filter,
4582+ &mut inter1_u,
40734583 );
4074- luma_grid = vec![0i32; side * side];
4075- u_grid = vec![0i32; chroma_side * chroma_side];
4076- v_grid = vec![0i32; chroma_side * chroma_side];
4584+ let mut pred_u = vec![0u8; chroma_side * chroma_side];
4585+ mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
4586+
4587+ let mut inter0_v = vec![0i32; chroma_side * chroma_side];
4588+ mc::predict_compound_intermediate(
4589+ &pv0.data,
4590+ pv0.width,
4591+ pv0.true_width,
4592+ pv0.true_height,
4593+ mv_to_q4(cpx, mv0.1, false),
4594+ mv_to_q4(cpy, mv0.0, false),
4595+ chroma_side,
4596+ chroma_side,
4597+ h_filter,
4598+ v_filter,
4599+ &mut inter0_v,
4600+ );
4601+ let mut inter1_v = vec![0i32; chroma_side * chroma_side];
4602+ mc::predict_compound_intermediate(
4603+ &pv1.data,
4604+ pv1.width,
4605+ pv1.true_width,
4606+ pv1.true_height,
4607+ mv_to_q4(cpx, mv1.1, false),
4608+ mv_to_q4(cpy, mv1.0, false),
4609+ chroma_side,
4610+ chroma_side,
4611+ h_filter,
4612+ v_filter,
4613+ &mut inter1_v,
4614+ );
4615+ let mut pred_v = vec![0u8; chroma_side * chroma_side];
4616+ mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
4617+
4618+ if skip {
4619+ y.reconstruct_mc(px, py, side, &pred_y, &vec![0i32; side * side]);
4620+ u.reconstruct_mc(
4621+ cpx,
4622+ cpy,
4623+ chroma_side,
4624+ &pred_u,
4625+ &vec![0i32; chroma_side * chroma_side],
4626+ );
4627+ v.reconstruct_mc(
4628+ cpx,
4629+ cpy,
4630+ chroma_side,
4631+ &pred_v,
4632+ &vec![0i32; chroma_side * chroma_side],
4633+ );
4634+ luma_grid = vec![0i32; side * side];
4635+ u_grid = vec![0i32; chroma_side * chroma_side];
4636+ v_grid = vec![0i32; chroma_side * chroma_side];
4637+ } else {
4638+ let around = neighbours.around(at, side);
4639+ luma_grid = read_inter_plane(
4640+ dec,
4641+ cdfs,
4642+ luma_set_inter,
4643+ scan_luma,
4644+ 0,
4645+ around[0],
4646+ mode_for_tx,
4647+ y,
4648+ px,
4649+ py,
4650+ side,
4651+ base_q_idx,
4652+ &pred_y,
4653+ )?;
4654+ u_grid = read_inter_plane(
4655+ dec,
4656+ cdfs,
4657+ chroma_set,
4658+ scan_chroma,
4659+ 1,
4660+ around[1],
4661+ mode_for_tx,
4662+ u,
4663+ cpx,
4664+ cpy,
4665+ chroma_side,
4666+ base_q_idx,
4667+ &pred_u,
4668+ )?;
4669+ v_grid = read_inter_plane(
4670+ dec,
4671+ cdfs,
4672+ chroma_set,
4673+ scan_chroma,
4674+ 2,
4675+ around[2],
4676+ mode_for_tx,
4677+ v,
4678+ cpx,
4679+ cpy,
4680+ chroma_side,
4681+ base_q_idx,
4682+ &pred_v,
4683+ )?;
4684+ }
40774685 } else {
4078- let around = neighbours.around(at, side);
4079- luma_grid = read_inter_plane(
4686+ let ref_frame =
4687+ read_single_ref(dec, cdfs, neighbours.above_ref[c], neighbours.left_ref[r]);
4688+ ref_frame_for_lf = ref_frame;
4689+ // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
4690+ // stacked defects (lf_level ref/mode-delta forwarding, the
4691+ // switchable_interp ref-frame ctx gate, and a film-grain synthesis
4692+ // gap that looked like a GOLDEN MC bug by survivor bias -- see the
4693+ // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
4694+ // below same as every other non-`LAST_FRAME` reference. lane-av1refs
4695+ // widens this from GOLDEN alone to every reference `read_single_ref`
4696+ // can name.
4697+ let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
4698+ (ref_y, ref_u, ref_v)
4699+ } else {
4700+ match other_refs[ref_frame as usize] {
4701+ Some((ry, ru, rv)) => (ry, ru, rv),
4702+ None => {
4703+ return Err(unsupported(
4704+ "a reference frame selected with no picture at this frame's own \
4705+ ref_frame_idx slot for it",
4706+ ));
4707+ }
4708+ }
4709+ };
4710+
4711+ let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
4712+ let bw4 = side / 4;
4713+ // spec 7.10.2.8: only reached when the frame header set
4714+ // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
4715+ // otherwise) -- `cur_offset_0` is this query block's own resolved
4716+ // `ref_frame`'s distance from the current frame (spec 7.9.3),
4717+ // recomputed per block since different blocks pick different refs.
4718+ let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
4719+ field: t.field,
4720+ cur_offset_0: crate::motion_field::get_relative_dist(
4721+ t.order_hint_bits,
4722+ t.order_hint,
4723+ t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
4724+ ),
4725+ allow_high_precision_mv,
4726+ });
4727+ let stack = find_mv_stack_with_sign_bias(
4728+ grid,
4729+ mi_row,
4730+ mi_col,
4731+ bw4,
4732+ bw4,
4733+ ref_frame,
4734+ mi_cols as usize,
4735+ mi_rows as usize,
4736+ sign_bias_table,
4737+ tpl,
4738+ );
4739+ let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
4740+ let mut is_globalmv = false;
4741+ let (mv, is_new_mv) = if !not_new {
4742+ // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
4743+ // read at most two `drl_mode` bits, one per stack entry past the
4744+ // first, stopping at the first `0`. The chosen index selects
4745+ // which stack entry `read_mv`'s base predictor comes from
4746+ // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
4747+ // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
4748+ let mut idx = 0usize;
4749+ while idx < 2 && stack.entries.len() > idx + 1 {
4750+ if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
4751+ break;
4752+ }
4753+ idx += 1;
4754+ }
4755+ let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
4756+ (
4757+ read_mv(
4758+ dec,
4759+ &mut cdfs.mv_comp,
4760+ &mut cdfs.mv_joint,
4761+ base_mv,
4762+ allow_high_precision_mv,
4763+ ),
4764+ true,
4765+ )
4766+ } else {
4767+ let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
4768+ is_globalmv = !not_zero;
4769+ let mv = if !not_zero {
4770+ // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1) under the
4771+ // `GmType::IDENTITY` this crate's `decode_stream` requires of
4772+ // every inter frame's `LAST_FRAME` entry (any other warp
4773+ // model is refused before the tile decoder is ever called).
4774+ (0, 0)
4775+ } else {
4776+ let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
4777+ if nearest {
4778+ stack.nearest_mv
4779+ } else {
4780+ // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
4781+ // at 1): read at most two more `drl_mode` bits, one per stack
4782+ // entry past the second, stopping at the first `0`.
4783+ // `drl_ctx[idx]` is the context between `entries[idx]` and
4784+ // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
4785+ // exactly the pair this index is choosing between.
4786+ let mut idx = 1usize;
4787+ while idx < 3 && stack.entries.len() > idx + 1 {
4788+ if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
4789+ break;
4790+ }
4791+ idx += 1;
4792+ }
4793+ stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
4794+ }
4795+ };
4796+ (mv, false)
4797+ };
4798+ // spec `get_ref_filter_type`: a neighbour's own filter only feeds
4799+ // this block's switchable_interp context when that neighbour coded
4800+ // the SAME reference frame this block is about to read -- a
4801+ // different-ref neighbour reads as "no neighbour" ([3, 3], the
4802+ // sentinel `Neighbours::new` already seeds unset slots with),
4803+ // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
4804+ // block next to a LAST_FRAME one inherits that neighbour's filter
4805+ // choice into its own context, corrupting the symbol it reads.
4806+ let above_filter_ctx = if neighbours.above_ref[c] == ref_frame {
4807+ neighbours.above_filter[c]
4808+ } else {
4809+ [3, 3]
4810+ };
4811+ let left_filter_ctx = if neighbours.left_ref[r] == ref_frame {
4812+ neighbours.left_filter[r]
4813+ } else {
4814+ [3, 3]
4815+ };
4816+ let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
40804817 dec,
40814818 cdfs,
4082- luma_set_inter,
4083- scan_luma,
4084- 0,
4085- around[0],
4086- mode_for_tx,
4087- y,
4088- px,
4089- py,
4819+ interp_fixed,
4820+ enable_dual_filter,
4821+ is_globalmv,
4822+ above_filter_ctx,
4823+ left_filter_ctx,
4824+ );
4825+ block_filter = resolved_filter;
4826+ globalmv_for_lf = is_globalmv;
4827+ if std::env::var_os("EC_AV1_TRACE").is_some() {
4828+ eprintln!(
4829+ "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={:?}",
4830+ skip as u8, mv.0, mv.1, block_filter
4831+ );
4832+ }
4833+ for dr in 0..bw4 {
4834+ for dc in 0..bw4 {
4835+ grid.set(
4836+ mi_row + dr,
4837+ mi_col + dc,
4838+ MiInfo {
4839+ is_inter: true,
4840+ ref_frame,
4841+ ref_frame1: None,
4842+ mv1: None,
4843+ mv,
4844+ is_new_mv,
4845+ size: bw4,
4846+ },
4847+ );
4848+ }
4849+ }
4850+ mode_for_tx = 0;
4851+
4852+ let mut pred_y = vec![0u8; side * side];
4853+ mc::predict_with_filters(
4854+ &py_ref.data,
4855+ py_ref.width,
4856+ py_ref.true_width,
4857+ py_ref.true_height,
4858+ mv_to_q4(px, mv.1, true),
4859+ mv_to_q4(py, mv.0, true),
40904860 side,
4091- base_q_idx,
4092- &pred_y,
4093- )?;
4094- u_grid = read_inter_plane(
4095- dec,
4096- cdfs,
4097- chroma_set,
4098- scan_chroma,
4099- 1,
4100- around[1],
4101- mode_for_tx,
4102- u,
4103- cpx,
4104- cpy,
4861+ side,
4862+ h_filter,
4863+ v_filter,
4864+ &mut pred_y,
4865+ );
4866+ let mut pred_u = vec![0u8; chroma_side * chroma_side];
4867+ mc::predict_with_filters(
4868+ &pu_ref.data,
4869+ pu_ref.width,
4870+ pu_ref.true_width,
4871+ pu_ref.true_height,
4872+ mv_to_q4(cpx, mv.1, false),
4873+ mv_to_q4(cpy, mv.0, false),
41054874 chroma_side,
4106- base_q_idx,
4107- &pred_u,
4108- )?;
4109- v_grid = read_inter_plane(
4110- dec,
4111- cdfs,
4112- chroma_set,
4113- scan_chroma,
4114- 2,
4115- around[2],
4116- mode_for_tx,
4117- v,
4118- cpx,
4119- cpy,
41204875 chroma_side,
4121- base_q_idx,
4122- &pred_v,
4123- )?;
4876+ h_filter,
4877+ v_filter,
4878+ &mut pred_u,
4879+ );
4880+ let mut pred_v = vec![0u8; chroma_side * chroma_side];
4881+ mc::predict_with_filters(
4882+ &pv_ref.data,
4883+ pv_ref.width,
4884+ pv_ref.true_width,
4885+ pv_ref.true_height,
4886+ mv_to_q4(cpx, mv.1, false),
4887+ mv_to_q4(cpy, mv.0, false),
4888+ chroma_side,
4889+ chroma_side,
4890+ h_filter,
4891+ v_filter,
4892+ &mut pred_v,
4893+ );
4894+
4895+ if skip {
4896+ y.reconstruct_mc(px, py, side, &pred_y, &vec![0i32; side * side]);
4897+ u.reconstruct_mc(
4898+ cpx,
4899+ cpy,
4900+ chroma_side,
4901+ &pred_u,
4902+ &vec![0i32; chroma_side * chroma_side],
4903+ );
4904+ v.reconstruct_mc(
4905+ cpx,
4906+ cpy,
4907+ chroma_side,
4908+ &pred_v,
4909+ &vec![0i32; chroma_side * chroma_side],
4910+ );
4911+ luma_grid = vec![0i32; side * side];
4912+ u_grid = vec![0i32; chroma_side * chroma_side];
4913+ v_grid = vec![0i32; chroma_side * chroma_side];
4914+ } else {
4915+ let around = neighbours.around(at, side);
4916+ luma_grid = read_inter_plane(
4917+ dec,
4918+ cdfs,
4919+ luma_set_inter,
4920+ scan_luma,
4921+ 0,
4922+ around[0],
4923+ mode_for_tx,
4924+ y,
4925+ px,
4926+ py,
4927+ side,
4928+ base_q_idx,
4929+ &pred_y,
4930+ )?;
4931+ u_grid = read_inter_plane(
4932+ dec,
4933+ cdfs,
4934+ chroma_set,
4935+ scan_chroma,
4936+ 1,
4937+ around[1],
4938+ mode_for_tx,
4939+ u,
4940+ cpx,
4941+ cpy,
4942+ chroma_side,
4943+ base_q_idx,
4944+ &pred_u,
4945+ )?;
4946+ v_grid = read_inter_plane(
4947+ dec,
4948+ cdfs,
4949+ chroma_set,
4950+ scan_chroma,
4951+ 2,
4952+ around[2],
4953+ mode_for_tx,
4954+ v,
4955+ cpx,
4956+ cpy,
4957+ chroma_side,
4958+ base_q_idx,
4959+ &pred_v,
4960+ )?;
4961+ }
41244962 }
41254963 } else {
41264964 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
@@ -4158,6 +4996,8 @@ fn decode_inter_block(
41584996 MiInfo {
41594997 is_inter: false,
41604998 ref_frame: -1,
4999+ ref_frame1: None,
5000+ mv1: None,
41615001 mv: (0, 0),
41625002 is_new_mv: false,
41635003 size: side / 4,
@@ -4274,7 +5114,10 @@ fn decode_inter_block(
42745114 }
42755115 }
42765116 neighbours.record(at, side, mode_for_tx, &[luma_grid, u_grid, v_grid]);
4277- neighbours.record_inter(at, side, skip, is_inter, ref_frame_for_lf, block_filter);
5117+ neighbours.record_inter(at, side, skip, is_inter, ref_frame_for_lf, block_filter, skip_mode);
5118+ if let Some((ref1, group_idx, idx)) = compound_ctx {
5119+ neighbours.record_compound_ctx(at, side, ref1, group_idx, idx);
5120+ }
42785121 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
42795122 neighbours.fill_lf_grid(
42805123 (r * (SUB / MI), c * (SUB / MI)),
@@ -4321,12 +5164,37 @@ fn decode_inter_block8(
43215164 ref_y: &PlaneBuf,
43225165 ref_u: &PlaneBuf,
43235166 ref_v: &PlaneBuf,
5167+ other_refs: &RefSlots,
43245168 base_q_idx: u8,
43255169 scan8: &[u16],
43265170 scan4: &[u16],
43275171 prev_leaf: Option<((usize, usize), bool, bool)>,
43285172 allow_high_precision_mv: bool,
4329-) -> Result<(bool, bool)> {
5173+ // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
5174+ // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
5175+ // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
5176+ // context uses that same approximation.
5177+ reference_select: bool,
5178+ enable_masked_compound: bool,
5179+ enable_jnt_comp: bool,
5180+ order_hint_bits: u32,
5181+ order_hint: u32,
5182+ ref_order_hints: [u32; 7],
5183+ // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
5184+ // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
5185+ // so its `skip_mode` context reuses the same [`SUB`]-grid
5186+ // `above_skip_mode[c]`/`left_skip_mode[r]` the enclosing 16x16 slot
5187+ // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
5188+ // just above).
5189+ skip_mode_present: bool,
5190+ skip_mode_frame: [u8; 2],
5191+ // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
5192+ // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
5193+ // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
5194+ // `compound_ctx` local, just handed back instead of applied here (this
5195+ // fn's `neighbours` recording happens once for the whole straddling
5196+ // 16x16 block, after every leaf).
5197+) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>)> {
43305198 const LAST_FRAME: i8 = 1;
43315199 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
43325200 const SIZE_GROUP_8: usize = 1;
@@ -4350,16 +5218,344 @@ fn decode_inter_block8(
43505218 left_inter = pinter;
43515219 }
43525220 }
5221+ let skip_mode_ctx =
5222+ usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
5223+ let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
5224+ if skip_mode {
5225+ SKIP_MODE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5226+ }
5227+
43535228 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
4354- let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
5229+ let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
43555230
43565231 let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);
43575232 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
4358- let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
5233+ let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
43595234
43605235 let mode_for_tx;
43615236 let (luma_grid, u_grid, v_grid);
5237+ let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
43625238 if is_inter {
5239+ if reference_select || skip_mode {
5240+ let above_nbr = has_above.then(|| NeighbourRef {
5241+ is_inter: above_inter,
5242+ ref0: if above_inter { LAST_FRAME } else { 0 },
5243+ ref1: None,
5244+ uni: false,
5245+ });
5246+ let left_nbr = has_left.then(|| NeighbourRef {
5247+ is_inter: left_inter,
5248+ ref0: if left_inter { LAST_FRAME } else { 0 },
5249+ ref1: None,
5250+ uni: false,
5251+ });
5252+ if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
5253+ let (ref0, ref1) = if skip_mode {
5254+ (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
5255+ } else {
5256+ read_compound_ref_frames(
5257+ dec,
5258+ cdfs,
5259+ above_nbr,
5260+ left_nbr,
5261+ if has_above && above_inter {
5262+ LAST_FRAME
5263+ } else {
5264+ -1
5265+ },
5266+ if has_left && left_inter {
5267+ LAST_FRAME
5268+ } else {
5269+ -1
5270+ },
5271+ )
5272+ };
5273+ let (mi_row, mi_col) = leaf_mi;
5274+ // lane-av1comp: this leaf path has neither a real sign-bias
5275+ // table nor `tpl_frame` (see this function's own doc on the
5276+ // coarse `LAST_FRAME`-or-intra neighbour approximation
5277+ // already in force above), matching the plain `find_mv_stack`
5278+ // (no bias, no tpl) the leaf's single-ref arm below already
5279+ // uses.
5280+ let comp_stack = crate::mvstack::find_mv_stack_compound(
5281+ grid,
5282+ mi_row,
5283+ mi_col,
5284+ 2,
5285+ 2,
5286+ (ref0, ref1),
5287+ mi_cols as usize,
5288+ mi_rows as usize,
5289+ &NO_SIGN_BIAS,
5290+ None,
5291+ );
5292+ let compound_mode = if skip_mode {
5293+ 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
5294+ } else {
5295+ read_inter_compound_mode(
5296+ dec,
5297+ cdfs,
5298+ comp_stack.new_mv_ctx,
5299+ comp_stack.ref_mv_ctx,
5300+ )
5301+ };
5302+ let (mv0, mv1) = assign_compound_mv(
5303+ dec,
5304+ cdfs,
5305+ &comp_stack,
5306+ compound_mode,
5307+ allow_high_precision_mv,
5308+ );
5309+
5310+ // spec 5.11.25: same gating [`decode_inter_block`]'s own
5311+ // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
5312+ // slot -- the only granularity `Neighbours`' comp_group_idx/
5313+ // compound_idx arrays track.
5314+ let group_ctx = get_comp_group_idx_context(neighbours, outer_at, SIDE);
5315+ let comp_group_idx = if !skip_mode
5316+ && enable_masked_compound
5317+ && is_any_masked_compound_used_here(SIDE)
5318+ {
5319+ dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
5320+ } else {
5321+ 0
5322+ };
5323+ if comp_group_idx == 1 {
5324+ return Err(unsupported(
5325+ "a masked COMPOUND_REFERENCE 8x8 leaf (comp_group_idx == 1, wedge/\
5326+ diffwtd) -- this decoder's compound blend is the plain distance-\
5327+ weighted/simple-average combine only, lane-av1comp",
5328+ ));
5329+ }
5330+ // corner-cut (lane-av1comp r16/r17): same non-pixel-exact
5331+ // plain-average reconstruction defect as the 16x16 leaf's
5332+ // own mask above (r17: falsified as loop-filter-shaped,
5333+ // isolated to predict_compound_intermediate/combine_compound
5334+ // itself) -- see that comment.
5335+ return Err(unsupported(
5336+ "a COMPOUND_REFERENCE 8x8 leaf using the plain/distance-weighted \
5337+ average blend (comp_group_idx == 0) -- proven non-pixel-exact \
5338+ against a real aomenc stream (lane-av1comp r16, see \
5339+ av1comp-r16-compound-mismatch.obu)",
5340+ ));
5341+ #[allow(unreachable_code)]
5342+ let (fwd_offset, bck_offset, compound_idx) = if !skip_mode && enable_jnt_comp {
5343+ let idx_ctx = get_comp_index_context(
5344+ neighbours,
5345+ outer_at,
5346+ SIDE,
5347+ order_hint_bits,
5348+ order_hint,
5349+ ref_order_hints[(ref0 - LAST_FRAME) as usize],
5350+ ref_order_hints[(ref1 - LAST_FRAME) as usize],
5351+ );
5352+ let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
5353+ if idx == 1 {
5354+ (8, 8, 1u8)
5355+ } else {
5356+ let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
5357+ order_hint_bits,
5358+ order_hint,
5359+ ref_order_hints[(ref0 - LAST_FRAME) as usize],
5360+ ref_order_hints[(ref1 - LAST_FRAME) as usize],
5361+ );
5362+ (fwd, bck, 0u8)
5363+ }
5364+ } else {
5365+ (8, 8, 1u8)
5366+ };
5367+ compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
5368+
5369+ let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
5370+ let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
5371+
5372+ for dr in 0..2 {
5373+ for dc in 0..2 {
5374+ grid.set(
5375+ mi_row + dr,
5376+ mi_col + dc,
5377+ MiInfo {
5378+ is_inter: true,
5379+ ref_frame: ref0,
5380+ ref_frame1: Some(ref1),
5381+ mv1: Some(mv1),
5382+ mv: mv0,
5383+ is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
5384+ size: 2,
5385+ },
5386+ );
5387+ }
5388+ }
5389+ mode_for_tx = 0;
5390+
5391+ // lane-av1comp corner-cut, matching this leaf's single-ref
5392+ // arm below (`mc::predict`'s own fixed-Regular default):
5393+ // `decode_inter_block8` never resolves a switchable filter,
5394+ // so both compound taps use `Regular` too.
5395+ use mc::InterpFilterKind::Regular;
5396+ let mut inter0_y = vec![0i32; SIDE * SIDE];
5397+ mc::predict_compound_intermediate(
5398+ &py0.data,
5399+ py0.width,
5400+ py0.true_width,
5401+ py0.true_height,
5402+ mv_to_q4(px, mv0.1, true),
5403+ mv_to_q4(py, mv0.0, true),
5404+ SIDE,
5405+ SIDE,
5406+ Regular,
5407+ Regular,
5408+ &mut inter0_y,
5409+ );
5410+ let mut inter1_y = vec![0i32; SIDE * SIDE];
5411+ mc::predict_compound_intermediate(
5412+ &py1.data,
5413+ py1.width,
5414+ py1.true_width,
5415+ py1.true_height,
5416+ mv_to_q4(px, mv1.1, true),
5417+ mv_to_q4(py, mv1.0, true),
5418+ SIDE,
5419+ SIDE,
5420+ Regular,
5421+ Regular,
5422+ &mut inter1_y,
5423+ );
5424+ let mut pred_y = vec![0u8; SIDE * SIDE];
5425+ mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
5426+
5427+ let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5428+ mc::predict_compound_intermediate(
5429+ &pu0.data,
5430+ pu0.width,
5431+ pu0.true_width,
5432+ pu0.true_height,
5433+ mv_to_q4(cpx, mv0.1, false),
5434+ mv_to_q4(cpy, mv0.0, false),
5435+ CHROMA_SIDE,
5436+ CHROMA_SIDE,
5437+ Regular,
5438+ Regular,
5439+ &mut inter0_u,
5440+ );
5441+ let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5442+ mc::predict_compound_intermediate(
5443+ &pu1.data,
5444+ pu1.width,
5445+ pu1.true_width,
5446+ pu1.true_height,
5447+ mv_to_q4(cpx, mv1.1, false),
5448+ mv_to_q4(cpy, mv1.0, false),
5449+ CHROMA_SIDE,
5450+ CHROMA_SIDE,
5451+ Regular,
5452+ Regular,
5453+ &mut inter1_u,
5454+ );
5455+ let mut pred_u = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
5456+ mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
5457+
5458+ let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5459+ mc::predict_compound_intermediate(
5460+ &pv0.data,
5461+ pv0.width,
5462+ pv0.true_width,
5463+ pv0.true_height,
5464+ mv_to_q4(cpx, mv0.1, false),
5465+ mv_to_q4(cpy, mv0.0, false),
5466+ CHROMA_SIDE,
5467+ CHROMA_SIDE,
5468+ Regular,
5469+ Regular,
5470+ &mut inter0_v,
5471+ );
5472+ let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5473+ mc::predict_compound_intermediate(
5474+ &pv1.data,
5475+ pv1.width,
5476+ pv1.true_width,
5477+ pv1.true_height,
5478+ mv_to_q4(cpx, mv1.1, false),
5479+ mv_to_q4(cpy, mv1.0, false),
5480+ CHROMA_SIDE,
5481+ CHROMA_SIDE,
5482+ Regular,
5483+ Regular,
5484+ &mut inter1_v,
5485+ );
5486+ let mut pred_v = vec![0u8; CHROMA_SIDE * CHROMA_SIDE];
5487+ mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
5488+
5489+ if skip {
5490+ y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
5491+ u.reconstruct_mc(
5492+ cpx,
5493+ cpy,
5494+ CHROMA_SIDE,
5495+ &pred_u,
5496+ &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
5497+ );
5498+ v.reconstruct_mc(
5499+ cpx,
5500+ cpy,
5501+ CHROMA_SIDE,
5502+ &pred_v,
5503+ &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
5504+ );
5505+ luma_grid = vec![0i32; SIDE * SIDE];
5506+ u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5507+ v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
5508+ } else {
5509+ let around = neighbours.around_mi(leaf_mi, 8);
5510+ luma_grid = read_inter_plane(
5511+ dec,
5512+ cdfs,
5513+ TxbSet::Luma8Inter,
5514+ scan8,
5515+ 0,
5516+ around[0],
5517+ mode_for_tx,
5518+ y,
5519+ px,
5520+ py,
5521+ SIDE,
5522+ base_q_idx,
5523+ &pred_y,
5524+ )?;
5525+ u_grid = read_inter_plane(
5526+ dec,
5527+ cdfs,
5528+ TxbSet::Chroma4,
5529+ scan4,
5530+ 1,
5531+ around[1],
5532+ mode_for_tx,
5533+ u,
5534+ cpx,
5535+ cpy,
5536+ CHROMA_SIDE,
5537+ base_q_idx,
5538+ &pred_u,
5539+ )?;
5540+ v_grid = read_inter_plane(
5541+ dec,
5542+ cdfs,
5543+ TxbSet::Chroma4,
5544+ scan4,
5545+ 2,
5546+ around[2],
5547+ mode_for_tx,
5548+ v,
5549+ cpx,
5550+ cpy,
5551+ CHROMA_SIDE,
5552+ base_q_idx,
5553+ &pred_v,
5554+ )?;
5555+ }
5556+ return Ok((skip, is_inter, skip_mode, compound_ctx8));
5557+ }
5558+ }
43635559 let sr_ctx = single_ref_ctx(above_inter || left_inter);
43645560 let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]);
43655561 let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]);
@@ -4436,6 +5632,8 @@ fn decode_inter_block8(
44365632 MiInfo {
44375633 is_inter: true,
44385634 ref_frame: LAST_FRAME,
5635+ ref_frame1: None,
5636+ mv1: None,
44395637 mv,
44405638 is_new_mv,
44415639 size: 2,
@@ -4580,6 +5778,8 @@ fn decode_inter_block8(
45805778 MiInfo {
45815779 is_inter: false,
45825780 ref_frame: -1,
5781+ ref_frame1: None,
5782+ mv1: None,
45835783 mv: (0, 0),
45845784 is_new_mv: false,
45855785 size: 2,
@@ -4695,7 +5895,7 @@ fn decode_inter_block8(
46955895 }
46965896 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
46975897 neighbours.fill_lf_grid(leaf_mi, 2, 8, if is_inter { LAST_FRAME } else { 0 });
4698- Ok((skip, is_inter))
5898+ Ok((skip, is_inter, skip_mode, compound_ctx8))
46995899 }
47005900
47015901 /// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
@@ -4725,6 +5925,7 @@ pub fn decode_inter_frame_tile(
47255925 allow_high_precision_mv: bool,
47265926 interp_fixed: Option<mc::InterpFilterKind>,
47275927 enable_dual_filter: bool,
5928+ reference_select: bool,
47285929 ) -> Result<Picture> {
47295930 decode_inter_frame_tile_with_cdfs(
47305931 data,
@@ -4746,6 +5947,11 @@ pub fn decode_inter_frame_tile(
47465947 0,
47475948 [0; 7],
47485949 None,
5950+ reference_select,
5951+ false,
5952+ false,
5953+ false,
5954+ [0; 2],
47495955 )
47505956 .map(|(picture, _, _)| picture)
47515957 }
@@ -4780,6 +5986,17 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
47805986 order_hint: u32,
47815987 ref_order_hints: [u32; 7],
47825988 tpl_field: Option<&crate::motion_field::TplField>,
5989+ // lane-av1comp: this frame header's own `reference_select` bit, threaded
5990+ // to every `decode_inter_block`/`decode_inter_block8` call below.
5991+ reference_select: bool,
5992+ // lane-av1comp: `seq_params`' own compound-blend enable bits.
5993+ enable_masked_compound: bool,
5994+ enable_jnt_comp: bool,
5995+ // lane-av1comp round 14: this frame header's own `skip_mode_present`/
5996+ // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
5997+ // `decode_inter_block8` call below.
5998+ skip_mode_present: bool,
5999+ skip_mode_frame: [u8; 2],
47836000 ) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
47846001 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
47856002 field,
@@ -4976,6 +6193,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
49766193 interp_fixed,
49776194 enable_dual_filter,
49786195 tpl_frame.as_ref(),
6196+ reference_select,
6197+ enable_masked_compound,
6198+ enable_jnt_comp,
6199+ order_hint_bits,
6200+ order_hint,
6201+ ref_order_hints,
6202+ skip_mode_present,
6203+ skip_mode_frame,
49796204 )?;
49806205 }
49816206 PARTITION_SPLIT => {
@@ -5034,6 +6259,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
50346259 interp_fixed,
50356260 enable_dual_filter,
50366261 tpl_frame.as_ref(),
6262+ reference_select,
6263+ enable_masked_compound,
6264+ enable_jnt_comp,
6265+ order_hint_bits,
6266+ order_hint,
6267+ ref_order_hints,
6268+ skip_mode_present,
6269+ skip_mode_frame,
50376270 )?;
50386271 } else {
50396272 let ctx16 = neighbours.partition_ctx(at16, SUB);
@@ -5054,6 +6287,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
50546287 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
50556288 .collect();
50566289 let mut prev_leaf: Option<((usize, usize), bool, bool)> = None;
6290+ let mut last_compound_ctx: Option<(i8, i8, u8, u8)> = None;
6291+ let mut last_skip_mode = false;
50576292 for (mr, mc) in leaf_positions {
50586293 let leaf_mi = (mr as usize, mc as usize);
50596294 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
@@ -5063,28 +6298,42 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
50636298 "a partition below 8x8 (this encoder never writes one)",
50646299 ));
50656300 }
5066- let (skip, is_inter) = decode_inter_block8(
5067- &mut dec,
5068- &mut cdfs,
5069- &mut neighbours,
5070- &mut grid,
5071- mi_cols,
5072- mi_rows,
5073- at16,
5074- leaf_mi,
5075- &mut y,
5076- &mut u,
5077- &mut v,
5078- &ref_y,
5079- &ref_u,
5080- &ref_v,
5081- base_q_idx,
5082- &scan8,
5083- &scan4,
5084- prev_leaf,
5085- allow_high_precision_mv,
5086- )?;
6301+ let (skip, is_inter, skip_mode_leaf, compound_ctx8) =
6302+ decode_inter_block8(
6303+ &mut dec,
6304+ &mut cdfs,
6305+ &mut neighbours,
6306+ &mut grid,
crates/ec-av1/src/encode.rsmodified+12 -0
@@ -2612,6 +2612,8 @@ pub(crate) fn encode_inter_frame(
26122612 Some(info) => MiInfo {
26132613 is_inter: true,
26142614 ref_frame: LAST_FRAME,
2615+ ref_frame1: None,
2616+ mv1: None,
26152617 mv: info.mv,
26162618 is_new_mv: matches!(info.mode, InterMode::NewMv),
26172619 size: 8,
@@ -2623,6 +2625,8 @@ pub(crate) fn encode_inter_frame(
26232625 None => MiInfo {
26242626 is_inter: false,
26252627 ref_frame: -1,
2628+ ref_frame1: None,
2629+ mv1: None,
26262630 mv: (0, 0),
26272631 is_new_mv: false,
26282632 size: 8,
@@ -2700,6 +2704,8 @@ pub(crate) fn encode_inter_frame(
27002704 Some(info) => MiInfo {
27012705 is_inter: true,
27022706 ref_frame: LAST_FRAME,
2707+ ref_frame1: None,
2708+ mv1: None,
27032709 mv: info.mv,
27042710 is_new_mv: matches!(info.mode, InterMode::NewMv),
27052711 size: 4,
@@ -2707,6 +2713,8 @@ pub(crate) fn encode_inter_frame(
27072713 None => MiInfo {
27082714 is_inter: false,
27092715 ref_frame: -1,
2716+ ref_frame1: None,
2717+ mv1: None,
27102718 mv: (0, 0),
27112719 is_new_mv: false,
27122720 size: 4,
@@ -2750,6 +2758,8 @@ pub(crate) fn encode_inter_frame(
27502758 Some(info) => MiInfo {
27512759 is_inter: true,
27522760 ref_frame: LAST_FRAME,
2761+ ref_frame1: None,
2762+ mv1: None,
27532763 mv: info.mv,
27542764 is_new_mv: matches!(
27552765 info.mode,
@@ -2760,6 +2770,8 @@ pub(crate) fn encode_inter_frame(
27602770 None => MiInfo {
27612771 is_inter: false,
27622772 ref_frame: -1,
2773+ ref_frame1: None,
2774+ mv1: None,
27632775 mv: (0, 0),
27642776 is_new_mv: false,
27652777 size: 2,
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -15,6 +15,7 @@
1515 pub mod bits;
1616 pub mod cdf;
1717 mod cdf_state;
18+mod compound;
1819 pub mod decode;
1920 pub mod encode;
2021 pub mod encoder;
crates/ec-av1/src/mc.rsmodified+148 -0
@@ -411,6 +411,154 @@ pub fn predict_with_filters(
411411 crate::encode::stage_add(1, stage_t.elapsed());
412412 }
413413
414+/// `InterRound1` for a compound ref (spec 7.11.3.2's `isCompound` branch,
415+/// `COMPOUND_ROUND1_BITS` in libaom's `convolve.h`): 4 bits shallower than
416+/// [`INTER_ROUND_1`] so the vertical pass lands in the `CONV_BUF` domain
417+/// (still above 8-bit pixel range) instead of a finished sample --
418+/// `predict_compound_intermediate` below stops there and leaves the final
419+/// clip to whichever combine step (simple/distance-weighted average, or a
420+/// future masked blend) runs on the pair of intermediates.
421+const INTER_ROUND_1_COMPOUND: u32 = 7;
422+
423+/// `InterPostRound` (spec 7.11.3.2): `2 * FILTER_BITS - (InterRound0 +
424+/// InterRound1)` with the *compound* `InterRound1` above -- `2*7 - (3+7) ==
425+/// 4`. [`combine_compound`] folds this together with `DIST_PRECISION_BITS`
426+/// (below) into one final shift.
427+const INTER_POST_ROUND: u32 = 4;
428+
429+/// `DIST_PRECISION_BITS` (spec 7.11.3.15 / libaom `enums.h`): the two
430+/// weights [`combine_compound`] takes always sum to `1 << 4 == 16`, whether
431+/// they are the simple-average split (8/8) or a distance-weighted split
432+/// from [`crate::compound::dist_wtd_comp_weight_assign`].
433+const DIST_PRECISION_BITS: u32 = 4;
434+
435+/// [`predict_with_filters`]'s compound counterpart: same two-pass separable
436+/// filter, but the vertical pass rounds by [`INTER_ROUND_1_COMPOUND`]
437+/// instead of [`INTER_ROUND_1`] and is never clipped to a pixel -- the
438+/// `CONV_BUF` intermediate domain spec 7.11.3.2 keeps a compound block's two
439+/// per-reference predictions in until [`combine_compound`] blends them.
440+/// `dst` receives one `i32` per sample, row-major, same shape as
441+/// [`predict_with_filters`]'s `u8` `dst`.
442+///
443+/// # Panics
444+/// Panics when `dst` is not `block_w * block_h` long, or the reference is
445+/// empty.
446+#[allow(clippy::too_many_arguments)]
447+pub fn predict_compound_intermediate(
448+ reference: &[u8],
449+ stride: usize,
450+ true_width: usize,
451+ true_height: usize,
452+ x_q4: i32,
453+ y_q4: i32,
454+ block_w: usize,
455+ block_h: usize,
456+ h_kind: InterpFilterKind,
457+ v_kind: InterpFilterKind,
458+ dst: &mut [i32],
459+) {
460+ assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
461+ assert!(!reference.is_empty(), "a reference plane has samples");
462+
463+ let x0 = x_q4.div_euclid(16);
464+ let xfrac = x_q4.rem_euclid(16) as usize;
465+ let y0 = y_q4.div_euclid(16);
466+ let yfrac = y_q4.rem_euclid(16) as usize;
467+
468+ let (h_wide, h_narrow) = h_kind.tables();
469+ let (v_wide, v_narrow) = v_kind.tables();
470+ let h_filter = if block_w <= 4 {
471+ &h_narrow[xfrac]
472+ } else {
473+ &h_wide[xfrac]
474+ };
475+ let v_filter = if block_h <= 4 {
476+ &v_narrow[yfrac]
477+ } else {
478+ &v_wide[yfrac]
479+ };
480+
481+ let rows = block_h + 7;
482+ let mut intermediate = vec![0i32; rows * block_w];
483+ for r in 0..rows {
484+ let y = y0 - 3 + r as i32;
485+ for c in 0..block_w {
486+ let mut sum = 0;
487+ for (t, &tap) in h_filter.iter().enumerate() {
488+ let x = x0 + c as i32 + t as i32 - 3;
489+ sum += tap * sample(reference, stride, true_width, true_height, x, y);
490+ }
491+ intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0);
492+ }
493+ }
494+
495+ for row in 0..block_h {
496+ for col in 0..block_w {
497+ let mut sum = 0;
498+ for (t, &tap) in v_filter.iter().enumerate() {
499+ sum += tap * intermediate[(row + t) * block_w + col];
500+ }
501+ dst[row * block_w + col] = round2(sum, INTER_ROUND_1_COMPOUND);
502+ }
503+ }
504+}
505+
506+/// Blends two [`predict_compound_intermediate`] outputs into a finished
507+/// 8-bit block (spec 7.11.3.15's weighted-average combine, the
508+/// `comp_group_idx == 0` path -- `fwd_weight`/`bck_weight` are either the
509+/// simple-average split `(8, 8)` or [`crate::compound::dist_wtd_comp_weight_assign`]'s
510+/// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound
511+/// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this
512+/// function does not cover -- decode.rs still refuses those by name.
513+pub fn combine_compound(
514+ pred0: &[i32],
515+ pred1: &[i32],
516+ fwd_weight: i32,
517+ bck_weight: i32,
518+ dst: &mut [u8],
519+) {
520+ assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
521+ assert_eq!(dst.len(), pred0.len(), "the destination is the block");
522+ for i in 0..dst.len() {
523+ let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;
524+ dst[i] = round2(sum, INTER_POST_ROUND + DIST_PRECISION_BITS).clamp(0, 255) as u8;
525+ }
526+}
527+
528+/// Whole-pel identity case: [`predict_compound_intermediate`]'s two-pass
529+/// filter reduces to `16 * source_sample` exactly (the fraction-0 row is a
530+/// single `128` tap both passes, and `128*128 == 1 << 14`, `14 - 7 == 7 ==
531+/// INTER_ROUND_1_COMPOUND`, so the extra `2^4` of gain the compound path
532+/// keeps over [`predict`]'s 11-bit round survives untouched) --
533+/// [`combine_compound`] then divides that back out exactly with an 8/8
534+/// simple-average weight split, so a compound block whose two references
535+/// (and MVs) happen to coincide reproduces the plain source sample, not an
536+/// off-by-one from double rounding.
537+#[test]
538+fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
539+ let reference = vec![100u8; 16 * 16];
540+ let mut pred0 = vec![0i32; 16];
541+ predict_compound_intermediate(
542+ &reference,
543+ 16,
544+ 16,
545+ 16,
546+ 0,
547+ 0,
548+ 4,
549+ 4,
550+ InterpFilterKind::Regular,
551+ InterpFilterKind::Regular,
552+ &mut pred0,
553+ );
554+ assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}");
555+
556+ let pred1 = pred0.clone();
557+ let mut dst = vec![0u8; 16];
558+ combine_compound(&pred0, &pred1, 8, 8, &mut dst);
559+ assert!(dst.iter().all(|&v| v == 100), "{dst:?}");
560+}
561+
414562 #[cfg(test)]
415563 mod tests {
416564 use super::{InterpFilterKind, predict, predict_with_filter};
crates/ec-av1/src/mvstack.rsmodified+1142 -0
@@ -121,8 +121,22 @@ pub struct MiInfo {
121121 /// The single reference frame this unit's MV points into. Ignored (and
122122 /// the unit contributes no candidate) when `is_inter` is `false`.
123123 pub ref_frame: i8,
124+ /// The unit's *second* reference frame when it was coded compound
125+ /// (spec `RefFrames[1]`), `None` for a single-reference/intra unit --
126+ /// lane-av1comp: today's callers (single-ref decode/encode) never set
127+ /// this, so it exists only so [`MiGrid`] can carry compound state once
128+ /// `read_ref_frames` (spec 5.11.25) lands; nothing reads it yet, and
129+ /// [`find_mv_stack`]'s scan still matches candidates on `ref_frame`
130+ /// alone (its own compound dual-ref scan is unported -- see the ledger).
131+ pub ref_frame1: Option<i8>,
124132 /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units.
125133 pub mv: (i32, i32),
134+ /// The unit's second motion vector, matching `ref_frame1` (spec
135+ /// `Mvs[1]`) — `Some` only for a compound-coded unit, `None` otherwise.
136+ /// lane-av1comp step 4: exists so the compound mvstack scan below can
137+ /// read a compound neighbour's second MV; no caller sets it yet (same
138+ /// unwired state `ref_frame1` landed in for r3).
139+ pub mv1: Option<(i32, i32)>,
126140 /// Whether this unit's own mode was `NEWMV` (spec's
127141 /// `have_newmv_in_inter_mode`, compound modes excluded since this module
128142 /// has no compound candidates). Feeds `NewMvContext` (7.10.2.8): a
@@ -977,6 +991,680 @@ pub fn find_mv_stack_with_sign_bias(
977991 }
978992 }
979993
994+/// One neighbour's vote for a compound-reference (spec `RefFrame[0]` *and*
995+/// `RefFrame[1]` both active) candidate: two full motion vectors and the
996+/// combined weight — spec 7.10.2's compound half of `add_ref_mv_candidate`
997+/// (libaom `mvref_common.c`, the `is_compound` branch of `scan_row_mbmi`/
998+/// `scan_col_mbmi`/`scan_blk_mbmi`).
999+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1000+pub struct CompoundStackEntry {
1001+ /// The candidate's vote for `RefFrame[0]`'s motion vector.
1002+ pub mv0: (i32, i32),
1003+ /// The candidate's vote for `RefFrame[1]`'s motion vector.
1004+ pub mv1: (i32, i32),
1005+ /// The summed weight of every neighbour cell that voted for this pair.
1006+ pub weight: u32,
1007+}
1008+
1009+/// [`find_mv_stack_compound`]'s result — [`MvStack`]'s shape, doubled for
1010+/// the reference pair.
1011+#[derive(Clone, Debug, PartialEq, Eq)]
1012+pub struct CompoundMvStack {
1013+ /// The candidates, highest weight first.
1014+ pub entries: Vec<CompoundStackEntry>,
1015+ /// `RefStackMv[0]` for both refs, or `((0,0),(0,0))` when the stack is
1016+ /// empty.
1017+ pub nearest_mv: ((i32, i32), (i32, i32)),
1018+ /// `RefStackMv[1]` for both refs, or `((0,0),(0,0))` when the stack has
1019+ /// fewer than two entries.
1020+ pub near_mv: ((i32, i32), (i32, i32)),
1021+ /// The predictor pair a `NEW_NEWMV`-family block's MV differences are
1022+ /// coded against.
1023+ pub pred_mv: ((i32, i32), (i32, i32)),
1024+ /// Context for the compound `new_mv` symbol.
1025+ pub new_mv_ctx: usize,
1026+ /// Context for the compound `ref_mv` symbol.
1027+ pub ref_mv_ctx: usize,
1028+ /// Context for the compound `zero_mv` symbol.
1029+ pub zero_mv_ctx: usize,
1030+ /// Context for each `drl_mode` symbol between consecutive stack entries.
1031+ pub drl_ctx: Vec<usize>,
1032+}
1033+
1034+/// [`add_candidate`], doubled: dedupes on the whole `(mv0, mv1)` pair.
1035+fn add_compound_candidate(
1036+ candidates: &mut Vec<CompoundStackEntry>,
1037+ mv0: (i32, i32),
1038+ mv1: (i32, i32),
1039+ weight: u32,
1040+) {
1041+ if let Some(entry) = candidates.iter_mut().find(|e| e.mv0 == mv0 && e.mv1 == mv1) {
1042+ entry.weight += weight;
1043+ } else {
1044+ candidates.push(CompoundStackEntry { mv0, mv1, weight });
1045+ }
1046+}
1047+
1048+/// The compound row scan (spec 7.10.2.2's compound branch, libaom
1049+/// `scan_row_mbmi`'s `is_compound` path): [`scan_row`]'s weight/run-length
1050+/// math unchanged, but a candidate only votes when *both* its `ref_frame`
1051+/// and `ref_frame1` equal the query's pair exactly, in that order — a
1052+/// compound pair is always encoded forward-then-backward
1053+/// (`RefFrame[0]`/`RefFrame[1]`), so unlike [`process_single_ref_mv_candidate`]'s
1054+/// extension pass, no sign-bias flip ever applies to an exact-pair scan
1055+/// match (libaom's own `scan_row_mbmi` compound branch doesn't flip either).
1056+#[allow(clippy::too_many_arguments)]
1057+fn scan_row_compound(
1058+ grid: &MiGrid,
1059+ mi_row: usize,
1060+ mi_col: usize,
1061+ bw4: usize,
1062+ row_offset: isize,
1063+ max_row_offset: isize,
1064+ ref_frame: (i8, i8),
1065+ candidates: &mut Vec<CompoundStackEntry>,
1066+ newmv_count: &mut u32,
1067+ processed_rows: &mut usize,
1068+) -> bool {
1069+ let Some(row) = mi_row.checked_add_signed(row_offset) else {
1070+ return false;
1071+ };
1072+ let col_shift: usize = if row_offset.unsigned_abs() > 1 { 1 } else { 0 };
1073+ let use_step_16 = bw4 >= 16;
1074+ let end_mi = bw4.min(16);
1075+ let mut found = false;
1076+ let mut i = 0usize;
1077+ while i < end_mi {
1078+ let Some(info) = grid.get(row, mi_col + col_shift + i) else {
1079+ i += 1;
1080+ continue;
1081+ };
1082+ let n4 = info.size;
1083+ let mut len = bw4.min(n4);
1084+ if use_step_16 {
1085+ len = len.max(4);
1086+ } else if row_offset.unsigned_abs() > 1 {
1087+ len = len.max(2);
1088+ }
1089+ let mut weight = ROW_COL_WEIGHT_FLOOR;
1090+ if bw4 <= n4 {
1091+ let inc = ((-max_row_offset + row_offset + 1) as usize).min(n4);
1092+ weight = weight.max(inc as u32);
1093+ *processed_rows = (inc as isize - row_offset - 1).max(0) as usize;
1094+ }
1095+ if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 == Some(ref_frame.1) {
1096+ found = true;
1097+ add_compound_candidate(
1098+ candidates,
1099+ info.mv,
1100+ info.mv1.unwrap_or((0, 0)),
1101+ len as u32 * weight,
1102+ );
1103+ *newmv_count += u32::from(info.is_new_mv);
1104+ }
1105+ i += len.max(1);
1106+ }
1107+ found
1108+}
1109+
1110+/// The compound col scan (spec 7.10.2.3's compound branch): [`scan_row_compound`],
1111+/// transposed — mirrors [`scan_col`]/[`scan_row`]'s own relationship.
1112+#[allow(clippy::too_many_arguments)]
1113+fn scan_col_compound(
1114+ grid: &MiGrid,
1115+ mi_row: usize,
1116+ mi_col: usize,
1117+ bh4: usize,
1118+ col_offset: isize,
1119+ max_col_offset: isize,
1120+ ref_frame: (i8, i8),
1121+ candidates: &mut Vec<CompoundStackEntry>,
1122+ newmv_count: &mut u32,
1123+ processed_cols: &mut usize,
1124+) -> bool {
1125+ let Some(col) = mi_col.checked_add_signed(col_offset) else {
1126+ return false;
1127+ };
1128+ let row_shift: usize = if col_offset.unsigned_abs() > 1 { 1 } else { 0 };
1129+ let use_step_16 = bh4 >= 16;
1130+ let end_mi = bh4.min(16);
1131+ let mut found = false;
1132+ let mut i = 0usize;
1133+ while i < end_mi {
1134+ let Some(info) = grid.get(mi_row + row_shift + i, col) else {
1135+ i += 1;
1136+ continue;
1137+ };
1138+ let n4 = info.size;
1139+ let mut len = bh4.min(n4);
1140+ if use_step_16 {
1141+ len = len.max(4);
1142+ } else if col_offset.unsigned_abs() > 1 {
1143+ len = len.max(2);
1144+ }
1145+ let mut weight = ROW_COL_WEIGHT_FLOOR;
1146+ if bh4 <= n4 {
1147+ let inc = ((-max_col_offset + col_offset + 1) as usize).min(n4);
1148+ weight = weight.max(inc as u32);
1149+ *processed_cols = (inc as isize - col_offset - 1).max(0) as usize;
1150+ }
1151+ if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 == Some(ref_frame.1) {
1152+ found = true;
1153+ add_compound_candidate(
1154+ candidates,
1155+ info.mv,
1156+ info.mv1.unwrap_or((0, 0)),
1157+ len as u32 * weight,
1158+ );
1159+ *newmv_count += u32::from(info.is_new_mv);
1160+ }
1161+ i += len.max(1);
1162+ }
1163+ found
1164+}
1165+
1166+/// The compound top-right probe ([`scan_top_right`]'s pair-matched twin).
1167+fn scan_top_right_compound(
1168+ grid: &MiGrid,
1169+ mi_row: usize,
1170+ mi_col: usize,
1171+ bw4: usize,
1172+ ref_frame: (i8, i8),
1173+ candidates: &mut Vec<CompoundStackEntry>,
1174+ newmv_count: &mut u32,
1175+) -> bool {
1176+ let Some(row) = mi_row.checked_sub(1) else {
1177+ return false;
1178+ };
1179+ let col = mi_col + bw4;
1180+ if let Some(info) = grid.get(row, col)
1181+ && info.is_inter
1182+ && info.ref_frame == ref_frame.0
1183+ && info.ref_frame1 == Some(ref_frame.1)
1184+ {
1185+ add_compound_candidate(
1186+ candidates,
1187+ info.mv,
1188+ info.mv1.unwrap_or((0, 0)),
1189+ CORNER_WEIGHT,
1190+ );
1191+ *newmv_count += u32::from(info.is_new_mv);
1192+ return true;
1193+ }
1194+ false
1195+}
1196+
1197+/// The compound diagonal corner probe ([`scan_corner`]'s pair-matched twin).
1198+fn scan_corner_compound(
1199+ grid: &MiGrid,
1200+ mi_row: usize,
1201+ mi_col: usize,
1202+ ref_frame: (i8, i8),
1203+ candidates: &mut Vec<CompoundStackEntry>,
1204+ newmv_count: &mut u32,
1205+) -> bool {
1206+ let (Some(row), Some(col)) = (mi_row.checked_sub(1), mi_col.checked_sub(1)) else {
1207+ return false;
1208+ };
1209+ if let Some(info) = grid.get(row, col)
1210+ && info.is_inter
1211+ && info.ref_frame == ref_frame.0
1212+ && info.ref_frame1 == Some(ref_frame.1)
1213+ {
1214+ add_compound_candidate(
1215+ candidates,
1216+ info.mv,
1217+ info.mv1.unwrap_or((0, 0)),
1218+ CORNER_WEIGHT,
1219+ );
1220+ *newmv_count += u32::from(info.is_new_mv);
1221+ return true;
1222+ }
1223+ false
1224+}
1225+
1226+/// Per-side unresolved-MV accumulator [`process_compound_ref_mv_candidate`]
1227+/// fills across every candidate the compound extension pass walks: up to two
1228+/// motion vectors that matched `ref_frame.0`/`.1` exactly (`ref_id`), and up
1229+/// to two more borrowed from a differently-referenced but still-inter
1230+/// neighbour under the sign-bias flip [`process_single_ref_mv_candidate`]
1231+/// also applies (`ref_diff`). Ported from libaom's `setup_ref_mv_list`
1232+/// (`mvref_common.c`, `process_compound_ref_mv_candidate` ~line 380-430 plus
1233+/// the combine step at ~696-762): the extension walk fills this once across
1234+/// the whole row-then-col scan, and [`combine_compound_candidates`] below
1235+/// zips the two independently-filled sides back into full pair candidates.
1236+#[derive(Default)]
1237+struct CompoundRefLists {
1238+ ref_id: [Vec<(i32, i32)>; 2],
1239+ ref_diff: [Vec<(i32, i32)>; 2],
1240+}
1241+
1242+/// libaom's `process_compound_ref_mv_candidate`: folds one already-coded
1243+/// neighbour's up to two reference slots into `lists`, split by which side
1244+/// of `ref_frame` (the query block's own compound pair) each slot's own
1245+/// reference frame matches — an exact match goes to that side's `ref_id`
1246+/// list, anything else (still inter, wrong reference) goes to `ref_diff`
1247+/// under the usual sign-bias flip.
1248+fn process_compound_ref_mv_candidate(
1249+ candidate: &MiInfo,
1250+ ref_frame: (i8, i8),
1251+ sign_bias_table: &SignBiasTable,
1252+ lists: &mut CompoundRefLists,
1253+) {
1254+ if !candidate.is_inter {
1255+ return;
1256+ }
1257+ let slots = [
1258+ Some((candidate.ref_frame, candidate.mv)),
1259+ candidate
1260+ .ref_frame1
1261+ .map(|rf1| (rf1, candidate.mv1.unwrap_or((0, 0)))),
1262+ ];
1263+ for (candidate_ref, candidate_mv) in slots.into_iter().flatten() {
1264+ for (i, side_ref) in [ref_frame.0, ref_frame.1].into_iter().enumerate() {
1265+ if candidate_ref == side_ref {
1266+ if lists.ref_id[i].len() < 2 {
1267+ lists.ref_id[i].push(candidate_mv);
1268+ }
1269+ } else if lists.ref_diff[i].len() < 2 {
1270+ let mut mv = candidate_mv;
1271+ if sign_bias(sign_bias_table, candidate_ref) != sign_bias(sign_bias_table, side_ref)
1272+ {
1273+ mv = (-mv.0, -mv.1);
1274+ }
1275+ lists.ref_diff[i].push(mv);
1276+ }
1277+ }
1278+ }
1279+}
1280+
1281+/// libaom's combine step (`setup_ref_mv_list`, `mvref_common.c` ~696-720):
1282+/// zips each side's `ref_id` (exact matches) then `ref_diff` (borrowed,
1283+/// sign-flipped) entries, position-wise and independently per side, into up
1284+/// to two full `(mv0, mv1)` pair candidates — missing slots default to
1285+/// `(0, 0)`, matching libaom's zero-initialized `combined_mvs`.
1286+fn combine_compound_candidates(lists: &CompoundRefLists) -> [((i32, i32), (i32, i32)); 2] {
1287+ let side_slots = |side: usize| -> [(i32, i32); 2] {
1288+ let merged: Vec<(i32, i32)> = lists.ref_id[side]
1289+ .iter()
1290+ .chain(lists.ref_diff[side].iter())
1291+ .take(2)
1292+ .copied()
1293+ .collect();
1294+ std::array::from_fn(|i| merged.get(i).copied().unwrap_or((0, 0)))
1295+ };
1296+ let side0 = side_slots(0);
1297+ let side1 = side_slots(1);
1298+ [(side0[0], side1[0]), (side0[1], side1[1])]
1299+}
1300+
1301+/// [`find_mv_stack_with_sign_bias`]'s compound-reference twin (spec
1302+/// 7.10.2's `is_compound` path throughout): builds the reference MV stack
1303+/// for a block predicted against *two* simultaneously-active reference
1304+/// frames (`ref_frame.0`, `ref_frame.1`), keeping every existing
1305+/// single-reference caller of [`find_mv_stack`]/[`find_mv_stack_with_sign_bias`]
1306+/// untouched — this is a new, parallel entry point, not an extension of the
1307+/// single-ref one. Same reduction scope as the single-ref module doc
1308+/// (single tile, square blocks, `IDENTITY` global motion only); the
1309+/// mode-context switch below reuses the identical `(nearest_match,
1310+/// ref_match_count)` derivation the single-ref path uses, since libaom's own
1311+/// switch statement (`mvref_common.c` ~619-643) is ref-count-agnostic — it
1312+/// only ever reads those two counts, regardless of which `MODE_CTX_REF_FRAMES`
1313+/// slot `mode_context` it's indexing.
1314+///
1315+/// The compound extension combine step (`setup_ref_mv_list`, ~line 700-754)
1316+/// and the temporal `add_tpl_ref_mv` fold-in (~line 341-433) are both exact
1317+/// ports of libaom's real behaviour as of r5 — see the inline comments at
1318+/// each site.
1319+#[allow(clippy::too_many_arguments)]
1320+pub fn find_mv_stack_compound(
1321+ grid: &MiGrid,
1322+ mi_row: usize,
1323+ mi_col: usize,
1324+ bw4: usize,
1325+ bh4: usize,
1326+ ref_frame: (i8, i8),
1327+ mi_cols: usize,
1328+ mi_rows: usize,
1329+ sign_bias_table: &SignBiasTable,
1330+ tpl: Option<CompoundTplArgs>,
1331+) -> CompoundMvStack {
1332+ let mut candidates: Vec<CompoundStackEntry> = Vec::new();
1333+ let mut newmv_count = 0u32;
1334+
1335+ let row_adj = bh4 < 2 && mi_row % 2 == 1;
1336+ let col_adj = bw4 < 2 && mi_col % 2 == 1;
1337+ let max_row_offset: isize = if mi_row > 0 {
1338+ let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj);
1339+ reach.max(-(mi_row as isize))
1340+ } else {
1341+ 0
1342+ };
1343+ let max_col_offset: isize = if mi_col > 0 {
1344+ let reach = if bw4 < 2 { -4 } else { -6 } + isize::from(col_adj);
1345+ reach.max(-(mi_col as isize))
1346+ } else {
1347+ 0
1348+ };
1349+
1350+ let mut processed_rows = 0usize;
1351+ let mut processed_cols = 0usize;
1352+ let found_above = mi_row > 0
1353+ && scan_row_compound(
1354+ grid,
1355+ mi_row,
1356+ mi_col,
1357+ bw4,
1358+ -1,
1359+ max_row_offset,
1360+ ref_frame,
1361+ &mut candidates,
1362+ &mut newmv_count,
1363+ &mut processed_rows,
1364+ );
1365+ let found_left = mi_col > 0
1366+ && scan_col_compound(
1367+ grid,
1368+ mi_row,
1369+ mi_col,
1370+ bh4,
1371+ -1,
1372+ max_col_offset,
1373+ ref_frame,
1374+ &mut candidates,
1375+ &mut newmv_count,
1376+ &mut processed_cols,
1377+ );
1378+ let found_top_right = scan_top_right_compound(
1379+ grid,
1380+ mi_row,
1381+ mi_col,
1382+ bw4,
1383+ ref_frame,
1384+ &mut candidates,
1385+ &mut newmv_count,
1386+ );
1387+
1388+ let row_matched = found_above || found_top_right;
1389+ let nearest_match = usize::from(row_matched) + usize::from(found_left);
1390+
1391+ for entry in &mut candidates {
1392+ entry.weight += REF_CAT_LEVEL;
1393+ }
1394+
1395+ // Temporal compound candidates (spec 7.10.2.8's compound
1396+ // `add_tpl_ref_mv`): the same projected field, read once per side of the
1397+ // pair through the existing single-ref [`crate::motion_field::add_tpl_ref_mv`]
1398+ // — each side's own `cur_offset` scales the *same* stored candidate to
1399+ // that side's reference frame. libaom's real `add_tpl_ref_mv` looks up
1400+ // the stored `mfmv0`/`ref_frame_offset` pair exactly once per `(blk_row,
1401+ // blk_col)` and, if present, always projects it to *both* sides (the
1402+ // lookup itself never fails for one side and succeeds for the other);
1403+ // a missing side there is `INVALID_MV`/global-motion zero-fill, never a
1404+ // dropped candidate. Ported exactly: each side is read independently and
1405+ // a missing side zero-fills rather than vetoing the pair.
1406+ let mut zero_mv_ctx = 0usize;
1407+ if let Some(CompoundTplArgs {
1408+ field,
1409+ cur_offset_0,
1410+ cur_offset_1,
1411+ allow_high_precision_mv,
1412+ }) = tpl
1413+ {
1414+ let mut any_hit = false;
1415+ let blk_row_end = bh4.min(16);
1416+ let blk_col_end = bw4.min(16);
1417+ let step_h = if bh4 >= 16 { 4 } else { 2 };
1418+ let step_w = if bw4 >= 16 { 4 } else { 2 };
1419+ let mut first_sample_missing = true;
1420+ let mut first_sample_far = false;
1421+ let mut blk_row = 0usize;
1422+ while blk_row < blk_row_end {
1423+ let mut blk_col = 0usize;
1424+ while blk_col < blk_col_end {
1425+ let cand0 = crate::motion_field::add_tpl_ref_mv(
1426+ field,
1427+ mi_row,
1428+ mi_col,
1429+ blk_row as isize,
1430+ blk_col as isize,
1431+ cur_offset_0,
1432+ allow_high_precision_mv,
1433+ );
1434+ let cand1 = crate::motion_field::add_tpl_ref_mv(
1435+ field,
1436+ mi_row,
1437+ mi_col,
1438+ blk_row as isize,
1439+ blk_col as isize,
1440+ cur_offset_1,
1441+ allow_high_precision_mv,
1442+ );
1443+ if cand0.is_some() || cand1.is_some() {
1444+ any_hit = true;
1445+ let mv0 = cand0.map_or((0, 0), |c| c.mv);
1446+ let mv1 = cand1.map_or((0, 0), |c| c.mv);
1447+ if blk_row == 0 && blk_col == 0 {
1448+ first_sample_missing = false;
1449+ first_sample_far = mv0.0.abs() >= 16
1450+ || mv0.1.abs() >= 16
1451+ || mv1.0.abs() >= 16
1452+ || mv1.1.abs() >= 16;
1453+ }
1454+ add_compound_candidate(&mut candidates, mv0, mv1, 2);
1455+ }
1456+ blk_col += step_w;
1457+ }
1458+ blk_row += step_h;
1459+ }
1460+ if any_hit {
1461+ TMV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1462+ }
1463+ zero_mv_ctx = usize::from(first_sample_missing || first_sample_far);
1464+ }
1465+
1466+ let mut dummy_newmv_count = 0u32;
1467+ let corner_matched = scan_corner_compound(
1468+ grid,
1469+ mi_row,
1470+ mi_col,
1471+ ref_frame,
1472+ &mut candidates,
1473+ &mut dummy_newmv_count,
1474+ );
1475+ let mut row_matched_ext = false;
1476+ let mut col_matched_ext = false;
1477+ for idx in 2..=MVREF_ROW_COLS {
1478+ let row_offset = -((idx as isize) * 2) + 1 + isize::from(row_adj);
1479+ let col_offset = -((idx as isize) * 2) + 1 + isize::from(col_adj);
1480+ if row_offset.unsigned_abs() <= max_row_offset.unsigned_abs()
1481+ && row_offset.unsigned_abs() > processed_rows
1482+ && scan_row_compound(
1483+ grid,
1484+ mi_row,
1485+ mi_col,
1486+ bw4,
1487+ row_offset,
1488+ max_row_offset,
1489+ ref_frame,
1490+ &mut candidates,
1491+ &mut dummy_newmv_count,
1492+ &mut processed_rows,
1493+ )
1494+ {
1495+ row_matched_ext = true;
1496+ }
1497+ if col_offset.unsigned_abs() <= max_col_offset.unsigned_abs()
1498+ && col_offset.unsigned_abs() > processed_cols
1499+ && scan_col_compound(
1500+ grid,
1501+ mi_row,
1502+ mi_col,
1503+ bh4,
1504+ col_offset,
1505+ max_col_offset,
1506+ ref_frame,
1507+ &mut candidates,
1508+ &mut dummy_newmv_count,
1509+ &mut processed_cols,
1510+ )
1511+ {
1512+ col_matched_ext = true;
1513+ }
1514+ }
1515+ let ref_match_count = usize::from(row_matched || corner_matched || row_matched_ext)
1516+ + usize::from(found_left || col_matched_ext);
1517+
1518+ candidates.sort_by_key(|e| std::cmp::Reverse(e.weight));
1519+ candidates.truncate(MAX_STACK_SIZE);
1520+
1521+ // The compound extension pass (libaom's `setup_ref_mv_list`, "Handle
1522+ // compound reference frame extension"): gather across the row directly
1523+ // above and the column directly left (same `mi_size` reach as the
1524+ // single-ref pass), then combine once.
1525+ let mi_width = (16usize).min(bw4).min(mi_cols.saturating_sub(mi_col));
1526+ let mi_height = (16usize).min(bh4).min(mi_rows.saturating_sub(mi_row));
1527+ let mi_size = mi_width.min(mi_height);
1528+ if candidates.len() < MAX_MV_REF_CANDIDATES {
1529+ let mut lists = CompoundRefLists::default();
1530+ if max_row_offset.unsigned_abs() >= 1 {
1531+ let mut idx = 0usize;
1532+ while idx < mi_size {
1533+ let cand = grid.get(mi_row - 1, mi_col + idx);
1534+ let step = cand.map_or(1, |c| c.size).max(1);
1535+ if let Some(c) = cand {
1536+ process_compound_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut lists);
1537+ }
1538+ idx += step;
1539+ }
1540+ }
1541+ if max_col_offset.unsigned_abs() >= 1 {
1542+ let mut idx = 0usize;
1543+ while idx < mi_size {
1544+ let cand = grid.get(mi_row + idx, mi_col - 1);
1545+ let step = cand.map_or(1, |c| c.size).max(1);
1546+ if let Some(c) = cand {
1547+ process_compound_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut lists);
1548+ }
1549+ idx += step;
1550+ }
1551+ }
1552+ // libaom's real dedup (`setup_ref_mv_list` ~735-754): when the stack
1553+ // already has exactly one entry, compare only `comp_list[0]` against
1554+ // it and, on a match, take `comp_list[1]` instead (skip, no weight
1555+ // bump) — otherwise append `comp_list[0]` as a brand-new entry. When
1556+ // the stack is empty, both `comp_list[0]` and `comp_list[1]` are
1557+ // appended unconditionally, with no dedup check at all.
1558+ let comp_list = combine_compound_candidates(&lists);
1559+ if candidates.len() == 1 {
1560+ let (mv0, mv1) = if comp_list[0] == (candidates[0].mv0, candidates[0].mv1) {
1561+ comp_list[1]
1562+ } else {
1563+ comp_list[0]
1564+ };
1565+ candidates.push(CompoundStackEntry {
1566+ mv0,
1567+ mv1,
1568+ weight: 2,
1569+ });
1570+ } else if candidates.is_empty() {
1571+ for (mv0, mv1) in comp_list {
1572+ candidates.push(CompoundStackEntry {
1573+ mv0,
1574+ mv1,
1575+ weight: 2,
1576+ });
1577+ }
1578+ }
1579+ }
1580+
1581+ let clamp = |mv| clamp_mv_ref(mv, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows);
1582+ let nearest_mv = candidates
1583+ .first()
1584+ .map_or(((0, 0), (0, 0)), |e| (clamp(e.mv0), clamp(e.mv1)));
1585+ let near_mv = candidates
1586+ .get(1)
1587+ .map_or(((0, 0), (0, 0)), |e| (clamp(e.mv0), clamp(e.mv1)));
1588+ let pred_mv = if candidates.is_empty() {
1589+ ((0, 0), (0, 0))
1590+ } else {
1591+ nearest_mv
1592+ };
1593+
1594+ let new_mv_ctx = match nearest_match {
1595+ 0 => usize::from(ref_match_count >= 1),
1596+ 1 => {
1597+ if newmv_count > 0 {
1598+ 2
1599+ } else {
1600+ 3
1601+ }
1602+ }
1603+ _ => {
1604+ if newmv_count >= 1 {
1605+ 4
1606+ } else {
1607+ 5
1608+ }
1609+ }
1610+ };
1611+ let ref_mv_ctx = match nearest_match {
1612+ 0 => match ref_match_count {
1613+ 0 => 0,
1614+ 1 => 1,
1615+ _ => 2,
1616+ },
1617+ 1 => {
1618+ if ref_match_count >= 2 {
1619+ 4
1620+ } else {
1621+ 3
1622+ }
1623+ }
1624+ _ => 5,
1625+ };
1626+
1627+ let drl_ctx = candidates
1628+ .windows(2)
1629+ .map(|w| {
1630+ let (a, b) = (w[0].weight, w[1].weight);
1631+ if a >= REF_CAT_LEVEL && b >= REF_CAT_LEVEL {
1632+ 0
1633+ } else if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL {
1634+ 1
1635+ } else {
1636+ 2
1637+ }
1638+ })
1639+ .collect();
1640+
1641+ CompoundMvStack {
1642+ entries: candidates,
1643+ nearest_mv,
1644+ near_mv,
1645+ pred_mv,
1646+ new_mv_ctx,
1647+ ref_mv_ctx,
1648+ zero_mv_ctx,
1649+ drl_ctx,
1650+ }
1651+}
1652+
1653+/// [`find_mv_stack_compound`]'s temporal-MV inputs — [`TplArgs`], doubled:
1654+/// one `cur_offset` per side of the pair (`get_relative_dist(OrderHint,
1655+/// OrderHints[ref_frame.N - LAST_FRAME])`, spec 7.9.3), since a compound
1656+/// query projects the same stored field twice, once per reference.
1657+pub struct CompoundTplArgs<'a> {
1658+ /// The current frame's projected temporal motion field.
1659+ pub field: &'a crate::motion_field::TplField,
1660+ /// `get_relative_dist` for `ref_frame.0`.
1661+ pub cur_offset_0: i32,
1662+ /// `get_relative_dist` for `ref_frame.1`.
1663+ pub cur_offset_1: i32,
1664+ /// The frame header's own `allow_high_precision_mv`.
1665+ pub allow_high_precision_mv: bool,
1666+}
1667+
9801668 /// The single-reference context shared by the `single_ref_p1`/`p3`/`p4`
9811669 /// binary decisions this crate's LAST-only reference chain codes (spec
9821670 /// 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<i8>, left: Option<i8>) -> usize {
10701758 ref_ctx(above, left, &[BWDREF_FRAME], &[ALTREF2_FRAME])
10711759 }
10721760
1761+/// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` vs. `LAST3`/`GOLDEN`,
1762+/// conditioned on a unidirectional pair known to be one of the three
1763+/// `LAST`-anchored ones (lane-av1comp).
1764+pub(crate) fn uni_comp_ref_p1_ctx(above: Option<i8>, left: Option<i8>) -> usize {
1765+ ref_ctx(above, left, &[LAST2_FRAME], &[LAST3_FRAME, GOLDEN_FRAME])
1766+}
1767+
1768+/// One neighbouring block's reference-frame shape, as
1769+/// [`reference_mode_ctx`]/[`comp_reference_type_ctx`] need it: `None` for an
1770+/// out-of-frame neighbour, `Some(ref0, None)` for an intra or single-ref
1771+/// inter block, `Some(ref0, Some(ref1))` for a compound one. `uni` is
1772+/// `ref1`'s meaning only when compound: whether the pair libaom's
1773+/// `has_uni_comp_refs` would call unidirectional (both refs on the same
1774+/// side of the current frame).
1775+#[derive(Clone, Copy)]
1776+pub(crate) struct NeighbourRef {
1777+ pub is_inter: bool,
1778+ pub ref0: i8,
1779+ pub ref1: Option<i8>,
1780+ pub uni: bool,
1781+}
1782+
1783+fn is_backward(r: i8) -> bool {
1784+ (BWDREF_FRAME..=ALTREF_FRAME).contains(&r)
1785+}
1786+
1787+/// `av1_get_reference_mode_context` (spec 5.11.25's `comp_mode` context,
1788+/// libaom `pred_common.c`): 5 contexts from how many of the above/left
1789+/// neighbours are themselves compound-predicted, and (when neither/one is)
1790+/// whether their single reference is a backward one.
1791+pub(crate) fn reference_mode_ctx(above: Option<NeighbourRef>, left: Option<NeighbourRef>) -> usize {
1792+ match (above, left) {
1793+ (Some(a), Some(l)) => match (a.ref1.is_some(), l.ref1.is_some()) {
1794+ (false, false) => usize::from(is_backward(a.ref0) ^ is_backward(l.ref0)),
1795+ (false, true) => 2 + usize::from(is_backward(a.ref0) || !a.is_inter),
1796+ (true, false) => 2 + usize::from(is_backward(l.ref0) || !l.is_inter),
1797+ (true, true) => 4,
1798+ },
1799+ (Some(e), None) | (None, Some(e)) => {
1800+ if e.ref1.is_some() {
1801+ 3
1802+ } else {
1803+ usize::from(is_backward(e.ref0))
1804+ }
1805+ }
1806+ (None, None) => 1,
1807+ }
1808+}
1809+
1810+/// `av1_get_comp_reference_type_context` (spec 5.11.25's
1811+/// `comp_reference_type` context, libaom `pred_common.c`): 5 contexts from
1812+/// whether the above/left neighbours are intra, single-ref, unidirectional
1813+/// compound, or bidirectional compound.
1814+pub(crate) fn comp_reference_type_ctx(
1815+ above: Option<NeighbourRef>,
1816+ left: Option<NeighbourRef>,
1817+) -> usize {
1818+ match (above, left) {
1819+ (Some(a), Some(l)) => match (a.is_inter, l.is_inter) {
1820+ (false, false) => 2,
1821+ (false, true) | (true, false) => {
1822+ let inter = if a.is_inter { a } else { l };
1823+ if inter.ref1.is_none() {
1824+ 2
1825+ } else {
1826+ 1 + 2 * usize::from(inter.uni)
1827+ }
1828+ }
1829+ (true, true) => {
1830+ let (a_sg, l_sg) = (a.ref1.is_none(), l.ref1.is_none());
1831+ if a_sg && l_sg {
1832+ 1 + 2 * usize::from(!(is_backward(a.ref0) ^ is_backward(l.ref0)))
1833+ } else if a_sg || l_sg {
1834+ let uni = if a_sg { l.uni } else { a.uni };
1835+ if !uni {
1836+ 1
1837+ } else {
1838+ 3 + usize::from(!(is_backward(a.ref0) ^ is_backward(l.ref0)))
1839+ }
1840+ } else if !a.uni && !l.uni {
1841+ 0
1842+ } else if !a.uni || !l.uni {
1843+ 2
1844+ } else {
1845+ 3 + usize::from(!((a.ref0 == BWDREF_FRAME) ^ (l.ref0 == BWDREF_FRAME)))
1846+ }
1847+ }
1848+ },
1849+ (Some(e), None) | (None, Some(e)) => {
1850+ if !e.is_inter {
1851+ 2
1852+ } else if e.ref1.is_none() {
1853+ 2
1854+ } else {
1855+ 4 * usize::from(e.uni)
1856+ }
1857+ }
1858+ (None, None) => 2,
1859+ }
1860+}
1861+
10731862 #[cfg(test)]
10741863 mod tests {
10751864 use super::*;
@@ -1078,6 +1867,8 @@ mod tests {
10781867 MiInfo {
10791868 is_inter: true,
10801869 ref_frame: 1,
1870+ ref_frame1: None,
1871+ mv1: None,
10811872 mv,
10821873 is_new_mv: false,
10831874 // 1: smaller than every `bw4`/`bh4` these small-grid tests use,
@@ -1229,6 +2020,8 @@ mod tests {
12292020 MiInfo {
12302021 is_inter: true,
12312022 ref_frame: 1,
2023+ ref_frame1: None,
2024+ mv1: None,
12322025 mv: (4, 4),
12332026 is_new_mv: true,
12342027 size: 1,
@@ -1307,6 +2100,8 @@ mod tests {
13072100 MiInfo {
13082101 is_inter: true,
13092102 ref_frame: 1,
2103+ ref_frame1: None,
2104+ mv1: None,
13102105 mv,
13112106 is_new_mv: false,
13122107 size: 8,
@@ -1334,6 +2129,8 @@ mod tests {
13342129 MiInfo {
13352130 is_inter: false,
13362131 ref_frame: -1,
2132+ ref_frame1: None,
2133+ mv1: None,
13372134 mv: (0, 0),
13382135 is_new_mv: false,
13392136 size: 8,
@@ -1348,6 +2145,8 @@ mod tests {
13482145 MiInfo {
13492146 is_inter: true,
13502147 ref_frame: 1,
2148+ ref_frame1: None,
2149+ mv1: None,
13512150 mv,
13522151 is_new_mv: false,
13532152 size: 8,
@@ -1425,4 +2224,347 @@ mod tests {
14252224 assert_eq!(stack.entries.len(), 1);
14262225 assert_eq!(stack.entries[0].mv, (4, 4));
14272226 }
2227+
2228+ fn single(ref0: i8) -> NeighbourRef {
2229+ NeighbourRef {
2230+ is_inter: true,
2231+ ref0,
2232+ ref1: None,
2233+ uni: false,
2234+ }
2235+ }
2236+ fn comp(ref0: i8, ref1: i8, uni: bool) -> NeighbourRef {
2237+ NeighbourRef {
2238+ is_inter: true,
2239+ ref0,
2240+ ref1: Some(ref1),
2241+ uni,
2242+ }
2243+ }
2244+ fn intra() -> NeighbourRef {
2245+ NeighbourRef {
2246+ is_inter: false,
2247+ ref0: 0,
2248+ ref1: None,
2249+ uni: false,
2250+ }
2251+ }
2252+
2253+ /// `av1_get_reference_mode_context`, no edges available: libaom's `ctx
2254+ /// = 1` fallback.
2255+ #[test]
2256+ fn reference_mode_ctx_no_edges_is_one() {
2257+ assert_eq!(reference_mode_ctx(None, None), 1);
2258+ }
2259+
2260+ /// Both edges single-ref, same forward/backward-ness: `ctx = 0`; one of
2261+ /// each: `ctx = 1` (the XOR in libaom's `ctx = IS_BACKWARD(above) ^
2262+ /// IS_BACKWARD(left)`).
2263+ #[test]
2264+ fn reference_mode_ctx_single_single() {
2265+ assert_eq!(
2266+ reference_mode_ctx(Some(single(LAST_FRAME)), Some(single(LAST2_FRAME))),
2267+ 0
2268+ );
2269+ assert_eq!(
2270+ reference_mode_ctx(Some(single(LAST_FRAME)), Some(single(BWDREF_FRAME))),
2271+ 1
2272+ );
2273+ }
2274+
2275+ /// One edge compound, the other single forward: libaom's `2 +
2276+ /// IS_BACKWARD(above)` collapses to `2` here (forward, inter).
2277+ #[test]
2278+ fn reference_mode_ctx_single_and_compound() {
2279+ assert_eq!(
2280+ reference_mode_ctx(
2281+ Some(single(LAST_FRAME)),
2282+ Some(comp(LAST_FRAME, LAST2_FRAME, true))
2283+ ),
2284+ 2
2285+ );
2286+ assert_eq!(
2287+ reference_mode_ctx(
2288+ Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2289+ Some(single(LAST_FRAME))
2290+ ),
2291+ 2
2292+ );
2293+ }
2294+
2295+ /// Both edges compound: libaom's fixed `ctx = 4`.
2296+ #[test]
2297+ fn reference_mode_ctx_compound_compound_is_four() {
2298+ assert_eq!(
2299+ reference_mode_ctx(
2300+ Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2301+ Some(comp(BWDREF_FRAME, ALTREF_FRAME, true))
2302+ ),
2303+ 4
2304+ );
2305+ }
2306+
2307+ /// `av1_get_comp_reference_type_context`, no edges: libaom's `ctx = 2`
2308+ /// fallback.
2309+ #[test]
2310+ fn comp_reference_type_ctx_no_edges_is_two() {
2311+ assert_eq!(comp_reference_type_ctx(None, None), 2);
2312+ }
2313+
2314+ /// Both edges intra: libaom's `ctx = 2`.
2315+ #[test]
2316+ fn comp_reference_type_ctx_intra_intra_is_two() {
2317+ assert_eq!(comp_reference_type_ctx(Some(intra()), Some(intra())), 2);
2318+ }
2319+
2320+ /// Both edges single/single: forward-vs-backward split doubles the same
2321+ /// way `single_ref_p1`'s own XOR does (libaom's `1 + 2 * !(a ^ l)`).
2322+ #[test]
2323+ fn comp_reference_type_ctx_single_single() {
2324+ assert_eq!(
2325+ comp_reference_type_ctx(Some(single(LAST_FRAME)), Some(single(LAST2_FRAME))),
2326+ 3
2327+ );
2328+ assert_eq!(
2329+ comp_reference_type_ctx(Some(single(LAST_FRAME)), Some(single(BWDREF_FRAME))),
2330+ 1
2331+ );
2332+ }
2333+
2334+ /// Both edges bidirectional compound: libaom's `ctx = 0`.
2335+ #[test]
2336+ fn comp_reference_type_ctx_bidir_bidir_is_zero() {
2337+ assert_eq!(
2338+ comp_reference_type_ctx(
2339+ Some(comp(LAST_FRAME, BWDREF_FRAME, false)),
2340+ Some(comp(LAST2_FRAME, ALTREF_FRAME, false))
2341+ ),
2342+ 0
2343+ );
2344+ }
2345+
2346+ /// Both edges unidirectional compound: libaom's `3 + !(a==BWDREF ^
2347+ /// l==BWDREF)`.
2348+ #[test]
2349+ fn comp_reference_type_ctx_unidir_unidir() {
2350+ assert_eq!(
2351+ comp_reference_type_ctx(
2352+ Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2353+ Some(comp(LAST_FRAME, LAST3_FRAME, true))
2354+ ),
2355+ 4
2356+ );
2357+ assert_eq!(
2358+ comp_reference_type_ctx(
2359+ Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2360+ Some(comp(BWDREF_FRAME, ALTREF_FRAME, true))
2361+ ),
2362+ 3
2363+ );
2364+ }
2365+
2366+ /// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` beats `LAST3`/
2367+ /// `GOLDEN` in the vote, context 2 (libaom's `<` branch reversed --
2368+ /// fewer `a`s than `b`s is context 0, matching [`ref_ctx`]'s shared
2369+ /// convention).
2370+ #[test]
2371+ fn uni_comp_ref_p1_ctx_matches_ref_ctx_shape() {
2372+ assert_eq!(uni_comp_ref_p1_ctx(Some(LAST2_FRAME), None), 2);
2373+ assert_eq!(uni_comp_ref_p1_ctx(Some(LAST3_FRAME), None), 0);
2374+ assert_eq!(uni_comp_ref_p1_ctx(None, None), 1);
2375+ }
2376+
2377+ // --- lane-av1comp step 4: compound mvstack (find_mv_stack_compound) ---
2378+
2379+ const COMP_PAIR: (i8, i8) = (LAST_FRAME, ALTREF_FRAME);
2380+
2381+ fn comp_inter(mv0: (i32, i32), mv1: (i32, i32)) -> MiInfo {
2382+ MiInfo {
2383+ is_inter: true,
2384+ ref_frame: COMP_PAIR.0,
2385+ ref_frame1: Some(COMP_PAIR.1),
2386+ mv: mv0,
2387+ mv1: Some(mv1),
2388+ is_new_mv: false,
2389+ size: 1,
2390+ }
2391+ }
2392+
2393+ #[test]
2394+ fn compound_scan_only_matches_the_exact_pair() {
2395+ let mut grid = MiGrid::new(8, 8);
2396+ // Same-side single-ref neighbour (LAST only) must not vote.
2397+ grid.set(1, 2, inter((4, 4)));
2398+ // Wrong second ref (GOLDEN, not ALTREF) must not vote either.
2399+ grid.set(
2400+ 1,
2401+ 3,
2402+ MiInfo {
2403+ is_inter: true,
2404+ ref_frame: LAST_FRAME,
2405+ ref_frame1: Some(GOLDEN_FRAME),
2406+ mv: (9, 9),
2407+ mv1: Some((9, 9)),
2408+ is_new_mv: false,
2409+ size: 1,
2410+ },
2411+ );
2412+ // Exact pair match.
2413+ let (mv0, mv1) = ((2, 2), (-6, 3));
2414+ grid.set(2, 1, comp_inter(mv0, mv1));
2415+
2416+ let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None);
2417+
2418+ // The exact-pair immediate scan lands one boosted entry; the
2419+ // compound extension pass (short stack, len < MAX_MV_REF_CANDIDATES)
2420+ // separately tops it up with a low-weight combo built from the two
2421+ // near-miss neighbours it's allowed to gather over regardless of
2422+ // reference frame -- a real second entry, not spurious.
2423+ assert_eq!(stack.entries.len(), 2);
2424+ assert_eq!(stack.entries[0].mv0, mv0);
2425+ assert_eq!(stack.entries[0].mv1, mv1);
2426+ assert_eq!(stack.entries[0].weight, 2 + REF_CAT_LEVEL);
2427+ assert_eq!(stack.nearest_mv, (mv0, mv1));
2428+ }
2429+
2430+ #[test]
2431+ fn compound_dedupes_same_pair_and_sums_weight() {
2432+ let mut grid = MiGrid::new(8, 8);
2433+ let (mv0, mv1) = ((4, 4), (-4, -4));
2434+ // Block at (2, 2), 2x2 mi units: above spans cols 2..4, left rows 2..4.
2435+ grid.set(1, 2, comp_inter(mv0, mv1));
2436+ grid.set(1, 3, comp_inter(mv0, mv1));
2437+ grid.set(2, 1, comp_inter(mv0, mv1));
2438+ grid.set(3, 1, comp_inter(mv0, mv1));
2439+
2440+ let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None);
2441+
2442+ // Exact libaom `is_dup` port: with exactly one entry already in the
2443+ // stack (the four identical-pair neighbours deduped by the
2444+ // immediate-scan pass), the extension combine step compares only
2445+ // `comp_list[0]` against that entry -- a match here, since both are
2446+ // built from the same identical-pair neighbours -- so it takes
2447+ // `comp_list[1]` (the *second* ref_id slot, still the same (mv0,
2448+ // mv1) pair) as a brand-new stack entry rather than folding weight
2449+ // into the existing one. Two entries, same pair, not merged.
2450+ assert_eq!(stack.entries.len(), 2);
2451+ assert_eq!(stack.entries[0].mv0, mv0);
2452+ assert_eq!(stack.entries[0].mv1, mv1);
2453+ // 2 above + 2 left cells, weight 2 each (size:1 floor), plus the
2454+ // REF_CAT_LEVEL boost every immediate-scan entry gets.
2455+ assert_eq!(stack.entries[0].weight, 8 + REF_CAT_LEVEL);
2456+ assert_eq!(stack.entries[1].mv0, mv0);
2457+ assert_eq!(stack.entries[1].mv1, mv1);
2458+ assert_eq!(stack.entries[1].weight, 2);
2459+ }
2460+
2461+ #[test]
2462+ fn compound_two_distinct_pairs_sort_by_weight() {
2463+ let mut grid = MiGrid::new(8, 8);
2464+ let above = ((4, 4), (1, 1));
2465+ let left = ((8, 8), (2, 2));
2466+ grid.set(2, 3, comp_inter(above.0, above.1));
2467+ grid.set(2, 4, comp_inter(above.0, above.1));
2468+ grid.set(3, 2, comp_inter(left.0, left.1));
2469+ grid.set(4, 2, comp_inter(left.0, left.1));
2470+ grid.set(5, 2, comp_inter(left.0, left.1));
2471+
2472+ let stack = find_mv_stack_compound(&grid, 3, 3, 2, 3, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None);
2473+
2474+ assert_eq!(stack.entries.len(), 2);
2475+ assert_eq!(stack.entries[0].mv0, left.0);
2476+ assert_eq!(stack.entries[0].mv1, left.1);
2477+ assert_eq!(stack.entries[1].mv0, above.0);
2478+ assert_eq!(stack.entries[1].mv1, above.1);
2479+ assert_eq!(stack.nearest_mv, left);
2480+ assert_eq!(stack.near_mv, above);
2481+ }
2482+
2483+ #[test]
2484+ fn combine_compound_candidates_zips_ref_id_then_ref_diff_per_side() {
2485+ let mut lists = CompoundRefLists::default();
2486+ lists.ref_id[0].push((1, 1));
2487+ lists.ref_diff[0].push((2, 2));
2488+ lists.ref_id[1].push((3, 3));
2489+ // side 1 has only one entry -> comp_idx 1 falls back to ref_diff.
2490+ lists.ref_diff[1].push((4, 4));
2491+
2492+ let combined = combine_compound_candidates(&lists);
2493+ assert_eq!(combined[0], ((1, 1), (3, 3)));
2494+ assert_eq!(combined[1], ((2, 2), (4, 4)));
2495+ }
2496+
2497+ #[test]
2498+ fn process_compound_ref_mv_candidate_splits_exact_vs_borrowed() {
2499+ let mut lists = CompoundRefLists::default();
2500+ // Exact match on side 0 (LAST_FRAME), wrong ref on side 1 -> borrowed
2501+ // into ref_diff[1] with no sign flip (NO_SIGN_BIAS).
2502+ let candidate = MiInfo {
2503+ is_inter: true,
2504+ ref_frame: LAST_FRAME,
2505+ ref_frame1: None,
2506+ mv: (5, 5),
2507+ mv1: None,
2508+ is_new_mv: false,
2509+ size: 1,
2510+ };
2511+ process_compound_ref_mv_candidate(&candidate, COMP_PAIR, &NO_SIGN_BIAS, &mut lists);
2512+ assert_eq!(lists.ref_id[0], vec![(5, 5)]);
2513+ assert_eq!(lists.ref_diff[1], vec![(5, 5)]);
2514+ assert!(lists.ref_id[1].is_empty());
2515+ assert!(lists.ref_diff[0].is_empty());
2516+ }
2517+
2518+ #[test]
2519+ fn compound_extension_pass_tops_up_a_short_stack() {
2520+ // No exact-pair neighbour at all, but a LAST-only neighbour above and
2521+ // an ALTREF-only neighbour left: the extension pass should combine
2522+ // them into one topped-up candidate rather than leaving the stack
2523+ // empty.
2524+ let mut grid = MiGrid::new(8, 8);
2525+ grid.set(
2526+ 1,
2527+ 2,
2528+ MiInfo {
2529+ is_inter: true,
2530+ ref_frame: LAST_FRAME,
2531+ ref_frame1: None,
2532+ mv: (7, 7),
2533+ mv1: None,
2534+ is_new_mv: false,
2535+ size: 8,
2536+ },
2537+ );
2538+ grid.set(
2539+ 2,
2540+ 1,
2541+ MiInfo {
2542+ is_inter: true,
2543+ ref_frame: ALTREF_FRAME,
2544+ ref_frame1: None,
2545+ mv: (-3, -3),
2546+ mv1: None,
2547+ is_new_mv: false,
2548+ size: 8,
2549+ },
2550+ );
2551+
2552+ let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, None);
2553+
2554+ // The combine step (libaom's real "Handle compound reference frame
2555+ // extension") zips each side's ref_id-then-ref_diff lists
2556+ // independently, producing *two* distinct combos here (the exact
2557+ // match and the borrowed one land on opposite sides for each combo
2558+ // index) — both get added, `MAX_MV_REF_CANDIDATES` (2) is exactly
2559+ // this stack's cap.
2560+ assert_eq!(stack.entries.len(), 2);
2561+ assert_eq!(stack.entries[0].weight, 2);
2562+ // combo 0: side 0's own exact ref_id match, side 1's borrowed one.
2563+ assert_eq!(stack.entries[0].mv0, (7, 7));
2564+ assert_eq!(stack.entries[0].mv1, (-3, -3));
2565+ // combo 1: the mirror -- side 0's borrowed entry, side 1's own exact
2566+ // ref_id match.
2567+ assert_eq!(stack.entries[1].mv0, (-3, -3));
2568+ assert_eq!(stack.entries[1].mv1, (7, 7));
2569+ }
14282570 }
crates/ec-av1/src/stream.rsmodified+461 -24
@@ -79,6 +79,43 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
7979 let obu_offset = pos;
8080 pos += obu.total_size;
8181
82+ if let ObuKind::FrameHeader(header) = &obu.kind {
83+ // `show_existing_frame` (spec 7.21/5.9.2): no tile payload, this
84+ // OBU only names a DPB slot to output again -- the coded-frame
85+ // count and the shown-picture count are different things (a
86+ // hidden altref's own `Frame` OBU below is never pushed to
87+ // `pictures` on its own; it is only pushed here, later, when a
88+ // `show_existing_frame` header names its slot). Before r15 this
89+ // arm didn't exist at all: every `ObuKind::Frame` was pushed
90+ // unconditionally regardless of `show_frame`, so a hidden altref
91+ // was emitted (wrongly, in decode order) and its real
92+ // `show_existing_frame` output was silently dropped.
93+ let slot = header.frame_to_show_map_idx as usize;
94+ let picture = ref_slots[slot].clone().ok_or_else(|| {
95+ Error::unsupported(
96+ "AV1 decode_stream",
97+ "a show_existing_frame header naming an empty reference slot",
98+ )
99+ })?;
100+ for i in 0..NUM_REF_FRAMES {
101+ if header.refresh_frame_flags & (1 << i) != 0 {
102+ cdf_slots[i] = cdf_slots[slot].clone();
103+ ref_slots[i] = Some(picture.clone());
104+ motion_field_slots[i] = motion_field_slots[slot].clone();
105+ order_hint_slots[i] = order_hint_slots[slot];
106+ }
107+ }
108+ let output = if header.film_grain.apply_grain {
109+ let mc_identity = parser
110+ .sequence_header()
111+ .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
112+ crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity)
113+ } else {
114+ picture
115+ };
116+ pictures.push(output);
117+ continue;
118+ }
82119 let ObuKind::Frame(header, tiles) = obu.kind else {
83120 continue;
84121 };
@@ -178,21 +215,14 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
178215 "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)",
179216 ));
180217 }
181- // `decode_inter_block`'s `single_ref_p*` chain codes only
182- // `SINGLE_REFERENCE` blocks (never reads `comp_mode`) -- a frame
183- // whose `reference_select` header bit lets any block choose
184- // `COMPOUND_REFERENCE` would desync at the first block that reads
185- // a `comp_mode` symbol this decoder never consumes. `skip_mode`
186- // (spec 5.9.22) is provably unreachable here as a consequence: its
187- // own `skip_mode_params()` only sets `skip_mode_present` when
188- // `reference_select` is set, so refusing `reference_select` refuses
189- // `skip_mode` too, without needing a second check.
190- if header.reference_select {
191- return Err(Error::unsupported(
192- "AV1 decode_stream",
193- "a frame with reference_select set (this decoder never reads comp_mode / codes only single-reference blocks)",
194- ));
195- }
218+ // lane-av1comp: `decode_inter_block`/`decode_inter_block8` now read
219+ // `comp_mode` per block whenever this frame's own `reference_select`
220+ // header bit is set (spec 5.11.25), and refuse by name the blocks
221+ // that pick `COMPOUND_REFERENCE` -- two-reference motion
222+ // compensation is not wired yet. Round 14: `skip_mode` (spec 5.9.22)
223+ // is wired at the block level too (forced NEAREST_NEARESTMV compound
224+ // of `skip_mode_frame`, plain average blend), so the old blanket
225+ // `skip_mode_present` refusal is gone.
196226 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
197227 // which tile's end-of-tile adapted CDFs become the frame's own; this
198228 // decoder only ever decodes tile 0 (`tiles.first()` above), so a
@@ -218,6 +248,13 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
218248 let enable_edge_filter = parser
219249 .sequence_header()
220250 .is_some_and(|seq| seq.enable_intra_edge_filter);
251+ // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits.
252+ let enable_masked_compound = parser
253+ .sequence_header()
254+ .is_some_and(|seq| seq.enable_masked_compound);
255+ let enable_jnt_comp = parser
256+ .sequence_header()
257+ .is_some_and(|seq| seq.enable_jnt_comp);
221258 let interp_fixed = match header.interpolation_filter {
222259 ec_av1_syntax::InterpolationFilter::Switchable => None,
223260 fixed => Some(crate::mc::InterpFilterKind::from_header(fixed)),
@@ -337,6 +374,11 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
337374 header.order_hint,
338375 ref_order_hints,
339376 tpl_field.as_ref(),
377+ header.reference_select,
378+ enable_masked_compound,
379+ enable_jnt_comp,
380+ header.skip_mode_present,
381+ header.skip_mode_frame,
340382 )?
341383 };
342384 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
@@ -382,15 +424,17 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
382424 order_hint_slots[i] = header.order_hint;
383425 }
384426 }
385- let output = if header.film_grain.apply_grain {
386- let mc_identity = parser
387- .sequence_header()
388- .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
389- crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity)
390- } else {
391- picture
392- };
393- pictures.push(output);
427+ if header.show_frame {
428+ let output = if header.film_grain.apply_grain {
429+ let mc_identity = parser
430+ .sequence_header()
431+ .is_some_and(|seq| seq.color_config.matrix_coefficients == 0);
432+ crate::film_grain::apply_grain(&picture, &header.film_grain, mc_identity)
433+ } else {
434+ picture
435+ };
436+ pictures.push(output);
437+ }
394438 }
395439 Ok(pictures)
396440 }
@@ -513,6 +557,22 @@ mod tests {
513557 use std::io::Write;
514558 use std::process::{Command, Stdio};
515559
560+ /// Firing-detection gates (single-ref envelope, temporal-MV, `comp_mode`,
561+ /// `skip_mode`/compound) all read a process-global atomic counter delta
562+ /// (`decode::ref_hits`/`tmv_hits`/`comp_mode_hits`/`skip_mode_hits`) to
563+ /// prove a real block picked the feature under test, not just that a
564+ /// header bit was set. Under `cargo test`'s default parallel run, a
565+ /// SIBLING test's own decode bumps the same global counter mid-gate --
566+ /// a false "fired" reading pixel-compares an attempt the gate would
567+ /// otherwise `continue` past, on top of genuine defects that path may
568+ /// still have. Serialising every counter-delta gate behind this one
569+ /// mutex makes firing detection honest again (matches the existing
570+ /// cdf-forwarding-gate flake shape, ledger `omp-liveness-pgrep-self-match`).
571+ static GATE_COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
572+ fn lock_gate_counters() -> std::sync::MutexGuard<'static, ()> {
573+ GATE_COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner())
574+ }
575+
516576 fn have_ffmpeg() -> bool {
517577 Command::new("ffmpeg")
518578 .arg("-version")
@@ -2239,6 +2299,7 @@ mod tests {
22392299 frame_count: usize,
22402300 attempts: u32,
22412301 ) {
2302+ let _gate_lock = lock_gate_counters();
22422303 if !have_ffmpeg() {
22432304 eprintln!("SKIP {gate_name}: no ffmpeg");
22442305 return;
@@ -2400,6 +2461,365 @@ mod tests {
24002461 );
24012462 }
24022463
2464+ /// lane-av1comp: proves `reference_select`/`comp_mode` are actually read
2465+ /// off a real bitstream rather than only unit-tested in isolation --
2466+ /// `--auto-alt-ref=1 --lag-in-frames=16` gives aomenc a backward
2467+ /// reference to pick `COMPOUND_REFERENCE` with, `--enable-order-hint=1`
2468+ /// is required for it to ever consider compound at all. Three
2469+ /// acceptable outcomes: (a) a stream where `reference_select` never
2470+ /// actually drove a block to `COMPOUND_REFERENCE` decodes bit-exact end
2471+ /// to end (proving the per-block `comp_mode` read did not desync the
2472+ /// single-ref blocks around it); (b) a stream that does fire compound
2473+ /// is refused by name with [`decode::comp_mode_hits`] having advanced
2474+ /// (proving `comp_mode`/`read_compound_ref_frames` consumed the right
2475+ /// symbols before refusing, rather than desyncing and refusing for an
2476+ /// unrelated reason) -- masked/wedge compound (`comp_group_idx == 1`)
2477+ /// and a partition below 16x16 (a real, separately tracked capability
2478+ /// gap) are the two refusal arms this can still legitimately name; (c)
2479+ /// r13 wired plain `COMPOUND_AVERAGE` MC for real, so as of r15 a
2480+ /// stream that fires compound may also decode fully -- accepted only
2481+ /// when every output frame is pixel-exact against ffmpeg.
2482+ #[test]
2483+ fn a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly() {
2484+ const NAME: &str = "a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly";
2485+ let _gate_lock = lock_gate_counters();
2486+ if !have_ffmpeg() {
2487+ eprintln!("SKIP {NAME}: no ffmpeg");
2488+ return;
2489+ }
2490+ if !have_aomenc() {
2491+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2492+ return;
2493+ }
2494+ let (width, height, frame_count) = (64usize, 64usize, 20usize);
2495+ let mut refusals = Vec::new();
2496+ let mut never_fired = 0u32;
2497+ for attempt in 0..60u32 {
2498+ let seed = 42 + attempt % 40;
2499+ let duration = frame_count as f64 / 25.0;
2500+ let source =
2501+ format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25");
2502+ let y4m = Command::new("ffmpeg")
2503+ .args([
2504+ "-v",
2505+ "error",
2506+ "-f",
2507+ "lavfi",
2508+ "-i",
2509+ &source,
2510+ "-pix_fmt",
2511+ "yuv420p",
2512+ "-f",
2513+ "yuv4mpegpipe",
2514+ "-",
2515+ ])
2516+ .stdin(Stdio::null())
2517+ .stdout(Stdio::piped())
2518+ .stderr(Stdio::piped())
2519+ .output()
2520+ .expect("ffmpeg failed to run");
2521+ assert!(
2522+ y4m.status.success(),
2523+ "ffmpeg fixture: {}",
2524+ String::from_utf8_lossy(&y4m.stderr)
2525+ );
2526+ let args: Vec<&str> = vec![
2527+ "--codec=av1",
2528+ "--passes=1",
2529+ "--end-usage=q",
2530+ "--cq-level=45",
2531+ "--cpu-used=0",
2532+ "--kf-max-dist=1000",
2533+ "--threads=1",
2534+ "--row-mt=0",
2535+ "--auto-alt-ref=1",
2536+ "--lag-in-frames=16",
2537+ "--enable-order-hint=1",
2538+ "--enable-warped-motion=0",
2539+ "--enable-obmc=0",
2540+ "--enable-masked-comp=0",
2541+ "--enable-interintra-comp=0",
2542+ "--enable-onesided-comp=0",
2543+ "--enable-interintra-wedge=0",
2544+ "--enable-smooth-interintra=0",
2545+ "--enable-rect-partitions=0",
2546+ "--enable-ab-partitions=0",
2547+ "--enable-1to4-partitions=0",
2548+ "--enable-filter-intra=0",
2549+ "--enable-smooth-intra=0",
2550+ "--enable-paeth-intra=0",
2551+ "--enable-directional-intra=0",
2552+ "--enable-angle-delta=0",
2553+ "--enable-tx-size-search=0",
2554+ "--enable-cdef=0",
2555+ "--enable-restoration=0",
2556+ "--max-partition-size=32",
2557+ "--min-partition-size=32",
2558+ "--enable-palette=0",
2559+ "--enable-intrabc=0",
2560+ "--enable-cfl-intra=0",
2561+ "--enable-ref-frame-mvs=0",
2562+ "--obu",
2563+ "-o",
2564+ "-",
2565+ "-",
2566+ ];
2567+ let mut child = Command::new(aomenc_path())
2568+ .args(&args)
2569+ .stdin(Stdio::piped())
2570+ .stdout(Stdio::piped())
2571+ .stderr(Stdio::piped())
2572+ .spawn()
2573+ .expect("aomenc failed to start");
2574+ child
2575+ .stdin
2576+ .take()
2577+ .expect("aomenc stdin")
2578+ .write_all(&y4m.stdout)
2579+ .expect("writing y4m to aomenc");
2580+ let out = child.wait_with_output().expect("aomenc failed to run");
2581+ assert!(
2582+ out.status.success(),
2583+ "aomenc refused the fixture: {}",
2584+ String::from_utf8_lossy(&out.stderr)
2585+ );
2586+ let stream = out.stdout;
2587+ let before = decode::comp_mode_hits();
2588+ match decode_stream(&stream) {
2589+ Err(e) => {
2590+ let msg = e.to_string();
2591+ let fired = decode::comp_mode_hits() > before;
2592+ assert!(
2593+ msg.contains("unsupported"),
2594+ "{NAME} failed outright (seed {seed}): {msg}"
2595+ );
2596+ if fired {
2597+ // `comp_mode` firing does not stop the block walk --
2598+ // a later, unrelated block in the same tile can
2599+ // still hit any other named refusal this decoder
2600+ // carries. A partition below 16x16 is a real, open
2601+ // capability gap tracked on its own (not a
2602+ // COMPOUND_REFERENCE defect); accept it here too
2603+ // rather than fail a compound-specific gate on a
2604+ // partition-search coincidence.
2605+ assert!(
2606+ msg.contains("COMPOUND_REFERENCE") || msg.contains("a partition"),
2607+ "{NAME}: comp_mode fired (seed {seed}) but the refusal \
2608+ was for something else: {msg}"
2609+ );
2610+ let advanced = decode::comp_mode_hits() - before;
2611+ eprintln!(
2612+ "{NAME} FIRING seed {seed}: comp_mode hits advanced by \
2613+ {advanced}, refused by name as expected: {msg}"
2614+ );
2615+ return;
2616+ }
2617+ refusals.push(format!("seed {seed}: {msg}"));
2618+ continue;
2619+ }
2620+ Ok(frames) => {
2621+ if decode::comp_mode_hits() == before {
2622+ never_fired += 1;
2623+ continue;
2624+ }
2625+ // Outcome (c): plain COMPOUND_AVERAGE decoded fully --
2626+ // non-negotiable pixel exactness, no tolerance.
2627+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2628+ assert_eq!(frames.len(), frame_count);
2629+ let mismatched = frames
2630+ .iter()
2631+ .zip(&ffmpeg_frames)
2632+ .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2633+ if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
2634+ std::fs::write(&path, &stream).expect("writing pinned stream");
2635+ eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
2636+ }
2637+ for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2638+ assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
2639+ assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
2640+ assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
2641+ }
2642+ eprintln!(
2643+ "{NAME} FIRING seed {seed}: comp_mode hits advanced by {}, decoded \
2644+ fully and pixel-exact",
2645+ decode::comp_mode_hits() - before
2646+ );
2647+ return;
2648+ }
2649+ }
2650+ }
2651+ eprintln!(
2652+ "SKIP {NAME}: {never_fired} attempts decoded fully (reference_select never drove a \
2653+ block to COMPOUND_REFERENCE) and every other attempt hit a named refusal that never \
2654+ reached comp_mode:\n{}",
2655+ refusals.join("\n")
2656+ );
2657+ }
2658+
2659+ /// lane-av1comp round 14's decisive gate for `skip_mode`: same
2660+ /// pin-on-mismatch pattern as [`a_real_aomenc_single_ref_gate`], proving
2661+ /// [`decode::skip_mode_hits`] actually advanced (a real block picked
2662+ /// `skip_mode`, not just that the frame header bit was set) and that the
2663+ /// resulting forced-compound `NEAREST_NEARESTMV` decode is still
2664+ /// pixel-exact against ffmpeg. `--auto-alt-ref=1 --lag-in-frames=16
2665+ /// --enable-fwd-kf=0` (backward references) plus
2666+ /// `--enable-ref-frame-mvs=0` (unimplemented temporal MV projection,
2667+ /// same as every other gate here) is aomenc's own requirement for
2668+ /// `skip_mode_present` to ever be considered at all (spec 5.9.22 needs
2669+ /// both a forward and a backward reference candidate).
2670+ #[test]
2671+ fn a_real_aomenc_stream_with_compound_references_decodes_pixel_exact() {
2672+ const NAME: &str = "a_real_aomenc_stream_with_compound_references_decodes_pixel_exact";
2673+ let _gate_lock = lock_gate_counters();
2674+ if !have_ffmpeg() {
2675+ eprintln!("SKIP {NAME}: no ffmpeg");
2676+ return;
2677+ }
2678+ if !have_aomenc() {
2679+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
2680+ return;
2681+ }
2682+ let (width, height, frame_count) = (64usize, 64usize, 24usize);
2683+ let mut refusals = Vec::new();
2684+ let mut never_fired = 0u32;
2685+ for attempt in 0..80u32 {
2686+ let seed = 42 + attempt % 40;
2687+ let duration = frame_count as f64 / 25.0;
2688+ let source =
2689+ format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25");
2690+ let y4m = Command::new("ffmpeg")
2691+ .args([
2692+ "-v",
2693+ "error",
2694+ "-f",
2695+ "lavfi",
2696+ "-i",
2697+ &source,
2698+ "-pix_fmt",
2699+ "yuv420p",
2700+ "-f",
2701+ "yuv4mpegpipe",
2702+ "-",
2703+ ])
2704+ .stdin(Stdio::null())
2705+ .stdout(Stdio::piped())
2706+ .stderr(Stdio::piped())
2707+ .output()
2708+ .expect("ffmpeg failed to run");
2709+ assert!(
2710+ y4m.status.success(),
2711+ "ffmpeg fixture: {}",
2712+ String::from_utf8_lossy(&y4m.stderr)
2713+ );
2714+ let args: Vec<&str> = vec![
2715+ "--codec=av1",
2716+ "--passes=1",
2717+ "--end-usage=q",
2718+ "--cq-level=45",
2719+ "--cpu-used=0",
2720+ "--kf-max-dist=1000",
2721+ "--threads=1",
2722+ "--row-mt=0",
2723+ "--auto-alt-ref=1",
2724+ "--lag-in-frames=16",
2725+ "--enable-fwd-kf=0",
2726+ "--enable-order-hint=1",
2727+ "--enable-warped-motion=0",
2728+ "--enable-obmc=0",
2729+ "--enable-masked-comp=0",
2730+ "--enable-interintra-comp=0",
2731+ "--enable-onesided-comp=0",
2732+ "--enable-interintra-wedge=0",
2733+ "--enable-smooth-interintra=0",
2734+ "--enable-rect-partitions=0",
2735+ "--enable-ab-partitions=0",
2736+ "--enable-1to4-partitions=0",
2737+ "--enable-filter-intra=0",
2738+ "--enable-smooth-intra=0",
2739+ "--enable-paeth-intra=0",
2740+ "--enable-directional-intra=0",
2741+ "--enable-angle-delta=0",
2742+ "--enable-tx-size-search=0",
2743+ "--enable-cdef=0",
2744+ "--enable-restoration=0",
2745+ "--max-partition-size=32",
2746+ "--min-partition-size=32",
2747+ "--enable-palette=0",
2748+ "--enable-intrabc=0",
2749+ "--enable-cfl-intra=0",
2750+ "--enable-ref-frame-mvs=0",
2751+ "--obu",
2752+ "-o",
2753+ "-",
2754+ "-",
2755+ ];
2756+ let mut child = Command::new(aomenc_path())
2757+ .args(&args)
2758+ .stdin(Stdio::piped())
2759+ .stdout(Stdio::piped())
2760+ .stderr(Stdio::piped())
2761+ .spawn()
2762+ .expect("aomenc failed to start");
2763+ child
2764+ .stdin
2765+ .take()
2766+ .expect("aomenc stdin")
2767+ .write_all(&y4m.stdout)
2768+ .expect("writing y4m to aomenc");
2769+ let out = child.wait_with_output().expect("aomenc failed to run");
2770+ assert!(
2771+ out.status.success(),
2772+ "aomenc refused the fixture: {}",
2773+ String::from_utf8_lossy(&out.stderr)
2774+ );
2775+ let stream = out.stdout;
2776+ let before = decode::skip_mode_hits();
2777+ let frames = match decode_stream(&stream) {
2778+ Err(e) => {
2779+ let msg = e.to_string();
2780+ assert!(
2781+ msg.contains("unsupported"),
2782+ "{NAME} failed outright (seed {seed}): {msg}"
2783+ );
2784+ refusals.push(format!("seed {seed}: {msg}"));
2785+ continue;
2786+ }
2787+ Ok(frames) => frames,
2788+ };
2789+ if decode::skip_mode_hits() == before {
2790+ never_fired += 1;
2791+ continue;
2792+ }
2793+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2794+ assert_eq!(frames.len(), frame_count);
2795+ let mismatched = frames
2796+ .iter()
2797+ .zip(&ffmpeg_frames)
2798+ .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2799+ if mismatched {
2800+ if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
2801+ std::fs::write(&path, &stream).expect("writing pinned stream");
2802+ eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
2803+ }
2804+ }
2805+ for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2806+ assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
2807+ assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
2808+ assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
2809+ }
2810+ eprintln!(
2811+ "{NAME} FIRING seed {seed}: skip_mode hits advanced by {}",
2812+ decode::skip_mode_hits() - before
2813+ );
2814+ return;
2815+ }
2816+ eprintln!(
2817+ "SKIP {NAME}: {never_fired} attempts decoded but never fired skip_mode, and every \
2818+ other attempt hit a named refusal:\n{}",
2819+ refusals.join("\n")
2820+ );
2821+ }
2822+
24032823 /// `LAST2_FRAME`/`LAST3_FRAME` are just older slots in the same forward
24042824 /// reference-buffer ring `LAST_FRAME`/`GOLDEN_FRAME` already prove --
24052825 /// dropping the golden gate's `--max-reference-frames=3
@@ -2503,6 +2923,7 @@ mod tests {
25032923 /// count as a real pass rather than a `never_fired` skip.
25042924 fn a_real_aomenc_temporal_mv_gate(seed_base: u32, attempts: u32) {
25052925 let gate_name = "a_real_aomenc_temporal_mv_gate";
2926+ let _gate_lock = lock_gate_counters();
25062927 if !have_ffmpeg() {
25072928 eprintln!("SKIP {gate_name}: no ffmpeg");
25082929 return;
@@ -2669,6 +3090,22 @@ mod tests {
26693090 a_real_aomenc_temporal_mv_gate(42, 40);
26703091 }
26713092
3093+ /// r17 bisect scratch: decode a pinned stream exactly once, so
3094+ /// `decode::r17_dump`'s frame index (a process-wide counter) lines up
3095+ /// with `aomdec`'s own per-frame `EC_AV1_PREFILT_DUMP`/
3096+ /// `EC_AV1_POSTFILT_DUMP` numbering. Remove with the rest of the r17
3097+ /// scaffolding.
3098+ #[test]
3099+ #[ignore]
3100+ fn scratch_decode_pinned_stream_once() {
3101+ let path = std::env::var("EC_AV1_PIN").expect("set EC_AV1_PIN to the .obu path");
3102+ let stream = std::fs::read(&path).expect("read pinned stream");
3103+ match decode_stream(&stream) {
3104+ Ok(frames) => eprintln!("OK: {} frames", frames.len()),
3105+ Err(e) => eprintln!("ERR: {e}"),
3106+ }
3107+ }
3108+
26723109 /// scratch: decode a pinned stream end to end and report where/why it
26733110 /// refuses, plus `non_last_ref_hits` progression.
26743111 #[test]
crates/ec-av1/src/tile.rsmodified+16 -0
@@ -2434,6 +2434,8 @@ pub fn sb_coeff_inter_frame_tile(
24342434 MiInfo {
24352435 is_inter: true,
24362436 ref_frame: LAST_FRAME,
2437+ ref_frame1: None,
2438+ mv1: None,
24372439 mv,
24382440 is_new_mv,
24392441 size: 8,
@@ -2450,6 +2452,8 @@ pub fn sb_coeff_inter_frame_tile(
24502452 MiInfo {
24512453 is_inter: true,
24522454 ref_frame: LAST_FRAME,
2455+ ref_frame1: None,
2456+ mv1: None,
24532457 mv,
24542458 is_new_mv,
24552459 size: 8,
@@ -2477,6 +2481,8 @@ pub fn sb_coeff_inter_frame_tile(
24772481 MiInfo {
24782482 is_inter: false,
24792483 ref_frame: -1,
2484+ ref_frame1: None,
2485+ mv1: None,
24802486 mv: (0, 0),
24812487 is_new_mv: false,
24822488 size: 8,
@@ -2615,6 +2621,8 @@ fn write_inter_frame_leaf(
26152621 MiInfo {
26162622 is_inter: true,
26172623 ref_frame: LAST_FRAME,
2624+ ref_frame1: None,
2625+ mv1: None,
26182626 mv,
26192627 is_new_mv,
26202628 size: SUB_MI as usize,
@@ -2642,6 +2650,8 @@ fn write_inter_frame_leaf(
26422650 MiInfo {
26432651 is_inter: false,
26442652 ref_frame: -1,
2653+ ref_frame1: None,
2654+ mv1: None,
26452655 mv: (0, 0),
26462656 is_new_mv: false,
26472657 size: SUB_MI as usize,
@@ -2803,6 +2813,8 @@ fn write_inter_frame_leaf8(
28032813 MiInfo {
28042814 is_inter: true,
28052815 ref_frame: LAST_FRAME,
2816+ ref_frame1: None,
2817+ mv1: None,
28062818 mv,
28072819 is_new_mv,
28082820 size: 2,
@@ -2830,6 +2842,8 @@ fn write_inter_frame_leaf8(
28302842 MiInfo {
28312843 is_inter: false,
28322844 ref_frame: -1,
2845+ ref_frame1: None,
2846+ mv1: None,
28332847 mv: (0, 0),
28342848 is_new_mv: false,
28352849 size: 2,
@@ -5082,6 +5096,8 @@ mod tests {
50825096 MiInfo {
50835097 is_inter: true,
50845098 ref_frame: 1,
5099+ ref_frame1: None,
5100+ mv1: None,
50855101 mv,
50865102 is_new_mv,
50875103 size: 8,