diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index 4008a23d..cda67451 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -532,6 +532,16 @@ pub const PALETTE_UV_COLOR_INDEX: [[[u16; 9]; 5]; 7] = [ /// `default_intrabc_cdf` (entropymode.c): the `use_intrabc` flag on an /// intra frame with `allow_intrabc` set. pub const INTRABC: [u16; 3] = [30531, 32768, 0]; +/// `default_wiener_restore_cdf` (entropymode.c): a `RESTORE_WIENER`-plane +/// LR unit's own `use_wiener` flag (spec 5.11.57 `read_lr_unit`). +pub const RESTORE_WIENER: [u16; 3] = [11570, 32768, 0]; +/// `default_sgrproj_restore_cdf`: a `RESTORE_SGRPROJ`-plane LR unit's own +/// `use_sgrproj` flag. +pub const RESTORE_SGRPROJ: [u16; 3] = [16855, 32768, 0]; +/// `default_switchable_restore_cdf`: a `RESTORE_SWITCHABLE`-plane LR unit's +/// own `restoration_type` (3-way: `RESTORE_NONE`/`RESTORE_WIENER`/ +/// `RESTORE_SGRPROJ`). +pub const RESTORE_SWITCHABLE: [u16; 4] = [9413, 22581, 32768, 0]; /// `default_delta_q_cdf` (entropymode.c:840-852, lane-realworld r4): the /// 4-symbol `delta_q_abs` alphabet read once per superblock when diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 406da8b9..fe45bc89 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -439,6 +439,15 @@ pub(crate) struct Cdfs { pub palette_uv_color_index: [[[u16; 9]; 5]; 7], /// The `use_intrabc` flag -- see [`cdf::INTRABC`]. pub intrabc: [u16; 3], + /// A `RESTORE_WIENER`-plane LR unit's `use_wiener` flag -- see + /// [`cdf::RESTORE_WIENER`]. + pub restore_wiener: [u16; 3], + /// A `RESTORE_SGRPROJ`-plane LR unit's `use_sgrproj` flag -- see + /// [`cdf::RESTORE_SGRPROJ`]. + pub restore_sgrproj: [u16; 3], + /// A `RESTORE_SWITCHABLE`-plane LR unit's `restoration_type` -- see + /// [`cdf::RESTORE_SWITCHABLE`]. + pub restore_switchable: [u16; 4], /// `delta_q_abs` (lane-realworld r4, spec 5.11.10) -- see [`cdf::DELTA_Q`]. pub delta_q: [u16; 5], /// `delta_lf_abs`, the single-value form (spec 5.11.11) -- see @@ -672,6 +681,9 @@ impl Cdfs { reset3(&mut self.palette_y_color_index); reset3(&mut self.palette_uv_color_index); reset1(&mut self.intrabc); + reset1(&mut self.restore_wiener); + reset1(&mut self.restore_sgrproj); + reset1(&mut self.restore_switchable); reset1(&mut self.delta_q); reset1(&mut self.delta_lf); reset2(&mut self.delta_lf_multi); @@ -1137,6 +1149,9 @@ impl Cdfs { palette_y_color_index: cdf::PALETTE_Y_COLOR_INDEX, palette_uv_color_index: cdf::PALETTE_UV_COLOR_INDEX, intrabc: cdf::INTRABC, + restore_wiener: cdf::RESTORE_WIENER, + restore_sgrproj: cdf::RESTORE_SGRPROJ, + restore_switchable: cdf::RESTORE_SWITCHABLE, delta_q: cdf::DELTA_Q, delta_lf: cdf::DELTA_LF, delta_lf_multi: [cdf::DELTA_LF; 4], diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 6807ad80..1fba4154 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -21,7 +21,9 @@ //! too). Anything outside that refuses with [`Error::unsupported`] rather than //! silently miscoding. -use ec_av1_syntax::{CdefParams, DeltaParams, LoopFilterParams, TileInfo}; +use ec_av1_syntax::{ + CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, TileInfo, +}; use ec_core::{Error, Result}; use crate::cdf; @@ -3353,6 +3355,7 @@ fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly /// (own-edge and reach clamps both), passing what it gathers straight to /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone. +#[derive(Clone)] struct PlaneBuf { data: Vec, width: usize, @@ -5333,6 +5336,62 @@ fn apply_cdef( } } +/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's +/// ordering note: libaom also runs `superres_post_decode` between the two, +/// but this decoder never implements super-resolution, so there is nothing +/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF +/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop +/// restoration's stripe-boundary rows read from it instead of the +/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment. +#[allow(clippy::too_many_arguments)] +fn apply_loop_restoration( + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + deblocked_y: &PlaneBuf, + deblocked_u: &PlaneBuf, + deblocked_v: &PlaneBuf, + lr: &LoopRestorationParams, + grid: &crate::restoration::RestorationGrid, +) { + y.data = crate::restoration::apply_loop_restoration_plane( + &y.data, + &deblocked_y.data, + y.width, + y.true_width, + y.true_height, + 0, + lr.frame_restoration_type[0], + lr.loop_restoration_size[0], + grid, + 0, + ); + u.data = crate::restoration::apply_loop_restoration_plane( + &u.data, + &deblocked_u.data, + u.width, + u.true_width, + u.true_height, + 1, + lr.frame_restoration_type[1], + lr.loop_restoration_size[1], + grid, + 1, + ); + v.data = crate::restoration::apply_loop_restoration_plane( + &v.data, + &deblocked_v.data, + v.width, + v.true_width, + v.true_height, + 1, + lr.frame_restoration_type[2], + lr.loop_restoration_size[2], + grid, + 2, + ); +} + /// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes, /// returning the picture it reconstructs to. /// @@ -5384,6 +5443,7 @@ pub fn decode_key_frame_tile( false, cdef, loop_filter, + &LoopRestorationParams::default(), None, tx_select, reduced_tx_set, @@ -5431,6 +5491,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( enable_edge_filter: bool, cdef: &CdefParams, loop_filter: &LoopFilterParams, + lr: &LoopRestorationParams, initial_cdfs: Option, tx_select: bool, reduced_tx_set: bool, @@ -5506,6 +5567,11 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( mi_cols as usize, mi_rows as usize, ); + let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height); + let mut lr_reference = [( + crate::restoration::WienerInfo::default(), + crate::restoration::SgrprojInfo::default(), + ); 3]; // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its // own byte range and its own fresh copy of the frame's initial CDFs @@ -5570,6 +5636,16 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( for sb_r in sb_r0..sb_r1 { neighbours.start_row(); for sb_c in sb_c0..sb_c1 { + crate::restoration::read_lr( + &mut dec, + &mut cdfs, + lr, + &mut lr_grid, + &mut lr_reference, + sb_r * SB_MI, + sb_c * SB_MI, + SB_MI, + ); CDEF_TRANSMITTED.with(|c| c.set(false)); let at = (sb_r as usize * 4, sb_c as usize * 4); let ctx = neighbours.partition_ctx(at, SB); @@ -6020,7 +6096,9 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( frame_width as usize, frame_height as usize, ); + let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone()); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); + apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid); let (fw, fh) = (frame_width as usize, frame_height as usize); if fw == width && fh == height { @@ -10213,6 +10291,7 @@ pub fn decode_inter_frame_tile( other_refs, cdef, loop_filter, + &LoopRestorationParams::default(), None, allow_high_precision_mv, force_integer_mv, @@ -10256,6 +10335,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( other_refs: [Option<&Picture>; 8], cdef: &CdefParams, loop_filter: &LoopFilterParams, + lr: &LoopRestorationParams, initial_cdfs: Option, allow_high_precision_mv: bool, force_integer_mv: bool, @@ -10474,6 +10554,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( mi_rows as usize, ); let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); + let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height); + let mut lr_reference = [( + crate::restoration::WienerInfo::default(), + crate::restoration::SgrprojInfo::default(), + ); 3]; // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile // loop (spec 5.11.2 decode_tile / 7.20 exit_symbol) -- each tile gets @@ -10544,6 +10629,16 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( for sb_r in sb_r0..sb_r1 { neighbours.start_row(); for sb_c in sb_c0..sb_c1 { + crate::restoration::read_lr( + &mut dec, + &mut cdfs, + lr, + &mut lr_grid, + &mut lr_reference, + sb_r * SB_MI, + sb_c * SB_MI, + SB_MI, + ); CDEF_TRANSMITTED.with(|c| c.set(false)); let sb_at = (sb_r as usize * 4, sb_c as usize * 4); let sb_ctx = neighbours.partition_ctx(sb_at, SB); @@ -11763,7 +11858,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( frame_width as usize, frame_height as usize, ); + let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone()); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); + apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid); let motion_field = build_motion_field( &grid, diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index ca80f861..ca25eff4 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -31,6 +31,7 @@ pub mod mvstack; pub mod obu; pub mod quant; mod refusal_inventory; +mod restoration; pub mod sequence; mod superres; pub mod stream; diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 6077f485..0658da92 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -51,7 +51,6 @@ const REFUSALS: &[&str] = &[ "a block that actually uses intrabc (this decoder never reconstructs one)", "a frame OBU with no tile group", "a frame naming primary_ref_frame at a reference slot with no saved CDF state", - "a frame with loop restoration enabled (this decoder never reads the per-unit lr symbols)", "a frame with no mode-info grid", "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)", "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding", diff --git a/crates/ec-av1/src/restoration.rs b/crates/ec-av1/src/restoration.rs new file mode 100644 index 00000000..05301fda --- /dev/null +++ b/crates/ec-av1/src/restoration.rs @@ -0,0 +1,1063 @@ +//! AV1 loop restoration: spec 5.11.57 `read_lr`/`read_lr_unit` (per-superblock +//! symbol reads, once corners are computed per +//! `av1_loop_restoration_corners_in_sb`, restoration.c:1277) and spec 7.17's +//! two pixel filters (Wiener, self-guided/SGR). See `lanes/lr.report.md` for +//! the full derivation (libaom `decodeframe.c`/`restoration.c` line refs). + +use crate::msac::SymbolDecoder; +use ec_av1_syntax::obu::floor_log2; +use ec_av1_syntax::{LoopRestorationParams, RestorationType}; + +/// `ns(n)` (spec 4.10.7) read through the arithmetic coder's equiprobable +/// bit primitive (`aom_read_literal`/`SymbolDecoder::literal`), matching +/// libaom's `read_primitive_quniform_`. Same algorithm as +/// `ec_av1_syntax::obu::read_ns`, ported to the msac reader `decode_subexp` +/// needs (LR's coefficients ride the arithmetic-coded tile, not the +/// uncompressed header `BitReader` global motion's subexp already targets). +fn ns_msac(dec: &mut SymbolDecoder, n: u32) -> u32 { + if n <= 1 { + return 0; + } + let w = floor_log2(n) + 1; + let m = (1u32 << w) - n; + let v = dec.literal(w - 1); + if v < m { + return v; + } + (v << 1) - m + dec.literal(1) +} + +/// `decode_subexp()` (spec 5.9.28) with `k` a parameter, not the fixed `3` +/// global motion uses -- libaom's `read_primitive_subexpfin_`. LR's Wiener +/// taps and SGR `xqd` each pick a different `k` (1/2/3 for the three Wiener +/// taps, 4 for SGR). +fn decode_subexp_msac(dec: &mut SymbolDecoder, num_syms: u32, k: u32) -> u32 { + let mut i = 0u32; + let mut mk = 0u32; + loop { + let b = if i > 0 { k + i - 1 } else { k }; + let a = 1u32 << b; + if num_syms <= mk + 3 * a { + return ns_msac(dec, num_syms - mk) + mk; + } + if dec.literal(1) == 0 { + return dec.literal(b) + mk; + } + i += 1; + mk += a; + } +} + +/// `inv_recenter_nonneg` (`aom_dsp/recenter.h`) == spec `inverse_recenter`. +fn inverse_recenter(r: u32, v: u32) -> u32 { + if v > 2 * r { + v + } else if v & 1 != 0 { + r - ((v + 1) >> 1) + } else { + r + (v >> 1) + } +} + +/// `aom_read_primitive_refsubexpfin` (`inv_recenter_finite_nonneg` composed +/// with `read_primitive_subexpfin`): a value in `[0, n)` recentred around +/// `reference`. +fn decode_unsigned_subexp_with_ref_msac(dec: &mut SymbolDecoder, n: u32, k: u32, reference: u32) -> u32 { + let v = decode_subexp_msac(dec, n, k); + if (reference << 1) <= n { + inverse_recenter(reference, v) + } else { + n - 1 - inverse_recenter(n - 1 - reference, v) + } +} + +/// Signed wrapper, matching the way `read_wiener_filter`/`read_sgrproj_filter` +/// call `aom_read_primitive_refsubexpfin(rb, max-min+1, k, ref-min)+min`. +fn decode_signed_subexp_with_ref_msac(dec: &mut SymbolDecoder, low: i32, high: i32, k: u32, reference: i32) -> i32 { + let n = (high - low) as u32; + let r = (reference - low).clamp(0, n as i32) as u32; + decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low +} + +const WIENER_HALFWIN: usize = 3; +pub(crate) const WIENER_WIN: usize = 7; +const WIENER_TAP_MINV: [i32; 3] = [-5, -23, -17]; +const WIENER_TAP_MAXV: [i32; 3] = [10, 8, 46]; +const WIENER_TAP_K: [u32; 3] = [1, 2, 3]; +const WIENER_TAP_MIDV: [i32; 3] = [3, -7, 15]; + +/// `WienerInfo`: a restoration unit's 7-tap separable filter, symmetric +/// (spec `vfilter[i] == vfilter[6-i]`), with the centre tap derived +/// (`WIENER_FILT_STEP - 2*sum(taps 0..3)`, spec 7.17.4). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct WienerInfo { + pub vfilter: [i32; 7], + pub hfilter: [i32; 7], +} + +impl Default for WienerInfo { + fn default() -> Self { + Self { + vfilter: midpoint_filter(), + hfilter: midpoint_filter(), + } + } +} + +fn midpoint_filter() -> [i32; 7] { + let [t0, t1, t2] = WIENER_TAP_MIDV; + let centre = 128 - 2 * (t0 + t1 + t2); + [t0, t1, t2, centre, t2, t1, t0] +} + +/// One direction's 3 free taps (spec `read_wiener_filter`'s per-direction +/// loop): reads with `k`/min/max per tap index, recentred on `ref_dir` +/// (which the caller updates to the just-decoded value after each unit, +/// spec `ref_wiener_info` -- reset to the midpoint filter at each tile). +fn read_wiener_direction(dec: &mut SymbolDecoder, chroma: bool, reference: &[i32; 7]) -> [i32; 7] { + let mut taps = [0i32; 3]; + for i in 0..3 { + // `wiener_win == WIENER_WIN_CHROMA` (5-tap) skips tap 0, which is + // always 0 for chroma (spec `read_wiener_filter`, `wiener_win` + // branch on plane). + if i == 0 && chroma { + taps[0] = 0; + continue; + } + taps[i] = decode_signed_subexp_with_ref_msac( + dec, + WIENER_TAP_MINV[i], + WIENER_TAP_MAXV[i] + 1, + WIENER_TAP_K[i], + reference[i], + ); + } + let centre = 128 - 2 * (taps[0] + taps[1] + taps[2]); + [taps[0], taps[1], taps[2], centre, taps[2], taps[1], taps[0]] +} + +/// `read_wiener_filter` (decodeframe.c ~1595): both directions, updating +/// `reference` in place (the running per-plane, per-tile reference state). +fn read_wiener_filter(dec: &mut SymbolDecoder, chroma: bool, reference: &mut WienerInfo) -> WienerInfo { + let vfilter = read_wiener_direction(dec, chroma, &reference.vfilter); + let hfilter = read_wiener_direction(dec, chroma, &reference.hfilter); + let info = WienerInfo { vfilter, hfilter }; + *reference = info; + info +} + +/// `SgrprojInfo`: one self-guided restoration unit's parameter-set index +/// and the two (at most) coded correction weights. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct SgrprojInfo { + pub ep: usize, + pub xqd: [i32; 2], +} + +const SGRPROJ_PRJ_BITS: i32 = 7; +const SGRPROJ_PRJ_MIN0: i32 = -(1 << SGRPROJ_PRJ_BITS) * 3 / 4; +const SGRPROJ_PRJ_MAX0: i32 = SGRPROJ_PRJ_MIN0 + (1 << SGRPROJ_PRJ_BITS) - 1; +const SGRPROJ_PRJ_MIN1: i32 = -(1 << SGRPROJ_PRJ_BITS) / 4; +const SGRPROJ_PRJ_MAX1: i32 = SGRPROJ_PRJ_MIN1 + (1 << SGRPROJ_PRJ_BITS) - 1; +const SGRPROJ_PRJ_SUBEXP_K: u32 = 4; + +/// `av1_sgr_params` (`restoration.c:36`): `(r0, r1, s0, s1)` per of the 16 +/// `SGRPROJ_PARAMS_BITS`-selected parameter sets. `r == 0` for a radius +/// means that pass is skipped (its `xqd` is then forced, not coded). +pub(crate) const SGR_PARAMS: [(i32, i32, i32, i32); 16] = [ + (2, 1, 140, 3236), + (2, 1, 112, 2158), + (2, 1, 93, 1618), + (2, 1, 80, 1438), + (2, 1, 70, 1295), + (2, 1, 58, 1177), + (2, 1, 47, 1079), + (2, 1, 37, 996), + (2, 1, 30, 925), + (2, 1, 25, 863), + (0, 1, -1, 2589), + (0, 1, -1, 1618), + (0, 1, -1, 1177), + (0, 1, -1, 925), + (2, 0, 56, -1), + (2, 0, 22, -1), +]; + +/// `read_sgrproj_filter` (decodeframe.c ~1651). `reference` is the running +/// per-plane, per-tile `xqd` state (spec `ref_sgrproj_info`), updated in +/// place after every read (both coded and forced components). +fn read_sgrproj_filter(dec: &mut SymbolDecoder, reference: &mut SgrprojInfo) -> SgrprojInfo { + let ep = dec.literal(4) as usize; + let (r0, r1, _s0, _s1) = SGR_PARAMS[ep]; + let mut xqd = [0i32; 2]; + if r0 == 0 { + xqd[0] = 0; + xqd[1] = decode_unsigned_subexp_with_ref_msac( + dec, + (SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1) as u32, + SGRPROJ_PRJ_SUBEXP_K, + (reference.xqd[1] - SGRPROJ_PRJ_MIN1) as u32, + ) as i32 + + SGRPROJ_PRJ_MIN1; + } else if r1 == 0 { + xqd[0] = decode_unsigned_subexp_with_ref_msac( + dec, + (SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1) as u32, + SGRPROJ_PRJ_SUBEXP_K, + (reference.xqd[0] - SGRPROJ_PRJ_MIN0) as u32, + ) as i32 + + SGRPROJ_PRJ_MIN0; + xqd[1] = ((1 << SGRPROJ_PRJ_BITS) - xqd[0]).clamp(SGRPROJ_PRJ_MIN1, SGRPROJ_PRJ_MAX1); + } else { + xqd[0] = decode_unsigned_subexp_with_ref_msac( + dec, + (SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1) as u32, + SGRPROJ_PRJ_SUBEXP_K, + (reference.xqd[0] - SGRPROJ_PRJ_MIN0) as u32, + ) as i32 + + SGRPROJ_PRJ_MIN0; + xqd[1] = decode_unsigned_subexp_with_ref_msac( + dec, + (SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1) as u32, + SGRPROJ_PRJ_SUBEXP_K, + (reference.xqd[1] - SGRPROJ_PRJ_MIN1) as u32, + ) as i32 + + SGRPROJ_PRJ_MIN1; + } + let info = SgrprojInfo { ep, xqd }; + *reference = info; + info +} + +impl Default for SgrprojInfo { + fn default() -> Self { + Self { + ep: 0, + xqd: [ + (SGRPROJ_PRJ_MIN0 + SGRPROJ_PRJ_MAX0) / 2, + (SGRPROJ_PRJ_MIN1 + SGRPROJ_PRJ_MAX1) / 2, + ], + } + } +} + +/// One restoration unit's decoded filter (spec `RestorationUnitInfo`, +/// `RESTORE_NONE`/`WIENER`/`SGRPROJ` -- `Switchable`-frame units pick one of +/// these per unit; `Wiener`/`Sgrproj`-frame units are all this same variant +/// or `None`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum UnitFilter { + None, + Wiener(WienerInfo), + Sgrproj(SgrprojInfo), +} + +/// Per-plane restoration-unit grid for one tile/frame (spec `RestorationInfo` +/// per plane) -- `av1_lr_count_units`'s `horz_units`/`vert_units` sizing plus +/// the flattened `runit_idx = rcol + rrow*horz_units` storage `read_lr` +/// fills in superblock order. +pub(crate) struct RestorationGrid { + pub horz_units: [usize; 3], + pub vert_units: [usize; 3], + units: [Vec; 3], +} + +impl RestorationGrid { + pub(crate) fn new(lr: &LoopRestorationParams, frame_width: u32, frame_height: u32) -> Self { + let mut horz_units = [1usize; 3]; + let mut vert_units = [1usize; 3]; + let mut units: [Vec; 3] = [Vec::new(), Vec::new(), Vec::new()]; + for plane in 0..3 { + if lr.frame_restoration_type[plane] == RestorationType::None { + continue; + } + let (pw, ph) = if plane == 0 { + (frame_width, frame_height) + } else { + ((frame_width + 1) / 2, (frame_height + 1) / 2) + }; + let unit_size = lr.loop_restoration_size[plane]; + horz_units[plane] = count_units(pw, unit_size); + vert_units[plane] = count_units(ph, unit_size); + units[plane] = vec![UnitFilter::None; horz_units[plane] * vert_units[plane]]; + } + Self { + horz_units, + vert_units, + units, + } + } + + fn set(&mut self, plane: usize, rrow: usize, rcol: usize, filter: UnitFilter) { + let idx = rcol + rrow * self.horz_units[plane]; + self.units[plane][idx] = filter; + } + + pub(crate) fn get(&self, plane: usize, rrow: usize, rcol: usize) -> UnitFilter { + let idx = rcol + rrow * self.horz_units[plane]; + self.units[plane][idx] + } +} + +/// `av1_lr_count_units` (restoration.c:63): round, not ceil, to nearest. +fn count_units(plane_size: u32, unit_size: u32) -> usize { + (((plane_size + (unit_size >> 1)) / unit_size).max(1)) as usize +} + +fn ceil_div(a: u32, b: u32) -> u32 { + a.div_ceil(b) +} + +/// `read_lr` (spec 5.11.57) for one superblock at mode-info position +/// `(mi_row, mi_col)`: for every plane the frame uses LR on, computes the +/// unit-grid corners this superblock covers +/// (`av1_loop_restoration_corners_in_sb`, restoration.c:1277 -- every unit +/// is >= 64px, so only the top-of-superblock call ever has non-empty +/// corners, matching this decoder's own once-per-SB call site) and reads +/// one `read_lr_unit` per covered `(rrow, rcol)`, per plane, in plane +/// order. `sb_mi` is the superblock's mode-info width (`SB_MI`, 16 for the +/// 64px superblocks this decoder always uses). +#[allow(clippy::too_many_arguments)] +pub(crate) fn read_lr( + dec: &mut SymbolDecoder, + cdfs: &mut crate::cdf_state::Cdfs, + lr: &LoopRestorationParams, + grid: &mut RestorationGrid, + reference: &mut [(WienerInfo, SgrprojInfo); 3], + mi_row: u32, + mi_col: u32, + sb_mi: u32, +) { + if !lr.uses_lr { + return; + } + for plane in 0..3 { + let ftype = lr.frame_restoration_type[plane]; + if ftype == RestorationType::None { + continue; + } + let mi_size = if plane == 0 { 4u32 } else { 2u32 }; + let unit_size = lr.loop_restoration_size[plane]; + let horz_units = grid.horz_units[plane] as u32; + let vert_units = grid.vert_units[plane] as u32; + let rcol0 = ceil_div(mi_col * mi_size, unit_size); + let rcol1 = ceil_div((mi_col + sb_mi) * mi_size, unit_size).min(horz_units); + let rrow0 = ceil_div(mi_row * mi_size, unit_size); + let rrow1 = ceil_div((mi_row + sb_mi) * mi_size, unit_size).min(vert_units); + let chroma = plane != 0; + for rrow in rrow0..rrow1 { + for rcol in rcol0..rcol1 { + let filter = read_lr_unit(dec, cdfs, ftype, chroma, &mut reference[plane]); + grid.set(plane, rrow as usize, rcol as usize, filter); + } + } + } +} + +/// r3 gate self-pin: how many units decoded a real (non-`None`) filter, by +/// kind -- proves a real `--enable-restoration=1` aomenc stream actually +/// exercises `read_lr_unit`'s Wiener/SGR/switchable arms, not just that the +/// symbol-count/refusal-string wiring compiles. Never reset -- summed across +/// a gate's whole attempt loop, matching `MASKED_COMPOUND_HITS`/`WEDGE_HITS` +/// (decode.rs) which this mirrors. +thread_local! { + static WIENER_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static SGRPROJ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static SWITCHABLE_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`WIENER_HITS`]. +pub(crate) fn wiener_hits() -> usize { + WIENER_HITS.with(|c| c.get()) +} +/// Current value of [`SGRPROJ_HITS`]. +pub(crate) fn sgrproj_hits() -> usize { + SGRPROJ_HITS.with(|c| c.get()) +} +/// Current value of [`SWITCHABLE_HITS`] -- bumped once per unit whose frame +/// `restoration_type` is `Switchable`, regardless of which `RestoreType` +/// (`None`/Wiener/Sgrproj) that unit's own symbol resolved to. +pub(crate) fn switchable_hits() -> usize { + SWITCHABLE_HITS.with(|c| c.get()) +} + +fn read_lr_unit( + dec: &mut SymbolDecoder, + cdfs: &mut crate::cdf_state::Cdfs, + ftype: RestorationType, + chroma: bool, + reference: &mut (WienerInfo, SgrprojInfo), +) -> UnitFilter { + match ftype { + RestorationType::Switchable => { + SWITCHABLE_HITS.with(|c| c.set(c.get() + 1)); + let t = dec.symbol(&mut cdfs.restore_switchable); + match t { + 0 => UnitFilter::None, + 1 => { + WIENER_HITS.with(|c| c.set(c.get() + 1)); + UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0)) + } + _ => { + SGRPROJ_HITS.with(|c| c.set(c.get() + 1)); + UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1)) + } + } + } + RestorationType::Wiener => { + if dec.symbol(&mut cdfs.restore_wiener) != 0 { + WIENER_HITS.with(|c| c.set(c.get() + 1)); + UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0)) + } else { + UnitFilter::None + } + } + RestorationType::Sgrproj => { + let bit = dec.symbol(&mut cdfs.restore_sgrproj); + if bit != 0 { + SGRPROJ_HITS.with(|c| c.set(c.get() + 1)); + UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1)) + } else { + UnitFilter::None + } + } + RestorationType::None => UnitFilter::None, + } +} + +// --------------------------------------------------------------------- +// Spec 7.17: the two pixel filters (Wiener, self-guided) plus the +// restoration-unit/stripe walk that drives them. +// --------------------------------------------------------------------- + +/// `Round2` (spec 4.7): halves round up, arithmetic shift for negative sums +/// -- same primitive as `mc.rs`/`warp.rs`'s own `round2`, here at `i64` +/// since the self-guided filter's intermediate products don't fit `i32`. +fn round2(value: i64, shift: u32) -> i64 { + if shift == 0 { + value + } else { + (value + (1i64 << (shift - 1))) >> shift + } +} + +/// One plane's sample fetch for the pixel filters (spec 7.17.2's stripe +/// boundary substitution, libaom `setup_processing_stripe_boundary`/ +/// `get_stripe_boundary_info`): within the stripe `[stripe_v_start, +/// stripe_v_end)` currently being filtered, read the post-CDEF plane; +/// outside it (the 3-row border both filters' kernels reach into), read the +/// post-deblock, pre-CDEF plane instead -- UNLESS the stripe is the very +/// first/last stripe in the whole plane, where the frame's own top/bottom +/// edge replicates (`av1_extend_frame`) rather than crossing into deblocked +/// data. Columns always clamp to the plane's own true width -- restoration +/// unit COLUMN boundaries have no such substitution, only stripe (row) +/// boundaries do. +#[allow(clippy::too_many_arguments)] +fn lr_sample( + cdef: &[u8], + deblocked: &[u8], + stride: usize, + plane_w: usize, + plane_h: usize, + stripe_v_start: usize, + stripe_v_end: usize, + row: i64, + col: i64, +) -> i32 { + let col_c = col.clamp(0, plane_w as i64 - 1) as usize; + if row >= stripe_v_start as i64 && row < stripe_v_end as i64 { + i32::from(cdef[row as usize * stride + col_c]) + } else if row < stripe_v_start as i64 { + if stripe_v_start == 0 { + i32::from(cdef[col_c]) + } else { + // libaom saves 2 deblocked context lines and duplicates the + // outer one to fill a 3-row border (`RESTORATION_BORDER`): + // row `stripe_v_start-1` reads deblocked row `stripe_v_start-1`, + // rows `stripe_v_start-2`/`-3` both read deblocked row + // `stripe_v_start-2`. + let dist = stripe_v_start as i64 - 1 - row; + let src_row = if dist == 0 { + stripe_v_start - 1 + } else { + stripe_v_start.saturating_sub(2) + }; + i32::from(deblocked[src_row * stride + col_c]) + } + } else if stripe_v_end == plane_h { + i32::from(cdef[(plane_h - 1) * stride + col_c]) + } else { + // Mirror image of the above: rows `stripe_v_end`/`stripe_v_end+1` + // read their own deblocked row, row `stripe_v_end+2` duplicates + // `stripe_v_end+1`. + let dist = (row - stripe_v_end as i64).min(1) as usize; + let src_row = (stripe_v_end + dist).min(plane_h - 1); + i32::from(deblocked[src_row * stride + col_c]) + } +} + +/// Wiener pixel filter (spec 7.17.4, libaom `wiener_filter_stripe` -> +/// `av1_wiener_convolve_add_src_c`), one stripe-height chunk of one +/// restoration unit: a separable 7-tap horizontal pass (rounded by +/// `WIENER_ROUND0_BITS==3`, clipped to spec's intermediate range) feeding a +/// 7-tap vertical pass (rounded by `2*FILTER_BITS-3==11`) -- the same +/// `INTER_ROUND_0`/`INTER_ROUND_1` shifts `mc.rs`'s motion compensation +/// uses, since AV1 reuses that same separable-filter machinery here with a +/// custom 7-tap kernel instead of the fixed subpel tables. libaom's C +/// folds an extra `+/- (1 << ...)` bias into each pass to compensate for a +/// pointer-alignment trick that borrows the interpolation filter's 8-tap +/// convolution loop for a 7-tap kernel; that bias cancels algebraically +/// against `WienerInfo`'s own derived centre tap (`128 - 2*sum(taps)`), so +/// plugging the real taps straight into `sum(tap * sample)` (no bias term) +/// reproduces the same output byte-for-byte. +#[allow(clippy::too_many_arguments)] +fn apply_wiener_stripe( + out: &mut [u8], + cdef: &[u8], + deblocked: &[u8], + stride: usize, + plane_w: usize, + plane_h: usize, + h_start: usize, + h_end: usize, + v_start: usize, + v_end: usize, + info: &WienerInfo, +) { + let w = h_end - h_start; + let h = v_end - v_start; + if w == 0 || h == 0 { + return; + } + let rows = h + 6; + let mut inter = vec![0i32; rows * w]; + for r in 0..rows { + let row = v_start as i64 - 3 + r as i64; + for c in 0..w { + let col = h_start as i64 + c as i64; + let mut sum = 0i64; + for (t, &tap) in info.hfilter.iter().enumerate() { + let x = col - 3 + t as i64; + sum += tap as i64 + * lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, x) as i64; + } + // `WIENER_CLAMP_LIMIT(round0=3, bd=8) - 1`. + inter[r * w + c] = round2(sum, 3).clamp(0, 8191) as i32; + } + } + for r in 0..h { + for c in 0..w { + let mut sum = 0i64; + for (t, &tap) in info.vfilter.iter().enumerate() { + sum += tap as i64 * inter[(r + t) * w + c] as i64; + } + out[(v_start + r) * stride + h_start + c] = round2(sum, 11).clamp(0, 255) as u8; + } + } +} + +/// `av1_x_by_xplus1` (`restoration.c`): `round(256*z/(z+1))` for `z` in +/// `[0,255]`, saturating the `z==0` case to `1` instead of `0` (see the +/// libaom source comment this ports -- keeps `256-A[k]` inside a `u8` and +/// avoids a later overflow, without visibly affecting a near-flat block). +// r8: this table was transcribed with two errors -- index 101 (253 written +// as 254) and indices 165..=169 (254 written as 255) -- traced by comparing +// a call-unique dump (gated on the pinned stream's `xqd == [-16,-32]`, not a +// reused coordinate) against libaom's real `av1_x_by_xplus1` at the same +// `z=101`; both tables now generated straight from +// `~/.cache/aom-oracle/src/av1/common/restoration.c` to rule out any other +// transcription slip. +const SGR_X_BY_XPLUS1: [i32; 256] = [ + 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239, + 240, 241, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247, + 248, 248, 248, 248, 249, 249, 249, 249, 249, 250, 250, 250, 250, 250, 250, + 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252, + 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253, + 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, + 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, + 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 256, +]; + +/// `av1_one_by_x` (`restoration.c`): `round(4096/n)` for `n` in `1..=25` +/// (`MAX_NELEM`, `(2*MAX_RADIUS+1)^2`), indexed `[n-1]`. +const SGR_ONE_BY_X: [i32; 25] = [ + 4096, 2048, 1365, 1024, 819, 683, 585, 512, 455, 410, 372, 341, 315, 293, 273, 256, 241, 228, 216, 205, 195, 186, + 178, 171, 164, +]; + +const SGRPROJ_MTABLE_BITS: u32 = 20; +const SGRPROJ_RECIP_BITS: u32 = 12; +const SGRPROJ_SGR_BITS: u32 = 8; +const SGRPROJ_RST_BITS: u32 = 4; + +/// `calculate_intermediate_result` (`restoration.c`): the blend-factor pair +/// `(A[k], B[k])` at every position in `-1..=h` x `-1..=w` relative to a +/// restoration unit (a 1-pixel border around the unit, spec 7.17.3's +/// `BoxFilter`), for one of the two SGR radii. `r`/`s` are `SGR_PARAMS[ep]`'s +/// `(r0,s0)` or `(r1,s1)`; libaom computes this only at odd rows for the +/// `r==2` ("fast") radius as a running-sum speed optimisation -- the box +/// sum itself is identical at every row regardless, so computing it +/// everywhere (this function does, via a plain windowed sum through +/// [`lr_sample`] rather than libaom's O(1)-per-step sliding sum) and only +/// *reading* the odd rows back in [`apply_sgrproj_stripe`]'s fast branch +/// reproduces the same values without porting the sliding-window trick. +#[allow(clippy::too_many_arguments)] +fn compute_ab( + cdef: &[u8], + deblocked: &[u8], + stride: usize, + plane_w: usize, + plane_h: usize, + h_start: usize, + v_start: usize, + v_end: usize, + w: usize, + h: usize, + r: i32, + s: i32, +) -> Vec<(i32, i64)> { + let gw = w + 2; + let gh = h + 2; + let mut ab = vec![(0i32, 0i64); gw * gh]; + let n = ((2 * r + 1) * (2 * r + 1)) as i64; + for gi in 0..gh { + let i = gi as i64 - 1; + for gj in 0..gw { + let j = gj as i64 - 1; + let mut a = 0i64; + let mut b = 0i64; + for dr in -r..=r { + let row = v_start as i64 + i + dr as i64; + for dc in -r..=r { + let col = h_start as i64 + j + dc as i64; + let px = + lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col) as i64; + a += px * px; + b += px; + } + } + let p = if a * n < b * b { 0 } else { a * n - b * b }; + let z = round2(p * s as i64, SGRPROJ_MTABLE_BITS).clamp(0, 255) as usize; + let a_val = SGR_X_BY_XPLUS1[z]; + let b_val = round2( + (256 - a_val) as i64 * b * SGR_ONE_BY_X[(n - 1) as usize] as i64, + SGRPROJ_RECIP_BITS, + ); + if std::env::var("EC_LR_CALL_DUMP").is_ok() + && v_start as i64 + i == 60 + && h_start as i64 + j == 6 + && r == 1 + { + eprintln!( + "EC_LR_CALL_DUMP compute_ab u_tap: r={r} s={s} n={n} box_a={a} box_b={b} \ + p={p} z={z} a_val={a_val} b_val={b_val}" + ); + } + ab[gi * gw + gj] = (a_val, b_val); + } + } + ab +} + +/// Self-guided pixel filter (spec 7.17.3, libaom `sgrproj_filter_stripe` -> +/// `av1_apply_selfguided_restoration_c`), one stripe-height chunk of one +/// restoration unit: up to two box-filtered blends (`SGR_PARAMS[ep]`'s `r0` +/// "fast"/even-odd-row and `r1` dense radii, either may be `0` and skipped) +/// combined with the decoded `xqd` weights via `av1_decode_xq`. +#[allow(clippy::too_many_arguments)] +fn apply_sgrproj_stripe( + out: &mut [u8], + cdef: &[u8], + deblocked: &[u8], + stride: usize, + plane_w: usize, + plane_h: usize, + h_start: usize, + h_end: usize, + v_start: usize, + v_end: usize, + info: &SgrprojInfo, +) { + let w = h_end - h_start; + let h = v_end - v_start; + if w == 0 || h == 0 { + return; + } + let (r0, r1, s0, s1) = SGR_PARAMS[info.ep]; + let gw = w + 2; + let idx = |gi: i64, gj: i64| -> usize { (gi + 1) as usize * gw + (gj + 1) as usize }; + + let ab0 = (r0 > 0).then(|| compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r0, s0)); + let ab1 = (r1 > 0).then(|| compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r1, s1)); + + // r8: call-unique debug dump -- r6's coordinate-only gate (`v_start==60`) + // matched several unrelated calls across the gate's attempt sweep, so its + // captured bytes were never provably from the failing call. `info.xqd` + // is this restoration unit's own decoded weights, unique to the one call + // r7 traced (`[-16,-32]`); dump the real 9-byte dense-arm (r1) "u"-tap + // window (physical rows 59..=61, cols 5..=7 -- r7's traced tap) straight + // from `lr_sample` for this exact call, no coordinate matching involved. + if std::env::var("EC_LR_CALL_DUMP").is_ok() && r1 > 0 && info.xqd == [-16, -32] { + let bytes: Vec = (59..=61) + .flat_map(|row| { + (5..=7).map(move |col| { + lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col) + }) + }) + .collect(); + eprintln!( + "EC_LR_CALL_DUMP: xqd={:?} v_start={v_start} v_end={v_end} h_start={h_start} \ + u-tap 9-byte window (rows 59..=61, cols 5..=7) = {bytes:?}", + info.xqd + ); + } + + let mut xq = [0i32; 2]; + if r0 == 0 { + xq[0] = 0; + xq[1] = (1 << SGRPROJ_PRJ_BITS) - info.xqd[1]; + } else if r1 == 0 { + xq[0] = info.xqd[0]; + xq[1] = 0; + } else { + xq[0] = info.xqd[0]; + xq[1] = (1 << SGRPROJ_PRJ_BITS) - xq[0] - info.xqd[1]; + } + + for i in 0..h as i64 { + for j in 0..w as i64 { + let dgd = lr_sample( + cdef, + deblocked, + stride, + plane_w, + plane_h, + v_start, + v_end, + v_start as i64 + i, + h_start as i64 + j, + ) as i64; + let u = dgd << SGRPROJ_RST_BITS; + let mut v = u << SGRPROJ_PRJ_BITS; + if let Some(ab) = &ab0 { + // "Fast" radius (`r0==2`): A/B were only ever meaningfully + // computed at odd rows (see `compute_ab`'s doc comment) -- + // an even output row blends its two odd neighbour rows + // (weight 6/5, `nb=5`), an odd output row reuses its own + // row's A/B plus column neighbours (weight 6/5, `nb=4`). + let (a, b, nb) = if i & 1 == 0 { + let (a_um1, b_um1) = ab[idx(i - 1, j)]; + let (a_up1, b_up1) = ab[idx(i + 1, j)]; + let (a_uml, b_uml) = ab[idx(i - 1, j - 1)]; + let (a_umr, b_umr) = ab[idx(i - 1, j + 1)]; + let (a_upl, b_upl) = ab[idx(i + 1, j - 1)]; + let (a_upr, b_upr) = ab[idx(i + 1, j + 1)]; + let a = (a_um1 + a_up1) as i64 * 6 + (a_uml + a_umr + a_upl + a_upr) as i64 * 5; + let b = (b_um1 + b_up1) * 6 + (b_uml + b_umr + b_upl + b_upr) * 5; + (a, b, 5u32) + } else { + let (a_c, b_c) = ab[idx(i, j)]; + let (a_l, b_l) = ab[idx(i, j - 1)]; + let (a_r, b_r) = ab[idx(i, j + 1)]; + let a = a_c as i64 * 6 + (a_l + a_r) as i64 * 5; + let b = b_c * 6 + (b_l + b_r) * 5; + (a, b, 4u32) + }; + let flt0 = round2(a * dgd + b, SGRPROJ_SGR_BITS + nb - SGRPROJ_RST_BITS); + v += xq[0] as i64 * (flt0 - u); + } + if let Some(ab) = &ab1 { + // Dense radius (`r1==1`): every row was computed, so the + // combine is the full 3x3 neighbourhood (weight 4/3). + let (a_c, b_c) = ab[idx(i, j)]; + let (a_u, b_u) = ab[idx(i - 1, j)]; + let (a_d, b_d) = ab[idx(i + 1, j)]; + let (a_l, b_l) = ab[idx(i, j - 1)]; + let (a_r, b_r) = ab[idx(i, j + 1)]; + let (a_ul, b_ul) = ab[idx(i - 1, j - 1)]; + let (a_ur, b_ur) = ab[idx(i - 1, j + 1)]; + let (a_dl, b_dl) = ab[idx(i + 1, j - 1)]; + let (a_dr, b_dr) = ab[idx(i + 1, j + 1)]; + let a = (a_c + a_u + a_d + a_l + a_r) as i64 * 4 + (a_ul + a_ur + a_dl + a_dr) as i64 * 3; + let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3; + let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS); + v += xq[1] as i64 * (flt1 - u); + if std::env::var("EC_LR_CALL_DUMP").is_ok() + && info.xqd == [-16, -32] + && v_start as i64 + i == 61 + && h_start as i64 + j == 6 + { + eprintln!( + "EC_LR_CALL_DUMP combine: c={:?} u_tap(row60)={:?} d={:?} l={:?} r={:?} \ + ul={:?} ur={:?} dl={:?} dr={:?} dense a={a} b={b} dgd={dgd} \ + u={u} flt1={flt1} xq={xq:?} v_before_final_round={v}", + ab[idx(i, j)], ab[idx(i - 1, j)], ab[idx(i + 1, j)], ab[idx(i, j - 1)], + ab[idx(i, j + 1)], ab[idx(i - 1, j - 1)], ab[idx(i - 1, j + 1)], + ab[idx(i + 1, j - 1)], ab[idx(i + 1, j + 1)] + ); + } + } + let out_v = round2(v, SGRPROJ_PRJ_BITS as u32 + SGRPROJ_RST_BITS).clamp(0, 255) as u8; + out[(v_start as i64 + i) as usize * stride + (h_start as i64 + j) as usize] = out_v; + } + } +} + +/// Chunks one restoration unit's `[v_start, v_end)` extent into 64-row +/// (56 for the plane's very first stripe -- `RESTORATION_UNIT_OFFSET==8`) +/// processing stripes and filters each (libaom +/// `av1_loop_restoration_filter_unit`'s own `while (i < unit_h)` loop) -- +/// a restoration unit can be up to `256*1.5` px tall, spanning several +/// stripes, each of which needs its own boundary-source decision from +/// [`lr_sample`]. +#[allow(clippy::too_many_arguments)] +fn filter_restoration_unit( + out: &mut [u8], + cdef: &[u8], + deblocked: &[u8], + stride: usize, + plane_w: usize, + plane_h: usize, + h_start: usize, + h_end: usize, + v_start: usize, + v_end: usize, + ss_y: u32, + filter: UnitFilter, +) { + let full_stripe_height = 64usize >> ss_y; + let runit_offset = 8usize >> ss_y; + let unit_h = v_end - v_start; + let mut i = 0usize; + while i < unit_h { + let stripe_v_start = v_start + i; + let frame_stripe = (stripe_v_start + runit_offset) / full_stripe_height; + let nominal_h = full_stripe_height - if frame_stripe == 0 { runit_offset } else { 0 }; + let h = nominal_h.min(unit_h - i); + let stripe_v_end = stripe_v_start + h; + match filter { + UnitFilter::Wiener(info) => apply_wiener_stripe( + out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info, + ), + UnitFilter::Sgrproj(info) => apply_sgrproj_stripe( + out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info, + ), + UnitFilter::None => {} + } + i += h; + } +} + +/// Applies loop restoration to one whole plane's post-CDEF samples (spec +/// 7.17). Walks restoration units exactly as libaom's +/// `foreach_rest_unit_in_plane` (`unit_size` steps, the tail folded into +/// the previous unit when the remainder is under `1.5*unit_size` -- the +/// same round-to-nearest [`count_units`] already used to size +/// [`RestorationGrid`]), then re-offsets internal row boundaries by +/// `RESTORATION_UNIT_OFFSET==8` (the first/last row of the plane keeps its +/// full extent). Returns a fresh copy of `cdef` with only this plane's +/// restoration-unit pixels replaced -- a restoration unit must never read +/// another, already-filtered unit's output (spec keeps a separate +/// destination buffer for exactly this reason), so this never filters in +/// place. +#[allow(clippy::too_many_arguments)] +pub(crate) fn apply_loop_restoration_plane( + cdef: &[u8], + deblocked: &[u8], + stride: usize, + plane_w: usize, + plane_h: usize, + ss_y: u32, + ftype: RestorationType, + unit_size: u32, + grid: &RestorationGrid, + plane: usize, +) -> Vec { + let mut out = cdef.to_vec(); + if ftype == RestorationType::None || unit_size == 0 { + return out; + } + let voffset = 8u32 >> ss_y; + let ext_size = (unit_size * 3) / 2; + let mut y0 = 0u32; + let mut rrow = 0usize; + while y0 < plane_h as u32 { + let remaining_h = plane_h as u32 - y0; + let uh = if remaining_h < ext_size { remaining_h } else { unit_size }; + let v_start = (y0 as i64 - voffset as i64).max(0) as u32; + let mut v_end = y0 + uh; + if v_end < plane_h as u32 { + v_end -= voffset; + } + + let mut x0 = 0u32; + let mut rcol = 0usize; + while x0 < plane_w as u32 { + let remaining_w = plane_w as u32 - x0; + let uw = if remaining_w < ext_size { remaining_w } else { unit_size }; + let filter = grid.get(plane, rrow, rcol); + if filter != UnitFilter::None { + filter_restoration_unit( + &mut out, + cdef, + deblocked, + stride, + plane_w, + plane_h, + x0 as usize, + (x0 + uw) as usize, + v_start as usize, + v_end as usize, + ss_y, + filter, + ); + } + x0 += uw; + rcol += 1; + } + y0 += uh; + rrow += 1; + } + debug_assert_eq!(rrow, grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units"); + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::msac::{SymbolDecoder, SymbolEncoder}; + + /// `write_primitive_quniform`, the exact inverse of [`ns_msac`] -- used + /// only to build roundtrip fixtures for the decode-only helpers above + /// (this decoder never writes loop restoration itself). + fn write_ns(enc: &mut SymbolEncoder, n: u32, v: u32) { + if n <= 1 { + return; + } + let w = floor_log2(n) + 1; + let m = (1u32 << w) - n; + if v < m { + enc.literal(v, w - 1); + } else { + enc.literal((v + m) >> 1, w - 1); + enc.literal((v + m) & 1, 1); + } + } + + fn write_subexp(enc: &mut SymbolEncoder, num_syms: u32, k: u32, v: u32) { + let mut i = 0u32; + let mut mk = 0u32; + loop { + let b = if i > 0 { k + i - 1 } else { k }; + let a = 1u32 << b; + if num_syms <= mk + 3 * a { + write_ns(enc, num_syms - mk, v - mk); + return; + } + if v < mk + a { + enc.literal(0, 1); + enc.literal(v - mk, b); + return; + } + enc.literal(1, 1); + i += 1; + mk += a; + } + } + + fn recenter(r: u32, v: u32) -> u32 { + if v > 2 * r { + v + } else if v >= r { + (v - r) << 1 + } else { + ((r - v) << 1) - 1 + } + } + + fn write_unsigned_subexp_with_ref(enc: &mut SymbolEncoder, n: u32, k: u32, reference: u32, v: u32) { + let r = reference.clamp(0, n.saturating_sub(1)); + let coded = if (r << 1) <= n { + recenter(r, v) + } else { + recenter(n - 1 - r, n - 1 - v) + }; + write_subexp(enc, n, k, coded); + } + + /// `decode_subexp_msac`/`ns_msac` roundtrip every value in a handful of + /// `(num_syms, k)` alphabets -- the shapes LR's tap ranges (`k` 1..=4, + /// `num_syms` up to 96) actually hit, per `WIENER_TAP_MAXV`-`MINV`+1 / + /// `SGRPROJ_PRJ_MAX-MIN+1`. + #[test] + fn subexp_roundtrips_every_value() { + for &(num_syms, k) in &[(16u32, 1u32), (32, 2), (64, 3), (96, 4), (128, 4), (3, 1), (1, 3)] { + for v in 0..num_syms { + let mut enc = SymbolEncoder::new(); + write_subexp(&mut enc, num_syms, k, v); + let payload = enc.finish(); + let mut dec = SymbolDecoder::new(&payload); + let got = decode_subexp_msac(&mut dec, num_syms, k); + assert_eq!(got, v, "num_syms={num_syms} k={k} v={v}"); + } + } + } + + /// The recentred, ref-relative form `read_wiener_filter`/ + /// `read_sgrproj_filter` actually call -- every `(n, reference, v)` + /// combination for LR's own tap-0 range (16 values, matching + /// `WIENER_FILT_TAP0_MAXV-MINV+1`). + #[test] + fn unsigned_subexp_with_ref_roundtrips() { + let n = 16u32; + for k in 1..=4u32 { + for reference in 0..n { + for v in 0..n { + let mut enc = SymbolEncoder::new(); + write_unsigned_subexp_with_ref(&mut enc, n, k, reference, v); + let payload = enc.finish(); + let mut dec = SymbolDecoder::new(&payload); + let got = decode_unsigned_subexp_with_ref_msac(&mut dec, n, k, reference); + assert_eq!(got, v, "n={n} k={k} reference={reference} v={v}"); + } + } + } + } + + /// Signed wrapper sanity: a handful of `(low, high, k, reference, v)` + /// covering LR's actual Wiener tap-1/tap-2 and SGR `xqd0`/`xqd1` ranges. + #[test] + fn signed_subexp_with_ref_roundtrips() { + let cases: [(i32, i32, u32); 4] = [ + (-5, 11, 1), // Wiener tap0 + (-23, 9, 2), // Wiener tap1 + (-17, 47, 3), // Wiener tap2 + (-96, 32, 4), // SGR xqd0 + ]; + for (low, high, k) in cases { + let n = (high - low) as u32; + for reference_v in [low, low + n as i32 / 3, high - 1] { + for v in [low, low + n as i32 / 2, high - 1] { + let r = (reference_v - low).clamp(0, n as i32) as u32; + let coded_v = (v - low) as u32; + let mut enc = SymbolEncoder::new(); + write_unsigned_subexp_with_ref(&mut enc, n, k, r, coded_v); + let payload = enc.finish(); + let mut dec = SymbolDecoder::new(&payload); + let got = decode_signed_subexp_with_ref_msac(&mut dec, low, high, k, reference_v); + assert_eq!(got, v, "low={low} high={high} k={k} reference={reference_v} v={v}"); + } + } + } + } +} diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index d604ac6e..6511943c 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -222,16 +222,15 @@ pub fn decode_stream(data: &[u8]) -> Result> { } // Loop restoration carries per-restoration-unit symbols in the tile // (spec 5.11.57 `read_lr`, one group per LR unit reached from the - // superblock walk) that this decoder never reads -- same - // silent-desync shape as the refusals above. Traced live 2026-08-27: - // an aomenc inter frame with `Sgrproj` on the V plane desynced the - // partition walk into out-of-alphabet garbage. - if header.loop_restoration.uses_lr { - return Err(Error::unsupported( - "AV1 decode_stream", - "a frame with loop restoration enabled (this decoder never reads the per-unit lr symbols)", - )); - } + // superblock walk) -- lane-lr r2 ported the reader + // (`crate::restoration`), r3 moved this refusal check to AFTER the + // tile decode call below (was here, before it, in r2 -- meaning + // `read_lr` was NEVER actually reached through `decode_stream`, the + // gap the r3 gate caught live: 40/40 attempts hit this refusal with + // zero `read_lr_unit` hits). Checking post-decode instead proves the + // superblock walk actually survived `read_lr` (no desync) before + // refusing on the true remaining gap: decoded Wiener/SGR filters are + // stored per unit but never applied to pixels. // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV` // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the @@ -429,6 +428,7 @@ pub fn decode_stream(data: &[u8]) -> Result> { enable_edge_filter, &header.cdef, &header.loop_filter, + &header.loop_restoration, initial_cdfs, header.tx_mode == TxMode::Select, header.reduced_tx_set, @@ -516,6 +516,7 @@ pub fn decode_stream(data: &[u8]) -> Result> { other_refs, &header.cdef, &header.loop_filter, + &header.loop_restoration, initial_cdfs, header.allow_high_precision_mv, header.force_integer_mv, @@ -540,6 +541,9 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.delta, )? }; + // lane-lr r4: the Wiener/self-guided pixel filters are wired + // (`decode.rs::apply_loop_restoration`) -- no more refusal here, + // `uses_lr` frames now decode all the way to pixels. // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's // *initial* table into the slots it refreshes, not the adapted // end-of-tile one. @@ -5373,6 +5377,218 @@ mod tests { ); } + + /// lane-lr r3: proves stage 1/2's exit criterion -- a real + /// `--enable-restoration=1` aomenc stream must survive the whole + /// partition walk (every symbol read entropy-exact) and land on the + /// NEW, narrowed refusal ("read but not applied"), never desync into + /// some other named refusal or an outright decode panic. Multi-superblock + /// fixture (192x128 = 3x2 SBs of 64px) per the charter's own trap + /// warning -- a single-SB fixture can never re-enter `read_lr` a second + /// time and would leave `SWITCHABLE_HITS`/etc. proving only one call + /// site, not the per-SB loop. + #[test] + fn a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly() { + const NAME: &str = "a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height) = (192usize, 128usize); + let n_attempts: u32 = std::env::var("EC_LR_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(40); + let mut lr_refusals = 0u32; + let mut other_refusals = Vec::new(); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); + let y4m = Command::new("ffmpeg") + .args(["-v", "error", "-f", "lavfi", "-i"]) + .arg(&source) + .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + // r3: a low cq-level (high quality/bitrate) is load-bearing -- + // sampled live (2026-08-30) that aomenc's RD only ever picks a + // non-`RESTORE_NONE` frame_restoration_type at cq-level<=20 for + // this fixture; cq-level=45 (this gate's sibling gates' usual + // value) landed `uses_lr=false` on every attempt. + "--cq-level=15", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + // r3: this decoder always assumes 64px superblocks + // (`decode.rs` hardcodes `SB_MI=16`, ledger `lane-sb128` + // dead-ends) -- force aomenc to match rather than risk + // the unrelated sb128 gap eating this gate's own window. + "--sb-size=64", + "--enable-restoration=1", + "--enable-cdef=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-tx-size-search=0", + "--max-partition-size=32", + "--min-partition-size=16", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + "--enable-warped-motion=0", + "--enable-global-motion=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-obmc=0", + "--obu", + "-o", + "-", + "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + match decode_stream(&stream) { + Ok(pics) => { + // r4: the pixel filters are wired -- every `uses_lr` + // frame must now decode Ok AND match an independent + // decoder pixel-exact, not just refuse cleanly. + let reference = ffmpeg_decode_sequence(&stream, width, height, pics.len()); + let mismatched = pics + .iter() + .zip(&reference) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + // r7: pin a mismatching stream the same way the + // masked-compound gate does -- lets a follow-up round + // decode this exact seed's bytes directly instead of + // re-deriving them from a live 40-attempt sweep. + if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!( + "EC_AV1_GATE_DUMP: wrote mismatching LR stream (seed {seed}) to {path}" + ); + } + for (i, (pic, refpic)) in pics.iter().zip(reference.iter()).enumerate() { + assert_eq!(pic.y, refpic.y, "{NAME}: luma mismatch (seed {seed} frame {i})"); + assert_eq!(pic.u, refpic.u, "{NAME}: U mismatch (seed {seed} frame {i})"); + assert_eq!(pic.v, refpic.v, "{NAME}: V mismatch (seed {seed} frame {i})"); + } + lr_refusals += 1; // reused below as "attempts that actually exercised LR pixels" + } + Err(e) => { + let msg = e.to_string(); + other_refusals.push(format!("seed {seed}: {msg}")); + } + } + } + assert!( + other_refusals.is_empty(), + "{NAME}: {} attempts failed outright instead of decoding:\n{}", + other_refusals.len(), + other_refusals.join("\n") + ); + assert!( + lr_refusals > 0, + "{NAME}: no attempt ever decoded pixel-exact ({n_attempts} attempts)" + ); + // Any real (non-`RESTORE_NONE`) filter kind is acceptable proof -- + // aomenc's RD picks the frame-level `restoration_type` itself (not + // always `Switchable`; observed `Sgrproj` live at cq-level=15 for + // this fixture), so hard-requiring one specific arm would be the + // gate-recipe-confound class (ledger). + let total_hits = crate::restoration::wiener_hits() + + crate::restoration::sgrproj_hits() + + crate::restoration::switchable_hits(); + assert!( + total_hits > 0, + "{NAME}: {lr_refusals} LR refusals fired but read_lr_unit never decoded a real \ + (non-None) filter -- gate proved nothing about the symbol path" + ); + eprintln!( + "{NAME}: {lr_refusals} LR refusals, {} other refusals out of {n_attempts}, \ + wiener_hits={} sgrproj_hits={} switchable_hits={}", + other_refusals.len(), + crate::restoration::wiener_hits(), + crate::restoration::sgrproj_hits(), + crate::restoration::switchable_hits() + ); + } + + /// r8: decode the ONE pinned stream `EC_AV1_GATE_DUMP` captured in r7 + /// (`fixtures/lr-sgr-r7.obu`, seed 46) directly -- not the live + /// 40-attempt sweep, which reuses `v_start` coordinates across unrelated + /// seeds/frames and made r6's captured 9 bytes unprovable. Run with + /// `EC_LR_CALL_DUMP=1` set (see `restoration.rs`'s `apply_sgrproj_stripe`) + /// to get the real window on stderr, call-uniquely keyed to `xqd == + /// [-16,-32]` rather than any coordinate. + #[test] + #[ignore = "reads a pinned fixture under the gitignored fixtures dir; run manually with EC_LR_CALL_DUMP=1"] + fn pinned_lr_sgr_stream_call_unique_dump() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/lr-sgr-r7.obu"); + let stream = std::fs::read(path).expect("reading pinned lr-sgr-r7.obu"); + let pics = decode_stream(&stream).expect("pinned lr-sgr-r7.obu must decode"); + if have_ffmpeg() { + let reference = ffmpeg_decode_sequence(&stream, 192, 128, pics.len()); + for (i, (got, want)) in pics.iter().zip(&reference).enumerate() { + let y_mismatch = got.y != want.y; + let u_mismatch = got.u != want.u; + let v_mismatch = got.v != want.v; + eprintln!( + "frame {i}: y_mismatch={y_mismatch} u_mismatch={u_mismatch} v_mismatch={v_mismatch}" + ); + if y_mismatch { + let n = got.y.iter().zip(&want.y).filter(|(a, b)| a != b).count(); + eprintln!(" {n} luma bytes differ / {}", got.y.len()); + } + if v_mismatch { + let w = 96usize; // chroma plane width (192/2) + for (idx, (a, b)) in got.v.iter().zip(&want.v).enumerate() { + if a != b { + eprintln!(" V[{},{}] got={a} want={b}", idx / w, idx % w); + } + } + } + } + } + } + /// lane-realworld r2: `read_cdef` (spec 5.11.56) ported -- per-superblock /// `cdef_idx`, wired at all five `skip`-decode sites, `apply_cdef` looks /// up strength through the grid instead of a hardcoded `[0]`. Structure @@ -5569,7 +5785,6 @@ mod tests { crate::decode::cdef_idx_hits() ); } - /// Pinned streams captured by `EC_AV1_GATE_DUMP` off /// `a_real_aomenc_stream_with_warped_motion_refuses_or_matches` -- each /// one is a former mismatch, kept as a regression pin (warp-mismatch: @@ -6584,6 +6799,7 @@ mod tests { enable_edge_filter, &header.cdef, &header.loop_filter, + &header.loop_restoration, None, header.tx_mode == TxMode::Select, header.reduced_tx_set, @@ -6790,6 +7006,7 @@ mod tests { enable_edge_filter, &header.cdef, &header.loop_filter, + &header.loop_restoration, None, header.tx_mode == TxMode::Select, header.reduced_tx_set, @@ -7104,6 +7321,7 @@ mod tests { enable_edge_filter, &header.cdef, &header.loop_filter, + &header.loop_restoration, None, header.tx_mode == TxMode::Select, header.reduced_tx_set, diff --git a/lanes/lr-r2.charter.md b/lanes/lr-r2.charter.md new file mode 100644 index 00000000..7152ae1b --- /dev/null +++ b/lanes/lr-r2.charter.md @@ -0,0 +1,85 @@ +# lane-lr r2 — read_lr wiring, then the two filters + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-lr`, branch `lane-lr`, +at 4d7ae64. + +## Read these two files first, then start writing code +- `lanes/lr.report.md` — r1's complete design writeup. Its "Next lever" section + has every formula and `file:line` you need. Do NOT re-derive what it already + contains (class `worker-cap-spent-reading`). +- `lanes/lr.charter.md` — the original charter: staging, gate rules, hard rules. + Still binding. + +## What r1 landed (both committed, suite confirmed green 232/0 on this tree) +- `crates/ec-av1/src/cdf.rs`: `RESTORE_WIENER = [11570, 32768, 0]`, + `RESTORE_SGRPROJ = [16855, 32768, 0]`, + `RESTORE_SWITCHABLE = [9413, 22581, 32768, 0]` — copied from libaom + `entropymode.c` `default_{wiener,sgrproj,switchable}_restore_cdf` and + converted to this codebase's `[a0, (a1,) 32768, 0]` convention, checked + against `INTRABC`'s own `AOM_CDF2(30531) -> [30531, 32768, 0]`. +- `crates/ec-av1/src/cdf_state.rs`: the three tables wired into `Cdfs` — + fields, `new()` defaults, `reset_counts` via `reset1` — following `intrabc`. +- Nothing reads them from the bitstream yet; the whole-frame refusal at + `crates/ec-av1/src/stream.rs:195-198` is unchanged. + +## r1's decisive facts, so you do not re-find them +- `restoration.c:1277` `av1_loop_restoration_corners_in_sb` returns 0 unless + `bsize == sb_size`, so "read LR once per superblock" is spec-exact here, not + a simplification — every restoration unit is >= 64px. +- `msac.rs:348` `SymbolDecoder::literal(bits)` is the `L(n)` primitive LR's + subexp reads need. The existing `decode_subexp` / + `decode_unsigned_subexp_with_ref` / `decode_signed_subexp_with_ref` / + `inverse_recenter` at `ec-av1-syntax/src/frame.rs:1797-1848` are + `BitReader`-only (uncompressed frame header) — LR needs a SECOND, + msac-flavoured port, not reuse. +- Threading point: `decode_key_frame_tile_with_cdfs` (decode.rs:4478) and + `decode_inter_frame_tile_with_cdfs` (decode.rs:9088) already take long + positional argument lists including cdef and loop_filter. Add + `&LoopRestorationParams` there and pass `&LoopRestorationParams::default()` + from the public wrappers (`decode_key_frame_tile:4435`, + `decode_inter_frame_tile:9030`) — that keeps ~10 test call sites untouched. +- Wiener tap ranges `(-5, 10, k1)` `(-23, 8, k2)` `(-17, 46, k3)`; + SGR ranges `(-96, 31, k4)` `(-32, 95, k4)`. `av1_sgr_params` is in libaom + `restoration.c`. + +## Order of work — COMMIT AFTER EVERY GREEN MILESTONE +1. Port the msac-flavoured subexp/recenter helpers with their own unit tests + pinned against known values. COMMIT. +2. `read_lr` / `read_lr_unit` called once per superblock before + `decode_partition` at decode.rs ~4547 (key frame) and ~9275 (inter), with + the per-plane unit-grid formula from the report. The frame still refuses, + by a NEW and accurate name ("loop restoration symbols are read but the + filters are not applied"). The proof this stage works: a stream that used to + desync the partition walk into out-of-alphabet garbage now walks its + partitions cleanly and fails only the pixel compare. COMMIT. +3. Wiener filter, incl. the 3-pixel stripe boundary save/restore (libaom's + `rlbs`) — that boundary handling is the classic trap. COMMIT. +4. Self-guided, incl. the box-sum radii and `av1_sgr_params`. COMMIT. +5. Switchable; remove the last refusal; the gate asserts Ok, never an Err. + COMMIT. + +## Gate rules (mandatory, unchanged from r1's charter) +`EC_AV1_REQUIRE_AOMENC=1` on every test run; `-t ` on every ffmpeg +generate; fixtures through the existing `gradients_source(seed, w, h, tail)` +helper (ffmpeg's `gradients` ignores its own seed); aomenc +`--threads=1 --row-mt=0 --enable-restoration=1`; a HARD-asserted firing count +via a thread-local `Cell` counter matching the existing `*_HITS` +(thread-local, NOT atomics). A gate that cannot prove LR fired is vacuous. + +Note: main now carries a `gate_coverage` guard that derives, from the gate +source, which aomenc tools are switched off in all 20 gates and on in none. +`enable-restoration` is one gate short of that list today; your gate enabling it +is exactly the right outcome. + +## Hard rules +- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`. Foreground builds, + `nice -n 19 cargo ... -j4`. The suite takes ~4 minutes on this tree — give + any `cargo test` call a timeout of at least 600000 ms; do not let a 120 s + default kill it and then background it unpolled, as r1 did. +- Sibling worktrees (edith_codecs, -chroma, -realworld, -superres, -tiles) have + live agents. Never build in or edit them. +- Baseline to hold: 232 passed / 0 failed on this tree (main is at 234 with two + new guard tests you will inherit at merge). +- NEVER push, never merge, never touch `main`. Commit on `lane-lr` only. +- 75-turn cap: commit at every green step; near the cap, commit whatever + compiles as `wip(av1): ...` and update `lanes/lr.report.md`. diff --git a/lanes/lr-r3.charter.md b/lanes/lr-r3.charter.md new file mode 100644 index 00000000..c9f6eddc --- /dev/null +++ b/lanes/lr-r3.charter.md @@ -0,0 +1,63 @@ +# lane-lr r3 — gate the symbols, then apply the filters + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-lr`, branch `lane-lr`. +Read ONLY the r2 section of `lanes/lr.report.md` — it is a typing plan, not a +re-derivation task. Do not re-read libaom for what it already records +(class `worker-cap-spent-reading`). + +## State — the symbols are read +r2 landed and verified (suite 235 passed / 0 failed, 181 s — 232 baseline plus +three new pinned roundtrip tests): +- `crates/ec-av1/src/restoration.rs` (new): the msac-flavoured subexp/recenter + port (`decode_subexp_msac`, `decode_unsigned_subexp_with_ref_msac`, + `decode_signed_subexp_with_ref_msac`, `ns_msac`), `WienerInfo` / `SgrprojInfo` + / `UnitFilter`, the `SGR_PARAMS` table, `read_wiener_filter` / + `read_sgrproj_filter` / `read_lr_unit` / `read_lr`, and `RestorationGrid`. +- `decode.rs`: both tile functions take `lr: &LoopRestorationParams` and call + `read_lr` once per superblock before `decode_partition`; the public wrappers + pass `&LoopRestorationParams::default()`. +- `stream.rs`: both call sites thread `&header.loop_restoration`; the refusal + now names the true remaining gap ("symbols read, filters not applied"). + +## Order — COMMIT AFTER EVERY GREEN STEP +1. **The gate that proves stage 2 actually worked.** A real aomenc + `--enable-restoration=1` stream must survive the partition walk and fail + only on the new refusal — before this, "the symbols are read correctly" is + unproven. Hard-assert a firing count with a thread-local `Cell` in + `restoration.rs`'s `read_lr_unit`. Remember the shape of the trap r2's + sibling lane hit: a per-superblock symbol needs a fixture with more than one + superblock, or it can never fire. COMMIT. +2. **Wiener.** A new `apply_loop_restoration` pass after `apply_cdef` in + `decode.rs`, driven by `RestorationGrid`. The 3-pixel stripe boundary + save/restore (libaom's `rlbs`) is the classic trap — 64-row stripes, and the + filter reads rows the next stripe has already overwritten unless you save + them. COMMIT. +3. **Self-guided**, incl. the box-sum radii and `SGR_PARAMS`. COMMIT. +4. **Switchable**; drop the stream.rs refusal; the gate asserts Ok, never an Err. + COMMIT. + +Ordering fact a sibling lane established, which you need for step 2: libaom's +`decodeframe.c` calls `superres_post_decode()` BETWEEN `av1_cdef_frame` and +`av1_loop_restoration_filter_frame` — **superres runs before loop restoration**. +Not load-bearing while superres is refused here, but get the order right now. + +## Gate rules +`EC_AV1_REQUIRE_AOMENC=1` on every run (a missing oracle must FAIL, not SKIP); +`-t ` on every ffmpeg generate; fixtures through +`gradients_source(seed, w, h, tail)`; aomenc +`--threads=1 --row-mt=0 --enable-restoration=1`; firing counts are HARD asserts. + +## Note for the merge +Main carries two guards you do not have: `gate_coverage.rs` (pins the aomenc +tools no gate exercises — `enable-restoration` is one gate away from that list) +and `refusal_inventory.rs` (pins every decode-path refusal string, so adding or +renaming one fails until the list is updated — and r2 RENAMED the LR refusal). +Report the refusal strings you add, rename or remove, verbatim. + +## Hard rules +`export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground builds +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms (the suite +runs ~3 min). Sibling worktrees (edith_codecs, -chroma, -realworld, -superres, +-tiles, -palette) have live agents — never build in or edit them. Never push, +never merge, never touch `main`. 75-turn cap, does not reset: commit at every +green step. Update `lanes/lr.report.md` with an r3 section, VERDICT first. diff --git a/lanes/lr-r4.charter.md b/lanes/lr-r4.charter.md new file mode 100644 index 00000000..9cf5ad2a --- /dev/null +++ b/lanes/lr-r4.charter.md @@ -0,0 +1,46 @@ +# lane-lr r4 — the Wiener and self-guided filters + +At ebac7a0. Read `lanes/lr.report.md`'s r3 section only. + +## State — the symbols are read AND proven +r3's gate `a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly` +runs a real `--enable-restoration=1` stream: 39/40 attempts reach the LR +refusal with zero other refusals, `wiener_hits=19`, `sgrproj_hits=72`. +`RestorationGrid` and the per-plane `(WienerInfo, SgrprojInfo)` are populated +correctly. Suite 236/0. + +r3 also found and fixed a real bug r2's report had claimed away: the `uses_lr` +refusal ran BEFORE the tile decode, so `read_lr` was never invoked through +`decode_stream` at all — 40/40 attempts had zero `read_lr_unit` hits until the +check moved after the tile decode. + +Two gate facts r3 paid for: `--enable-restoration=1` only actually lands +`uses_lr = true` on this fixture at `cq-level <= 20` (the sibling gates' usual +45 never fires it), and `--sb-size=64` is required or aomenc's default 128px +superblock lands in a dead-ended partition gap and eats the attempt window. +And a dead end: do NOT hard-require `switchable_hits() > 0` — aomenc's RD may +pick a frame-level fixed Wiener or Sgrproj type instead. Assert the SUM. + +## Your job +1. **Wiener.** `apply_loop_restoration` after `apply_cdef` in `decode.rs` (two + call sites, ~4983 key-frame and ~10502 inter-frame), driven by + `RestorationGrid`. The 3-pixel stripe boundary save/restore (libaom's + `rlbs`) is the trap: 64-row stripes, and the filter reads rows the next + stripe has already overwritten unless you save them first. COMMIT. +2. **Self-guided**, incl. the box-sum radii and `SGR_PARAMS`. COMMIT. +3. Widen r3's gate to assert `Ok` and pixel-exactness instead of the named + refusal, then drop the `stream.rs` refusal. COMMIT. + +Ordering fact from a sibling lane: libaom runs `superres_post_decode()` between +`av1_cdef_frame` and `av1_loop_restoration_filter_frame` — superres before LR. + +Merge note: main is at 06d29ee with `gate_coverage.rs` (pins the aomenc tools no +gate exercises — `enable-restoration` is one gate from that list) and +`refusal_inventory.rs` (pins every decode-path refusal string). Report every +refusal string you add, rename or remove, verbatim. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling +worktrees have live agents — never build in or edit them. Never push, never +merge, never touch `main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN +STEP. Update `lanes/lr.report.md` with an r4 section, VERDICT first. diff --git a/lanes/lr-r5.charter.md b/lanes/lr-r5.charter.md new file mode 100644 index 00000000..05e05d40 --- /dev/null +++ b/lanes/lr-r5.charter.md @@ -0,0 +1,35 @@ +# lane-lr r5 — finish Wiener, then self-guided + +At 06ba9af — r4's Wiener work, committed verbatim by the orchestrator at its cap +and **never seen to compile**. `lanes/lr-r4.charter.md` is still binding; read it +and the r3 section of `lanes/lr.report.md`. + +1. `cargo check`, fix whatever r4 left mid-edit, then the full suite + (baseline 236/0 on this tree). Getting 06ba9af green is the whole job until + it is green. COMMIT. +2. Finish Wiener: `apply_loop_restoration` after `apply_cdef` in `decode.rs` + (two call sites, key-frame and inter-frame), driven by `RestorationGrid`. + The 3-pixel stripe boundary save/restore (libaom's `rlbs`) is the trap: + 64-row stripes, and the filter reads rows the next stripe has already + overwritten unless you save them first. COMMIT. +3. Self-guided, incl. the box-sum radii and `SGR_PARAMS`. COMMIT. +4. Widen the r3 gate to assert `Ok` and pixel-exactness instead of the named + refusal, then drop the `stream.rs` refusal. COMMIT. + +Facts already paid for: the symbols are read and gate-proven +(`wiener_hits=19`, `sgrproj_hits=72` on a real stream); `--enable-restoration=1` +only lands `uses_lr` at `cq-level <= 20`; `--sb-size=64` is required or aomenc's +default 128px superblock lands in a dead-ended partition gap; do NOT +hard-require `switchable_hits() > 0` — assert the SUM of the three arms, since +aomenc's RD may pick a frame-level fixed type. Ordering: libaom runs superres +between CDEF and loop restoration. + +Merge note: main is at 53b319b with `gate_coverage.rs` (pins the aomenc tools no +gate exercises) and `refusal_inventory.rs` (pins every decode-path refusal +string). Report every refusal string you add, rename or remove, verbatim. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling +worktrees have live agents — never build in or edit them. Never push, never +merge, never touch `main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN +STEP. Update `lanes/lr.report.md` with an r5 section, VERDICT first. diff --git a/lanes/lr-r6.charter.md b/lanes/lr-r6.charter.md new file mode 100644 index 00000000..36d63472 --- /dev/null +++ b/lanes/lr-r6.charter.md @@ -0,0 +1,63 @@ +# lane-lr r6 — one pixel + +At 0f36e31. Read the r5 section of `lanes/lr.report.md`. + +**Correction to the r5 charter, on the record:** it said HEAD had "never been +seen to compile". That was the orchestrator's inference from a cap-time commit, +and it was wrong — r4's work compiles clean and all four charter steps +(Wiener + self-guided at both call sites, the gate widened to assert `Ok` and +pixel-exactness, the `stream.rs` refusal dropped) are genuinely finished. r5 +spent its round diagnosing instead, which was the right call. + +## The defect +`a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly` fails +deterministically — reproduced identically on every rerun, not a flake: +**one pixel of 6144**, V plane, row 61 col 6, ours 195 vs ffmpeg 194. Seed 46, +filter `Sgrproj { ep: 6, xqd: [-16, -32] }`, inside chroma's last partial +restoration stripe [60, 64) of a 64px plane. Y and U are bit-exact on every +attempt; only this one (plane, pixel, filter) combination diverges. + +## Ruled out by r5, do not redo (class `worker-cap-spent-reading`) +- The stripe-boundary substitution (`lr_sample`), hand-verified line-by-line + against libaom's `setup_processing_stripe_boundary` / + `save_deblock_boundary_lines` for the failing stripe. Matches exactly. +- The dense (`r1 = 1`) SGR arm's A/B grid values and final combine, dumped live + and independently recomputed in Python from the real cdef/deblocked bytes. + Correct. +- Standalone C reimplementations of the box filter (`/tmp/lr_ref.c`, + `/tmp/lr_probe.c`) produced mutually inconsistent numbers across runs of + identical code. Do not trust them or their 194-vs-195 claim; they are not + evidence. If you want C ground truth, call libaom's own exported function + through a harness linked against `~/.cache/aom-oracle/build/libaom.a`, the way + `scripts/superres-pin-harness.c` does — that is the pattern that works here. + +## Start here +The fast (`r0 = 2`) arm's individual neighbour A/B reads at (row 61, col 6), +which r5 ran out of budget to instrument the same way it did the dense arm. +If that also checks out, go upstream to the V-plane CDEF/deblock pixel data +feeding the stripe. + +Sibling lanes built oracle rungs you can use: `EC_AV1_POSTDEBLOCK_DUMP` and +`EC_AV1_PREFILT_WIDE_DUMP` (in `scripts/instrument-aom-oracle.sh`, aomdec +already rebuilt on this box) give libaom's own post-deblock and wide pre-filter +buffers — exactly the upstream check above, without hand-tracing. Note also that +this is a partial stripe at a plane edge and a 1-LSB divergence: rounding in the +partial-stripe height or an edge-clamped neighbour is the shape to suspect. + +## Then +Once green: COMMIT immediately. Then remove any remaining LR refusal, confirm +`gate_coverage.rs`'s `NEVER_EXERCISED` no longer needs `enable-restoration` +(main's copy — you may not have the file), and write the r6 report. + +Merge note: main is at 53f5358 and has moved (multi-tile key frames, chroma +smooth/paeth, CDEF index reads, three reworded refusals, and +`refusal_inventory.rs` which pins every decode-path refusal string). Consider +`git merge main` here and resolving it yourself before the branch is merged +back — you know which side owns each hunk. Report every refusal string you add, +rename or remove, verbatim. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling +worktrees have live agents — never build in or edit them. Never push, never +merge into `main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP. +Update `lanes/lr.report.md` with an r6 section, VERDICT first. diff --git a/lanes/lr-r7.charter.md b/lanes/lr-r7.charter.md new file mode 100644 index 00000000..1b551ffe --- /dev/null +++ b/lanes/lr-r7.charter.md @@ -0,0 +1,55 @@ +# lane-lr r7 — one tap + +At e5ad671 (+ this charter). Read the r6 section of `lanes/lr.report.md`. + +## Where you stand — the search is down to one number +r6 linked libaom's real `av1_apply_selfguided_restoration_c` out of +`~/.cache/aom-oracle/build/libaom.a` and called it directly on OUR OWN +`lr_sample`-substituted bytes. It reproduced 194. That decisively rules out +`lr_sample` and the stripe boundary — r5's suspicion — and it rules out the +fast (`r0`) arm, whose `flt0` is bit-exact against real libaom. + +What is left: the dense (`r1`) arm. Eight of its nine A/B taps at the failing +pixel match a from-scratch box-sum of the real bytes; the combined `flt1` is +**3110 where libaom gets 3109**. One tap, or a rounding mode. + +r6's harness is now committed at `scripts/lr-sgr-pin-harness.c` — it lived in +the scratchpad, which this box reaps (class `oracle-in-reaped-dir`). Use and +extend it. + +## Do not +- Re-suspect `lr_sample` or the stripe boundary. Proven correct. +- Re-suspect the fast arm. Proven bit-exact. +- Hand-trace further. Three rounds have now shown our arithmetic is + self-consistent with our own output; only libaom's own intermediate values + can break the tie. + +## Do +r6 named the two ways to get per-tap ground truth, and preferred the first: +1. `calculate_intermediate_result` and `boxsum1` are `static` in libaom's + `restoration.c`, so they cannot be called from the harness as-is. Patch them + non-static in the oracle copy and rebuild (~5 min) — the same pattern + `scripts/instrument-aom-oracle.sh` already uses for the trace rungs, so add + it there as an env-gated rung rather than an ad-hoc edit, and it stays + reusable. +2. Or bisect single input pixels through the existing harness until the tap + that diverges identifies itself. + +Then fix it, get the gate green, COMMIT immediately. + +## Then +Wiener and self-guided are otherwise feature-complete with the refusal already +dropped, so once green this lane is ready to merge. Before it does: confirm +`gate_coverage.rs`'s `NEVER_EXERCISED` no longer needs `enable-restoration` +(main's copy — down to `enable-intrabc` alone as of this batch), and consider +`git merge main` here first and resolving it yourself; main is at 93d9510 and +has landed multi-tile decode, CDEF index reads, chroma modes, a `bit_depth != 8` +refusal and three reworded partition refusals since this branch forked. Report +every refusal string you add, rename or remove, verbatim. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling +worktrees have live agents — never build in or edit them. Never push, never +merge into `main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP, and +commit any harness or instrument you build — a scratchpad is not storage. +Update `lanes/lr.report.md` with an r7 section, VERDICT first. diff --git a/lanes/lr-r8.charter.md b/lanes/lr-r8.charter.md new file mode 100644 index 00000000..05e906d3 --- /dev/null +++ b/lanes/lr-r8.charter.md @@ -0,0 +1,48 @@ +# lane-lr r8 — one call, not forty + +At 1c122a2. Read the r7 section of `lanes/lr.report.md` first. + +r7's real result is a RETRACTION, and it is the most useful thing in the lane: +r6's recorded divergence — dense-arm "u" tap (A,B) = (254,303) vs our 3110 — +**could not be reproduced**. Compiled libaom's own `calculate_intermediate_result` +(now exported by rung 6 of `scripts/instrument-aom-oracle.sh`) gives (253,454) at +that pixel; our `compute_ab`/`lr_sample` live-trace reads the correct raw bytes +(111/154/194); and an independent Python replica of the box-sum formula fed those +bytes reproduces libaom's (253,454) exactly. So `lr_sample`, the box-sum formula +and the fast arm are all reconfirmed correct — **do not re-suspect any of them.** + +The reason r6's number was wrong is the round's real finding: its dump matched on +a COORDINATE (`v_start == 60`) that is not unique across the gate's 5-attempt +sweep, so the nine bytes it captured are not provably from the failing call. +A measurement that cannot name which call produced it is not evidence. + +## The job +1. Decode the ONE pinned stream, not the sweep: `fixtures/lr-sgr-r7.obu` is + seed-46's mismatching stream (gitignored, worktree-local; regenerate with + `EC_AV1_GATE_DUMP=fixtures/lr-sgr-r7.obu EC_LR_GATE_ATTEMPTS=10` if lost). + `EC_AV1_GATE_DUMP` is already wired into the gate (`stream.rs` ~4791). +2. Re-add a debug dump keyed CALL-UNIQUELY to that single call — r7 suggests + gating on `xqd == [-16,-32]` — and get the real nine-byte window it reads. + Compare against `100,111,117,140,154,163,182,194,201`. +3. With a call-unique measurement in hand, either the bytes differ (a sampling / + stripe-boundary defect, and you have the coordinates) or they match and the + 3110-vs-3109 gap lives downstream of `compute_ab`. Follow whichever the + measurement says; do not carry r6's hypothesis forward. + +Then merge `main` into this branch and resolve it yourself — main has moved a +long way (multi-tile, delta_q/delta_lf, a `bit_depth != 8` refusal) — so the lane +arrives mergeable. And check `refusal_inventory.rs` still matches this branch's +refusal set. + +Oracle hygiene: `~/.cache/aom-oracle` is SHARED with five sibling lanes. Rung 6 +is permanent and env-safe; any further change goes in as a rung in +`scripts/instrument-aom-oracle.sh` (silent when unset, idempotent), never as a +throwaway patch left in the shared tree. Rebuild with +`ninja -C ~/.cache/aom-oracle/build libaom.a`. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms; +`EC_AV1_REQUIRE_AOMENC=1`. Sibling worktrees have live agents — never build in or +edit them. Never push, never merge this branch into main. 75-turn cap, does not +reset: COMMIT AT EVERY GREEN STEP. End with `lanes/lr-r8.report.md`, VERDICT on +line 1. diff --git a/lanes/lr-r9.charter.md b/lanes/lr-r9.charter.md new file mode 100644 index 00000000..9a795a62 --- /dev/null +++ b/lanes/lr-r9.charter.md @@ -0,0 +1,42 @@ +# lane-lr r9 — finish what r8 started + +At 7ad6d77. Read `lanes/lr-r8.charter.md` (still your charter — r8 never got to +report) and the r7 section of `lanes/lr.report.md`. + +r8 stopped at its turn cap having done two things: +1. **Found and fixed a real defect** — `SGR_X_BY_XPLUS1` was mistranscribed at + `av1_x_by_xplus1[101]` and `[165..=169]`, committed at 7ad6d77. Whether that + closes the 3110-vs-3109 gap is UNKNOWN to me: the round never reported a + gate result. **Run the LR gate first and find out** before assuming either + way — and say plainly in your report which it was. +2. Started a merge of an already-stale `main`. I aborted it; nothing of yours + was lost. Redo it against current `main` (a8724cb, far ahead: tile rows, + delta_q/delta_lf, key-frame superres, palette-Y, a `bit_depth != 8` refusal, + and two guard tests that will fail until this branch's refusal list matches). + +If the gate is still red, the r8 charter's method stands and has not been tried: +decode the ONE pinned stream `fixtures/lr-sgr-r7.obu` (seed 46, `EC_AV1_GATE_DUMP` +already wired at `stream.rs` ~4791) instead of the 40-attempt sweep, with a dump +keyed CALL-UNIQUELY to the failing call — r6's coordinate-keyed dump +(`v_start == 60`) captured some other invocation and cost a whole round +([[dump-not-call-unique]]). `lr_sample`, the box-sum formula and the fast arm are +independently reconfirmed correct; do not re-suspect them. + +Note that r8's find is itself the lesson: a mistranscribed constant in a 256-entry +table is invisible to every by-hand review and shows up as a one-off arithmetic +gap. If the gate is still red, diff the OTHER SGR tables against libaom +wholesale — `av1_one_by_x`, the `sgr_params` rows — before tracing anything. + +Merge `main` into this branch, resolve it yourself, and land the round green so +the SGR fix can reach main either way: a correct table fix is worth merging even +if the last pixel is still out, provided the gate's status is stated honestly. + +Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground +`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms; +`EC_AV1_REQUIRE_AOMENC=1`. The oracle at `~/.cache/aom-oracle` is SHARED with +five sibling lanes — instrument only via env-gated rungs in +`scripts/instrument-aom-oracle.sh`, never a throwaway patch left in the tree, and +note that rung numbers 6, 7, 8 and 8b are already taken on main; take 9. Sibling +worktrees have live agents — never build in or edit them. Never push, never merge +this branch into main. 75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP. +End with `lanes/lr-r9.report.md`, VERDICT on line 1. diff --git a/lanes/lr.charter.md b/lanes/lr.charter.md new file mode 100644 index 00000000..668178e3 --- /dev/null +++ b/lanes/lr.charter.md @@ -0,0 +1,100 @@ +# lane-lr — loop restoration decode (read_lr + Wiener + self-guided) + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-lr`, branch `lane-lr`, off main 87a1e34. + +## Goal +Remove the whole-frame refusal at `crates/ec-av1/src/stream.rs:195` +("a frame with loop restoration enabled") by actually decoding it: +1. the per-restoration-unit symbols read from the tile data during the + superblock walk (spec 5.11.57 `read_lr` / `read_lr_unit`), and +2. the two restoration filters themselves (spec 7.17: Wiener 7.17.4, + self-guided 7.17.2/7.17.3), applied to the CDEF-filtered frame. + +## Anchors +- Spec: 5.11.57 `read_lr`, 5.11.58 `read_lr_unit`, 6.10.15, 7.17 `loop restoration process`. +- libaom (oracle source, `~/.cache/aom-oracle` build tree — find the src dir under it): + `av1/decoder/decodeframe.c` `read_lr()` / `read_lr_unit()`; + `av1/common/restoration.c` `av1_loop_restoration_filter_frame`, + `wiener_filter_stripe`, `selfguided_restoration`, `av1_selfguided_restoration_c`, + and the `sgr_params` table. +- Existing syntax: `crates/ec-av1-syntax/src/frame.rs:341` `LoopRestorationParams` + (`frame_restoration_type`, `loop_restoration_size`, `uses_lr`). +- The superblock walk in the decoder is `crates/ec-av1/src/decode.rs` around + lines 4547 and 9275 (`for sb_r in 0..sb_rows { for sb_c ... }`). `read_lr` is + called once per superblock, BEFORE `decode_partition`, and loops over the LR + units whose top-left falls in this superblock, per plane. +- CDF tables live in `crates/ec-av1/src/cdf.rs`. There is currently NO + restoration CDF (`grep -i restoration crates/ec-av1/src/cdf.rs` is empty) — + you must add `restore_wiener`, `restore_sgrproj`, `restore_switchable` + (the switchable one is a 3-symbol CDF) with libaom's `default_*_cdf` values + copied EXACTLY from `av1/common/token_cdfs.h` / `entropymode.c`. Note that + the Wiener/SGR *coefficients* are NOT CDF-coded: they use + `decode_signed_subexp_with_ref` (literal + subexp bits), spec 5.9.27-ish. +- CDF WIRING IS FOUR SITES in this codebase but in practice only the defaults + array needs hand-checking (reset2/reset3 are length-generic, save/restore is + a whole-struct Clone). Still verify the counter reset covers new tables. + +## Method (this is a range-ladder lane) +CLASS `compare-range-not-tell`: never compare `tell()` across decoders — +compare the msac RANGE after each element. The instrumented oracle at +`~/.cache/aom-oracle` has env-gated rungs: `EC_TRACE=1` (EC_PART), +`EC_TRACE_COEFF=1` (EC_COEFF), `EC_TRACE_MODE=1` (EC_MODE/EC_IMODE). +If you need an LR rung, ADD one to `scripts/instrument-aom-oracle.sh` +following the exact shape of the existing rungs (env-gated, silent when unset, +idempotent, wrapper-around-impl) and rebuild the oracle with +`scripts/build-aom-oracle.sh`. That is an expected part of this lane. +CLASS `equal-range-means-unread`: if the reference's range is UNCHANGED where +ours moves, we read a symbol it never wrote; if theirs moves and ours doesn't, +we skipped one. Only when both move by different amounts is a table implicated. + +## Staging — commit after EVERY green milestone +1. **Syntax only.** Read the lr symbols correctly and then still refuse the + frame by name ("loop restoration symbols are read but the filters are not + applied"). Prove correctness by the partition walk surviving: a stream that + previously desynced into out-of-alphabet garbage now decodes its partitions + and only fails the pixel compare. COMMIT. +2. **Wiener.** Implement `wiener_filter_stripe` (64-row stripes with the + 3-pixel stripe boundary handling — that boundary handling is the classic + trap; libaom saves/restores `rlbs` boundary lines). Gate a stream forced to + Wiener only. COMMIT. +3. **Self-guided.** `selfguided_restoration` incl. the box-sum radii and the + `sgr_params` table. COMMIT. +4. **Switchable.** Remove the last refusal. COMMIT. + +## Gate (mandatory, in `crates/ec-av1/src/stream.rs` next to the existing gates) +- Follow the existing gate shape exactly. `EC_AV1_REQUIRE_AOMENC=1` must be set + when you run tests, so a missing oracle FAILS rather than SKIPs. +- Bound every ffmpeg `generate` with `-t ` (an unbounded source + deadlocked a gate for an hour; class `gate-loader-slurps-whole-file`). +- Build the fixture through the existing `gradients_source(seed, w, h, tail)` + helper — do NOT hand-write a `gradients=size=` string; ffmpeg's gradients + source ignores its seed and the helper derives colours from the seed instead. +- aomenc flags: `--threads=1 --row-mt=0`, and whatever turns LR on + (it is on by default; `--enable-restoration=1`). To force a single filter + type, encode content that provokes it, or use the aomenc knob if one exists — + if not, assert per-type firing counts instead. +- The gate MUST hard-assert a firing count (e.g. `wiener_hits > 0`), a + thread-local `Cell` counter in decode.rs like the existing `*_HITS` + (they are thread-local now, NOT atomics — process-global atomics made one + gate count another test's work). CLASS `gate-blind-to-feature`: a gate that + cannot prove its feature fired is vacuous. +- Refusals inside the gate are FORBIDDEN once the stage that removes them + lands: assert the decode returns Ok, do not tolerate an Err. + +## Hard rules +- Own build dir: `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`. + Foreground builds only, `nice -n 19 cargo ... -j4`. Never `cargo` in another + worktree, never touch a sibling worktree's files. +- Suite scope: `nice -n 19 cargo test -p ec-av1 --lib` (67 s baseline on main, + 232 passed / 0 failed). It must stay green. +- NEVER push, never merge, never touch `main`. Commit on `lane-lr` only. +- You have a 75-turn cap. **Commit work-in-progress after every green + milestone** — five builders have lost complete implementations at the cap. + If you are near the cap, commit whatever compiles as `wip(av1): ...` and + write `lanes/lr.report.md` before you stop. +- Refuse-by-name rather than desync: any case you do not implement must return + `Error::unsupported` with an accurate string. CLASS + `refusal-claim-disproved-by-its-own-gate`: never write a refusal string that + claims the encoder never emits the case unless you have proved it. +- Write `lanes/lr.report.md` at the end: what landed, gate name + firing count, + what still refuses and by what exact string, and the next lever. diff --git a/lanes/lr.report.md b/lanes/lr.report.md new file mode 100644 index 00000000..54e866f6 --- /dev/null +++ b/lanes/lr.report.md @@ -0,0 +1,529 @@ +# lane-lr report + +## What landed (committed on `lane-lr`, 14a0273) +- Added the three loop-restoration CDF tables this decoder was missing + (`crates/ec-av1/src/cdf.rs`): `RESTORE_WIENER`, `RESTORE_SGRPROJ`, + `RESTORE_SWITCHABLE`, copied exactly from libaom + `av1/common/entropymode.c`'s `default_{wiener,sgrproj,switchable}_restore_cdf` + (`AOM_CDF2(11570)`, `AOM_CDF2(16855)`, `AOM_CDF3(9413, 22581)` — converted + to this codebase's `[a0, (a1,) 32768, 0]` convention, matching the existing + `INTRABC` table's own conversion of `AOM_CDF2(30531)`). +- Wired all three into `Cdfs` (`crates/ec-av1/src/cdf_state.rs`): struct + fields, `Cdfs::new`'s defaults, and `reset_counts` (all three are + unindexed `[u16; N]`, same shape as `intrabc`, so `reset1` — the + 4-site wiring checklist's counter-reset site is the only hand-checked + one; save/restore and the other two sites are generic over any shape). +- `cargo check -p ec-av1` clean. + +## What still refuses, and by what string +The whole-frame refusal is UNCHANGED: `crates/ec-av1/src/stream.rs:195-198` +still returns `Error::unsupported("AV1 decode_stream", "a frame with loop +restoration enabled (this decoder never reads the per-unit lr symbols)")` +for any `header.loop_restoration.uses_lr` frame. The CDF tables added this +round are not read from the bitstream anywhere yet — this is groundwork +for stage 1 (charter's "syntax only" milestone), not stage 1 itself. + +## Design worked out but not yet coded (for the next round) +Traced the full spec/libaom shape so the next round can go straight to +code instead of re-reading source: + +- `av1_loop_restoration_corners_in_sb` (`restoration.c:1277`) only returns + non-zero corners when `bsize == sb_size` — i.e. despite `decode_partition` + calling it recursively at every partition level in libaom, only the + top-of-superblock call ever does anything, because every restoration + unit is >= 64px (SB size). The charter's "once per superblock" plan is + therefore exactly spec-equivalent, not a simplification with a gap. +- Per-plane unit grid: `horz_units = max(1, round(plane_w / unit_size))`, + `vert_units` likewise (`av1_lr_count_units`, `restoration.c:63`, note + ROUND not ceil). `plane_w`/`plane_h` are `frame_width`/`frame_height` for + luma; this decoder is 4:2:0-only in the tile-decode functions already + (`u`/`v` are hardcoded half-size), so chroma is + `(frame_width+1)/2, (frame_height+1)/2` (`ROUND_POWER_OF_TWO`). + `unit_size` = `header.loop_restoration.loop_restoration_size[plane]` + directly (already computed per-plane in + `ec-av1-syntax/src/frame.rs:1626-1637`). +- Per-SB corner math (`restoration.c:1277-1335`, no superres in this + decoder so the superres-scaled branches are dead code here): + `rcol0 = ceil_div(mi_col0 * mi_size_x, unit_size)`, + `rcol1 = min(ceil_div((mi_col0+sb_mi_w) * mi_size_x, unit_size), horz_units)`, + same for rows; `mi_size_x = 4` luma, `2` chroma (4:2:0). Then + `runit_idx = rcol + rrow * horz_units`, and `read_lr_unit` is called once + per `(rrow, rcol)` in that rectangle, per plane, in plane order. +- `read_lr_unit` symbol shape (`decodeframe.c:1687-1723`): if + `frame_restoration_type[plane] == Switchable`, read one + `restore_switchable` (3-way) symbol and dispatch; if `== Wiener`, read one + `restore_wiener` binary symbol, Wiener filter only if 1; if `== + Sgrproj`, same with `restore_sgrproj` and the SGR filter. `None` never + calls this at all (loop skipped by `frame_restoration_type[plane] == + RESTORE_NONE` — i.e. it's legal for the switchable-frame case per plane + even when only some planes use LR, since `frame_restoration_type` is + per-plane). +- Wiener coefficients: 3 taps per direction (vfilter/hfilter), each via + `aom_read_primitive_refsubexpfin(n, k, ref)` — SAME algorithm this crate + already has for global-motion params + (`ec-av1-syntax/src/frame.rs:1797-1839`, + `decode_signed/unsigned_subexp_with_ref`/`decode_subexp`/`inverse_recenter`) + but that existing implementation runs on a raw `BitReader` (frame header, + uncompressed bits); the LR coefficients are read through the arithmetic + decoder (`aom_reader`, i.e. this crate's `SymbolDecoder`), using + `aom_read_literal`/`aom_read_bit` as the raw-bit primitives — + `SymbolDecoder::literal(bits)` (`msac.rs:348`, already exists, built on + `symbol_fixed(&EQUIPROBABLE)`) is the exact equivalent. The subexp/recenter + math needs a second, msac-flavoured port of those four functions (same + arithmetic, `dec.literal(1)`/`dec.literal(n)` in place of `r.read_bit()`/ + `r.read_bits(n)`) — not reusable as-is because the reader types differ. + Per-tap `(min, max, k)`, all computed from libaom `restoration.h`: + tap0 `(-5, 10, k=1)`, tap1 `(-23, 8, k=2)`, tap2 `(-17, 46, k=3)` + (`WIENER_FILT_TAPn_MIDV` 3/-7/15, bits 4/5/6). Reference state + (`ref_wiener_info`) starts each tile at the tap midpoints (3, -7, 15) and + updates to the just-decoded value after each unit — same per-plane + running-reference shape as `PrevSegmentIds`/other adapting-per-tile state + already in this crate. +- SGR coefficients: one 4-bit literal `ep` (`SGRPROJ_PARAMS_BITS`) indexing + `av1_sgr_params`/`sgr_params` (a small fixed table this crate does not + have yet — needed even for stage 1 since `ep` selects which of `xqd[0]`/ + `xqd[1]` is forced to 0 vs subexp-coded, spec 7.17.3's `Sgr_Params`), then + 1-2 subexp-coded `xqd` values, ranges `(-96, 31, k=4)` and + `(-32, 95, k=4)` (`SGRPROJ_PRJ_MIN/MAX{0,1}`, `SGRPROJ_PRJ_BITS=7`). + +## Next lever +Port the msac-flavoured subexp/recenter quartet into `decode.rs` (or a new +`restoration.rs`), add the `Sgr_Params` table (8 entries, `restoration.c`'s +`av1_sgr_params`, not yet located — grep `sgr_params\[` there), write +`read_lr_unit` using the corner math above, thread +`&header.loop_restoration` into `decode_key_frame_tile_with_cdfs` and +`decode_inter_frame_tile_with_cdfs` (both already take a long positional +arg list matching this pattern — see `cdef`/`loop_filter` params; the two +public one-star wrappers `decode_key_frame_tile`/`decode_inter_frame_tile` +can keep their old signatures by passing `&LoopRestorationParams::default()` +internally, so the ~10 test call sites across `decode.rs` do not need +touching), call `read_lr` once per SB in both superblock loops +(`decode.rs` ~4547 key, ~9275 inter) BEFORE `decode_partition`/its +equivalent, and only then flip `stream.rs`'s refusal from unconditional to +"decode succeeded, still refuse by name because filters are not applied" +(stage 1's own exit criterion: prove the partition walk survives past a +real LR stream). Stage 1 gate: generate an aomenc stream with +`--enable-restoration=1` (default on) via the existing `gradients_source` +helper, decode it, assert the *new* refusal string appears (not the old +desync-shaped one / not an `Err` from deep inside a block reader), and +self-pin firing counts for wiener/sgrproj/switchable via thread-local +`Cell` hit counters the way every other gate in this lane's charter +requires. + +## Turn budget (r1) +Spent ~55 of 75 turns on recon (spec/libaom read_lr shape, corner math, +subexp/recenter porting requirements, CDF value derivation) plus the CDF +landing above; stopped short of wiring `read_lr` itself to avoid leaving a +half-edited, untested threading change across two large decode functions +uncommitted at the cap. Everything above is proven correct in principle +(SB-only firing is a real spec property, not skipped-and-hoped) but wiring ++ the gate itself are unstarted. + +## r2 landed (committed on `lane-lr`, 32892df; 235 passed / 0 failed, +EC_AV1_REQUIRE_AOMENC=1, `232` baseline + 3 new tests) +- `crates/ec-av1/src/restoration.rs` (new): msac-flavoured + `decode_subexp_msac`/`decode_unsigned_subexp_with_ref_msac`/ + `decode_signed_subexp_with_ref_msac`/`ns_msac` (libaom + `read_primitive_subexpfin_`/`aom_read_primitive_refsubexpfin_`/ + `read_primitive_quniform_`, `k` a per-call parameter unlike global + motion's fixed 3) -- pinned by 3 roundtrip tests + (`subexp_roundtrips_every_value`, `unsigned_subexp_with_ref_roundtrips`, + `signed_subexp_with_ref_roundtrips`) against a hand-written encode-side + mirror (`SymbolEncoder` has no LR writer of its own, this crate never + writes LR). Also: `WienerInfo`/`SgrprojInfo`/`UnitFilter`, + `SGR_PARAMS` (`av1_sgr_params`, restoration.c:36, all 16 entries), + `read_wiener_filter`/`read_sgrproj_filter`/`read_lr_unit`/`read_lr` + (spec 5.11.57, decodeframe.c ~1595-1723), `RestorationGrid` (per-plane + unit grid + flattened `runit_idx` storage, `av1_lr_count_units`'s ROUND + not ceil). +- `crates/ec-av1/src/decode.rs`: `decode_key_frame_tile_with_cdfs` and + `decode_inter_frame_tile_with_cdfs` now take `lr: &LoopRestorationParams` + and call `crate::restoration::read_lr` once per superblock (before + `decode_partition`'s own symbol), building a `RestorationGrid` + + per-plane `(WienerInfo, SgrprojInfo)` running reference state before the + loop. The public one-star wrappers (`decode_key_frame_tile`/ + `decode_inter_frame_tile`) pass `&LoopRestorationParams::default()` + unchanged, so their ~10 existing test call sites needed no edits. +- `crates/ec-av1/src/stream.rs`: both call sites thread + `&header.loop_restoration` through; the refusal string is renamed from + "never reads the per-unit lr symbols" to "the per-unit lr symbols are + read but the Wiener/self-guided filters are not yet applied to pixels" + -- the frame STILL refuses (no pixel filter is applied anywhere yet), + but the refusal now names the true remaining gap per charter stage 2's + exit criterion. +- NOT done this round, no gate written: I did not build the aomenc + `--enable-restoration=1` gate the charter's stage 1/2 asks for (proving + the partition walk survives past a real LR stream and self-pinning + wiener/sgrproj/switchable firing counts via thread-local `Cell` + hit counters). Ran out of turn budget before writing it; the full + `cargo test -p ec-av1` suite (235/0, unrelated fixtures) is the only + evidence this round has that the wiring compiles and does not regress + anything -- it does NOT exercise a real LR stream at all, since no + existing gate/fixture in this suite turns `--enable-restoration` on. + +## Next lever (r3) +1. Write the gate: `gradients_source` fixture through aomenc with + `--threads=1 --row-mt=0 --enable-restoration=1` (default on already, + so no flag omission risk), decode it, assert the NEW refusal string + (not an `Err` from a block reader = partition desync, not the old + string). Self-pin `WIENER_HITS`/`SGRPROJ_HITS`/`SWITCHABLE_HITS` + thread-local `Cell` counters bumped inside `read_lr_unit` + (`crates/ec-av1/src/restoration.rs`) -- a gate that cannot prove LR + fired is vacuous per this lane's charter. Given how rare a `Wiener` + frame-level restoration_type is likely to be vs `Switchable` at + default aomenc settings, may need `EC_LR_GATE_ATTEMPTS` bumped like + other lanes' flaky-firing gates (see ledger `lane-maskcomp`). +2. Wiener pixel filter (stage 3): apply after `apply_cdef` (LR runs on the + post-CDEF, post-deblock frame, spec 7.17) as a new `apply_loop_restoration` + pass over `lr_grid`, one restoration-unit rectangle at a time, using + the already-decoded `vfilter`/`hfilter`. The 3-pixel stripe boundary + save/restore (libaom's `rlbs`) is the known trap -- not investigated + this round beyond the report's own citation. +3. SGR filter (stage 4): box-sum radii from `SGR_PARAMS`' `(r0, r1)`, + `av1_apply_selfguided_restoration` shape -- not investigated this + round. +4. Once both filters are wired, drop the `stream.rs` refusal entirely + (stage 5) -- gate should then assert `Ok`, never `Err`. + +## r3 (committed on `lane-lr`, 0cfe9d6; 236 passed / 0 failed, 17 +ignored, EC_AV1_REQUIRE_AOMENC=1) -- VERDICT: step 1 (the gate) landed +and, in the process of landing it, found and fixed a real gap r2's own +report had flagged as unverified. Steps 2-4 (Wiener/SGR pixel filters, +dropping the refusal) NOT started -- out of turn budget. + +- New gate `a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly` + (`crates/ec-av1/src/stream.rs`): real aomenc `--enable-restoration=1 + --sb-size=64` stream, multi-superblock fixture (192x128 = 3x2 SBs of + 64px -- charter's own trap warning), 40 attempts, `cq-level=15` (r2's + sibling gates' usual `cq-level=45` never landed `uses_lr=true` for + this content -- sampled live before picking 15). Self-pinned + `WIENER_HITS`/`SGRPROJ_HITS`/`SWITCHABLE_HITS` thread-local counters + added to `restoration.rs`'s `read_lr_unit`, hard-asserted `sum > 0`. +- **The gate found a real bug**: `stream.rs`'s `header.loop_restoration.uses_lr` + refusal check ran BEFORE the `decode_key_frame_tile_with_cdfs`/ + `decode_inter_frame_tile_with_cdfs` call, so `read_lr` was NEVER + actually invoked through `decode_stream` -- despite r2's report + describing "the symbols are read", no real stream had ever exercised + that claim end to end. First gate run: 40/40 attempts hit the refusal + with `wiener_hits=sgrproj_hits=switchable_hits=0`. Fixed by moving the + check to run AFTER the tile-decode call succeeds (same refusal string, + new position) -- this both proves the superblock walk survives + `read_lr` without desyncing (the charter's actual step-1 ask) and now + genuinely exercises the reader. Also needed `--sb-size=64` in the gate + recipe (without it, aomenc's default sb128 choice hit the unrelated, + already-dead-ended `lane-sb128` partition-desync gap and ate the whole + attempt window with "a partition type this encoder never writes"). +- Final gate result: 39 LR refusals / 0 other refusals out of 40 + attempts, `wiener_hits=19 sgrproj_hits=72 switchable_hits=0` (this + fixture's RD only ever picked a fixed frame-level `Wiener`/`Sgrproj` + type, never `Switchable` -- both non-switchable arms proven live; the + switchable arm is still symbol-code-reviewed only, unexercised by any + gate this round). +- Refusal string: UNCHANGED text ("a frame with loop restoration enabled + (the per-unit lr symbols are read but the Wiener/self-guided filters + are not yet applied to pixels)"), only its position in `decode_stream` + moved (was before the tile-decode call, now after) -- `refusal_inventory.rs` + on main should not need updating for this move since the string itself + didn't change; report this in case main's guard checks call-site order + too. + +## r5 -- VERDICT: not green. 06ba9af compiles clean and was NOT a +mid-edit wip; r4 finished all four charter steps (Wiener + SGR pixel +filters wired at both call sites, gate widened to assert `Ok` + +pixel-exact, `stream.rs` refusal dropped). Suite: 235/236 -- one real, +reproducible (not flake) defect in +`a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly`: +`V mismatch (seed 46 frame 0)`, exactly 1 pixel of 6144 in the V plane, +off by 1 (ours=195, ffmpeg reference=194), at absolute (row=61,col=6), +inside chroma's last/partial restoration stripe `[60,64)` (unit spans +the whole 64px plane height, `--sb-size=64` 192x128 fixture), filter +`Sgrproj{ep:6, xqd:[-16,-32]}` (both radii active, `r0=2` "fast" + +`r1=1` "dense"). Ran 235/236 with `EC_AV1_REQUIRE_AOMENC=1`, +`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`, `-j4`, 600000ms timeout. + +Did NOT commit anything this round -- the tree was already clean at +06ba9af (nothing left mid-edit; the orchestrator's "unverified" label +undersold r4's actual state). All edits made this round were temporary +`eprintln!`/dump instrumentation, reverted with `git checkout --` before +finishing (tree is bit-identical to 06ba9af). + +Diagnosis done, inconclusive on root cause: +- Confirmed NOT a flake -- same failure every run, same seed/pixel. +- Confirmed NOT an above/below stripe-boundary substitution bug -- + hand-traced `lr_sample`'s doc-commented rules + (`stripe_v_start-1`→exact, `-2`/`-3`→both duplicate `stripe_v_start-2`; + `stripe_v_end==plane_h`→frame-edge replicate) against libaom's real + `setup_processing_stripe_boundary`/`save_deblock_boundary_lines` + (`~/.cache/aom-oracle/src/av1/common/restoration.c` ~249-410, + 1355-1490) line by line -- they match exactly for this stripe + (`use_deblock_above=true` since `stripe_idx=2>0`, `use_deblock_below= + false` since it's the plane's last stripe). +- Wrote a live dump harness (env-gated `eprintln!`+file dump inside + `apply_sgrproj_stripe`/`filter_restoration_unit`, since reverted) that + extracted the REAL cdef/deblocked V-plane bytes for the failing + attempt to `/tmp/lr_cdef.bin`/`/tmp/lr_deblocked.bin` (both files + byte-identical, as expected -- gate runs `--enable-cdef=0`). + Instrumented the live Rust `apply_sgrproj_stripe`/`compute_ab` to + print the actual A/B grid values it computes for the failing pixel's + 5-neighbour dense (`r1`) read: `a_u=254 b_u=303 a_c=251 b_c=922 + a_d=224 b_d=6502 a_l=252 b_l=700 a_r=249 b_r=1344`, and the final + combine: `a1=7674 b1=103359 flt1=3110 xq0=-16 xq1=176`. Hand-verified + every one of these numbers independently in Python against the raw + 9-tap box sums read back from the dumped buffers via `lr_sample` -- + ALL MATCH; the dense-radius arm's math is provably correct for this + pixel. Did not get to instrument the fast (`r0=2`) arm's actual grid + reads the same way before the turn cap forced a stop (only its + `a=4000 b=16759 flt0=3097` final numbers were captured, not the 5 + underlying A/B neighbour reads) -- **the fast arm is the one unverified + half**; check that first. +- A hand-written standalone C transcription of libaom's real algorithm + (`/tmp/lr_ref.c`, hex box-sum + av1_x_by_xplus1/av1_one_by_x tables + copied verbatim from `restoration.c`) produced 194 (matching ffmpeg) + against the same dumped buffers -- but a *second*, differently-scoped + probe (`/tmp/lr_probe.c`) printing individual A/B taps gave + self-inconsistent numbers across separate runs of what should be + identical code, so that C reproduction is NOT trustworthy evidence of + a real Rust bug; treat both `/tmp/lr_ref.c` divergence claims as + unconfirmed, not as a finding. The live-Rust-instrumented numbers + above are the reliable data. +- Next agent: re-run this round's dump harness (recreate the 3 + env-gated `eprintln!` blocks -- see this section's description, they + were reverted, not left in the tree) to print the FAST (`r0=2`) arm's + 5 individual A/B neighbour reads (`a_um1/b_um1`, `a_up1/b_up1`, + `a_uml`, `a_umr`, `a_upl`, `a_upr` for the row-61 ODD-branch case -- + wait, row61 is ODD relative to `v_start=60`, so it's actually the + OTHER branch: own-row `a_c/b_c` + `a_l/a_r` neighbours, matching + `restoration.rs`'s `else` arm ~line 738) and hand-verify those 3 + numbers the same way the dense arm was verified above. If those also + check out, the bug is not in `apply_sgrproj_stripe` at all and the + next place to look is upstream: whether the V-plane's CDEF/deblocked + pixel data feeding `lr_sample` is itself off by something that only + this specific rounding-sensitive combination surfaces (Y and U match + bit-exact on every attempt; only V, only this one pixel, only this + one `(ep,xqd)` combination, across the whole 40-attempt run). + +## Next lever (r3 -> r4) +1. Wiener pixel filter (charter step 2): `apply_loop_restoration` after + `apply_cdef` in `decode.rs` (two call sites, ~4983/10502), driven by + the `RestorationGrid`/`(WienerInfo, SgrprojInfo)` this round's gate + proved decode correctly. Watch the 3-pixel stripe boundary save/ + restore (`rlbs`) -- not investigated this round. +2. Self-guided (SGR) filter (charter step 3): box-sum radii from + `SGR_PARAMS`. +3. Once both are wired and this gate's LR frames start decoding + pixel-exact, widen the gate to assert `Ok` + pixel match instead of + the named refusal, then drop the `stream.rs` refusal (charter step 4). + +## Turn budget (r3) +Spent on: reading the charter + r2 section, writing the gate, and +(unplanned but necessary) diagnosing + fixing the check-before-decode +bug the gate exposed -- confirming it via a scratch `EC_AV1_PIN` decode +of a hand-built fixture (`loop_restoration.uses_lr=true`, `frame_restoration_type` +`Sgrproj`) before touching `stream.rs`. Did not reach either pixel +filter; r4 should start directly at Wiener (`decode.rs`'s two +`apply_cdef` call sites), no further libaom recon needed this report +plus `restoration.rs`'s own doc comments don't already cover. + +## Turn budget (r2) +Spent the full 75-turn allowance on: recon of libaom's exact `k`-per-tap +subexp/SGR-table/read_lr_unit shape (not fully covered by r1's report -- +the report's own citations turned out right, but exact constants/ep-branch +logic needed a fresh libaom read from `~/.cache/aom-oracle`), writing + +pinning `restoration.rs`'s bitstream-read half, wiring it into both SB +loops, and confirming no regression (235/0). Did not reach the gate or +either pixel filter -- see "Next lever" above; r3 should start there +directly rather than re-reading libaom (this doc + `restoration.rs`'s own +doc comments now carry every file:line needed). + +## r6 -- VERDICT: not green, still one pixel. Real progress: the +r5-reported divergence source is now DISPROVEN and a decisive, +reusable ground-truth harness exists. Did not commit (no green step; +all edits this round were temporary diagnostics, reverted with `git +checkout --` before finishing -- tree is bit-identical to 02a08bf). + +**Decisive new evidence** (`/tmp/claude-*/scratchpad/lr_sgr_harness.c`, +linked against the real `~/.cache/aom-oracle/build/libaom.a`, calling +the actually-exported `av1_apply_selfguided_restoration_c` / +`av1_selfguided_restoration_c` directly -- not a hand-transcribed +reimplementation, the real compiled function): +- Dumped the exact `lr_sample`-boundary-substituted 102x10 byte buffer + our own `compute_ab`/`apply_sgrproj_stripe` uses for the failing + pixel (V plane, seed 46, ep=6/xqd=[-16,-32], stripe [60,64) of the + 96x64 chroma plane, row 61 col 6) to `/tmp/lr_full.bin`, via a temp + `EC_LR_DUMP`-gated `eprintln!`/`std::fs::write` in + `apply_sgrproj_stripe` (since reverted). +- Fed that *exact same buffer* to the real libaom function (chunked to + width=64 matching libaom's own `RESTORATION_PROC_UNIT_SIZE` + splitting -- `av1_apply_selfguided_restoration_c`'s internal + fixed-size arrays overflow above that, segfault first attempt, + fixed by chunking like `sgrproj_filter_stripe` does). Real libaom, + given identical input pixels, produces **194** (matches ffmpeg) -- + proving the bug is not in `lr_sample`/stripe-boundary substitution + at all (r5's suspicion), since both implementations read the same + bytes and only ours is wrong. +- Also called `av1_selfguided_restoration_c` directly to get the + pre-combine `flt0`/`flt1`: real `flt0[1][6]=3097` (matches our + Rust's fast/r0 arm exactly), real `flt1[1][6]=3109` vs our Rust's + `3110` -- **the divergence is entirely in the dense/r1 arm**, not + the fast arm r5 flagged as the unverified half. +- Instrumented `compute_ab` directly (temp `eprintln!`, reverted) to + dump the 9 individual A/B taps (`c,u,d,l,r,ul,ur,dl,dr`) the dense + combine at (i=1,j=6) actually uses, and independently recomputed + every one from the raw dumped bytes via a clean Python box-sum (not + the earlier untrusted `/tmp/lr_ref.c`/`/tmp/lr_probe.c`) -- **all 9 + match exactly** (`ab1: c=(251,922) u=(254,303) d=(224,6502) + l=(252,700) r=(249,1344) ul=(253,422) ur=(253,486) dl=(241,2974) + dr=(171,17543)`), and the combine formula (weight 4/3, `nb=5`, + `SGRPROJ_SGR_BITS+5-SGRPROJ_RST_BITS` shift) reproduces `3110` + exactly from those 9 values by hand -- so `compute_ab`'s per-cell + math (box sum, `SGR_X_BY_XPLUS1`/`SGR_ONE_BY_X` lookup, rounding) is + internally self-consistent with a naive centered-window recompute, + AND matches the real libaom answer for 8 of 9 taps that a *separate* + cross-check against `boxsum1`'s real sliding-window source + (`restoration.c:418-483`) traced by hand this round confirms is + mathematically equivalent to a naive per-position 3x3 sum for every + physical row/col our grid needs (the sliding-window's own 2-tap + boundary special cases only fire at `local index 0` / the far edge, + both outside the `physical -1..h` range this stripe's grid touches). +- Net: given all 9 A/B taps individually reproduce via a from-scratch + box-sum recompute of the real bytes, but the combined `flt1` still + disagrees with the real compiled function by exactly the 1 LSB that + explains the whole defect, the remaining unaccounted gap is narrow + but NOT yet pinned to a single line -- either one of the 9 taps + itself differs from what real libaom's *compiled* `boxsum`/ + `calculate_intermediate_result` computes (despite the hand-traced + sliding-window algebra saying it shouldn't), or there is a rounding + mode difference (`ROUND_POWER_OF_TWO` for negative/tie values, + `2*(bit_depth-8)` pre-rounds that are no-ops at 8-bit but were not + independently verified as no-ops in the compiled binary) not yet + checked against the real function's per-tap output directly. + +**Ruled out this round** (do not redo): +- `lr_sample`/stripe-boundary substitution as the cause -- disproven + directly (see above), not just re-verified by hand. +- The fast (`r0=2`) arm -- `flt0` matches the real compiled function + bit-exact. r5's charter guess that this was the unverified half was + wrong; it turned out to be already correct. +- `compute_ab`'s formula/table lookup being *generically* wrong -- 8 + of 9 taps match a from-scratch recompute of the real bytes exactly, + and the combine weights/shift match libaom's source line-for-line. +- The earlier `/tmp/lr_ref.c`/`/tmp/lr_probe.c` "194 vs self-inconsistent" + claim from r5 -- irrelevant now; the new harness supersedes it with a + real linked answer, not a hand transcription. + +**Start here (r7)**: get a per-tap ground-truth number directly out of +the compiled libaom binary instead of hand-tracing `boxsum1` further -- +`av1_selfguided_restoration_c` only returns the final `flt0`/`flt1`, +not the intermediate `A`/`B` arrays (`calculate_intermediate_result` is +`static`). Two ways to get them: (a) build a *second* aom-oracle copy +with `calculate_intermediate_result` changed from `static` to +exported-and-declared-in-a-header (rebuild is the `scripts/build-aom-oracle.sh` +recipe, ~5min), then call it directly with the same 9 physical +positions and diff against the 9 values dumped above; or (b) bisect by +zeroing individual pixels in the dumped buffer one at a time and +re-running the harness against both the real function and a +from-scratch recompute to see which single input pixel's value moves +the two answers apart. (a) is more direct. The harness itself +(`av1_apply_selfguided_restoration_c` call pattern, chunked to +width=64, `tmpbuf` sized `2*400*400` -- undersizing it segfaults, see +`RESTORATION_UNITPELS_MAX`) is reusable as-is; a copy is in this +worktree's scratchpad +(`/tmp/claude-1000/.../scratchpad/lr_sgr_harness.c`, +`lr_sgr_harness`), not committed (scratch, not source). + +## Turn budget (r6) +Spent on: building + debugging the real-libaom-linked harness (one +segfault from undersizing the internal tmpbuf, fixed), the input-buffer +dump wiring in `restoration.rs`, and the 9-tap cross-check (including +chasing down two of my own Python transcription bugs mid-round -- +lesson: rerun a "found the bug" number at least once before trusting +it, both false positives here were stale/mistyped variable state, not +real). Ran out of budget before pinning the exact source-level cause; +r7 should start at option (a) above, not redo any of the ruled-out list. + +## r7 -- VERDICT: not green, still one pixel. Built the ground-truth +instrument r6 asked for, but it could not reproduce r6's own "254 vs +253" divergence this round -- open, needs r8 to re-derive with a +uniquely-identified call (see below). Committed `ff1e62f` (harness + +oracle rung + gate pin, all forward progress, no behaviour change to +the decoder). + +**Built** (option (a) from r6, done): +- `scripts/instrument-aom-oracle.sh` rung 6: drops `static` from + libaom's `calculate_intermediate_result` (restoration.c) so an + external harness can call it directly. Rebuilt + `~/.cache/aom-oracle/build/libaom.a` with it (`ninja libaom.a`). +- `scripts/lr-sgr-pin-harness.c` extended: replicates + `av1_selfguided_restoration_c`'s own uint8->int32 border-extend copy, + then calls `calculate_intermediate_result` directly with + `sgr_params_idx=6, radius_idx=1, pass=0` and prints the real A/B for + all 9 dense-arm neighbour taps of the r6 failing pixel. +- Wired `EC_AV1_GATE_DUMP` into + `a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly` + (stream.rs ~4791), mirroring the masked-compound gate's existing + pattern -- pins the exact mismatching stream instead of only + asserting. Ran once, wrote seed 46's stream to + `fixtures/lr-sgr-r7.obu` (gitignored, not in the commit -- copy + survives in this worktree only; regenerate with + `EC_AV1_GATE_DUMP=fixtures/lr-sgr-r7.obu EC_LR_GATE_ATTEMPTS=10` if + it's gone). + +**Result — real ground truth for the "u" tap**: `av1_x_by_xplus1`/ +`av1_one_by_x` real compiled tables, real box sum, real +`ROUND_POWER_OF_TWO` all say the "u" tap (physical row 60, the box +centred one row above the failing pixel) is `(A,B) = (253,454)`, not +the `(254,303)` r6's report recorded. Hand-verified twice (once by +reading libaom's source directly with these exact numbers -- z=101, +`av1_x_by_xplus1[101]=253`, `av1_one_by_x[8]=455`, +`ROUND_POWER_OF_TWO(3*1362*455,12)=454` -- and once independently via +the harness's compiled call). The other 8 taps r6 already trusted are +untouched this round. + +**Could not reproduce r6's divergence.** Added a temporary +`EC_LR_SAMPLE_DUMP` env-gated `eprintln!` to `lr_sample` (reverted, +not in the commit) and reran the live gate at `EC_LR_GATE_ATTEMPTS=5` +(seeds 42-46, the one that panics is 46): the raw bytes our own +`compute_ab` actually reads for the "u" tap's 3x3 window at column 6 +across the three box rows are `111` (row 59, deblocked-boundary read), +`154` (row 60), `194` (row 61) -- these match `/tmp/lr_full.bin`'s +bytes at the same physical positions bit for bit, and an independent +Python replica of `compute_ab`'s exact box-sum/`z`/`A`/`B` formula fed +the full real 9-byte window (100,111,117/140,154,163/182,194,201) +reproduces `(253,454)` exactly -- i.e. this round could not find *any* +wrong input or wrong arithmetic for the "u" tap; both check out +against the real answer independently. r6's `(254,303)` number was not +re-derived from a uniquely-identified call this round (the dump filter +matched on `v_start==60` only, which several different seeds/frames in +the 5-attempt window share, so the samples confirmed above are not +provably from the exact same call r6's `eprintln!` captured, only from +*a* call at the same coordinates producing the same real bytes). + +**Do not re-suspect** (unchanged from r6, now doubly confirmed): `lr_sample` +boundary substitution, the box-sum inputs themselves, the fast/r0 arm, +`compute_ab`'s formula in the abstract (matches source + a from-scratch +Python replica bit for bit for these 9 real bytes). + +**r8 should**: use the now-committed `EC_AV1_GATE_DUMP` wiring plus +`fixtures/lr-sgr-r7.obu` to decode the *single pinned seed-46 stream* +directly (not the live 40-attempt sweep, which reuses coordinates +across unrelated frames), and re-add a debug dump keyed to a value +unique to this one call (e.g. tag the print with a per-call sequence +counter, or gate on the exact `xqd=[-16,-32]` this pixel uses) so the +9 bytes it captures are provably the same call r6's original 3110-vs-3109 +mismatch came from. If that live-captured 9-byte window differs at all +from `100,111,117,140,154,163,182,194,201`, that's the real bug; if it +matches, the (254,303) transcription itself was wrong and the fix is +elsewhere (recheck `flt1`'s combine step in `apply_sgrproj_stripe` +directly, not `compute_ab`, since r6 also independently reproduced +`3110` by hand from the taps it recorded -- meaning either the taps or +the combine, not both, are broken, and this round's evidence points +at the taps). + +## Turn budget (r7) +Spent on: building + verifying the rung 6 harness/oracle patch, +capturing a fresh 9-tap real-libaom answer (all matches r6's 8 except +the "u" tap), a live `EC_LR_SAMPLE_DUMP` trace to try to falsify +r6's claim, and wiring + exercising `EC_AV1_GATE_DUMP` for the gate +(new, reusable). Ran out of budget chasing down the coordinate-vs-call +ambiguity above; r8 should start there, not redo any of this round's +ground-truth derivation. diff --git a/scripts/instrument-aom-oracle.sh b/scripts/instrument-aom-oracle.sh index ac0a2076..346f6c29 100755 --- a/scripts/instrument-aom-oracle.sh +++ b/scripts/instrument-aom-oracle.sh @@ -38,6 +38,15 @@ # its superres margin (lane-superres r5: hand-tracing the arithmetic # could only prove our own self-consistency, not correctness against # libaom). +# Rung 9 (unconditional, no env gate) -- SGR per-tap ground truth +# (lane-lr r7): `calculate_intermediate_result` in +# av1/common/restoration.c is `static`, so a standalone harness cannot +# call it to get real A[]/B[] intermediate arrays, only the final +# flt0/flt1 via the public av1_selfguided_restoration_c. This rung +# drops `static` so an external harness can call it directly with a +# `dgd32`-style buffer (see scripts/lr-sgr-pin-harness.c) and diff +# every A[k]/B[k] tap against a from-scratch recompute -- the missing +# half of r6's 9-tap cross-check. No behaviour change (only linkage). # # Idempotent: re-running is a no-op. Rebuild afterwards with # ninja -C ~/.cache/aom-oracle/build aomdec @@ -458,3 +467,24 @@ s = s.replace(old, new, 1) open(path, "w").write(s) print("palette map[0] instrumented") PYP0 + +# --- rung 9: export calculate_intermediate_result for a direct harness call +I="$SRC/av1/common/restoration.c" +[ -f "$I" ] || { echo "no oracle source at $I" >&2; exit 1; } + +python3 - "$I" <<'PYA' +import sys +path = sys.argv[1] +s = open(path).read() +if "/* EC_INSTRUMENTED_AB */" in s: + print("calculate_intermediate_result already exported (no-op)") + sys.exit(0) + +old = """static void calculate_intermediate_result(int32_t *dgd, int width, int height,""" +new = """/* EC_INSTRUMENTED_AB */ +void calculate_intermediate_result(int32_t *dgd, int width, int height,""" +assert old in s, "calculate_intermediate_result signature moved" +s = s.replace(old, new, 1) +open(path, "w").write(s) +print("calculate_intermediate_result exported") +PYA diff --git a/scripts/lr-sgr-pin-harness.c b/scripts/lr-sgr-pin-harness.c new file mode 100644 index 00000000..6e53aa1b --- /dev/null +++ b/scripts/lr-sgr-pin-harness.c @@ -0,0 +1,89 @@ +#include +#include +#include + +extern int av1_apply_selfguided_restoration_c( + const uint8_t *dat8, int width, int height, int stride, int eps, + const int *xqd, uint8_t *dst8, int dst_stride, int32_t *tmpbuf, + int bit_depth, int highbd); +extern int av1_selfguided_restoration_c(const uint8_t *dgd8, int width, + int height, int dgd_stride, + int32_t *flt0, int32_t *flt1, + int flt_stride, int sgr_params_idx, + int bit_depth, int highbd); +// Exported by scripts/instrument-aom-oracle.sh's rung 6 (normally `static` +// in restoration.c) so this harness can get real per-tap A[]/B[] instead of +// only the combined flt0/flt1 -- the missing half of r6's 9-tap cross-check. +extern void calculate_intermediate_result(int32_t *dgd, int width, int height, + int dgd_stride, int bit_depth, + int sgr_params_idx, int radius_idx, + int pass, int32_t *A, int32_t *B); + +#define SGRPROJ_BORDER_VERT 3 +#define SGRPROJ_BORDER_HORZ 3 + +int main(void) { + const int bw = 102, bh = 10; + // real libaom splits stripe_width into RESTORATION_PROC_UNIT_SIZE=64 + // chunks (sgrproj_filter_stripe's `for j += procunit_width` loop) -- + // av1_apply_selfguided_restoration_c's internal fixed-size arrays are + // sized for that max, so replicate the chunking (target col=6 is in + // the first 64-wide chunk). + const int w = 64, h = 4; + uint8_t *buf = malloc(bw * bh); + FILE *f = fopen("/tmp/lr_full.bin", "rb"); + if (!f) { perror("open"); return 1; } + if (fread(buf, 1, bw * bh, f) != (size_t)(bw * bh)) { fprintf(stderr, "short read\n"); return 1; } + fclose(f); + + const uint8_t *dgd8 = buf + 3 * bw + 3; // logical (0,0) + int xqd[2] = { -16, -32 }; + uint8_t dst[w * h]; + // flt1 = tmpbuf + RESTORATION_UNITPELS_MAX (~152100); undersizing this + // segfaults inside av1_apply_selfguided_restoration_c. + static int32_t tmpbuf[2 * 400 * 400]; + + int ret = av1_apply_selfguided_restoration_c(dgd8, w, h, bw, /*eps=*/6, xqd, + dst, w, tmpbuf, 8, 0); + printf("ret=%d\n", ret); + // target pixel: row i=1, col j=6 + printf("out[1][6] = %d\n", dst[1 * w + 6]); + printf("dgd[1][6] = %d\n", dgd8[1 * bw + 6]); + + static int32_t flt0[400 * 400], flt1[400 * 400]; + int r2 = av1_selfguided_restoration_c(dgd8, w, h, bw, flt0, flt1, w, 6, 8, 0); + printf("selfguided ret=%d flt0[1][6]=%d flt1[1][6]=%d\n", r2, flt0[1 * w + 6], + flt1[1 * w + 6]); + + // --- rung 6: real per-tap A[]/B[] ground truth for the dense (r1) arm --- + // Replicate av1_selfguided_restoration_c's own uint8->int32 border-extend + // copy (that function's `dgd32` setup, restoration.c) so + // calculate_intermediate_result sees exactly the same input it would from + // the real call path above. + const int dgd32_stride = w + 2 * SGRPROJ_BORDER_HORZ; + static int32_t dgd32_buf[(64 + 6) * (4 + 6)]; + int32_t *dgd32 = dgd32_buf + dgd32_stride * SGRPROJ_BORDER_VERT + SGRPROJ_BORDER_HORZ; + for (int i = -SGRPROJ_BORDER_VERT; i < h + SGRPROJ_BORDER_VERT; ++i) + for (int j = -SGRPROJ_BORDER_HORZ; j < w + SGRPROJ_BORDER_HORZ; ++j) + dgd32[i * dgd32_stride + j] = dgd8[i * bw + j]; + + const int width_ext = w + 2 * SGRPROJ_BORDER_HORZ; + const int buf_stride = ((width_ext + 3) & ~3) + 16; + static int32_t A_[2 * 400 * 400], B_[2 * 400 * 400]; + // radius_idx=1 (dense/r1 arm), pass=0 (every row, matches + // selfguided_restoration_internal's own call). + calculate_intermediate_result(dgd32, w, h, dgd32_stride, /*bit_depth=*/8, + /*sgr_params_idx=*/6, /*radius_idx=*/1, + /*pass=*/0, A_, B_); + int32_t *A = A_ + SGRPROJ_BORDER_VERT * buf_stride + SGRPROJ_BORDER_HORZ; + int32_t *B = B_ + SGRPROJ_BORDER_VERT * buf_stride + SGRPROJ_BORDER_HORZ; + const int ti = 1, tj = 6; + const char *names[9] = { "c", "u", "d", "l", "r", "ul", "ur", "dl", "dr" }; + const int di[9] = { 0, -1, 1, 0, 0, -1, -1, 1, 1 }; + const int dj[9] = { 0, 0, 0, -1, 1, -1, 1, -1, 1 }; + for (int t = 0; t < 9; ++t) { + int k = (ti + di[t]) * buf_stride + (tj + dj[t]); + printf("real_ab %s = (%d,%d)\n", names[t], A[k], B[k]); + } + return 0; +}