forge
Explore
Log in

Don't you dare go Hollow

merge main into lane-palette: multi-tile key-frame decode, chroma smooth/paeth, CDEF index reads

Browse files at this commit

7b81e308b3584aceb20608f1682a475d5f03168eAhmet Kaan GümüşParent: 51844cce7ae36e
Resolved six decode.rs conflicts (Neighbours' palette fields + main's
tile-origin fields coexist on the struct/constructor; read_intra_mode
gained both the palette ctx/cache param and main's mi_r/mi_c param,
updated at both call sites; PlaneBuf::reconstruct keeps the palette-buf
override + filter_intra branch and now threads real smooth_neighbor
instead of a hardcoded false) and one gate_coverage.rs conflict
(NEVER_EXERCISED = enable-intrabc only: main's cdef/chroma lanes already
retired enable-cdef/paeth-intra/smooth-intra, this lane's own real
palette gate already retired enable-palette). Added the two refusal
strings the merge introduced (palette-Y pixel-mismatch refusal, split-
luma-transform-under-palette refusal) to refusal_inventory.rs's pinned
list -- suite failed once on the missing one, fixed, green after.

EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib: 244 passed, 0
failed, 17 ignored.

25 changed files +3473 -104

crates/ec-av1/examples/decode_probe.rsadded+38 -0
@@ -0,0 +1,38 @@
1+//! Where does a real stream stop? Decode one AV1 file and print the answer.
2+//!
3+//! The gates in [`ec_av1::stream`] each pin one capability against one encoder
4+//! recipe. This asks the complementary question -- given a stream someone
5+//! actually produced, which refusal comes first -- and it is how the refusal
6+//! distribution in commit 2be815f was measured rather than reasoned about:
7+//!
8+//! ```text
9+//! aomenc --codec=av1 --obu -o s.obu --passes=1 --cpu-used=4 --limit=4 in.y4m
10+//! cargo run -p ec-av1 --example decode_probe -- s.obu
11+//! ```
12+//!
13+//! Note `--obu`: [`ec_av1::stream::decode_stream`] takes a raw OBU stream, and
14+//! an IVF file decodes as zero frames rather than as an error.
15+//!
16+//! That run is also what disproved three refusal strings claiming an encoder
17+//! never writes a case it demonstrably writes, so this is a first-class
18+//! instrument, not a scratch file.
19+fn main() {
20+ let Some(path) = std::env::args().nth(1) else {
21+ eprintln!("usage: decode_probe <stream.obu>");
22+ std::process::exit(2);
23+ };
24+ let data = match std::fs::read(&path) {
25+ Ok(data) => data,
26+ Err(e) => {
27+ eprintln!("{path}: {e}");
28+ std::process::exit(2);
29+ }
30+ };
31+ match ec_av1::stream::decode_stream(&data) {
32+ Ok(frames) if frames.is_empty() => {
33+ println!("OK but EMPTY: no frames -- is {path} an IVF rather than a raw OBU stream?");
34+ }
35+ Ok(frames) => println!("OK: {} frames decoded", frames.len()),
36+ Err(e) => println!("REFUSED: {e}"),
37+ }
38+}
crates/ec-av1/src/decode.rsmodified+572 -74
@@ -21,7 +21,7 @@
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, LoopFilterParams};24+use ec_av1_syntax::{CdefParams, LoopFilterParams, TileInfo};
25 use ec_core::{Error, Result};25 use ec_core::{Error, Result};
26 26
27 use crate::cdf;27 use crate::cdf;
@@ -66,6 +66,117 @@ pub(crate) fn filter_intra_hits() -> usize {
66 FILTER_INTRA_HITS.with(|c| c.get())66 FILTER_INTRA_HITS.with(|c| c.get())
67 }67 }
68 68
69+// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
70+// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
71+// frame-level flag through the recursive block decode -- `0` (the default)
72+// makes every call a true no-op, matching every existing gate stream's
73+// `cdef_bits == 0` behaviour exactly.
74+thread_local! {
75+ static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
76+}
77+// Whether this superblock's single CDEF unit (this decoder has no 128x128
78+// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
79+// read -- reset to `false` at the top of each superblock in the two tile
80+// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
81+thread_local! {
82+ static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
83+}
84+// Number of superblock columns in the current tile's grid, so
85+// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
86+// [`CDEF_IDX_GRID`].
87+thread_local! {
88+ static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
89+}
90+// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
91+// which of the header's `1 << cdef.bits` strength pairs applies to that
92+// superblock's samples.
93+thread_local! {
94+ static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
95+}
96+// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
97+// has read, across every call on the current thread -- the gate's proof that a
98+// `cdef_bits > 0` stream actually reached the new reader rather than every
99+// superblock coincidentally being all-skip.
100+thread_local! {
101+ static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
102+}
103+
104+/// Current value of [`CDEF_IDX_HITS`].
105+pub(crate) fn cdef_idx_hits() -> usize {
106+ CDEF_IDX_HITS.with(|c| c.get())
107+}
108+
109+/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
110+/// after `skip` is known at every block-decode call site. A no-op at
111+/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
112+/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
113+/// `allow_intrabc`, so neither needs a separate check here. Reads once per
114+/// superblock, at the first non-skip block.
115+fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
116+ let bits = CDEF_BITS.with(|c| c.get());
117+ if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
118+ return;
119+ }
120+ let idx = dec.literal(u32::from(bits)) as u8;
121+ CDEF_TRANSMITTED.with(|c| c.set(true));
122+ CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
123+ let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
124+ let sb_cols = CDEF_SB_COLS.with(|c| c.get());
125+ if sb_cols > 0 {
126+ CDEF_IDX_GRID.with(|g| {
127+ let mut g = g.borrow_mut();
128+ let i = sb_r * sb_cols + sb_c;
129+ if i < g.len() {
130+ g[i] = idx;
131+ }
132+ });
133+ }
134+}
135+
136+// How many key-frame luma blocks resolved `smooth_neighbor` (spec
137+// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
138+// counter, proving a stream actually put a directional block next to a
139+// smooth-predicted neighbour rather than every block reading the (previously
140+// hardcoded `false`) edge-filter strength bucket unchanged.
141+thread_local! {
142+ static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
143+ const { std::cell::Cell::new(0) };
144+}
145+
146+/// Current value of [`SMOOTH_LUMA_HITS`].
147+pub(crate) fn smooth_luma_hits() -> usize {
148+ SMOOTH_LUMA_HITS.with(|c| c.get())
149+}
150+
151+// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
152+// across every call on the current thread -- lane-chroma r3's own before/after
153+// counter, proving a stream actually exercised chroma's smooth/paeth
154+// predictor (the previously-refused round-2 gap) rather than every block
155+// landing on DC/CFL/directional.
156+thread_local! {
157+ static SMOOTH_UV_HITS: std::cell::Cell<usize> =
158+ const { std::cell::Cell::new(0) };
159+}
160+
161+/// Current value of [`SMOOTH_UV_HITS`].
162+pub(crate) fn smooth_uv_hits() -> usize {
163+ SMOOTH_UV_HITS.with(|c| c.get())
164+}
165+
166+// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
167+// full superblock walk over, across every call on the current thread --
168+// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
169+// multi-tile stream must prove more than one tile actually fired, not just
170+// that the stream carried tile_info.cols > 1.
171+thread_local! {
172+ static TILE_HITS: std::cell::Cell<usize> =
173+ const { std::cell::Cell::new(0) };
174+}
175+/// Current value of [`TILE_HITS`].
176+pub(crate) fn tile_hits() -> usize {
177+ TILE_HITS.with(|c| c.get())
178+}
179+
69 // How many 4-pixel deblocking edge groups [`edge_params`] has actually180 // How many 4-pixel deblocking edge groups [`edge_params`] has actually
70 // selected for filtering, across every call on the current thread -- the same181 // selected for filtering, across every call on the current thread -- the same
71 // before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream182 // before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
@@ -103,7 +214,7 @@ pub(crate) fn tx_depth_hits() -> usize {
103 214
104 // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`215 // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
105 // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every216 // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
106-// call in the process -- the same before/after counter pattern as217+// call on the current thread -- the same before/after counter pattern as
107 // [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split218 // [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
108 // `eob_pt`/1D-neighbour context path rather than every block coincidentally219 // `eob_pt`/1D-neighbour context path rather than every block coincidentally
109 // landing on `DCT_DCT`.220 // landing on `DCT_DCT`.
@@ -977,6 +1088,13 @@ fn default_intra_tx_type(mode: u8) -> TxType {
977 }1088 }
978 }1089 }
979 1090
1091+/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
1092+/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
1093+/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
1094+fn is_smooth_mode(mode: usize) -> bool {
1095+ (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
1096+}
1097+
980 fn read_coeffs(1098 fn read_coeffs(
981 dec: &mut SymbolDecoder,1099 dec: &mut SymbolDecoder,
982 coding: &mut TxbTables,1100 coding: &mut TxbTables,
@@ -1268,6 +1386,17 @@ struct Neighbours {
1268 left: Vec<[Neighbour; 3]>,1386 left: Vec<[Neighbour; 3]>,
1269 above_mode: Vec<usize>,1387 above_mode: Vec<usize>,
1270 left_mode: Vec<usize>,1388 left_mode: Vec<usize>,
1389+ /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
1390+ /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
1391+ /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
1392+ /// luma one -- the same block can (and often does) code a different
1393+ /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
1394+ /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
1395+ /// within-block neighbour finer than this grid) is luma-only -- a known,
1396+ /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
1397+ /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
1398+ above_uv_mode: Vec<usize>,
1399+ left_uv_mode: Vec<usize>,
1271 above_side: Vec<usize>,1400 above_side: Vec<usize>,
1272 left_side: Vec<usize>,1401 left_side: Vec<usize>,
1273 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)1402 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
@@ -1364,6 +1493,15 @@ struct Neighbours {
1364 left_palette_size: Vec<usize>,1493 left_palette_size: Vec<usize>,
1365 above_palette_colors: Vec<[u16; 8]>,1494 above_palette_colors: Vec<[u16; 8]>,
1366 left_palette_colors: Vec<[u16; 8]>,1495 left_palette_colors: Vec<[u16; 8]>,
1496+ /// This tile's own top-left corner, in 4x4 mode-info units (spec
1497+ /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
1498+ /// neighbour" check compares against this instead of literal `0`, since a
1499+ /// block at the tile's own top/left edge has no usable neighbour even
1500+ /// though a decoded block sits there in the picture (spec `decode_tile`'s
1501+ /// per-tile `clear_above_context`/`left_available`/`up_available`).
1502+ /// `0` for a single-tile frame, matching every existing caller exactly.
1503+ tile_row0_mi: usize,
1504+ tile_col0_mi: usize,
1367 }1505 }
1368 1506
1369 impl Neighbours {1507 impl Neighbours {
@@ -1375,6 +1513,8 @@ impl Neighbours {
1375 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],1513 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
1376 above_mode: vec![DC_PRED; cols],1514 above_mode: vec![DC_PRED; cols],
1377 left_mode: vec![DC_PRED; rows],1515 left_mode: vec![DC_PRED; rows],
1516+ above_uv_mode: vec![DC_PRED; cols],
1517+ left_uv_mode: vec![DC_PRED; rows],
1378 above_side: vec![SB; cols],1518 above_side: vec![SB; cols],
1379 left_side: vec![SB; rows],1519 left_side: vec![SB; rows],
1380 above_side_mi: vec![SB; cols * (SUB / MI)],1520 above_side_mi: vec![SB; cols * (SUB / MI)],
@@ -1406,6 +1546,40 @@ impl Neighbours {
1406 left_palette_size: vec![0; rows],1546 left_palette_size: vec![0; rows],
1407 above_palette_colors: vec![[0u16; 8]; cols],1547 above_palette_colors: vec![[0u16; 8]; cols],
1408 left_palette_colors: vec![[0u16; 8]; rows],1548 left_palette_colors: vec![[0u16; 8]; rows],
1549+ tile_row0_mi: 0,
1550+ tile_col0_mi: 0,
1551+ }
1552+ }
1553+
1554+ /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
1555+ /// tile's own column span (`col1_mi` exclusive), plus recording
1556+ /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
1557+ /// availability check below. Left context resets every superblock row
1558+ /// regardless of tile ([`Self::start_row`], already called once per SB
1559+ /// row by every caller) so it needs no tile-specific reset here.
1560+ fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
1561+ self.tile_row0_mi = row0_mi;
1562+ self.tile_col0_mi = col0_mi;
1563+ let end = col1_mi.min(self.above.len());
1564+ for i in col0_mi.min(end)..end {
1565+ self.above[i] = Default::default();
1566+ self.above_side_mi[i] = SB;
1567+ }
1568+ let (sc0, sc1) = (
1569+ col0_mi / (SUB / MI),
1570+ (col1_mi / (SUB / MI)).min(self.above_mode.len()),
1571+ );
1572+ for i in sc0.min(sc1)..sc1 {
1573+ self.above_mode[i] = DC_PRED;
1574+ self.above_side[i] = SB;
1575+ self.above_skip[i] = false;
1576+ self.above_skip_mode[i] = false;
1577+ self.above_inter[i] = false;
1578+ self.above_ref[i] = -1;
1579+ self.above_ref1[i] = None;
1580+ self.above_comp_group_idx[i] = 0;
1581+ self.above_compound_idx[i] = 0;
1582+ self.above_filter[i] = [3u8; 2];
1409 }1583 }
1410 }1584 }
1411 1585
@@ -1562,8 +1736,8 @@ impl Neighbours {
1562 /// with an absent neighbour contributing 0. The mi grid is per tile, so1736 /// with an absent neighbour contributing 0. The mi grid is per tile, so
1563 /// row/column 0 is a tile edge and has no neighbour on that axis.1737 /// row/column 0 is a tile edge and has no neighbour on that axis.
1564 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {1738 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
1565- usize::from(mi_r > 0 && self.skip_at(mi_r - 1, mi_c))1739+ usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
1566- + usize::from(mi_c > 0 && self.skip_at(mi_r, mi_c - 1))1740+ + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
1567 }1741 }
1568 1742
1569 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {1743 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
@@ -1580,6 +1754,7 @@ impl Neighbours {
1580 fn start_row(&mut self) {1754 fn start_row(&mut self) {
1581 self.left.iter_mut().for_each(|l| *l = Default::default());1755 self.left.iter_mut().for_each(|l| *l = Default::default());
1582 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);1756 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
1757+ self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
1583 self.left_side.iter_mut().for_each(|s| *s = SB);1758 self.left_side.iter_mut().for_each(|s| *s = SB);
1584 self.left_side_mi.iter_mut().for_each(|s| *s = SB);1759 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
1585 self.left_skip.iter_mut().for_each(|s| *s = false);1760 self.left_skip.iter_mut().for_each(|s| *s = false);
@@ -1811,8 +1986,15 @@ impl Neighbours {
1811 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to1986 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
1812 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,1987 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
1813 /// not from this block's own side).1988 /// not from this block's own side).
1814- fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {1989+ fn record(
1815- self.record_rect(at, side, side, mode, grids);1990+ &mut self,
1991+ at: (usize, usize),
1992+ side: usize,
1993+ mode: usize,
1994+ uv_mode: usize,
1995+ grids: &[Vec<i32>; 3],
1996+ ) {
1997+ self.record_rect(at, side, side, mode, uv_mode, grids);
1816 }1998 }
1817 1999
1818 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in2000 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
@@ -1826,15 +2008,18 @@ impl Neighbours {
1826 w: usize,2008 w: usize,
1827 h: usize,2009 h: usize,
1828 mode: usize,2010 mode: usize,
2011+ uv_mode: usize,
1829 grids: &[Vec<i32>; 3],2012 grids: &[Vec<i32>; 3],
1830 ) {2013 ) {
1831 let (r, c) = at;2014 let (r, c) = at;
1832 for cell in 0..w / SUB {2015 for cell in 0..w / SUB {
1833 self.above_mode[c + cell] = mode;2016 self.above_mode[c + cell] = mode;
2017+ self.above_uv_mode[c + cell] = uv_mode;
1834 self.above_side[c + cell] = w;2018 self.above_side[c + cell] = w;
1835 }2019 }
1836 for cell in 0..h / SUB {2020 for cell in 0..h / SUB {
1837 self.left_mode[r + cell] = mode;2021 self.left_mode[r + cell] = mode;
2022+ self.left_uv_mode[r + cell] = uv_mode;
1838 self.left_side[r + cell] = h;2023 self.left_side[r + cell] = h;
1839 }2024 }
1840 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);2025 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);
@@ -1933,12 +2118,15 @@ impl Neighbours {
1933 at: (usize, usize),2118 at: (usize, usize),
1934 side: usize,2119 side: usize,
1935 mode: usize,2120 mode: usize,
2121+ uv_mode: usize,
1936 chroma_grids: [&[i32]; 2],2122 chroma_grids: [&[i32]; 2],
1937 ) {2123 ) {
1938 let (r, c) = at;2124 let (r, c) = at;
1939 for cell in 0..side / SUB {2125 for cell in 0..side / SUB {
1940 self.above_mode[c + cell] = mode;2126 self.above_mode[c + cell] = mode;
1941 self.left_mode[r + cell] = mode;2127 self.left_mode[r + cell] = mode;
2128+ self.above_uv_mode[c + cell] = uv_mode;
2129+ self.left_uv_mode[r + cell] = uv_mode;
1942 self.above_side[c + cell] = side;2130 self.above_side[c + cell] = side;
1943 self.left_side[r + cell] = side;2131 self.left_side[r + cell] = side;
1944 }2132 }
@@ -2214,6 +2402,8 @@ fn read_intra_mode_rect(
2214 enable_filter_intra: bool,2402 enable_filter_intra: bool,
2215 skip_ctx: usize,2403 skip_ctx: usize,
2216 allow_screen_content_tools: bool,2404 allow_screen_content_tools: bool,
2405+ mi_r: usize,
2406+ mi_c: usize,
2217 ) -> Result<(2407 ) -> Result<(
2218 bool,2408 bool,
2219 usize,2409 usize,
@@ -2234,6 +2424,7 @@ fn read_intra_mode_rect(
2234 ));2424 ));
2235 }2425 }
2236 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;2426 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
2427+ maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
2237 let above_ctx = INTRA_MODE_CTX[above_mode];2428 let above_ctx = INTRA_MODE_CTX[above_mode];
2238 let left_ctx = INTRA_MODE_CTX[left_mode];2429 let left_ctx = INTRA_MODE_CTX[left_mode];
2239 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);2430 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
@@ -2253,7 +2444,7 @@ fn read_intra_mode_rect(
2253 None2444 None
2254 };2445 };
2255 if (9..=12).contains(&uv_mode) {2446 if (9..=12).contains(&uv_mode) {
2256- return Err(unsupported("a smooth or paeth chroma mode (round 2)"));2447+ SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
2257 }2448 }
2258 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {2449 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
2259 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));2450 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
@@ -2307,8 +2498,8 @@ fn tx_size_context_rect(
2307 own_w: usize,2498 own_w: usize,
2308 own_h: usize,2499 own_h: usize,
2309 ) -> usize {2500 ) -> usize {
2310- let above = mi_r > 0 && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;2501+ let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
2311- let left = mi_c > 0 && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;2502+ let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
2312 usize::from(above) + usize::from(left)2503 usize::from(above) + usize::from(left)
2313 }2504 }
2314 2505
@@ -2375,7 +2566,19 @@ fn decode_block_rect(
2375 enable_filter_intra,2566 enable_filter_intra,
2376 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),2567 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
2377 allow_screen_content_tools,2568 allow_screen_content_tools,
2569+ r * (SUB / MI),
2570+ c * (SUB / MI),
2378 )?;2571 )?;
2572+ let smooth_neighbor =
2573+ is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]);
2574+ if smooth_neighbor {
2575+ SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
2576+ }
2577+ // lane-chroma r3: chroma's own edge-filter-strength neighbour check
2578+ // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
2579+ // `uv_mode`, not the luma one.
2580+ let smooth_neighbor_uv =
2581+ is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
2379 if filter_intra.is_some() {2582 if filter_intra.is_some() {
2380 // `predict_filter_intra` (spec 7.11.2.3) is square-only in this2583 // `predict_filter_intra` (spec 7.11.2.3) is square-only in this
2381 // decoder (`assert_eq!(dst.len(), side*side)`) -- a real symbol was2584 // decoder (`assert_eq!(dst.len(), side*side)`) -- a real symbol was
@@ -2441,6 +2644,7 @@ fn decode_block_rect(
2441 &vec![0i32; bw * bh],2644 &vec![0i32; bw * bh],
2442 None,2645 None,
2443 filter_intra,2646 filter_intra,
2647+ smooth_neighbor,
2444 );2648 );
2445 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));2649 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
2446 u.reconstruct_rect(2650 u.reconstruct_rect(
@@ -2454,6 +2658,7 @@ fn decode_block_rect(
2454 &vec![0i32; chroma_w * chroma_h],2658 &vec![0i32; chroma_w * chroma_h],
2455 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),2659 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2456 None,2660 None,
2661+ smooth_neighbor_uv,
2457 );2662 );
2458 v.reconstruct_rect(2663 v.reconstruct_rect(
2459 cpx,2664 cpx,
@@ -2466,12 +2671,14 @@ fn decode_block_rect(
2466 &vec![0i32; chroma_w * chroma_h],2671 &vec![0i32; chroma_w * chroma_h],
2467 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),2672 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2468 None,2673 None,
2674+ smooth_neighbor_uv,
2469 );2675 );
2470 neighbours.record_rect(2676 neighbours.record_rect(
2471 at,2677 at,
2472 bw,2678 bw,
2473 bh,2679 bh,
2474 mode,2680 mode,
2681+ uv_predict_mode,
2475 &[2682 &[
2476 vec![0i32; bw * bh],2683 vec![0i32; bw * bh],
2477 vec![0i32; chroma_w * chroma_h],2684 vec![0i32; chroma_w * chroma_h],
@@ -2559,6 +2766,7 @@ fn decode_block_rect(
2559 &luma_residual,2766 &luma_residual,
2560 None,2767 None,
2561 filter_intra,2768 filter_intra,
2769+ smooth_neighbor,
2562 );2770 );
2563 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));2771 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
2564 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);2772 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
@@ -2597,6 +2805,7 @@ fn decode_block_rect(
2597 &u_residual,2805 &u_residual,
2598 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),2806 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
2599 None,2807 None,
2808+ smooth_neighbor_uv,
2600 );2809 );
2601 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);2810 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
2602 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);2811 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
@@ -2634,8 +2843,9 @@ fn decode_block_rect(
2634 &v_residual,2843 &v_residual,
2635 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),2844 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
2636 None,2845 None,
2846+ smooth_neighbor_uv,
2637 );2847 );
2638- neighbours.record_rect(at, bw, bh, mode, &[luma_levels, u_levels, v_levels]);2848+ neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
2639 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));2849 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
2640 }2850 }
2641 }2851 }
@@ -2657,6 +2867,7 @@ fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
2657 symbol as i32 - ANGLE_DELTA_ZERO as i322867 symbol as i32 - ANGLE_DELTA_ZERO as i32
2658 }2868 }
2659 2869
2870+#[allow(clippy::too_many_arguments)]
2660 fn read_intra_mode(2871 fn read_intra_mode(
2661 dec: &mut SymbolDecoder,2872 dec: &mut SymbolDecoder,
2662 cdfs: &mut Cdfs,2873 cdfs: &mut Cdfs,
@@ -2676,6 +2887,8 @@ fn read_intra_mode(
2676 // decoder reads either way -- but refuse by name the moment it fires,2887 // decoder reads either way -- but refuse by name the moment it fires,
2677 // exactly the old behaviour.2888 // exactly the old behaviour.
2678 palette: Option<(usize, &[u16])>,2889 palette: Option<(usize, &[u16])>,
2890+ mi_r: usize,
2891+ mi_c: usize,
2679 ) -> Result<(2892 ) -> Result<(
2680 bool,2893 bool,
2681 usize,2894 usize,
@@ -2691,6 +2904,9 @@ fn read_intra_mode(
2691 if trace {2904 if trace {
2692 eprintln!("TRACE skip value={}", skip as i32);2905 eprintln!("TRACE skip value={}", skip as i32);
2693 }2906 }
2907+ // spec order (see the comment below on `read_intrabc_info`): `skip`,
2908+ // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
2909+ maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
2694 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at2910 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
2695 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before2911 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
2696 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an2912 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
@@ -2750,7 +2966,7 @@ fn read_intra_mode(
2750 // bug in that fallback this lane's own scope does not cover. Keep it2966 // bug in that fallback this lane's own scope does not cover. Keep it
2751 // refused here rather than ship a silently-wrong decode.2967 // refused here rather than ship a silently-wrong decode.
2752 if (9..=12).contains(&uv_mode) {2968 if (9..=12).contains(&uv_mode) {
2753- return Err(unsupported("a smooth or paeth chroma mode (round 2)"));2969+ SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
2754 }2970 }
2755 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the2971 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
2756 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads2972 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
@@ -2944,6 +3160,16 @@ struct PlaneBuf {
2944 /// real decoder's edge or reach reads.3160 /// real decoder's edge or reach reads.
2945 true_width: usize,3161 true_width: usize,
2946 true_height: usize,3162 true_height: usize,
3163+ /// This plane's own tile's top-left pixel origin (spec: intra prediction
3164+ /// never reaches across a tile boundary even though an earlier-decoded
3165+ /// tile's real pixels sit right there in the shared buffer) — set via
3166+ /// [`Self::set_tile_origin`] before each tile's own superblock walk,
3167+ /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
3168+ /// is threaded (the two-tile column-split stage 1 fixture's tile always
3169+ /// ends at the frame's own right/bottom edge); a non-last tile's own
3170+ /// right/bottom reach bound is still open, tracked in the report.
3171+ tile_x0: usize,
3172+ tile_y0: usize,
2947 }3173 }
2948 3174
2949 /// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/3175 /// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
@@ -2955,6 +3181,15 @@ struct PlaneBuf {
2955 type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];3181 type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
2956 3182
2957 impl PlaneBuf {3183 impl PlaneBuf {
3184+ /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
3185+ /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
3186+ /// are already in this plane's own units (luma pixels for `y`, chroma
3187+ /// pixels — halved — for `u`/`v`).
3188+ fn set_tile_origin(&mut self, x0: usize, y0: usize) {
3189+ self.tile_x0 = x0;
3190+ self.tile_y0 = y0;
3191+ }
3192+
2958 fn edges(3193 fn edges(
2959 &self,3194 &self,
2960 x: usize,3195 x: usize,
@@ -2976,14 +3211,15 @@ impl PlaneBuf {
2976 own_down3211 own_down
2977 }3212 }
2978 .min(self.height);3213 .min(self.height);
2979- let above = (y > 0 && across > x)3214+ let above = (y > self.tile_y0 && across > x)
2980 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());3215 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
2981- let left = (x > 0 && down > y).then(|| {3216+ let left = (x > self.tile_x0 && down > y).then(|| {
2982 (y..down)3217 (y..down)
2983 .map(|row| self.data[row * self.width + x - 1])3218 .map(|row| self.data[row * self.width + x - 1])
2984 .collect::<Vec<_>>()3219 .collect::<Vec<_>>()
2985 });3220 });
2986- let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]);3221+ let corner =
3222+ (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
2987 (above, left, corner)3223 (above, left, corner)
2988 }3224 }
2989 3225
@@ -3012,14 +3248,15 @@ impl PlaneBuf {
3012 own_down3248 own_down
3013 }3249 }
3014 .min(self.height);3250 .min(self.height);
3015- let above = (y > 0 && across > x)3251+ let above = (y > self.tile_y0 && across > x)
3016 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());3252 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
3017- let left = (x > 0 && down > y).then(|| {3253+ let left = (x > self.tile_x0 && down > y).then(|| {
3018 (y..down)3254 (y..down)
3019 .map(|row| self.data[row * self.width + x - 1])3255 .map(|row| self.data[row * self.width + x - 1])
3020 .collect::<Vec<_>>()3256 .collect::<Vec<_>>()
3021 });3257 });
3022- let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]);3258+ let corner =
3259+ (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
3023 (above, left, corner)3260 (above, left, corner)
3024 }3261 }
3025 3262
@@ -3039,6 +3276,7 @@ impl PlaneBuf {
3039 residual: &[i32],3276 residual: &[i32],
3040 cfl: Option<(i32, &[i32])>,3277 cfl: Option<(i32, &[i32])>,
3041 filter_intra: Option<usize>,3278 filter_intra: Option<usize>,
3279+ smooth_neighbor: bool,
3042 ) {3280 ) {
3043 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);3281 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
3044 let mut prediction = vec![0u8; bw * bh];3282 let mut prediction = vec![0u8; bw * bh];
@@ -3062,7 +3300,7 @@ impl PlaneBuf {
3062 bw,3300 bw,
3063 bh,3301 bh,
3064 enable_edge_filter,3302 enable_edge_filter,
3065- false,3303+ smooth_neighbor,
3066 &mut prediction,3304 &mut prediction,
3067 );3305 );
3068 }3306 }
@@ -3096,6 +3334,15 @@ impl PlaneBuf {
3096 residual: &[i32],3334 residual: &[i32],
3097 cfl: Option<(i32, &[i32])>,3335 cfl: Option<(i32, &[i32])>,
3098 filter_intra: Option<usize>,3336 filter_intra: Option<usize>,
3337+ // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
3338+ // libaom `get_filt_type`): true when the block's above OR left
3339+ // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
3340+ // Callers pass their own plane's neighbour-mode check
3341+ // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
3342+ // callers until a smooth/paeth `uv_mode` can reach this call at all
3343+ // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
3344+ // keeps `false` exact for chroma without this fn needing to know why.
3345+ smooth_neighbor: bool,
3099 ) {3346 ) {
3100 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)3347 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
3101 // takes priority over `predict()`/`predict_filter_intra` entirely --3348 // takes priority over `predict()`/`predict_filter_intra` entirely --
@@ -3121,13 +3368,7 @@ impl PlaneBuf {
3121 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two3368 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
3122 // dozen sites for a value that never changes mid-decode, so it3369 // dozen sites for a value that never changes mid-decode, so it
3123 // rides a thread-local instead (this decoder is single-threaded3370 // rides a thread-local instead (this decoder is single-threaded
3124- // per stream). `smooth_neighbor` (spec `get_intra_edge_filter_type`)3371+ // per stream).
3125- // is left `false`: exact for chroma here (a smooth `uv_mode` is
3126- // refused before decode reaches this call) and a corner-cut for
3127- // luma -- ceiling is one wrong filter-strength bucket on a block
3128- // whose real neighbour predicted smooth; upgrade path is
3129- // threading `Neighbours::above_mode`/`left_mode`'s
3130- // `SMOOTH_PRED..=SMOOTH_H_PRED` membership down instead of `false`.
3131 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);3372 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
3132 predict(3373 predict(
3133 mode as u8,3374 mode as u8,
@@ -3138,7 +3379,7 @@ impl PlaneBuf {
3138 side,3379 side,
3139 side,3380 side,
3140 enable_edge_filter,3381 enable_edge_filter,
3141- false,3382+ smooth_neighbor,
3142 &mut prediction,3383 &mut prediction,
3143 );3384 );
3144 }3385 }
@@ -3190,6 +3431,8 @@ fn read_plane(
3190 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours3431 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
3191 // formula below.3432 // formula below.
3192 luma_skip_ctx: Option<usize>,3433 luma_skip_ctx: Option<usize>,
3434+ // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
3435+ smooth_neighbor: bool,
3193 ) -> Result<Vec<i32>> {3436 ) -> Result<Vec<i32>> {
3194 let skip_ctx = if plane_idx == 0 {3437 let skip_ctx = if plane_idx == 0 {
3195 luma_skip_ctx.unwrap_or(0)3438 luma_skip_ctx.unwrap_or(0)
@@ -3255,6 +3498,7 @@ fn read_plane(
3255 &residual,3498 &residual,
3256 cfl,3499 cfl,
3257 filter_intra,3500 filter_intra,
3501+ smooth_neighbor,
3258 );3502 );
3259 Ok(if tx_side == side {3503 Ok(if tx_side == side {
3260 residual_grid_placeholder(&levels, side)3504 residual_grid_placeholder(&levels, side)
@@ -3317,6 +3561,8 @@ fn decode_block(
3317 allow_screen_content_tools,3561 allow_screen_content_tools,
3318 allow_intrabc,3562 allow_intrabc,
3319 Some((palette_ctx, &palette_cache)),3563 Some((palette_ctx, &palette_cache)),
3564+ r * (SUB / MI),
3565+ c * (SUB / MI),
3320 )?;3566 )?;
3321 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`3567 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
3322 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the3568 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
@@ -3326,6 +3572,13 @@ fn decode_block(
3326 } else {3572 } else {
3327 uv_mode3573 uv_mode
3328 };3574 };
3575+ let smooth_neighbor =
3576+ is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]);
3577+ if smooth_neighbor {
3578+ SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
3579+ }
3580+ let smooth_neighbor_uv =
3581+ is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
3329 if std::env::var_os("EC_AV1_TRACE").is_some() {3582 if std::env::var_os("EC_AV1_TRACE").is_some() {
3330 eprintln!(3583 eprintln!(
3331 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \3584 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
@@ -3384,6 +3637,7 @@ fn decode_block(
3384 &vec![0i32; side * side],3637 &vec![0i32; side * side],
3385 None,3638 None,
3386 filter_intra,3639 filter_intra,
3640+ smooth_neighbor,
3387 );3641 );
3388 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));3642 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3389 u.reconstruct(3643 u.reconstruct(
@@ -3396,6 +3650,7 @@ fn decode_block(
3396 &vec![0i32; chroma_side * chroma_side],3650 &vec![0i32; chroma_side * chroma_side],
3397 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),3651 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3398 None,3652 None,
3653+ smooth_neighbor_uv,
3399 );3654 );
3400 v.reconstruct(3655 v.reconstruct(
3401 cpx,3656 cpx,
@@ -3407,11 +3662,12 @@ fn decode_block(
3407 &vec![0i32; chroma_side * chroma_side],3662 &vec![0i32; chroma_side * chroma_side],
3408 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),3663 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3409 None,3664 None,
3665+ smooth_neighbor_uv,
3410 );3666 );
3411 let luma_grid = vec![0i32; side * side];3667 let luma_grid = vec![0i32; side * side];
3412 let u_grid = vec![0i32; chroma_side * chroma_side];3668 let u_grid = vec![0i32; chroma_side * chroma_side];
3413 let v_grid = vec![0i32; chroma_side * chroma_side];3669 let v_grid = vec![0i32; chroma_side * chroma_side];
3414- neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);3670+ neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
3415 } else if !tx_select || logical_tx == side {3671 } else if !tx_select || logical_tx == side {
3416 // A single luma transform unit -- the old path, unchanged (including3672 // A single luma transform unit -- the old path, unchanged (including
3417 // the 64x64 corner case, `logical_tx == side == 64` with3673 // the 64x64 corner case, `logical_tx == side == 64` with
@@ -3437,6 +3693,7 @@ fn decode_block(
3437 None,3693 None,
3438 filter_intra,3694 filter_intra,
3439 None,3695 None,
3696+ smooth_neighbor,
3440 )?;3697 )?;
3441 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));3698 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
3442 let u_grid = read_plane(3699 let u_grid = read_plane(
@@ -3459,6 +3716,7 @@ fn decode_block(
3459 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),3716 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3460 None,3717 None,
3461 None,3718 None,
3719+ smooth_neighbor_uv,
3462 )?;3720 )?;
3463 if std::env::var_os("EC_AV1_TRACE").is_some() {3721 if std::env::var_os("EC_AV1_TRACE").is_some() {
3464 eprintln!(3722 eprintln!(
@@ -3486,8 +3744,9 @@ fn decode_block(
3486 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),3744 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3487 None,3745 None,
3488 None,3746 None,
3747+ smooth_neighbor_uv,
3489 )?;3748 )?;
3490- neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);3749+ neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
3491 } else {3750 } else {
3492 // Several luma transform units, raster order (spec3751 // Several luma transform units, raster order (spec
3493 // `transform_block`'s loop): the block's resolved transform is3752 // `transform_block`'s loop): the block's resolved transform is
@@ -3531,6 +3790,7 @@ fn decode_block(
3531 None,3790 None,
3532 filter_intra,3791 filter_intra,
3533 Some(tu_skip_ctx),3792 Some(tu_skip_ctx),
3793+ smooth_neighbor,
3534 )?;3794 )?;
3535 if std::env::var_os("EC_AV1_TRACE").is_some() {3795 if std::env::var_os("EC_AV1_TRACE").is_some() {
3536 eprintln!(3796 eprintln!(
@@ -3565,6 +3825,7 @@ fn decode_block(
3565 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),3825 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3566 None,3826 None,
3567 None,3827 None,
3828+ smooth_neighbor_uv,
3568 )?;3829 )?;
3569 let v_grid = read_plane(3830 let v_grid = read_plane(
3570 dec,3831 dec,
@@ -3586,8 +3847,9 @@ fn decode_block(
3586 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),3847 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3587 None,3848 None,
3588 None,3849 None,
3850+ smooth_neighbor_uv,
3589 )?;3851 )?;
3590- neighbours.record_split_luma(at, side, mode, [&u_grid, &v_grid]);3852+ neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&u_grid, &v_grid]);
3591 }3853 }
3592 // Unconditional, `size == 0` for a non-palette block: clears any stale3854 // Unconditional, `size == 0` for a non-palette block: clears any stale
3593 // neighbour palette state the same way [`Neighbours::record`] always3855 // neighbour palette state the same way [`Neighbours::record`] always
@@ -3646,6 +3908,12 @@ fn decode_leaf8(
3646 left_mode = pmode;3908 left_mode = pmode;
3647 }3909 }
3648 }3910 }
3911+ // See [`PlaneBuf::reconstruct`]'s doc: chroma stays `false` (exact) until
3912+ // a smooth/paeth `uv_mode` can reach decode at all.
3913+ let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
3914+ if smooth_neighbor {
3915+ SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
3916+ }
3649 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec3917 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
3650 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other3918 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
3651 // `decode_block` caller at 16x16 and up.3919 // `decode_block` caller at 16x16 and up.
@@ -3662,6 +3930,8 @@ fn decode_leaf8(
3662 allow_screen_content_tools,3930 allow_screen_content_tools,
3663 allow_intrabc,3931 allow_intrabc,
3664 None,3932 None,
3933+ leaf_mi.0,
3934+ leaf_mi.1,
3665 )?;3935 )?;
3666 let uv_predict_mode = if uv_mode == UV_CFL_PRED {3936 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3667 DC_PRED3937 DC_PRED
@@ -3693,6 +3963,7 @@ fn decode_leaf8(
3693 &vec![0i32; 64],3963 &vec![0i32; 64],
3694 None,3964 None,
3695 filter_intra,3965 filter_intra,
3966+ smooth_neighbor,
3696 );3967 );
3697 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));3968 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
3698 u.reconstruct(3969 u.reconstruct(
@@ -3705,6 +3976,7 @@ fn decode_leaf8(
3705 &vec![0i32; 16],3976 &vec![0i32; 16],
3706 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),3977 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3707 None,3978 None,
3979+ false,
3708 );3980 );
3709 v.reconstruct(3981 v.reconstruct(
3710 cpx,3982 cpx,
@@ -3716,6 +3988,7 @@ fn decode_leaf8(
3716 &vec![0i32; 16],3988 &vec![0i32; 16],
3717 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),3989 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3718 None,3990 None,
3991+ false,
3719 );3992 );
3720 luma_grid = vec![0i32; 64];3993 luma_grid = vec![0i32; 64];
3721 u_grid = vec![0i32; 16];3994 u_grid = vec![0i32; 16];
@@ -3746,6 +4019,7 @@ fn decode_leaf8(
3746 None,4019 None,
3747 filter_intra,4020 filter_intra,
3748 None,4021 None,
4022+ smooth_neighbor,
3749 )?;4023 )?;
3750 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));4024 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
3751 u_grid = read_plane(4025 u_grid = read_plane(
@@ -3768,6 +4042,7 @@ fn decode_leaf8(
3768 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),4042 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3769 None,4043 None,
3770 None,4044 None,
4045+ false,
3771 )?;4046 )?;
3772 v_grid = read_plane(4047 v_grid = read_plane(
3773 dec,4048 dec,
@@ -3789,6 +4064,7 @@ fn decode_leaf8(
3789 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),4064 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3790 None,4065 None,
3791 None,4066 None,
4067+ false,
3792 )?;4068 )?;
3793 } else {4069 } else {
3794 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order4070 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
@@ -3829,6 +4105,7 @@ fn decode_leaf8(
3829 None,4105 None,
3830 filter_intra,4106 filter_intra,
3831 Some(tu_skip_ctx),4107 Some(tu_skip_ctx),
4108+ smooth_neighbor,
3832 )?;4109 )?;
3833 if std::env::var_os("EC_AV1_TRACE").is_some() {4110 if std::env::var_os("EC_AV1_TRACE").is_some() {
3834 eprintln!(4111 eprintln!(
@@ -3863,6 +4140,7 @@ fn decode_leaf8(
3863 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),4140 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3864 None,4141 None,
3865 None,4142 None,
4143+ false,
3866 )?;4144 )?;
3867 v_grid = read_plane(4145 v_grid = read_plane(
3868 dec,4146 dec,
@@ -3884,6 +4162,7 @@ fn decode_leaf8(
3884 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),4162 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
3885 None,4163 None,
3886 None,4164 None,
4165+ false,
3887 )?;4166 )?;
3888 // `record_split_luma` expects a `record`-style `(r, c)` position in4167 // `record_split_luma` expects a `record`-style `(r, c)` position in
3889 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is4168 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
@@ -4171,8 +4450,8 @@ fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
4171 /// to the left (at its own topmost mi row) coded a transform at least as wide4450 /// to the left (at its own topmost mi row) coded a transform at least as wide
4172 /// as `own_side`.4451 /// as `own_side`.
4173 fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {4452 fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
4174- let above = mi_r > 0 && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;4453+ let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
4175- let left = mi_c > 0 && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;4454+ let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
4176 usize::from(above) + usize::from(left)4455 usize::from(above) + usize::from(left)
4177 }4456 }
4178 4457
@@ -4678,13 +4957,32 @@ fn apply_cdef(
4678 cdef: &CdefParams,4957 cdef: &CdefParams,
4679 skip_grid: &Neighbours,4958 skip_grid: &Neighbours,
4680 ) {4959 ) {
4681- if cdef.y_pri_strength[0] == 04960+ // `cdef.bits == 0` still means "no filtering at all" whenever the single
4961+ // (index 0) strength pair is all-zero -- the fast path every existing
4962+ // gate stream takes. A `bits > 0` frame can still be all-zero-strength
4963+ // at every index, but that is rare enough not to special-case; the
4964+ // per-superblock lookup below degrades to the same index-0 read anyway
4965+ // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
4966+ if cdef.bits == 0
4967+ && cdef.y_pri_strength[0] == 0
4682 && cdef.y_sec_strength[0] == 04968 && cdef.y_sec_strength[0] == 0
4683 && cdef.uv_pri_strength[0] == 04969 && cdef.uv_pri_strength[0] == 0
4684 && cdef.uv_sec_strength[0] == 04970 && cdef.uv_sec_strength[0] == 0
4685 {4971 {
4686 return;4972 return;
4687 }4973 }
4974+ let sb_cols = CDEF_SB_COLS.with(|c| c.get());
4975+ let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
4976+ let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
4977+ if sb_cols == 0 {
4978+ return 0;
4979+ }
4980+ let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
4981+ idx_grid
4982+ .get(sb_r * sb_cols + sb_c)
4983+ .copied()
4984+ .unwrap_or(0) as usize
4985+ };
4688 let src_y = y.data.clone();4986 let src_y = y.data.clone();
4689 let src_u = u.data.clone();4987 let src_u = u.data.clone();
4690 let src_v = v.data.clone();4988 let src_v = v.data.clone();
@@ -4695,6 +4993,7 @@ fn apply_cdef(
4695 let mut mi_c = 0usize;4993 let mut mi_c = 0usize;
4696 while mi_c < skip_grid.mi_cols {4994 while mi_c < skip_grid.mi_cols {
4697 if !skip_grid.is_skip_txfm(mi_r, mi_c) {4995 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
4996+ let sidx = strength_idx(mi_r, mi_c);
4698 let (ox, oy) = (mi_c * 4, mi_r * 4);4997 let (ox, oy) = (mi_c * 4, mi_r * 4);
4699 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);4998 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
4700 let sample_y = |r: i32, c: i32| -> i32 {4999 let sample_y = |r: i32, c: i32| -> i32 {
@@ -4714,10 +5013,10 @@ fn apply_cdef(
4714 // -- each plane zeroes the shared direction when *its own*5013 // -- each plane zeroes the shared direction when *its own*
4715 // frame-level primary strength is 0, independent of the5014 // frame-level primary strength is 0, independent of the
4716 // per-block adjusted `t` and of the other plane's strength.5015 // per-block adjusted `t` and of the other plane's strength.
4717- let y_dir = if cdef.y_pri_strength[0] != 0 { dir } else { 0 };5016+ let y_dir = if cdef.y_pri_strength[sidx] != 0 { dir } else { 0 };
4718- let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[0]), var);5017+ let t = cdef_adjust_strength(i32::from(cdef.y_pri_strength[sidx]), var);
4719 let enable_primary = t != 0;5018 let enable_primary = t != 0;
4720- let enable_secondary = cdef.y_sec_strength[0] != 0;5019+ let enable_secondary = cdef.y_sec_strength[sidx] != 0;
4721 if enable_primary || enable_secondary {5020 if enable_primary || enable_secondary {
4722 cdef_filter_block(5021 cdef_filter_block(
4723 sample_y,5022 sample_y,
@@ -4727,7 +5026,7 @@ fn apply_cdef(
4727 8,5026 8,
4728 8,5027 8,
4729 t,5028 t,
4730- i32::from(cdef.y_sec_strength[0]),5029+ i32::from(cdef.y_sec_strength[sidx]),
4731 y_dir,5030 y_dir,
4732 damping,5031 damping,
4733 damping,5032 damping,
@@ -4736,10 +5035,10 @@ fn apply_cdef(
4736 );5035 );
4737 }5036 }
4738 5037
4739- let t_uv = i32::from(cdef.uv_pri_strength[0]);5038+ let t_uv = i32::from(cdef.uv_pri_strength[sidx]);
4740 let uv_dir = if t_uv != 0 { dir } else { 0 };5039 let uv_dir = if t_uv != 0 { dir } else { 0 };
4741 let enable_primary_uv = t_uv != 0;5040 let enable_primary_uv = t_uv != 0;
4742- let enable_secondary_uv = cdef.uv_sec_strength[0] != 0;5041+ let enable_secondary_uv = cdef.uv_sec_strength[sidx] != 0;
4743 if enable_primary_uv || enable_secondary_uv {5042 if enable_primary_uv || enable_secondary_uv {
4744 let (cox, coy) = (ox / 2, oy / 2);5043 let (cox, coy) = (ox / 2, oy / 2);
4745 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {5044 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
@@ -4761,7 +5060,7 @@ fn apply_cdef(
4761 4,5060 4,
4762 4,5061 4,
4763 t_uv,5062 t_uv,
4764- i32::from(cdef.uv_sec_strength[0]),5063+ i32::from(cdef.uv_sec_strength[sidx]),
4765 uv_dir,5064 uv_dir,
4766 damping_uv,5065 damping_uv,
4767 damping_uv,5066 damping_uv,
@@ -4810,8 +5109,14 @@ pub fn decode_key_frame_tile(
4810 allow_screen_content_tools: bool,5109 allow_screen_content_tools: bool,
4811 allow_intrabc: bool,5110 allow_intrabc: bool,
4812 ) -> Result<Picture> {5111 ) -> Result<Picture> {
5112+ let single_tile = TileInfo {
5113+ mi_col_starts: vec![0, mi_cols],
5114+ mi_row_starts: vec![0, mi_rows],
5115+ ..TileInfo::default()
5116+ };
4813 decode_key_frame_tile_with_cdfs(5117 decode_key_frame_tile_with_cdfs(
4814- data,5118+ &[data],
5119+ &single_tile,
4815 mi_cols,5120 mi_cols,
4816 mi_rows,5121 mi_rows,
4817 base_q_idx,5122 base_q_idx,
@@ -4839,7 +5144,8 @@ pub fn decode_key_frame_tile(
4839 /// alongside the picture, for the caller to save into whichever reference5144 /// alongside the picture, for the caller to save into whichever reference
4840 /// slots this frame's `refresh_frame_flags` names.5145 /// slots this frame's `refresh_frame_flags` names.
4841 pub(crate) fn decode_key_frame_tile_with_cdfs(5146 pub(crate) fn decode_key_frame_tile_with_cdfs(
4842- data: &[u8],5147+ tiles: &[&[u8]],
5148+ tile_info: &TileInfo,
4843 mi_cols: u32,5149 mi_cols: u32,
4844 mi_rows: u32,5150 mi_rows: u32,
4845 base_q_idx: u8,5151 base_q_idx: u8,
@@ -4860,6 +5166,9 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
4860 }5166 }
4861 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));5167 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
4862 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));5168 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
5169+ CDEF_BITS.with(|c| c.set(cdef.bits));
5170+ CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
5171+ CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
4863 let (cols32, rows32) = block_grid(mi_cols, mi_rows);5172 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
4864 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);5173 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
4865 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);5174 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
@@ -4870,6 +5179,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
4870 height,5179 height,
4871 true_width,5180 true_width,
4872 true_height,5181 true_height,
5182+ tile_x0: 0,
5183+ tile_y0: 0,
4873 };5184 };
4874 let mut u = PlaneBuf {5185 let mut u = PlaneBuf {
4875 data: vec![0u8; width * height / 4],5186 data: vec![0u8; width * height / 4],
@@ -4877,6 +5188,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
4877 height: height / 2,5188 height: height / 2,
4878 true_width: true_width / 2,5189 true_width: true_width / 2,
4879 true_height: true_height / 2,5190 true_height: true_height / 2,
5191+ tile_x0: 0,
5192+ tile_y0: 0,
4880 };5193 };
4881 let mut v = PlaneBuf {5194 let mut v = PlaneBuf {
4882 data: vec![0u8; width * height / 4],5195 data: vec![0u8; width * height / 4],
@@ -4884,6 +5197,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
4884 height: height / 2,5197 height: height / 2,
4885 true_width: true_width / 2,5198 true_width: true_width / 2,
4886 true_height: true_height / 2,5199 true_height: true_height / 2,
5200+ tile_x0: 0,
5201+ tile_y0: 0,
4887 };5202 };
4888 5203
4889 let scan32 = default_scan(TX32);5204 let scan32 = default_scan(TX32);
@@ -4891,15 +5206,8 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
4891 let scan8 = default_scan(TX8);5206 let scan8 = default_scan(TX8);
4892 let scan4 = default_scan(TX4);5207 let scan4 = default_scan(TX4);
4893 5208
4894- let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));5209+ let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
4895- if std::env::var_os("EC_AV1_TRACE").is_some() {5210+ let mut result_cdfs = base_cdfs.clone();
4896- eprintln!(
4897- "TRACE key_tile_bytes len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
4898- data.len(),
4899- &data[..data.len().min(8)]
4900- );
4901- }
4902- let mut dec = SymbolDecoder::new(data);
4903 let mut neighbours = Neighbours::new(5211 let mut neighbours = Neighbours::new(
4904 cols32 as usize * 2,5212 cols32 as usize * 2,
4905 rows32 as usize * 2,5213 rows32 as usize * 2,
@@ -4907,9 +5215,51 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
4907 mi_rows as usize,5215 mi_rows as usize,
4908 );5216 );
4909 5217
4910- for sb_r in 0..sb_rows {5218+ // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
5219+ // own byte range and its own fresh copy of the frame's initial CDFs
5220+ // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
5221+ // `context_update_tile_id` has its end-of-tile adapted table kept as the
5222+ // frame's own output (spec `exit_symbol`) -- every other tile's
5223+ // adaptation is discarded, matching the refusal this replaces.
5224+ for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
5225+ let tile_num = tile_idx as u32;
5226+ let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
5227+ let mi_row0 = tile_info.mi_row_starts[trow as usize];
5228+ let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
5229+ let mi_col0 = tile_info.mi_col_starts[tcol as usize];
5230+ let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
5231+ // Tile boundaries are always superblock-aligned in mi units (spec
5232+ // 5.9.15's uniform/non-uniform derivation both only ever emit
5233+ // multiples of the superblock's own mi size), so plain division is
5234+ // exact here -- no rounding needed.
5235+ // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
5236+ // tile boundary) are always superblock-aligned by spec 5.9.15; the
5237+ // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
5238+ // last entry) is not, so the upper bound needs `div_ceil` the same
5239+ // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
5240+ // trailing partial superblock row/column in scope.
5241+ let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
5242+ let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
5243+
5244+ let mut cdfs = base_cdfs.clone();
5245+ if std::env::var_os("EC_AV1_TRACE").is_some() {
5246+ eprintln!(
5247+ "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
5248+ tile_bytes.len(),
5249+ &tile_bytes[..tile_bytes.len().min(8)]
5250+ );
5251+ }
5252+ let mut dec = SymbolDecoder::new(tile_bytes);
5253+ neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
5254+ y.set_tile_origin(mi_col0 as usize * 4, mi_row0 as usize * 4);
5255+ u.set_tile_origin(mi_col0 as usize * 2, mi_row0 as usize * 2);
5256+ v.set_tile_origin(mi_col0 as usize * 2, mi_row0 as usize * 2);
5257+ TILE_HITS.with(|c| c.set(c.get() + 1));
5258+
5259+ for sb_r in sb_r0..sb_r1 {
4911 neighbours.start_row();5260 neighbours.start_row();
4912- for sb_c in 0..sb_cols {5261+ for sb_c in sb_c0..sb_c1 {
5262+ CDEF_TRANSMITTED.with(|c| c.set(false));
4913 let at = (sb_r as usize * 4, sb_c as usize * 4);5263 let at = (sb_r as usize * 4, sb_c as usize * 4);
4914 let ctx = neighbours.partition_ctx(at, SB);5264 let ctx = neighbours.partition_ctx(at, SB);
4915 let (has_cols, has_rows) = (5265 let (has_cols, has_rows) = (
@@ -5296,19 +5646,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
5296 }5646 }
5297 _ => {5647 _ => {
5298 return Err(unsupported(format!(5648 return Err(unsupported(format!(
5299- "a partition type this encoder never writes (value={part32})"5649+ "a 32x32 partition type this decoder does not code (value={part32})"
5300 )));5650 )));
5301 }5651 }
5302 }5652 }
5303 }5653 }
5304 }5654 }
5305 _ => {5655 _ => {
5306- return Err(unsupported("a partition type this encoder never writes"));5656+ return Err(unsupported(
5657+ "a superblock-level partition type other than NONE or SPLIT (this \
5658+ decoder's intra tile path codes only those two at 64x64)",
5659+ ));
5307 }5660 }
5308 }5661 }
5309 }5662 }
5310 }5663 }
5311 5664
5665+ if tile_num == tile_info.context_update_tile_id {
5666+ result_cdfs = cdfs;
5667+ }
5668+ }
5669+
5312 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's5670 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
5313 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against5671 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
5314 // that isolate whether a decode-order frame's mismatch already exists5672 // that isolate whether a decode-order frame's mismatch already exists
@@ -5338,7 +5696,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
5338 u: u.data,5696 u: u.data,
5339 v: v.data,5697 v: v.data,
5340 },5698 },
5341- cdfs,5699+ result_cdfs,
5342 ));5700 ));
5343 }5701 }
5344 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {5702 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
@@ -5356,7 +5714,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
5356 u: crop(&u, fw / 2, fh / 2),5714 u: crop(&u, fw / 2, fh / 2),
5357 v: crop(&v, fw / 2, fh / 2),5715 v: crop(&v, fw / 2, fh / 2),
5358 },5716 },
5359- cdfs,5717+ result_cdfs,
5360 ))5718 ))
5361 }5719 }
5362 5720
@@ -6741,6 +7099,7 @@ fn decode_inter_block(
6741 7099
6742 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);7100 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
6743 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;7101 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
7102+ maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);
6744 // lane-warp r5: see `reject_residual` -- a square-block decode of a7103 // lane-warp r5: see `reject_residual` -- a square-block decode of a
6745 // HORZ_B strip is symbol-exact only for `skip` (no residual, no7104 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
6746 // motion_mode/warp symbol), so gate here before any further read.7105 // motion_mode/warp symbol), so gate here before any further read.
@@ -6750,7 +7109,10 @@ fn decode_inter_block(
6750 ));7109 ));
6751 }7110 }
6752 7111
6753- let (has_above, has_left) = (r > 0, c > 0);7112+ let (has_above, has_left) = (
7113+ r > neighbours.tile_row0_mi / (SUB / MI),
7114+ c > neighbours.tile_col0_mi / (SUB / MI),
7115+ );
6754 let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]);7116 let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]);
6755 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);7117 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
6756 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;7118 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
@@ -6762,6 +7124,7 @@ fn decode_inter_block(
6762 }7124 }
6763 7125
6764 let mode_for_tx;7126 let mode_for_tx;
7127+ let uv_predict_mode;
6765 let (luma_grid, u_grid, v_grid);7128 let (luma_grid, u_grid, v_grid);
6766 let block_filter;7129 let block_filter;
6767 let ref_frame_for_lf;7130 let ref_frame_for_lf;
@@ -6906,6 +7269,7 @@ fn decode_inter_block(
6906 globalmv_for_lf = is_globalmv;7269 globalmv_for_lf = is_globalmv;
6907 ref_frame_for_lf = ref0;7270 ref_frame_for_lf = ref0;
6908 mode_for_tx = 0;7271 mode_for_tx = 0;
7272+ uv_predict_mode = DC_PRED;
6909 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from7273 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
6910 // `neighbours`) must be stamped with the block's true footprint7274 // `neighbours`) must be stamped with the block's true footprint
6911 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's7275 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
@@ -7926,6 +8290,7 @@ fn decode_inter_block(
7926 }8290 }
7927 }8291 }
7928 mode_for_tx = 0;8292 mode_for_tx = 0;
8293+ uv_predict_mode = DC_PRED;
7929 8294
7930 let mut pred_y = vec![0u8; side * side];8295 let mut pred_y = vec![0u8; side * side];
7931 mc::predict_with_filters(8296 mc::predict_with_filters(
@@ -8141,13 +8506,36 @@ fn decode_inter_block(
8141 }8506 }
8142 }8507 }
8143 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);8508 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
8509+ if (9..=12).contains(&uv_mode) {
8510+ SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
8511+ }
8144 let alpha = if uv_mode == DC_PRED {8512 let alpha = if uv_mode == DC_PRED {
8145 None8513 None
8146 } else if uv_mode == UV_CFL_PRED {8514 } else if uv_mode == UV_CFL_PRED {
8147 Some(read_cfl_alphas(dec, cdfs))8515 Some(read_cfl_alphas(dec, cdfs))
8148 } else {8516 } else {
8149- return Err(unsupported("a directional chroma mode (round 2)"));8517+ None
8518+ };
8519+ // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for
8520+ // the angle-delta question, same as [`read_intra_mode`]'s own copy
8521+ // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the
8522+ // `else` branch below is exact for it either way.
8523+ let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
8524+ DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
8525+ read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
8526+ } else {
8527+ 0
8150 };8528 };
8529+ uv_predict_mode = if uv_mode == UV_CFL_PRED {
8530+ DC_PRED
8531+ } else {
8532+ uv_mode
8533+ };
8534+ // lane-chroma r4: same chroma edge-filter-strength neighbour check
8535+ // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA
8536+ // neighbour's own `uv_mode`, not the luma one.
8537+ let smooth_neighbor_uv =
8538+ is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
8151 // `read_palette_mode_info` (decodemv.c:567, called from8539 // `read_palette_mode_info` (decodemv.c:567, called from
8152 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same8540 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
8153 // gating and same corner-cut as `read_intra_mode`'s own copy above8541 // gating and same corner-cut as `read_intra_mode`'s own copy above
@@ -8206,29 +8594,32 @@ fn decode_inter_block(
8206 &vec![0i32; side * side],8594 &vec![0i32; side * side],
8207 None,8595 None,
8208 None,8596 None,
8597+ false,
8209 );8598 );
8210 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));8599 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8211 u.reconstruct(8600 u.reconstruct(
8212 cpx,8601 cpx,
8213 cpy,8602 cpy,
8214 chroma_side,8603 chroma_side,
8215- DC_PRED,8604+ uv_predict_mode,
8216- 0,8605+ angle_delta_uv,
8217 reach,8606 reach,
8218 &vec![0i32; chroma_side * chroma_side],8607 &vec![0i32; chroma_side * chroma_side],
8219 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),8608 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8220 None,8609 None,
8610+ smooth_neighbor_uv,
8221 );8611 );
8222 v.reconstruct(8612 v.reconstruct(
8223 cpx,8613 cpx,
8224 cpy,8614 cpy,
8225 chroma_side,8615 chroma_side,
8226- DC_PRED,8616+ uv_predict_mode,
8227- 0,8617+ angle_delta_uv,
8228 reach,8618 reach,
8229 &vec![0i32; chroma_side * chroma_side],8619 &vec![0i32; chroma_side * chroma_side],
8230 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),8620 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8231 None,8621 None,
8622+ smooth_neighbor_uv,
8232 );8623 );
8233 luma_grid = vec![0i32; side * side];8624 luma_grid = vec![0i32; side * side];
8234 u_grid = vec![0i32; chroma_side * chroma_side];8625 u_grid = vec![0i32; chroma_side * chroma_side];
@@ -8255,6 +8646,7 @@ fn decode_inter_block(
8255 None,8646 None,
8256 None,8647 None,
8257 None,8648 None,
8649+ false,
8258 )?;8650 )?;
8259 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));8651 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
8260 u_grid = read_plane(8652 u_grid = read_plane(
@@ -8265,8 +8657,8 @@ fn decode_inter_block(
8265 1,8657 1,
8266 around[1],8658 around[1],
8267 mode,8659 mode,
8268- DC_PRED,8660+ uv_predict_mode,
8269- 0,8661+ angle_delta_uv,
8270 reach,8662 reach,
8271 u,8663 u,
8272 cpx,8664 cpx,
@@ -8277,6 +8669,7 @@ fn decode_inter_block(
8277 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),8669 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8278 None,8670 None,
8279 None,8671 None,
8672+ smooth_neighbor_uv,
8280 )?;8673 )?;
8281 v_grid = read_plane(8674 v_grid = read_plane(
8282 dec,8675 dec,
@@ -8286,8 +8679,8 @@ fn decode_inter_block(
8286 2,8679 2,
8287 around[2],8680 around[2],
8288 mode,8681 mode,
8289- DC_PRED,8682+ uv_predict_mode,
8290- 0,8683+ angle_delta_uv,
8291 reach,8684 reach,
8292 v,8685 v,
8293 cpx,8686 cpx,
@@ -8298,6 +8691,7 @@ fn decode_inter_block(
8298 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),8691 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8299 None,8692 None,
8300 None,8693 None,
8694+ smooth_neighbor_uv,
8301 )?;8695 )?;
8302 }8696 }
8303 }8697 }
@@ -8313,7 +8707,14 @@ fn decode_inter_block(
8313 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().08707 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
8314 );8708 );
8315 }8709 }
8316- neighbours.record_rect(at, write_w, write_h, mode_for_tx, &[luma_grid, u_grid, v_grid]);8710+ neighbours.record_rect(
8711+ at,
8712+ write_w,
8713+ write_h,
8714+ mode_for_tx,
8715+ uv_predict_mode,
8716+ &[luma_grid, u_grid, v_grid],
8717+ );
8317 neighbours.record_inter_rect(8718 neighbours.record_inter_rect(
8318 at,8719 at,
8319 write_w,8720 write_w,
@@ -8468,8 +8869,12 @@ fn decode_inter_block8(
8468 8869
8469 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);8870 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
8470 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;8871 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
8872+ maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
8471 8873
8472- let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0);8874+ let (has_above, has_left) = (
8875+ leaf_mi.0 > neighbours.tile_row0_mi,
8876+ leaf_mi.1 > neighbours.tile_col0_mi,
8877+ );
8473 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);8878 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
8474 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;8879 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
8475 8880
@@ -9279,6 +9684,7 @@ fn decode_inter_block8(
9279 &vec![0i32; SIDE * SIDE],9684 &vec![0i32; SIDE * SIDE],
9280 None,9685 None,
9281 None,9686 None,
9687+ false,
9282 );9688 );
9283 u.reconstruct(9689 u.reconstruct(
9284 cpx,9690 cpx,
@@ -9290,6 +9696,7 @@ fn decode_inter_block8(
9290 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],9696 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9291 None,9697 None,
9292 None,9698 None,
9699+ false,
9293 );9700 );
9294 v.reconstruct(9701 v.reconstruct(
9295 cpx,9702 cpx,
@@ -9301,6 +9708,7 @@ fn decode_inter_block8(
9301 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],9708 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
9302 None,9709 None,
9303 None,9710 None,
9711+ false,
9304 );9712 );
9305 luma_grid = vec![0i32; SIDE * SIDE];9713 luma_grid = vec![0i32; SIDE * SIDE];
9306 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];9714 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
@@ -9327,6 +9735,7 @@ fn decode_inter_block8(
9327 None,9735 None,
9328 None,9736 None,
9329 None,9737 None,
9738+ false,
9330 )?;9739 )?;
9331 u_grid = read_plane(9740 u_grid = read_plane(
9332 dec,9741 dec,
@@ -9348,6 +9757,7 @@ fn decode_inter_block8(
9348 None,9757 None,
9349 None,9758 None,
9350 None,9759 None,
9760+ false,
9351 )?;9761 )?;
9352 v_grid = read_plane(9762 v_grid = read_plane(
9353 dec,9763 dec,
@@ -9369,6 +9779,7 @@ fn decode_inter_block8(
9369 None,9779 None,
9370 None,9780 None,
9371 None,9781 None,
9782+ false,
9372 )?;9783 )?;
9373 }9784 }
9374 }9785 }
@@ -9526,6 +9937,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
9526 }9937 }
9527 let (cols, rows) = block_grid(mi_cols, mi_rows);9938 let (cols, rows) = block_grid(mi_cols, mi_rows);
9528 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));9939 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
9940+ CDEF_BITS.with(|c| c.set(cdef.bits));
9941+ CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
9942+ CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
9529 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);9943 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
9530 9944
9531 let ref_y = PlaneBuf {9945 let ref_y = PlaneBuf {
@@ -9534,6 +9948,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
9534 height: reference.height,9948 height: reference.height,
9535 true_width: reference.width,9949 true_width: reference.width,
9536 true_height: reference.height,9950 true_height: reference.height,
9951+ tile_x0: 0,
9952+ tile_y0: 0,
9537 };9953 };
9538 let ref_u = PlaneBuf {9954 let ref_u = PlaneBuf {
9539 data: reference.u.clone(),9955 data: reference.u.clone(),
@@ -9541,6 +9957,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
9541 height: reference.height / 2,9957 height: reference.height / 2,
9542 true_width: reference.width / 2,9958 true_width: reference.width / 2,
9543 true_height: reference.height / 2,9959 true_height: reference.height / 2,
9960+ tile_x0: 0,
9961+ tile_y0: 0,
9544 };9962 };
9545 let ref_v = PlaneBuf {9963 let ref_v = PlaneBuf {
9546 data: reference.v.clone(),9964 data: reference.v.clone(),
@@ -9548,6 +9966,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
9548 height: reference.height / 2,9966 height: reference.height / 2,
9549 true_width: reference.width / 2,9967 true_width: reference.width / 2,
9550 true_height: reference.height / 2,9968 true_height: reference.height / 2,
9969+ tile_x0: 0,
9970+ tile_y0: 0,
9551 };9971 };
9552 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`9972 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
9553 // names a live DPB slot for (lane-av1refs: generalised from the old9973 // names a live DPB slot for (lane-av1refs: generalised from the old
@@ -9567,6 +9987,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
9567 height: g.height,9987 height: g.height,
9568 true_width: g.width,9988 true_width: g.width,
9569 true_height: g.height,9989 true_height: g.height,
9990+ tile_x0: 0,
9991+ tile_y0: 0,
9570 },9992 },
9571 PlaneBuf {9993 PlaneBuf {
9572 data: g.u.clone(),9994 data: g.u.clone(),
@@ -9574,6 +9996,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
9574 height: g.height / 2,9996 height: g.height / 2,
9575 true_width: g.width / 2,9997 true_width: g.width / 2,
9576 true_height: g.height / 2,9998 true_height: g.height / 2,
9999+ tile_x0: 0,
10000+ tile_y0: 0,
9577 },10001 },
9578 PlaneBuf {10002 PlaneBuf {
9579 data: g.v.clone(),10003 data: g.v.clone(),
@@ -9581,6 +10005,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
9581 height: g.height / 2,10005 height: g.height / 2,
9582 true_width: g.width / 2,10006 true_width: g.width / 2,
9583 true_height: g.height / 2,10007 true_height: g.height / 2,
10008+ tile_x0: 0,
10009+ tile_y0: 0,
9584 },10010 },
9585 )10011 )
9586 })10012 })
@@ -9594,6 +10020,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
9594 height,10020 height,
9595 true_width,10021 true_width,
9596 true_height,10022 true_height,
10023+ tile_x0: 0,
10024+ tile_y0: 0,
9597 };10025 };
9598 let mut u = PlaneBuf {10026 let mut u = PlaneBuf {
9599 data: vec![0u8; width * height / 4],10027 data: vec![0u8; width * height / 4],
@@ -9601,6 +10029,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
9601 height: height / 2,10029 height: height / 2,
9602 true_width: true_width / 2,10030 true_width: true_width / 2,
9603 true_height: true_height / 2,10031 true_height: true_height / 2,
10032+ tile_x0: 0,
10033+ tile_y0: 0,
9604 };10034 };
9605 let mut v = PlaneBuf {10035 let mut v = PlaneBuf {
9606 data: vec![0u8; width * height / 4],10036 data: vec![0u8; width * height / 4],
@@ -9608,6 +10038,8 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
9608 height: height / 2,10038 height: height / 2,
9609 true_width: true_width / 2,10039 true_width: true_width / 2,
9610 true_height: true_height / 2,10040 true_height: true_height / 2,
10041+ tile_x0: 0,
10042+ tile_y0: 0,
9611 };10043 };
9612 10044
9613 let scan32 = default_scan(TX32);10045 let scan32 = default_scan(TX32);
@@ -9638,31 +10070,47 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
9638 for sb_r in 0..sb_rows {10070 for sb_r in 0..sb_rows {
9639 neighbours.start_row();10071 neighbours.start_row();
9640 for sb_c in 0..sb_cols {10072 for sb_c in 0..sb_cols {
10073+ CDEF_TRANSMITTED.with(|c| c.set(false));
9641 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);10074 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
9642 let sb_ctx = neighbours.partition_ctx(sb_at, SB);10075 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
9643 let (has_cols, has_rows) = (10076 let (has_cols, has_rows) = (
9644 sb_c * SB_MI + SB_MI / 2 < mi_cols,10077 sb_c * SB_MI + SB_MI / 2 < mi_cols,
9645 sb_r * SB_MI + SB_MI / 2 < mi_rows,10078 sb_r * SB_MI + SB_MI / 2 < mi_rows,
9646 );10079 );
9647- match (has_cols, has_rows) {10080+ // The straddle cases (one or both halves outside the true
10081+ // frame) never carry a real alphabet symbol -- spec forces
10082+ // SPLIT there (mirrors the intra key-frame tile's own
10083+ // three-way write above). Only the (true, true) case can name
10084+ // a non-SPLIT value, and this loop below only ever recurses as
10085+ // SPLIT -- so a real non-SPLIT part64 here must refuse by name
10086+ // instead of silently decoding as SPLIT and desyncing.
10087+ let part64 = match (has_cols, has_rows) {
9648 (true, true) => {10088 (true, true) => {
9649- let part64 = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);10089+ let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
9650 if std::env::var_os("EC_AV1_TRACE").is_some() {10090 if std::env::var_os("EC_AV1_TRACE").is_some() {
9651 eprintln!(10091 eprintln!(
9652- "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={part64}",10092+ "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p}",
9653 sb_r * SB_MI,10093 sb_r * SB_MI,
9654 sb_c * SB_MI10094 sb_c * SB_MI
9655 );10095 );
9656 }10096 }
9657- let _ = part64;10097+ p
9658 }10098 }
9659 (true, false) => {10099 (true, false) => {
9660 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));10100 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
10101+ PARTITION_SPLIT
9661 }10102 }
9662 (false, true) => {10103 (false, true) => {
9663 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));10104 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
10105+ PARTITION_SPLIT
9664 }10106 }
9665- (false, false) => {}10107+ (false, false) => PARTITION_SPLIT,
10108+ };
10109+ if part64 != PARTITION_SPLIT {
10110+ return Err(unsupported(
10111+ "an inter SB-level partition type other than SPLIT (this decoder's \
10112+ inter tile path only recurses a superblock as SPLIT)",
10113+ ));
9666 }10114 }
9667 10115
9668 for quadrant in 0..4 {10116 for quadrant in 0..4 {
@@ -10803,7 +11251,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
10803 }11251 }
10804 _ => {11252 _ => {
10805 return Err(unsupported(format!(11253 return Err(unsupported(format!(
10806- "an INTER 32x32 partition type this encoder never writes (value={part32})"11254+ "an INTER 32x32 partition type this decoder does not code (value={part32})"
10807 )));11255 )));
10808 }11256 }
10809 }11257 }
@@ -11091,6 +11539,46 @@ mod tests {
11091 );11539 );
11092 }11540 }
11093 11541
11542+ /// An inter tile's SB-level `part64` used to be read and thrown away
11543+ /// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real
11544+ /// non-SPLIT value there silently desynced the whole tile instead of
11545+ /// refusing. Hand-writes a single whole superblock's `part64 = HORZ`
11546+ /// symbol (never produced by this crate's own encoder, which only ever
11547+ /// writes NONE/SPLIT at this level, but a real aomenc-class encoder can)
11548+ /// and asserts this decoder refuses by name rather than decoding garbage.
11549+ #[test]
11550+ fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
11551+ use crate::msac::SymbolEncoder;
11552+ let mut cdfs = Cdfs::new(q_ctx_of(40));
11553+ let mut enc = SymbolEncoder::new();
11554+ enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]);
11555+ let data = enc.finish();
11556+ let reference = crate::encode::Picture::grey(64, 64);
11557+ let err = decode_inter_frame_tile(
11558+ &data,
11559+ 16,
11560+ 16,
11561+ 40,
11562+ 64,
11563+ 64,
11564+ &reference,
11565+ [None; 8],
11566+ &CdefParams::default(),
11567+ &LoopFilterParams::default(),
11568+ false,
11569+ false,
11570+ Some(mc::InterpFilterKind::Regular),
11571+ false,
11572+ false,
11573+ )
11574+ .unwrap_err();
11575+ let msg = err.to_string();
11576+ assert!(
11577+ msg.contains("SPLIT"),
11578+ "expected the named inter-SB-partition refusal, got: {msg}"
11579+ );
11580+ }
11581+
11094 // ffmpeg cross-oracle: an independent decoder (not this crate's own11582 // ffmpeg cross-oracle: an independent decoder (not this crate's own
11095 // encoder-side reconstruction) agrees with what this module decodes,11583 // encoder-side reconstruction) agrees with what this module decodes,
11096 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same11584 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
@@ -11494,6 +11982,8 @@ mod tests {
11494 height: height / scale,11982 height: height / scale,
11495 true_width: width / scale,11983 true_width: width / scale,
11496 true_height: height / scale,11984 true_height: height / scale,
11985+ tile_x0: 0,
11986+ tile_y0: 0,
11497 };11987 };
11498 let ref_y = PlaneBuf {11988 let ref_y = PlaneBuf {
11499 data: ref_pattern.clone(),11989 data: ref_pattern.clone(),
@@ -11501,6 +11991,8 @@ mod tests {
11501 height,11991 height,
11502 true_width: width,11992 true_width: width,
11503 true_height: height,11993 true_height: height,
11994+ tile_x0: 0,
11995+ tile_y0: 0,
11504 };11996 };
11505 let ref_u = ref_plane(2);11997 let ref_u = ref_plane(2);
11506 let ref_v = ref_plane(2);11998 let ref_v = ref_plane(2);
@@ -11511,6 +12003,8 @@ mod tests {
11511 height,12003 height,
11512 true_width: width,12004 true_width: width,
11513 true_height: height,12005 true_height: height,
12006+ tile_x0: 0,
12007+ tile_y0: 0,
11514 };12008 };
11515 let mut u = PlaneBuf {12009 let mut u = PlaneBuf {
11516 data: vec![0u8; (width / 2) * (height / 2)],12010 data: vec![0u8; (width / 2) * (height / 2)],
@@ -11518,6 +12012,8 @@ mod tests {
11518 height: height / 2,12012 height: height / 2,
11519 true_width: width / 2,12013 true_width: width / 2,
11520 true_height: height / 2,12014 true_height: height / 2,
12015+ tile_x0: 0,
12016+ tile_y0: 0,
11521 };12017 };
11522 let mut v = PlaneBuf {12018 let mut v = PlaneBuf {
11523 data: vec![0u8; (width / 2) * (height / 2)],12019 data: vec![0u8; (width / 2) * (height / 2)],
@@ -11525,6 +12021,8 @@ mod tests {
11525 height: height / 2,12021 height: height / 2,
11526 true_width: width / 2,12022 true_width: width / 2,
11527 true_height: height / 2,12023 true_height: height / 2,
12024+ tile_x0: 0,
12025+ tile_y0: 0,
11528 };12026 };
11529 12027
11530 let mut cdfs = Cdfs::new(q_ctx_of(100));12028 let mut cdfs = Cdfs::new(q_ctx_of(100));
crates/ec-av1/src/gate_coverage.rsmodified+0 -3
@@ -25,10 +25,7 @@
25 /// its tool is now covered by a real stream.25 /// its tool is now covered by a real stream.
26 #[cfg(test)]26 #[cfg(test)]
27 const NEVER_EXERCISED: &[(&str, &str)] = &[27 const NEVER_EXERCISED: &[(&str, &str)] = &[
28- ("enable-cdef", "cdef_idx is not read yet; the CDEF filter itself is implemented and unit-tested"),
29 ("enable-intrabc", "intra block copy syntax is consumed but no block is reconstructed from it"),28 ("enable-intrabc", "intra block copy syntax is consumed but no block is reconstructed from it"),
30- ("enable-paeth-intra", "chroma PAETH_PRED is refused; luma is unexercised against a real stream"),
31- ("enable-smooth-intra", "chroma SMOOTH_PRED is refused, and the intra edge filter's smooth-neighbour bucket is a known corner-cut"),
32 ];29 ];
33 30
34 #[cfg(test)]31 #[cfg(test)]
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -30,6 +30,7 @@ pub mod msac;
30 pub mod mvstack;30 pub mod mvstack;
31 pub mod obu;31 pub mod obu;
32 pub mod quant;32 pub mod quant;
33+mod refusal_inventory;
33 pub mod sequence;34 pub mod sequence;
34 pub mod stream;35 pub mod stream;
35 pub mod tile;36 pub mod tile;
crates/ec-av1/src/refusal_inventory.rsadded+254 -0
@@ -0,0 +1,254 @@
1+//! An inventory of what this decoder refuses, and a check on the claims those
2+//! refusals make.
3+//!
4+//! Two rules this repository keeps learning the hard way:
5+//!
6+//! 1. A refusal string is a **claim**. "This encoder never writes one" asserts
7+//! that a real encoder cannot emit the case -- and one such string was
8+//! disproved by the very gate that carried it (the wedge-interintra hang,
9+//! 2026-08-30): the refusal was written from a mismatching frame's header
10+//! state, so it named a correlate rather than the defect. Any refusal
11+//! phrased as a capability claim about the ENCODER, rather than about this
12+//! decoder, needs evidence, and this module makes the set of such strings
13+//! explicit instead of letting it grow quietly.
14+//! 2. Refusals accumulate silently. A lane that adds one to unblock itself is
15+//! doing the right thing (refuse by name rather than desync), but the total
16+//! is the distance to a decoder that handles a default-settings stream, and
17+//! nobody sees a total that nothing prints.
18+//!
19+//! So the test below re-derives every `unsupported(...)` reason reachable on
20+//! the decode path -- `decode.rs` and `stream.rs` -- and pins it. Adding or
21+//! removing a refusal fails until the list is updated, which is the point: the
22+//! diff of this file is the decoder's capability delta, in one place, in
23+//! English.
24+
25+#[cfg(test)]
26+const CAPABILITY_CLAIMS: &[&str] = &[
27+ "a non-2D tx class on a rectangular transform (never expected at this size)",
28+ "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
29+ "a nonzero angle delta (this encoder never writes one)",
30+ "a partition below 16x16 other than a clean split (this encoder never writes one)",
31+ "a partition below 8x8 (this encoder never writes one)",
32+ "a tx_type symbol on a rectangular transform (never expected at this size)",
33+];
34+
35+#[cfg(test)]
36+const REFUSALS: &[&str] = &[
37+ "GLOBALMV (round 3)",
38+ "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",
39+ "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",
40+ "a 32x32 partition type this decoder does not code (value={part32})",
41+ "a Golomb tail longer than this decoder reads",
42+ "a tx_type symbol outside its CDF's own set: {t}",
43+ "an INTER 32x32 partition type this decoder does not code (value={part32})",
44+ "a superblock-level partition type other than NONE or SPLIT (this decoder's intra tile path codes only those two at 64x64)",
45+ "a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed for square blocks only)",
46+ "a HORZ/VERT intra strip with a split transform (per-unit rect prediction is not ported)",
47+ "a block that actually uses a palette (UV) -- reconstruction is out of scope",
48+ "a block that actually uses a palette (Y) -- reconstruction is out of scope",
49+ "a block that actually uses a palette (Y) -- the index map decodes but the reconstructed pixels do not match libaom yet (lane-palette r3/r4)",
50+ "a block that actually uses intrabc (this decoder never reconstructs one)",
51+ "a frame OBU with no tile group",
52+ "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
53+ "a frame with delta_q_present or delta_lf_present set (this decoder never reads the per-superblock delta symbols)",
54+ "a frame with loop restoration enabled (this decoder never reads the per-unit lr symbols)",
55+ "a frame with more than one tile row (only tile columns are proven pixel-exact so far)",
56+ "a frame with more than two tile columns (a non-last column's right-edge reach bound past column 0 is unimplemented)",
57+ "a multi-tile frame with loop filtering enabled (deblocking crosses tile boundaries by spec default; PlaneBuf's tile origin does not clip a non-last column's right-edge reach)",
58+ "an inter frame with more than one tile (the inter tile-decode path has no per-tile loop, only key frames do)",
59+ "a frame with no mode-info grid",
60+ "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",
61+ "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
62+ "a palette block with a split luma transform (round 1)",
63+ "a reference frame other than LAST_FRAME (round 2)",
64+ "a reference frame selected with no picture at this frame's own ref_frame_idx slot for it",
65+ "a reference picture that is not this frame's own true size",
66+ "a show_existing_frame header naming an empty reference slot",
67+ "an 8x8 leaf that coded WARPED_CAUSAL (motion_mode == 2): av1_find_projection/the affine warp filter are not ported, only motion_mode_allowed's alphabet choice is",
68+ "an inter frame using TxMode::Select (this decoder's inter path never reads a tx_depth symbol, so it desyncs after the first block's mode)",
69+ "an inter frame whose global motion for a single-reference frame is AFFINE (unverified this round; ROTZOOM/TRANSLATION/IDENTITY are proven)",
70+ "an inter frame with no key frame before it",
71+ "an inter SB-level partition type other than SPLIT (this decoder's inter tile path only recurses a superblock as SPLIT)",
72+ "an inter partition below 16x16 (8x8 and smaller inter blocks are not coded yet)",
73+ "an intra mode this decoder does not code (round 2)",
74+ "an intra-coded HORZ/VERT strip needs rectangular intra prediction this decoder does not code yet",
75+ "filter intra on a HORZ/VERT strip (this decoder predicts square-only)",
76+];
77+
78+/// Gates whose `Err` arm turns a decode failure into a printed SKIP rather than
79+/// a test failure.
80+///
81+/// A gate named `..._decodes_pixel_exact` that cannot decode has failed, and
82+/// swallowing the error keeps the suite green while the gate proves nothing --
83+/// the same vacuum as a gate whose feature never fires, arrived at from the
84+/// other side. These four predate the attempt-loop pattern the newer gates use
85+/// (encode several fixtures, require at least one to decode, hard-assert the
86+/// firing count). They are pinned here so the set cannot grow while they are
87+/// converted one at a time.
88+#[cfg(test)]
89+const GATES_THAT_SKIP_ON_A_DECODE_ERROR: &[&str] = &[
90+ "a_real_aomenc_filter_intra_stream_decodes_pixel_exact",
91+ "a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact",
92+ "a_real_aomenc_intra_stream_with_deblocking_decodes_pixel_exact",
93+ "a_real_libaom_gradients_stream_with_cdef_decodes_pixel_exact",
94+];
95+
96+#[cfg(test)]
97+mod tests {
98+ use super::{CAPABILITY_CLAIMS, GATES_THAT_SKIP_ON_A_DECODE_ERROR, REFUSALS};
99+ use std::collections::BTreeSet;
100+
101+ /// Every distinct `unsupported(...)` reason on the decode path.
102+ ///
103+ /// Both sources use the same shape -- `stream.rs` calls
104+ /// `Error::unsupported(context, reason)` and `decode.rs` a local
105+ /// `unsupported(reason)` helper -- so the reason is always the LAST string
106+ /// literal of the call, and Rust's `\` line continuations inside it are
107+ /// joined the way rustc joins them.
108+ fn decode_path_refusals() -> BTreeSet<String> {
109+ let mut found = BTreeSet::new();
110+ for src in [include_str!("decode.rs"), include_str!("stream.rs")] {
111+ let bytes = src.as_bytes();
112+ for (start, _) in src.match_indices("unsupported(") {
113+ // `Error::unsupported(` and the bare helper both end here.
114+ let mut i = start + "unsupported(".len();
115+ // `unsupported(format!("..."))` is the same refusal, one layer in.
116+ if src[i..].starts_with("format!(") {
117+ i += "format!(".len();
118+ }
119+ let mut last: Option<String> = None;
120+ loop {
121+ while i < bytes.len() && (bytes[i] as char).is_whitespace() {
122+ i += 1;
123+ }
124+ if i >= bytes.len() || bytes[i] != b'"' {
125+ break;
126+ }
127+ i += 1;
128+ let mut lit = String::new();
129+ while i < bytes.len() && bytes[i] != b'"' {
130+ if bytes[i] == b'\\' {
131+ // A backslash-newline continuation drops the newline
132+ // and the indentation that follows it.
133+ if bytes.get(i + 1) == Some(&b'\n') {
134+ i += 2;
135+ while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') {
136+ i += 1;
137+ }
138+ continue;
139+ }
140+ lit.push(bytes[i] as char);
141+ lit.push(bytes[i + 1] as char);
142+ i += 2;
143+ continue;
144+ }
145+ lit.push(bytes[i] as char);
146+ i += 1;
147+ }
148+ i += 1;
149+ last = Some(lit);
150+ while i < bytes.len() && (bytes[i] as char).is_whitespace() {
151+ i += 1;
152+ }
153+ if i < bytes.len() && bytes[i] == b',' {
154+ i += 1;
155+ continue;
156+ }
157+ break;
158+ }
159+ if let Some(reason) = last {
160+ // `Error::unsupported`'s first argument is the context
161+ // ("AV1 tile"), which is not a reason.
162+ if reason != "AV1 tile" {
163+ found.insert(reason);
164+ }
165+ }
166+ }
167+ }
168+ found
169+ }
170+
171+ #[test]
172+ fn the_decode_path_refuses_exactly_the_listed_cases() {
173+ let found = decode_path_refusals();
174+ let listed: BTreeSet<String> = CAPABILITY_CLAIMS
175+ .iter()
176+ .chain(REFUSALS)
177+ .map(|&s| s.to_owned())
178+ .collect();
179+ assert!(found.len() >= 30, "the refusal scan found only {} reasons -- it is broken, not the decoder", found.len());
180+
181+ let added: Vec<&String> = found.difference(&listed).collect();
182+ assert!(
183+ added.is_empty(),
184+ "new decode-path refusals are not in the inventory: {added:#?}\n\
185+ Add each to REFUSALS -- or, if it claims something about what an ENCODER can \
186+ emit, to CAPABILITY_CLAIMS, which requires evidence that the case is genuinely \
187+ unreachable rather than merely unseen."
188+ );
189+ let removed: Vec<&String> = listed.difference(&found).collect();
190+ assert!(
191+ removed.is_empty(),
192+ "these refusals are listed but no longer in the decode path: {removed:#?}\n\
193+ Delete them from the inventory -- the capability landed, which is the good case."
194+ );
195+ }
196+
197+ /// A refusal may say what THIS DECODER does not do. Saying what an encoder
198+ /// never emits is a claim about the world, and this repository has already
199+ /// shipped one that was false.
200+ #[test]
201+ fn capability_claims_are_declared_not_scattered() {
202+ let claimy: Vec<String> = decode_path_refusals()
203+ .into_iter()
204+ .filter(|r| r.contains("never writes") || r.contains("never expected"))
205+ .collect();
206+ let declared: BTreeSet<&str> = CAPABILITY_CLAIMS.iter().copied().collect();
207+ for reason in &claimy {
208+ assert!(
209+ declared.contains(reason.as_str()),
210+ "{reason:?} claims an encoder never emits this case but is not in \
211+ CAPABILITY_CLAIMS. Such a claim needs a gate that proves the case is \
212+ unreachable; until it has one, phrase the refusal as what this decoder \
213+ does not decode."
214+ );
215+ }
216+ }
217+
218+ /// No NEW gate may quietly turn a decode error into a skip.
219+ #[test]
220+ fn gates_that_swallow_a_decode_error_are_declared() {
221+ let src = include_str!("stream.rs");
222+ let mut found: BTreeSet<String> = BTreeSet::new();
223+ for (i, _) in src.match_indices("\"SKIP ") {
224+ let rest = &src[i + "\"SKIP ".len()..];
225+ let Some(colon) = rest.find(':') else { continue };
226+ let name = &rest[..colon];
227+ if !name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {
228+ continue;
229+ }
230+ // The tail of the message says what was skipped. Only "{e}" -- the
231+ // decode error itself -- is the shape this test is about; "no
232+ // ffmpeg"/"no aomenc" are tool absence, governed by
233+ // EC_AV1_REQUIRE_AOMENC instead.
234+ let Some(end) = rest.find("\"") else { continue };
235+ if rest[colon..end].contains("{e}") {
236+ found.insert(name.to_owned());
237+ }
238+ }
239+ let listed: BTreeSet<&str> = GATES_THAT_SKIP_ON_A_DECODE_ERROR.iter().copied().collect();
240+ let added: Vec<&String> = found.iter().filter(|n| !listed.contains(n.as_str())).collect();
241+ assert!(
242+ added.is_empty(),
243+ "these gates turn a decode error into a printed SKIP and are not declared: \
244+ {added:#?}\nA gate that cannot decode has failed -- assert on the error, or use \
245+ the attempt-loop pattern (several fixtures, at least one must decode, firing count \
246+ hard-asserted)."
247+ );
248+ let stale: Vec<&&str> = listed.iter().filter(|n| !found.contains(**n)).collect();
249+ assert!(
250+ stale.is_empty(),
251+ "{stale:#?} no longer swallow a decode error -- delete them from the list."
252+ );
253+ }
254+}
crates/ec-av1/src/stream.rsmodified+904 -27
@@ -125,19 +125,11 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
125 })?;125 })?;
126 // `read_cdef` (spec `decodeframe.c`, called at the first non-skip126 // `read_cdef` (spec `decodeframe.c`, called at the first non-skip
127 // block of each 64x64) only reads a literal `cdef_idx` when127 // block of each 64x64) only reads a literal `cdef_idx` when
128- // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (this128+ // `cdef_bits > 0`; at `cdef_bits == 0` there is nothing to read (a
129- // crate's own writer's only case, and both `lane-av1cdef` gate129+ // true no-op). lane-realworld r1: the per-64x64 `cdef_idx` literal is
130- // streams'), so the per-block symbol this crate's tile readers never130+ // now read (`maybe_read_cdef_idx` in decode.rs) and threaded into
131- // consume is a true no-op there. A `cdef_bits > 0` stream would131+ // [`crate::decode::apply_cdef`]'s per-superblock strength lookup, so
132- // desync the moment it hit a real strength selector this decoder132+ // a `cdef_bits > 0` stream no longer needs this refusal.
133- // never reads — refuse that by name rather than silently miscode,
134- // the same pattern as the other round-2 refusals below.
135- if header.cdef.bits != 0 {
136- return Err(Error::unsupported(
137- "AV1 decode_stream",
138- "a frame with cdef_bits > 0 (this decoder never reads the per-64x64 cdef_idx symbol)",
139- ));
140- }
141 // An intra frame's `decode_key_frame_tile*` now reads `tx_depth`133 // An intra frame's `decode_key_frame_tile*` now reads `tx_depth`
142 // under `TxMode::Select` (lane-av1txsel, spec 5.11.16): the key-frame134 // under `TxMode::Select` (lane-av1txsel, spec 5.11.16): the key-frame
143 // decode path threads `tx_select` through `decode_block`/135 // decode path threads `tx_select` through `decode_block`/
@@ -286,13 +278,58 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
286 // `skip_mode_present` refusal is gone.278 // `skip_mode_present` refusal is gone.
287 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names279 // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
288 // which tile's end-of-tile adapted CDFs become the frame's own; this280 // which tile's end-of-tile adapted CDFs become the frame's own; this
289- // decoder only ever decodes tile 0 (`tiles.first()` above), so a281+ // decoder still only ever *keeps* tile 0's adapted table (see the
290- // multi-tile frame is refused rather than silently forwarding the282+ // `context_update_tile_id != 0` refusal further down), so any frame
291- // wrong tile's table (or leaving the rest of the picture undecoded).283+ // naming a different tile there is refused rather than silently
292- if header.tile_info.cols > 1 || header.tile_info.rows > 1 {284+ // forwarding the wrong tile's table.
285+ //
286+ // lane-tiles r4: the multi-tile refusal itself is now scoped, not
287+ // blanket. `decode_key_frame_tile_with_cdfs` genuinely loops every
288+ // tile (r2/r3), proven pixel-exact by
289+ // `a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact`
290+ // (2 tile columns, `--loopfilter-control=0`) -- but that gate's own
291+ // doc comment names two gaps it deliberately sidesteps, so this
292+ // refusal keeps refusing exactly those:
293+ // - `decode_inter_frame_tile_with_cdfs` takes one `&[u8]` tile
294+ // payload, not a `tiles: &[&[u8]]` list -- it has no per-tile
295+ // loop at all, so an inter frame with >1 tile is still refused
296+ // unconditionally.
297+ // - Deblocking crosses tile boundaries by spec default (AV1 has
298+ // no `loop_filter_across_tiles_enabled`-style flag at all --
299+ // confirmed absent from `ec-av1-syntax`'s `loop_filter_params`
300+ // read, spec 5.9.11 has no such field either), but `PlaneBuf`'s
301+ // `tile_x0`/`tile_y0` origin only ever clips a tile's own
302+ // left/top reach, not a non-last column's right-edge reach --
303+ // so a key frame with `loop_filter.level` non-zero (deblocking
304+ // actually on) still refuses.
305+ // - The proven gate is 2 tile *columns*, 1 tile *row*; a
306+ // non-last column's right-edge reach bound past column 0 is
307+ // unimplemented for 3+ columns (r3's own known gap), so `cols`
308+ // is capped at 2. Tile rows are untested this round, so `rows`
309+ // stays capped at 1.
310+ let loop_filter_on = header.loop_filter.level.iter().any(|&l| l != 0);
311+ if header.frame_type != FrameType::Key && header.tile_info.cols > 1 {
312+ return Err(Error::unsupported(
313+ "AV1 decode_stream",
314+ "an inter frame with more than one tile (the inter tile-decode path has no per-tile loop, only key frames do)",
315+ ));
316+ }
317+ if header.tile_info.rows > 1 {
318+ return Err(Error::unsupported(
319+ "AV1 decode_stream",
320+ "a frame with more than one tile row (only tile columns are proven pixel-exact so far)",
321+ ));
322+ }
323+ if header.tile_info.cols > 2 {
324+ return Err(Error::unsupported(
325+ "AV1 decode_stream",
326+ "a frame with more than two tile columns (a non-last column's right-edge reach bound past column 0 is unimplemented)",
327+ ));
328+ }
329+ if header.tile_info.cols > 1 && loop_filter_on {
293 return Err(Error::unsupported(330 return Err(Error::unsupported(
294 "AV1 decode_stream",331 "AV1 decode_stream",
295- "a frame with more than one tile (this decoder only ever decodes tile 0)",332+ "a multi-tile frame with loop filtering enabled (deblocking crosses tile boundaries by spec default; PlaneBuf's tile origin does not clip a non-last column's right-edge reach)",
296 ));333 ));
297 }334 }
298 // `Tile::offset` is relative to the buffer `parse_obu` was handed335 // `Tile::offset` is relative to the buffer `parse_obu` was handed
@@ -300,6 +337,13 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
300 // to `obu_offset`, not to `data` as a whole.337 // to `obu_offset`, not to `data` as a whole.
301 let start = obu_offset + tile.offset;338 let start = obu_offset + tile.offset;
302 let tile_bytes = data.get(start..start + tile.size).ok_or(Error::NeedMore)?;339 let tile_bytes = data.get(start..start + tile.size).ok_or(Error::NeedMore)?;
340+ let tile_bufs: Vec<&[u8]> = tiles
341+ .iter()
342+ .map(|t| {
343+ data.get(obu_offset + t.offset..obu_offset + t.offset + t.size)
344+ .ok_or(Error::NeedMore)
345+ })
346+ .collect::<Result<_>>()?;
303 let enable_filter_intra = parser347 let enable_filter_intra = parser
304 .sequence_header()348 .sequence_header()
305 .is_some_and(|seq| seq.enable_filter_intra);349 .is_some_and(|seq| seq.enable_filter_intra);
@@ -360,7 +404,8 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
360 404
361 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {405 let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
362 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(406 let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
363- tile_bytes,407+ &tile_bufs,
408+ &header.tile_info,
364 header.mi_cols,409 header.mi_cols,
365 header.mi_rows,410 header.mi_rows,
366 header.quantization.base_q_idx,411 header.quantization.base_q_idx,
@@ -1855,6 +1900,272 @@ mod tests {
1855 );1900 );
1856 }1901 }
1857 1902
1903+ /// lane-chroma r2 stage 1: a real aomenc key frame with
1904+ /// `--enable-smooth-intra=1` (opposite of every sibling recipe's `=0`)
1905+ /// and `--enable-paeth-intra=0` -- paeth chroma stays off so the still-
1906+ /// refused smooth/paeth `uv_mode` (round-2, unrelated to this gate) never
1907+ /// fires; smooth *luma* neighbours are exactly what this gate wants to
1908+ /// exercise, proving [`decode::smooth_luma_hits`] actually landed a
1909+ /// directional block next to a smooth-predicted one and decoded
1910+ /// pixel-exact (the [`PlaneBuf::reconstruct`] `smooth_neighbor` fix).
1911+ #[test]
1912+ fn a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact() {
1913+ if !have_ffmpeg() {
1914+ eprintln!(
1915+ "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no ffmpeg"
1916+ );
1917+ return;
1918+ }
1919+ if !have_aomenc() {
1920+ eprintln!(
1921+ "SKIP a_real_aomenc_stream_with_smooth_luma_neighbour_decodes_pixel_exact: no aomenc at {}",
1922+ aomenc_path().display()
1923+ );
1924+ return;
1925+ }
1926+ let (width, height) = (64usize, 64usize);
1927+ let mut refusals = Vec::new();
1928+ let mut fired_runs = 0u32;
1929+ for attempt in 0..40u32 {
1930+ let seed = 42 + attempt;
1931+ let source = format!(
1932+ "mandelbrot=size=64x64:start_scale={}:rate=25",
1933+ 5.0 - f64::from(attempt) * 0.06
1934+ );
1935+ let y4m = Command::new("ffmpeg")
1936+ .args([
1937+ "-v",
1938+ "error",
1939+ "-f",
1940+ "lavfi",
1941+ "-i",
1942+ &source,
1943+ "-pix_fmt",
1944+ "yuv420p",
1945+ "-t",
1946+ "0.04",
1947+ "-f",
1948+ "yuv4mpegpipe",
1949+ "-",
1950+ ])
1951+ .stdin(Stdio::null())
1952+ .stdout(Stdio::piped())
1953+ .stderr(Stdio::piped())
1954+ .output()
1955+ .expect("ffmpeg failed to run");
1956+ assert!(
1957+ y4m.status.success(),
1958+ "ffmpeg fixture: {}",
1959+ String::from_utf8_lossy(&y4m.stderr)
1960+ );
1961+ let mut child = Command::new(aomenc_path())
1962+ .args([
1963+ "--codec=av1",
1964+ "--passes=1",
1965+ "--end-usage=q",
1966+ "--cq-level=45",
1967+ "--cpu-used=0",
1968+ "--enable-rect-partitions=0",
1969+ "--enable-ab-partitions=0",
1970+ "--enable-1to4-partitions=0",
1971+ "--enable-filter-intra=0",
1972+ "--enable-smooth-intra=1",
1973+ // Smooth/paeth chroma is a still-refused, separate
1974+ // round-2 gap -- off so no attempt trips it while this
1975+ // gate is purely about luma's edge-filter fix.
1976+ "--enable-paeth-intra=0",
1977+ "--enable-tx-size-search=0",
1978+ "--enable-cdef=0",
1979+ "--enable-restoration=0",
1980+ "--enable-intra-edge-filter=1",
1981+ "--max-partition-size=32",
1982+ "--min-partition-size=16",
1983+ "--enable-palette=0",
1984+ "--enable-intrabc=0",
1985+ "--enable-cfl-intra=0",
1986+ "--enable-ref-frame-mvs=0",
1987+ "--obu",
1988+ "-o",
1989+ "-",
1990+ "-",
1991+ ])
1992+ .stdin(Stdio::piped())
1993+ .stdout(Stdio::piped())
1994+ .stderr(Stdio::piped())
1995+ .spawn()
1996+ .expect("aomenc failed to start");
1997+ child
1998+ .stdin
1999+ .take()
2000+ .expect("aomenc stdin")
2001+ .write_all(&y4m.stdout)
2002+ .expect("writing y4m to aomenc");
2003+ let out = child.wait_with_output().expect("aomenc failed to run");
2004+ assert!(
2005+ out.status.success(),
2006+ "aomenc refused the fixture: {}",
2007+ String::from_utf8_lossy(&out.stderr)
2008+ );
2009+ let stream = out.stdout;
2010+ let smooth_before = decode::smooth_luma_hits();
2011+ let frames = match decode_stream(&stream) {
2012+ Ok(frames) => frames,
2013+ Err(e) => {
2014+ refusals.push(format!("seed {seed}: {e}"));
2015+ continue;
2016+ }
2017+ };
2018+ if decode::smooth_luma_hits() == smooth_before {
2019+ refusals.push(format!(
2020+ "seed {seed}: decoded, but no smooth-luma-neighbour block fired"
2021+ ));
2022+ continue;
2023+ }
2024+ fired_runs += 1;
2025+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
2026+ assert_eq!(
2027+ frames[0].y, ffmpeg_frames[0].y,
2028+ "luma vs ffmpeg (seed {seed})"
2029+ );
2030+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
2031+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
2032+ if fired_runs >= 4 {
2033+ return;
2034+ }
2035+ }
2036+ assert!(
2037+ fired_runs > 0,
2038+ "every attempt hit a named refusal or never exercised a smooth luma neighbour:\n{}",
2039+ refusals.join("\n")
2040+ );
2041+ }
2042+
2043+ /// The smooth/paeth-chroma gate (lane-chroma r1/r3): a real aomenc key
2044+ /// frame with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the
2045+ /// opposite of the directional-chroma gate below, which turns these OFF
2046+ /// to keep this gap from firing while directional chroma is under test).
2047+ /// Some seeds won't pick smooth/paeth for chroma at all -- retry like
2048+ /// every other real-encoder gate here, but the first attempt that
2049+ /// actually fires [`decode::smooth_uv_hits`] must decode pixel-exact.
2050+ #[test]
2051+ fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() {
2052+ if !have_ffmpeg() {
2053+ eprintln!(
2054+ "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg"
2055+ );
2056+ return;
2057+ }
2058+ if !have_aomenc() {
2059+ eprintln!(
2060+ "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}",
2061+ aomenc_path().display()
2062+ );
2063+ return;
2064+ }
2065+ let (width, height) = (64usize, 64usize);
2066+ let mut refusals = Vec::new();
2067+ let mut fired_runs = 0u32;
2068+ for attempt in 0..40u32 {
2069+ let seed = 42 + attempt;
2070+ let source = format!(
2071+ "mandelbrot=size=64x64:start_scale={}:rate=25",
2072+ 5.0 - f64::from(attempt) * 0.06
2073+ );
2074+ let y4m = Command::new("ffmpeg")
2075+ .args([
2076+ "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-t",
2077+ "0.04", "-f", "yuv4mpegpipe", "-",
2078+ ])
2079+ .stdin(Stdio::null())
2080+ .stdout(Stdio::piped())
2081+ .stderr(Stdio::piped())
2082+ .output()
2083+ .expect("ffmpeg failed to run");
2084+ assert!(
2085+ y4m.status.success(),
2086+ "ffmpeg fixture: {}",
2087+ String::from_utf8_lossy(&y4m.stderr)
2088+ );
2089+ let mut child = Command::new(aomenc_path())
2090+ .args([
2091+ "--codec=av1",
2092+ "--passes=1",
2093+ "--end-usage=q",
2094+ "--cq-level=45",
2095+ "--cpu-used=0",
2096+ "--enable-rect-partitions=0",
2097+ "--enable-ab-partitions=0",
2098+ "--enable-1to4-partitions=0",
2099+ "--enable-filter-intra=0",
2100+ "--enable-smooth-intra=1",
2101+ "--enable-paeth-intra=1",
2102+ "--enable-tx-size-search=0",
2103+ "--enable-cdef=0",
2104+ "--enable-restoration=0",
2105+ "--enable-intra-edge-filter=1",
2106+ "--max-partition-size=32",
2107+ // 8x8/leaf8 splits are a separate, already-named refusal.
2108+ "--min-partition-size=16",
2109+ "--enable-palette=0",
2110+ "--enable-intrabc=0",
2111+ "--enable-cfl-intra=0",
2112+ "--enable-ref-frame-mvs=0",
2113+ "--obu",
2114+ "-o",
2115+ "-",
2116+ "-",
2117+ ])
2118+ .stdin(Stdio::piped())
2119+ .stdout(Stdio::piped())
2120+ .stderr(Stdio::piped())
2121+ .spawn()
2122+ .expect("aomenc failed to start");
2123+ child
2124+ .stdin
2125+ .take()
2126+ .expect("aomenc stdin")
2127+ .write_all(&y4m.stdout)
2128+ .expect("writing y4m to aomenc");
2129+ let out = child.wait_with_output().expect("aomenc failed to run");
2130+ assert!(
2131+ out.status.success(),
2132+ "aomenc refused the fixture: {}",
2133+ String::from_utf8_lossy(&out.stderr)
2134+ );
2135+ let stream = out.stdout;
2136+ let smooth_before = decode::smooth_uv_hits();
2137+ let frames = match decode_stream(&stream) {
2138+ Ok(frames) => frames,
2139+ Err(e) => {
2140+ refusals.push(format!("seed {seed}: {e}"));
2141+ continue;
2142+ }
2143+ };
2144+ if decode::smooth_uv_hits() == smooth_before {
2145+ refusals.push(format!(
2146+ "seed {seed}: decoded, but no smooth/paeth uv_mode fired"
2147+ ));
2148+ continue;
2149+ }
2150+ fired_runs += 1;
2151+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
2152+ assert_eq!(
2153+ frames[0].y, ffmpeg_frames[0].y,
2154+ "luma vs ffmpeg (seed {seed})"
2155+ );
2156+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
2157+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
2158+ if fired_runs >= 4 {
2159+ return;
2160+ }
2161+ }
2162+ assert!(
2163+ fired_runs > 0,
2164+ "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}",
2165+ refusals.join("\n")
2166+ );
2167+ }
2168+
1858 /// The directional-chroma/angle-delta gate: a real aomenc key frame with2169 /// The directional-chroma/angle-delta gate: a real aomenc key frame with
1859 /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the2170 /// `--enable-directional-intra`/`--enable-angle-delta` left ON (the
1860 /// opposite of every sibling recipe's `=0`, which existed specifically to2171 /// opposite of every sibling recipe's `=0`, which existed specifically to
@@ -4813,14 +5124,211 @@ mod tests {
4813 );5124 );
4814 }5125 }
4815 5126
4816- /// Pinned streams captured by `EC_AV1_GATE_DUMP` off5127+ /// lane-realworld r2: `read_cdef` (spec 5.11.56) ported -- per-superblock
4817- /// `a_real_aomenc_stream_with_warped_motion_refuses_or_matches` -- each5128+ /// `cdef_idx`, wired at all five `skip`-decode sites, `apply_cdef` looks
4818- /// one is a former mismatch, kept as a regression pin (warp-mismatch:5129+ /// up strength through the grid instead of a hardcoded `[0]`. Structure
4819- /// the WARPED_CAUSAL interp-read suppression; warp-flake-7: the same5130+ /// copied from `a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact`
4820- /// suppression for skip_mode blocks; warp-flake-5: mvstack entry5131+ /// but `--enable-cdef=1` (the one thing that gate turns off) and every
4821- /// clamping; ii-flake-1..8: interintra neighbours excluded from5132+ /// *other* filter/mode feature this lane doesn't touch disabled, so a
4822- /// warp-sample gathering, ref_frame[1] == INTRA_FRAME in the mi grid).5133+ /// mismatch here can only be attributed to CDEF. `cdef_idx_hits()` is a
4823- /// `EC_AV1_GATE_DUMP_PIN` overrides to a single stream.5134+ /// hard assert -- a run that never reads a real cdef_idx symbol proves
5135+ /// nothing (class `gate-blind-to-feature`).
5136+ #[test]
5137+ fn a_real_aomenc_stream_with_cdef_decodes_pixel_exact() {
5138+ const NAME: &str = "a_real_aomenc_stream_with_cdef_decodes_pixel_exact";
5139+ let _gate_lock = lock_gate_counters();
5140+ if !have_ffmpeg() {
5141+ eprintln!("SKIP {NAME}: no ffmpeg");
5142+ return;
5143+ }
5144+ if !have_aomenc() {
5145+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
5146+ return;
5147+ }
5148+ // cdef_bits selects among PER-SUPERBLOCK strengths -- a single-SB
5149+ // 64x64 frame (the other gates' size) gives aomenc nothing to
5150+ // differentiate, so it always writes bits=0 and cdef_idx is never
5151+ // read. 128x64 = 2 SBs is the minimum that lets aomenc's RD ever
5152+ // pick bits > 0. Multi-SB content at --cpu-used=0 (every other
5153+ // gate's setting) makes aomenc pick PARTITION_HORZ_4/VERT_B etc.
5154+ // at the top SB level regardless of the ab/1to4-partitions=0
5155+ // flags below (a real gap: this decoder's intra part64 match only
5156+ // covers NONE/SPLIT, and the inter path blindly assumes SPLIT --
5157+ // both pre-existing, out of this lane's scope); --cpu-used=4
5158+ // avoids that RD path entirely and needs --aq-mode=0
5159+ // --deltaq-mode=0 to keep delta_q/delta_lf (next lane step) off.
5160+ let (width, height, frame_count) = (128usize, 64usize, 24usize);
5161+ let mut named_refusals = 0u32;
5162+ let mut matched = 0u32;
5163+ let n_attempts: u32 = std::env::var("EC_CDEF_GATE_ATTEMPTS")
5164+ .ok()
5165+ .and_then(|s| s.parse().ok())
5166+ .unwrap_or(40);
5167+ for attempt in 0..n_attempts {
5168+ let seed = 42 + attempt;
5169+ let duration = frame_count as f64 / 25.0;
5170+ // mandelbrot's ringing-prone hard edges are what CDEF's RD
5171+ // search targets; flat gradients (charter's first guess) may
5172+ // never make aomenc choose cdef_bits > 0.
5173+ let source = format!(
5174+ "mandelbrot=size={width}x{height}:rate=25:start_x={sx}:start_y={sy}",
5175+ sx = -0.6 + 0.005 * (attempt as f64),
5176+ sy = -0.4 + 0.005 * (attempt as f64)
5177+ );
5178+ let y4m = Command::new("ffmpeg")
5179+ .args([
5180+ "-v",
5181+ "error",
5182+ "-f",
5183+ "lavfi",
5184+ "-i",
5185+ &source,
5186+ "-t",
5187+ &duration.to_string(),
5188+ "-pix_fmt",
5189+ "yuv420p",
5190+ "-f",
5191+ "yuv4mpegpipe",
5192+ "-",
5193+ ])
5194+ .stdin(Stdio::null())
5195+ .stdout(Stdio::piped())
5196+ .stderr(Stdio::piped())
5197+ .output()
5198+ .expect("ffmpeg failed to run");
5199+ assert!(
5200+ y4m.status.success(),
5201+ "ffmpeg fixture: {}",
5202+ String::from_utf8_lossy(&y4m.stderr)
5203+ );
5204+ let args: Vec<&str> = vec![
5205+ "--codec=av1",
5206+ "--passes=1",
5207+ "--end-usage=q",
5208+ "--cq-level=45",
5209+ "--cpu-used=4",
5210+ "--aq-mode=0",
5211+ "--deltaq-mode=0",
5212+ "--kf-max-dist=1000",
5213+ "--threads=1",
5214+ "--row-mt=0",
5215+ "--auto-alt-ref=1",
5216+ "--lag-in-frames=16",
5217+ "--enable-fwd-kf=0",
5218+ "--enable-order-hint=1",
5219+ // r2: a starved inter toolset (everything below off) pushes
5220+ // aomenc's RD toward exotic partition shapes (HORZ_4/VERT_B
5221+ // etc.) at the SB(64) level even with those partition
5222+ // flags off -- this decoder's part64 8/9/10-way arms and
5223+ // the inter path's blind SPLIT assumption don't cover that;
5224+ // keeping the same rich toolset the (working, ab/1to4-off)
5225+ // masked-compound gate uses avoids it.
5226+ "--enable-warped-motion=1",
5227+ "--enable-global-motion=0",
5228+ "--enable-obmc=1",
5229+ "--tune-content=default",
5230+ "--enable-masked-comp=1",
5231+ "--enable-dist-wtd-comp=0",
5232+ "--enable-interintra-comp=1",
5233+ "--enable-onesided-comp=0",
5234+ "--enable-interintra-wedge=0",
5235+ "--enable-smooth-interintra=1",
5236+ "--enable-rect-partitions=0",
5237+ "--enable-ab-partitions=0",
5238+ "--enable-1to4-partitions=0",
5239+ "--enable-filter-intra=0",
5240+ "--enable-smooth-intra=0",
5241+ "--enable-paeth-intra=0",
5242+ "--enable-directional-intra=0",
5243+ "--enable-angle-delta=0",
5244+ "--enable-tx-size-search=0",
5245+ "--enable-cdef=1",
5246+ "--enable-restoration=0",
5247+ "--max-partition-size=32",
5248+ "--min-partition-size=32",
5249+ "--enable-palette=0",
5250+ "--enable-intrabc=0",
5251+ "--enable-cfl-intra=0",
5252+ "--enable-ref-frame-mvs=0",
5253+ "--obu",
5254+ "-o",
5255+ "-",
5256+ "-",
5257+ ];
5258+ let mut child = Command::new(aomenc_path())
5259+ .args(&args)
5260+ .stdin(Stdio::piped())
5261+ .stdout(Stdio::piped())
5262+ .stderr(Stdio::piped())
5263+ .spawn()
5264+ .expect("aomenc failed to start");
5265+ child
5266+ .stdin
5267+ .take()
5268+ .expect("aomenc stdin")
5269+ .write_all(&y4m.stdout)
5270+ .expect("writing y4m to aomenc");
5271+ let out = child.wait_with_output().expect("aomenc failed to run");
5272+ assert!(
5273+ out.status.success(),
5274+ "aomenc refused the fixture: {}",
5275+ String::from_utf8_lossy(&out.stderr)
5276+ );
5277+ let stream = out.stdout;
5278+ let frames = match decode_stream(&stream) {
5279+ Err(e) => {
5280+ let msg = e.to_string();
5281+ assert!(
5282+ msg.contains("unsupported"),
5283+ "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
5284+ );
5285+ assert!(
5286+ !msg.contains("cdef"),
5287+ "{NAME} refused on cdef (seed {seed}) -- cdef_idx decode is ported: {msg}"
5288+ );
5289+ named_refusals += 1;
5290+ eprintln!("seed {seed} refusal: {msg}");
5291+ continue;
5292+ }
5293+ Ok(frames) => frames,
5294+ };
5295+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
5296+ assert_eq!(frames.len(), frame_count);
5297+ let mismatched = frames
5298+ .iter()
5299+ .zip(&ffmpeg_frames)
5300+ .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
5301+ if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
5302+ std::fs::write(&path, &stream).expect("writing pinned stream");
5303+ eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
5304+ }
5305+ for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
5306+ assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})");
5307+ assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})");
5308+ assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})");
5309+ }
5310+ matched += 1;
5311+ }
5312+ assert!(
5313+ crate::decode::cdef_idx_hits() > 0,
5314+ "{NAME}: zero cdef_idx blocks fired ({matched} matches, {named_refusals} other \
5315+ refusals out of {n_attempts}) -- gate proved nothing this run"
5316+ );
5317+ eprintln!(
5318+ "{NAME}: {named_refusals} other-capability refusals, {matched} pixel-exact matches \
5319+ out of {n_attempts}, cdef_idx_hits={}",
5320+ crate::decode::cdef_idx_hits()
5321+ );
5322+ }
5323+
5324+ /// Pinned streams captured by `EC_AV1_GATE_DUMP` off
5325+ /// `a_real_aomenc_stream_with_warped_motion_refuses_or_matches` -- each
5326+ /// one is a former mismatch, kept as a regression pin (warp-mismatch:
5327+ /// the WARPED_CAUSAL interp-read suppression; warp-flake-7: the same
5328+ /// suppression for skip_mode blocks; warp-flake-5: mvstack entry
5329+ /// clamping; ii-flake-1..8: interintra neighbours excluded from
5330+ /// warp-sample gathering, ref_frame[1] == INTRA_FRAME in the mi grid).
5331+ /// `EC_AV1_GATE_DUMP_PIN` overrides to a single stream.
4824 /// Deterministic and static -- `#[ignore]`d because the gitignored5332 /// Deterministic and static -- `#[ignore]`d because the gitignored
4825 /// fixtures dir may be absent; run manually.5333 /// fixtures dir may be absent; run manually.
4826 #[test]5334 #[test]
@@ -5629,4 +6137,373 @@ mod tests {
5629 }6137 }
5630 }6138 }
5631 }6139 }
6140+
6141+ /// lane-tiles r3: a real two-tile-column aomenc key frame, decoded
6142+ /// through [`decode_key_frame_tile_with_cdfs`] directly with the whole
6143+ /// `tiles: &[&[u8]]` list -- `decode_stream`'s `cols > 1 || rows > 1`
6144+ /// refusal (this file, ~line 292) still fires for any stream this wide,
6145+ /// so this gate bypasses it on purpose to prove the per-tile loop r2
6146+ /// landed (fresh `SymbolDecoder`/CDF copy per tile, `Neighbours::start_tile`,
6147+ /// `PlaneBuf::set_tile_origin`) actually decodes both tiles pixel-exact
6148+ /// before that refusal is lifted. 128x64 is exactly two 64x64
6149+ /// superblocks wide with `--tile-columns=1` (`TileCols=2`), so tile 1 is
6150+ /// also the frame's own right edge -- the known gap (`PlaneBuf`'s
6151+ /// tile_x0/tile_y0 only clip left/top reach, not a non-last column's
6152+ /// right-edge reach) does not apply to this fixture; it would to a
6153+ /// 3+-column one. Tile count itself is a structural aomenc param, not
6154+ /// RD-dependent content, but this decoder's chroma smooth/paeth gap
6155+ /// (`decode.rs` "a smooth or paeth chroma mode (round 2)", unrelated to
6156+ /// tiles, pre-dating this lane) is content-dependent -- no aomenc flag
6157+ /// disables UV-only smooth/paeth search, so a small seed sweep is
6158+ /// needed the same way the sibling `a_real_aomenc_stream_with_*` gates
6159+ /// retry past unrelated named refusals (every refusal in this crate is
6160+ /// prefixed `"AV1 tile"` regardless of category, so unlike the sibling
6161+ /// gates' `warp`/`obmc`/`interintra` banned lists there is no
6162+ /// tile-specific substring to forbid here -- `matched > 0` plus the
6163+ /// hard `tile_hits > 1`/pixel-exact asserts on any actual decode are
6164+ /// the real proof).
6165+ #[test]
6166+ fn a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact() {
6167+ const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact";
6168+ if !have_ffmpeg() {
6169+ eprintln!("SKIP {NAME}: no ffmpeg");
6170+ return;
6171+ }
6172+ if !have_aomenc() {
6173+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6174+ return;
6175+ }
6176+ let (width, height) = (128usize, 64usize);
6177+ let mut matched = 0u32;
6178+ let mut named_refusals = 0u32;
6179+ for attempt in 0..20u32 {
6180+ let seed = 42 + attempt;
6181+ let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
6182+ let y4m = Command::new("ffmpeg")
6183+ .args([
6184+ "-v",
6185+ "error",
6186+ "-f",
6187+ "lavfi",
6188+ "-i",
6189+ &source,
6190+ "-pix_fmt",
6191+ "yuv420p",
6192+ "-f",
6193+ "yuv4mpegpipe",
6194+ "-",
6195+ ])
6196+ .stdin(Stdio::null())
6197+ .stdout(Stdio::piped())
6198+ .stderr(Stdio::piped())
6199+ .output()
6200+ .expect("ffmpeg failed to run");
6201+ assert!(
6202+ y4m.status.success(),
6203+ "ffmpeg fixture: {}",
6204+ String::from_utf8_lossy(&y4m.stderr)
6205+ );
6206+ let mut child = Command::new(aomenc_path())
6207+ .args([
6208+ "--codec=av1",
6209+ "--passes=1",
6210+ "--end-usage=q",
6211+ "--cq-level=45",
6212+ "--cpu-used=0",
6213+ "--limit=1",
6214+ "--kf-max-dist=1000",
6215+ "--threads=1",
6216+ "--row-mt=0",
6217+ "--tile-columns=1",
6218+ "--tile-rows=0",
6219+ // This decoder hardcodes SB_MI=16 (64px) superblocks
6220+ // everywhere (`decode.rs`'s sb128 dead-end, ledger
6221+ // `av1-superblock-contexts`) -- without this, aomenc's
6222+ // own default 128x128 superblock makes 128x64 exactly
6223+ // ONE superblock wide, so `--tile-columns=1` has nothing
6224+ // to split and `cols` comes back 1.
6225+ "--sb-size=64",
6226+ // Deblocking crosses tile boundaries by default (spec
6227+ // `loop_filter_across_tiles_enabled`); `PlaneBuf`'s
6228+ // tile_x0/tile_y0 origin only ever clips a tile's own
6229+ // left/top reach (r2/r3's documented known gap), so a
6230+ // non-last tile column's right-edge deblock would read
6231+ // into the next tile's still-undecoded/differently-
6232+ // origined samples. Off here since deblocking itself is
6233+ // not what this gate is proving.
6234+ "--loopfilter-control=0",
6235+ "--enable-rect-partitions=0",
6236+ "--enable-ab-partitions=0",
6237+ "--enable-1to4-partitions=0",
6238+ "--enable-filter-intra=0",
6239+ "--enable-smooth-intra=0",
6240+ "--enable-paeth-intra=0",
6241+ "--enable-directional-intra=0",
6242+ "--enable-angle-delta=0",
6243+ "--enable-tx-size-search=0",
6244+ "--enable-cdef=0",
6245+ "--enable-restoration=0",
6246+ "--max-partition-size=32",
6247+ "--min-partition-size=32",
6248+ "--enable-palette=0",
6249+ "--enable-intrabc=0",
6250+ "--enable-cfl-intra=0",
6251+ "--obu",
6252+ "-o",
6253+ "-",
6254+ "-",
6255+ ])
6256+ .stdin(Stdio::piped())
6257+ .stdout(Stdio::piped())
6258+ .stderr(Stdio::piped())
6259+ .spawn()
6260+ .expect("aomenc failed to start");
6261+ child
6262+ .stdin
6263+ .take()
6264+ .expect("aomenc stdin")
6265+ .write_all(&y4m.stdout)
6266+ .expect("writing y4m to aomenc");
6267+ let out = child.wait_with_output().expect("aomenc failed to run");
6268+ assert!(
6269+ out.status.success(),
6270+ "aomenc refused the fixture: {}",
6271+ String::from_utf8_lossy(&out.stderr)
6272+ );
6273+ let stream = out.stdout;
6274+
6275+ // Parse the stream ourselves (rather than `decode_stream`, whose
6276+ // multi-tile refusal is exactly what this gate exists to run
6277+ // ahead of) to reach the real `Frame` OBU's `tile_info` and its
6278+ // full `Vec<Tile>` -- `Av1Parser::parse_obu` already locates
6279+ // every tile in a multi-tile tile group (`parse_tile_group`), it
6280+ // is only `decode_stream` that ever narrows this to
6281+ // `tiles.first()`.
6282+ let mut parser = Av1Parser::new();
6283+ let mut pos = 0usize;
6284+ let mut frame = None;
6285+ while pos < stream.len() {
6286+ let obu_offset = pos;
6287+ let obu = parser.parse_obu(&stream[pos..]).unwrap();
6288+ pos += obu.total_size;
6289+ if let ObuKind::Frame(header, tiles) = obu.kind {
6290+ frame = Some((header, tiles, obu_offset));
6291+ break;
6292+ }
6293+ }
6294+ let (header, tiles, obu_offset) = frame.expect("stream has a Frame OBU");
6295+ assert!(
6296+ header.tile_info.cols > 1,
6297+ "{NAME}: aomenc did not actually split into >1 tile column (cols={}, seed {seed})",
6298+ header.tile_info.cols
6299+ );
6300+ assert_eq!(
6301+ tiles.len(),
6302+ header.tile_info.cols as usize,
6303+ "{NAME}: expected one tile per column (seed {seed})"
6304+ );
6305+ // `Tile::offset` is relative to the buffer `parse_obu` was
6306+ // handed (`&stream[pos..]` at the time this OBU was parsed), so
6307+ // it needs `obu_offset` added back -- the same adjustment
6308+ // `decode_stream` makes for its own single-tile slice above.
6309+ let tile_bufs: Vec<&[u8]> = tiles
6310+ .iter()
6311+ .map(|t| &stream[obu_offset + t.offset..obu_offset + t.offset + t.size])
6312+ .collect();
6313+
6314+ let enable_filter_intra = parser
6315+ .sequence_header()
6316+ .is_some_and(|seq| seq.enable_filter_intra);
6317+ let enable_edge_filter = parser
6318+ .sequence_header()
6319+ .is_some_and(|seq| seq.enable_intra_edge_filter);
6320+
6321+ let before = crate::decode::tile_hits();
6322+ let picture = match decode_key_frame_tile_with_cdfs(
6323+ &tile_bufs,
6324+ &header.tile_info,
6325+ header.mi_cols,
6326+ header.mi_rows,
6327+ header.quantization.base_q_idx,
6328+ header.frame_width,
6329+ header.frame_height,
6330+ enable_filter_intra,
6331+ enable_edge_filter,
6332+ &header.cdef,
6333+ &header.loop_filter,
6334+ None,
6335+ header.tx_mode == TxMode::Select,
6336+ header.reduced_tx_set,
6337+ header.allow_screen_content_tools,
6338+ header.allow_intrabc,
6339+ ) {
6340+ Err(e) => {
6341+ let msg = e.to_string();
6342+ assert!(
6343+ msg.contains("unsupported"),
6344+ "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
6345+ );
6346+ named_refusals += 1;
6347+ eprintln!("seed {seed} refusal: {msg}");
6348+ continue;
6349+ }
6350+ Ok((picture, _end_cdfs)) => picture,
6351+ };
6352+ let hits = crate::decode::tile_hits() - before;
6353+ assert!(
6354+ hits > 1,
6355+ "{NAME}: tile_hits delta was {hits}, expected >1 -- both tiles must actually \
6356+ decode, not just tile 0 (seed {seed})"
6357+ );
6358+
6359+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
6360+ assert_eq!(picture.y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
6361+ assert_eq!(picture.u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
6362+ assert_eq!(picture.v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
6363+ matched += 1;
6364+ }
6365+ assert!(
6366+ matched > 0,
6367+ "{NAME}: every attempt refused ({named_refusals} refusals); the gate never decoded \
6368+ a two-tile-column stream"
6369+ );
6370+ eprintln!(
6371+ "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
6372+ );
6373+ }
6374+
6375+ /// lane-tiles r4: the same real two-tile-column stream as the gate
6376+ /// above, this time run through `decode_stream` itself -- the entry
6377+ /// point real callers use, not the `decode_key_frame_tile_with_cdfs`
6378+ /// bypass. Proves the `cols > 1` refusal is actually lifted (not just
6379+ /// that the underlying per-tile loop works) for the scoped case this
6380+ /// round proved safe: 2 tile columns, 1 tile row, key frame, loop
6381+ /// filtering off (`--loopfilter-control=0` stays -- deblocking crosses
6382+ /// tile boundaries by spec default and `PlaneBuf` cannot bound a
6383+ /// non-last column's right-edge reach yet, see the refusal's own doc
6384+ /// comment above `decode_stream`).
6385+ #[test]
6386+ fn a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream() {
6387+ const NAME: &str = "a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream";
6388+ if !have_ffmpeg() {
6389+ eprintln!("SKIP {NAME}: no ffmpeg");
6390+ return;
6391+ }
6392+ if !have_aomenc() {
6393+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
6394+ return;
6395+ }
6396+ let (width, height) = (128usize, 64usize);
6397+ let mut matched = 0u32;
6398+ let mut named_refusals = 0u32;
6399+ for attempt in 0..20u32 {
6400+ let seed = 42 + attempt;
6401+ let source = gradients_source(seed, width, height, "duration=0.04:rate=25");
6402+ let y4m = Command::new("ffmpeg")
6403+ .args([
6404+ "-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", "yuv420p", "-f",
6405+ "yuv4mpegpipe", "-",
6406+ ])
6407+ .stdin(Stdio::null())
6408+ .stdout(Stdio::piped())
6409+ .stderr(Stdio::piped())
6410+ .output()
6411+ .expect("ffmpeg failed to run");
6412+ assert!(
6413+ y4m.status.success(),
6414+ "ffmpeg fixture: {}",
6415+ String::from_utf8_lossy(&y4m.stderr)
6416+ );
6417+ let mut child = Command::new(aomenc_path())
6418+ .args([
6419+ "--codec=av1",
6420+ "--passes=1",
6421+ "--end-usage=q",
6422+ "--cq-level=45",
6423+ "--cpu-used=0",
6424+ "--limit=1",
6425+ "--kf-max-dist=1000",
6426+ "--threads=1",
6427+ "--row-mt=0",
6428+ "--tile-columns=1",
6429+ "--tile-rows=0",
6430+ "--sb-size=64",
6431+ "--loopfilter-control=0",
6432+ "--enable-rect-partitions=0",
6433+ "--enable-ab-partitions=0",
6434+ "--enable-1to4-partitions=0",
6435+ "--enable-filter-intra=0",
6436+ "--enable-smooth-intra=0",
6437+ "--enable-paeth-intra=0",
6438+ "--enable-directional-intra=0",
6439+ "--enable-angle-delta=0",
6440+ "--enable-tx-size-search=0",
6441+ "--enable-cdef=0",
6442+ "--enable-restoration=0",
6443+ "--max-partition-size=32",
6444+ "--min-partition-size=32",
6445+ "--enable-palette=0",
6446+ "--enable-intrabc=0",
6447+ "--enable-cfl-intra=0",
6448+ "--obu",
6449+ "-o",
6450+ "-",
6451+ "-",
6452+ ])
6453+ .stdin(Stdio::piped())
6454+ .stdout(Stdio::piped())
6455+ .stderr(Stdio::piped())
6456+ .spawn()
6457+ .expect("aomenc failed to start");
6458+ child
6459+ .stdin
6460+ .take()
6461+ .expect("aomenc stdin")
6462+ .write_all(&y4m.stdout)
6463+ .expect("writing y4m to aomenc");
6464+ let out = child.wait_with_output().expect("aomenc failed to run");
6465+ assert!(
6466+ out.status.success(),
6467+ "aomenc refused the fixture: {}",
6468+ String::from_utf8_lossy(&out.stderr)
6469+ );
6470+ let stream = out.stdout;
6471+
6472+ let before = crate::decode::tile_hits();
6473+ let pictures = match decode_stream(&stream) {
6474+ Err(e) => {
6475+ let msg = e.to_string();
6476+ assert!(
6477+ msg.contains("unsupported"),
6478+ "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
6479+ );
6480+ named_refusals += 1;
6481+ eprintln!("seed {seed} refusal: {msg}");
6482+ continue;
6483+ }
6484+ Ok(pictures) => pictures,
6485+ };
6486+ let hits = crate::decode::tile_hits() - before;
6487+ assert!(
6488+ hits > 1,
6489+ "{NAME}: tile_hits delta was {hits}, expected >1 -- both tiles must actually \
6490+ decode, not just tile 0 (seed {seed})"
6491+ );
6492+ assert_eq!(pictures.len(), 1, "{NAME}: expected exactly 1 picture (seed {seed})");
6493+
6494+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
6495+ assert_eq!(pictures[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
6496+ assert_eq!(pictures[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
6497+ assert_eq!(pictures[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
6498+ matched += 1;
6499+ }
6500+ assert!(
6501+ matched > 0,
6502+ "{NAME}: every attempt refused ({named_refusals} refusals); decode_stream never \
6503+ decoded a two-tile-column stream"
6504+ );
6505+ eprintln!(
6506+ "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals out of 20"
6507+ );
6508+ }
5632 }6509 }
lanes/chroma-r1-attempt.diffadded+254 -0
@@ -0,0 +1,254 @@
1+diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs
2+index fc53c53..9abc050 100644
3+--- a/crates/ec-av1/src/decode.rs
4++++ b/crates/ec-av1/src/decode.rs
5+@@ -126,6 +126,20 @@ pub(crate) fn directional_uv_hits() -> usize {
6+ DIRECTIONAL_UV_HITS.with(|c| c.get())
7+ }
8+
9++/// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
10++/// across every call in the process -- lane-chroma r1's own before/after
11++/// counter, proving a stream actually exercised chroma's smooth/paeth
12++/// predictor rather than every block landing on DC/CFL/directional.
13++thread_local! {
14++ static SMOOTH_UV_HITS: std::cell::Cell<usize> =
15++ const { std::cell::Cell::new(0) };
16++}
17++
18++/// Current value of [`SMOOTH_UV_HITS`].
19++pub(crate) fn smooth_uv_hits() -> usize {
20++ SMOOTH_UV_HITS.with(|c| c.get())
21++}
22++
23+ /// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
24+ /// something other than [`ANGLE_DELTA_ZERO`], across every call in the
25+ /// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
26+@@ -1967,7 +1981,7 @@ fn read_intra_mode_rect(
27+ None
28+ };
29+ if (9..=12).contains(&uv_mode) {
30+- return Err(unsupported("a smooth or paeth chroma mode (round 2)"));
31++ SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
32+ }
33+ let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
34+ DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
35+@@ -2447,15 +2461,15 @@ fn read_intra_mode(
36+ } else {
37+ None
38+ };
39+- // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
40+- // from this lane's directional chroma: a corner block with neither
41+- // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
42+- // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
43+- // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
44+- // bug in that fallback this lane's own scope does not cover. Keep it
45+- // refused here rather than ship a silently-wrong decode.
46++ // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma: lane-chroma r1 lands this --
47++ // the predictor itself (`intra::predict`) is already shared with luma and
48++ // already spec-correct for the no-neighbour corner case (127/129/128 is
49++ // the spec's own default, `Edges::build`). The earlier round's "worst
50++ // delta 78" trace was `smooth_neighbor` hardcoded `false` interacting
51++ // with a DIFFERENT bug that has since been fixed elsewhere; re-verified
52++ // clean under `a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact`.
53+ if (9..=12).contains(&uv_mode) {
54+- return Err(unsupported("a smooth or paeth chroma mode (round 2)"));
55++ SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
56+ }
57+ // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
58+ // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
59+diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs
60+index 20ff033..31479d2 100644
61+--- a/crates/ec-av1/src/stream.rs
62++++ b/crates/ec-av1/src/stream.rs
63+@@ -1861,6 +1861,191 @@ mod tests {
64+ );
65+ }
66+
67++ /// The smooth/paeth-chroma gate (lane-chroma r1): a real aomenc key frame
68++ /// with `--enable-smooth-intra=1 --enable-paeth-intra=1` (the opposite of
69++ /// the directional-chroma gate above, which turned these OFF to keep this
70++ /// round-2 gap from firing while directional chroma was under test) and
71++ /// directional intra left on aomenc's own default too, so the RD search
72++ /// is free to land on any `uv_mode`. Some seeds won't pick smooth/paeth
73++ /// for chroma at all -- retry like every other real-encoder gate here,
74++ /// but the first attempt that actually fires [`decode::smooth_uv_hits`]
75++ /// must decode pixel-exact.
76++ #[test]
77++ fn a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact() {
78++ if !have_ffmpeg() {
79++ eprintln!(
80++ "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no ffmpeg"
81++ );
82++ return;
83++ }
84++ if !have_aomenc() {
85++ eprintln!(
86++ "SKIP a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact: no aomenc at {}",
87++ aomenc_path().display()
88++ );
89++ return;
90++ }
91++ let (width, height) = (64usize, 64usize);
92++ let mut refusals = Vec::new();
93++ let mut fired_runs = 0u32;
94++ for attempt in 0..40u32 {
95++ let seed = 42 + attempt;
96++ let source = format!(
97++ "mandelbrot=size=64x64:start_scale={}:rate=25",
98++ 5.0 - f64::from(attempt) * 0.06
99++ );
100++ let y4m = Command::new("ffmpeg")
101++ .args([
102++ "-v",
103++ "error",
104++ "-f",
105++ "lavfi",
106++ "-i",
107++ &source,
108++ "-pix_fmt",
109++ "yuv420p",
110++ "-t",
111++ "0.04",
112++ "-f",
113++ "yuv4mpegpipe",
114++ "-",
115++ ])
116++ .stdin(Stdio::null())
117++ .stdout(Stdio::piped())
118++ .stderr(Stdio::piped())
119++ .output()
120++ .expect("ffmpeg failed to run");
121++ assert!(
122++ y4m.status.success(),
123++ "ffmpeg fixture: {}",
124++ String::from_utf8_lossy(&y4m.stderr)
125++ );
126++ let mut child = Command::new(aomenc_path())
127++ .args([
128++ "--codec=av1",
129++ "--passes=1",
130++ "--end-usage=q",
131++ "--cq-level=45",
132++ "--cpu-used=0",
133++ "--enable-rect-partitions=0",
134++ "--enable-ab-partitions=0",
135++ "--enable-1to4-partitions=0",
136++ "--enable-filter-intra=0",
137++ "--enable-smooth-intra=1",
138++ "--enable-paeth-intra=1",
139++ "--enable-tx-size-search=0",
140++ "--enable-cdef=0",
141++ "--enable-restoration=0",
142++ "--enable-intra-edge-filter=1",
143++ "--max-partition-size=32",
144++ // Same reason as the tx-select gate above: 8x8 and other
145++ // sub-16x16 splits are a separate, already-named refusal.
146++ "--min-partition-size=16",
147++ "--enable-palette=0",
148++ "--enable-intrabc=0",
149++ "--enable-cfl-intra=0",
150++ // use_ref_frame_mvs (temporal MV projection) is unimplemented in mvstack;
151++ // leaving it on silently desyncs symbols on inter frames (grainfix lesson).
152++ "--enable-ref-frame-mvs=0",
153++ "--obu",
154++ "-o",
155++ "-",
156++ "-",
157++ ])
158++ .stdin(Stdio::piped())
159++ .stdout(Stdio::piped())
160++ .stderr(Stdio::piped())
161++ .spawn()
162++ .expect("aomenc failed to start");
163++ child
164++ .stdin
165++ .take()
166++ .expect("aomenc stdin")
167++ .write_all(&y4m.stdout)
168++ .expect("writing y4m to aomenc");
169++ let out = child.wait_with_output().expect("aomenc failed to run");
170++ assert!(
171++ out.status.success(),
172++ "aomenc refused the fixture: {}",
173++ String::from_utf8_lossy(&out.stderr)
174++ );
175++ let stream = out.stdout;
176++ let smooth_before = decode::smooth_uv_hits();
177++ let frames = match decode_stream(&stream) {
178++ Ok(frames) => frames,
179++ Err(e) => {
180++ refusals.push(format!("seed {seed}: {e}"));
181++ continue;
182++ }
183++ };
184++ if decode::smooth_uv_hits() == smooth_before {
185++ refusals.push(format!(
186++ "seed {seed}: decoded, but no smooth/paeth uv_mode fired"
187++ ));
188++ continue;
189++ }
190++ fired_runs += 1;
191++ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
192++ let mismatched = frames[0].y != ffmpeg_frames[0].y
193++ || frames[0].u != ffmpeg_frames[0].u
194++ || frames[0].v != ffmpeg_frames[0].v;
195++ if mismatched && let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
196++ std::fs::write(&path, &stream).expect("writing pinned stream");
197++ eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
198++ }
199++ assert_eq!(
200++ frames[0].y, ffmpeg_frames[0].y,
201++ "luma vs ffmpeg (seed {seed})"
202++ );
203++ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg (seed {seed})");
204++ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg (seed {seed})");
205++ if fired_runs >= 4 {
206++ return;
207++ }
208++ }
209++ assert!(
210++ fired_runs > 0,
211++ "every attempt hit a named refusal or never exercised smooth/paeth chroma:\n{}",
212++ refusals.join("\n")
213++ );
214++ }
215++
216++ #[test]
217++ #[ignore]
218++ fn zzz_smooth_pin_diag() {
219++ let path = std::env::var("EC_ZZZ_PATH").unwrap_or_else(|_| {
220++ "/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/baaa03f8-c4ff-4469-8ebb-83100429b150/scratchpad/smooth-pin.obu"
221++ .to_string()
222++ });
223++ let stream = std::fs::read(&path).unwrap();
224++ let frames = decode_stream(&stream).unwrap();
225++ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, 64, 64, 1);
226++ for (row, (a, b)) in frames[0]
227++ .y
228++ .chunks(64)
229++ .zip(ffmpeg_frames[0].y.chunks(64))
230++ .enumerate()
231++ {
232++ for (col, (x, y)) in a.iter().zip(b).enumerate() {
233++ if x != y {
234++ eprintln!("Y mismatch row={row} col={col} ours={x} ffmpeg={y}");
235++ }
236++ }
237++ }
238++ for (row, (a, b)) in frames[0]
239++ .u
240++ .chunks(32)
241++ .zip(ffmpeg_frames[0].u.chunks(32))
242++ .enumerate()
243++ {
244++ for (col, (x, y)) in a.iter().zip(b).enumerate() {
245++ if x != y {
246++ eprintln!("U mismatch row={row} col={col} ours={x} ffmpeg={y}");
247++ }
248++ }
249++ }
250++ }
251++
252+ /// As above, but a multi-frame inter sequence -- `--lag-in-frames=0
253+ /// --auto-alt-ref=0` keep every non-key frame a simple forward
254+ /// single-`LAST_FRAME` P frame (no alt-ref/backward reference this
lanes/chroma-r1.charter.mdadded+65 -0
@@ -0,0 +1,65 @@
1+# lane-chroma r1 charter — the chroma intra modes this decoder still refuses
2+
3+## Where you are
4+Worktree /home/user/Documents/Code/Rust/edith_codecs-chroma, branch
5+lane-chroma @ main.
6+Build/test ONLY:
7+ `env CARGO_TARGET_DIR=$HOME/.cache/cargo-target-chroma CARGO_BUILD_JOBS=4 nice -n 19 cargo test -p ec-av1 --release --lib <name> -- --nocapture`
8+FOREGROUND, EC_AV1_REQUIRE_AOMENC=1 on gates. Never push. Never touch the main
9+checkout or the sibling -realworld worktree. WIP COMMIT after every green step.
10+
11+## The measurement
12+Walking a DEFAULT-settings stream through its blockers, this is number 5 in the
13+chain — reached as soon as CDEF, delta-q and palette are out of the way:
14+
15+ unsupported: AV1 tile (a smooth or paeth chroma mode (round 2))
16+
17+at `decode.rs`:
18+
19+ if (9..=12).contains(&uv_mode) {
20+ return Err(unsupported("a smooth or paeth chroma mode (round 2)"));
21+ }
22+
23+There is a sibling refusal, "a directional chroma mode (round 2)", to check
24+alongside it.
25+
26+## Why this may be much smaller than it looks — verify before assuming
27+`crates/ec-av1/src/intra.rs` ALREADY implements SMOOTH_PRED, SMOOTH_V, SMOOTH_H
28+and PAETH_PRED, and they are exercised for LUMA today. The chroma path may
29+simply be refusing modes whose predictor is already present and correct.
30+
31+Do NOT assume that. Establish it:
32+1. Read the luma call path and the chroma call path side by side and list every
33+ difference — edge construction, availability, the `Reach`, subsampling, the
34+ CfL interaction (`UV_CFL_PRED` is mode 13 and is handled separately today).
35+2. Check against libaom what a chroma block of these modes actually needs that
36+ a luma block does not. `av1_predict_intra_block` is shared in libaom, which
37+ is evidence the predictor is shared, but the EDGE setup differs for a
38+ subsampled plane.
39+3. If it really is just the refusal, removing it is a two-line change and the
40+ whole value of the round is the PROOF — a gate with a hard-asserted firing
41+ count showing real aomenc streams decode those modes pixel-exact.
42+
43+The "(round 2)" suffix means an earlier round deliberately deferred these. Find
44+out whether it deferred them because they were hard or merely because they were
45+out of that round's scope — `git log -S "smooth or paeth chroma"` will say.
46+
47+## Method
48+Refuse-by-name first, decode second. On a pixel mismatch, self-pin with
49+`EC_AV1_GATE_DUMP` and compare the msac RANGE (never `tell()`) against the
50+instrumented oracle: `EC_TRACE=1`, `EC_TRACE_MODE=1` (covers intra key-frame
51+mode info too), `EC_TRACE_COEFF=1`. If the oracle's range is UNCHANGED where
52+ours moves, we read a symbol it never wrote — check that before suspecting a
53+predictor.
54+
55+Note these modes affect PIXELS, not symbol flow, if the mode symbol is already
56+being read correctly today — so a mismatch here is most likely a prediction
57+defect, and the recon dump (`EC_AV1_PREFILT_DUMP` on both sides) is the faster
58+instrument than the range ladder.
59+
60+## Done criteria
61+Full lib suite stays green (232 passed / 0 failed on main today). Smooth and
62+Paeth chroma decode pixel-exact under a gate that HARD-ASSERTS its firing count,
63+or the report explains precisely what a chroma block needs that is missing.
64+Report on the directional-chroma sibling too, even if you do not land it.
65+REPORT `lanes/chroma-r1.report.md`, VERDICT on the FIRST line.
lanes/chroma-r1.report.mdadded+126 -0
@@ -0,0 +1,126 @@
1+# lane-chroma r1 report — smooth/paeth chroma refusal
2+
3+VERDICT: NOT LANDED — root cause found and localized, refusal kept (reverted
4+to HEAD). This is the charter's documented fallback outcome: "the report
5+explains precisely what a chroma block needs that is missing."
6+
7+## What was established (charter step 1-2)
8+
9+The predictor itself (`crate::intra::predict`, `SMOOTH_PRED`/`SMOOTH_V_PRED`/
10+`SMOOTH_H_PRED`/`PAETH_PRED` branches) IS shared between luma and chroma,
11+and its formula matches spec 7.11.2.6 / libaom `intrapred.c` exactly (weight
12+tables, `round2` shifts, no-neighbour `Edges::build` fallback of 127/129/128
13+which is the spec's own default for a corner block). The chroma call path
14+(`PlaneBuf::reconstruct`) is the SAME function luma uses — there is no
15+missing chroma-specific machinery for the predictor math itself.
16+
17+`git log -S "smooth or paeth chroma"` shows the refusal was added in the SAME
18+commit (4f93fb2, "chroma tx_type derivation…") that landed the predictor
19+plumbing — its own comment already named the reason: a corner block with no
20+above/left neighbour, fed `SMOOTH_PRED`, produced a wrong pixel (worst delta
21+78 vs ffmpeg), traced 2026-08-27. So the earlier round deferred this because
22+it was HARD (a real bug found), not because it was merely out of scope.
23+
24+## What this round found (charter step 3, attempted, then reverted)
25+
26+Removed both refusals (`decode.rs` ~1970 and ~2458, the two `read_intra_mode`
27+variants), added a `SMOOTH_UV_HITS` counter, and wrote
28+`a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact` (same
29+structure as the existing `..._with_directional_chroma_...` gate, but
30+`--enable-smooth-intra=1 --enable-paeth-intra=1`). First attempt (seed 42)
31+FAILED: luma mismatched ffmpeg, not chroma.
32+
33+Grepped every other real-aomenc gate in `stream.rs` (23 call sites): every
34+single one passes `--enable-smooth-intra=0 --enable-paeth-intra=0`. So
35+smooth/paeth has NEVER been exercised end-to-end against a real encoder
36+stream before this lane, for EITHER plane — the charter's premise "already
37+exercises them for LUMA" holds only in `intra.rs`'s own unit tests, not
38+against a real bitstream. This is a real, previously-unverified defect, not
39+a chroma-specific gap.
40+
41+Root-caused with `EC_AV1_TRACE=1` (mode dump) + a throwaway pixel-diff test
42+against the pinned stream, with and without the loop filter
43+(`--loopfilter-control=0` reproduces it too, ruling out deblocking):
44+
45+- First mismatch (no-LF stream): `row=16 col=48`, inside luma block
46+ `px=48 py=16 side=16 mode=5` (`D113_PRED`, a directional mode).
47+- Its ABOVE neighbour is `px=48 py=0 side=16 mode=11` (`SMOOTH_H_PRED`).
48+
49+This is exactly the corner-cut already named in the code, verbatim, at the
50+`reconstruct()` call site's own doc comment:
51+
52+> `smooth_neighbor` (spec `get_intra_edge_filter_type`) is left `false`:
53+> exact for chroma here (a smooth `uv_mode` is refused before decode reaches
54+> this call) and a corner-cut for LUMA -- ceiling is one wrong filter-strength
55+> bucket on a block whose real neighbour predicted smooth; upgrade path is
56+> threading `Neighbours::above_mode`/`left_mode`'s `SMOOTH_PRED..=SMOOTH_H_PRED`
57+> membership down instead of `false`.
58+
59+Enabling `--enable-smooth-intra=1` makes the RD search reachable to actually
60+land SMOOTH_H on a block, which is exactly the case the corner-cut's own
61+comment predicted would break: `intra_edge_filter_strength`'s
62+`smooth_neighbor` threshold bucket is picked wrong for the directional
63+neighbour below it, producing the observed off-by-one-ish deltas
64+(`intra_edge_filter_strength` returns the wrong strength index -> different
65+filter kernel -> pixels shift by 1-2).
66+
67+## Why it wasn't landed this round
68+
69+The fix is well-scoped (`Neighbours::above_mode`/`left_mode` already track
70+per-16x16-cell LUMA mode; threading `SMOOTH_PRED..=SMOOTH_H_PRED.contains()`
71+into every `reconstruct`/`reconstruct_rect` call site's `smooth_neighbor`
72+argument is mechanical) but touches ~9 call sites across 3 planes x 3 partition
73+shapes (`decode.rs:2161,2174,2186,2279,2317,2354,2928,3038,3050,3061,3337,
74+3349,3360,7850,7862,7873,8923,8934,8945`), and the CHROMA side of the same
75+question needs a NEW piece of state this decoder does not track at all: a
76+per-cell UV-mode neighbour array (today's `Neighbours` only has `above_mode`/
77+`left_mode` for LUMA). Landing chroma smooth/paeth correctly needs BOTH the
78+luma-side threading (fixes the observed defect) AND new UV-mode tracking
79+(so a chroma block's own `smooth_neighbor` reflects its chroma neighbour, not
80+its luma one) — verified but not measured against a gate this round, out of
81+budget. Shipping only the luma-side half and leaving chroma's `smooth_neighbor`
82+hardcoded `false` would silently reintroduce the same bug on the chroma side
83+the moment two chroma smooth/directional blocks sit adjacent, which is exactly
84+the kind of silently-wrong decode this lane's own rules forbid landing.
85+
86+Given the choice between (a) landing a two-line refusal removal with a KNOWN,
87+now-quantified pixel defect gated by a passing test that happened not to
88+exercise the bad case, and (b) reverting to the safe refusal with the root
89+cause fully documented, this round takes (b). The attempted diff (refusal
90+removal + counter + gate + throwaway diagnostic test) is saved at
91+`/tmp/claude-1000/-home-user-Documents-Code-Rust-edith-codecs/baaa03f8-c4ff-4469-8ebb-83100429b150/scratchpad/chroma-r1-attempt.diff`
92+for whichever round lands the `smooth_neighbor` threading.
93+
94+## Gate firing count
95+
96+None — the gate (`a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact`)
97+was written and fired real smooth/paeth chroma symbols on its very first
98+attempt (seed 42), but FAILED on luma pixel mismatch before reaching a
99+chroma pixel-exact assertion; it was reverted along with the refusal removal
100+rather than left in the tree failing or disabled. `smooth_uv_hits` counter:
101+1 firing observed (chroma `uv_mode=11` on block `px=32 py=16`), never
102+verified pixel-exact.
103+
104+## The directional-chroma sibling ("a directional chroma mode (round 2)")
105+
106+Not touched this round; it lives at a DIFFERENT, unrelated code path
107+(`decode.rs:7786`, inside the intra-block-within-an-inter-frame reader) than
108+the two smooth/paeth refusals (`~1970`/`~2458`, the key-frame `read_intra_mode`
109+variants). That inter-frame intra-block path never computes `angle_delta_uv`
110+at all and refuses ANY non-DC/non-CFL `uv_mode` outright — i.e. directional
111+chroma is refused there unconditionally, unlike the key-frame path (`~2458`),
112+which ALREADY decodes directional chroma correctly today (see the existing,
113+passing `a_real_aomenc_stream_with_directional_chroma_decodes_pixel_exact`
114+gate). Landing the `~7786` sibling needs angle-delta-for-chroma support added
115+to that separate reader, plus its own gate; not attempted this round —
116+smaller in shape than the smooth/paeth work (no known predictor bug blocking
117+it, just missing plumbing) but independent scope, deferred to a future round.
118+
119+## Disposition
120+
121+deferred: thread `smooth_neighbor` through luma + add chroma UV-mode
122+neighbour tracking, then re-attempt this refusal removal — unblocks on
123+someone picking up the saved attempt diff and the ~9 call-site list above.
124+deferred: the `~7786` "directional chroma mode (round 2)" sibling in the
125+inter-frame intra-block path — unblocks independently, no known bug, just
126+unwritten angle-delta-for-chroma plumbing in that reader.
lanes/chroma-r2.charter.mdadded+80 -0
@@ -0,0 +1,80 @@
1+# lane-chroma r2 — smooth-neighbour edge filter, then smooth/paeth chroma
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-chroma`, branch
4+`lane-chroma`, at 3ca2455 (r1's report; r1 landed NO code — it reverted).
5+
6+## What r1 established (read `lanes/chroma-r1.report.md` first — it is short)
7+- The `SMOOTH_PRED`/`PAETH_PRED` predictor math in `intra.rs` is already
8+ spec-correct and shared between luma and chroma. Removing the chroma refusal
9+ (`decode.rs` uv_mode 9..=12, around lines 1970 and 2458) is NOT the work.
10+- The real defect is on LUMA: `reconstruct()` hardcodes `smooth_neighbor = false`
11+ — its own comment calls this "a corner-cut for luma" and names the upgrade
12+ path. `intra_edge_filter_strength` therefore picks the wrong bucket whenever a
13+ directional block's neighbour used a SMOOTH mode. r1 reproduced it exactly:
14+ seed 42, directional block px=48 py=16 mode=5, neighbour px=48 py=0 with
15+ SMOOTH_H_PRED, off by 1-2 in the filtered edge.
16+- **Nothing in this repo had ever exercised it**: all 23 real-aomenc gates in
17+ `stream.rs` pass `--enable-smooth-intra=0 --enable-paeth-intra=0`. That is a
18+ fleet-wide gate-recipe blindness, not a one-gate miss.
19+- r1's attempted diff (refusal removal + the new gate + the counter) is
20+ preserved at `lanes/chroma-r1-attempt.diff` in this worktree. Start from it.
21+
22+## Goal, in order
23+1. **Fix the luma bug first, on its own, with its own gate.** Thread the
24+ neighbour's intra mode into `reconstruct()` / `reconstruct_rect()` so
25+ `smooth_neighbor` is `above_mode` (or `left_mode`, per the spec's
26+ directionality) being in `SMOOTH_PRED..=SMOOTH_H_PRED`. r1's report lists
27+ the ~9 call sites. `Neighbours` already tracks per-block state — add the
28+ luma mode alongside whatever it already stores; follow the shape of the
29+ existing `skip_at` / `skip_txfm_ctx` accessors in `decode.rs`.
30+ Spec anchor: 7.11.2.9 `intra edge filter strength` — the `filt_type`
31+ argument is 1 when the relevant neighbour used a smooth mode. libaom:
32+ `av1/common/reconintra.c` `get_filt_type()` / `av1_filter_intra_edge` and
33+ `intra_edge_filter_strength`; `get_filt_type` reads
34+ `av1_is_directional_mode` and `is_smooth(above_mbmi)`/`is_smooth(left_mbmi)`.
35+ Gate it with a real-aomenc stream that enables smooth intra for LUMA while
36+ the chroma refusal is still in place (chroma can still refuse at this
37+ stage — that keeps the two changes separable). COMMIT.
38+2. **Then** add chroma UV-mode neighbour tracking and remove the smooth/paeth
39+ chroma refusal, with the gate from the attempt diff
40+ (`a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact`)
41+ passing pixel-exact on luma AND chroma. COMMIT.
42+3. **Then** the directional-chroma sibling if turns remain: `decode.rs:7786`,
43+ the inter-frame intra-block reader, which refuses any non-DC/CFL uv_mode
44+ unconditionally and never computes `angle_delta_uv`. r1 found no bug there,
45+ only unwritten plumbing. COMMIT.
46+
47+## Gate rules (mandatory)
48+- Run tests with `EC_AV1_REQUIRE_AOMENC=1` — a missing oracle must FAIL, not SKIP.
49+- Bound every ffmpeg `generate` with `-t <seconds>`.
50+- Build fixtures through the existing `gradients_source(seed, w, h, tail)`
51+ helper; ffmpeg's `gradients` source ignores its own seed.
52+- aomenc `--threads=1 --row-mt=0`, and of course `--enable-smooth-intra=1`
53+ (and `--enable-paeth-intra=1` for stage 2).
54+- Hard-assert a firing count with a thread-local `Cell<usize>` counter in
55+ decode.rs matching the existing `*_HITS` (thread-local now, NOT atomics):
56+ for stage 1, count the blocks where `smooth_neighbor` came out TRUE — a gate
57+ that runs with smooth intra enabled but never hits the new branch proves
58+ nothing (class `gate-blind-to-feature`).
59+- Refusals inside a gate are FORBIDDEN once the stage removing them lands.
60+
61+## Method
62+CLASS `compare-range-not-tell`: compare the msac RANGE against the oracle, never
63+`tell()`. Oracle at `~/.cache/aom-oracle`, rungs `EC_TRACE=1` (partitions),
64+`EC_TRACE_COEFF=1`, `EC_TRACE_MODE=1` (inter + intra mode info),
65+`EC_AV1_PREFILT_DUMP=<prefix>` (per-frame pre-filter recon — the right rung for
66+a predictor bug, since it isolates prediction from the loop filters).
67+Add a rung via `scripts/instrument-aom-oracle.sh` + `scripts/build-aom-oracle.sh`
68+in the existing shape (env-gated, silent when unset, idempotent) if you need one.
69+
70+## Hard rules
71+- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-chroma`. Foreground builds,
72+ `nice -n 19 cargo ... -j4`. Sibling worktrees (edith_codecs, -realworld, -lr,
73+ -superres, -tiles) have live agents — never build in or edit them.
74+- Suite: `nice -n 19 cargo test -p ec-av1 --lib`, baseline 232 passed / 0 failed.
75+- NEVER push, never merge, never touch `main`. Commit on `lane-chroma` only.
76+- 75-turn cap: COMMIT AFTER EVERY GREEN MILESTONE. r1 spent its whole budget and
77+ landed zero code because it held everything in the working tree; a commit that
78+ compiles beats a perfect uncommitted tree. Do not re-derive what r1's report
79+ already tells you (class `worker-cap-spent-reading`).
80+- End with `lanes/chroma-r2.report.md`, VERDICT on the first line.
lanes/chroma-r3.charter.mdadded+60 -0
@@ -0,0 +1,60 @@
1+# lane-chroma r3 — run the smooth-intra gate, then the chroma refusal
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-chroma`, branch
4+`lane-chroma`.
5+
6+## State
7+- `8bca1d6` — **the luma fix landed**: `smooth_neighbor` is threaded into the
8+ intra edge filter strength instead of being hardcoded `false`. This is r1's
9+ root cause (a directional block neighbouring a smooth-mode one picked the
10+ wrong filter bucket). Committed, compiles.
11+- The next commit is the orchestrator's cap-rescue of r2's gate: ~140 new lines
12+ in `crates/ec-av1/src/stream.rs`, a smooth-intra gate that **compiles but has
13+ never been run once**. That is your first job.
14+- `lanes/chroma-r2.charter.md` — still binding for everything below.
15+- `lanes/chroma-r1.report.md` + `lanes/chroma-r1-attempt.diff` — r1's root-cause
16+ writeup and its reverted attempt (the chroma-side gate lives there).
17+
18+## Order — COMMIT AFTER EVERY GREEN STEP
19+1. Run the new gate:
20+ `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-chroma` then
21+ `EC_AV1_REQUIRE_AOMENC=1 nice -n 19 cargo test -p ec-av1 --lib <gate name> -j4 -- --nocapture`
22+ with a timeout of at least 600000 ms. Make it pass pixel-exact on luma with a
23+ HARD-asserted firing count proving `smooth_neighbor` actually came out TRUE
24+ somewhere — a gate that enables smooth intra but never hits the new branch
25+ proves nothing (class `gate-blind-to-feature`). Then the full suite
26+ (baseline 232/0 on this tree; main is at 234 with two new guard tests).
27+ COMMIT.
28+2. Chroma: add UV-mode neighbour tracking to `Neighbours` and remove the
29+ smooth/paeth chroma refusals (decode.rs uv_mode 9..=12, around 1970 and
30+ 2458), with r1's gate
31+ `a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact` from the
32+ attempt diff green on luma AND chroma. COMMIT.
33+3. Once a gate really enables smooth-intra and paeth-intra, main's
34+ `crates/ec-av1/src/gate_coverage.rs` guard will FAIL by design: its
35+ `NEVER_EXERCISED` list still names `enable-smooth-intra` and
36+ `enable-paeth-intra` as tools no gate exercises. Deleting those two entries
37+ is part of landing this work — that guard exists precisely so closing the
38+ hole is noticed. (The guard is on main, so you will meet it at merge if not
39+ before; if `gate_coverage.rs` is not in your tree yet, note it in the report
40+ for the merge instead.)
41+4. If turns remain: the directional-chroma sibling at `decode.rs:7786`, the
42+ inter-frame intra-block reader, which refuses any non-DC/CFL uv_mode
43+ unconditionally and never computes `angle_delta_uv`. No known bug there,
44+ just unwritten plumbing. COMMIT.
45+
46+## Gate rules (mandatory)
47+`EC_AV1_REQUIRE_AOMENC=1` on every run; `-t <seconds>` on every ffmpeg generate;
48+fixtures through `gradients_source(seed, w, h, tail)`; aomenc
49+`--threads=1 --row-mt=0 --enable-smooth-intra=1` (and `--enable-paeth-intra=1`
50+for stage 2); firing counts are HARD asserts via thread-local `Cell<usize>`
51+counters like the existing `*_HITS`.
52+
53+## Hard rules
54+- Own `CARGO_TARGET_DIR` as above; foreground builds, `nice -n 19 cargo ... -j4`;
55+ every `cargo test` gets a timeout of at least 600000 ms.
56+- Sibling worktrees (edith_codecs, -realworld, -lr, -superres, -tiles) have live
57+ agents. Never build in or edit them.
58+- NEVER push, never merge, never touch `main`. Commit on `lane-chroma` only.
59+- 75-turn cap and it does NOT reset on resume: commit at every green step.
60+- End with `lanes/chroma-r3.report.md`, VERDICT on the first line.
lanes/chroma-r4.charter.mdadded+49 -0
@@ -0,0 +1,49 @@
1+# lane-chroma r4 — finish the chroma refusal removal
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-chroma`, branch
4+`lane-chroma`. Read `lanes/chroma-r3.charter.md` (still binding) and, briefly,
5+`lanes/chroma-r1.report.md` for the root cause. Do not re-derive them.
6+
7+## State
8+- `8bca1d6` — the real luma fix: `smooth_neighbor` threaded into the intra edge
9+ filter strength instead of hardcoded `false`.
10+- `bafda07` — r2's smooth-intra gate, cap-rescued, compiles.
11+- HEAD — r3's work, cap-rescued by the orchestrator: `decode.rs` +99,
12+ `stream.rs` +126. r3's last words before the cap were "now let's add the r1
13+ gate for smooth/paeth chroma (charter step 2), then run the full lib test
14+ suite" — so the luma gate is believed to have gone green in r3's hands, but
15+ **no suite run has ever been seen on this tree**. Verify, do not assume.
16+
17+## Order
18+1. `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-chroma` then
19+ `EC_AV1_REQUIRE_AOMENC=1 nice -n 19 cargo test -p ec-av1 --lib -j4`
20+ (timeout >= 600000 ms). Report the count against 232/0 for this tree.
21+ If red, fixing HEAD is the whole job until it is green. COMMIT once green.
22+2. Chroma: UV-mode neighbour tracking in `Neighbours`, remove the smooth/paeth
23+ chroma refusals (decode.rs uv_mode 9..=12, around 1970 and 2458), with r1's
24+ gate `a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact`
25+ (in `lanes/chroma-r1-attempt.diff`) green on luma AND chroma. COMMIT.
26+3. Note for the merge: main carries `crates/ec-av1/src/gate_coverage.rs`, whose
27+ `NEVER_EXERCISED` list still names `enable-smooth-intra` and
28+ `enable-paeth-intra` as tools no gate exercises. Once your gates enable them,
29+ those two entries must be deleted — that guard exists so closing the hole is
30+ noticed. If `gate_coverage.rs` is not in your tree, say so in the report so
31+ the merge does it.
32+4. If turns remain: the directional-chroma sibling at `decode.rs:7786` (the
33+ inter-frame intra-block reader refuses any non-DC/CFL uv_mode and never
34+ computes `angle_delta_uv`). COMMIT.
35+
36+## Gate rules
37+`EC_AV1_REQUIRE_AOMENC=1` on every run; `-t <seconds>` on every ffmpeg generate;
38+fixtures through `gradients_source(seed, w, h, tail)`; aomenc
39+`--threads=1 --row-mt=0 --enable-smooth-intra=1 --enable-paeth-intra=1`;
40+firing counts are HARD asserts via thread-local `Cell<usize>` counters.
41+
42+## Hard rules
43+Own `CARGO_TARGET_DIR` as above; foreground builds `nice -n 19 cargo ... -j4`;
44+every `cargo test` a timeout >= 600000 ms. Sibling worktrees (edith_codecs,
45+-realworld, -lr, -superres, -tiles, -palette) have live agents — never build in
46+or edit them. Never push, never merge, never touch `main`. 75-turn cap, does not
47+reset: COMMIT AT EVERY GREEN STEP — three rounds in a row on this lane have
48+ended with the work uncommitted. End with `lanes/chroma-r4.report.md`, VERDICT
49+on line 1.
lanes/chroma-r4.report.mdadded+66 -0
@@ -0,0 +1,66 @@
1+VERDICT: GREEN
2+
3+## Step 1 -- verify HEAD
4+`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4`: **234 passed; 0 failed; 17
5+ignored** (vs the charter's 232/0 baseline -- 2 extra tests are r3's own new
6+smooth-intra/smooth-paeth-chroma gates, already in HEAD). Tree was clean at
7+start (nothing to commit for this step); r3's cap-rescued work is genuinely
8+green, contrary to the "no suite run has ever been seen" warning.
9+
10+## Step 2 -- chroma UV-mode neighbour tracking + smooth/paeth chroma refusal
11+Already done in HEAD (r3's commit `47da0be`): `Neighbours::above_uv_mode`/
12+`left_uv_mode` exist, `decode.rs`'s two `read_intra_mode`/`read_intra_mode_rect`
13+sites (keyframe callers) removed the `9..=12` uv_mode refusal, and
14+`lanes/chroma-r1-attempt.diff`'s gate
15+(`a_real_aomenc_stream_with_smooth_paeth_chroma_decodes_pixel_exact`) is
16+present in `stream.rs` and passes on its own
17+(`cargo test ... smooth_paeth_chroma` -- 1 passed). No new commit needed.
18+
19+## Step 3 -- gate_coverage.rs
20+`crates/ec-av1/src/gate_coverage.rs` **does not exist in this tree**
21+(confirmed via `find`). Per the charter, the merge must delete the
22+`enable-smooth-intra`/`enable-paeth-intra` entries from `NEVER_EXERCISED`
23+on `main`'s copy.
24+
25+## Step 4 -- directional-chroma sibling (turns remained)
26+Charter's line number (`decode.rs:7786`) had drifted from r3's +99 lines;
27+the real sibling was `decode_inter_block`'s intra-in-inter branch (the
28+`else` arm handling an intra block coded inside an inter frame), which read
29+`uv_mode` and refused outright with `"a directional chroma mode (round 2)"`
30+for anything past DC/CFL, and never read `angle_delta_uv` at all.
31+
32+Fixed by mirroring `read_intra_mode`'s already-proven pattern in that one
33+function (`crates/ec-av1/src/decode.rs`, `decode_inter_block`):
34+- `uv_predict_mode` (CFL predicts as DC for the reconstruct call, same as
35+ the keyframe path) threaded through both `u`/`v.reconstruct` calls (skip
36+ path) and both chroma `read_plane` calls (non-skip path), replacing the
37+ hardcoded `DC_PRED`.
38+- `angle_delta_uv` computed via `read_angle_delta` when `uv_mode` is
39+ directional (`V_PRED..=D67_PRED`), replacing the hardcoded `0`.
40+- `smooth_neighbor_uv` computed from the chroma neighbour's own `uv_mode`
41+ (`is_smooth_mode(above_uv_mode/left_uv_mode)`), replacing the hardcoded
42+ `false`, threaded into the same reconstruct/read_plane calls.
43+- `SMOOTH_UV_HITS`/`DIRECTIONAL_UV_HITS` counted here too (shared
44+ thread-locals with the keyframe path).
45+- `neighbours.record_rect`'s uv-mode arg (previously hardcoded `DC_PRED`)
46+ now carries the real `uv_predict_mode` so a following block's own
47+ smooth-neighbour check sees it.
48+- The luma-mode side of this branch (`mode`, its own angle_delta refusal at
49+ the top) is **untouched** -- out of this charter step's chroma-only scope.
50+
51+`cargo check -p ec-av1 --lib`: clean (no new warnings/errors). Full lib
52+suite re-run after the change: still **234 passed; 0 failed; 17 ignored** --
53+no regression.
54+
55+**Gap, disclosed per "refusal strings are claims":** no dedicated gate
56+proves a real aomenc stream ever actually exercises this specific path (an
57+intra block, directional/smooth/paeth `uv_mode`, coded *inside an inter
58+frame*) end to end against ffmpeg. The change is a direct structural mirror
59+of the already-gated keyframe fix (identical CDF tables, identical
60+`get_uv_mode`/angle-delta semantics per spec 9.3), and the full suite stays
61+green, but it is **code-verified by mirroring, not gate-verified by firing**.
62+`deferred: dedicated a_real_aomenc_stream_with_directional_chroma_in_inter_frame_intra gate -- next round, no seat left this round -- unblocks by writing a stream.rs gate that forces an inter-frame key/delta pair whose delta frame codes an intra 8x8+ leaf with directional/smooth/paeth uv_mode (drop --enable-tx-size-search=0 constraint if it starves the recipe) and asserts on decode::smooth_uv_hits()/directional_uv_hits() firing plus pixel-exact vs ffmpeg`.
63+
64+## Commit
65+`c806bd6` -- directional/smooth/paeth chroma in inter-frame intra blocks.
66+Nothing else uncommitted; `git status` clean.
lanes/realworld-r1.charter.mdadded+69 -0
@@ -0,0 +1,69 @@
1+# lane-realworld r1 charter — the first two blockers on a DEFAULT stream
2+
3+## Where you are
4+Worktree /home/user/Documents/Code/Rust/edith_codecs-realworld, branch
5+lane-realworld @ main.
6+Build/test ONLY:
7+ `env CARGO_TARGET_DIR=$HOME/.cache/cargo-target-realworld CARGO_BUILD_JOBS=4 nice -n 19 cargo test -p ec-av1 --release --lib <name> -- --nocapture`
8+FOREGROUND, EC_AV1_REQUIRE_AOMENC=1 on gates. Never push. Never touch the main
9+checkout or the sibling -chroma worktree. WIP COMMIT after every green step.
10+
11+## The measurement this lane exists for
12+Every gate in this crate encodes with a long list of `--enable-*=0` flags. A
13+stream encoded with DEFAULT settings — nothing disabled — refuses on the very
14+first frame. Walking the chain by disabling one feature at a time gives the
15+real-world blocker order:
16+
17+ 1. `cdef_bits > 0` <- a default stream stops here
18+ 2. `delta_q_present || delta_lf_present`
19+ 3. a block that actually uses a palette
20+ 4. a partition below 8x8
21+ 5. a smooth or paeth chroma mode (lane-chroma has this)
22+ 6. a partition below 16x16 other than a clean split
23+
24+This lane takes 1 and 2, because nothing else matters until a default stream
25+gets past them.
26+
27+## 1. CDEF index (the bigger win, do it first)
28+The CDEF FILTER is already implemented and working — `cdef` appears ~108 times
29+in this crate and streams with `cdef_bits == 0` decode pixel-exact today. What
30+is missing is only the per-64x64 `cdef_idx` SYMBOL: when `cdef_bits > 0` the
31+frame header carries 2^bits strength pairs and each 64x64 block reads an index
32+selecting which pair applies.
33+
34+Read `read_cdef` in `~/.cache/aom-oracle/src/av1/decoder/decodeframe.c` and the
35+spec's `read_cdef` (5.11.56). Points to get right:
36+- the symbol is a LITERAL of `cdef_bits` bits, not an adapting CDF;
37+- it is read once per 64x64 in the superblock, skipped when the block is
38+ entirely skip, and NOT read at all when `coded_lossless` or `allow_intrabc`;
39+- the index selects into the header's already-parsed strength arrays, which
40+ this crate's syntax layer reads — check before re-parsing anything.
41+
42+## 2. delta_q / delta_lf
43+Per-superblock `delta_q_abs` / `delta_lf_abs` symbols with their own CDFs, plus
44+carrying the running quantizer (and per-plane loop-filter deltas) through the
45+block decode. Anchor: spec 5.11.15 `read_delta_qindex` / 5.11.16
46+`read_delta_lflevel`, and libaom's `read_delta_q`/`read_delta_lf` in decodemv.c.
47+Any new adapting CDF must be wired at ALL FOUR sites — struct field, defaults,
48+save/restore, per-frame counter reset.
49+
50+## Method and gates
51+Refuse-by-name first, decode second: a desync is never acceptable, a precise
52+refusal always is. On a pixel mismatch, self-pin with `EC_AV1_GATE_DUMP` and
53+compare the msac RANGE (never `tell()`) against the instrumented oracle — the
54+rungs are `EC_TRACE=1` (partitions), `EC_TRACE_MODE=1` (inter AND intra mode
55+info), `EC_TRACE_COEFF=1` (coefficients). Class rule worth remembering: if the
56+oracle's range is UNCHANGED where ours moves, we are reading a symbol it never
57+wrote — check that before suspecting a table.
58+
59+Add a GATE for each feature, with a hard-asserted firing count, following the
60+shape of the existing gates. A gate that cannot fire the feature it names
61+measures nothing; this batch has already fixed three of those.
62+
63+## Done criteria
64+Full lib suite stays green (232 passed / 0 failed on main today). A stream
65+encoded with `--enable-cdef=1` (the default) and one with delta-q enabled each
66+decode pixel-exact against ffmpeg, proven by a hard-asserted gate. REPORT
67+`lanes/realworld-r1.report.md`, VERDICT on the FIRST line, and re-walk the
68+blocker chain at the end so the report says exactly which blocker a default
69+stream now stops at.
lanes/realworld-r2.charter.mdadded+93 -0
@@ -0,0 +1,93 @@
1+# lane-realworld r2 — verify cdef_idx, gate it, then delta_q / delta_lf
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-realworld`, branch
4+`lane-realworld`, at bd61617.
5+
6+## State handed to you (r1's own words; nothing here is verified)
7+bd61617 is r1's work, committed verbatim by the orchestrator when r1 hit its
8+turn cap. It compiles (`cargo build -p ec-av1 --release` was clean). Its
9+**suite status is UNKNOWN** — the test run was launched and the cap hit before
10+it returned. There is **no gate test at all** yet.
11+
12+What it contains — CDEF index only, `delta_q`/`delta_lf` entirely unstarted:
13+- `crates/ec-av1/src/decode.rs`: thread-locals `CDEF_BITS`, `CDEF_TRANSMITTED`,
14+ `CDEF_SB_COLS`, `CDEF_IDX_GRID`, `CDEF_IDX_HITS` + a `cdef_idx_hits()`
15+ accessor, mirroring the existing `*_HITS` pattern.
16+- `maybe_read_cdef_idx(dec, mi_r, mi_c, skip)` — the spec 5.11.56 `read_cdef`
17+ port. No-op when `cdef.bits == 0` or `skip`; reads once per superblock (this
18+ decoder's SB is the CDEF unit — no 128x128 support, so no 4-way index).
19+- Wired at all five sites where `skip` is decoded: `read_intra_mode` (shared by
20+ `decode_block` and `decode_leaf8`, given new `mi_r`/`mi_c` params),
21+ `read_intra_mode_rect` / `decode_block_rect`, `decode_inter_block` (~6462),
22+ `decode_inter_block8` (~8189).
23+- Both tile functions (`decode_key_frame_tile_with_cdfs`,
24+ `decode_inter_frame_tile_with_cdfs`) set `CDEF_BITS` / `CDEF_SB_COLS` and init
25+ `CDEF_IDX_GRID` before the SB loop, and reset `CDEF_TRANSMITTED = false` at
26+ the top of each SB.
27+- `apply_cdef` looks up a per-superblock `sidx` through a
28+ `strength_idx(mi_r, mi_c)` closure over `CDEF_IDX_GRID`, replacing every
29+ hardcoded `[0]` strength index.
30+- `crates/ec-av1/src/stream.rs`: the `header.cdef.bits != 0` refusal in
31+ `decode_stream` was REMOVED.
32+
33+**Risk r1 flagged:** `apply_cdef`'s early-return guard became
34+`cdef.bits == 0 && <all index-0 strengths zero>`, so a `bits > 0` stream now
35+always walks the full filter loop even when every strength is zero. Believed
36+correct, never checked against a real decode.
37+
38+## Do these in order — COMMIT AFTER EVERY GREEN STEP, never batch
39+1. `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-realworld` then
40+ `EC_AV1_REQUIRE_AOMENC=1 nice -n 19 cargo test -p ec-av1 --lib -j4`.
41+ Report the pass count against the 232 passed / 0 failed baseline. If it is
42+ red, fixing bd61617 is the whole job until it is green.
43+2. **The CDEF gate.** Copy the structure of
44+ `a_real_aomenc_stream_with_masked_compound_decodes_pixel_exact`
45+ (stream.rs around 4447-4657) but keep `--enable-cdef=1` (drop that gate's
46+ `--enable-cdef=0`) and disable the unrelated features (masked-comp,
47+ interintra, obmc, warp, restoration, palette, intrabc) exactly as that gate
48+ does. Hard-assert `crate::decode::cdef_idx_hits() > 0` — the accessor
49+ already exists. Bound the ffmpeg generate with `-t <seconds>`; build the
50+ fixture through `gradients_source(seed, w, h, tail)`; aomenc
51+ `--threads=1 --row-mt=0`. Flat gradients may not make aomenc's RD choose
52+ `cdef_bits > 0` — if the counter stays 0 across attempts, switch the source
53+ to `mandelbrot` the way the masked-compound gate does (bounded with `-t`).
54+ A gate that cannot prove cdef_idx fired is vacuous (class
55+ `gate-blind-to-feature`), and a firing count is a HARD assert, never a
56+ warning. COMMIT.
57+3. **Then** `delta_q` / `delta_lf` (spec 5.11.15 `read_delta_qindex`, 5.11.16
58+ `read_delta_lflevel`; libaom `av1/decoder/decodemv.c` `read_delta_qindex` /
59+ `read_delta_lflevel`). This needs new ADAPTING CDFs — four wiring sites:
60+ struct field, defaults array, save/restore, per-frame counter reset (see
61+ `cdf_state.rs:590+`; in this codebase reset2/reset3 are length-generic and
62+ save/restore is a whole-struct Clone, so the defaults array is the one that
63+ needs hand-checking, but verify the counter reset covers the new tables —
64+ class `cdf-counter-not-reset`: a table missing from the reset gives right
65+ values at the wrong adaptation rate). It also needs the running
66+ quantizer/loop-filter-delta state threaded through block decode, and the
67+ deltas are read once per superblock at the first non-skip block.
68+ Its own gate, its own firing counter, its own commit.
69+
70+## Method
71+CLASS `compare-range-not-tell`: compare msac RANGE against the oracle, never
72+`tell()`. Oracle `~/.cache/aom-oracle`; rungs `EC_TRACE=1` (partitions),
73+`EC_TRACE_COEFF=1`, `EC_TRACE_MODE=1` (inter + intra mode info),
74+`EC_AV1_PREFILT_DUMP=<prefix>` (pre-filter recon — the right rung for
75+separating a CDEF filter bug from a symbol bug). Add a rung with
76+`scripts/instrument-aom-oracle.sh` + `scripts/build-aom-oracle.sh` in the
77+existing shape (env-gated, silent when unset, idempotent) if you need one.
78+CLASS `equal-range-means-unread`: reference range unchanged where ours moves =
79+we read a symbol it never wrote; theirs moves and ours does not = we skipped one.
80+
81+## Hard rules
82+- Foreground builds, `nice -n 19 cargo ... -j4`, own `CARGO_TARGET_DIR` as
83+ above. Sibling worktrees (edith_codecs, -chroma, -lr, -superres, -tiles) have
84+ live agents — never build in or edit them.
85+- NEVER push, never merge, never touch `main`. Commit on `lane-realworld` only.
86+- 75-turn cap. Two agents have now burned a cap on this lane. Do not re-read
87+ what this charter already told you (class `worker-cap-spent-reading`), and
88+ commit at every green step.
89+- Refuse-by-name rather than desync. Never write a refusal string claiming the
90+ encoder cannot emit a case unless you proved it.
91+- End with `lanes/realworld-r2.report.md`, VERDICT on the first line: what
92+ landed, gate names + firing counts, remaining refusal strings verbatim, and
93+ the next lever.
lanes/realworld-r2.report.mdadded+98 -0
@@ -0,0 +1,98 @@
1+# lane-realworld r2 report
2+
3+VERDICT: Step 1 (suite verify) and step 2 (CDEF gate) landed and committed
4+(080acfd on branch lane-realworld). Step 3 (delta_q/delta_lf) is
5+UNSTARTED -- next agent picks it up fresh, nothing half-done to unwind.
6+
7+## Step 1 -- suite verify
8+`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4` on bd61617:
9+**232 passed, 0 failed, 17 ignored** -- matches the baseline exactly, no
10+fix needed. bd61617's CDEF code compiled clean and the suite was
11+already green; r1's risk (apply_cdef's guard) turned out fine in
12+practice (see below).
13+
14+## Step 2 -- the CDEF gate (committed 080acfd)
15+`a_real_aomenc_stream_with_cdef_decodes_pixel_exact` in
16+`crates/ec-av1/src/stream.rs` (~4668-4870). Latest run:
17+**40/40 pixel-exact matches, 0 named refusals, `cdef_idx_hits()` 24-40
18+per run (hard-asserted > 0)**.
19+
20+### The real finding: the charter's recipe (copy masked-compound's
21+64x64 single-SB fixture) is structurally incapable of firing cdef_idx.
22+`cdef.bits` selects among per-*superblock* strength profiles; a 64x64
23+frame is exactly one superblock, so aomenc's RD has nothing to
24+differentiate and always writes `bits=0` -- confirmed empirically
25+(20-attempt runs at 64x64, `cdef_idx_hits()` stayed 0 every time).
26+Needed a multi-SB fixture (128x64, 2 SBs) instead.
27+
28+### Two pre-existing gaps this multi-SB fixture immediately hit (NOT
29+this lane's to fix, named so the next lane can find them by grep):
30+1. At `--cpu-used=0` (every other real-stream gate's setting), aomenc's
31+ RD on multi-SB content picks SB-level (part64) partition types this
32+ decoder's intra key-frame path doesn't cover -- only
33+ `PARTITION_NONE`/`PARTITION_SPLIT` are handled at
34+ `decode_key_frame_tile_with_cdfs`'s top match (`decode.rs` ~4684),
35+ everything else (`HORZ_4`=8, `VERT_B`=7 observed live) falls into the
36+ catchall `unsupported("a partition type this encoder never writes")`
37+ at `decode.rs:5049`. This reproduced with `--enable-rect-partitions=0
38+ --enable-ab-partitions=0 --enable-1to4-partitions=0` all set --
39+ aomenc chose them anyway (this build/cpu-used=0 combo doesn't fully
40+ honor those flags for the top-of-tree decision, empirically). The
41+ INTER path (`decode_inter_frame_tile_with_cdfs`, `decode.rs:9397`)
42+ has a worse latent bug for the same reason: it reads `part64` and
43+ then does `let _ = part64;` -- discards it and blindly recurses as
44+ if it were always `SPLIT`. If a real inter frame's SB ever writes
45+ anything but SPLIT there, this **silently desyncs** rather than
46+ refusing by name. Not exercised by this gate (avoided via
47+ `--cpu-used=4`, see below) but is a live landmine for any future
48+ multi-SB real-stream gate.
49+2. `--cpu-used>=1`'s default `aq-mode` writes `delta_q_present`/
50+ `delta_lf_present`, which this decoder already refuses by name
51+ (correctly) -- but that's exactly this lane's *next* step, so
52+ sidestepped for now with `--aq-mode=0 --deltaq-mode=0`.
53+
54+### The working recipe: 128x64 (2 SBs), `--cpu-used=4` (steers RD away
55+from the unsupported part64 types), `--aq-mode=0 --deltaq-mode=0`
56+(keeps delta_q/delta_lf off), `--enable-cdef=1`, everything else same
57+shape as the masked-compound gate (rich inter toolset: warped-motion,
58+obmc, masked-comp, interintra-comp all =1, since a starved toolset was
59+also observed to push RD toward the same unsupported partition types
60+even at `--cpu-used=0`/min-max-partition=64).
61+
62+No refusal strings were added or altered -- the pre-existing
63+"a partition type this encoder never writes" and "delta_q_present or
64+delta_lf_present" refusals are both genuine (proven by direct
65+reproduction, not assumed).
66+
67+## Step 3 -- delta_q / delta_lf: NOT STARTED
68+Ran out of budget before beginning. Per charter: spec 5.11.15
69+`read_delta_qindex` / 5.11.16 `read_delta_lflevel`; libaom
70+`av1/decoder/decodemv.c` same names. Needs: new adapting CDFs (struct
71+field + defaults array + verify counter-reset coverage per
72+`cdf-counter-not-reset` class -- save/restore and reset2/reset3 are
73+already length-generic per `cdf_state.rs:590+`), running
74+quantizer/loop-filter-delta state threaded through block decode, read
75+once per SB at the first non-skip block. Its own gate/counter/commit.
76+The existing refusal ("a frame with delta_q_present or delta_lf_present
77+set") is reproducible on demand with `--aq-mode=1` or default
78+`cpu-used>=1` at 128x64+ -- a ready-made fixture recipe for that gate's
79+own "still refuses correctly until landed" check, then flip once wired.
80+
81+## Remaining refusal strings verbatim (still true, not touched)
82+- `"a partition type this encoder never writes"` (SB-level, intra;
83+ `decode.rs:5049`) -- pre-existing, real, out of scope.
84+- `"a partition type this encoder never writes (value={part32})"` (32
85+ level, intra; `decode.rs:5042`) -- pre-existing.
86+- `"an INTER 32x32 partition type this encoder never writes
87+ (value={part32})"` (`decode.rs:10555`) -- pre-existing.
88+- `"a frame with delta_q_present or delta_lf_present set (this decoder
89+ never reads the per-superblock delta symbols)"` -- this lane's step 3
90+ target, still refuses correctly.
91+- `"a partition below 16x16 other than a clean split..."`,
92+ `"a partition below 8x8..."`, `"a 16x16 block whose true edge cuts
93+ through both axes..."` -- untouched, unrelated.
94+
95+## Next lever
96+delta_q/delta_lf (charter step 3), exactly as scoped. The part64
97+multi-SB gap (finding #1 above) is a separate, larger lane -- flagged,
98+not fixed, not this lane's job.
lanes/realworld-r3.charter.mdadded+71 -0
@@ -0,0 +1,71 @@
1+# lane-realworld r3 — the part64 silent desync, then delta_q / delta_lf
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-realworld`, branch
4+`lane-realworld`, at ad0832c. Read `lanes/realworld-r2.report.md` first — it
5+carries the spec refs, the CDF wiring checklist and a ready-made
6+refusal-reproduction recipe. Do not re-derive it.
7+
8+## State — blocker 1 is CLOSED
9+`bd61617` (cdef_idx reads) + `080acfd` (its gate) + `ad0832c` (report). Gate
10+`a_real_aomenc_stream_with_cdef_decodes_pixel_exact`: 40/40 pixel-exact, zero
11+refusals, `cdef_idx_hits()` hard-asserted `> 0` (24-40 per run). Suite 233/0.
12+
13+r2's finding worth keeping: `cdef_bits` selects among per-SUPERBLOCK strength
14+profiles, so a single-64x64-superblock fixture can NEVER reach `bits > 0` —
15+20 attempts kept `cdef_idx_hits()` at 0. The gate needed a 128x64, two-superblock
16+fixture.
17+
18+## Job 1 — a silent desync, fix it before anything else
19+`decode_inter_frame_tile_with_cdfs` (decode.rs ~9397) reads `part64` and then
20+throws it away (`let _ = part64;`), blindly assuming SPLIT. A real non-SPLIT
21+`part64` in an inter frame **silently desyncs** — it does not refuse by name.
22+That is the one thing this project treats as never acceptable: refuse by name or
23+decode, never desync.
24+
25+Minimum: make it refuse by name, accurately, and prove the refusal with a test.
26+Better, if it is small: handle the non-SPLIT cases the way the intra path does.
27+Either way this is its own commit, and the refusal string must describe what
28+THIS DECODER does not do — not what an encoder supposedly never writes.
29+
30+Related, out of scope but record it: at `--cpu-used=0` aomenc picks SB-level
31+`HORZ_4` / `VERT_B` partitions that the intra `part64` match at decode.rs:5049
32+does not cover, even with `--enable-rect/ab/1to4-partitions=0`. r2 sidestepped
33+it with `--cpu-used=4`. Do NOT chase it here; note it in the report.
34+
35+## Job 2 — delta_q / delta_lf (blocker 2), unstarted
36+Spec 5.11.15 `read_delta_qindex`, 5.11.16 `read_delta_lflevel`; libaom
37+`av1/decoder/decodemv.c` `read_delta_qindex` / `read_delta_lflevel`. New
38+ADAPTING CDFs: four wiring sites — struct field, defaults array, save/restore,
39+per-frame counter reset (`cdf_state.rs`; `reset2`/`reset3` are length-generic
40+and save/restore is a whole-struct Clone, so the defaults array is what needs
41+hand-checking, but verify the counter reset covers the new tables — class
42+`cdf-counter-not-reset`: a missing reset gives right values at the wrong
43+adaptation rate). Plus the running quantizer / loop-filter-delta state threaded
44+through block decode; the deltas are read once per superblock at the first
45+non-skip block. Then remove the refusal at stream.rs
46+("a frame with delta_q_present or delta_lf_present set"). Its own gate, its own
47+hard-asserted firing counter, its own commit.
48+
49+## Gate rules
50+`EC_AV1_REQUIRE_AOMENC=1` on every run; `-t <seconds>` on every ffmpeg generate;
51+fixtures through `gradients_source(seed, w, h, tail)`; aomenc
52+`--threads=1 --row-mt=0`; firing counts are HARD asserts via thread-local
53+`Cell<usize>` counters. Size the fixture so the feature can actually fire —
54+r2's cdef lesson generalises: a per-superblock symbol needs more than one
55+superblock.
56+
57+## Note for the merge
58+Main now carries two guards you do not have yet: `gate_coverage.rs` (pins the
59+aomenc tools no gate exercises — `enable-cdef` is on that list and your gate
60+closes it, so that entry must be deleted at merge) and `refusal_inventory.rs`
61+(pins every decode-path refusal string; adding or removing one fails until the
62+list is updated). Say in your report exactly which refusal strings you added or
63+removed, verbatim, so the merge can update both lists.
64+
65+## Hard rules
66+`export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-realworld`; foreground builds
67+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling
68+worktrees (edith_codecs, -chroma, -lr, -superres, -tiles, -palette) have live
69+agents — never build in or edit them. Never push, never merge, never touch
70+`main`. 75-turn cap, does not reset: commit at every green step. End with
71+`lanes/realworld-r3.report.md`, VERDICT on line 1.
lanes/realworld-r3.report.mdadded+158 -0
@@ -0,0 +1,158 @@
1+# lane-realworld r3 report
2+
3+VERDICT: Job 1 (part64 silent desync) FIXED, tested, committed (879999d).
4+Job 2 (delta_q/delta_lf) UNSTARTED but fully scoped below — turn budget ran
5+out during the design phase, before any code was written, so there is
6+nothing half-done to unwind for the next agent.
7+
8+## Job 1 -- part64 silent desync (committed 879999d)
9+`decode_inter_frame_tile_with_cdfs` (decode.rs, the `(true, true)` arm around
10+what was line 9397) read `part64` then `let _ = part64;`, always recursing
11+the quadrant loop as if SPLIT. Fixed: the value is now kept (still inferred
12+as `PARTITION_SPLIT` for the three straddle/forced-half cases, matching the
13+intra tile's own three-way write), and if a real read comes back anything
14+other than `PARTITION_SPLIT` the function returns
15+`Err(unsupported("an inter SB-level partition type other than SPLIT (this
16+decoder's inter tile path only recurses a superblock as SPLIT)"))` before
17+the quadrant recursion runs.
18+
19+**New refusal string** (verbatim, for the merge's `refusal_inventory.rs`):
20+`"an inter SB-level partition type other than SPLIT (this decoder's inter
21+tile path only recurses a superblock as SPLIT)"`
22+
23+Test: `decode::tests::a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing`
24+hand-writes a single `PARTITION_HORZ` `part64` symbol with `SymbolEncoder`
25+and asserts `decode_inter_frame_tile` returns that named error rather than
26+decoding garbage. `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4`:
27+**234 passed, 0 failed, 17 ignored** (was 232/0/17 before this lane; +1 this
28+test, +1 from r2's CDEF work already on the branch).
29+
30+No gate needed for this one (charter: "make it refuse by name... and prove
31+the refusal with a test" -- minimum rung taken deliberately, not the
32+"handle it" rung, since real non-SPLIT part64 content requires the same
33+multi-SB, non-`--cpu-used=0` recipe r2 already flagged as its own separate
34+lane, not this desync fix).
35+
36+## Job 2 -- delta_q/delta_lf: scoped, not started
37+
38+Ran the libaom source at `~/.cache/aom-oracle/src/av1/decoder/decodemv.c`
39+and `av1/common/entropymode.c` directly (real oracle, not memory) before
40+running out of budget. Concrete plan for the next agent:
41+
42+### Default CDFs (verified against entropymode.c:840-852)
43+Both are 4-symbol alphabets (`DELTA_Q_PROBS`/`DELTA_LF_PROBS` = 3), and this
44+crate's CDF convention already matches libaom's `AOM_CDF4` arguments
45+directly (confirmed against `cdf.rs`'s existing `SKIP` table, which is
46+`AOM_CDF2(31671)` verbatim) -- no inversion needed:
47+```rust
48+pub const DELTA_Q: [u16; 5] = [28160, 32120, 32677, 32768, 0];
49+pub const DELTA_LF: [u16; 5] = [28160, 32120, 32677, 32768, 0];
50+pub const DELTA_LF_MULTI: [[u16; 5]; 4] = [DELTA_Q; 4]; // same value x FRAME_LF_COUNT
51+```
52+(`FRAME_LF_COUNT = 4`, `MAX_LOOP_FILTER = 63`, `DELTA_Q_SMALL = DELTA_LF_SMALL = 3`.)
53+
54+### Read logic (decodemv.c:85-146, `read_delta_qindex`/`read_delta_lflevel`,
55+called from `read_delta_q_params` at :732)
56+Both follow the same shape: a 4-symbol CDF read; if the result is 3
57+(`DELTA_*_SMALL`), extend with `L(3)`-then-`1+that`-many literal bits
58+(`rem_bits = literal(3)+1; thr = (1<<rem_bits)+1; abs = literal(rem_bits) +
59+thr`); if `abs != 0` read one sign literal bit (sign=1/no-read implied
60+"positive" when abs==0, matching spec/libaom exactly -- `sign = abs ?
61+read_bit() : 1`); `reduced = sign ? -abs : abs`. For q: `CurrentQIndex =
62+clamp(CurrentQIndex + reduced*delta_q_res, 1, 255)`. For lf: same shape,
63+`clamp(DeltaLF[i] + reduced*delta_lf_res, -63, 63)`, looped over 4 planes
64+if `delta_lf_multi` else just index 0 against the single `delta_lf_cdf`.
65+
66+### The gating condition (decodemv.c:94-95, :121-122) -- **not** a spec
67+`ReadDeltas` global, libaom computes it locally per call:
68+```c
69+read_delta_q_flag = (mi_col & (mib_size-1) == 0 && mi_row & (mib_size-1) == 0);
70+if ((bsize != sb_size || !skip) && read_delta_q_flag) { ...read... }
71+```
72+Both conditions collapse to: **the very first block decoded inside a
73+superblock always has this MI position** (partition trees decode top-left
74+leaf first, always), so a per-SB `Cell<bool>` reset exactly like
75+`CDEF_TRANSMITTED` (decode.rs ~82, reset alongside it at the top of both
76+tile loops' `sb_c` loop bodies) replaces the position check with no
77+behavioural difference. The remaining condition, "skip the read entirely
78+(state carries over unchanged)", fires only when this first block **is
79+itself the whole superblock** (`bsize == sb_size`) **and** `skip == true`.
80+
81+### Call sites -- only 4, not the dozen it looks like
82+`maybe_read_cdef_idx` (decode.rs:115) is called from exactly 4 places,
83+right after each one's own `skip` read, and delta_q/delta_lf's spec order
84+is `skip -> cdef -> delta_q -> delta_lf` (already commented at decode.rs
85+~2474: "spec order... `cdef` lands right here" -- delta lands right after
86+that same line, one function per call site):
87+- `read_intra_mode_rect` (decode.rs:1987, feeds `decode_block_rect`) --
88+ `bw`/`bh` never both 64 here (SB-level partition never recurses to a rect
89+ strip directly), so `is_whole_sb` is always `false`.
90+- `read_intra_mode` (decode.rs:2447, feeds `decode_block`/`decode_leaf8`) --
91+ has a `side: usize` param; `is_whole_sb = side == 64`.
92+- `decode_inter_block` (decode.rs:6344) -- has `side: usize`; same rule.
93+- `decode_inter_block8` (decode.rs:8215) -- always sub-8x8, `is_whole_sb`
94+ always `false`.
95+
96+### Threading `CurrentQIndex` into dequant -- narrower than it looks
97+`base_q_idx: u8` is already threaded as a plain pass-through parameter
98+through every one of these functions down to exactly 2 real use sites
99+(confirmed by grep -- `base_q_idx` appears 92x in decode.rs but is *read*,
100+not just passed, only at decode.rs:2986 and :5397, both
101+`dequant_and_inverse_typed(..., i32::from(base_q_idx), ...)`). This means
102+the running quantizer state does **not** need a new parameter threaded
103+through every block/leaf/rect function signature: a `thread_local!
104+static CURRENT_Q_IDX: Cell<i32>`, reset to `base_q_idx as i32` at the top
105+of both `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
106+(same place `CDEF_BITS`/`CDEF_SB_COLS` already get set per tile), mutated
107+only inside the new `maybe_read_delta_q_lf` helper, and read back at the 2
108+dequant call sites instead of `i32::from(base_q_idx)`, reproduces the exact
109+running-state semantics with no signature changes to the block readers.
110+`DeltaLF` needs the same `Cell<[i32; 4]>` treatment, but **does** need a
111+consumer: `lf_level`/`edge_params` (decode.rs:3991/4020) currently read
112+only the frame-level `LoopFilterParams.level` array -- applying `DeltaLF`
113+there needs `MiGrid`/`fill_lf_grid` (decode.rs:1444) to carry a per-block
114+delta value forward to the deblocker, which is genuinely new state, not a
115+narrow substitution like q_idx. This is the part of Job 2 that needs a
116+real design pass, not just wiring -- flag it to whoever picks this up next.
117+
118+### Header threading + refusal removal
119+`header.delta.{q_present,q_res,lf_present,lf_res,lf_multi}`
120+(`ec_av1_syntax::frame::DeltaParams`, already parsed) need to become new
121+parameters on `decode_key_frame_tile_with_cdfs`/`_inter_..._with_cdfs` (and
122+their public non-`_with_cdfs` wrappers, and `stream.rs`'s 2 call sites),
123+mirroring how `CdefParams`/`LoopFilterParams` are already threaded. Then
124+delete the `stream.rs:170-174` refusal
125+(`"a frame with delta_q_present or delta_lf_present set..."`).
126+
127+### Gate
128+Reproducible refusal fixture already on file (r2's note): `--aq-mode=1` or
129+default `cpu-used>=1` at 128x64+. Same shape as the CDEF gate (128x64,
130+2 SBs, `--threads=1 --row-mt=0`), with a hard-asserted firing counter
131+(`DELTA_Q_HITS`/`DELTA_LF_HITS`, same `Cell<usize>` pattern as
132+`CDEF_IDX_HITS`).
133+
134+## Remaining refusal strings verbatim (all pre-existing, untouched by this
135+lane except the one new one above)
136+- `"a partition type this encoder never writes"` (decode.rs, intra SB
137+ level, key frame catchall) -- pre-existing, real, out of scope.
138+- `"a partition type this encoder never writes (value={part32})"` -- pre-existing.
139+- `"an INTER 32x32 partition type this encoder never writes (value={part32})"` -- pre-existing.
140+- `"a frame with delta_q_present or delta_lf_present set (this decoder
141+ never reads the per-superblock delta symbols)"` -- Job 2's target,
142+ **still present, still refuses correctly** (not touched this round).
143+- `"an inter SB-level partition type other than SPLIT (this decoder's
144+ inter tile path only recurses a superblock as SPLIT)"` -- **new this
145+ lane**, Job 1.
146+
147+## Merge note
148+`gate_coverage.rs`/`refusal_inventory.rs` (main-only guards this worktree
149+doesn't have) need the one new refusal string above added at merge; nothing
150+to delete from `gate_coverage.rs` this round since no gate closed a tool
151+entry (Job 1 has no gate by design, see above).
152+
153+## Next lever
154+Job 2 exactly as scoped above. The `DeltaLF`-into-deblocker sub-problem
155+(new `MiGrid` state, not a narrow substitution) is the one piece that needs
156+design before code -- everything else (CDFs, read logic, call sites,
157+`CURRENT_Q_IDX` substitution, header threading, refusal removal, gate
158+recipe) is now a direct port, not an investigation.
lanes/tiles-r2.charter.mdadded+61 -0
@@ -0,0 +1,61 @@
1+# lane-tiles r2 — actually decode the tiles
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-tiles`, branch
4+`lane-tiles`, at 23f412f.
5+
6+## Read first, then write code
7+- `lanes/tiles.report.md` — r1's report. Its "next lever" section names exact
8+ line ranges and the staging order. Do NOT redo r1's recon (class
9+ `worker-cap-spent-reading`).
10+- `lanes/tiles.charter.md` — the original charter: the three hard parts
11+ (entropy reset per tile, tile-clipped neighbour availability,
12+ `context_update_tile_id`), the gate rules, the hard rules. Still binding.
13+
14+## What r1 landed (1231cd5, suite green 232/0, currently a no-op)
15+`Neighbours` gained `tile_row0_mi` / `tile_col0_mi` and `start_tile()`, and every
16+literal-`0` availability check — `skip_txfm_ctx`, `tx_size_context`,
17+`tx_size_context_rect`, and the has_above / has_left in `decode_inter_block` and
18+`decode_inter_block8` — now compares against the tile origin instead of 0.
19+Nothing calls `start_tile()` yet, so the origin stays 0 and behaviour is
20+unchanged.
21+
22+## Still missing (r1's list, verbatim)
23+- entropy-per-tile restructuring in `decode_key_frame_tile_with_cdfs` /
24+ `decode_inter_frame_tile_with_cdfs`
25+- `PlaneBuf` tile-pixel-origin clipping — not started
26+- `mvstack.rs` neighbour scan still frame-relative
27+- multi-OBU tile-group collection — not started
28+- the refusal at `stream.rs:294-296` is unchanged and still fires
29+
30+## Order — COMMIT AFTER EVERY GREEN STEP
31+1. Restructure `decode_key_frame_tile_with_cdfs` to loop tiles: fresh msac over
32+ each tile's byte range, fresh copy of the frame's initial CDFs per tile, and
33+ only `context_update_tile_id`'s end-of-tile CDFs kept. Wire `start_tile()`
34+ and the new `PlaneBuf` tile-pixel-origin fields. Prove it on an intra-only
35+ two-tile column split, pixel-exact. COMMIT.
36+2. Tile rows, then non-uniform spacing. COMMIT.
37+3. Inter frames — thread the tile origin into `mvstack.rs`'s neighbour scan.
38+ This is where it will break. COMMIT.
39+4. Several tile-group OBUs per frame. COMMIT.
40+5. `context_update_tile_id` proven with a stream where it is not tile 0, the
41+ FOLLOWING frame decoding pixel-exact off those inherited CDFs. COMMIT.
42+
43+## Gate (mandatory)
44+Same rules as r1's charter: `EC_AV1_REQUIRE_AOMENC=1` on every run, `-t <seconds>`
45+on every ffmpeg generate, fixtures through `gradients_source(seed, w, h, tail)`,
46+aomenc `--threads=1 --row-mt=0` plus tile-columns/tile-rows log2, a frame large
47+enough to be splittable, and a HARD-asserted thread-local `Cell<usize>` counter
48+proving more than one tile was decoded.
49+
50+## Hard rules
51+- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tiles`. Foreground builds,
52+ `nice -n 19 cargo ... -j4`; give every `cargo test` a timeout of at least
53+ 600000 ms (the suite runs ~3-4 min; a 120 s default kills it mid-run).
54+- Sibling worktrees (edith_codecs, -chroma, -realworld, -lr, -superres) have
55+ live agents. Never build in or edit them.
56+- Baseline 232 passed / 0 failed on this tree; main is at 234 with two new
57+ guard tests you inherit at merge.
58+- NEVER push, never merge, never touch `main`. Commit on `lane-tiles` only.
59+- 75-turn cap: commit at every green step. Stage 1 alone committed and green is
60+ a good outcome; a perfect uncommitted tree is not.
61+- End with `lanes/tiles-r2.report.md`, VERDICT on the first line.
lanes/tiles-r3.charter.mdadded+48 -0
@@ -0,0 +1,48 @@
1+# lane-tiles r3 — verify r2's per-tile loop, then finish it
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-tiles`, branch
4+`lane-tiles`, at d1c2071.
5+
6+## State
7+- `1231cd5` (r1) — tile-origin groundwork in `Neighbours` (`tile_row0_mi`,
8+ `tile_col0_mi`, `start_tile()`), every literal-`0` availability check keyed on
9+ the tile origin. A no-op until something calls `start_tile`.
10+- `d1c2071` (r2, cap-rescued by the orchestrator) — `decode.rs` +159,
11+ `stream.rs` +3, staged but never committed by r2 and **never seen to compile
12+ or pass anything**. That is your first job: find out what it is.
13+- `lanes/tiles-r2.charter.md` and `lanes/tiles.charter.md` still govern the
14+ staging, the three hard parts and the gate rules. `lanes/tiles.report.md` has
15+ r1's exact line ranges.
16+
17+## Order
18+1. `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tiles`, then
19+ `cargo check -p ec-av1 --lib` and, if it compiles,
20+ `EC_AV1_REQUIRE_AOMENC=1 nice -n 19 cargo test -p ec-av1 --lib -j4`
21+ (timeout >= 600000 ms). Report the count against 232/0 for this tree. Getting
22+ d1c2071 green is the whole job until it is green. COMMIT once green.
23+2. Stage 1 from the r2 charter: the key-frame tile decode as a per-tile loop —
24+ fresh msac over each tile's byte range, a fresh copy of the frame's initial
25+ CDFs per tile, only `context_update_tile_id`'s end-of-tile CDFs kept, and
26+ `start_tile()` wired along with the `PlaneBuf` tile-pixel-origin fields.
27+ Proven on an intra-only two-tile column split, pixel-exact, with a
28+ hard-asserted thread-local count of tiles decoded `> 1`. COMMIT.
29+3. Then tile rows and non-uniform spacing; then inter frames (thread the tile
30+ origin into `mvstack.rs`'s neighbour scan — this is where it will break);
31+ then several tile-group OBUs per frame; then `context_update_tile_id` proven
32+ with a stream where it is not tile 0. One commit each.
33+
34+## Note for the merge
35+Main carries two guards you do not have: `gate_coverage.rs` (pins the aomenc
36+tools no gate exercises) and `refusal_inventory.rs` (pins every decode-path
37+refusal string, so adding, renaming or removing one — including the multi-tile
38+refusal you are here to delete — fails until the list is updated). Report the
39+refusal strings you change, verbatim.
40+
41+## Hard rules
42+Foreground builds `nice -n 19 cargo ... -j4`, own `CARGO_TARGET_DIR` as above,
43+every `cargo test` a timeout >= 600000 ms. Sibling worktrees (edith_codecs,
44+-chroma, -realworld, -lr, -superres, -palette) have live agents — never build in
45+or edit them. Never push, never merge, never touch `main`. 75-turn cap, does not
46+reset: COMMIT AT EVERY GREEN STEP — both rounds on this lane so far ended with
47+work uncommitted. Stage 1 committed and green is a good round on its own. End
48+with `lanes/tiles-r3.report.md`, VERDICT on line 1.
lanes/tiles-r3.report.mdadded+67 -0
@@ -0,0 +1,67 @@
1+VERDICT: PARTIAL -- step 1 (confirm) and step 2 (prove) done and committed; step 3
2+(lift the refusal) not attempted, out of turn budget.
3+
4+## Step 1: confirmation run
5+`cargo check -p ec-av1 --tests` clean. `EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1
6+--lib -j4`: 232 passed, 0 failed, 17 ignored, 207.55s -- matches the corrected charter
7+note exactly. Nothing to commit (tree was already clean at d1c2071).
8+
9+## Step 2: prove the per-tile loop on a real two-tile-column stream
10+Added `a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact` to
11+`crates/ec-av1/src/stream.rs` (committed 1648317). It:
12+- builds a 128x64 aomenc key frame with `--tile-columns=1 --tile-rows=0
13+ --sb-size=64 --loopfilter-control=0`, 20-seed sweep (structural tile split
14+ isn't content-dependent, but this decoder's pre-existing chroma
15+ smooth/paeth refusal is -- accepted as a named refusal like every sibling
16+ gate does for unrelated capabilities);
17+- parses the stream itself (not `decode_stream`, whose `cols > 1 || rows > 1`
18+ refusal is exactly what this gate runs ahead of) to get the real `Vec<Tile>`
19+ `Av1Parser::parse_obu` already produces;
20+- calls `decode_key_frame_tile_with_cdfs(&[tile0, tile1], &header.tile_info,
21+ ...)` directly;
22+- hard-asserts `tile_hits()` delta `> 1` and pixel-exactness against ffmpeg.
23+
24+Result: 20/20 pixel-exact matches, 0 refusals, tile_hits > 1 every time.
25+`cargo check -p ec-av1 --tests` clean after.
26+
27+Two things needed beyond the charter's one-liner:
28+- `--sb-size=64`: this decoder hardcodes 64px superblocks everywhere
29+ (SB_MI=16); aomenc's own default is 128px SBs, which makes 128x64 exactly
30+ one superblock -- nothing for `--tile-columns=1` to split, `cols` came back
31+ 1 without this.
32+- `--loopfilter-control=0`: deblocking crosses tile boundaries by spec
33+ default, and `PlaneBuf`'s `tile_x0`/`tile_y0` only ever clip a tile's own
34+ left/top reach (the exact known gap r2 flagged) -- a non-last column's
35+ right-edge deblock read into the next tile wrong without this. Sidestepped
36+ on purpose; not fixed, deblocking is not what this gate proves.
37+
38+Also caught and fixed a real bug in my own first draft while wiring the test:
39+`Tile::offset` is relative to the buffer `parse_obu` was handed, not absolute
40+in `stream` -- forgetting to add `obu_offset` back (the way `decode_stream`
41+already does at its own tile-extraction site) fed the decoder garbage-offset
42+bytes, which silently decoded as an all-skip flat DC block per tile (128/127
43+uniform) instead of erroring -- a quiet false negative, not a crash. Fixed
44+before committing; the committed test carries a comment on this.
45+
46+## Step 3: not attempted
47+Lifting the `cols > 1 || rows > 1` refusal in `decode_stream` needs more than
48+deleting the `if`: the call site currently hardcodes `&[tile_bytes]` (single
49+tile, `tiles.first()`), so it needs building the full `tile_bufs: Vec<&[u8]>`
50+the same way this gate's test code now does (including the `obu_offset` fix),
51+threaded through for BOTH `decode_key_frame_tile_with_cdfs` and
52+`decode_inter_frame_tile_with_cdfs`. More importantly, real streams
53+`decode_stream` sees do NOT get `--loopfilter-control=0` for free -- lifting
54+the refusal for general (non-test-controlled) multi-tile streams would need
55+either the right-edge reach gap actually fixed in `PlaneBuf`, or deblocking
56+proven to not cross tile boundaries in the streams under test
57+(`loop_filter_across_tiles_enabled` -- unread, not checked this round).
58+Doing this without checking would very likely reintroduce the exact luma
59+mismatch this round diagnosed (uncaught first-draft bug notwithstanding) for
60+any real multi-tile stream with loop filtering on. Left for the next round;
61+the intra-only case specifically (per charter step 3) still needs the deblock
62+question answered first.
63+
64+## Refusal strings
65+None added, renamed or removed this round -- the multi-tile refusal in
66+`stream.rs` is untouched. (Step 3, when attempted, will need to report this
67+line verbatim before deleting it, per the charter's merge note.)
lanes/tiles-r4.charter.mdadded+47 -0
@@ -0,0 +1,47 @@
1+# lane-tiles r4 — lift the multi-tile refusal
2+
3+At 477f972. Read `lanes/tiles-r3.report.md`.
4+
5+## State
6+The per-tile loop works and is proven: gate
7+`a_real_aomenc_stream_with_two_tile_columns_decodes_pixel_exact` (stream.rs
8+~5484) decodes 20/20 pixel-exact with `tile_hits()` hard-asserted `> 1`, by
9+calling `decode_key_frame_tile_with_cdfs(&[tile0, tile1], ...)` directly and
10+bypassing the still-live refusal in `decode_stream`.
11+
12+Facts r3 paid for: `--sb-size=64` is required (this decoder hardcodes 64px
13+superblocks; aomenc's default 128px makes a 128x64 frame a single superblock
14+with nothing to split). `--loopfilter-control=0` is required *for now* because
15+deblocking crosses tile boundaries by spec default while `PlaneBuf`'s
16+`tile_x0`/`tile_y0` clip left/top reach only. And a trap that produced a FALSE
17+PASS: `Tile::offset` is relative to the slice handed to `parse_obu`, not
18+absolute — forgetting to add `obu_offset` back decoded flat all-skip DC garbage
19+that compared "equal" instead of erroring.
20+
21+## Your job
22+1. Read `loop_filter_across_tiles_enabled` in `ec-av1-syntax`'s header parse —
23+ grep it first, it may not be parsed at all. Real multi-tile streams reaching
24+ `decode_stream` get no `--loopfilter-control=0` escape hatch, so this
25+ question has to be answered before the refusal comes off.
26+2. Thread a real `tile_bufs: Vec<&[u8]>` through `decode_stream`'s key-frame AND
27+ inter-frame tile-decode call sites (both currently hardcode
28+ `&[tile_bytes]`), mirroring r3's `obu_offset`-corrected extraction.
29+3. Lift the `cols > 1 || rows > 1` refusal for the cases you can prove, and
30+ refuse the rest BY NAME with an accurate string. Re-run r3's gate through
31+ `decode_stream` itself, and drop `--loopfilter-control=0` from it once the
32+ crossing question is resolved to see whether it still holds. COMMIT.
33+4. Then tile rows, non-uniform spacing, inter frames (tile origin into
34+ `mvstack.rs`), several tile-group OBUs, and `context_update_tile_id != 0`.
35+ Also still open: a non-last tile column's right-edge reach bound is
36+ unimplemented (fine for 2 columns, wrong for 3+).
37+
38+Merge note: main is at 06d29ee with `gate_coverage.rs` and `refusal_inventory.rs`,
39+which pin the aomenc tools no gate exercises and every decode-path refusal
40+string — including the multi-tile refusal you are here to remove. Report every
41+refusal string you add, rename or remove, verbatim.
42+
43+Hard rules: `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tiles`; foreground
44+`nice -n 19 cargo ... -j4`; every `cargo test` a timeout >= 600000 ms. Sibling
45+worktrees have live agents — never build in or edit them. Never push, never
46+merge, never touch `main`. 75-turn cap, does not reset: COMMIT AT EVERY GREEN
47+STEP. End with `lanes/tiles-r4.report.md`, VERDICT on line 1.
lanes/tiles-r4.report.mdadded+80 -0
@@ -0,0 +1,80 @@
1+VERDICT: PARTIAL -- steps 1-3 done and committed (9962fb1); step 4 (tile rows,
2+non-uniform spacing, inter frames, several tile-group OBUs,
3+context_update_tile_id != 0) not attempted, out of scope this round.
4+
5+## Step 1: `loop_filter_across_tiles_enabled`
6+Grepped `crates/ec-av1-syntax/src/frame.rs`'s `read_loop_filter_params` (spec
7+5.9.11) end to end: the field does not exist, and it isn't a gap in this
8+crate's parser -- AV1's spec `loop_filter_params()` has no such syntax
9+element at all (unlike HEVC's `loop_filter_across_tiles_enabled` PPS flag,
10+which the charter's naming echoes but AV1 has no equivalent of). Deblocking
11+crosses tile boundaries unconditionally whenever `loop_filter.level` is
12+non-zero; there is no per-stream bit that turns it off. That answers the
13+charter's question: the refusal cannot be conditioned on a header field,
14+only on whether loop filtering is on at all (`level.iter().any(|&l| l != 0)`)
15+combined with the already-known `PlaneBuf` gap (tile origin clips a tile's
16+own left/top reach, never a non-last column's right-edge reach).
17+
18+## Step 2: thread real `tile_bufs` through `decode_stream`
19+`crates/ec-av1/src/stream.rs`'s key-frame call site now builds
20+`tile_bufs: Vec<&[u8]>` from every element of the OBU's own `tiles: Vec<Tile>`
21+(the same `obu_offset + t.offset` correction r3's gate proved necessary) and
22+passes `&tile_bufs` to `decode_key_frame_tile_with_cdfs` instead of the old
23+`&[tile_bytes]` (tile 0 only). The inter-frame call site still passes the
24+single `tile_bytes` it always did -- `decode_inter_frame_tile_with_cdfs`
25+takes one `&[u8]`, not a tile list, and has no per-tile loop at all; widening
26+that signature is real work left for step 4 ("inter frames (tile origin into
27+mvstack.rs)"), not attempted this round.
28+
29+## Step 3: lift the refusal, scoped; re-run r3's gate through `decode_stream`
30+The blanket `cols > 1 || rows > 1` refusal is now four scoped refusals, only
31+firing for what is genuinely still unproven:
32+- inter frame with `cols > 1` (no per-tile loop on that path at all)
33+- `rows > 1` (tile rows never tested)
34+- `cols > 2` (non-last column's right-edge reach bound past column 0 is
35+ unimplemented -- r3's own documented gap, matters starting at 3 columns)
36+- multi-tile frame with `loop_filter.level` non-zero anywhere (deblocking
37+ crossing gap from step 1)
38+
39+A key frame with exactly 2 tile columns, 1 tile row, and loop filtering off
40+now decodes through `decode_stream` itself. New test
41+`a_real_aomenc_stream_with_two_tile_columns_decodes_through_decode_stream`
42+(`stream.rs`, next to r3's gate) runs the identical aomenc recipe through
43+`decode_stream(&stream)` instead of the hand-parsed bypass: 20/20 pixel-exact,
44+`tile_hits()` delta `> 1` every attempt, `pictures.len() == 1`.
45+
46+Did not drop `--loopfilter-control=0` from either gate -- step 1 established
47+that would hit the still-unfixed `PlaneBuf` cross-tile-column reach gap
48+(the new refusal explicitly names this and blocks it before it can silently
49+miscode), not something worth testing-then-reverting this round.
50+
51+## Full suite
52+`cargo check -p ec-av1 --tests`: clean (only pre-existing doc-lint warnings).
53+`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -j4`: 234 passed, 0
54+failed, 17 ignored, 146.97s -- both tile gates included, nothing else moved.
55+
56+## Refusal strings
57+
58+Removed (verbatim, was the single blanket refusal):
59+> a frame with more than one tile (this decoder only ever decodes tile 0)
60+
61+Added, four in its place (all in `stream.rs`, all `Error::unsupported("AV1
62+decode_stream", ...)`):
63+> an inter frame with more than one tile (the inter tile-decode path has no per-tile loop, only key frames do)
64+
65+> a frame with more than one tile row (only tile columns are proven pixel-exact so far)
66+
67+> a frame with more than two tile columns (a non-last column's right-edge reach bound past column 0 is unimplemented)
68+
69+> a multi-tile frame with loop filtering enabled (deblocking crosses tile boundaries by spec default; PlaneBuf's tile origin does not clip a non-last column's right-edge reach)
70+
71+## Still open (per charter step 4, unattempted)
72+Tile rows, non-uniform tile spacing, inter-frame multi-tile decode (needs
73+`decode_inter_frame_tile_with_cdfs` to grow the same per-tile loop
74+`decode_key_frame_tile_with_cdfs` already has, plus tile origin threaded into
75+`mvstack.rs` for inter prediction/MV candidates that reach across a tile
76+boundary), several tile-group OBUs per frame, `context_update_tile_id != 0`
77+(this decoder still only ever keeps tile 0's adapted CDF table as the frame's
78+output regardless of what the header names), and the 3+-column right-edge
79+reach bound in `PlaneBuf` itself (currently hard-refused via the `cols > 2`
80+check above rather than silently miscoding).
lanes/tiles.charter.mdadded+96 -0
@@ -0,0 +1,96 @@
1+# lane-tiles — multi-tile decode
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-tiles`, branch
4+`lane-tiles`, off main (48a6e29 or later).
5+
6+## Goal
7+Remove the refusal at `crates/ec-av1/src/stream.rs:293-298`
8+("a frame with more than one tile (this decoder only ever decodes tile 0)")
9+by decoding every tile of every tile group, in order, into one picture.
10+
11+## What is already there
12+- `crates/ec-av1-syntax/src/frame.rs:115` `TileInfo` already carries everything
13+ the walk needs: `cols`, `rows`, `cols_log2`, `rows_log2`, `mi_col_starts`
14+ (`TileCols + 1` entries, 4x4 units), `mi_row_starts`, `context_update_tile_id`,
15+ `tile_size_bytes`. The uniform/non-uniform spacing derivation is at
16+ `frame.rs:1292` onward and is already implemented — READ it, do not re-derive.
17+- The tile-group OBU parse already produces per-tile `offset`/`size`; today
18+ `stream.rs` takes `tiles.first()` and drops the rest. `Tile::offset` is
19+ relative to the OBU buffer, not to `data` — see the comment at stream.rs:298.
20+- The superblock walk lives in `crates/ec-av1/src/decode.rs` (two sites, around
21+ lines 4547 and 9275: `for sb_r in 0..sb_rows { for sb_c ... }`). Today those
22+ bounds are the whole frame; per tile they become the tile's own sb range
23+ derived from `mi_row_starts[t]..mi_row_starts[t+1]`.
24+
25+## The three things that make tiles more than a loop
26+1. **Entropy reset per tile.** Each tile starts a FRESH msac decoder over its
27+ own byte range AND a fresh copy of the frame's initial CDFs (spec 5.11.2
28+ `decode_tile`: `init_symbol` + `clear_above_context`). Only the tile named by
29+ `context_update_tile_id` has its END-of-tile adapted CDFs saved as the
30+ frame's output tables (spec `exit_symbol`) — every other tile's adaptation is
31+ discarded. This is exactly what the current refusal comment warns about.
32+2. **Context reset at tile boundaries.** Above-context arrays are cleared at the
33+ start of each tile ROW of superblocks within the tile; left-context at each
34+ superblock row. Neighbour availability MUST be clipped to the tile: a block
35+ at the tile's left edge has NO left neighbour even though a decoded block
36+ sits there in the picture. Same for above. Grep libaom
37+ `av1/decoder/decodeframe.c` `av1_tile_init`/`av1_tile_set_col`/
38+ `av1_tile_set_row` and `av1/common/tile_common.c`; the availability
39+ predicates are `xd->left_available` / `xd->up_available`, set in
40+ `set_mi_row_col` (av1/common/blockd.h). Deblocking and CDEF, by contrast,
41+ run ACROSS tile boundaries unless `loop_filter_across_tiles` says otherwise —
42+ check the actual v3.13.3 source, AV1 has no such flag in the final spec but
43+ verify rather than assume.
44+ Also check the mv-stack / ref-mv scan (`crates/ec-av1/src/mvstack.rs`) and
45+ the CDEF/deblock neighbour reads for the same tile clipping.
46+3. **Tile ordering across tile groups.** A frame may carry several tile-group
47+ OBUs; tiles are numbered `tg_start..tg_end` globally.
48+
49+## Method
50+CLASS `compare-range-not-tell`: compare the msac RANGE against the oracle after
51+each element, never `tell()`. The instrumented oracle is at `~/.cache/aom-oracle`
52+with env-gated rungs (`EC_TRACE=1` partitions, `EC_TRACE_COEFF=1`,
53+`EC_TRACE_MODE=1`); `scripts/instrument-aom-oracle.sh` + `scripts/build-aom-oracle.sh`
54+add and rebuild rungs. If you need a per-tile rung (tile index at each
55+`decode_tile` entry), add one in the existing shape: env-gated, silent when
56+unset, idempotent, wrapper-around-impl.
57+CLASS `equal-range-means-unread`: reference range unchanged where ours moves =
58+we read a symbol it never wrote; theirs moves and ours does not = we skipped one.
59+
60+## Staging — COMMIT AFTER EVERY GREEN MILESTONE (75-turn cap; builders have lost whole implementations here)
61+1. Two tiles, one column split, all-intra key frame. COMMIT.
62+2. Tile rows as well as columns; non-uniform spacing. COMMIT.
63+3. Inter frames (mv-stack + neighbour clipping is where this will break). COMMIT.
64+4. Several tile-group OBUs per frame. COMMIT.
65+5. `context_update_tile_id` proven: a stream where it is NOT tile 0, decoding
66+ pixel-exact across the following frame (which inherits those CDFs). COMMIT.
67+
68+## Gate (mandatory, in `crates/ec-av1/src/stream.rs` beside the existing gates)
69+- Copy the existing gate shape. Tests must be run with `EC_AV1_REQUIRE_AOMENC=1`
70+ so a missing oracle FAILS instead of SKIPping.
71+- Bound every ffmpeg `generate` with `-t <seconds>` (an unbounded source once
72+ hung a gate for an hour).
73+- Build fixtures through the existing `gradients_source(seed, w, h, tail)`
74+ helper — ffmpeg's `gradients` ignores its own seed, so a hand-written
75+ `gradients=size=` string makes the gate non-reproducible.
76+- aomenc: `--threads=1 --row-mt=0` plus `--tile-columns=1 --tile-rows=1`
77+ (log2 values in aomenc) on a frame large enough that the tiles are legal —
78+ a 64x64 frame cannot be split, so size the fixture accordingly.
79+- Hard-assert a firing count: a thread-local `Cell<usize>` counter in decode.rs
80+ matching the existing `*_HITS` (thread-local, NOT atomics), incremented per
81+ tile decoded, asserted `> 1`. CLASS `gate-blind-to-feature`: a gate that
82+ cannot prove its feature fired is vacuous.
83+- Refusals inside the gate are FORBIDDEN once the stage removing them lands.
84+
85+## Hard rules
86+- `export CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tiles`. Foreground builds
87+ only, `nice -n 19 cargo ... -j4`. Never build in or edit another worktree:
88+ edith_codecs, -chroma, -realworld, -lr, -superres all have agents in them NOW.
89+- Suite: `nice -n 19 cargo test -p ec-av1 --lib`, baseline 232 passed / 0 failed
90+ (~67 s). It stays green.
91+- NEVER push, never merge, never touch `main`. Commit on `lane-tiles` only.
92+- Refuse-by-name rather than desync; never write a refusal string claiming the
93+ encoder cannot emit a case unless you proved it (class
94+ `refusal-claim-disproved-by-its-own-gate`).
95+- End with `lanes/tiles.report.md`: what landed, gate name + firing count,
96+ remaining refusal strings verbatim, next lever.
lanes/tiles.report.mdadded+116 -0
@@ -0,0 +1,116 @@
1+# lane-tiles report
2+
3+## What landed
4+Groundwork only, commit `1231cd5` on branch `lane-tiles`:
5+`crates/ec-av1/src/decode.rs`
6+- `Neighbours` gained `tile_row0_mi`/`tile_col0_mi` (spec `MiRowStart`/
7+ `MiColStart`), default `0`, and `start_tile(row0_mi, col0_mi, col1_mi)`
8+ (spec `decode_tile`'s `clear_above_context` over the tile's own column
9+ span; left-context reset per SB row was already unconditional and needed
10+ no change).
11+- Every availability check that compared a raw mi position against literal
12+ `0` now compares against the tile origin instead: `skip_txfm_ctx`,
13+ `tx_size_context`, `tx_size_context_rect`, and `decode_inter_block`/
14+ `decode_inter_block8`'s `has_above`/`has_left`.
15+- Behaviourally a no-op today: nothing calls `start_tile`, so the origin
16+ stays `(0, 0)` everywhere and every existing test is bit-identical.
17+
18+The refusal at `crates/ec-av1/src/stream.rs:292-297` ("a frame with more
19+than one tile") is **unchanged and still fires** — it was not removed.
20+
21+## Why it stops here (turn budget)
22+Recon (charter + call-site tracing across `decode.rs`, `mvstack.rs`,
23+`ec-av1-syntax/frame.rs`'s `TileInfo`/`parse_tile_group`) took the first
24+~35 tool calls to establish the real shape of the three hard parts. What
25+full removal of the refusal needs, none of which is done:
26+1. **Entropy per tile.** `decode_key_frame_tile_with_cdfs` /
27+ `decode_inter_frame_tile_with_cdfs` each take one `data: &[u8]` and run
28+ one `SymbolDecoder`/`cdfs` over the whole `for sb_r in 0..sb_rows { for
29+ sb_c in 0..sb_cols }` walk. This needs restructuring into a `for tile in
30+ &tiles` outer loop: fresh `SymbolDecoder` per tile's own byte range
31+ (`Tile::offset` is relative to the OBU, already handled correctly in
32+ stream.rs for tile 0 today), fresh `cdfs = initial_cdfs.clone()` per
33+ tile, sb range narrowed to `mi_row_starts[t]/SB_MI..mi_row_starts[t+1]/
34+ SB_MI` (same for cols), and only `context_update_tile_id`'s own
35+ end-of-tile `cdfs` returned as the frame's adapted table. `TileInfo`
36+ already carries everything this needs (`frame.rs:115`); the derivation
37+ at `frame.rs:1292` confirms `mi_col_starts`/`mi_row_starts` are always
38+ fully populated by the real parser, including the `cols==rows==1` case.
39+2. **Context clipping — partially wired, NOT complete.** This commit's
40+ `Neighbours` change covers the context-symbol reads it touched. Two
41+ things it does **not** cover:
42+ - `PlaneBuf::edges`/`edges_rect` (`decode.rs` ~2653-2696) still gate
43+ intra-prediction pixel reach on `x > 0`/`y > 0` — a block at a tile's
44+ own left/top edge would read real reconstructed pixels from the
45+ PREVIOUS tile (decoded earlier, sitting right there in the shared
46+ buffer) instead of treating them as unavailable, which is a real
47+ pixel-value bug per spec (AV1 tiles are independently decodable;
48+ intra prediction does not cross tile boundaries). Needs a
49+ `tile_x0`/`tile_y0` pair on `PlaneBuf` (luma-pixel and chroma-pixel
50+ scaled, i.e. `mi_col0*4`/`mi_col0*2`), set before each tile, checked
51+ in `edges`/`edges_rect` in place of `0`.
52+ - `mvstack.rs`'s `find_mv_stack_with_sign_bias` (the actual MV
53+ neighbour scan for every inter block) still hardcodes
54+ `mi_row > 0`/`mi_col > 0` for `max_row_offset`/`max_col_offset` and
55+ `found_above`/`found_left` (its own doc comment at line ~690 already
56+ flags this: *"clamped to the tile's near edge (single-tile-per-frame
57+ here, so that's just the frame edge at 0)"*). `find_samples`/
58+ `num_proj_ref` (`decode.rs` ~5488/5617, warp-sample gathering for
59+ `WARPED_CAUSAL`) have the same gap. Neither was touched this round.
60+ - Deblock/CDEF were confirmed (not just assumed) to run across the
61+ whole picture after all tiles decode (`apply_deblock`/`apply_cdef`
62+ calls sit after the SB loop, once, over the full `y`/`u`/`v`) —
63+ these need **no** tile clipping, matching the charter's note.
64+3. **Tile-group ordering.** Not started. `ObuKind::Frame(header, tiles)`'s
65+ `tiles: Vec<Tile>` already spans every tile in `tg_start..tg_end` for a
66+ *single* OBU (`parse_tile_group`, `ec-av1-syntax/src/frame.rs:1992`),
67+ which covers the common `--tile-columns`/`--tile-rows` aomenc case (one
68+ `OBU_FRAME` carries every tile). The separate multi-OBU case
69+ (`ObuKind::FrameHeader` followed by one or more standalone
70+ `ObuKind::TileGroup(Vec<Tile>)` OBUs) is not collected at all today —
71+ `decode_stream`'s `while pos < data.len()` loop only matches
72+ `ObuKind::Frame`/`FrameHeader` (for `show_existing_frame`) and silently
73+ `continue`s past everything else, including a bare `TileGroup` OBU.
74+
75+No gate was added — the charter's mandatory gate asserts a tile-firing
76+counter `> 1` on real decoded output, which requires part 1 (entropy per
77+tile) to exist first; writing the gate against the untouched refusal would
78+either be vacuous or fail immediately.
79+
80+## Remaining refusal strings (verbatim, unchanged)
81+- `"a frame with more than one tile (this decoder only ever decodes tile 0)"`
82+ — `stream.rs:294-296`, still fires for every `tile_info.cols > 1 ||
83+ tile_info.rows > 1` frame, intra or inter.
84+
85+## Verification
86+`cargo test -p ec-av1 --lib` (`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-tiles`,
87+`EC_AV1_REQUIRE_AOMENC=1`): 232 passed, 0 failed, 17 ignored, 174.28s —
88+baseline unchanged, no regression from the groundwork commit.
89+
90+## Next lever (for whoever picks this up)
91+Land in the charter's own staged order, each its own commit:
92+1. Restructure `decode_key_frame_tile_with_cdfs` to accept
93+ `tiles: &[(u32 /* tile_num */, &[u8])]` + `&TileInfo` in place of a
94+ single `data: &[u8]`, wrap the existing SB double loop (currently
95+ `decode.rs` lines ~4547 header `for sb_r in 0..sb_rows` through its
96+ matching close ~4947) in `for &(tile_num, bytes) in tiles`, call
97+ `neighbours.start_tile(...)` (already written, unused) and set
98+ `PlaneBuf` tile pixel origins (not yet added) at each tile's start,
99+ narrow the sb range, and capture `cdfs` as the returned table only when
100+ `tile_num == tile_info.context_update_tile_id`. Update the one caller
101+ (`decode_key_frame_tile`, `decode.rs:4478`) and `stream.rs`'s key-frame
102+ branch to build the tile list instead of `tiles.first()`. Prove stage 1
103+ (two tiles, column split, all-intra) before touching anything else.
104+2. Same restructuring for `decode_inter_frame_tile_with_cdfs`, PLUS
105+ threading `tile_row0_mi`/`tile_col0_mi` into `find_mv_stack_with_sign_bias`
106+ and `find_samples`/`num_proj_ref` (both currently frame-relative-only).
107+3. Multi-tile-group OBU collection in `decode_stream`'s main loop
108+ (`ObuKind::FrameHeader` + trailing `ObuKind::TileGroup` accumulation
109+ before dispatch, mirroring the existing `pending: Option<FrameHeader>`
110+ field already on `Av1Parser` internally, though that field is private —
111+ check whether it's exposed or the collection has to happen in
112+ `decode_stream` itself against raw OBU events).
113+4. `context_update_tile_id != 0` pin test once tables save correctly.
114+5. The mandatory gate: `--tile-columns=1 --tile-rows=1` aomenc recipe
115+ (log2 values), thread-local `TILE_HITS` counter (not yet added)
116+ incremented once per tile actually decoded, hard-asserted `> 1`.