forge
Explore
Log in

Don't you dare go Hollow

Merge commit '913df61' into lane-superres

Browse files at this commit

849c804f38b05d4b60e915ba87c639e0f9b118d7Ahmet Kaan GümüşParent: d780b9b53dfc78
crates/ec-av1/src/cdf.rsmodified+10 -0
@@ -532,6 +532,16 @@ pub const PALETTE_UV_COLOR_INDEX: [[[u16; 9]; 5]; 7] = [
532 /// `default_intrabc_cdf` (entropymode.c): the `use_intrabc` flag on an532 /// `default_intrabc_cdf` (entropymode.c): the `use_intrabc` flag on an
533 /// intra frame with `allow_intrabc` set.533 /// intra frame with `allow_intrabc` set.
534 pub const INTRABC: [u16; 3] = [30531, 32768, 0];534 pub const INTRABC: [u16; 3] = [30531, 32768, 0];
535+/// `default_wiener_restore_cdf` (entropymode.c): a `RESTORE_WIENER`-plane
536+/// LR unit's own `use_wiener` flag (spec 5.11.57 `read_lr_unit`).
537+pub const RESTORE_WIENER: [u16; 3] = [11570, 32768, 0];
538+/// `default_sgrproj_restore_cdf`: a `RESTORE_SGRPROJ`-plane LR unit's own
539+/// `use_sgrproj` flag.
540+pub const RESTORE_SGRPROJ: [u16; 3] = [16855, 32768, 0];
541+/// `default_switchable_restore_cdf`: a `RESTORE_SWITCHABLE`-plane LR unit's
542+/// own `restoration_type` (3-way: `RESTORE_NONE`/`RESTORE_WIENER`/
543+/// `RESTORE_SGRPROJ`).
544+pub const RESTORE_SWITCHABLE: [u16; 4] = [9413, 22581, 32768, 0];
535 545
536 /// `default_delta_q_cdf` (entropymode.c:840-852, lane-realworld r4): the546 /// `default_delta_q_cdf` (entropymode.c:840-852, lane-realworld r4): the
537 /// 4-symbol `delta_q_abs` alphabet read once per superblock when547 /// 4-symbol `delta_q_abs` alphabet read once per superblock when
crates/ec-av1/src/cdf_state.rsmodified+15 -0
@@ -439,6 +439,15 @@ pub(crate) struct Cdfs {
439 pub palette_uv_color_index: [[[u16; 9]; 5]; 7],439 pub palette_uv_color_index: [[[u16; 9]; 5]; 7],
440 /// The `use_intrabc` flag -- see [`cdf::INTRABC`].440 /// The `use_intrabc` flag -- see [`cdf::INTRABC`].
441 pub intrabc: [u16; 3],441 pub intrabc: [u16; 3],
442+ /// A `RESTORE_WIENER`-plane LR unit's `use_wiener` flag -- see
443+ /// [`cdf::RESTORE_WIENER`].
444+ pub restore_wiener: [u16; 3],
445+ /// A `RESTORE_SGRPROJ`-plane LR unit's `use_sgrproj` flag -- see
446+ /// [`cdf::RESTORE_SGRPROJ`].
447+ pub restore_sgrproj: [u16; 3],
448+ /// A `RESTORE_SWITCHABLE`-plane LR unit's `restoration_type` -- see
449+ /// [`cdf::RESTORE_SWITCHABLE`].
450+ pub restore_switchable: [u16; 4],
442 /// `delta_q_abs` (lane-realworld r4, spec 5.11.10) -- see [`cdf::DELTA_Q`].451 /// `delta_q_abs` (lane-realworld r4, spec 5.11.10) -- see [`cdf::DELTA_Q`].
443 pub delta_q: [u16; 5],452 pub delta_q: [u16; 5],
444 /// `delta_lf_abs`, the single-value form (spec 5.11.11) -- see453 /// `delta_lf_abs`, the single-value form (spec 5.11.11) -- see
@@ -672,6 +681,9 @@ impl Cdfs {
672 reset3(&mut self.palette_y_color_index);681 reset3(&mut self.palette_y_color_index);
673 reset3(&mut self.palette_uv_color_index);682 reset3(&mut self.palette_uv_color_index);
674 reset1(&mut self.intrabc);683 reset1(&mut self.intrabc);
684+ reset1(&mut self.restore_wiener);
685+ reset1(&mut self.restore_sgrproj);
686+ reset1(&mut self.restore_switchable);
675 reset1(&mut self.delta_q);687 reset1(&mut self.delta_q);
676 reset1(&mut self.delta_lf);688 reset1(&mut self.delta_lf);
677 reset2(&mut self.delta_lf_multi);689 reset2(&mut self.delta_lf_multi);
@@ -1137,6 +1149,9 @@ impl Cdfs {
1137 palette_y_color_index: cdf::PALETTE_Y_COLOR_INDEX,1149 palette_y_color_index: cdf::PALETTE_Y_COLOR_INDEX,
1138 palette_uv_color_index: cdf::PALETTE_UV_COLOR_INDEX,1150 palette_uv_color_index: cdf::PALETTE_UV_COLOR_INDEX,
1139 intrabc: cdf::INTRABC,1151 intrabc: cdf::INTRABC,
1152+ restore_wiener: cdf::RESTORE_WIENER,
1153+ restore_sgrproj: cdf::RESTORE_SGRPROJ,
1154+ restore_switchable: cdf::RESTORE_SWITCHABLE,
1140 delta_q: cdf::DELTA_Q,1155 delta_q: cdf::DELTA_Q,
1141 delta_lf: cdf::DELTA_LF,1156 delta_lf: cdf::DELTA_LF,
1142 delta_lf_multi: [cdf::DELTA_LF; 4],1157 delta_lf_multi: [cdf::DELTA_LF; 4],
crates/ec-av1/src/decode.rsmodified+98 -1
@@ -21,7 +21,9 @@
21 //! too). Anything outside that refuses with [`Error::unsupported`] rather than21 //! too). Anything outside that refuses with [`Error::unsupported`] rather than
22 //! silently miscoding.22 //! silently miscoding.
23 23
24-use ec_av1_syntax::{CdefParams, DeltaParams, LoopFilterParams, TileInfo};24+use ec_av1_syntax::{
25+ CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams, TileInfo,
26+};
25 use ec_core::{Error, Result};27 use ec_core::{Error, Result};
26 28
27 use crate::cdf;29 use crate::cdf;
@@ -3353,6 +3355,7 @@ fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
3353 /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly3355 /// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
3354 /// (own-edge and reach clamps both), passing what it gathers straight to3356 /// (own-edge and reach clamps both), passing what it gathers straight to
3355 /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.3357 /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
3358+#[derive(Clone)]
3356 struct PlaneBuf {3359 struct PlaneBuf {
3357 data: Vec<u8>,3360 data: Vec<u8>,
3358 width: usize,3361 width: usize,
@@ -5333,6 +5336,62 @@ fn apply_cdef(
5333 }5336 }
5334 }5337 }
5335 5338
5339+/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
5340+/// ordering note: libaom also runs `superres_post_decode` between the two,
5341+/// but this decoder never implements super-resolution, so there is nothing
5342+/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
5343+/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
5344+/// restoration's stripe-boundary rows read from it instead of the
5345+/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
5346+#[allow(clippy::too_many_arguments)]
5347+fn apply_loop_restoration(
5348+ y: &mut PlaneBuf,
5349+ u: &mut PlaneBuf,
5350+ v: &mut PlaneBuf,
5351+ deblocked_y: &PlaneBuf,
5352+ deblocked_u: &PlaneBuf,
5353+ deblocked_v: &PlaneBuf,
5354+ lr: &LoopRestorationParams,
5355+ grid: &crate::restoration::RestorationGrid,
5356+) {
5357+ y.data = crate::restoration::apply_loop_restoration_plane(
5358+ &y.data,
5359+ &deblocked_y.data,
5360+ y.width,
5361+ y.true_width,
5362+ y.true_height,
5363+ 0,
5364+ lr.frame_restoration_type[0],
5365+ lr.loop_restoration_size[0],
5366+ grid,
5367+ 0,
5368+ );
5369+ u.data = crate::restoration::apply_loop_restoration_plane(
5370+ &u.data,
5371+ &deblocked_u.data,
5372+ u.width,
5373+ u.true_width,
5374+ u.true_height,
5375+ 1,
5376+ lr.frame_restoration_type[1],
5377+ lr.loop_restoration_size[1],
5378+ grid,
5379+ 1,
5380+ );
5381+ v.data = crate::restoration::apply_loop_restoration_plane(
5382+ &v.data,
5383+ &deblocked_v.data,
5384+ v.width,
5385+ v.true_width,
5386+ v.true_height,
5387+ 1,
5388+ lr.frame_restoration_type[2],
5389+ lr.loop_restoration_size[2],
5390+ grid,
5391+ 2,
5392+ );
5393+}
5394+
5336 /// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,5395 /// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
5337 /// returning the picture it reconstructs to.5396 /// returning the picture it reconstructs to.
5338 ///5397 ///
@@ -5384,6 +5443,7 @@ pub fn decode_key_frame_tile(
5384 false,5443 false,
5385 cdef,5444 cdef,
5386 loop_filter,5445 loop_filter,
5446+ &LoopRestorationParams::default(),
5387 None,5447 None,
5388 tx_select,5448 tx_select,
5389 reduced_tx_set,5449 reduced_tx_set,
@@ -5431,6 +5491,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
5431 enable_edge_filter: bool,5491 enable_edge_filter: bool,
5432 cdef: &CdefParams,5492 cdef: &CdefParams,
5433 loop_filter: &LoopFilterParams,5493 loop_filter: &LoopFilterParams,
5494+ lr: &LoopRestorationParams,
5434 initial_cdfs: Option<Cdfs>,5495 initial_cdfs: Option<Cdfs>,
5435 tx_select: bool,5496 tx_select: bool,
5436 reduced_tx_set: bool,5497 reduced_tx_set: bool,
@@ -5506,6 +5567,11 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
5506 mi_cols as usize,5567 mi_cols as usize,
5507 mi_rows as usize,5568 mi_rows as usize,
5508 );5569 );
5570+ let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
5571+ let mut lr_reference = [(
5572+ crate::restoration::WienerInfo::default(),
5573+ crate::restoration::SgrprojInfo::default(),
5574+ ); 3];
5509 5575
5510 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its5576 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
5511 // own byte range and its own fresh copy of the frame's initial CDFs5577 // 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(
5570 for sb_r in sb_r0..sb_r1 {5636 for sb_r in sb_r0..sb_r1 {
5571 neighbours.start_row();5637 neighbours.start_row();
5572 for sb_c in sb_c0..sb_c1 {5638 for sb_c in sb_c0..sb_c1 {
5639+ crate::restoration::read_lr(
5640+ &mut dec,
5641+ &mut cdfs,
5642+ lr,
5643+ &mut lr_grid,
5644+ &mut lr_reference,
5645+ sb_r * SB_MI,
5646+ sb_c * SB_MI,
5647+ SB_MI,
5648+ );
5573 CDEF_TRANSMITTED.with(|c| c.set(false));5649 CDEF_TRANSMITTED.with(|c| c.set(false));
5574 let at = (sb_r as usize * 4, sb_c as usize * 4);5650 let at = (sb_r as usize * 4, sb_c as usize * 4);
5575 let ctx = neighbours.partition_ctx(at, SB);5651 let ctx = neighbours.partition_ctx(at, SB);
@@ -6020,7 +6096,9 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
6020 frame_width as usize,6096 frame_width as usize,
6021 frame_height as usize,6097 frame_height as usize,
6022 );6098 );
6099+ let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
6023 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);6100 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
6101+ apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
6024 6102
6025 let (fw, fh) = (frame_width as usize, frame_height as usize);6103 let (fw, fh) = (frame_width as usize, frame_height as usize);
6026 if fw == width && fh == height {6104 if fw == width && fh == height {
@@ -10213,6 +10291,7 @@ pub fn decode_inter_frame_tile(
10213 other_refs,10291 other_refs,
10214 cdef,10292 cdef,
10215 loop_filter,10293 loop_filter,
10294+ &LoopRestorationParams::default(),
10216 None,10295 None,
10217 allow_high_precision_mv,10296 allow_high_precision_mv,
10218 force_integer_mv,10297 force_integer_mv,
@@ -10256,6 +10335,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
10256 other_refs: [Option<&Picture>; 8],10335 other_refs: [Option<&Picture>; 8],
10257 cdef: &CdefParams,10336 cdef: &CdefParams,
10258 loop_filter: &LoopFilterParams,10337 loop_filter: &LoopFilterParams,
10338+ lr: &LoopRestorationParams,
10259 initial_cdfs: Option<Cdfs>,10339 initial_cdfs: Option<Cdfs>,
10260 allow_high_precision_mv: bool,10340 allow_high_precision_mv: bool,
10261 force_integer_mv: bool,10341 force_integer_mv: bool,
@@ -10474,6 +10554,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
10474 mi_rows as usize,10554 mi_rows as usize,
10475 );10555 );
10476 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);10556 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
10557+ let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
10558+ let mut lr_reference = [(
10559+ crate::restoration::WienerInfo::default(),
10560+ crate::restoration::SgrprojInfo::default(),
10561+ ); 3];
10477 10562
10478 // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile10563 // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile
10479 // loop (spec 5.11.2 decode_tile / 7.20 exit_symbol) -- each tile gets10564 // 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(
10544 for sb_r in sb_r0..sb_r1 {10629 for sb_r in sb_r0..sb_r1 {
10545 neighbours.start_row();10630 neighbours.start_row();
10546 for sb_c in sb_c0..sb_c1 {10631 for sb_c in sb_c0..sb_c1 {
10632+ crate::restoration::read_lr(
10633+ &mut dec,
10634+ &mut cdfs,
10635+ lr,
10636+ &mut lr_grid,
10637+ &mut lr_reference,
10638+ sb_r * SB_MI,
10639+ sb_c * SB_MI,
10640+ SB_MI,
10641+ );
10547 CDEF_TRANSMITTED.with(|c| c.set(false));10642 CDEF_TRANSMITTED.with(|c| c.set(false));
10548 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);10643 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
10549 let sb_ctx = neighbours.partition_ctx(sb_at, SB);10644 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
@@ -11763,7 +11858,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
11763 frame_width as usize,11858 frame_width as usize,
11764 frame_height as usize,11859 frame_height as usize,
11765 );11860 );
11861+ let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
11766 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);11862 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
11863+ apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
11767 11864
11768 let motion_field = build_motion_field(11865 let motion_field = build_motion_field(
11769 &grid,11866 &grid,
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -31,6 +31,7 @@ pub mod mvstack;
31 pub mod obu;31 pub mod obu;
32 pub mod quant;32 pub mod quant;
33 mod refusal_inventory;33 mod refusal_inventory;
34+mod restoration;
34 pub mod sequence;35 pub mod sequence;
35 mod superres;36 mod superres;
36 pub mod stream;37 pub mod stream;
crates/ec-av1/src/refusal_inventory.rsmodified+0 -1
@@ -51,7 +51,6 @@ const REFUSALS: &[&str] = &[
51 "a block that actually uses intrabc (this decoder never reconstructs one)",51 "a block that actually uses intrabc (this decoder never reconstructs one)",
52 "a frame OBU with no tile group",52 "a frame OBU with no tile group",
53 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",53 "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
54- "a frame with loop restoration enabled (this decoder never reads the per-unit lr symbols)",
55 "a frame with no mode-info grid",54 "a frame with no mode-info grid",
56 "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",55 "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",
57 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",56 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
crates/ec-av1/src/restoration.rsadded+1063 -0
@@ -0,0 +1,1063 @@
1+//! AV1 loop restoration: spec 5.11.57 `read_lr`/`read_lr_unit` (per-superblock
2+//! symbol reads, once corners are computed per
3+//! `av1_loop_restoration_corners_in_sb`, restoration.c:1277) and spec 7.17's
4+//! two pixel filters (Wiener, self-guided/SGR). See `lanes/lr.report.md` for
5+//! the full derivation (libaom `decodeframe.c`/`restoration.c` line refs).
6+
7+use crate::msac::SymbolDecoder;
8+use ec_av1_syntax::obu::floor_log2;
9+use ec_av1_syntax::{LoopRestorationParams, RestorationType};
10+
11+/// `ns(n)` (spec 4.10.7) read through the arithmetic coder's equiprobable
12+/// bit primitive (`aom_read_literal`/`SymbolDecoder::literal`), matching
13+/// libaom's `read_primitive_quniform_`. Same algorithm as
14+/// `ec_av1_syntax::obu::read_ns`, ported to the msac reader `decode_subexp`
15+/// needs (LR's coefficients ride the arithmetic-coded tile, not the
16+/// uncompressed header `BitReader` global motion's subexp already targets).
17+fn ns_msac(dec: &mut SymbolDecoder, n: u32) -> u32 {
18+ if n <= 1 {
19+ return 0;
20+ }
21+ let w = floor_log2(n) + 1;
22+ let m = (1u32 << w) - n;
23+ let v = dec.literal(w - 1);
24+ if v < m {
25+ return v;
26+ }
27+ (v << 1) - m + dec.literal(1)
28+}
29+
30+/// `decode_subexp()` (spec 5.9.28) with `k` a parameter, not the fixed `3`
31+/// global motion uses -- libaom's `read_primitive_subexpfin_`. LR's Wiener
32+/// taps and SGR `xqd` each pick a different `k` (1/2/3 for the three Wiener
33+/// taps, 4 for SGR).
34+fn decode_subexp_msac(dec: &mut SymbolDecoder, num_syms: u32, k: u32) -> u32 {
35+ let mut i = 0u32;
36+ let mut mk = 0u32;
37+ loop {
38+ let b = if i > 0 { k + i - 1 } else { k };
39+ let a = 1u32 << b;
40+ if num_syms <= mk + 3 * a {
41+ return ns_msac(dec, num_syms - mk) + mk;
42+ }
43+ if dec.literal(1) == 0 {
44+ return dec.literal(b) + mk;
45+ }
46+ i += 1;
47+ mk += a;
48+ }
49+}
50+
51+/// `inv_recenter_nonneg` (`aom_dsp/recenter.h`) == spec `inverse_recenter`.
52+fn inverse_recenter(r: u32, v: u32) -> u32 {
53+ if v > 2 * r {
54+ v
55+ } else if v & 1 != 0 {
56+ r - ((v + 1) >> 1)
57+ } else {
58+ r + (v >> 1)
59+ }
60+}
61+
62+/// `aom_read_primitive_refsubexpfin` (`inv_recenter_finite_nonneg` composed
63+/// with `read_primitive_subexpfin`): a value in `[0, n)` recentred around
64+/// `reference`.
65+fn decode_unsigned_subexp_with_ref_msac(dec: &mut SymbolDecoder, n: u32, k: u32, reference: u32) -> u32 {
66+ let v = decode_subexp_msac(dec, n, k);
67+ if (reference << 1) <= n {
68+ inverse_recenter(reference, v)
69+ } else {
70+ n - 1 - inverse_recenter(n - 1 - reference, v)
71+ }
72+}
73+
74+/// Signed wrapper, matching the way `read_wiener_filter`/`read_sgrproj_filter`
75+/// call `aom_read_primitive_refsubexpfin(rb, max-min+1, k, ref-min)+min`.
76+fn decode_signed_subexp_with_ref_msac(dec: &mut SymbolDecoder, low: i32, high: i32, k: u32, reference: i32) -> i32 {
77+ let n = (high - low) as u32;
78+ let r = (reference - low).clamp(0, n as i32) as u32;
79+ decode_unsigned_subexp_with_ref_msac(dec, n, k, r) as i32 + low
80+}
81+
82+const WIENER_HALFWIN: usize = 3;
83+pub(crate) const WIENER_WIN: usize = 7;
84+const WIENER_TAP_MINV: [i32; 3] = [-5, -23, -17];
85+const WIENER_TAP_MAXV: [i32; 3] = [10, 8, 46];
86+const WIENER_TAP_K: [u32; 3] = [1, 2, 3];
87+const WIENER_TAP_MIDV: [i32; 3] = [3, -7, 15];
88+
89+/// `WienerInfo`: a restoration unit's 7-tap separable filter, symmetric
90+/// (spec `vfilter[i] == vfilter[6-i]`), with the centre tap derived
91+/// (`WIENER_FILT_STEP - 2*sum(taps 0..3)`, spec 7.17.4).
92+#[derive(Clone, Copy, Debug, PartialEq)]
93+pub(crate) struct WienerInfo {
94+ pub vfilter: [i32; 7],
95+ pub hfilter: [i32; 7],
96+}
97+
98+impl Default for WienerInfo {
99+ fn default() -> Self {
100+ Self {
101+ vfilter: midpoint_filter(),
102+ hfilter: midpoint_filter(),
103+ }
104+ }
105+}
106+
107+fn midpoint_filter() -> [i32; 7] {
108+ let [t0, t1, t2] = WIENER_TAP_MIDV;
109+ let centre = 128 - 2 * (t0 + t1 + t2);
110+ [t0, t1, t2, centre, t2, t1, t0]
111+}
112+
113+/// One direction's 3 free taps (spec `read_wiener_filter`'s per-direction
114+/// loop): reads with `k`/min/max per tap index, recentred on `ref_dir`
115+/// (which the caller updates to the just-decoded value after each unit,
116+/// spec `ref_wiener_info` -- reset to the midpoint filter at each tile).
117+fn read_wiener_direction(dec: &mut SymbolDecoder, chroma: bool, reference: &[i32; 7]) -> [i32; 7] {
118+ let mut taps = [0i32; 3];
119+ for i in 0..3 {
120+ // `wiener_win == WIENER_WIN_CHROMA` (5-tap) skips tap 0, which is
121+ // always 0 for chroma (spec `read_wiener_filter`, `wiener_win`
122+ // branch on plane).
123+ if i == 0 && chroma {
124+ taps[0] = 0;
125+ continue;
126+ }
127+ taps[i] = decode_signed_subexp_with_ref_msac(
128+ dec,
129+ WIENER_TAP_MINV[i],
130+ WIENER_TAP_MAXV[i] + 1,
131+ WIENER_TAP_K[i],
132+ reference[i],
133+ );
134+ }
135+ let centre = 128 - 2 * (taps[0] + taps[1] + taps[2]);
136+ [taps[0], taps[1], taps[2], centre, taps[2], taps[1], taps[0]]
137+}
138+
139+/// `read_wiener_filter` (decodeframe.c ~1595): both directions, updating
140+/// `reference` in place (the running per-plane, per-tile reference state).
141+fn read_wiener_filter(dec: &mut SymbolDecoder, chroma: bool, reference: &mut WienerInfo) -> WienerInfo {
142+ let vfilter = read_wiener_direction(dec, chroma, &reference.vfilter);
143+ let hfilter = read_wiener_direction(dec, chroma, &reference.hfilter);
144+ let info = WienerInfo { vfilter, hfilter };
145+ *reference = info;
146+ info
147+}
148+
149+/// `SgrprojInfo`: one self-guided restoration unit's parameter-set index
150+/// and the two (at most) coded correction weights.
151+#[derive(Clone, Copy, Debug, PartialEq)]
152+pub(crate) struct SgrprojInfo {
153+ pub ep: usize,
154+ pub xqd: [i32; 2],
155+}
156+
157+const SGRPROJ_PRJ_BITS: i32 = 7;
158+const SGRPROJ_PRJ_MIN0: i32 = -(1 << SGRPROJ_PRJ_BITS) * 3 / 4;
159+const SGRPROJ_PRJ_MAX0: i32 = SGRPROJ_PRJ_MIN0 + (1 << SGRPROJ_PRJ_BITS) - 1;
160+const SGRPROJ_PRJ_MIN1: i32 = -(1 << SGRPROJ_PRJ_BITS) / 4;
161+const SGRPROJ_PRJ_MAX1: i32 = SGRPROJ_PRJ_MIN1 + (1 << SGRPROJ_PRJ_BITS) - 1;
162+const SGRPROJ_PRJ_SUBEXP_K: u32 = 4;
163+
164+/// `av1_sgr_params` (`restoration.c:36`): `(r0, r1, s0, s1)` per of the 16
165+/// `SGRPROJ_PARAMS_BITS`-selected parameter sets. `r == 0` for a radius
166+/// means that pass is skipped (its `xqd` is then forced, not coded).
167+pub(crate) const SGR_PARAMS: [(i32, i32, i32, i32); 16] = [
168+ (2, 1, 140, 3236),
169+ (2, 1, 112, 2158),
170+ (2, 1, 93, 1618),
171+ (2, 1, 80, 1438),
172+ (2, 1, 70, 1295),
173+ (2, 1, 58, 1177),
174+ (2, 1, 47, 1079),
175+ (2, 1, 37, 996),
176+ (2, 1, 30, 925),
177+ (2, 1, 25, 863),
178+ (0, 1, -1, 2589),
179+ (0, 1, -1, 1618),
180+ (0, 1, -1, 1177),
181+ (0, 1, -1, 925),
182+ (2, 0, 56, -1),
183+ (2, 0, 22, -1),
184+];
185+
186+/// `read_sgrproj_filter` (decodeframe.c ~1651). `reference` is the running
187+/// per-plane, per-tile `xqd` state (spec `ref_sgrproj_info`), updated in
188+/// place after every read (both coded and forced components).
189+fn read_sgrproj_filter(dec: &mut SymbolDecoder, reference: &mut SgrprojInfo) -> SgrprojInfo {
190+ let ep = dec.literal(4) as usize;
191+ let (r0, r1, _s0, _s1) = SGR_PARAMS[ep];
192+ let mut xqd = [0i32; 2];
193+ if r0 == 0 {
194+ xqd[0] = 0;
195+ xqd[1] = decode_unsigned_subexp_with_ref_msac(
196+ dec,
197+ (SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1) as u32,
198+ SGRPROJ_PRJ_SUBEXP_K,
199+ (reference.xqd[1] - SGRPROJ_PRJ_MIN1) as u32,
200+ ) as i32
201+ + SGRPROJ_PRJ_MIN1;
202+ } else if r1 == 0 {
203+ xqd[0] = decode_unsigned_subexp_with_ref_msac(
204+ dec,
205+ (SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1) as u32,
206+ SGRPROJ_PRJ_SUBEXP_K,
207+ (reference.xqd[0] - SGRPROJ_PRJ_MIN0) as u32,
208+ ) as i32
209+ + SGRPROJ_PRJ_MIN0;
210+ xqd[1] = ((1 << SGRPROJ_PRJ_BITS) - xqd[0]).clamp(SGRPROJ_PRJ_MIN1, SGRPROJ_PRJ_MAX1);
211+ } else {
212+ xqd[0] = decode_unsigned_subexp_with_ref_msac(
213+ dec,
214+ (SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1) as u32,
215+ SGRPROJ_PRJ_SUBEXP_K,
216+ (reference.xqd[0] - SGRPROJ_PRJ_MIN0) as u32,
217+ ) as i32
218+ + SGRPROJ_PRJ_MIN0;
219+ xqd[1] = decode_unsigned_subexp_with_ref_msac(
220+ dec,
221+ (SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1) as u32,
222+ SGRPROJ_PRJ_SUBEXP_K,
223+ (reference.xqd[1] - SGRPROJ_PRJ_MIN1) as u32,
224+ ) as i32
225+ + SGRPROJ_PRJ_MIN1;
226+ }
227+ let info = SgrprojInfo { ep, xqd };
228+ *reference = info;
229+ info
230+}
231+
232+impl Default for SgrprojInfo {
233+ fn default() -> Self {
234+ Self {
235+ ep: 0,
236+ xqd: [
237+ (SGRPROJ_PRJ_MIN0 + SGRPROJ_PRJ_MAX0) / 2,
238+ (SGRPROJ_PRJ_MIN1 + SGRPROJ_PRJ_MAX1) / 2,
239+ ],
240+ }
241+ }
242+}
243+
244+/// One restoration unit's decoded filter (spec `RestorationUnitInfo`,
245+/// `RESTORE_NONE`/`WIENER`/`SGRPROJ` -- `Switchable`-frame units pick one of
246+/// these per unit; `Wiener`/`Sgrproj`-frame units are all this same variant
247+/// or `None`).
248+#[derive(Clone, Copy, Debug, PartialEq)]
249+pub(crate) enum UnitFilter {
250+ None,
251+ Wiener(WienerInfo),
252+ Sgrproj(SgrprojInfo),
253+}
254+
255+/// Per-plane restoration-unit grid for one tile/frame (spec `RestorationInfo`
256+/// per plane) -- `av1_lr_count_units`'s `horz_units`/`vert_units` sizing plus
257+/// the flattened `runit_idx = rcol + rrow*horz_units` storage `read_lr`
258+/// fills in superblock order.
259+pub(crate) struct RestorationGrid {
260+ pub horz_units: [usize; 3],
261+ pub vert_units: [usize; 3],
262+ units: [Vec<UnitFilter>; 3],
263+}
264+
265+impl RestorationGrid {
266+ pub(crate) fn new(lr: &LoopRestorationParams, frame_width: u32, frame_height: u32) -> Self {
267+ let mut horz_units = [1usize; 3];
268+ let mut vert_units = [1usize; 3];
269+ let mut units: [Vec<UnitFilter>; 3] = [Vec::new(), Vec::new(), Vec::new()];
270+ for plane in 0..3 {
271+ if lr.frame_restoration_type[plane] == RestorationType::None {
272+ continue;
273+ }
274+ let (pw, ph) = if plane == 0 {
275+ (frame_width, frame_height)
276+ } else {
277+ ((frame_width + 1) / 2, (frame_height + 1) / 2)
278+ };
279+ let unit_size = lr.loop_restoration_size[plane];
280+ horz_units[plane] = count_units(pw, unit_size);
281+ vert_units[plane] = count_units(ph, unit_size);
282+ units[plane] = vec![UnitFilter::None; horz_units[plane] * vert_units[plane]];
283+ }
284+ Self {
285+ horz_units,
286+ vert_units,
287+ units,
288+ }
289+ }
290+
291+ fn set(&mut self, plane: usize, rrow: usize, rcol: usize, filter: UnitFilter) {
292+ let idx = rcol + rrow * self.horz_units[plane];
293+ self.units[plane][idx] = filter;
294+ }
295+
296+ pub(crate) fn get(&self, plane: usize, rrow: usize, rcol: usize) -> UnitFilter {
297+ let idx = rcol + rrow * self.horz_units[plane];
298+ self.units[plane][idx]
299+ }
300+}
301+
302+/// `av1_lr_count_units` (restoration.c:63): round, not ceil, to nearest.
303+fn count_units(plane_size: u32, unit_size: u32) -> usize {
304+ (((plane_size + (unit_size >> 1)) / unit_size).max(1)) as usize
305+}
306+
307+fn ceil_div(a: u32, b: u32) -> u32 {
308+ a.div_ceil(b)
309+}
310+
311+/// `read_lr` (spec 5.11.57) for one superblock at mode-info position
312+/// `(mi_row, mi_col)`: for every plane the frame uses LR on, computes the
313+/// unit-grid corners this superblock covers
314+/// (`av1_loop_restoration_corners_in_sb`, restoration.c:1277 -- every unit
315+/// is >= 64px, so only the top-of-superblock call ever has non-empty
316+/// corners, matching this decoder's own once-per-SB call site) and reads
317+/// one `read_lr_unit` per covered `(rrow, rcol)`, per plane, in plane
318+/// order. `sb_mi` is the superblock's mode-info width (`SB_MI`, 16 for the
319+/// 64px superblocks this decoder always uses).
320+#[allow(clippy::too_many_arguments)]
321+pub(crate) fn read_lr(
322+ dec: &mut SymbolDecoder,
323+ cdfs: &mut crate::cdf_state::Cdfs,
324+ lr: &LoopRestorationParams,
325+ grid: &mut RestorationGrid,
326+ reference: &mut [(WienerInfo, SgrprojInfo); 3],
327+ mi_row: u32,
328+ mi_col: u32,
329+ sb_mi: u32,
330+) {
331+ if !lr.uses_lr {
332+ return;
333+ }
334+ for plane in 0..3 {
335+ let ftype = lr.frame_restoration_type[plane];
336+ if ftype == RestorationType::None {
337+ continue;
338+ }
339+ let mi_size = if plane == 0 { 4u32 } else { 2u32 };
340+ let unit_size = lr.loop_restoration_size[plane];
341+ let horz_units = grid.horz_units[plane] as u32;
342+ let vert_units = grid.vert_units[plane] as u32;
343+ let rcol0 = ceil_div(mi_col * mi_size, unit_size);
344+ let rcol1 = ceil_div((mi_col + sb_mi) * mi_size, unit_size).min(horz_units);
345+ let rrow0 = ceil_div(mi_row * mi_size, unit_size);
346+ let rrow1 = ceil_div((mi_row + sb_mi) * mi_size, unit_size).min(vert_units);
347+ let chroma = plane != 0;
348+ for rrow in rrow0..rrow1 {
349+ for rcol in rcol0..rcol1 {
350+ let filter = read_lr_unit(dec, cdfs, ftype, chroma, &mut reference[plane]);
351+ grid.set(plane, rrow as usize, rcol as usize, filter);
352+ }
353+ }
354+ }
355+}
356+
357+/// r3 gate self-pin: how many units decoded a real (non-`None`) filter, by
358+/// kind -- proves a real `--enable-restoration=1` aomenc stream actually
359+/// exercises `read_lr_unit`'s Wiener/SGR/switchable arms, not just that the
360+/// symbol-count/refusal-string wiring compiles. Never reset -- summed across
361+/// a gate's whole attempt loop, matching `MASKED_COMPOUND_HITS`/`WEDGE_HITS`
362+/// (decode.rs) which this mirrors.
363+thread_local! {
364+ static WIENER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
365+ static SGRPROJ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
366+ static SWITCHABLE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
367+}
368+
369+/// Current value of [`WIENER_HITS`].
370+pub(crate) fn wiener_hits() -> usize {
371+ WIENER_HITS.with(|c| c.get())
372+}
373+/// Current value of [`SGRPROJ_HITS`].
374+pub(crate) fn sgrproj_hits() -> usize {
375+ SGRPROJ_HITS.with(|c| c.get())
376+}
377+/// Current value of [`SWITCHABLE_HITS`] -- bumped once per unit whose frame
378+/// `restoration_type` is `Switchable`, regardless of which `RestoreType`
379+/// (`None`/Wiener/Sgrproj) that unit's own symbol resolved to.
380+pub(crate) fn switchable_hits() -> usize {
381+ SWITCHABLE_HITS.with(|c| c.get())
382+}
383+
384+fn read_lr_unit(
385+ dec: &mut SymbolDecoder,
386+ cdfs: &mut crate::cdf_state::Cdfs,
387+ ftype: RestorationType,
388+ chroma: bool,
389+ reference: &mut (WienerInfo, SgrprojInfo),
390+) -> UnitFilter {
391+ match ftype {
392+ RestorationType::Switchable => {
393+ SWITCHABLE_HITS.with(|c| c.set(c.get() + 1));
394+ let t = dec.symbol(&mut cdfs.restore_switchable);
395+ match t {
396+ 0 => UnitFilter::None,
397+ 1 => {
398+ WIENER_HITS.with(|c| c.set(c.get() + 1));
399+ UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0))
400+ }
401+ _ => {
402+ SGRPROJ_HITS.with(|c| c.set(c.get() + 1));
403+ UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1))
404+ }
405+ }
406+ }
407+ RestorationType::Wiener => {
408+ if dec.symbol(&mut cdfs.restore_wiener) != 0 {
409+ WIENER_HITS.with(|c| c.set(c.get() + 1));
410+ UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0))
411+ } else {
412+ UnitFilter::None
413+ }
414+ }
415+ RestorationType::Sgrproj => {
416+ let bit = dec.symbol(&mut cdfs.restore_sgrproj);
417+ if bit != 0 {
418+ SGRPROJ_HITS.with(|c| c.set(c.get() + 1));
419+ UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1))
420+ } else {
421+ UnitFilter::None
422+ }
423+ }
424+ RestorationType::None => UnitFilter::None,
425+ }
426+}
427+
428+// ---------------------------------------------------------------------
429+// Spec 7.17: the two pixel filters (Wiener, self-guided) plus the
430+// restoration-unit/stripe walk that drives them.
431+// ---------------------------------------------------------------------
432+
433+/// `Round2` (spec 4.7): halves round up, arithmetic shift for negative sums
434+/// -- same primitive as `mc.rs`/`warp.rs`'s own `round2`, here at `i64`
435+/// since the self-guided filter's intermediate products don't fit `i32`.
436+fn round2(value: i64, shift: u32) -> i64 {
437+ if shift == 0 {
438+ value
439+ } else {
440+ (value + (1i64 << (shift - 1))) >> shift
441+ }
442+}
443+
444+/// One plane's sample fetch for the pixel filters (spec 7.17.2's stripe
445+/// boundary substitution, libaom `setup_processing_stripe_boundary`/
446+/// `get_stripe_boundary_info`): within the stripe `[stripe_v_start,
447+/// stripe_v_end)` currently being filtered, read the post-CDEF plane;
448+/// outside it (the 3-row border both filters' kernels reach into), read the
449+/// post-deblock, pre-CDEF plane instead -- UNLESS the stripe is the very
450+/// first/last stripe in the whole plane, where the frame's own top/bottom
451+/// edge replicates (`av1_extend_frame`) rather than crossing into deblocked
452+/// data. Columns always clamp to the plane's own true width -- restoration
453+/// unit COLUMN boundaries have no such substitution, only stripe (row)
454+/// boundaries do.
455+#[allow(clippy::too_many_arguments)]
456+fn lr_sample(
457+ cdef: &[u8],
458+ deblocked: &[u8],
459+ stride: usize,
460+ plane_w: usize,
461+ plane_h: usize,
462+ stripe_v_start: usize,
463+ stripe_v_end: usize,
464+ row: i64,
465+ col: i64,
466+) -> i32 {
467+ let col_c = col.clamp(0, plane_w as i64 - 1) as usize;
468+ if row >= stripe_v_start as i64 && row < stripe_v_end as i64 {
469+ i32::from(cdef[row as usize * stride + col_c])
470+ } else if row < stripe_v_start as i64 {
471+ if stripe_v_start == 0 {
472+ i32::from(cdef[col_c])
473+ } else {
474+ // libaom saves 2 deblocked context lines and duplicates the
475+ // outer one to fill a 3-row border (`RESTORATION_BORDER`):
476+ // row `stripe_v_start-1` reads deblocked row `stripe_v_start-1`,
477+ // rows `stripe_v_start-2`/`-3` both read deblocked row
478+ // `stripe_v_start-2`.
479+ let dist = stripe_v_start as i64 - 1 - row;
480+ let src_row = if dist == 0 {
481+ stripe_v_start - 1
482+ } else {
483+ stripe_v_start.saturating_sub(2)
484+ };
485+ i32::from(deblocked[src_row * stride + col_c])
486+ }
487+ } else if stripe_v_end == plane_h {
488+ i32::from(cdef[(plane_h - 1) * stride + col_c])
489+ } else {
490+ // Mirror image of the above: rows `stripe_v_end`/`stripe_v_end+1`
491+ // read their own deblocked row, row `stripe_v_end+2` duplicates
492+ // `stripe_v_end+1`.
493+ let dist = (row - stripe_v_end as i64).min(1) as usize;
494+ let src_row = (stripe_v_end + dist).min(plane_h - 1);
495+ i32::from(deblocked[src_row * stride + col_c])
496+ }
497+}
498+
499+/// Wiener pixel filter (spec 7.17.4, libaom `wiener_filter_stripe` ->
500+/// `av1_wiener_convolve_add_src_c`), one stripe-height chunk of one
501+/// restoration unit: a separable 7-tap horizontal pass (rounded by
502+/// `WIENER_ROUND0_BITS==3`, clipped to spec's intermediate range) feeding a
503+/// 7-tap vertical pass (rounded by `2*FILTER_BITS-3==11`) -- the same
504+/// `INTER_ROUND_0`/`INTER_ROUND_1` shifts `mc.rs`'s motion compensation
505+/// uses, since AV1 reuses that same separable-filter machinery here with a
506+/// custom 7-tap kernel instead of the fixed subpel tables. libaom's C
507+/// folds an extra `+/- (1 << ...)` bias into each pass to compensate for a
508+/// pointer-alignment trick that borrows the interpolation filter's 8-tap
509+/// convolution loop for a 7-tap kernel; that bias cancels algebraically
510+/// against `WienerInfo`'s own derived centre tap (`128 - 2*sum(taps)`), so
511+/// plugging the real taps straight into `sum(tap * sample)` (no bias term)
512+/// reproduces the same output byte-for-byte.
513+#[allow(clippy::too_many_arguments)]
514+fn apply_wiener_stripe(
515+ out: &mut [u8],
516+ cdef: &[u8],
517+ deblocked: &[u8],
518+ stride: usize,
519+ plane_w: usize,
520+ plane_h: usize,
521+ h_start: usize,
522+ h_end: usize,
523+ v_start: usize,
524+ v_end: usize,
525+ info: &WienerInfo,
526+) {
527+ let w = h_end - h_start;
528+ let h = v_end - v_start;
529+ if w == 0 || h == 0 {
530+ return;
531+ }
532+ let rows = h + 6;
533+ let mut inter = vec![0i32; rows * w];
534+ for r in 0..rows {
535+ let row = v_start as i64 - 3 + r as i64;
536+ for c in 0..w {
537+ let col = h_start as i64 + c as i64;
538+ let mut sum = 0i64;
539+ for (t, &tap) in info.hfilter.iter().enumerate() {
540+ let x = col - 3 + t as i64;
541+ sum += tap as i64
542+ * lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, x) as i64;
543+ }
544+ // `WIENER_CLAMP_LIMIT(round0=3, bd=8) - 1`.
545+ inter[r * w + c] = round2(sum, 3).clamp(0, 8191) as i32;
546+ }
547+ }
548+ for r in 0..h {
549+ for c in 0..w {
550+ let mut sum = 0i64;
551+ for (t, &tap) in info.vfilter.iter().enumerate() {
552+ sum += tap as i64 * inter[(r + t) * w + c] as i64;
553+ }
554+ out[(v_start + r) * stride + h_start + c] = round2(sum, 11).clamp(0, 255) as u8;
555+ }
556+ }
557+}
558+
559+/// `av1_x_by_xplus1` (`restoration.c`): `round(256*z/(z+1))` for `z` in
560+/// `[0,255]`, saturating the `z==0` case to `1` instead of `0` (see the
561+/// libaom source comment this ports -- keeps `256-A[k]` inside a `u8` and
562+/// avoids a later overflow, without visibly affecting a near-flat block).
563+// r8: this table was transcribed with two errors -- index 101 (253 written
564+// as 254) and indices 165..=169 (254 written as 255) -- traced by comparing
565+// a call-unique dump (gated on the pinned stream's `xqd == [-16,-32]`, not a
566+// reused coordinate) against libaom's real `av1_x_by_xplus1` at the same
567+// `z=101`; both tables now generated straight from
568+// `~/.cache/aom-oracle/src/av1/common/restoration.c` to rule out any other
569+// transcription slip.
570+const SGR_X_BY_XPLUS1: [i32; 256] = [
571+ 1, 128, 171, 192, 205, 213, 219, 224, 228, 230, 233, 235, 236, 238, 239,
572+ 240, 241, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247, 247, 247, 247,
573+ 248, 248, 248, 248, 249, 249, 249, 249, 249, 250, 250, 250, 250, 250, 250,
574+ 250, 251, 251, 251, 251, 251, 251, 251, 251, 251, 251, 252, 252, 252, 252,
575+ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 253, 253,
576+ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253,
577+ 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 254, 254, 254,
578+ 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
579+ 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
580+ 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
581+ 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254,
582+ 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
583+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
584+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
585+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
586+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
587+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
588+ 256,
589+];
590+
591+/// `av1_one_by_x` (`restoration.c`): `round(4096/n)` for `n` in `1..=25`
592+/// (`MAX_NELEM`, `(2*MAX_RADIUS+1)^2`), indexed `[n-1]`.
593+const SGR_ONE_BY_X: [i32; 25] = [
594+ 4096, 2048, 1365, 1024, 819, 683, 585, 512, 455, 410, 372, 341, 315, 293, 273, 256, 241, 228, 216, 205, 195, 186,
595+ 178, 171, 164,
596+];
597+
598+const SGRPROJ_MTABLE_BITS: u32 = 20;
599+const SGRPROJ_RECIP_BITS: u32 = 12;
600+const SGRPROJ_SGR_BITS: u32 = 8;
601+const SGRPROJ_RST_BITS: u32 = 4;
602+
603+/// `calculate_intermediate_result` (`restoration.c`): the blend-factor pair
604+/// `(A[k], B[k])` at every position in `-1..=h` x `-1..=w` relative to a
605+/// restoration unit (a 1-pixel border around the unit, spec 7.17.3's
606+/// `BoxFilter`), for one of the two SGR radii. `r`/`s` are `SGR_PARAMS[ep]`'s
607+/// `(r0,s0)` or `(r1,s1)`; libaom computes this only at odd rows for the
608+/// `r==2` ("fast") radius as a running-sum speed optimisation -- the box
609+/// sum itself is identical at every row regardless, so computing it
610+/// everywhere (this function does, via a plain windowed sum through
611+/// [`lr_sample`] rather than libaom's O(1)-per-step sliding sum) and only
612+/// *reading* the odd rows back in [`apply_sgrproj_stripe`]'s fast branch
613+/// reproduces the same values without porting the sliding-window trick.
614+#[allow(clippy::too_many_arguments)]
615+fn compute_ab(
616+ cdef: &[u8],
617+ deblocked: &[u8],
618+ stride: usize,
619+ plane_w: usize,
620+ plane_h: usize,
621+ h_start: usize,
622+ v_start: usize,
623+ v_end: usize,
624+ w: usize,
625+ h: usize,
626+ r: i32,
627+ s: i32,
628+) -> Vec<(i32, i64)> {
629+ let gw = w + 2;
630+ let gh = h + 2;
631+ let mut ab = vec![(0i32, 0i64); gw * gh];
632+ let n = ((2 * r + 1) * (2 * r + 1)) as i64;
633+ for gi in 0..gh {
634+ let i = gi as i64 - 1;
635+ for gj in 0..gw {
636+ let j = gj as i64 - 1;
637+ let mut a = 0i64;
638+ let mut b = 0i64;
639+ for dr in -r..=r {
640+ let row = v_start as i64 + i + dr as i64;
641+ for dc in -r..=r {
642+ let col = h_start as i64 + j + dc as i64;
643+ let px =
644+ lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col) as i64;
645+ a += px * px;
646+ b += px;
647+ }
648+ }
649+ let p = if a * n < b * b { 0 } else { a * n - b * b };
650+ let z = round2(p * s as i64, SGRPROJ_MTABLE_BITS).clamp(0, 255) as usize;
651+ let a_val = SGR_X_BY_XPLUS1[z];
652+ let b_val = round2(
653+ (256 - a_val) as i64 * b * SGR_ONE_BY_X[(n - 1) as usize] as i64,
654+ SGRPROJ_RECIP_BITS,
655+ );
656+ if std::env::var("EC_LR_CALL_DUMP").is_ok()
657+ && v_start as i64 + i == 60
658+ && h_start as i64 + j == 6
659+ && r == 1
660+ {
661+ eprintln!(
662+ "EC_LR_CALL_DUMP compute_ab u_tap: r={r} s={s} n={n} box_a={a} box_b={b} \
663+ p={p} z={z} a_val={a_val} b_val={b_val}"
664+ );
665+ }
666+ ab[gi * gw + gj] = (a_val, b_val);
667+ }
668+ }
669+ ab
670+}
671+
672+/// Self-guided pixel filter (spec 7.17.3, libaom `sgrproj_filter_stripe` ->
673+/// `av1_apply_selfguided_restoration_c`), one stripe-height chunk of one
674+/// restoration unit: up to two box-filtered blends (`SGR_PARAMS[ep]`'s `r0`
675+/// "fast"/even-odd-row and `r1` dense radii, either may be `0` and skipped)
676+/// combined with the decoded `xqd` weights via `av1_decode_xq`.
677+#[allow(clippy::too_many_arguments)]
678+fn apply_sgrproj_stripe(
679+ out: &mut [u8],
680+ cdef: &[u8],
681+ deblocked: &[u8],
682+ stride: usize,
683+ plane_w: usize,
684+ plane_h: usize,
685+ h_start: usize,
686+ h_end: usize,
687+ v_start: usize,
688+ v_end: usize,
689+ info: &SgrprojInfo,
690+) {
691+ let w = h_end - h_start;
692+ let h = v_end - v_start;
693+ if w == 0 || h == 0 {
694+ return;
695+ }
696+ let (r0, r1, s0, s1) = SGR_PARAMS[info.ep];
697+ let gw = w + 2;
698+ let idx = |gi: i64, gj: i64| -> usize { (gi + 1) as usize * gw + (gj + 1) as usize };
699+
700+ let ab0 = (r0 > 0).then(|| compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r0, s0));
701+ let ab1 = (r1 > 0).then(|| compute_ab(cdef, deblocked, stride, plane_w, plane_h, h_start, v_start, v_end, w, h, r1, s1));
702+
703+ // r8: call-unique debug dump -- r6's coordinate-only gate (`v_start==60`)
704+ // matched several unrelated calls across the gate's attempt sweep, so its
705+ // captured bytes were never provably from the failing call. `info.xqd`
706+ // is this restoration unit's own decoded weights, unique to the one call
707+ // r7 traced (`[-16,-32]`); dump the real 9-byte dense-arm (r1) "u"-tap
708+ // window (physical rows 59..=61, cols 5..=7 -- r7's traced tap) straight
709+ // from `lr_sample` for this exact call, no coordinate matching involved.
710+ if std::env::var("EC_LR_CALL_DUMP").is_ok() && r1 > 0 && info.xqd == [-16, -32] {
711+ let bytes: Vec<i32> = (59..=61)
712+ .flat_map(|row| {
713+ (5..=7).map(move |col| {
714+ lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col)
715+ })
716+ })
717+ .collect();
718+ eprintln!(
719+ "EC_LR_CALL_DUMP: xqd={:?} v_start={v_start} v_end={v_end} h_start={h_start} \
720+ u-tap 9-byte window (rows 59..=61, cols 5..=7) = {bytes:?}",
721+ info.xqd
722+ );
723+ }
724+
725+ let mut xq = [0i32; 2];
726+ if r0 == 0 {
727+ xq[0] = 0;
728+ xq[1] = (1 << SGRPROJ_PRJ_BITS) - info.xqd[1];
729+ } else if r1 == 0 {
730+ xq[0] = info.xqd[0];
731+ xq[1] = 0;
732+ } else {
733+ xq[0] = info.xqd[0];
734+ xq[1] = (1 << SGRPROJ_PRJ_BITS) - xq[0] - info.xqd[1];
735+ }
736+
737+ for i in 0..h as i64 {
738+ for j in 0..w as i64 {
739+ let dgd = lr_sample(
740+ cdef,
741+ deblocked,
742+ stride,
743+ plane_w,
744+ plane_h,
745+ v_start,
746+ v_end,
747+ v_start as i64 + i,
748+ h_start as i64 + j,
749+ ) as i64;
750+ let u = dgd << SGRPROJ_RST_BITS;
751+ let mut v = u << SGRPROJ_PRJ_BITS;
752+ if let Some(ab) = &ab0 {
753+ // "Fast" radius (`r0==2`): A/B were only ever meaningfully
754+ // computed at odd rows (see `compute_ab`'s doc comment) --
755+ // an even output row blends its two odd neighbour rows
756+ // (weight 6/5, `nb=5`), an odd output row reuses its own
757+ // row's A/B plus column neighbours (weight 6/5, `nb=4`).
758+ let (a, b, nb) = if i & 1 == 0 {
759+ let (a_um1, b_um1) = ab[idx(i - 1, j)];
760+ let (a_up1, b_up1) = ab[idx(i + 1, j)];
761+ let (a_uml, b_uml) = ab[idx(i - 1, j - 1)];
762+ let (a_umr, b_umr) = ab[idx(i - 1, j + 1)];
763+ let (a_upl, b_upl) = ab[idx(i + 1, j - 1)];
764+ let (a_upr, b_upr) = ab[idx(i + 1, j + 1)];
765+ let a = (a_um1 + a_up1) as i64 * 6 + (a_uml + a_umr + a_upl + a_upr) as i64 * 5;
766+ let b = (b_um1 + b_up1) * 6 + (b_uml + b_umr + b_upl + b_upr) * 5;
767+ (a, b, 5u32)
768+ } else {
769+ let (a_c, b_c) = ab[idx(i, j)];
770+ let (a_l, b_l) = ab[idx(i, j - 1)];
771+ let (a_r, b_r) = ab[idx(i, j + 1)];
772+ let a = a_c as i64 * 6 + (a_l + a_r) as i64 * 5;
773+ let b = b_c * 6 + (b_l + b_r) * 5;
774+ (a, b, 4u32)
775+ };
776+ let flt0 = round2(a * dgd + b, SGRPROJ_SGR_BITS + nb - SGRPROJ_RST_BITS);
777+ v += xq[0] as i64 * (flt0 - u);
778+ }
779+ if let Some(ab) = &ab1 {
780+ // Dense radius (`r1==1`): every row was computed, so the
781+ // combine is the full 3x3 neighbourhood (weight 4/3).
782+ let (a_c, b_c) = ab[idx(i, j)];
783+ let (a_u, b_u) = ab[idx(i - 1, j)];
784+ let (a_d, b_d) = ab[idx(i + 1, j)];
785+ let (a_l, b_l) = ab[idx(i, j - 1)];
786+ let (a_r, b_r) = ab[idx(i, j + 1)];
787+ let (a_ul, b_ul) = ab[idx(i - 1, j - 1)];
788+ let (a_ur, b_ur) = ab[idx(i - 1, j + 1)];
789+ let (a_dl, b_dl) = ab[idx(i + 1, j - 1)];
790+ let (a_dr, b_dr) = ab[idx(i + 1, j + 1)];
791+ 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;
792+ let b = (b_c + b_u + b_d + b_l + b_r) * 4 + (b_ul + b_ur + b_dl + b_dr) * 3;
793+ let flt1 = round2(a * dgd + b, SGRPROJ_SGR_BITS + 5 - SGRPROJ_RST_BITS);
794+ v += xq[1] as i64 * (flt1 - u);
795+ if std::env::var("EC_LR_CALL_DUMP").is_ok()
796+ && info.xqd == [-16, -32]
797+ && v_start as i64 + i == 61
798+ && h_start as i64 + j == 6
799+ {
800+ eprintln!(
801+ "EC_LR_CALL_DUMP combine: c={:?} u_tap(row60)={:?} d={:?} l={:?} r={:?} \
802+ ul={:?} ur={:?} dl={:?} dr={:?} dense a={a} b={b} dgd={dgd} \
803+ u={u} flt1={flt1} xq={xq:?} v_before_final_round={v}",
804+ ab[idx(i, j)], ab[idx(i - 1, j)], ab[idx(i + 1, j)], ab[idx(i, j - 1)],
805+ ab[idx(i, j + 1)], ab[idx(i - 1, j - 1)], ab[idx(i - 1, j + 1)],
806+ ab[idx(i + 1, j - 1)], ab[idx(i + 1, j + 1)]
807+ );
808+ }
809+ }
810+ let out_v = round2(v, SGRPROJ_PRJ_BITS as u32 + SGRPROJ_RST_BITS).clamp(0, 255) as u8;
811+ out[(v_start as i64 + i) as usize * stride + (h_start as i64 + j) as usize] = out_v;
812+ }
813+ }
814+}
815+
816+/// Chunks one restoration unit's `[v_start, v_end)` extent into 64-row
817+/// (56 for the plane's very first stripe -- `RESTORATION_UNIT_OFFSET==8`)
818+/// processing stripes and filters each (libaom
819+/// `av1_loop_restoration_filter_unit`'s own `while (i < unit_h)` loop) --
820+/// a restoration unit can be up to `256*1.5` px tall, spanning several
821+/// stripes, each of which needs its own boundary-source decision from
822+/// [`lr_sample`].
823+#[allow(clippy::too_many_arguments)]
824+fn filter_restoration_unit(
825+ out: &mut [u8],
826+ cdef: &[u8],
827+ deblocked: &[u8],
828+ stride: usize,
829+ plane_w: usize,
830+ plane_h: usize,
831+ h_start: usize,
832+ h_end: usize,
833+ v_start: usize,
834+ v_end: usize,
835+ ss_y: u32,
836+ filter: UnitFilter,
837+) {
838+ let full_stripe_height = 64usize >> ss_y;
839+ let runit_offset = 8usize >> ss_y;
840+ let unit_h = v_end - v_start;
841+ let mut i = 0usize;
842+ while i < unit_h {
843+ let stripe_v_start = v_start + i;
844+ let frame_stripe = (stripe_v_start + runit_offset) / full_stripe_height;
845+ let nominal_h = full_stripe_height - if frame_stripe == 0 { runit_offset } else { 0 };
846+ let h = nominal_h.min(unit_h - i);
847+ let stripe_v_end = stripe_v_start + h;
848+ match filter {
849+ UnitFilter::Wiener(info) => apply_wiener_stripe(
850+ out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info,
851+ ),
852+ UnitFilter::Sgrproj(info) => apply_sgrproj_stripe(
853+ out, cdef, deblocked, stride, plane_w, plane_h, h_start, h_end, stripe_v_start, stripe_v_end, &info,
854+ ),
855+ UnitFilter::None => {}
856+ }
857+ i += h;
858+ }
859+}
860+
861+/// Applies loop restoration to one whole plane's post-CDEF samples (spec
862+/// 7.17). Walks restoration units exactly as libaom's
863+/// `foreach_rest_unit_in_plane` (`unit_size` steps, the tail folded into
864+/// the previous unit when the remainder is under `1.5*unit_size` -- the
865+/// same round-to-nearest [`count_units`] already used to size
866+/// [`RestorationGrid`]), then re-offsets internal row boundaries by
867+/// `RESTORATION_UNIT_OFFSET==8` (the first/last row of the plane keeps its
868+/// full extent). Returns a fresh copy of `cdef` with only this plane's
869+/// restoration-unit pixels replaced -- a restoration unit must never read
870+/// another, already-filtered unit's output (spec keeps a separate
871+/// destination buffer for exactly this reason), so this never filters in
872+/// place.
873+#[allow(clippy::too_many_arguments)]
874+pub(crate) fn apply_loop_restoration_plane(
875+ cdef: &[u8],
876+ deblocked: &[u8],
877+ stride: usize,
878+ plane_w: usize,
879+ plane_h: usize,
880+ ss_y: u32,
881+ ftype: RestorationType,
882+ unit_size: u32,
883+ grid: &RestorationGrid,
884+ plane: usize,
885+) -> Vec<u8> {
886+ let mut out = cdef.to_vec();
887+ if ftype == RestorationType::None || unit_size == 0 {
888+ return out;
889+ }
890+ let voffset = 8u32 >> ss_y;
891+ let ext_size = (unit_size * 3) / 2;
892+ let mut y0 = 0u32;
893+ let mut rrow = 0usize;
894+ while y0 < plane_h as u32 {
895+ let remaining_h = plane_h as u32 - y0;
896+ let uh = if remaining_h < ext_size { remaining_h } else { unit_size };
897+ let v_start = (y0 as i64 - voffset as i64).max(0) as u32;
898+ let mut v_end = y0 + uh;
899+ if v_end < plane_h as u32 {
900+ v_end -= voffset;
901+ }
902+
903+ let mut x0 = 0u32;
904+ let mut rcol = 0usize;
905+ while x0 < plane_w as u32 {
906+ let remaining_w = plane_w as u32 - x0;
907+ let uw = if remaining_w < ext_size { remaining_w } else { unit_size };
908+ let filter = grid.get(plane, rrow, rcol);
909+ if filter != UnitFilter::None {
910+ filter_restoration_unit(
911+ &mut out,
912+ cdef,
913+ deblocked,
914+ stride,
915+ plane_w,
916+ plane_h,
917+ x0 as usize,
918+ (x0 + uw) as usize,
919+ v_start as usize,
920+ v_end as usize,
921+ ss_y,
922+ filter,
923+ );
924+ }
925+ x0 += uw;
926+ rcol += 1;
927+ }
928+ y0 += uh;
929+ rrow += 1;
930+ }
931+ debug_assert_eq!(rrow, grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units");
932+ out
933+}
934+
935+#[cfg(test)]
936+mod tests {
937+ use super::*;
938+ use crate::msac::{SymbolDecoder, SymbolEncoder};
939+
940+ /// `write_primitive_quniform`, the exact inverse of [`ns_msac`] -- used
941+ /// only to build roundtrip fixtures for the decode-only helpers above
942+ /// (this decoder never writes loop restoration itself).
943+ fn write_ns(enc: &mut SymbolEncoder, n: u32, v: u32) {
944+ if n <= 1 {
945+ return;
946+ }
947+ let w = floor_log2(n) + 1;
948+ let m = (1u32 << w) - n;
949+ if v < m {
950+ enc.literal(v, w - 1);
951+ } else {
952+ enc.literal((v + m) >> 1, w - 1);
953+ enc.literal((v + m) & 1, 1);
954+ }
955+ }
956+
957+ fn write_subexp(enc: &mut SymbolEncoder, num_syms: u32, k: u32, v: u32) {
958+ let mut i = 0u32;
959+ let mut mk = 0u32;
960+ loop {
961+ let b = if i > 0 { k + i - 1 } else { k };
962+ let a = 1u32 << b;
963+ if num_syms <= mk + 3 * a {
964+ write_ns(enc, num_syms - mk, v - mk);
965+ return;
966+ }
967+ if v < mk + a {
968+ enc.literal(0, 1);
969+ enc.literal(v - mk, b);
970+ return;
971+ }
972+ enc.literal(1, 1);
973+ i += 1;
974+ mk += a;
975+ }
976+ }
977+
978+ fn recenter(r: u32, v: u32) -> u32 {
979+ if v > 2 * r {
980+ v
981+ } else if v >= r {
982+ (v - r) << 1
983+ } else {
984+ ((r - v) << 1) - 1
985+ }
986+ }
987+
988+ fn write_unsigned_subexp_with_ref(enc: &mut SymbolEncoder, n: u32, k: u32, reference: u32, v: u32) {
989+ let r = reference.clamp(0, n.saturating_sub(1));
990+ let coded = if (r << 1) <= n {
991+ recenter(r, v)
992+ } else {
993+ recenter(n - 1 - r, n - 1 - v)
994+ };
995+ write_subexp(enc, n, k, coded);
996+ }
997+
998+ /// `decode_subexp_msac`/`ns_msac` roundtrip every value in a handful of
999+ /// `(num_syms, k)` alphabets -- the shapes LR's tap ranges (`k` 1..=4,
1000+ /// `num_syms` up to 96) actually hit, per `WIENER_TAP_MAXV`-`MINV`+1 /
1001+ /// `SGRPROJ_PRJ_MAX-MIN+1`.
1002+ #[test]
1003+ fn subexp_roundtrips_every_value() {
1004+ for &(num_syms, k) in &[(16u32, 1u32), (32, 2), (64, 3), (96, 4), (128, 4), (3, 1), (1, 3)] {
1005+ for v in 0..num_syms {
1006+ let mut enc = SymbolEncoder::new();
1007+ write_subexp(&mut enc, num_syms, k, v);
1008+ let payload = enc.finish();
1009+ let mut dec = SymbolDecoder::new(&payload);
1010+ let got = decode_subexp_msac(&mut dec, num_syms, k);
1011+ assert_eq!(got, v, "num_syms={num_syms} k={k} v={v}");
1012+ }
1013+ }
1014+ }
1015+
1016+ /// The recentred, ref-relative form `read_wiener_filter`/
1017+ /// `read_sgrproj_filter` actually call -- every `(n, reference, v)`
1018+ /// combination for LR's own tap-0 range (16 values, matching
1019+ /// `WIENER_FILT_TAP0_MAXV-MINV+1`).
1020+ #[test]
1021+ fn unsigned_subexp_with_ref_roundtrips() {
1022+ let n = 16u32;
1023+ for k in 1..=4u32 {
1024+ for reference in 0..n {
1025+ for v in 0..n {
1026+ let mut enc = SymbolEncoder::new();
1027+ write_unsigned_subexp_with_ref(&mut enc, n, k, reference, v);
1028+ let payload = enc.finish();
1029+ let mut dec = SymbolDecoder::new(&payload);
1030+ let got = decode_unsigned_subexp_with_ref_msac(&mut dec, n, k, reference);
1031+ assert_eq!(got, v, "n={n} k={k} reference={reference} v={v}");
1032+ }
1033+ }
1034+ }
1035+ }
1036+
1037+ /// Signed wrapper sanity: a handful of `(low, high, k, reference, v)`
1038+ /// covering LR's actual Wiener tap-1/tap-2 and SGR `xqd0`/`xqd1` ranges.
1039+ #[test]
1040+ fn signed_subexp_with_ref_roundtrips() {
1041+ let cases: [(i32, i32, u32); 4] = [
1042+ (-5, 11, 1), // Wiener tap0
1043+ (-23, 9, 2), // Wiener tap1
1044+ (-17, 47, 3), // Wiener tap2
1045+ (-96, 32, 4), // SGR xqd0
1046+ ];
1047+ for (low, high, k) in cases {
1048+ let n = (high - low) as u32;
1049+ for reference_v in [low, low + n as i32 / 3, high - 1] {
1050+ for v in [low, low + n as i32 / 2, high - 1] {
1051+ let r = (reference_v - low).clamp(0, n as i32) as u32;
1052+ let coded_v = (v - low) as u32;
1053+ let mut enc = SymbolEncoder::new();
1054+ write_unsigned_subexp_with_ref(&mut enc, n, k, r, coded_v);
1055+ let payload = enc.finish();
1056+ let mut dec = SymbolDecoder::new(&payload);
1057+ let got = decode_signed_subexp_with_ref_msac(&mut dec, low, high, k, reference_v);
1058+ assert_eq!(got, v, "low={low} high={high} k={k} reference={reference_v} v={v}");
1059+ }
1060+ }
1061+ }
1062+ }
1063+}
crates/ec-av1/src/stream.rsmodified+229 -11
@@ -222,16 +222,15 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
222 }222 }
223 // Loop restoration carries per-restoration-unit symbols in the tile223 // Loop restoration carries per-restoration-unit symbols in the tile
224 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the224 // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
225- // superblock walk) that this decoder never reads -- same225+ // superblock walk) -- lane-lr r2 ported the reader
226- // silent-desync shape as the refusals above. Traced live 2026-08-27:226+ // (`crate::restoration`), r3 moved this refusal check to AFTER the
227- // an aomenc inter frame with `Sgrproj` on the V plane desynced the227+ // tile decode call below (was here, before it, in r2 -- meaning
228- // partition walk into out-of-alphabet garbage.228+ // `read_lr` was NEVER actually reached through `decode_stream`, the
229- if header.loop_restoration.uses_lr {229+ // gap the r3 gate caught live: 40/40 attempts hit this refusal with
230- return Err(Error::unsupported(230+ // zero `read_lr_unit` hits). Checking post-decode instead proves the
231- "AV1 decode_stream",231+ // superblock walk actually survived `read_lr` (no desync) before
232- "a frame with loop restoration enabled (this decoder never reads the per-unit lr symbols)",232+ // refusing on the true remaining gap: decoded Wiener/SGR filters are
233- ));233+ // stored per unit but never applied to pixels.
234- }
235 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec234 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
236 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`235 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
237 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the236 // 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<Vec<Picture>> {
429 enable_edge_filter,428 enable_edge_filter,
430 &header.cdef,429 &header.cdef,
431 &header.loop_filter,430 &header.loop_filter,
431+ &header.loop_restoration,
432 initial_cdfs,432 initial_cdfs,
433 header.tx_mode == TxMode::Select,433 header.tx_mode == TxMode::Select,
434 header.reduced_tx_set,434 header.reduced_tx_set,
@@ -516,6 +516,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
516 other_refs,516 other_refs,
517 &header.cdef,517 &header.cdef,
518 &header.loop_filter,518 &header.loop_filter,
519+ &header.loop_restoration,
519 initial_cdfs,520 initial_cdfs,
520 header.allow_high_precision_mv,521 header.allow_high_precision_mv,
521 header.force_integer_mv,522 header.force_integer_mv,
@@ -540,6 +541,9 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
540 header.delta,541 header.delta,
541 )?542 )?
542 };543 };
544+ // lane-lr r4: the Wiener/self-guided pixel filters are wired
545+ // (`decode.rs::apply_loop_restoration`) -- no more refusal here,
546+ // `uses_lr` frames now decode all the way to pixels.
543 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's547 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
544 // *initial* table into the slots it refreshes, not the adapted548 // *initial* table into the slots it refreshes, not the adapted
545 // end-of-tile one.549 // end-of-tile one.
@@ -5373,6 +5377,218 @@ mod tests {
5373 );5377 );
5374 }5378 }
5375 5379
5380+
5381+ /// lane-lr r3: proves stage 1/2's exit criterion -- a real
5382+ /// `--enable-restoration=1` aomenc stream must survive the whole
5383+ /// partition walk (every symbol read entropy-exact) and land on the
5384+ /// NEW, narrowed refusal ("read but not applied"), never desync into
5385+ /// some other named refusal or an outright decode panic. Multi-superblock
5386+ /// fixture (192x128 = 3x2 SBs of 64px) per the charter's own trap
5387+ /// warning -- a single-SB fixture can never re-enter `read_lr` a second
5388+ /// time and would leave `SWITCHABLE_HITS`/etc. proving only one call
5389+ /// site, not the per-SB loop.
5390+ #[test]
5391+ fn a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly() {
5392+ const NAME: &str = "a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly";
5393+ let _gate_lock = lock_gate_counters();
5394+ if !have_ffmpeg() {
5395+ eprintln!("SKIP {NAME}: no ffmpeg");
5396+ return;
5397+ }
5398+ if !have_aomenc() {
5399+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5400+ return;
5401+ }
5402+ let (width, height) = (192usize, 128usize);
5403+ let n_attempts: u32 = std::env::var("EC_LR_GATE_ATTEMPTS")
5404+ .ok()
5405+ .and_then(|s| s.parse().ok())
5406+ .unwrap_or(40);
5407+ let mut lr_refusals = 0u32;
5408+ let mut other_refusals = Vec::new();
5409+ for attempt in 0..n_attempts {
5410+ let seed = 42 + attempt;
5411+ let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
5412+ let y4m = Command::new("ffmpeg")
5413+ .args(["-v", "error", "-f", "lavfi", "-i"])
5414+ .arg(&source)
5415+ .args(["-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-"])
5416+ .stdin(Stdio::null())
5417+ .stdout(Stdio::piped())
5418+ .stderr(Stdio::piped())
5419+ .output()
5420+ .expect("ffmpeg failed to run");
5421+ assert!(
5422+ y4m.status.success(),
5423+ "ffmpeg fixture: {}",
5424+ String::from_utf8_lossy(&y4m.stderr)
5425+ );
5426+ let mut child = Command::new(aomenc_path())
5427+ .args([
5428+ "--codec=av1",
5429+ "--passes=1",
5430+ "--end-usage=q",
5431+ // r3: a low cq-level (high quality/bitrate) is load-bearing --
5432+ // sampled live (2026-08-30) that aomenc's RD only ever picks a
5433+ // non-`RESTORE_NONE` frame_restoration_type at cq-level<=20 for
5434+ // this fixture; cq-level=45 (this gate's sibling gates' usual
5435+ // value) landed `uses_lr=false` on every attempt.
5436+ "--cq-level=15",
5437+ "--cpu-used=0",
5438+ "--threads=1",
5439+ "--row-mt=0",
5440+ // r3: this decoder always assumes 64px superblocks
5441+ // (`decode.rs` hardcodes `SB_MI=16`, ledger `lane-sb128`
5442+ // dead-ends) -- force aomenc to match rather than risk
5443+ // the unrelated sb128 gap eating this gate's own window.
5444+ "--sb-size=64",
5445+ "--enable-restoration=1",
5446+ "--enable-cdef=0",
5447+ "--enable-rect-partitions=0",
5448+ "--enable-ab-partitions=0",
5449+ "--enable-1to4-partitions=0",
5450+ "--enable-filter-intra=0",
5451+ "--enable-smooth-intra=0",
5452+ "--enable-paeth-intra=0",
5453+ "--enable-tx-size-search=0",
5454+ "--max-partition-size=32",
5455+ "--min-partition-size=16",
5456+ "--enable-palette=0",
5457+ "--enable-intrabc=0",
5458+ "--enable-cfl-intra=0",
5459+ "--enable-ref-frame-mvs=0",
5460+ "--enable-warped-motion=0",
5461+ "--enable-global-motion=0",
5462+ "--enable-masked-comp=0",
5463+ "--enable-interintra-comp=0",
5464+ "--enable-obmc=0",
5465+ "--obu",
5466+ "-o",
5467+ "-",
5468+ "-",
5469+ ])
5470+ .stdin(Stdio::piped())
5471+ .stdout(Stdio::piped())
5472+ .stderr(Stdio::piped())
5473+ .spawn()
5474+ .expect("aomenc failed to start");
5475+ child
5476+ .stdin
5477+ .take()
5478+ .expect("aomenc stdin")
5479+ .write_all(&y4m.stdout)
5480+ .expect("writing y4m to aomenc");
5481+ let out = child.wait_with_output().expect("aomenc failed to run");
5482+ assert!(
5483+ out.status.success(),
5484+ "aomenc refused the fixture: {}",
5485+ String::from_utf8_lossy(&out.stderr)
5486+ );
5487+ let stream = out.stdout;
5488+ match decode_stream(&stream) {
5489+ Ok(pics) => {
5490+ // r4: the pixel filters are wired -- every `uses_lr`
5491+ // frame must now decode Ok AND match an independent
5492+ // decoder pixel-exact, not just refuse cleanly.
5493+ let reference = ffmpeg_decode_sequence(&stream, width, height, pics.len());
5494+ let mismatched = pics
5495+ .iter()
5496+ .zip(&reference)
5497+ .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
5498+ // r7: pin a mismatching stream the same way the
5499+ // masked-compound gate does -- lets a follow-up round
5500+ // decode this exact seed's bytes directly instead of
5501+ // re-deriving them from a live 40-attempt sweep.
5502+ if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
5503+ std::fs::write(&path, &stream).expect("writing pinned stream");
5504+ eprintln!(
5505+ "EC_AV1_GATE_DUMP: wrote mismatching LR stream (seed {seed}) to {path}"
5506+ );
5507+ }
5508+ for (i, (pic, refpic)) in pics.iter().zip(reference.iter()).enumerate() {
5509+ assert_eq!(pic.y, refpic.y, "{NAME}: luma mismatch (seed {seed} frame {i})");
5510+ assert_eq!(pic.u, refpic.u, "{NAME}: U mismatch (seed {seed} frame {i})");
5511+ assert_eq!(pic.v, refpic.v, "{NAME}: V mismatch (seed {seed} frame {i})");
5512+ }
5513+ lr_refusals += 1; // reused below as "attempts that actually exercised LR pixels"
5514+ }
5515+ Err(e) => {
5516+ let msg = e.to_string();
5517+ other_refusals.push(format!("seed {seed}: {msg}"));
5518+ }
5519+ }
5520+ }
5521+ assert!(
5522+ other_refusals.is_empty(),
5523+ "{NAME}: {} attempts failed outright instead of decoding:\n{}",
5524+ other_refusals.len(),
5525+ other_refusals.join("\n")
5526+ );
5527+ assert!(
5528+ lr_refusals > 0,
5529+ "{NAME}: no attempt ever decoded pixel-exact ({n_attempts} attempts)"
5530+ );
5531+ // Any real (non-`RESTORE_NONE`) filter kind is acceptable proof --
5532+ // aomenc's RD picks the frame-level `restoration_type` itself (not
5533+ // always `Switchable`; observed `Sgrproj` live at cq-level=15 for
5534+ // this fixture), so hard-requiring one specific arm would be the
5535+ // gate-recipe-confound class (ledger).
5536+ let total_hits = crate::restoration::wiener_hits()
5537+ + crate::restoration::sgrproj_hits()
5538+ + crate::restoration::switchable_hits();
5539+ assert!(
5540+ total_hits > 0,
5541+ "{NAME}: {lr_refusals} LR refusals fired but read_lr_unit never decoded a real \
5542+ (non-None) filter -- gate proved nothing about the symbol path"
5543+ );
5544+ eprintln!(
5545+ "{NAME}: {lr_refusals} LR refusals, {} other refusals out of {n_attempts}, \
5546+ wiener_hits={} sgrproj_hits={} switchable_hits={}",
5547+ other_refusals.len(),
5548+ crate::restoration::wiener_hits(),
5549+ crate::restoration::sgrproj_hits(),
5550+ crate::restoration::switchable_hits()
5551+ );
5552+ }
5553+
5554+ /// r8: decode the ONE pinned stream `EC_AV1_GATE_DUMP` captured in r7
5555+ /// (`fixtures/lr-sgr-r7.obu`, seed 46) directly -- not the live
5556+ /// 40-attempt sweep, which reuses `v_start` coordinates across unrelated
5557+ /// seeds/frames and made r6's captured 9 bytes unprovable. Run with
5558+ /// `EC_LR_CALL_DUMP=1` set (see `restoration.rs`'s `apply_sgrproj_stripe`)
5559+ /// to get the real window on stderr, call-uniquely keyed to `xqd ==
5560+ /// [-16,-32]` rather than any coordinate.
5561+ #[test]
5562+ #[ignore = "reads a pinned fixture under the gitignored fixtures dir; run manually with EC_LR_CALL_DUMP=1"]
5563+ fn pinned_lr_sgr_stream_call_unique_dump() {
5564+ let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/lr-sgr-r7.obu");
5565+ let stream = std::fs::read(path).expect("reading pinned lr-sgr-r7.obu");
5566+ let pics = decode_stream(&stream).expect("pinned lr-sgr-r7.obu must decode");
5567+ if have_ffmpeg() {
5568+ let reference = ffmpeg_decode_sequence(&stream, 192, 128, pics.len());
5569+ for (i, (got, want)) in pics.iter().zip(&reference).enumerate() {
5570+ let y_mismatch = got.y != want.y;
5571+ let u_mismatch = got.u != want.u;
5572+ let v_mismatch = got.v != want.v;
5573+ eprintln!(
5574+ "frame {i}: y_mismatch={y_mismatch} u_mismatch={u_mismatch} v_mismatch={v_mismatch}"
5575+ );
5576+ if y_mismatch {
5577+ let n = got.y.iter().zip(&want.y).filter(|(a, b)| a != b).count();
5578+ eprintln!(" {n} luma bytes differ / {}", got.y.len());
5579+ }
5580+ if v_mismatch {
5581+ let w = 96usize; // chroma plane width (192/2)
5582+ for (idx, (a, b)) in got.v.iter().zip(&want.v).enumerate() {
5583+ if a != b {
5584+ eprintln!(" V[{},{}] got={a} want={b}", idx / w, idx % w);
5585+ }
5586+ }
5587+ }
5588+ }
5589+ }
5590+ }
5591+
5376 /// lane-realworld r2: `read_cdef` (spec 5.11.56) ported -- per-superblock5592 /// lane-realworld r2: `read_cdef` (spec 5.11.56) ported -- per-superblock
5377 /// `cdef_idx`, wired at all five `skip`-decode sites, `apply_cdef` looks5593 /// `cdef_idx`, wired at all five `skip`-decode sites, `apply_cdef` looks
5378 /// up strength through the grid instead of a hardcoded `[0]`. Structure5594 /// up strength through the grid instead of a hardcoded `[0]`. Structure
@@ -5569,7 +5785,6 @@ mod tests {
5569 crate::decode::cdef_idx_hits()5785 crate::decode::cdef_idx_hits()
5570 );5786 );
5571 }5787 }
5572-
5573 /// Pinned streams captured by `EC_AV1_GATE_DUMP` off5788 /// Pinned streams captured by `EC_AV1_GATE_DUMP` off
5574 /// `a_real_aomenc_stream_with_warped_motion_refuses_or_matches` -- each5789 /// `a_real_aomenc_stream_with_warped_motion_refuses_or_matches` -- each
5575 /// one is a former mismatch, kept as a regression pin (warp-mismatch:5790 /// one is a former mismatch, kept as a regression pin (warp-mismatch:
@@ -6584,6 +6799,7 @@ mod tests {
6584 enable_edge_filter,6799 enable_edge_filter,
6585 &header.cdef,6800 &header.cdef,
6586 &header.loop_filter,6801 &header.loop_filter,
6802+ &header.loop_restoration,
6587 None,6803 None,
6588 header.tx_mode == TxMode::Select,6804 header.tx_mode == TxMode::Select,
6589 header.reduced_tx_set,6805 header.reduced_tx_set,
@@ -6790,6 +7006,7 @@ mod tests {
6790 enable_edge_filter,7006 enable_edge_filter,
6791 &header.cdef,7007 &header.cdef,
6792 &header.loop_filter,7008 &header.loop_filter,
7009+ &header.loop_restoration,
6793 None,7010 None,
6794 header.tx_mode == TxMode::Select,7011 header.tx_mode == TxMode::Select,
6795 header.reduced_tx_set,7012 header.reduced_tx_set,
@@ -7104,6 +7321,7 @@ mod tests {
7104 enable_edge_filter,7321 enable_edge_filter,
7105 &header.cdef,7322 &header.cdef,
7106 &header.loop_filter,7323 &header.loop_filter,
7324+ &header.loop_restoration,
7107 None,7325 None,
7108 header.tx_mode == TxMode::Select,7326 header.tx_mode == TxMode::Select,
7109 header.reduced_tx_set,7327 header.reduced_tx_set,
lanes/lr-r2.charter.mdadded+85 -0
@@ -0,0 +1,85 @@
1+# lane-lr r2 — read_lr wiring, then the two filters
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-lr`, branch `lane-lr`,
4+at 4d7ae64.
5+
6+## Read these two files first, then start writing code
7+- `lanes/lr.report.md` — r1's complete design writeup. Its "Next lever" section
8+ has every formula and `file:line` you need. Do NOT re-derive what it already
9+ contains (class `worker-cap-spent-reading`).
10+- `lanes/lr.charter.md` — the original charter: staging, gate rules, hard rules.
11+ Still binding.
12+
13+## What r1 landed (both committed, suite confirmed green 232/0 on this tree)
14+- `crates/ec-av1/src/cdf.rs`: `RESTORE_WIENER = [11570, 32768, 0]`,
15+ `RESTORE_SGRPROJ = [16855, 32768, 0]`,
16+ `RESTORE_SWITCHABLE = [9413, 22581, 32768, 0]` — copied from libaom
17+ `entropymode.c` `default_{wiener,sgrproj,switchable}_restore_cdf` and
18+ converted to this codebase's `[a0, (a1,) 32768, 0]` convention, checked
19+ against `INTRABC`'s own `AOM_CDF2(30531) -> [30531, 32768, 0]`.
20+- `crates/ec-av1/src/cdf_state.rs`: the three tables wired into `Cdfs` —
21+ fields, `new()` defaults, `reset_counts` via `reset1` — following `intrabc`.
22+- Nothing reads them from the bitstream yet; the whole-frame refusal at
23+ `crates/ec-av1/src/stream.rs:195-198` is unchanged.
24+
25+## r1's decisive facts, so you do not re-find them
26+- `restoration.c:1277` `av1_loop_restoration_corners_in_sb` returns 0 unless
27+ `bsize == sb_size`, so "read LR once per superblock" is spec-exact here, not
28+ a simplification — every restoration unit is >= 64px.
29+- `msac.rs:348` `SymbolDecoder::literal(bits)` is the `L(n)` primitive LR's
30+ subexp reads need. The existing `decode_subexp` /
31+ `decode_unsigned_subexp_with_ref` / `decode_signed_subexp_with_ref` /
32+ `inverse_recenter` at `ec-av1-syntax/src/frame.rs:1797-1848` are
33+ `BitReader`-only (uncompressed frame header) — LR needs a SECOND,
34+ msac-flavoured port, not reuse.
35+- Threading point: `decode_key_frame_tile_with_cdfs` (decode.rs:4478) and
36+ `decode_inter_frame_tile_with_cdfs` (decode.rs:9088) already take long
37+ positional argument lists including cdef and loop_filter. Add
38+ `&LoopRestorationParams` there and pass `&LoopRestorationParams::default()`
39+ from the public wrappers (`decode_key_frame_tile:4435`,
40+ `decode_inter_frame_tile:9030`) — that keeps ~10 test call sites untouched.
41+- Wiener tap ranges `(-5, 10, k1)` `(-23, 8, k2)` `(-17, 46, k3)`;
42+ SGR ranges `(-96, 31, k4)` `(-32, 95, k4)`. `av1_sgr_params` is in libaom
43+ `restoration.c`.
44+
45+## Order of work — COMMIT AFTER EVERY GREEN MILESTONE
46+1. Port the msac-flavoured subexp/recenter helpers with their own unit tests
47+ pinned against known values. COMMIT.
48+2. `read_lr` / `read_lr_unit` called once per superblock before
49+ `decode_partition` at decode.rs ~4547 (key frame) and ~9275 (inter), with
50+ the per-plane unit-grid formula from the report. The frame still refuses,
51+ by a NEW and accurate name ("loop restoration symbols are read but the
52+ filters are not applied"). The proof this stage works: a stream that used to
53+ desync the partition walk into out-of-alphabet garbage now walks its
54+ partitions cleanly and fails only the pixel compare. COMMIT.
55+3. Wiener filter, incl. the 3-pixel stripe boundary save/restore (libaom's
56+ `rlbs`) — that boundary handling is the classic trap. COMMIT.
57+4. Self-guided, incl. the box-sum radii and `av1_sgr_params`. COMMIT.
58+5. Switchable; remove the last refusal; the gate asserts Ok, never an Err.
59+ COMMIT.
60+
61+## Gate rules (mandatory, unchanged from r1's charter)
62+`EC_AV1_REQUIRE_AOMENC=1` on every test run; `-t <seconds>` on every ffmpeg
63+generate; fixtures through the existing `gradients_source(seed, w, h, tail)`
64+helper (ffmpeg's `gradients` ignores its own seed); aomenc
65+`--threads=1 --row-mt=0 --enable-restoration=1`; a HARD-asserted firing count
66+via a thread-local `Cell<usize>` counter matching the existing `*_HITS`
67+(thread-local, NOT atomics). A gate that cannot prove LR fired is vacuous.
68+
69+Note: main now carries a `gate_coverage` guard that derives, from the gate
70+source, which aomenc tools are switched off in all 20 gates and on in none.
71+`enable-restoration` is one gate short of that list today; your gate enabling it
72+is exactly the right outcome.
73+
74+## Hard rules
75+- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`. Foreground builds,
76+ `nice -n 19 cargo ... -j4`. The suite takes ~4 minutes on this tree — give
77+ any `cargo test` call a timeout of at least 600000 ms; do not let a 120 s
78+ default kill it and then background it unpolled, as r1 did.
79+- Sibling worktrees (edith_codecs, -chroma, -realworld, -superres, -tiles) have
80+ live agents. Never build in or edit them.
81+- Baseline to hold: 232 passed / 0 failed on this tree (main is at 234 with two
82+ new guard tests you will inherit at merge).
83+- NEVER push, never merge, never touch `main`. Commit on `lane-lr` only.
84+- 75-turn cap: commit at every green step; near the cap, commit whatever
85+ compiles as `wip(av1): ...` and update `lanes/lr.report.md`.
lanes/lr-r3.charter.mdadded+63 -0
@@ -0,0 +1,63 @@
1+# lane-lr r3 — gate the symbols, then apply the filters
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-lr`, branch `lane-lr`.
4+Read ONLY the r2 section of `lanes/lr.report.md` — it is a typing plan, not a
5+re-derivation task. Do not re-read libaom for what it already records
6+(class `worker-cap-spent-reading`).
7+
8+## State — the symbols are read
9+r2 landed and verified (suite 235 passed / 0 failed, 181 s — 232 baseline plus
10+three new pinned roundtrip tests):
11+- `crates/ec-av1/src/restoration.rs` (new): the msac-flavoured subexp/recenter
12+ port (`decode_subexp_msac`, `decode_unsigned_subexp_with_ref_msac`,
13+ `decode_signed_subexp_with_ref_msac`, `ns_msac`), `WienerInfo` / `SgrprojInfo`
14+ / `UnitFilter`, the `SGR_PARAMS` table, `read_wiener_filter` /
15+ `read_sgrproj_filter` / `read_lr_unit` / `read_lr`, and `RestorationGrid`.
16+- `decode.rs`: both tile functions take `lr: &LoopRestorationParams` and call
17+ `read_lr` once per superblock before `decode_partition`; the public wrappers
18+ pass `&LoopRestorationParams::default()`.
19+- `stream.rs`: both call sites thread `&header.loop_restoration`; the refusal
20+ now names the true remaining gap ("symbols read, filters not applied").
21+
22+## Order — COMMIT AFTER EVERY GREEN STEP
23+1. **The gate that proves stage 2 actually worked.** A real aomenc
24+ `--enable-restoration=1` stream must survive the partition walk and fail
25+ only on the new refusal — before this, "the symbols are read correctly" is
26+ unproven. Hard-assert a firing count with a thread-local `Cell<usize>` in
27+ `restoration.rs`'s `read_lr_unit`. Remember the shape of the trap r2's
28+ sibling lane hit: a per-superblock symbol needs a fixture with more than one
29+ superblock, or it can never fire. COMMIT.
30+2. **Wiener.** A new `apply_loop_restoration` pass after `apply_cdef` in
31+ `decode.rs`, driven by `RestorationGrid`. The 3-pixel stripe boundary
32+ save/restore (libaom's `rlbs`) is the classic trap — 64-row stripes, and the
33+ filter reads rows the next stripe has already overwritten unless you save
34+ them. COMMIT.
35+3. **Self-guided**, incl. the box-sum radii and `SGR_PARAMS`. COMMIT.
36+4. **Switchable**; drop the stream.rs refusal; the gate asserts Ok, never an Err.
37+ COMMIT.
38+
39+Ordering fact a sibling lane established, which you need for step 2: libaom's
40+`decodeframe.c` calls `superres_post_decode()` BETWEEN `av1_cdef_frame` and
41+`av1_loop_restoration_filter_frame` — **superres runs before loop restoration**.
42+Not load-bearing while superres is refused here, but get the order right now.
43+
44+## Gate rules
45+`EC_AV1_REQUIRE_AOMENC=1` on every run (a missing oracle must FAIL, not SKIP);
46+`-t <seconds>` on every ffmpeg generate; fixtures through
47+`gradients_source(seed, w, h, tail)`; aomenc
48+`--threads=1 --row-mt=0 --enable-restoration=1`; firing counts are HARD asserts.
49+
50+## Note for the merge
51+Main carries two guards you do not have: `gate_coverage.rs` (pins the aomenc
52+tools no gate exercises — `enable-restoration` is one gate away from that list)
53+and `refusal_inventory.rs` (pins every decode-path refusal string, so adding or
54+renaming one fails until the list is updated — and r2 RENAMED the LR refusal).
55+Report the refusal strings you add, rename or remove, verbatim.
56+
57+## Hard rules
58+`export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground builds
59+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms (the suite
60+runs ~3 min). Sibling worktrees (edith_codecs, -chroma, -realworld, -superres,
61+-tiles, -palette) have live agents — never build in or edit them. Never push,
62+never merge, never touch `main`. 75-turn cap, does not reset: commit at every
63+green step. Update `lanes/lr.report.md` with an r3 section, VERDICT first.
lanes/lr-r4.charter.mdadded+46 -0
@@ -0,0 +1,46 @@
1+# lane-lr r4 — the Wiener and self-guided filters
2+
3+At ebac7a0. Read `lanes/lr.report.md`'s r3 section only.
4+
5+## State — the symbols are read AND proven
6+r3's gate `a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly`
7+runs a real `--enable-restoration=1` stream: 39/40 attempts reach the LR
8+refusal with zero other refusals, `wiener_hits=19`, `sgrproj_hits=72`.
9+`RestorationGrid` and the per-plane `(WienerInfo, SgrprojInfo)` are populated
10+correctly. Suite 236/0.
11+
12+r3 also found and fixed a real bug r2's report had claimed away: the `uses_lr`
13+refusal ran BEFORE the tile decode, so `read_lr` was never invoked through
14+`decode_stream` at all — 40/40 attempts had zero `read_lr_unit` hits until the
15+check moved after the tile decode.
16+
17+Two gate facts r3 paid for: `--enable-restoration=1` only actually lands
18+`uses_lr = true` on this fixture at `cq-level <= 20` (the sibling gates' usual
19+45 never fires it), and `--sb-size=64` is required or aomenc's default 128px
20+superblock lands in a dead-ended partition gap and eats the attempt window.
21+And a dead end: do NOT hard-require `switchable_hits() > 0` — aomenc's RD may
22+pick a frame-level fixed Wiener or Sgrproj type instead. Assert the SUM.
23+
24+## Your job
25+1. **Wiener.** `apply_loop_restoration` after `apply_cdef` in `decode.rs` (two
26+ call sites, ~4983 key-frame and ~10502 inter-frame), driven by
27+ `RestorationGrid`. The 3-pixel stripe boundary save/restore (libaom's
28+ `rlbs`) is the trap: 64-row stripes, and the filter reads rows the next
29+ stripe has already overwritten unless you save them first. COMMIT.
30+2. **Self-guided**, incl. the box-sum radii and `SGR_PARAMS`. COMMIT.
31+3. Widen r3's gate to assert `Ok` and pixel-exactness instead of the named
32+ refusal, then drop the `stream.rs` refusal. COMMIT.
33+
34+Ordering fact from a sibling lane: libaom runs `superres_post_decode()` between
35+`av1_cdef_frame` and `av1_loop_restoration_filter_frame` — superres before LR.
36+
37+Merge note: main is at 06d29ee with `gate_coverage.rs` (pins the aomenc tools no
38+gate exercises — `enable-restoration` is one gate from that list) and
39+`refusal_inventory.rs` (pins every decode-path refusal string). Report every
40+refusal string you add, rename or remove, verbatim.
41+
42+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground
43+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling
44+worktrees have live agents — never build in or edit them. Never push, never
45+merge, never touch `main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN
46+STEP. Update `lanes/lr.report.md` with an r4 section, VERDICT first.
lanes/lr-r5.charter.mdadded+35 -0
@@ -0,0 +1,35 @@
1+# lane-lr r5 — finish Wiener, then self-guided
2+
3+At 06ba9af — r4's Wiener work, committed verbatim by the orchestrator at its cap
4+and **never seen to compile**. `lanes/lr-r4.charter.md` is still binding; read it
5+and the r3 section of `lanes/lr.report.md`.
6+
7+1. `cargo check`, fix whatever r4 left mid-edit, then the full suite
8+ (baseline 236/0 on this tree). Getting 06ba9af green is the whole job until
9+ it is green. COMMIT.
10+2. Finish Wiener: `apply_loop_restoration` after `apply_cdef` in `decode.rs`
11+ (two call sites, key-frame and inter-frame), driven by `RestorationGrid`.
12+ The 3-pixel stripe boundary save/restore (libaom's `rlbs`) is the trap:
13+ 64-row stripes, and the filter reads rows the next stripe has already
14+ overwritten unless you save them first. COMMIT.
15+3. Self-guided, incl. the box-sum radii and `SGR_PARAMS`. COMMIT.
16+4. Widen the r3 gate to assert `Ok` and pixel-exactness instead of the named
17+ refusal, then drop the `stream.rs` refusal. COMMIT.
18+
19+Facts already paid for: the symbols are read and gate-proven
20+(`wiener_hits=19`, `sgrproj_hits=72` on a real stream); `--enable-restoration=1`
21+only lands `uses_lr` at `cq-level <= 20`; `--sb-size=64` is required or aomenc's
22+default 128px superblock lands in a dead-ended partition gap; do NOT
23+hard-require `switchable_hits() > 0` — assert the SUM of the three arms, since
24+aomenc's RD may pick a frame-level fixed type. Ordering: libaom runs superres
25+between CDEF and loop restoration.
26+
27+Merge note: main is at 53b319b with `gate_coverage.rs` (pins the aomenc tools no
28+gate exercises) and `refusal_inventory.rs` (pins every decode-path refusal
29+string). Report every refusal string you add, rename or remove, verbatim.
30+
31+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground
32+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling
33+worktrees have live agents — never build in or edit them. Never push, never
34+merge, never touch `main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN
35+STEP. Update `lanes/lr.report.md` with an r5 section, VERDICT first.
lanes/lr-r6.charter.mdadded+63 -0
@@ -0,0 +1,63 @@
1+# lane-lr r6 — one pixel
2+
3+At 0f36e31. Read the r5 section of `lanes/lr.report.md`.
4+
5+**Correction to the r5 charter, on the record:** it said HEAD had "never been
6+seen to compile". That was the orchestrator's inference from a cap-time commit,
7+and it was wrong — r4's work compiles clean and all four charter steps
8+(Wiener + self-guided at both call sites, the gate widened to assert `Ok` and
9+pixel-exactness, the `stream.rs` refusal dropped) are genuinely finished. r5
10+spent its round diagnosing instead, which was the right call.
11+
12+## The defect
13+`a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly` fails
14+deterministically — reproduced identically on every rerun, not a flake:
15+**one pixel of 6144**, V plane, row 61 col 6, ours 195 vs ffmpeg 194. Seed 46,
16+filter `Sgrproj { ep: 6, xqd: [-16, -32] }`, inside chroma's last partial
17+restoration stripe [60, 64) of a 64px plane. Y and U are bit-exact on every
18+attempt; only this one (plane, pixel, filter) combination diverges.
19+
20+## Ruled out by r5, do not redo (class `worker-cap-spent-reading`)
21+- The stripe-boundary substitution (`lr_sample`), hand-verified line-by-line
22+ against libaom's `setup_processing_stripe_boundary` /
23+ `save_deblock_boundary_lines` for the failing stripe. Matches exactly.
24+- The dense (`r1 = 1`) SGR arm's A/B grid values and final combine, dumped live
25+ and independently recomputed in Python from the real cdef/deblocked bytes.
26+ Correct.
27+- Standalone C reimplementations of the box filter (`/tmp/lr_ref.c`,
28+ `/tmp/lr_probe.c`) produced mutually inconsistent numbers across runs of
29+ identical code. Do not trust them or their 194-vs-195 claim; they are not
30+ evidence. If you want C ground truth, call libaom's own exported function
31+ through a harness linked against `~/.cache/aom-oracle/build/libaom.a`, the way
32+ `scripts/superres-pin-harness.c` does — that is the pattern that works here.
33+
34+## Start here
35+The fast (`r0 = 2`) arm's individual neighbour A/B reads at (row 61, col 6),
36+which r5 ran out of budget to instrument the same way it did the dense arm.
37+If that also checks out, go upstream to the V-plane CDEF/deblock pixel data
38+feeding the stripe.
39+
40+Sibling lanes built oracle rungs you can use: `EC_AV1_POSTDEBLOCK_DUMP` and
41+`EC_AV1_PREFILT_WIDE_DUMP` (in `scripts/instrument-aom-oracle.sh`, aomdec
42+already rebuilt on this box) give libaom's own post-deblock and wide pre-filter
43+buffers — exactly the upstream check above, without hand-tracing. Note also that
44+this is a partial stripe at a plane edge and a 1-LSB divergence: rounding in the
45+partial-stripe height or an edge-clamped neighbour is the shape to suspect.
46+
47+## Then
48+Once green: COMMIT immediately. Then remove any remaining LR refusal, confirm
49+`gate_coverage.rs`'s `NEVER_EXERCISED` no longer needs `enable-restoration`
50+(main's copy — you may not have the file), and write the r6 report.
51+
52+Merge note: main is at 53f5358 and has moved (multi-tile key frames, chroma
53+smooth/paeth, CDEF index reads, three reworded refusals, and
54+`refusal_inventory.rs` which pins every decode-path refusal string). Consider
55+`git merge main` here and resolving it yourself before the branch is merged
56+back — you know which side owns each hunk. Report every refusal string you add,
57+rename or remove, verbatim.
58+
59+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground
60+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling
61+worktrees have live agents — never build in or edit them. Never push, never
62+merge into `main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP.
63+Update `lanes/lr.report.md` with an r6 section, VERDICT first.
lanes/lr-r7.charter.mdadded+55 -0
@@ -0,0 +1,55 @@
1+# lane-lr r7 — one tap
2+
3+At e5ad671 (+ this charter). Read the r6 section of `lanes/lr.report.md`.
4+
5+## Where you stand — the search is down to one number
6+r6 linked libaom's real `av1_apply_selfguided_restoration_c` out of
7+`~/.cache/aom-oracle/build/libaom.a` and called it directly on OUR OWN
8+`lr_sample`-substituted bytes. It reproduced 194. That decisively rules out
9+`lr_sample` and the stripe boundary — r5's suspicion — and it rules out the
10+fast (`r0`) arm, whose `flt0` is bit-exact against real libaom.
11+
12+What is left: the dense (`r1`) arm. Eight of its nine A/B taps at the failing
13+pixel match a from-scratch box-sum of the real bytes; the combined `flt1` is
14+**3110 where libaom gets 3109**. One tap, or a rounding mode.
15+
16+r6's harness is now committed at `scripts/lr-sgr-pin-harness.c` — it lived in
17+the scratchpad, which this box reaps (class `oracle-in-reaped-dir`). Use and
18+extend it.
19+
20+## Do not
21+- Re-suspect `lr_sample` or the stripe boundary. Proven correct.
22+- Re-suspect the fast arm. Proven bit-exact.
23+- Hand-trace further. Three rounds have now shown our arithmetic is
24+ self-consistent with our own output; only libaom's own intermediate values
25+ can break the tie.
26+
27+## Do
28+r6 named the two ways to get per-tap ground truth, and preferred the first:
29+1. `calculate_intermediate_result` and `boxsum1` are `static` in libaom's
30+ `restoration.c`, so they cannot be called from the harness as-is. Patch them
31+ non-static in the oracle copy and rebuild (~5 min) — the same pattern
32+ `scripts/instrument-aom-oracle.sh` already uses for the trace rungs, so add
33+ it there as an env-gated rung rather than an ad-hoc edit, and it stays
34+ reusable.
35+2. Or bisect single input pixels through the existing harness until the tap
36+ that diverges identifies itself.
37+
38+Then fix it, get the gate green, COMMIT immediately.
39+
40+## Then
41+Wiener and self-guided are otherwise feature-complete with the refusal already
42+dropped, so once green this lane is ready to merge. Before it does: confirm
43+`gate_coverage.rs`'s `NEVER_EXERCISED` no longer needs `enable-restoration`
44+(main's copy — down to `enable-intrabc` alone as of this batch), and consider
45+`git merge main` here first and resolving it yourself; main is at 93d9510 and
46+has landed multi-tile decode, CDEF index reads, chroma modes, a `bit_depth != 8`
47+refusal and three reworded partition refusals since this branch forked. Report
48+every refusal string you add, rename or remove, verbatim.
49+
50+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground
51+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling
52+worktrees have live agents — never build in or edit them. Never push, never
53+merge into `main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP, and
54+commit any harness or instrument you build — a scratchpad is not storage.
55+Update `lanes/lr.report.md` with an r7 section, VERDICT first.
lanes/lr-r8.charter.mdadded+48 -0
@@ -0,0 +1,48 @@
1+# lane-lr r8 — one call, not forty
2+
3+At 1c122a2. Read the r7 section of `lanes/lr.report.md` first.
4+
5+r7's real result is a RETRACTION, and it is the most useful thing in the lane:
6+r6's recorded divergence — dense-arm "u" tap (A,B) = (254,303) vs our 3110 —
7+**could not be reproduced**. Compiled libaom's own `calculate_intermediate_result`
8+(now exported by rung 6 of `scripts/instrument-aom-oracle.sh`) gives (253,454) at
9+that pixel; our `compute_ab`/`lr_sample` live-trace reads the correct raw bytes
10+(111/154/194); and an independent Python replica of the box-sum formula fed those
11+bytes reproduces libaom's (253,454) exactly. So `lr_sample`, the box-sum formula
12+and the fast arm are all reconfirmed correct — **do not re-suspect any of them.**
13+
14+The reason r6's number was wrong is the round's real finding: its dump matched on
15+a COORDINATE (`v_start == 60`) that is not unique across the gate's 5-attempt
16+sweep, so the nine bytes it captured are not provably from the failing call.
17+A measurement that cannot name which call produced it is not evidence.
18+
19+## The job
20+1. Decode the ONE pinned stream, not the sweep: `fixtures/lr-sgr-r7.obu` is
21+ seed-46's mismatching stream (gitignored, worktree-local; regenerate with
22+ `EC_AV1_GATE_DUMP=fixtures/lr-sgr-r7.obu EC_LR_GATE_ATTEMPTS=10` if lost).
23+ `EC_AV1_GATE_DUMP` is already wired into the gate (`stream.rs` ~4791).
24+2. Re-add a debug dump keyed CALL-UNIQUELY to that single call — r7 suggests
25+ gating on `xqd == [-16,-32]` — and get the real nine-byte window it reads.
26+ Compare against `100,111,117,140,154,163,182,194,201`.
27+3. With a call-unique measurement in hand, either the bytes differ (a sampling /
28+ stripe-boundary defect, and you have the coordinates) or they match and the
29+ 3110-vs-3109 gap lives downstream of `compute_ab`. Follow whichever the
30+ measurement says; do not carry r6's hypothesis forward.
31+
32+Then merge `main` into this branch and resolve it yourself — main has moved a
33+long way (multi-tile, delta_q/delta_lf, a `bit_depth != 8` refusal) — so the lane
34+arrives mergeable. And check `refusal_inventory.rs` still matches this branch's
35+refusal set.
36+
37+Oracle hygiene: `~/.cache/aom-oracle` is SHARED with five sibling lanes. Rung 6
38+is permanent and env-safe; any further change goes in as a rung in
39+`scripts/instrument-aom-oracle.sh` (silent when unset, idempotent), never as a
40+throwaway patch left in the shared tree. Rebuild with
41+`ninja -C ~/.cache/aom-oracle/build libaom.a`.
42+
43+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground
44+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms;
45+`EC_AV1_REQUIRE_AOMENC=1`. Sibling worktrees have live agents — never build in or
46+edit them. Never push, never merge this branch into main. 75-turn cap, does not
47+reset: COMMIT AT EVERY GREEN STEP. End with `lanes/lr-r8.report.md`, VERDICT on
48+line 1.
lanes/lr-r9.charter.mdadded+42 -0
@@ -0,0 +1,42 @@
1+# lane-lr r9 — finish what r8 started
2+
3+At 7ad6d77. Read `lanes/lr-r8.charter.md` (still your charter — r8 never got to
4+report) and the r7 section of `lanes/lr.report.md`.
5+
6+r8 stopped at its turn cap having done two things:
7+1. **Found and fixed a real defect** — `SGR_X_BY_XPLUS1` was mistranscribed at
8+ `av1_x_by_xplus1[101]` and `[165..=169]`, committed at 7ad6d77. Whether that
9+ closes the 3110-vs-3109 gap is UNKNOWN to me: the round never reported a
10+ gate result. **Run the LR gate first and find out** before assuming either
11+ way — and say plainly in your report which it was.
12+2. Started a merge of an already-stale `main`. I aborted it; nothing of yours
13+ was lost. Redo it against current `main` (a8724cb, far ahead: tile rows,
14+ delta_q/delta_lf, key-frame superres, palette-Y, a `bit_depth != 8` refusal,
15+ and two guard tests that will fail until this branch's refusal list matches).
16+
17+If the gate is still red, the r8 charter's method stands and has not been tried:
18+decode the ONE pinned stream `fixtures/lr-sgr-r7.obu` (seed 46, `EC_AV1_GATE_DUMP`
19+already wired at `stream.rs` ~4791) instead of the 40-attempt sweep, with a dump
20+keyed CALL-UNIQUELY to the failing call — r6's coordinate-keyed dump
21+(`v_start == 60`) captured some other invocation and cost a whole round
22+([[dump-not-call-unique]]). `lr_sample`, the box-sum formula and the fast arm are
23+independently reconfirmed correct; do not re-suspect them.
24+
25+Note that r8's find is itself the lesson: a mistranscribed constant in a 256-entry
26+table is invisible to every by-hand review and shows up as a one-off arithmetic
27+gap. If the gate is still red, diff the OTHER SGR tables against libaom
28+wholesale — `av1_one_by_x`, the `sgr_params` rows — before tracing anything.
29+
30+Merge `main` into this branch, resolve it yourself, and land the round green so
31+the SGR fix can reach main either way: a correct table fix is worth merging even
32+if the last pixel is still out, provided the gate's status is stated honestly.
33+
34+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`; foreground
35+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms;
36+`EC_AV1_REQUIRE_AOMENC=1`. The oracle at `~/.cache/aom-oracle` is SHARED with
37+five sibling lanes — instrument only via env-gated rungs in
38+`scripts/instrument-aom-oracle.sh`, never a throwaway patch left in the tree, and
39+note that rung numbers 6, 7, 8 and 8b are already taken on main; take 9. Sibling
40+worktrees have live agents — never build in or edit them. Never push, never merge
41+this branch into main. 75-turn cap, does not reset: COMMIT AT EVERY GREEN STEP.
42+End with `lanes/lr-r9.report.md`, VERDICT on line 1.
lanes/lr.charter.mdadded+100 -0
@@ -0,0 +1,100 @@
1+# lane-lr — loop restoration decode (read_lr + Wiener + self-guided)
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-lr`, branch `lane-lr`, off main 87a1e34.
4+
5+## Goal
6+Remove the whole-frame refusal at `crates/ec-av1/src/stream.rs:195`
7+("a frame with loop restoration enabled") by actually decoding it:
8+1. the per-restoration-unit symbols read from the tile data during the
9+ superblock walk (spec 5.11.57 `read_lr` / `read_lr_unit`), and
10+2. the two restoration filters themselves (spec 7.17: Wiener 7.17.4,
11+ self-guided 7.17.2/7.17.3), applied to the CDEF-filtered frame.
12+
13+## Anchors
14+- Spec: 5.11.57 `read_lr`, 5.11.58 `read_lr_unit`, 6.10.15, 7.17 `loop restoration process`.
15+- libaom (oracle source, `~/.cache/aom-oracle` build tree — find the src dir under it):
16+ `av1/decoder/decodeframe.c` `read_lr()` / `read_lr_unit()`;
17+ `av1/common/restoration.c` `av1_loop_restoration_filter_frame`,
18+ `wiener_filter_stripe`, `selfguided_restoration`, `av1_selfguided_restoration_c`,
19+ and the `sgr_params` table.
20+- Existing syntax: `crates/ec-av1-syntax/src/frame.rs:341` `LoopRestorationParams`
21+ (`frame_restoration_type`, `loop_restoration_size`, `uses_lr`).
22+- The superblock walk in the decoder is `crates/ec-av1/src/decode.rs` around
23+ lines 4547 and 9275 (`for sb_r in 0..sb_rows { for sb_c ... }`). `read_lr` is
24+ called once per superblock, BEFORE `decode_partition`, and loops over the LR
25+ units whose top-left falls in this superblock, per plane.
26+- CDF tables live in `crates/ec-av1/src/cdf.rs`. There is currently NO
27+ restoration CDF (`grep -i restoration crates/ec-av1/src/cdf.rs` is empty) —
28+ you must add `restore_wiener`, `restore_sgrproj`, `restore_switchable`
29+ (the switchable one is a 3-symbol CDF) with libaom's `default_*_cdf` values
30+ copied EXACTLY from `av1/common/token_cdfs.h` / `entropymode.c`. Note that
31+ the Wiener/SGR *coefficients* are NOT CDF-coded: they use
32+ `decode_signed_subexp_with_ref` (literal + subexp bits), spec 5.9.27-ish.
33+- CDF WIRING IS FOUR SITES in this codebase but in practice only the defaults
34+ array needs hand-checking (reset2/reset3 are length-generic, save/restore is
35+ a whole-struct Clone). Still verify the counter reset covers new tables.
36+
37+## Method (this is a range-ladder lane)
38+CLASS `compare-range-not-tell`: never compare `tell()` across decoders —
39+compare the msac RANGE after each element. The instrumented oracle at
40+`~/.cache/aom-oracle` has env-gated rungs: `EC_TRACE=1` (EC_PART),
41+`EC_TRACE_COEFF=1` (EC_COEFF), `EC_TRACE_MODE=1` (EC_MODE/EC_IMODE).
42+If you need an LR rung, ADD one to `scripts/instrument-aom-oracle.sh`
43+following the exact shape of the existing rungs (env-gated, silent when unset,
44+idempotent, wrapper-around-impl) and rebuild the oracle with
45+`scripts/build-aom-oracle.sh`. That is an expected part of this lane.
46+CLASS `equal-range-means-unread`: if the reference's range is UNCHANGED where
47+ours moves, we read a symbol it never wrote; if theirs moves and ours doesn't,
48+we skipped one. Only when both move by different amounts is a table implicated.
49+
50+## Staging — commit after EVERY green milestone
51+1. **Syntax only.** Read the lr symbols correctly and then still refuse the
52+ frame by name ("loop restoration symbols are read but the filters are not
53+ applied"). Prove correctness by the partition walk surviving: a stream that
54+ previously desynced into out-of-alphabet garbage now decodes its partitions
55+ and only fails the pixel compare. COMMIT.
56+2. **Wiener.** Implement `wiener_filter_stripe` (64-row stripes with the
57+ 3-pixel stripe boundary handling — that boundary handling is the classic
58+ trap; libaom saves/restores `rlbs` boundary lines). Gate a stream forced to
59+ Wiener only. COMMIT.
60+3. **Self-guided.** `selfguided_restoration` incl. the box-sum radii and the
61+ `sgr_params` table. COMMIT.
62+4. **Switchable.** Remove the last refusal. COMMIT.
63+
64+## Gate (mandatory, in `crates/ec-av1/src/stream.rs` next to the existing gates)
65+- Follow the existing gate shape exactly. `EC_AV1_REQUIRE_AOMENC=1` must be set
66+ when you run tests, so a missing oracle FAILS rather than SKIPs.
67+- Bound every ffmpeg `generate` with `-t <seconds>` (an unbounded source
68+ deadlocked a gate for an hour; class `gate-loader-slurps-whole-file`).
69+- Build the fixture through the existing `gradients_source(seed, w, h, tail)`
70+ helper — do NOT hand-write a `gradients=size=` string; ffmpeg's gradients
71+ source ignores its seed and the helper derives colours from the seed instead.
72+- aomenc flags: `--threads=1 --row-mt=0`, and whatever turns LR on
73+ (it is on by default; `--enable-restoration=1`). To force a single filter
74+ type, encode content that provokes it, or use the aomenc knob if one exists —
75+ if not, assert per-type firing counts instead.
76+- The gate MUST hard-assert a firing count (e.g. `wiener_hits > 0`), a
77+ thread-local `Cell<usize>` counter in decode.rs like the existing `*_HITS`
78+ (they are thread-local now, NOT atomics — process-global atomics made one
79+ gate count another test's work). CLASS `gate-blind-to-feature`: a gate that
80+ cannot prove its feature fired is vacuous.
81+- Refusals inside the gate are FORBIDDEN once the stage that removes them
82+ lands: assert the decode returns Ok, do not tolerate an Err.
83+
84+## Hard rules
85+- Own build dir: `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`.
86+ Foreground builds only, `nice -n 19 cargo ... -j4`. Never `cargo` in another
87+ worktree, never touch a sibling worktree's files.
88+- Suite scope: `nice -n 19 cargo test -p ec-av1 --lib` (67 s baseline on main,
89+ 232 passed / 0 failed). It must stay green.
90+- NEVER push, never merge, never touch `main`. Commit on `lane-lr` only.
91+- You have a 75-turn cap. **Commit work-in-progress after every green
92+ milestone** — five builders have lost complete implementations at the cap.
93+ If you are near the cap, commit whatever compiles as `wip(av1): ...` and
94+ write `lanes/lr.report.md` before you stop.
95+- Refuse-by-name rather than desync: any case you do not implement must return
96+ `Error::unsupported` with an accurate string. CLASS
97+ `refusal-claim-disproved-by-its-own-gate`: never write a refusal string that
98+ claims the encoder never emits the case unless you have proved it.
99+- Write `lanes/lr.report.md` at the end: what landed, gate name + firing count,
100+ what still refuses and by what exact string, and the next lever.
lanes/lr.report.mdadded+529 -0
@@ -0,0 +1,529 @@
1+# lane-lr report
2+
3+## What landed (committed on `lane-lr`, 14a0273)
4+- Added the three loop-restoration CDF tables this decoder was missing
5+ (`crates/ec-av1/src/cdf.rs`): `RESTORE_WIENER`, `RESTORE_SGRPROJ`,
6+ `RESTORE_SWITCHABLE`, copied exactly from libaom
7+ `av1/common/entropymode.c`'s `default_{wiener,sgrproj,switchable}_restore_cdf`
8+ (`AOM_CDF2(11570)`, `AOM_CDF2(16855)`, `AOM_CDF3(9413, 22581)` — converted
9+ to this codebase's `[a0, (a1,) 32768, 0]` convention, matching the existing
10+ `INTRABC` table's own conversion of `AOM_CDF2(30531)`).
11+- Wired all three into `Cdfs` (`crates/ec-av1/src/cdf_state.rs`): struct
12+ fields, `Cdfs::new`'s defaults, and `reset_counts` (all three are
13+ unindexed `[u16; N]`, same shape as `intrabc`, so `reset1` — the
14+ 4-site wiring checklist's counter-reset site is the only hand-checked
15+ one; save/restore and the other two sites are generic over any shape).
16+- `cargo check -p ec-av1` clean.
17+
18+## What still refuses, and by what string
19+The whole-frame refusal is UNCHANGED: `crates/ec-av1/src/stream.rs:195-198`
20+still returns `Error::unsupported("AV1 decode_stream", "a frame with loop
21+restoration enabled (this decoder never reads the per-unit lr symbols)")`
22+for any `header.loop_restoration.uses_lr` frame. The CDF tables added this
23+round are not read from the bitstream anywhere yet — this is groundwork
24+for stage 1 (charter's "syntax only" milestone), not stage 1 itself.
25+
26+## Design worked out but not yet coded (for the next round)
27+Traced the full spec/libaom shape so the next round can go straight to
28+code instead of re-reading source:
29+
30+- `av1_loop_restoration_corners_in_sb` (`restoration.c:1277`) only returns
31+ non-zero corners when `bsize == sb_size` — i.e. despite `decode_partition`
32+ calling it recursively at every partition level in libaom, only the
33+ top-of-superblock call ever does anything, because every restoration
34+ unit is >= 64px (SB size). The charter's "once per superblock" plan is
35+ therefore exactly spec-equivalent, not a simplification with a gap.
36+- Per-plane unit grid: `horz_units = max(1, round(plane_w / unit_size))`,
37+ `vert_units` likewise (`av1_lr_count_units`, `restoration.c:63`, note
38+ ROUND not ceil). `plane_w`/`plane_h` are `frame_width`/`frame_height` for
39+ luma; this decoder is 4:2:0-only in the tile-decode functions already
40+ (`u`/`v` are hardcoded half-size), so chroma is
41+ `(frame_width+1)/2, (frame_height+1)/2` (`ROUND_POWER_OF_TWO`).
42+ `unit_size` = `header.loop_restoration.loop_restoration_size[plane]`
43+ directly (already computed per-plane in
44+ `ec-av1-syntax/src/frame.rs:1626-1637`).
45+- Per-SB corner math (`restoration.c:1277-1335`, no superres in this
46+ decoder so the superres-scaled branches are dead code here):
47+ `rcol0 = ceil_div(mi_col0 * mi_size_x, unit_size)`,
48+ `rcol1 = min(ceil_div((mi_col0+sb_mi_w) * mi_size_x, unit_size), horz_units)`,
49+ same for rows; `mi_size_x = 4` luma, `2` chroma (4:2:0). Then
50+ `runit_idx = rcol + rrow * horz_units`, and `read_lr_unit` is called once
51+ per `(rrow, rcol)` in that rectangle, per plane, in plane order.
52+- `read_lr_unit` symbol shape (`decodeframe.c:1687-1723`): if
53+ `frame_restoration_type[plane] == Switchable`, read one
54+ `restore_switchable` (3-way) symbol and dispatch; if `== Wiener`, read one
55+ `restore_wiener` binary symbol, Wiener filter only if 1; if `==
56+ Sgrproj`, same with `restore_sgrproj` and the SGR filter. `None` never
57+ calls this at all (loop skipped by `frame_restoration_type[plane] ==
58+ RESTORE_NONE` — i.e. it's legal for the switchable-frame case per plane
59+ even when only some planes use LR, since `frame_restoration_type` is
60+ per-plane).
61+- Wiener coefficients: 3 taps per direction (vfilter/hfilter), each via
62+ `aom_read_primitive_refsubexpfin(n, k, ref)` — SAME algorithm this crate
63+ already has for global-motion params
64+ (`ec-av1-syntax/src/frame.rs:1797-1839`,
65+ `decode_signed/unsigned_subexp_with_ref`/`decode_subexp`/`inverse_recenter`)
66+ but that existing implementation runs on a raw `BitReader` (frame header,
67+ uncompressed bits); the LR coefficients are read through the arithmetic
68+ decoder (`aom_reader`, i.e. this crate's `SymbolDecoder`), using
69+ `aom_read_literal`/`aom_read_bit` as the raw-bit primitives —
70+ `SymbolDecoder::literal(bits)` (`msac.rs:348`, already exists, built on
71+ `symbol_fixed(&EQUIPROBABLE)`) is the exact equivalent. The subexp/recenter
72+ math needs a second, msac-flavoured port of those four functions (same
73+ arithmetic, `dec.literal(1)`/`dec.literal(n)` in place of `r.read_bit()`/
74+ `r.read_bits(n)`) — not reusable as-is because the reader types differ.
75+ Per-tap `(min, max, k)`, all computed from libaom `restoration.h`:
76+ tap0 `(-5, 10, k=1)`, tap1 `(-23, 8, k=2)`, tap2 `(-17, 46, k=3)`
77+ (`WIENER_FILT_TAPn_MIDV` 3/-7/15, bits 4/5/6). Reference state
78+ (`ref_wiener_info`) starts each tile at the tap midpoints (3, -7, 15) and
79+ updates to the just-decoded value after each unit — same per-plane
80+ running-reference shape as `PrevSegmentIds`/other adapting-per-tile state
81+ already in this crate.
82+- SGR coefficients: one 4-bit literal `ep` (`SGRPROJ_PARAMS_BITS`) indexing
83+ `av1_sgr_params`/`sgr_params` (a small fixed table this crate does not
84+ have yet — needed even for stage 1 since `ep` selects which of `xqd[0]`/
85+ `xqd[1]` is forced to 0 vs subexp-coded, spec 7.17.3's `Sgr_Params`), then
86+ 1-2 subexp-coded `xqd` values, ranges `(-96, 31, k=4)` and
87+ `(-32, 95, k=4)` (`SGRPROJ_PRJ_MIN/MAX{0,1}`, `SGRPROJ_PRJ_BITS=7`).
88+
89+## Next lever
90+Port the msac-flavoured subexp/recenter quartet into `decode.rs` (or a new
91+`restoration.rs`), add the `Sgr_Params` table (8 entries, `restoration.c`'s
92+`av1_sgr_params`, not yet located — grep `sgr_params\[` there), write
93+`read_lr_unit` using the corner math above, thread
94+`&header.loop_restoration` into `decode_key_frame_tile_with_cdfs` and
95+`decode_inter_frame_tile_with_cdfs` (both already take a long positional
96+arg list matching this pattern — see `cdef`/`loop_filter` params; the two
97+public one-star wrappers `decode_key_frame_tile`/`decode_inter_frame_tile`
98+can keep their old signatures by passing `&LoopRestorationParams::default()`
99+internally, so the ~10 test call sites across `decode.rs` do not need
100+touching), call `read_lr` once per SB in both superblock loops
101+(`decode.rs` ~4547 key, ~9275 inter) BEFORE `decode_partition`/its
102+equivalent, and only then flip `stream.rs`'s refusal from unconditional to
103+"decode succeeded, still refuse by name because filters are not applied"
104+(stage 1's own exit criterion: prove the partition walk survives past a
105+real LR stream). Stage 1 gate: generate an aomenc stream with
106+`--enable-restoration=1` (default on) via the existing `gradients_source`
107+helper, decode it, assert the *new* refusal string appears (not the old
108+desync-shaped one / not an `Err` from deep inside a block reader), and
109+self-pin firing counts for wiener/sgrproj/switchable via thread-local
110+`Cell<usize>` hit counters the way every other gate in this lane's charter
111+requires.
112+
113+## Turn budget (r1)
114+Spent ~55 of 75 turns on recon (spec/libaom read_lr shape, corner math,
115+subexp/recenter porting requirements, CDF value derivation) plus the CDF
116+landing above; stopped short of wiring `read_lr` itself to avoid leaving a
117+half-edited, untested threading change across two large decode functions
118+uncommitted at the cap. Everything above is proven correct in principle
119+(SB-only firing is a real spec property, not skipped-and-hoped) but wiring
120++ the gate itself are unstarted.
121+
122+## r2 landed (committed on `lane-lr`, 32892df; 235 passed / 0 failed,
123+EC_AV1_REQUIRE_AOMENC=1, `232` baseline + 3 new tests)
124+- `crates/ec-av1/src/restoration.rs` (new): msac-flavoured
125+ `decode_subexp_msac`/`decode_unsigned_subexp_with_ref_msac`/
126+ `decode_signed_subexp_with_ref_msac`/`ns_msac` (libaom
127+ `read_primitive_subexpfin_`/`aom_read_primitive_refsubexpfin_`/
128+ `read_primitive_quniform_`, `k` a per-call parameter unlike global
129+ motion's fixed 3) -- pinned by 3 roundtrip tests
130+ (`subexp_roundtrips_every_value`, `unsigned_subexp_with_ref_roundtrips`,
131+ `signed_subexp_with_ref_roundtrips`) against a hand-written encode-side
132+ mirror (`SymbolEncoder` has no LR writer of its own, this crate never
133+ writes LR). Also: `WienerInfo`/`SgrprojInfo`/`UnitFilter`,
134+ `SGR_PARAMS` (`av1_sgr_params`, restoration.c:36, all 16 entries),
135+ `read_wiener_filter`/`read_sgrproj_filter`/`read_lr_unit`/`read_lr`
136+ (spec 5.11.57, decodeframe.c ~1595-1723), `RestorationGrid` (per-plane
137+ unit grid + flattened `runit_idx` storage, `av1_lr_count_units`'s ROUND
138+ not ceil).
139+- `crates/ec-av1/src/decode.rs`: `decode_key_frame_tile_with_cdfs` and
140+ `decode_inter_frame_tile_with_cdfs` now take `lr: &LoopRestorationParams`
141+ and call `crate::restoration::read_lr` once per superblock (before
142+ `decode_partition`'s own symbol), building a `RestorationGrid` +
143+ per-plane `(WienerInfo, SgrprojInfo)` running reference state before the
144+ loop. The public one-star wrappers (`decode_key_frame_tile`/
145+ `decode_inter_frame_tile`) pass `&LoopRestorationParams::default()`
146+ unchanged, so their ~10 existing test call sites needed no edits.
147+- `crates/ec-av1/src/stream.rs`: both call sites thread
148+ `&header.loop_restoration` through; the refusal string is renamed from
149+ "never reads the per-unit lr symbols" to "the per-unit lr symbols are
150+ read but the Wiener/self-guided filters are not yet applied to pixels"
151+ -- the frame STILL refuses (no pixel filter is applied anywhere yet),
152+ but the refusal now names the true remaining gap per charter stage 2's
153+ exit criterion.
154+- NOT done this round, no gate written: I did not build the aomenc
155+ `--enable-restoration=1` gate the charter's stage 1/2 asks for (proving
156+ the partition walk survives past a real LR stream and self-pinning
157+ wiener/sgrproj/switchable firing counts via thread-local `Cell<usize>`
158+ hit counters). Ran out of turn budget before writing it; the full
159+ `cargo test -p ec-av1` suite (235/0, unrelated fixtures) is the only
160+ evidence this round has that the wiring compiles and does not regress
161+ anything -- it does NOT exercise a real LR stream at all, since no
162+ existing gate/fixture in this suite turns `--enable-restoration` on.
163+
164+## Next lever (r3)
165+1. Write the gate: `gradients_source` fixture through aomenc with
166+ `--threads=1 --row-mt=0 --enable-restoration=1` (default on already,
167+ so no flag omission risk), decode it, assert the NEW refusal string
168+ (not an `Err` from a block reader = partition desync, not the old
169+ string). Self-pin `WIENER_HITS`/`SGRPROJ_HITS`/`SWITCHABLE_HITS`
170+ thread-local `Cell<usize>` counters bumped inside `read_lr_unit`
171+ (`crates/ec-av1/src/restoration.rs`) -- a gate that cannot prove LR
172+ fired is vacuous per this lane's charter. Given how rare a `Wiener`
173+ frame-level restoration_type is likely to be vs `Switchable` at
174+ default aomenc settings, may need `EC_LR_GATE_ATTEMPTS` bumped like
175+ other lanes' flaky-firing gates (see ledger `lane-maskcomp`).
176+2. Wiener pixel filter (stage 3): apply after `apply_cdef` (LR runs on the
177+ post-CDEF, post-deblock frame, spec 7.17) as a new `apply_loop_restoration`
178+ pass over `lr_grid`, one restoration-unit rectangle at a time, using
179+ the already-decoded `vfilter`/`hfilter`. The 3-pixel stripe boundary
180+ save/restore (libaom's `rlbs`) is the known trap -- not investigated
181+ this round beyond the report's own citation.
182+3. SGR filter (stage 4): box-sum radii from `SGR_PARAMS`' `(r0, r1)`,
183+ `av1_apply_selfguided_restoration` shape -- not investigated this
184+ round.
185+4. Once both filters are wired, drop the `stream.rs` refusal entirely
186+ (stage 5) -- gate should then assert `Ok`, never `Err`.
187+
188+## r3 (committed on `lane-lr`, 0cfe9d6; 236 passed / 0 failed, 17
189+ignored, EC_AV1_REQUIRE_AOMENC=1) -- VERDICT: step 1 (the gate) landed
190+and, in the process of landing it, found and fixed a real gap r2's own
191+report had flagged as unverified. Steps 2-4 (Wiener/SGR pixel filters,
192+dropping the refusal) NOT started -- out of turn budget.
193+
194+- New gate `a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly`
195+ (`crates/ec-av1/src/stream.rs`): real aomenc `--enable-restoration=1
196+ --sb-size=64` stream, multi-superblock fixture (192x128 = 3x2 SBs of
197+ 64px -- charter's own trap warning), 40 attempts, `cq-level=15` (r2's
198+ sibling gates' usual `cq-level=45` never landed `uses_lr=true` for
199+ this content -- sampled live before picking 15). Self-pinned
200+ `WIENER_HITS`/`SGRPROJ_HITS`/`SWITCHABLE_HITS` thread-local counters
201+ added to `restoration.rs`'s `read_lr_unit`, hard-asserted `sum > 0`.
202+- **The gate found a real bug**: `stream.rs`'s `header.loop_restoration.uses_lr`
203+ refusal check ran BEFORE the `decode_key_frame_tile_with_cdfs`/
204+ `decode_inter_frame_tile_with_cdfs` call, so `read_lr` was NEVER
205+ actually invoked through `decode_stream` -- despite r2's report
206+ describing "the symbols are read", no real stream had ever exercised
207+ that claim end to end. First gate run: 40/40 attempts hit the refusal
208+ with `wiener_hits=sgrproj_hits=switchable_hits=0`. Fixed by moving the
209+ check to run AFTER the tile-decode call succeeds (same refusal string,
210+ new position) -- this both proves the superblock walk survives
211+ `read_lr` without desyncing (the charter's actual step-1 ask) and now
212+ genuinely exercises the reader. Also needed `--sb-size=64` in the gate
213+ recipe (without it, aomenc's default sb128 choice hit the unrelated,
214+ already-dead-ended `lane-sb128` partition-desync gap and ate the whole
215+ attempt window with "a partition type this encoder never writes").
216+- Final gate result: 39 LR refusals / 0 other refusals out of 40
217+ attempts, `wiener_hits=19 sgrproj_hits=72 switchable_hits=0` (this
218+ fixture's RD only ever picked a fixed frame-level `Wiener`/`Sgrproj`
219+ type, never `Switchable` -- both non-switchable arms proven live; the
220+ switchable arm is still symbol-code-reviewed only, unexercised by any
221+ gate this round).
222+- Refusal string: UNCHANGED text ("a frame with loop restoration enabled
223+ (the per-unit lr symbols are read but the Wiener/self-guided filters
224+ are not yet applied to pixels)"), only its position in `decode_stream`
225+ moved (was before the tile-decode call, now after) -- `refusal_inventory.rs`
226+ on main should not need updating for this move since the string itself
227+ didn't change; report this in case main's guard checks call-site order
228+ too.
229+
230+## r5 -- VERDICT: not green. 06ba9af compiles clean and was NOT a
231+mid-edit wip; r4 finished all four charter steps (Wiener + SGR pixel
232+filters wired at both call sites, gate widened to assert `Ok` +
233+pixel-exact, `stream.rs` refusal dropped). Suite: 235/236 -- one real,
234+reproducible (not flake) defect in
235+`a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly`:
236+`V mismatch (seed 46 frame 0)`, exactly 1 pixel of 6144 in the V plane,
237+off by 1 (ours=195, ffmpeg reference=194), at absolute (row=61,col=6),
238+inside chroma's last/partial restoration stripe `[60,64)` (unit spans
239+the whole 64px plane height, `--sb-size=64` 192x128 fixture), filter
240+`Sgrproj{ep:6, xqd:[-16,-32]}` (both radii active, `r0=2` "fast" +
241+`r1=1` "dense"). Ran 235/236 with `EC_AV1_REQUIRE_AOMENC=1`,
242+`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-lr`, `-j4`, 600000ms timeout.
243+
244+Did NOT commit anything this round -- the tree was already clean at
245+06ba9af (nothing left mid-edit; the orchestrator's "unverified" label
246+undersold r4's actual state). All edits made this round were temporary
247+`eprintln!`/dump instrumentation, reverted with `git checkout --` before
248+finishing (tree is bit-identical to 06ba9af).
249+
250+Diagnosis done, inconclusive on root cause:
251+- Confirmed NOT a flake -- same failure every run, same seed/pixel.
252+- Confirmed NOT an above/below stripe-boundary substitution bug --
253+ hand-traced `lr_sample`'s doc-commented rules
254+ (`stripe_v_start-1`→exact, `-2`/`-3`→both duplicate `stripe_v_start-2`;
255+ `stripe_v_end==plane_h`→frame-edge replicate) against libaom's real
256+ `setup_processing_stripe_boundary`/`save_deblock_boundary_lines`
257+ (`~/.cache/aom-oracle/src/av1/common/restoration.c` ~249-410,
258+ 1355-1490) line by line -- they match exactly for this stripe
259+ (`use_deblock_above=true` since `stripe_idx=2>0`, `use_deblock_below=
260+ false` since it's the plane's last stripe).
261+- Wrote a live dump harness (env-gated `eprintln!`+file dump inside
262+ `apply_sgrproj_stripe`/`filter_restoration_unit`, since reverted) that
263+ extracted the REAL cdef/deblocked V-plane bytes for the failing
264+ attempt to `/tmp/lr_cdef.bin`/`/tmp/lr_deblocked.bin` (both files
265+ byte-identical, as expected -- gate runs `--enable-cdef=0`).
266+ Instrumented the live Rust `apply_sgrproj_stripe`/`compute_ab` to
267+ print the actual A/B grid values it computes for the failing pixel's
268+ 5-neighbour dense (`r1`) read: `a_u=254 b_u=303 a_c=251 b_c=922
269+ a_d=224 b_d=6502 a_l=252 b_l=700 a_r=249 b_r=1344`, and the final
270+ combine: `a1=7674 b1=103359 flt1=3110 xq0=-16 xq1=176`. Hand-verified
271+ every one of these numbers independently in Python against the raw
272+ 9-tap box sums read back from the dumped buffers via `lr_sample` --
273+ ALL MATCH; the dense-radius arm's math is provably correct for this
274+ pixel. Did not get to instrument the fast (`r0=2`) arm's actual grid
275+ reads the same way before the turn cap forced a stop (only its
276+ `a=4000 b=16759 flt0=3097` final numbers were captured, not the 5
277+ underlying A/B neighbour reads) -- **the fast arm is the one unverified
278+ half**; check that first.
279+- A hand-written standalone C transcription of libaom's real algorithm
280+ (`/tmp/lr_ref.c`, hex box-sum + av1_x_by_xplus1/av1_one_by_x tables
281+ copied verbatim from `restoration.c`) produced 194 (matching ffmpeg)
282+ against the same dumped buffers -- but a *second*, differently-scoped
283+ probe (`/tmp/lr_probe.c`) printing individual A/B taps gave
284+ self-inconsistent numbers across separate runs of what should be
285+ identical code, so that C reproduction is NOT trustworthy evidence of
286+ a real Rust bug; treat both `/tmp/lr_ref.c` divergence claims as
287+ unconfirmed, not as a finding. The live-Rust-instrumented numbers
288+ above are the reliable data.
289+- Next agent: re-run this round's dump harness (recreate the 3
290+ env-gated `eprintln!` blocks -- see this section's description, they
291+ were reverted, not left in the tree) to print the FAST (`r0=2`) arm's
292+ 5 individual A/B neighbour reads (`a_um1/b_um1`, `a_up1/b_up1`,
293+ `a_uml`, `a_umr`, `a_upl`, `a_upr` for the row-61 ODD-branch case --
294+ wait, row61 is ODD relative to `v_start=60`, so it's actually the
295+ OTHER branch: own-row `a_c/b_c` + `a_l/a_r` neighbours, matching
296+ `restoration.rs`'s `else` arm ~line 738) and hand-verify those 3
297+ numbers the same way the dense arm was verified above. If those also
298+ check out, the bug is not in `apply_sgrproj_stripe` at all and the
299+ next place to look is upstream: whether the V-plane's CDEF/deblocked
300+ pixel data feeding `lr_sample` is itself off by something that only
301+ this specific rounding-sensitive combination surfaces (Y and U match
302+ bit-exact on every attempt; only V, only this one pixel, only this
303+ one `(ep,xqd)` combination, across the whole 40-attempt run).
304+
305+## Next lever (r3 -> r4)
306+1. Wiener pixel filter (charter step 2): `apply_loop_restoration` after
307+ `apply_cdef` in `decode.rs` (two call sites, ~4983/10502), driven by
308+ the `RestorationGrid`/`(WienerInfo, SgrprojInfo)` this round's gate
309+ proved decode correctly. Watch the 3-pixel stripe boundary save/
310+ restore (`rlbs`) -- not investigated this round.
311+2. Self-guided (SGR) filter (charter step 3): box-sum radii from
312+ `SGR_PARAMS`.
313+3. Once both are wired and this gate's LR frames start decoding
314+ pixel-exact, widen the gate to assert `Ok` + pixel match instead of
315+ the named refusal, then drop the `stream.rs` refusal (charter step 4).
316+
317+## Turn budget (r3)
318+Spent on: reading the charter + r2 section, writing the gate, and
319+(unplanned but necessary) diagnosing + fixing the check-before-decode
320+bug the gate exposed -- confirming it via a scratch `EC_AV1_PIN` decode
321+of a hand-built fixture (`loop_restoration.uses_lr=true`, `frame_restoration_type`
322+`Sgrproj`) before touching `stream.rs`. Did not reach either pixel
323+filter; r4 should start directly at Wiener (`decode.rs`'s two
324+`apply_cdef` call sites), no further libaom recon needed this report
325+plus `restoration.rs`'s own doc comments don't already cover.
326+
327+## Turn budget (r2)
328+Spent the full 75-turn allowance on: recon of libaom's exact `k`-per-tap
329+subexp/SGR-table/read_lr_unit shape (not fully covered by r1's report --
330+the report's own citations turned out right, but exact constants/ep-branch
331+logic needed a fresh libaom read from `~/.cache/aom-oracle`), writing +
332+pinning `restoration.rs`'s bitstream-read half, wiring it into both SB
333+loops, and confirming no regression (235/0). Did not reach the gate or
334+either pixel filter -- see "Next lever" above; r3 should start there
335+directly rather than re-reading libaom (this doc + `restoration.rs`'s own
336+doc comments now carry every file:line needed).
337+
338+## r6 -- VERDICT: not green, still one pixel. Real progress: the
339+r5-reported divergence source is now DISPROVEN and a decisive,
340+reusable ground-truth harness exists. Did not commit (no green step;
341+all edits this round were temporary diagnostics, reverted with `git
342+checkout --` before finishing -- tree is bit-identical to 02a08bf).
343+
344+**Decisive new evidence** (`/tmp/claude-*/scratchpad/lr_sgr_harness.c`,
345+linked against the real `~/.cache/aom-oracle/build/libaom.a`, calling
346+the actually-exported `av1_apply_selfguided_restoration_c` /
347+`av1_selfguided_restoration_c` directly -- not a hand-transcribed
348+reimplementation, the real compiled function):
349+- Dumped the exact `lr_sample`-boundary-substituted 102x10 byte buffer
350+ our own `compute_ab`/`apply_sgrproj_stripe` uses for the failing
351+ pixel (V plane, seed 46, ep=6/xqd=[-16,-32], stripe [60,64) of the
352+ 96x64 chroma plane, row 61 col 6) to `/tmp/lr_full.bin`, via a temp
353+ `EC_LR_DUMP`-gated `eprintln!`/`std::fs::write` in
354+ `apply_sgrproj_stripe` (since reverted).
355+- Fed that *exact same buffer* to the real libaom function (chunked to
356+ width=64 matching libaom's own `RESTORATION_PROC_UNIT_SIZE`
357+ splitting -- `av1_apply_selfguided_restoration_c`'s internal
358+ fixed-size arrays overflow above that, segfault first attempt,
359+ fixed by chunking like `sgrproj_filter_stripe` does). Real libaom,
360+ given identical input pixels, produces **194** (matches ffmpeg) --
361+ proving the bug is not in `lr_sample`/stripe-boundary substitution
362+ at all (r5's suspicion), since both implementations read the same
363+ bytes and only ours is wrong.
364+- Also called `av1_selfguided_restoration_c` directly to get the
365+ pre-combine `flt0`/`flt1`: real `flt0[1][6]=3097` (matches our
366+ Rust's fast/r0 arm exactly), real `flt1[1][6]=3109` vs our Rust's
367+ `3110` -- **the divergence is entirely in the dense/r1 arm**, not
368+ the fast arm r5 flagged as the unverified half.
369+- Instrumented `compute_ab` directly (temp `eprintln!`, reverted) to
370+ dump the 9 individual A/B taps (`c,u,d,l,r,ul,ur,dl,dr`) the dense
371+ combine at (i=1,j=6) actually uses, and independently recomputed
372+ every one from the raw dumped bytes via a clean Python box-sum (not
373+ the earlier untrusted `/tmp/lr_ref.c`/`/tmp/lr_probe.c`) -- **all 9
374+ match exactly** (`ab1: c=(251,922) u=(254,303) d=(224,6502)
375+ l=(252,700) r=(249,1344) ul=(253,422) ur=(253,486) dl=(241,2974)
376+ dr=(171,17543)`), and the combine formula (weight 4/3, `nb=5`,
377+ `SGRPROJ_SGR_BITS+5-SGRPROJ_RST_BITS` shift) reproduces `3110`
378+ exactly from those 9 values by hand -- so `compute_ab`'s per-cell
379+ math (box sum, `SGR_X_BY_XPLUS1`/`SGR_ONE_BY_X` lookup, rounding) is
380+ internally self-consistent with a naive centered-window recompute,
381+ AND matches the real libaom answer for 8 of 9 taps that a *separate*
382+ cross-check against `boxsum1`'s real sliding-window source
383+ (`restoration.c:418-483`) traced by hand this round confirms is
384+ mathematically equivalent to a naive per-position 3x3 sum for every
385+ physical row/col our grid needs (the sliding-window's own 2-tap
386+ boundary special cases only fire at `local index 0` / the far edge,
387+ both outside the `physical -1..h` range this stripe's grid touches).
388+- Net: given all 9 A/B taps individually reproduce via a from-scratch
389+ box-sum recompute of the real bytes, but the combined `flt1` still
390+ disagrees with the real compiled function by exactly the 1 LSB that
391+ explains the whole defect, the remaining unaccounted gap is narrow
392+ but NOT yet pinned to a single line -- either one of the 9 taps
393+ itself differs from what real libaom's *compiled* `boxsum`/
394+ `calculate_intermediate_result` computes (despite the hand-traced
395+ sliding-window algebra saying it shouldn't), or there is a rounding
396+ mode difference (`ROUND_POWER_OF_TWO` for negative/tie values,
397+ `2*(bit_depth-8)` pre-rounds that are no-ops at 8-bit but were not
398+ independently verified as no-ops in the compiled binary) not yet
399+ checked against the real function's per-tap output directly.
400+
401+**Ruled out this round** (do not redo):
402+- `lr_sample`/stripe-boundary substitution as the cause -- disproven
403+ directly (see above), not just re-verified by hand.
404+- The fast (`r0=2`) arm -- `flt0` matches the real compiled function
405+ bit-exact. r5's charter guess that this was the unverified half was
406+ wrong; it turned out to be already correct.
407+- `compute_ab`'s formula/table lookup being *generically* wrong -- 8
408+ of 9 taps match a from-scratch recompute of the real bytes exactly,
409+ and the combine weights/shift match libaom's source line-for-line.
410+- The earlier `/tmp/lr_ref.c`/`/tmp/lr_probe.c` "194 vs self-inconsistent"
411+ claim from r5 -- irrelevant now; the new harness supersedes it with a
412+ real linked answer, not a hand transcription.
413+
414+**Start here (r7)**: get a per-tap ground-truth number directly out of
415+the compiled libaom binary instead of hand-tracing `boxsum1` further --
416+`av1_selfguided_restoration_c` only returns the final `flt0`/`flt1`,
417+not the intermediate `A`/`B` arrays (`calculate_intermediate_result` is
418+`static`). Two ways to get them: (a) build a *second* aom-oracle copy
419+with `calculate_intermediate_result` changed from `static` to
420+exported-and-declared-in-a-header (rebuild is the `scripts/build-aom-oracle.sh`
421+recipe, ~5min), then call it directly with the same 9 physical
422+positions and diff against the 9 values dumped above; or (b) bisect by
423+zeroing individual pixels in the dumped buffer one at a time and
424+re-running the harness against both the real function and a
425+from-scratch recompute to see which single input pixel's value moves
426+the two answers apart. (a) is more direct. The harness itself
427+(`av1_apply_selfguided_restoration_c` call pattern, chunked to
428+width=64, `tmpbuf` sized `2*400*400` -- undersizing it segfaults, see
429+`RESTORATION_UNITPELS_MAX`) is reusable as-is; a copy is in this
430+worktree's scratchpad
431+(`/tmp/claude-1000/.../scratchpad/lr_sgr_harness.c`,
432+`lr_sgr_harness`), not committed (scratch, not source).
433+
434+## Turn budget (r6)
435+Spent on: building + debugging the real-libaom-linked harness (one
436+segfault from undersizing the internal tmpbuf, fixed), the input-buffer
437+dump wiring in `restoration.rs`, and the 9-tap cross-check (including
438+chasing down two of my own Python transcription bugs mid-round --
439+lesson: rerun a "found the bug" number at least once before trusting
440+it, both false positives here were stale/mistyped variable state, not
441+real). Ran out of budget before pinning the exact source-level cause;
442+r7 should start at option (a) above, not redo any of the ruled-out list.
443+
444+## r7 -- VERDICT: not green, still one pixel. Built the ground-truth
445+instrument r6 asked for, but it could not reproduce r6's own "254 vs
446+253" divergence this round -- open, needs r8 to re-derive with a
447+uniquely-identified call (see below). Committed `ff1e62f` (harness +
448+oracle rung + gate pin, all forward progress, no behaviour change to
449+the decoder).
450+
451+**Built** (option (a) from r6, done):
452+- `scripts/instrument-aom-oracle.sh` rung 6: drops `static` from
453+ libaom's `calculate_intermediate_result` (restoration.c) so an
454+ external harness can call it directly. Rebuilt
455+ `~/.cache/aom-oracle/build/libaom.a` with it (`ninja libaom.a`).
456+- `scripts/lr-sgr-pin-harness.c` extended: replicates
457+ `av1_selfguided_restoration_c`'s own uint8->int32 border-extend copy,
458+ then calls `calculate_intermediate_result` directly with
459+ `sgr_params_idx=6, radius_idx=1, pass=0` and prints the real A/B for
460+ all 9 dense-arm neighbour taps of the r6 failing pixel.
461+- Wired `EC_AV1_GATE_DUMP` into
462+ `a_real_aomenc_stream_with_restoration_reads_lr_symbols_correctly`
463+ (stream.rs ~4791), mirroring the masked-compound gate's existing
464+ pattern -- pins the exact mismatching stream instead of only
465+ asserting. Ran once, wrote seed 46's stream to
466+ `fixtures/lr-sgr-r7.obu` (gitignored, not in the commit -- copy
467+ survives in this worktree only; regenerate with
468+ `EC_AV1_GATE_DUMP=fixtures/lr-sgr-r7.obu EC_LR_GATE_ATTEMPTS=10` if
469+ it's gone).
470+
471+**Result — real ground truth for the "u" tap**: `av1_x_by_xplus1`/
472+`av1_one_by_x` real compiled tables, real box sum, real
473+`ROUND_POWER_OF_TWO` all say the "u" tap (physical row 60, the box
474+centred one row above the failing pixel) is `(A,B) = (253,454)`, not
475+the `(254,303)` r6's report recorded. Hand-verified twice (once by
476+reading libaom's source directly with these exact numbers -- z=101,
477+`av1_x_by_xplus1[101]=253`, `av1_one_by_x[8]=455`,
478+`ROUND_POWER_OF_TWO(3*1362*455,12)=454` -- and once independently via
479+the harness's compiled call). The other 8 taps r6 already trusted are
480+untouched this round.
481+
482+**Could not reproduce r6's divergence.** Added a temporary
483+`EC_LR_SAMPLE_DUMP` env-gated `eprintln!` to `lr_sample` (reverted,
484+not in the commit) and reran the live gate at `EC_LR_GATE_ATTEMPTS=5`
485+(seeds 42-46, the one that panics is 46): the raw bytes our own
486+`compute_ab` actually reads for the "u" tap's 3x3 window at column 6
487+across the three box rows are `111` (row 59, deblocked-boundary read),
488+`154` (row 60), `194` (row 61) -- these match `/tmp/lr_full.bin`'s
489+bytes at the same physical positions bit for bit, and an independent
490+Python replica of `compute_ab`'s exact box-sum/`z`/`A`/`B` formula fed
491+the full real 9-byte window (100,111,117/140,154,163/182,194,201)
492+reproduces `(253,454)` exactly -- i.e. this round could not find *any*
493+wrong input or wrong arithmetic for the "u" tap; both check out
494+against the real answer independently. r6's `(254,303)` number was not
495+re-derived from a uniquely-identified call this round (the dump filter
496+matched on `v_start==60` only, which several different seeds/frames in
497+the 5-attempt window share, so the samples confirmed above are not
498+provably from the exact same call r6's `eprintln!` captured, only from
499+*a* call at the same coordinates producing the same real bytes).
500+
501+**Do not re-suspect** (unchanged from r6, now doubly confirmed): `lr_sample`
502+boundary substitution, the box-sum inputs themselves, the fast/r0 arm,
503+`compute_ab`'s formula in the abstract (matches source + a from-scratch
504+Python replica bit for bit for these 9 real bytes).
505+
506+**r8 should**: use the now-committed `EC_AV1_GATE_DUMP` wiring plus
507+`fixtures/lr-sgr-r7.obu` to decode the *single pinned seed-46 stream*
508+directly (not the live 40-attempt sweep, which reuses coordinates
509+across unrelated frames), and re-add a debug dump keyed to a value
510+unique to this one call (e.g. tag the print with a per-call sequence
511+counter, or gate on the exact `xqd=[-16,-32]` this pixel uses) so the
512+9 bytes it captures are provably the same call r6's original 3110-vs-3109
513+mismatch came from. If that live-captured 9-byte window differs at all
514+from `100,111,117,140,154,163,182,194,201`, that's the real bug; if it
515+matches, the (254,303) transcription itself was wrong and the fix is
516+elsewhere (recheck `flt1`'s combine step in `apply_sgrproj_stripe`
517+directly, not `compute_ab`, since r6 also independently reproduced
518+`3110` by hand from the taps it recorded -- meaning either the taps or
519+the combine, not both, are broken, and this round's evidence points
520+at the taps).
521+
522+## Turn budget (r7)
523+Spent on: building + verifying the rung 6 harness/oracle patch,
524+capturing a fresh 9-tap real-libaom answer (all matches r6's 8 except
525+the "u" tap), a live `EC_LR_SAMPLE_DUMP` trace to try to falsify
526+r6's claim, and wiring + exercising `EC_AV1_GATE_DUMP` for the gate
527+(new, reusable). Ran out of budget chasing down the coordinate-vs-call
528+ambiguity above; r8 should start there, not redo any of this round's
529+ground-truth derivation.
scripts/instrument-aom-oracle.shmodified+30 -0
@@ -38,6 +38,15 @@
38 # its superres margin (lane-superres r5: hand-tracing the arithmetic38 # its superres margin (lane-superres r5: hand-tracing the arithmetic
39 # could only prove our own self-consistency, not correctness against39 # could only prove our own self-consistency, not correctness against
40 # libaom).40 # libaom).
41+# Rung 9 (unconditional, no env gate) -- SGR per-tap ground truth
42+# (lane-lr r7): `calculate_intermediate_result` in
43+# av1/common/restoration.c is `static`, so a standalone harness cannot
44+# call it to get real A[]/B[] intermediate arrays, only the final
45+# flt0/flt1 via the public av1_selfguided_restoration_c. This rung
46+# drops `static` so an external harness can call it directly with a
47+# `dgd32`-style buffer (see scripts/lr-sgr-pin-harness.c) and diff
48+# every A[k]/B[k] tap against a from-scratch recompute -- the missing
49+# half of r6's 9-tap cross-check. No behaviour change (only linkage).
41 #50 #
42 # Idempotent: re-running is a no-op. Rebuild afterwards with51 # Idempotent: re-running is a no-op. Rebuild afterwards with
43 # ninja -C ~/.cache/aom-oracle/build aomdec52 # ninja -C ~/.cache/aom-oracle/build aomdec
@@ -458,3 +467,24 @@ s = s.replace(old, new, 1)
458 open(path, "w").write(s)467 open(path, "w").write(s)
459 print("palette map[0] instrumented")468 print("palette map[0] instrumented")
460 PYP0469 PYP0
470+
471+# --- rung 9: export calculate_intermediate_result for a direct harness call
472+I="$SRC/av1/common/restoration.c"
473+[ -f "$I" ] || { echo "no oracle source at $I" >&2; exit 1; }
474+
475+python3 - "$I" <<'PYA'
476+import sys
477+path = sys.argv[1]
478+s = open(path).read()
479+if "/* EC_INSTRUMENTED_AB */" in s:
480+ print("calculate_intermediate_result already exported (no-op)")
481+ sys.exit(0)
482+
483+old = """static void calculate_intermediate_result(int32_t *dgd, int width, int height,"""
484+new = """/* EC_INSTRUMENTED_AB */
485+void calculate_intermediate_result(int32_t *dgd, int width, int height,"""
486+assert old in s, "calculate_intermediate_result signature moved"
487+s = s.replace(old, new, 1)
488+open(path, "w").write(s)
489+print("calculate_intermediate_result exported")
490+PYA
scripts/lr-sgr-pin-harness.cadded+89 -0
@@ -0,0 +1,89 @@
1+#include <stdio.h>
2+#include <stdint.h>
3+#include <stdlib.h>
4+
5+extern int av1_apply_selfguided_restoration_c(
6+ const uint8_t *dat8, int width, int height, int stride, int eps,
7+ const int *xqd, uint8_t *dst8, int dst_stride, int32_t *tmpbuf,
8+ int bit_depth, int highbd);
9+extern int av1_selfguided_restoration_c(const uint8_t *dgd8, int width,
10+ int height, int dgd_stride,
11+ int32_t *flt0, int32_t *flt1,
12+ int flt_stride, int sgr_params_idx,
13+ int bit_depth, int highbd);
14+// Exported by scripts/instrument-aom-oracle.sh's rung 6 (normally `static`
15+// in restoration.c) so this harness can get real per-tap A[]/B[] instead of
16+// only the combined flt0/flt1 -- the missing half of r6's 9-tap cross-check.
17+extern void calculate_intermediate_result(int32_t *dgd, int width, int height,
18+ int dgd_stride, int bit_depth,
19+ int sgr_params_idx, int radius_idx,
20+ int pass, int32_t *A, int32_t *B);
21+
22+#define SGRPROJ_BORDER_VERT 3
23+#define SGRPROJ_BORDER_HORZ 3
24+
25+int main(void) {
26+ const int bw = 102, bh = 10;
27+ // real libaom splits stripe_width into RESTORATION_PROC_UNIT_SIZE=64
28+ // chunks (sgrproj_filter_stripe's `for j += procunit_width` loop) --
29+ // av1_apply_selfguided_restoration_c's internal fixed-size arrays are
30+ // sized for that max, so replicate the chunking (target col=6 is in
31+ // the first 64-wide chunk).
32+ const int w = 64, h = 4;
33+ uint8_t *buf = malloc(bw * bh);
34+ FILE *f = fopen("/tmp/lr_full.bin", "rb");
35+ if (!f) { perror("open"); return 1; }
36+ if (fread(buf, 1, bw * bh, f) != (size_t)(bw * bh)) { fprintf(stderr, "short read\n"); return 1; }
37+ fclose(f);
38+
39+ const uint8_t *dgd8 = buf + 3 * bw + 3; // logical (0,0)
40+ int xqd[2] = { -16, -32 };
41+ uint8_t dst[w * h];
42+ // flt1 = tmpbuf + RESTORATION_UNITPELS_MAX (~152100); undersizing this
43+ // segfaults inside av1_apply_selfguided_restoration_c.
44+ static int32_t tmpbuf[2 * 400 * 400];
45+
46+ int ret = av1_apply_selfguided_restoration_c(dgd8, w, h, bw, /*eps=*/6, xqd,
47+ dst, w, tmpbuf, 8, 0);
48+ printf("ret=%d\n", ret);
49+ // target pixel: row i=1, col j=6
50+ printf("out[1][6] = %d\n", dst[1 * w + 6]);
51+ printf("dgd[1][6] = %d\n", dgd8[1 * bw + 6]);
52+
53+ static int32_t flt0[400 * 400], flt1[400 * 400];
54+ int r2 = av1_selfguided_restoration_c(dgd8, w, h, bw, flt0, flt1, w, 6, 8, 0);
55+ printf("selfguided ret=%d flt0[1][6]=%d flt1[1][6]=%d\n", r2, flt0[1 * w + 6],
56+ flt1[1 * w + 6]);
57+
58+ // --- rung 6: real per-tap A[]/B[] ground truth for the dense (r1) arm ---
59+ // Replicate av1_selfguided_restoration_c's own uint8->int32 border-extend
60+ // copy (that function's `dgd32` setup, restoration.c) so
61+ // calculate_intermediate_result sees exactly the same input it would from
62+ // the real call path above.
63+ const int dgd32_stride = w + 2 * SGRPROJ_BORDER_HORZ;
64+ static int32_t dgd32_buf[(64 + 6) * (4 + 6)];
65+ int32_t *dgd32 = dgd32_buf + dgd32_stride * SGRPROJ_BORDER_VERT + SGRPROJ_BORDER_HORZ;
66+ for (int i = -SGRPROJ_BORDER_VERT; i < h + SGRPROJ_BORDER_VERT; ++i)
67+ for (int j = -SGRPROJ_BORDER_HORZ; j < w + SGRPROJ_BORDER_HORZ; ++j)
68+ dgd32[i * dgd32_stride + j] = dgd8[i * bw + j];
69+
70+ const int width_ext = w + 2 * SGRPROJ_BORDER_HORZ;
71+ const int buf_stride = ((width_ext + 3) & ~3) + 16;
72+ static int32_t A_[2 * 400 * 400], B_[2 * 400 * 400];
73+ // radius_idx=1 (dense/r1 arm), pass=0 (every row, matches
74+ // selfguided_restoration_internal's own call).
75+ calculate_intermediate_result(dgd32, w, h, dgd32_stride, /*bit_depth=*/8,
76+ /*sgr_params_idx=*/6, /*radius_idx=*/1,
77+ /*pass=*/0, A_, B_);
78+ int32_t *A = A_ + SGRPROJ_BORDER_VERT * buf_stride + SGRPROJ_BORDER_HORZ;
79+ int32_t *B = B_ + SGRPROJ_BORDER_VERT * buf_stride + SGRPROJ_BORDER_HORZ;
80+ const int ti = 1, tj = 6;
81+ const char *names[9] = { "c", "u", "d", "l", "r", "ul", "ur", "dl", "dr" };
82+ const int di[9] = { 0, -1, 1, 0, 0, -1, -1, 1, 1 };
83+ const int dj[9] = { 0, 0, 0, -1, 1, -1, 1, -1, 1 };
84+ for (int t = 0; t < 9; ++t) {
85+ int k = (ti + di[t]) * buf_stride + (tj + dj[t]);
86+ printf("real_ab %s = (%d,%d)\n", names[t], A[k], B[k]);
87+ }
88+ return 0;
89+}