diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 435edffd..4bfcb4a4 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -17061,6 +17061,240 @@ mod tests { ); } + /// lane-av1paletteuv: the census for `crate::tile::palette_uv_side`, the + /// `(side / 2).max(4)` named in `lanes/av1subsizesweep.report.md` as a + /// "4:2:2/4:4:0 palette map mis-sized" site. + /// + /// **What the site computes.** libaom reads the plane-1 colour-index map + /// at `av1_get_block_dimensions(bsize, 1, xd)` (blockd.h:1512): per axis, + /// `plane_block = block >> ss`, then `+2` when that came out under 4 + /// (the chroma sub-8x8 bump, blockd.h:1533-1541). For a SQUARE 4:2:0 + /// block both axes carry `ss = 1`, so both come to `side / 2` with the + /// bump -- which is exactly `(side / 2).max(4)`. The value is right. + /// + /// **What it is not.** At 4:2:2 the correct map is `(side >> 1) x side` + /// and at 4:4:4 it is `side x side` -- neither is square. So the value is + /// 4:2:0-only BY CONSTRUCTION, and this gate is what keeps it that way: + /// if an encoder that can emit another chroma shape ever appears, this + /// reds rather than the writer silently writing a half-height map. + /// + /// The three arms are (1) the value matches libaom's own per-axis + /// formula at 4:2:0 over every side the palette syntax admits, (2) no + /// reachable writer path can be handed another chroma shape, (3) a real + /// encode really fires chroma palettes, so arm 1 is not arithmetic on a + /// function nothing calls (class `gate-blind-to-feature`). + #[test] + fn the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it() { + const NAME: &str = + "the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it"; + let encode_src = include_str!("encode.rs"); + let encoder_src = include_str!("encoder.rs"); + + // ---- arm 1: the value, against libaom's formula -------------------- + // blockd.h:1530-1541, transcribed. A plane_block under 4 gains 2. + let libaom_plane1 = |block: usize, ss: usize| { + let plane_block = block >> ss; + plane_block + 2 * usize::from(plane_block < 4) + }; + let mut admitted = 0usize; + for side in 4usize..=64 { + // `palette_bsize_ctx`'s own domain: both sides <= 64 and + // bw * bh >= 64 (`av1_allow_palette`). A side outside it codes no + // palette syntax at all, so its map size is unobservable. + if side > 64 || side * side < 64 { + continue; + } + admitted += 1; + let want_x = libaom_plane1(side, 1); + let want_y = libaom_plane1(side, 1); + assert_eq!(want_x, want_y, "{NAME}: 4:2:0 arms the libaom formula"); + assert_eq!( + crate::tile::palette_uv_side(side), + want_x, + "{NAME}: side {side} -- palette_uv_side disagrees with libaom's plane-1 block" + ); + } + assert_eq!( + admitted, 57, + "{NAME}: the sweep admitted {admitted} sides, expected 57 (every integer 8..=64 -- \ + `palette_bsize_ctx`'s whole square domain, not just the powers of two a real block \ + takes) -- it must cover that domain, or it is not measuring it" + ); + + // Why `.max(4)` cannot fire, stated as a measurement rather than left + // for a reader to assume: `palette_bsize_ctx` refuses `bw * bh < 64`, + // so the smallest admitted square side is 8, whose halved plane block + // is already 4. The floor's only reachable input would be a side + // under 8, and libaom's own chroma sub-8x8 bump (+2) is likewise + // unreachable there. Dropping the floor is therefore NOT a witness + // mutation for this gate -- the mutation that bites is dropping the + // halving (measured, see the lane report) -- and this arm says why, + // so nobody later mistakes a green floor mutation for coverage. + for side in [8usize, 16, 32, 64] { + assert!( + side / 2 >= 4 && libaom_plane1(side, 1) == side / 2, + "{NAME}: side {side} -- the admitted domain moved, so `.max(4)` may now be \ + reachable and the floor needs a witness mutation of its own" + ); + } + + // The claim the gate rests on, stated as arithmetic so a future + // reader cannot mistake "correct" for "correct at any shape": at + // these shapes the per-axis answer is NOT this square. + for side in [8usize, 16, 32, 64] { + let square = crate::tile::palette_uv_side(side); + let want_422 = (libaom_plane1(side, 1), libaom_plane1(side, 0)); + let want_444 = (libaom_plane1(side, 0), libaom_plane1(side, 0)); + assert_ne!( + (square, square), + want_422, + "{NAME}: side {side} -- a square map IS the 4:2:2 map, so this gate's premise \ + (the site is 4:2:0-only) is wrong" + ); + assert_ne!( + (square, square), + want_444, + "{NAME}: side {side} -- a square map IS the 4:4:4 map" + ); + } + + // ---- arm 2: nothing can hand the writer another shape -------------- + // (a) Every non-test `ColorConfig` literal in the encoder names + // subsampling (1, 1). These are the two constructors the whole + // encoder reaches its colour config through; the test-module copies + // are excluded by scanning only the pre-`mod tests` prefix. + fn head(src: &str) -> &str { + let cut = src.find("\nmod tests").unwrap_or(src.len()); + &src[..cut] + } + for (label, src) in [ + ("encode.rs", head(encode_src)), + ("encoder.rs", head(encoder_src)), + ] { + // Every `subsampling_*` the non-test encoder names, counted: a + // `(0, y)` or `(1, 0)` here is a chroma shape + // `palette_uv_side` cannot express. The one value allowed is 1 + // -- 4:2:0, the shape the square map is the right size for. + let mut shapes: std::collections::BTreeSet<(usize, usize)> = Default::default(); + for (sx, _) in src.match_indices("subsampling_x:") { + let rest = &src[sx + "subsampling_x:".len()..]; + let digits = |s: &str| { + s.trim_start() + .split(|c: char| !c.is_ascii_digit()) + .next() + .and_then(|d| d.parse::().ok()) + .unwrap_or(usize::MAX) + }; + let x = digits(rest); + let y = rest + .find("subsampling_y:") + .map(|y| digits(&rest[y + "subsampling_y:".len()..])) + .unwrap_or(usize::MAX); + shapes.insert((x, y)); + } + assert_eq!( + shapes, + std::collections::BTreeSet::from([(1usize, 1usize)]), + "{NAME}: the non-test {label} names chroma shapes {shapes:?} -- any shape other \ + than 4:2:0 is one palette_uv_side's square map cannot express (at 4:2:2 the \ + map is (side >> 1) x side, at 4:4:4 side x side)" + ); + } + + // (b) `key_frame_headers_colour` is the only PUBLIC entry that takes + // a caller-chosen ColorConfig -- it is how a 4:2:2 or 4:4:4 header is + // written at all -- so it is the one door a non-4:2:0 shape comes + // through. It builds HEADERS only: no tile writer is reachable from + // its body. (Its own doc says so; this measures it.) + let headers_at = encode_src + .find("pub fn key_frame_headers_colour(") + .expect("key_frame_headers_colour is gone -- re-derive this arm's scan anchor"); + let body_end = encode_src[headers_at..] + .find("\npub fn ") + .map(|n| headers_at + n) + .unwrap_or(encode_src.len()); + let headers_body = &encode_src[headers_at..body_end]; + for writer in [ + "write_palette_syntax", + "write_color_index_map", + "encode_key_frame_inner", + "tile::", + ] { + assert!( + !headers_body.contains(writer), + "{NAME}: key_frame_headers_colour now reaches {writer} -- a caller can pair a \ + 4:2:2/4:4:4 header with a tile, and palette_uv_side writes a square map into \ + the per-axis slot libaom reads as (side >> ss_x) x (side >> ss_y)" + ); + } + + // (c) Every tile-producing entry point goes through + // `encode_key_frame_inner`, whose five non-test call sites all pass + // one of the two 4:2:0 constructors above. Counted over the + // non-test source only, so a new road is a red rather than a line + // somebody has to notice. + let inner_calls = head(encode_src).matches("encode_key_frame_inner(").count() + + head(encoder_src).matches("encode_key_frame_inner(").count() + - 1; // the definition itself + assert_eq!( + inner_calls, 5, + "{NAME}: encode_key_frame_inner has {inner_calls} non-test call sites, expected 5 -- \ + a new one must pass a colour config this gate has read" + ); + + // (d) The picture itself is 4:2:0-shaped at the door, so a 4:2:2 or + // 4:4:4 frame cannot even be handed to an encode entry. Measured by + // calling `check`, not by reading it. + for (label, divisor) in [("4:2:2", 2usize), ("4:4:4", 1)] { + let p = Picture { + width: 64, + height: 64, + y: vec![0; 64 * 64], + u: vec![0; 64 * 64 / divisor], + v: vec![0; 64 * 64 / divisor], + }; + assert!( + p.check().is_err(), + "{NAME}: Picture::check accepted a {label}-shaped picture -- if the encoder can be \ + fed one, palette_uv_side's square map is wrong by construction" + ); + } + + // ---- arm 3: the site really fires --------------------------------- + // Without this, arms 1 and 2 are arithmetic and a source scan over a + // function no encode reaches (class `gate-blind-to-feature`). + // + // The fire count is the DECODER's thread-local one, not the writer's + // process-global `tile::take_palette_uv_hits`: that one is a + // swap-to-zero, so a parallel sibling test's encode steals this test's + // count (measured: it read `[0; 9]` under `cargo test palette`, and + // passed alone). Round-tripping the stream instead also proves the + // stronger half -- the reader took the map at the extent the WRITER + // sized, which is what makes the square value right rather than merely + // unchallenged. + let _knobs = crate::speed::knob_read(); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let before = crate::decode::palette_uv_hits(); + let encoded = encode_key_frame_with_ctx(&screen_card(192, 96), 100, 0.5, fctx).unwrap(); + let decoded = crate::stream::decode_stream(&encoded.stream) + .unwrap_or_else(|e| panic!("{NAME}: our own stream refused: {e}")); + let fired = crate::decode::palette_uv_hits() - before; + assert!( + fired > 0, + "{NAME}: no block took a chroma palette -- palette_uv_side was never exercised, so \ + this gate measures nothing" + ); + assert_eq!( + decoded[0].u, encoded.reconstruction.u, + "{NAME}: the decoder did not read the chroma map at the extent the writer sized it" + ); + assert_eq!( + decoded[0].v, encoded.reconstruction.v, + "{NAME}: the decoder did not read the chroma map at the extent the writer sized it" + ); + eprintln!("{NAME}: {fired} chroma palette block(s) round-tripped"); + } + /// The lane's keep-rule measurement: the gate's own screen capture, one /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers. /// Setting the bit forces deblocking, CDEF and loop restoration off for diff --git a/lanes/av1paletteuv.report.md b/lanes/av1paletteuv.report.md new file mode 100644 index 00000000..210c9db6 --- /dev/null +++ b/lanes/av1paletteuv.report.md @@ -0,0 +1,196 @@ +# lane/av1paletteuv — `tile.rs::palette_uv_side` + +Charter: take ONLY the first of the three unprobed hardcoded-chroma sites named in +`lanes/av1subsizesweep.report.md`. The mu-chroma square sites and the floor-`>>` +plane allocators stay named, not edited. + +## Verdict + +**ALREADY CORRECT, with the measurement — and unreachable for any other chroma +shape.** The `(side / 2).max(4)` form is libaom's 4:2:0 plane-1 block exactly, +and no reachable path can hand the writer a 4:2:2 or 4:4:4 frame. Gated +(`encode::tests::the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it`), +five mutations measured biting. No production code changed. + +## 1. What the site computes, and what it should compute at each shape + +`crates/ec-av1/src/tile.rs:5004-5006` + +```rust +pub(crate) fn palette_uv_side(side: usize) -> usize { + (side / 2).max(4) +} +``` + +Callers (all writer-side; the decoder has no counterpart call): + +| site | role | +|---|---| +| `tile.rs:4979` (`write_palette_syntax`) | sizes the chroma colour-index map actually written | +| `tile.rs:4557` (`palette_uv_bits`) | prices that same map in the mode search | +| `encode.rs:7017` (`search_chroma`) | `debug_assert_eq!(palette_uv_side(side), at.side)` | + +What libaom does — `av1_get_block_dimensions(bsize, plane, xd, ...)` +(`av1/common/blockd.h:1512`), which `av1_decode_palette_tokens` +(`av1/decoder/detokenize.c:88-98`) hands to `decode_color_map_tokens` as +`plane_width`/`plane_height`: + +```c +const int plane_block_width = block_width >> pd->subsampling_x; +const int plane_block_height = block_height >> pd->subsampling_y; +const int is_chroma_sub8_x = plane > 0 && plane_block_width < 4; +const int is_chroma_sub8_y = plane > 0 && plane_block_height < 4; +*width = plane_block_width + 2 * is_chroma_sub8_x; +*height = plane_block_height + 2 * is_chroma_sub8_y; +``` + +So the correct map extent is **per-axis**: `(block_w >> ss_x, block_h >> ss_y)`, +each then bumped by 2 if it came out under 4. For a square block the two axes +agree only when `ss_x == ss_y`: + +| shape | `ss` | correct map | `palette_uv_side` | verdict | +|---|---|---|---|---| +| 4:2:0 | (1,1) | `(side>>1, side>>1)` | `(side/2).max(4)` | **exact** | +| 4:2:2 | (1,0) | `(side>>1, side)` — NOT square | square | wrong by half the rows | +| 4:4:4 | (0,0) | `(side, side)` — NOT `side/2` | square at half size | wrong on both axes | +| 4:4:0 | (2,2) | uncodable (libaom forbids the shape outright) | — | n/a | + +Note `.max(4)` is a stand-in for libaom's `+2 * is_chroma_sub8` bump and it is +**unreachable in the writer**: `palette_bsize_ctx_wh` refuses `bw*bh < 64`, so +the smallest admitted square side is 8 and `8>>1 == 4` already. Dropping the +floor therefore changes nothing today; the gate says so explicitly rather than +letting a green floor-mutation read as coverage. + +The decoder's counterpart is already per-axis and is NOT this function: +`decode.rs:20914-20933` reads the map at `(side >> ss_x(fctx), side >> ss_y(fctx))`. +That is why 4:2:2/4:4:4 decode is byte-exact today (measurement below) while the +writer is not — the site under review is the only square one left. + +## 2. Reachability measurement — how many encodes reach it, and with what shape + +**Writer-side chroma shape census (non-test source).** Every `subsampling_*` +literal the encoder names outside its test modules: + +- `encode.rs` (`unspecified_color_config`): `{(1, 1)}` +- `encoder.rs` (`Colour::color_config`, all three `Colour` variants): `{(1, 1)}` + +`encode_key_frame_inner` — the single funnel every tile-producing entry passes +through — has **5 non-test call sites** (`encode.rs:9112, 9154, 15811`; +`encoder.rs:1825, 2001`) and every one passes one of those two 4:2:0 +constructors. Counted, not described. + +**The one public door for another shape.** `key_frame_headers_colour` +(`encode.rs:2256`) is the only public entry taking a caller-chosen +`ColorConfig` — it is how a 4:2:2 or 4:4:4 sequence header is written at all. +Its body builds HEADERS ONLY: no tile writer is reachable from it (measured by +scanning its body for `write_palette_syntax`, `write_color_index_map`, +`encode_key_frame_inner`, `tile::`). + +**The picture door.** `Picture::check` / `check_even` require +`u.len() == v.len() == width*height/4`. Measured by CALL, not by reading: a +4:2:2-shaped (`w*h/2`) and a 4:4:4-shaped (`w*h`) picture are both refused. + +**Encode count that actually fires the site** (so the above is not a source +scan over dead code): the gate's own `screen_card(192,96)` key frame codes +**9 chroma-palette blocks** (sizes `[2, 0, 7, 0, 0, 0, 0]`), all at 4:2:0. +The sibling end-to-end gate measures **9 chroma palette blocks** in its key +frame and **48** across its 4-frame GOP, all byte-exact through ffmpeg. + +**Committed fixtures / real aomenc streams at 4:2:2 and 4:4:4**: measured, and +they exercise the DECODER's per-axis path, never this writer site — they are +decode-direction fixtures. Counts, both byte-exact against aomdec: + +- `fixtures/422_palette_intra_in_inter_384x240_17f.obu` — 17 decode-order + frames, **16 chroma palette unit windows** +- `fixtures/444_lossy_palette_chroma_352x242_10b.obu` — 17 decode-order frames, + **4 windowed palette chroma units** + +Conclusion: a real 4:2:2/4:4:4 palette stream reaches `decode.rs`'s per-axis +read (and passes), and cannot reach `palette_uv_side` at all, because the only +producer of tiles in this crate is 4:2:0. + +## 3. The gate + +`crates/ec-av1/src/encode.rs`, test +`the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it`. +Three arms: + +1. **The value** — transcribes libaom's per-axis formula and asserts + `palette_uv_side(side)` equals it for every side in + `palette_bsize_ctx`'s square domain (every integer 8..=64, 57 values, not + just the powers of two). Also asserts the premise as arithmetic: for sides + 8/16/32/64 the square is NOT the 4:2:2 map and NOT the 4:4:4 map, so + "correct" cannot be misread as "correct at any shape". Then states why + `.max(4)` cannot fire in the admitted domain. +2. **Nothing can hand the writer another shape** — (a) the `subsampling_*` + census over both encoder files' non-test prefixes, (b) the + `key_frame_headers_colour` body scan, (c) the 5 non-test + `encode_key_frame_inner` call-site count, (d) `Picture::check` refusing + 4:2:2- and 4:4:4-shaped pictures by call. +3. **The site really fires** — encodes `screen_card(192,96)`, decodes it back, + asserts the decoder's thread-local chroma-palette count moved and the + round-tripped U/V match the encoder's own reconstruction. This also proves + the reader took the map at the extent the WRITER sized, which is what makes + the square value right rather than merely unchallenged. + +Counter hygiene: arm 3 deliberately reads the DECODER's thread-local +`decode::palette_uv_hits()`, not the writer's process-global +`tile::take_palette_uv_hits()` (a swap-to-zero). The first draft used the +global one and was flaky under `cargo test palette` — a parallel sibling's +encode stole the count and it read `[0; 9]`, passing alone. Measured, then +fixed; the comment in the test names it. + +## 4. Mutation proofs (gate bites) + +| # | mutation | result | +|---|---|---| +| 1 | `palette_uv_side` → `side` (halving dropped) | RED at `side 8 -- palette_uv_side disagrees with libaom's plane-1 block` | +| 2 | → `(side / 2).max(8)` (floor raised) | RED at `side 8`, same arm | +| 3 | → `4` (map size pinned) | RED at `side 10`, same arm | +| 4 | `encoder.rs` `Colour::color_config` → `subsampling (0,0)` | RED: `the non-test encoder.rs names chroma shapes {(0, 0)}` (arm 2a) | +| 5 | one `crate::tile::` line inside `key_frame_headers_colour`'s body | RED: `key_frame_headers_colour now reaches tile::` (arm 2b) | + +Each mutation was reverted immediately; the tree carries only the new test +(`git diff --stat`: 1 file, +234, all inside the test module). + +**Known non-mutation**: dropping `.max(4)` entirely leaves the gate GREEN — +correctly, since the floor is unreachable in the admitted domain (§1). Recorded +in the test body so it is not mistaken for an untested path. + +## 5. Suite runs + +- `cargo test -p ec-av1 --lib palette` — **26 passed, 0 failed** (parallel, + includes the new gate). Before the arm-3 counter fix this same run was red on + `a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly` + (counter theft, described in §3). +- `cargo test -p ec-av1 --lib screen` — **19 passed, 0 failed, 4 ignored**. +- The earlier all-palette red under `EDQUOT` was environmental (`os error 122`, + this box's `/tmp` tmpfs at its user quota); re-run with + `TMPDIR=$HOME/.cache/tmp CARGO_TARGET_DIR=$HOME/tgt-paletteuv RUSTC_WRAPPER=` + it is green, per `skill://local-edquot-rust-build-tests`. +- Full `--lib` suite: NOT completed locally — it exceeded a 3000 s timeout with + `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact` + still running (no failure reported in the visible tail). Per the project rule + that full cargo suites run on the server fleet and not locally, this lane's + verification is the scoped runs above; a full-suite run is a server job. + +## 6. Still open (named, NOT edited — out of charter) + +1. **mu-chroma sites using `chroma_side * chroma_side`** — the square + chroma-block assumption at sites other than this one. `palette_uv_side` is + the palette-map site; the mu sites are a separate family, still unprobed. +2. **Floor-`>>` chroma plane allocators** — allocators that assume a + frame-edge shape via a floor shift. Also unprobed, also untouched. +3. **The gate's own forward obligation.** If an encoder colour config that is + not 4:2:0 ever appears, arm 2a/2b red. The FIX then is not a `palette_uv_side` + tweak: `write_color_index_map` and `palette_uv_bits` both take a single + `side`, so the map writer has to become per-axis (`bw`, `bh`) the way + `decode_color_index_map_wh` already is, before any non-4:2:0 palette can be + written at all. That is a bigger change than this charter, and it is the + named unblock. + +## 7. Environment notes + +- Worktree `/home/user/wt-av1paletteuv` on `lane/av1paletteuv` (an earlier + `/tmp` worktree was moved off the tmpfs, which was at its user quota). +- Own target dir `$HOME/tgt-paletteuv`; no pushes, no merges, primary untouched. \ No newline at end of file