diff --git a/crates/ec-av1/src/compound.rs b/crates/ec-av1/src/compound.rs new file mode 100644 index 00000000..028cc574 --- /dev/null +++ b/crates/ec-av1/src/compound.rs @@ -0,0 +1,121 @@ +//! Compound-reference blend weights (spec 7.11.3.15's "Distance weights +//! process", libaom's `av1_dist_wtd_comp_weight_assign` in +//! `reconinter.c`) -- pure, independent of the CDF/bitstream plumbing that +//! decides *whether* a block reads `compound_idx` at all (lane-av1comp, +//! decode.rs). Kept its own module so it is testable without a live +//! decoder: `dist_wtd_comp_weight_assign` takes exactly the four order +//! hints libaom's version reads off `AV1_COMMON`/`MB_MODE_INFO`. + +/// `MAX_FRAME_DISTANCE` (spec/`enums.h`): `(1 << FRAME_OFFSET_BITS) - 1`, +/// `FRAME_OFFSET_BITS == 5`. +const MAX_FRAME_DISTANCE: i32 = (1 << 5) - 1; + +/// `quant_dist_weight` (libaom `common_data.h`) -- the three candidate +/// weight ratios the search below picks between, before falling back to the +/// index-3 row when either distance is zero. +const QUANT_DIST_WEIGHT: [[i32; 2]; 4] = [[2, 3], [2, 5], [2, 7], [1, MAX_FRAME_DISTANCE]]; + +/// `quant_dist_lookup_table` (libaom `common_data.h`): the actual +/// `fwd_offset`/`bck_offset` pair each `QUANT_DIST_WEIGHT` row resolves to +/// (both always sum to 16, `1 << DIST_PRECISION_BITS`). +const QUANT_DIST_LOOKUP_TABLE: [[i32; 2]; 4] = [[9, 7], [11, 5], [12, 4], [13, 3]]; + +/// `av1_dist_wtd_comp_weight_assign` (spec 7.11.3.15 / libaom +/// `reconinter.c`): `(fwd_weight, bck_weight)` for a compound block, given +/// this frame's own `order_hint` and the two references' order hints -- +/// `ref0_order_hint` names `mbmi->ref_frame[0]` (libaom's "`bck`", despite +/// the name -- it is nearer in decode order for a typical GOP but the +/// spec's algebra does not assume that), `ref1_order_hint` names +/// `ref_frame[1]` ("`fwd`"). +/// +/// `compound_idx == 1` (or `!is_compound`, never reached from here) is the +/// simple-average caller's job: it never calls this and uses `(8, 8)` +/// directly (spec 7.11.3.15's `use_dist_wtd_comp_avg == 0` branch) -- +/// this function only ever implements the `use_dist_wtd_comp_avg == 1` +/// (`compound_idx == 0`) branch. +pub(crate) fn dist_wtd_comp_weight_assign( + order_hint_bits: u32, + cur_order_hint: u32, + ref0_order_hint: u32, + ref1_order_hint: u32, +) -> (i32, i32) { + let d0 = + crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint) + .abs() + .clamp(0, MAX_FRAME_DISTANCE); + let d1 = + crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint) + .abs() + .clamp(0, MAX_FRAME_DISTANCE); + + let order = usize::from(d0 <= d1); + + if d0 == 0 || d1 == 0 { + return ( + QUANT_DIST_LOOKUP_TABLE[3][order], + QUANT_DIST_LOOKUP_TABLE[3][1 - order], + ); + } + + let mut i = 0; + while i < 3 { + let c0 = QUANT_DIST_WEIGHT[i][order]; + let c1 = QUANT_DIST_WEIGHT[i][1 - order]; + let d0_c0 = d0 * c0; + let d1_c1 = d1 * c1; + if (d0 > d1 && d0_c0 < d1_c1) || (d0 <= d1 && d0_c0 > d1_c1) { + break; + } + i += 1; + } + + ( + QUANT_DIST_LOOKUP_TABLE[i][order], + QUANT_DIST_LOOKUP_TABLE[i][1 - order], + ) +} + +#[cfg(test)] +mod tests { + use super::dist_wtd_comp_weight_assign; + + /// Equidistant references (spec/libaom's `d0 == d1` case) land on + /// `order == 1` (`d0 <= d1`) throughout, and the very first weight + /// candidate (`i == 0`, ratio `2:3`) always survives the search's break + /// condition when `d0_c0 == d1_c1`'s neither branch fires -- so a + /// symmetric GOP (order hints `8` behind and `8` ahead of a `16`-hint + /// current frame) resolves to the row-0 weights `(7, 9)`: `order == 1` + /// (`d0 <= d1`) selects `QUANT_DIST_LOOKUP_TABLE[0][1] == 7` for + /// `fwd_offset` and `QUANT_DIST_LOOKUP_TABLE[0][0] == 9` for + /// `bck_offset`. + #[test] + fn equidistant_references_pick_the_first_weight_row() { + assert_eq!(dist_wtd_comp_weight_assign(8, 16, 8, 24), (7, 9)); + } + + /// A reference at zero relative distance (this frame repeats one of its + /// own references' order hint -- degenerate but spec-legal) always + /// takes the index-3 lookup row (`13`/`3`) rather than entering the + /// weight search, matching libaom's `d0 == 0 || d1 == 0` early return. + #[test] + fn zero_distance_reference_takes_the_index_3_row() { + // ref1 (fwd) coincides with cur -> d0 == 0. + assert_eq!(dist_wtd_comp_weight_assign(8, 16, 8, 16), (3, 13)); + } + + /// Weights always sum to `1 << DIST_PRECISION_BITS == 16` -- every row + /// of `QUANT_DIST_LOOKUP_TABLE` was picked to hold that invariant, and + /// [`combine_compound`](crate::mc::combine_compound)'s final shift + /// (`InterPostRound + DIST_PRECISION_BITS`) assumes it. + #[test] + fn weights_always_sum_to_sixteen() { + for cur in [0u32, 16, 40] { + for r0 in [0u32, 8, 32] { + for r1 in [4u32, 24, 48] { + let (fwd, bck) = dist_wtd_comp_weight_assign(8, cur, r0, r1); + assert_eq!(fwd + bck, 16, "cur={cur} r0={r0} r1={r1}"); + } + } + } + } +} diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index e749bf2a..6a3136b5 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -15,6 +15,7 @@ pub mod bits; pub mod cdf; mod cdf_state; +mod compound; pub mod decode; pub mod encode; pub mod encoder; diff --git a/crates/ec-av1/src/mc.rs b/crates/ec-av1/src/mc.rs index 2c6821a2..ed3965da 100644 --- a/crates/ec-av1/src/mc.rs +++ b/crates/ec-av1/src/mc.rs @@ -411,6 +411,154 @@ pub fn predict_with_filters( crate::encode::stage_add(1, stage_t.elapsed()); } +/// `InterRound1` for a compound ref (spec 7.11.3.2's `isCompound` branch, +/// `COMPOUND_ROUND1_BITS` in libaom's `convolve.h`): 4 bits shallower than +/// [`INTER_ROUND_1`] so the vertical pass lands in the `CONV_BUF` domain +/// (still above 8-bit pixel range) instead of a finished sample -- +/// `predict_compound_intermediate` below stops there and leaves the final +/// clip to whichever combine step (simple/distance-weighted average, or a +/// future masked blend) runs on the pair of intermediates. +const INTER_ROUND_1_COMPOUND: u32 = 7; + +/// `InterPostRound` (spec 7.11.3.2): `2 * FILTER_BITS - (InterRound0 + +/// InterRound1)` with the *compound* `InterRound1` above -- `2*7 - (3+7) == +/// 4`. [`combine_compound`] folds this together with `DIST_PRECISION_BITS` +/// (below) into one final shift. +const INTER_POST_ROUND: u32 = 4; + +/// `DIST_PRECISION_BITS` (spec 7.11.3.15 / libaom `enums.h`): the two +/// weights [`combine_compound`] takes always sum to `1 << 4 == 16`, whether +/// they are the simple-average split (8/8) or a distance-weighted split +/// from [`crate::compound::dist_wtd_comp_weight_assign`]. +const DIST_PRECISION_BITS: u32 = 4; + +/// [`predict_with_filters`]'s compound counterpart: same two-pass separable +/// filter, but the vertical pass rounds by [`INTER_ROUND_1_COMPOUND`] +/// instead of [`INTER_ROUND_1`] and is never clipped to a pixel -- the +/// `CONV_BUF` intermediate domain spec 7.11.3.2 keeps a compound block's two +/// per-reference predictions in until [`combine_compound`] blends them. +/// `dst` receives one `i32` per sample, row-major, same shape as +/// [`predict_with_filters`]'s `u8` `dst`. +/// +/// # Panics +/// Panics when `dst` is not `block_w * block_h` long, or the reference is +/// empty. +#[allow(clippy::too_many_arguments)] +pub fn predict_compound_intermediate( + reference: &[u8], + stride: usize, + true_width: usize, + true_height: usize, + x_q4: i32, + y_q4: i32, + block_w: usize, + block_h: usize, + h_kind: InterpFilterKind, + v_kind: InterpFilterKind, + dst: &mut [i32], +) { + assert_eq!(dst.len(), block_w * block_h, "the destination is the block"); + assert!(!reference.is_empty(), "a reference plane has samples"); + + let x0 = x_q4.div_euclid(16); + let xfrac = x_q4.rem_euclid(16) as usize; + let y0 = y_q4.div_euclid(16); + let yfrac = y_q4.rem_euclid(16) as usize; + + let (h_wide, h_narrow) = h_kind.tables(); + let (v_wide, v_narrow) = v_kind.tables(); + let h_filter = if block_w <= 4 { + &h_narrow[xfrac] + } else { + &h_wide[xfrac] + }; + let v_filter = if block_h <= 4 { + &v_narrow[yfrac] + } else { + &v_wide[yfrac] + }; + + let rows = block_h + 7; + let mut intermediate = vec![0i32; rows * block_w]; + for r in 0..rows { + let y = y0 - 3 + r as i32; + for c in 0..block_w { + let mut sum = 0; + for (t, &tap) in h_filter.iter().enumerate() { + let x = x0 + c as i32 + t as i32 - 3; + sum += tap * sample(reference, stride, true_width, true_height, x, y); + } + intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0); + } + } + + for row in 0..block_h { + for col in 0..block_w { + let mut sum = 0; + for (t, &tap) in v_filter.iter().enumerate() { + sum += tap * intermediate[(row + t) * block_w + col]; + } + dst[row * block_w + col] = round2(sum, INTER_ROUND_1_COMPOUND); + } + } +} + +/// Blends two [`predict_compound_intermediate`] outputs into a finished +/// 8-bit block (spec 7.11.3.15's weighted-average combine, the +/// `comp_group_idx == 0` path -- `fwd_weight`/`bck_weight` are either the +/// simple-average split `(8, 8)` or [`crate::compound::dist_wtd_comp_weight_assign`]'s +/// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound +/// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this +/// function does not cover -- decode.rs still refuses those by name. +pub fn combine_compound( + pred0: &[i32], + pred1: &[i32], + fwd_weight: i32, + bck_weight: i32, + dst: &mut [u8], +) { + assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block"); + assert_eq!(dst.len(), pred0.len(), "the destination is the block"); + for i in 0..dst.len() { + let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight; + dst[i] = round2(sum, INTER_POST_ROUND + DIST_PRECISION_BITS).clamp(0, 255) as u8; + } +} + +/// Whole-pel identity case: [`predict_compound_intermediate`]'s two-pass +/// filter reduces to `16 * source_sample` exactly (the fraction-0 row is a +/// single `128` tap both passes, and `128*128 == 1 << 14`, `14 - 7 == 7 == +/// INTER_ROUND_1_COMPOUND`, so the extra `2^4` of gain the compound path +/// keeps over [`predict`]'s 11-bit round survives untouched) -- +/// [`combine_compound`] then divides that back out exactly with an 8/8 +/// simple-average weight split, so a compound block whose two references +/// (and MVs) happen to coincide reproduces the plain source sample, not an +/// off-by-one from double rounding. +#[test] +fn compound_intermediate_whole_pel_identity_round_trips_through_combine() { + let reference = vec![100u8; 16 * 16]; + let mut pred0 = vec![0i32; 16]; + predict_compound_intermediate( + &reference, + 16, + 16, + 16, + 0, + 0, + 4, + 4, + InterpFilterKind::Regular, + InterpFilterKind::Regular, + &mut pred0, + ); + assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}"); + + let pred1 = pred0.clone(); + let mut dst = vec![0u8; 16]; + combine_compound(&pred0, &pred1, 8, 8, &mut dst); + assert!(dst.iter().all(|&v| v == 100), "{dst:?}"); +} + #[cfg(test)] mod tests { use super::{InterpFilterKind, predict, predict_with_filter};