From 3603580b9784ce3ea1ab8e523df4d3d06e9da39d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 8 Sep 2026 03:50:58 +0300 Subject: [PATCH] fix(av1): the key frame's 64x64 intra root at a superblock the frame edge cuts The root shipped behind two guards written from a desync report that does not reproduce: the frame had to be a whole number of superblocks, and the superblock wholly inside it. The first switched the whole feature off on any arbitrary export size. Legality is now the spec's has_cols/has_rows pair, the same the inter root and the tile writer already use, and the new stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane pins Y, U and V of the reconstruction, our decoder and ffmpeg at four straddling sizes (three cut on both axes), asserting the edge fire count first. --- crates/ec-av1/src/encode.rs | 93 ++++++++++++++++++++++++------------- crates/ec-av1/src/stream.rs | 63 +++++++++++++++++++++++++ lanes/corner.report.md | 50 ++++++++++++++++++++ 3 files changed, 173 insertions(+), 33 deletions(-) create mode 100644 lanes/corner.report.md diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index bf8a102f..2b89985a 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -662,13 +662,16 @@ pub(crate) const I64_ROOT: bool = true; /// the last [`take_i64_root_hits`], so a gate reports the fire rate rather /// than assuming it (class `gate-blind-to-feature`). /// Index 1 is how many were OFFERED the trial at all, so a gate reads a -/// SHARE and not a bare count. -static I64_HITS: [std::sync::atomic::AtomicUsize; 2] = - [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; +/// SHARE and not a bare count, and index 2 how many of the whole ones sat on +/// a superblock the true frame edge CUTS THROUGH (lane-corner) -- the +/// `gate-blind-to-feature` guard for the edge path, which no +/// superblock-aligned clip fires at all. +static I64_HITS: [std::sync::atomic::AtomicUsize; 3] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; -/// The key-frame `(whole, offered)` 64x64-intra-root counts since the last -/// call, and zero them. -pub fn take_i64_root_hits() -> [usize; 2] { +/// The key-frame `(whole, offered, edge)` 64x64-intra-root counts since the +/// last call, and zero them. +pub fn take_i64_root_hits() -> [usize; 3] { std::array::from_fn(|i| I64_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) } @@ -792,10 +795,17 @@ pub fn take_b64_var_tx_hits() -> usize { /// /// Off by `EC_AV1_B64EDGE=0`. fn b64_edge() -> bool { + edge_root_enabled() && b64_root() +} + +/// What `EC_AV1_B64EDGE` names on its own, without the inter root's own +/// preset switch -- the key frame's root ([`I64_ROOT`]) reads the same flag +/// but is gated by [`i64_root`]. +fn edge_root_enabled() -> bool { static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { crate::envflags::var("EC_AV1_B64EDGE").ok().map(|v| v != "0") }); - ENV.unwrap_or(true) && b64_root() + ENV.unwrap_or(true) } /// How many 64x64 roots the frame edge cut through since the last @@ -7271,34 +7281,47 @@ pub(crate) fn encode_key_frame_inner( // BEFORE its quadrants (so both start from the same // reconstruction) and compared against the four of them below -- // the shape the inter frame's own 64 root takes - // (`search_skip_64`). Only a superblock wholly inside the true - // frame is offered it: the writer's `Superblock::Whole` arm - // refuses one the edge cuts through, and a frame that allows - // intrabc is refused outright ([`I64_ROOT`]) because the quadrant - // searches below carry DV state a discarded trial would desync. + // (`search_skip_64`). A frame that allows intrabc is refused + // outright ([`I64_ROOT`]) because the quadrant searches below + // carry DV state a discarded trial would desync. let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK); - // corner-cut, ceiling named: only a frame whose true size is a - // WHOLE number of superblocks is offered the root at all. - // MEASURED (lane-i64): on a 248x152 frame -- whose bottom-right - // superblock is cut on BOTH axes -- a frame carrying whole 64 - // roots elsewhere desyncs that corner's CHROMA three ways (our - // writer's reconstruction, our decoder and ffmpeg all disagree, - // luma stays exact), i.e. a defect in the whole-64 chroma - // neighbour publication that only the doubly-cut tail block - // reads (class `last-block-desync-reads-as-reconstruction`). - // Every clip on the BD gates, and every real film/screen source, - // is superblock aligned, so nothing measured is withheld. - // Ceiling: trace the corner block's chroma `txb_skip`/dc context - // against aomdec and lift this line. - let aligned = header.mi_cols % crate::tile::SB_MI == 0 - && header.mi_rows % crate::tile::SB_MI == 0; + // lane-corner LIFTED the two guards this root shipped with: the + // frame no longer has to be a whole number of superblocks, and + // the superblock no longer has to be wholly inside the frame. + // The desync the guards were written for (a 248x152 corner's + // chroma disagreeing three ways) does NOT reproduce at this + // revision -- see + // `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`, + // which pins all three planes of the encoder's reconstruction, + // our decoder and ffmpeg on four straddling sizes, three of them + // cut on BOTH axes, with the edge fire count asserted. What the + // guards cost was every key-frame root on an arbitrary export + // size (the `aligned` line switched the whole feature off on, for + // instance, a 1920x792 frame). + let whole_inside = x64 + SUPERBLOCK <= luma.true_width + && y64 + SUPERBLOCK <= luma.true_height; + // lane-corner: and the superblock the true frame edge CUTS + // THROUGH with more than half of each axis still inside, which is + // all AV1 asks of a `PARTITION_NONE` root (spec + // `decode_partition`'s `has_cols`/`has_rows`, the same pair the + // key writer's `Superblock::Whole` arm checks) -- the shape the + // inter root already takes ([`b64_edge`]). + let edge_inside = edge_root_enabled() + && crate::tile::has_half( + sb_col as u32 * crate::tile::SB_MI, + crate::tile::SB_MI, + header.mi_cols, + ) + && crate::tile::has_half( + sb_row as u32 * crate::tile::SB_MI, + crate::tile::SB_MI, + header.mi_rows, + ); let sb64_legal = i64_root() - && aligned && ibc.is_none() && sb_row * 2 + 1 < rows && sb_col * 2 + 1 < cols - && x64 + SUPERBLOCK <= luma.true_width - && y64 + SUPERBLOCK <= luma.true_height; + && (whole_inside || edge_inside); let mut sb64: Option<(f64, BlockCoeffs, [(Vec, Vec); 3])> = None; if sb64_legal { I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -7509,6 +7532,9 @@ pub(crate) fn encode_key_frame_inner( left_mode[sb_row * 4 + cell] = block.mode; } I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if !whole_inside { + I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } let mode = block.mode; coded.push((index, Superblock::Whole(block), vec![mode])); } @@ -12088,7 +12114,7 @@ mod tests { } let _ = take_i64_root_hits(); let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap(); - let [roots, _offered] = take_i64_root_hits(); + let [roots, _offered, _edge] = take_i64_root_hits(); // The counters are process-global, so another test encoding in // parallel can only ADD to them -- the per-FRAME fact is the mode // list, which carries one entry per coded block and so exactly 12 @@ -16604,9 +16630,10 @@ mod tests { // reference (class `gate-blind-to-feature`). // lane-i64: the KEY frame's own 64x64 intra root -- how many of // the superblocks offered the trial were coded whole. - let [i64_whole, i64_offered] = take_i64_root_hits(); + let [i64_whole, i64_offered, i64_edge] = take_i64_root_hits(); eprintln!( - "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%)", + "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%), \ + {i64_edge} on a superblock the frame edge cuts", 100.0 * i64_whole as f64 / i64_offered.max(1) as f64, ); eprintln!( diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 58a1a072..0f11ae66 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -3450,6 +3450,69 @@ pub(crate) mod tests { ); } + /// lane-corner: sizes whose LAST superblock is cut by the true frame + /// edge on BOTH axes with more than half of each still inside -- so + /// `has_cols` and `has_rows` are both true and the spec lets that + /// superblock stay a whole 64x64 `PARTITION_NONE` block, which this + /// encoder's roots take (`EC_AV1_B64EDGE` on the inter side, the key + /// frame's own `Superblock::Whole`). The sibling luma-only test + /// (`encoder.rs`'s `a_non_superblock_aligned_clip_...`) is blind to + /// chroma (class `metric-blind-to-a-plane`), so this one compares all + /// three planes three ways: our decoder, the encoder's own + /// reconstruction, and ffmpeg. + #[test] + fn a_doubly_cut_superblock_root_round_trips_in_every_plane() { + let fctx = &crate::decode::FrameCtx::new(); + if !have_ffmpeg() { + eprintln!("SKIP a_doubly_cut_superblock_root_round_trips_in_every_plane: no ffmpeg"); + return; + } + const FRAMES: usize = 4; + // Each size leaves MORE than half of its last superblock row (and, + // but for 200x120's 8-px column, of its last column) inside, which is + // what makes the root legal there at all; 248x168/232x168/248x184 are + // cut on BOTH axes at once. 1920x1080 -- the user's own export shape + // -- is the same case: 1080 = 16*64 + 56, a 56-px bottom straddle. + for &(width, height) in &[(248usize, 168usize), (232, 168), (200, 120), (248, 184)] { + let pictures: Vec<_> = (0..FRAMES as i64) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let _ = crate::encode::take_b64_edge_hits(); + let _ = crate::encode::take_i64_root_hits(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) + .unwrap_or_else(|e| panic!("{width}x{height}: encoder refused: {e}")); + let edges = crate::encode::take_b64_edge_hits(); + let [i64_whole, i64_offered, i64_edge] = crate::encode::take_i64_root_hits(); + eprintln!( + "{width}x{height}: edge inter 64 roots {edges}, key 64 roots {i64_whole} of \ + {i64_offered} offered, {i64_edge} of them cut by the frame edge" + ); + // gate-blind-to-feature: without this the three-way compare below + // passes on a stream that never coded a whole root at the cut + // superblock at all. + assert!( + i64_edge > 0, + "{width}x{height}: no 64x64 root sat on a superblock the frame edge cuts" + ); + let decoded = decode_stream(&encoded.stream) + .unwrap_or_else(|e| panic!("{width}x{height}: our decoder refused: {e}")); + let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, FRAMES); + assert_eq!(ffmpeg_frames.len(), FRAMES, "{width}x{height}: ffmpeg frame count"); + assert_eq!(decoded.len(), FRAMES, "{width}x{height}: frame count"); + for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma: ours vs ffmpeg"); + assert_eq!(got.u, want.u, "{width}x{height} frame {i} U: ours vs ffmpeg"); + assert_eq!(got.v, want.v, "{width}x{height} frame {i} V: ours vs ffmpeg"); + } + for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() { + let rec = &frame.reconstruction; + assert_eq!(rec.y, want.y, "{width}x{height} frame {i} luma: recon vs ffmpeg"); + assert_eq!(rec.u, want.u, "{width}x{height} frame {i} U: recon vs ffmpeg"); + assert_eq!(rec.v, want.v, "{width}x{height} frame {i} V: recon vs ffmpeg"); + } + } + } + /// A hand-built 3-frame stream that actually fires `GOLDEN_FRAME` /// through [`decode_stream`], proving the round-4 flip (`decode.rs`'s /// `decode_inter_block` `GOLDEN_FRAME` arm) the way 120+ real aomenc diff --git a/lanes/corner.report.md b/lanes/corner.report.md new file mode 100644 index 00000000..43b9ed90 --- /dev/null +++ b/lanes/corner.report.md @@ -0,0 +1,50 @@ +# lane-corner — the whole-64 root at a superblock the frame edge cuts + +## Verdict on the chartered defect: STALE PREMISE, not reproducible + +The debt says a whole-64 root on a doubly-cut superblock desyncs chroma three +ways at 248x152. At `main` f6c67770 it does not, for two separate reasons: + +1. **248x152 cannot carry the block at all.** Its bottom-right superblock has + 24 px of 64 inside vertically, so spec `decode_partition`'s `has_rows` + (`MiRow + halfBlock4x4 < MiRows`: 32+8=40 vs MiRows 38) is FALSE and + `PARTITION_NONE` is not even a legal symbol there — the writer's + `Superblock::Whole` arm refuses it (`tile.rs:2919`). The chartered repro + (`a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg` with the + `aligned` guard removed) is GREEN because no edge root ever fires in it: + its sizes top out at height 152, and the key root's own + `x64 + SUPERBLOCK <= true_width` bound kept it to wholly-inside + superblocks anyway (class `gate-blind-to-feature`). +2. **Where the block IS legal, all three sides agree.** Sizes whose last + superblock keeps more than half of each axis inside (248x168, 232x168, + 248x184 — cut on BOTH axes — and 200x120) round-trip byte-exact in Y, U + and V across the encoder's own reconstruction, our decoder and ffmpeg, + over a 4-frame GOP. + +## What shipped + +* `encode.rs` `encode_key_frame_inner`: both guards lifted. The root's + legality is now the spec's — `whole_inside || edge_inside`, where + `edge_inside` is `has_half` on both axes — the same shape the inter root + has had since lane-b64b. The `EC_AV1_B64EDGE` switch is now readable + without the inter root's preset flag (`edge_root_enabled`), so `=0` + restores the old behaviour on both roots. +* `I64_HITS` grew a third slot: whole roots that sat on a cut superblock. + `take_i64_root_hits` returns `[whole, offered, edge]`, and the native gate + prints the edge share (class `gate-blind-to-feature`). +* `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`: + the three-way, three-PLANE pin at four straddling sizes, asserting the edge + fire count first. Its sibling + `encoder.rs::a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact` + compares LUMA only (class `metric-blind-to-a-plane`), which is why the + chroma claim in the debt was never actually gated either way. + +## Sweep + +`aligned`-style whole-frame refusals: `grep -rn "SB_MI == 0" crates/ec-av1/src` +returns no other site — this was the only frame-alignment guard. The encoder +writes 64x64 superblocks only, so there is no whole-128 chroma path to sweep. + +## Measurements + +(filled in below as the arms land)