diff --git a/crates/ec-av1/fixtures/reelb_head_key_frame.obu b/crates/ec-av1/fixtures/reelb_head_key_frame.obu new file mode 100644 index 0000000000000000000000000000000000000000..ecc409b000d6550743e1c768e075b23186e41c08 GIT binary patch literal 147 zcmV;E0Brvf016KP003g^zw$Zv^PwUEDS#>l0R!g%dVne#0_gYEq$Xw$Tu=>E zIRFFb000000)R4F5CDe&fB*mh03grHo2NmWeoqO5rDriCF8GQw;s}Qn usize { HORZ_VERT_INTRA_HITS.with(|c| c.get()) } +// How many blocks were decoded as a frame-edge rect strip -- the single +// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge +// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose +// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter +// paths share the counter. +thread_local! { + static EDGE_RECT_STRIP_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`EDGE_RECT_STRIP_HITS`]. +pub(crate) fn edge_rect_strip_hits() -> usize { + EDGE_RECT_STRIP_HITS.with(|c| c.get()) +} + // How many HORZ/VERT intra strips resolved a SPLIT luma transform // (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) -- // the case every rect path here refused by name before, and the first @@ -11801,16 +11816,31 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } p } else { + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit is the answer, not a formality -- libaom's + // `ec_read_partition_impl` returns `PARTITION_HORZ` (resp. + // `PARTITION_VERT`) when it reads 0, and only `PARTITION_SPLIT` + // when it reads 1. Forcing SPLIT here desynced the last + // superblock row of every frame whose height is not a multiple + // of 64 -- the ReelB head (3840x1608) diverges at + // mi_row=400 mi_col=0, the first block of that row. match (has_cols, has_rows) { (true, false) => { - dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE)); + if dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_HORZ + } } (false, true) => { - dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE)); + if dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_VERT + } } - _ => {} + _ => PARTITION_SPLIT, } - PARTITION_SPLIT }; match part { PARTITION_NONE => { @@ -11867,20 +11897,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } else { match (has_cols32, has_rows32) { (true, false) => { - dec.symbol_fixed(&gather( - &cdfs.partition_w32[ctx32], - VERT_ALIKE, - )); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_HORZ + } } (false, true) => { - dec.symbol_fixed(&gather( - &cdfs.partition_w32[ctx32], - HORZ_ALIKE, - )); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_VERT + } } - _ => {} + _ => PARTITION_SPLIT, } - PARTITION_SPLIT }; match part32 { PARTITION_NONE => { @@ -12319,16 +12356,63 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( does not code yet", )); } - if has_cols16 { + // lane-golomb r1 (class + // `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 names + // PARTITION_HORZ (resp. VERT), only 1 is + // SPLIT (libaom `ec_read_partition_impl`). + // This path can only walk the four SPLIT + // leaves, so a 0 refuses by name instead + // of desyncing. + let edge_split = if has_cols16 { dec.symbol_fixed(&gather( &cdfs.partition_w16[ctx16], VERT_ALIKE, - )); + )) } else { dec.symbol_fixed(&gather( &cdfs.partition_w16[ctx16], HORZ_ALIKE, - )); + )) + }; + if edge_split == 0 { + // lane-oddh r1: the strip IS decodable + // -- libaom's `decode_partition` codes + // only the FIRST half of an edge + // HORZ/VERT (the second call is + // guarded by the same has_rows/ + // has_cols test that made the + // partition non-square), so one + // 16x8 (resp. 8x16) strip covers the + // whole visible band of a frame whose + // height (resp. width) is 8 mod 16 -- + // the user's 3840x1608 film. + HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1)); + EDGE_RECT_STRIP_HITS.with(|c| c.set(c.get() + 1)); + let (mi_row0, mi_col0) = + (sr as u32 * SUB_MI, sc as u32 * SUB_MI); + let (bw, bh) = if has_cols16 { (16, 8) } else { (8, 16) }; + let mode = decode_leaf_rect( + &mut dec, + &mut cdfs, + &mut neighbours, + at16, + (mi_row0 as usize, mi_col0 as usize), + bw, + bh, + None, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + reduced_tx_set, + )?; + neighbours.above_mode[sc] = mode; + neighbours.left_mode[sr] = mode; + continue; } let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI); @@ -12878,22 +12962,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( tx_select, reduced_tx_set, )?; - decode_block_rect64( - &mut dec, - &mut cdfs, - &mut neighbours, - (at.0 + 2, at.1), - 64, - 32, - &mut y, - &mut u, - &mut v, - enable_filter_intra, - allow_screen_content_tools, - base_q_idx, - tx_select, - reduced_tx_set, - )?; + // lane-golomb r1: at the frame edge only the first half of the + // strip is coded (libaom `decode_partition` guards the second + // with the same has_rows test that made this partition non-square). + if has_rows { + decode_block_rect64( + &mut dec, + &mut cdfs, + &mut neighbours, + (at.0 + 2, at.1), + 64, + 32, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + reduced_tx_set, + )?; + } } PARTITION_VERT => { // lane-sbpart r2: mirror of PARTITION_HORZ above with @@ -12914,22 +13003,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( tx_select, reduced_tx_set, )?; - decode_block_rect64( - &mut dec, - &mut cdfs, - &mut neighbours, - (at.0, at.1 + 2), - 32, - 64, - &mut y, - &mut u, - &mut v, - enable_filter_intra, - allow_screen_content_tools, - base_q_idx, - tx_select, - reduced_tx_set, - )?; + // lane-golomb r1: at the frame edge only the first half of the + // strip is coded (libaom `decode_partition` guards the second + // with the same has_cols test that made this partition non-square). + if has_cols { + decode_block_rect64( + &mut dec, + &mut cdfs, + &mut neighbours, + (at.0, at.1 + 2), + 32, + 64, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + reduced_tx_set, + )?; + } } PARTITION_HORZ_A | PARTITION_HORZ_B | PARTITION_VERT_A | PARTITION_VERT_B => { // lane-part32 r4: the four superblock-level AB arms, each @@ -19271,12 +19365,24 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( p } (true, false) => { - dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)); - PARTITION_SPLIT + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_HORZ + } } (false, true) => { - dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)); - PARTITION_SPLIT + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_VERT + } } (false, false) => PARTITION_SPLIT, }; @@ -19444,14 +19550,27 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( } else { match (has_cols32, has_rows32) { (true, false) => { - dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE)); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_HORZ + } } (false, true) => { - dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE)); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_VERT + } } - _ => {} + _ => PARTITION_SPLIT, } - PARTITION_SPLIT }; match part32 { PARTITION_NONE => { @@ -19543,17 +19662,24 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( p } else { if has_cols16 { - dec.symbol_fixed(&gather( - &cdfs.partition_w16[ctx16], - VERT_ALIKE, - )); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w16[ctx16], VERT_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_HORZ + } } else { - dec.symbol_fixed(&gather( - &cdfs.partition_w16[ctx16], - HORZ_ALIKE, - )); + // lane-golomb r1 (class `parsed-then-discarded`): the gathered + // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT + // (libaom `ec_read_partition_impl`). + if dec.symbol_fixed(&gather(&cdfs.partition_w16[ctx16], HORZ_ALIKE)) == 1 { + PARTITION_SPLIT + } else { + PARTITION_VERT + } } - PARTITION_SPLIT }; if part16 == PARTITION_NONE { decode_inter_block( diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 1365c428..bf3c9423 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -50,6 +50,7 @@ const REFUSALS: &[&str] = &[ "a sub-8x8 leaf that uses intrabc (this reader has no block-vector path; the 8x8-and-up reader reconstructs one)", "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)", "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)", + "a sequence using 128x128 superblocks on a frame larger than 64x64 (this decoder's whole partition/CDEF/LR grid is 64x64-superblock only; aomenc picks 128x128 at --cpu-used=0)", "a frame OBU with no tile group", "a frame naming primary_ref_frame at a reference slot with no saved CDF state", "a frame with no mode-info grid", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 24abde9b..e7909945 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -525,6 +525,37 @@ pub fn decode_stream(data: &[u8]) -> Result> { "a bit depth of 12 (this decoder is gated at 8 and 10 only: warp/MC/wiener rounding shifts change at 12-bit and no 12-bit gate exists)", )); } + // lane-oddh r2: `use_128x128_superblock` reaches every level of the + // decode -- the partition tree starts at BLOCK_128X128, `SB_MI` is 32 + // mi units, and the CDEF/LR/deblock grids are per-128 -- and this + // decoder is written for 64x64 superblocks throughout (`SB_MI = 16`, + // no BLOCK_128X128 partition read at all). Until r1 that was SILENT: + // a 64x72 aomenc key frame at `--cpu-used=0` (libaom picks 128x128 + // whenever speed is 0, `av1_select_sb_size`) desynced at the very + // first symbol -- aomdec reads a gathered 2-symbol + // BLOCK_128X128 partition (has_cols false at mi_cols=16, + // has_rows true at mi_rows=18) where we read a 10-symbol + // BLOCK_64X64 one from the same byte, giving PARTITION_VERT_4 (9) + // against SPLIT (3). Refuse by name rather than decode wrong pixels. + // + // Scoped, not blanket (measured: a blanket refusal red-lined 29 + // previously pixel-exact gates): on a frame of at most 64x64 a + // 128x128 superblock decodes IDENTICALLY to a 64x64 one -- mi (0,0) + // has neither `has_rows` nor `has_cols`, so BLOCK_128X128 is a forced + // SPLIT that reads no symbol, and only one of its four 64x64 children + // is inside the frame. Every sibling inter gate at 64x64 and + // `--cpu-used=0` is exactly that case. The divergence starts the + // moment a superblock has a second child in frame. + if parser + .sequence_header() + .is_some_and(|seq| seq.use_128x128_superblock) + && (header.mi_cols > 16 || header.mi_rows > 16) + { + return Err(Error::unsupported( + "AV1 decode_stream", + "a sequence using 128x128 superblocks on a frame larger than 64x64 (this decoder's whole partition/CDEF/LR grid is 64x64-superblock only; aomenc picks 128x128 at --cpu-used=0)", + )); + } crate::decode::set_bit_depth(bit_depth); // lane-av1comp: `comp_group_idx`/`compound_idx`'s own gating bits. let enable_masked_compound = parser @@ -936,6 +967,209 @@ mod tests { ); } + /// lane-oddh r2 GATE: the frame-edge half-strip arms r1 added (a 64x32 / + /// 32x64 superblock-level or 16x8 / 8x16 16-level INTER block where the + /// frame's true edge cuts the strip in half) actually fire and decode + /// pixel-exact, at both bit depths. 160 = two full superblock rows plus + /// 32 pixels, so every superblock in the last row is a half strip; without + /// r1's arms these attempts refused outright, which is why this gate + /// asserts a nonzero `edge_rect_strip_hits` DELTA on attempts that were + /// actually compared -- a refused attempt's hits would prove nothing + /// (class "counter from refused stream"). + #[test] + #[ignore = "2026-09-02 lane-oddh r2: no aomenc recipe reaches the INTER edge half-strip arm yet -- rect partitions OFF makes the encoder answer the forced gathered edge symbol SPLIT every time (both bit depths decode 192x160 pixel-exact, edge_rect_strip_hits=0), and rect ON stops at three other lanes' gaps first: at cq 40 'a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding', at cq 62 'an INTER 32x32 partition type this decoder does not code (value=8/9)' (HORZ_4/VERT_4 even with --enable-1to4-partitions=0), and at min-partition 16 'a HORZ/VERT intra strip below 16x16 with a split transform'. The KEY-frame half of the same edge is gated: the tiny size sweep now covers 64x72/72x64/64x136/136x64/192x136"] + fn a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() || !have_aomenc() { + eprintln!("SKIP {NAME}: no ffmpeg/aomenc"); + return; + } + let (width, height, frames) = (192usize, 160usize, 6usize); + let mut compared = 0u32; + let mut strip_hits = 0usize; + let mut refused = 0u32; + for bit_depth in [8u32, 10u32] { + let duration = frames as f64 / 25.0; + let source = format!("testsrc2=size={width}x{height}:duration={duration}:rate=25"); + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=62", + // cpu-used >= 1 keeps libaom on 64x64 superblocks at this + // size (`av1_select_sb_size`: speed >= 1 and <= 480p). + "--cpu-used=4", "--threads=1", "--row-mt=0", "--kf-max-dist=1000", + &depth_arg, &input_depth_arg, + // The tool set every sibling inter gate pins; the edge + // strip itself needs rect partitions left ON. + "--enable-warped-motion=0", "--enable-obmc=0", "--enable-masked-comp=0", + "--enable-interintra-comp=0", "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", "--enable-smooth-interintra=0", + // Rect partitions stay ON: the edge strip is a FORCED + // (gathered) HORZ at the boundary, but with rect coding + // off the encoder answers that gathered symbol SPLIT every + // time and the arm never fires (measured, r2). + "--enable-ab-partitions=0", "--enable-1to4-partitions=0", + "--enable-palette=0", "--enable-intrabc=0", "--enable-cdef=0", + "--enable-restoration=0", "--enable-ref-frame-mvs=0", + "--enable-tx-size-search=0", "--enable-filter-intra=0", + "--enable-smooth-intra=0", "--enable-paeth-intra=0", + "--enable-directional-intra=0", "--enable-angle-delta=0", + "--enable-cfl-intra=0", + // 16 is the smallest leaf this decoder codes rect strips + // at; below it the sub-16 strip/1:4 refusals fire first + // and the gate never reaches the edge arm. + // 160 = two full superblock rows plus 32, so the forced + // HORZ at the last row is a 64x32 -- the superblock-level + // arm -- and a 32 floor keeps the run out of the sub-16 + // rect-strip gap another lane owns. + "--min-partition-size=32", "--max-partition-size=64", + "--obu", "-o", "-", "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("write y4m"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!(out.status.success(), "aomenc refused: {}", String::from_utf8_lossy(&out.stderr)); + let stream = out.stdout; + + let before = crate::decode::edge_rect_strip_hits(); + let decoded = match decode_stream(&stream) { + Ok(f) => f, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME}: {bit_depth}-bit failed outright, not a named refusal: {msg}" + ); + eprintln!("{NAME}: {bit_depth}-bit REFUSED {msg}"); + refused += 1; + continue; + } + }; + let reference = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frames) + } else { + ffmpeg_decode_sequence(&stream, width, height, frames) + }; + assert_eq!( + decoded.len(), + reference.len(), + "{NAME}: {bit_depth}-bit frame count" + ); + for (i, (ours, theirs)) in decoded.iter().zip(&reference).enumerate() { + let nd = |a: &[u16], b: &[u16]| a.iter().zip(b).filter(|(x, y)| x != y).count(); + assert_eq!( + (nd(&ours.y, &theirs.y), nd(&ours.u, &theirs.u), nd(&ours.v, &theirs.v)), + (0, 0, 0), + "{NAME}: {bit_depth}-bit frame {i} differs from ffmpeg" + ); + } + compared += 1; + strip_hits += crate::decode::edge_rect_strip_hits() - before; + } + assert!(compared > 0, "{NAME}: every attempt refused ({refused}) -- gate proved nothing"); + assert!( + strip_hits > 0, + "{NAME}: {compared} attempts decoded pixel-exact but not one frame-edge half strip \ + fired -- the recipe no longer reaches the arm this gate exists for" + ); + eprintln!("{NAME}: {compared} attempts pixel-exact, edge_rect_strip_hits={strip_hits}, {refused} refusals"); + } + + /// lane-oddh r2 GATE: a REAL aomenc stream that uses 128x128 superblocks + /// is refused by name, not silently mis-decoded. This is the root cause of + /// r1's pinned 64x72 first-symbol desync: libaom's `av1_select_sb_size` + /// returns BLOCK_128X128 whenever speed is 0, so a tiny frame encoded at + /// `--cpu-used=0` carries 128x128 superblocks, and this 64x64-only + /// decoder read a 10-symbol BLOCK_64X64 partition (value 9, VERT_4) where + /// aomdec read a gathered 2-symbol BLOCK_128X128 one (value 3, SPLIT) from + /// the same byte -- the uncompressed header parse was byte-identical + /// (49 bits, tile data at file offset 20; hand-verified against spec + /// 5.9.2 field by field). + /// + /// The `use_128x128_superblock` assert is the "knob reached the tool" + /// half: without it, an aomenc that ignored `--sb-size=128` would leave + /// the gate asserting a refusal that never fires. + #[test] + fn a_real_aomenc_128x128_superblock_stream_is_refused_by_name() { + if !have_ffmpeg() || !have_aomenc() { + eprintln!("SKIP: no ffmpeg/aomenc"); + return; + } + let (width, height) = (64usize, 72usize); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", + "mandelbrot=size=64x72:rate=25:start_x=-0.6:start_y=-0.4", "-t", "0.04", + "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!(y4m.status.success(), "ffmpeg fixture: {}", String::from_utf8_lossy(&y4m.stderr)); + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32", + "--cpu-used=0", "--sb-size=128", "--kf-max-dist=0", "--limit=1", + "--threads=1", "--row-mt=0", "--obu", "-o", "-", "-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child.stdin.take().expect("aomenc stdin").write_all(&y4m.stdout).expect("write y4m"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!(out.status.success(), "aomenc refused: {}", String::from_utf8_lossy(&out.stderr)); + let stream = out.stdout; + + // The knob actually arrived: this stream's sequence header codes + // `use_128x128_superblock = 1`. + let mut parser = Av1Parser::new(); + let mut pos = 0usize; + let mut sb128 = false; + while pos < stream.len() { + let Ok(obu) = parser.parse_obu(&stream[pos..]) else { + break; + }; + pos += obu.total_size.max(1); + if let Some(seq) = parser.sequence_header() { + sb128 = seq.use_128x128_superblock; + break; + } + } + assert!(sb128, "aomenc ignored --sb-size=128: this stream is 64x64-superblock"); + + let err = decode_stream(&stream).unwrap_err().to_string(); + assert!( + err.contains("a sequence using 128x128 superblocks"), + "expected the 128x128-superblock refusal for {width}x{height}, got: {err}" + ); + } + /// `decode_stream` on a lone key frame's stream matches both the tile /// path (`decode_key_frame_tile` called directly on `Encoded::tile`) and /// the encoder's own reconstruction, at an even and an odd size. @@ -2703,6 +2937,41 @@ mod tests { eprintln!("{NAME}: pixel-exact, grain_hits={}", crate::film_grain::grain_hits()); } + /// lane-golomb r1: THE FILM ITSELF. `crates/ec-av1/fixtures/reelb_head_key_frame.obu` + /// is the first frame of the user's ReelB AV1 release (3840x1608 + /// yuv420p10le, `ffmpeg -i -c copy -frames:v 1 -f obu`, 147 bytes) -- + /// a real 10-bit key frame whose height is NOT a multiple of the 64-pixel + /// superblock, so its last superblock row (mi_row=400 of 402) carries the + /// edge partition symbol this lane fixed: libaom's `ec_read_partition_impl` + /// returns `PARTITION_HORZ` when the gathered `split_or_horz` bit is 0, and + /// this decoder used to READ that bit and throw it away, forcing SPLIT + /// (class `parsed-then-discarded`). The desync surfaced two rows later as + /// "a Golomb tail longer than this decoder reads" -- a refusal naming the + /// symptom, never the cause. + #[test] + fn the_reelb_head_key_frame_decodes_pixel_exact() { + const NAME: &str = "the_reelb_head_key_frame_decodes_pixel_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures/reelb_head_key_frame.obu"); + let stream = std::fs::read(&path) + .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); + let (width, height) = (3840usize, 1608usize); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => panic!("{NAME}: decode_stream refused: {e}"), + }; + assert_eq!(frames.len(), 1, "{NAME}: one key frame"); + assert_eq!((frames[0].width, frames[0].height), (width, height)); + let ffmpeg_frames = ffmpeg_decode_sequence_10bit(&stream, width, height, 1); + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); + } + /// lane-hbd10 r1: a real `aomenc --bit-depth=10 --superres-mode=1 /// --superres-denominator=12` key frame, decoded pixel-exact against /// ffmpeg's own 10-bit decode. Proves `superres::upscale_row`'s @@ -13165,8 +13434,26 @@ mod tests { eprintln!("SKIP: no ffmpeg/aomenc"); return; } - let sizes: &[(usize, usize)] = - &[(8, 8), (16, 16), (32, 32), (16, 32), (32, 16), (64, 64), (48, 48), (24, 24)]; + // lane-oddh r2: the second half of this list is the odd-height / + // odd-width ladder -- frame sizes whose last superblock row or column + // is a partial 64 (72 = one full SB plus 8 rows, 136 = two plus 8), + // which is where the frame-edge half-strip path r1 added is the only + // way to code the edge. 192x136 is the inter-sized member. + let sizes: &[(usize, usize)] = &[ + (8, 8), + (16, 16), + (32, 32), + (16, 32), + (32, 16), + (64, 64), + (48, 48), + (24, 24), + (64, 72), + (72, 64), + (64, 136), + (136, 64), + (192, 136), + ]; let mut total_exact = 0u32; for &(width, height) in sizes { let mut ok = 0u32; @@ -13284,12 +13571,12 @@ mod tests { } // Hit counter: the sweep proved nothing unless every size x seed // attempt really ran end to end (aomenc -> us -> ffmpeg compare). - // Floor (hit counter): 7 of the 8 sizes must decode all 10 seeds + // Floor (hit counter): 12 of the 13 sizes must decode all 10 seeds // pixel-exact -- only 8x8 is allowed to refuse outright today. If a // future change makes sizes refuse instead of decode, this fails // rather than passing on refusals alone. assert!( - total_exact >= 70, + total_exact >= 120, "tiny sweep only reached {total_exact} pixel-exact attempts (floor 70) -- \ refusals cannot substitute for decodes" ); diff --git a/lanes/golomb-r1.report.md b/lanes/golomb-r1.report.md new file mode 100644 index 00000000..484257cb --- /dev/null +++ b/lanes/golomb-r1.report.md @@ -0,0 +1,47 @@ +# lane-golomb r1 — the edge partition bit was read and thrown away + +## Verdict +The "a Golomb tail longer than this decoder reads" refusal on the ReelB head was, as +suspected (`refusal-from-own-desync`), a symptom. Root cause: at a frame edge the partition +symbol is a single *gathered* bit, and this decoder read it and **discarded** it, always +inferring `PARTITION_SPLIT`. libaom `ec_read_partition_impl` (decodeframe.c:1255): +`!has_rows && has_cols` → `read ? PARTITION_SPLIT : PARTITION_HORZ`; the mirror case → +`PARTITION_VERT`. Class: `parsed-then-discarded`. + +Charter STEP-2 fallback ("libaom read_golomb caps at 32 bits, extend the reader") is FALSE: +`~/.cache/aom-oracle/src/av1/decoder/decodetxb.c:22` aborts the frame at `length > 20`, exactly +our cap. The cap was never the bug and is unchanged. + +## First divergent element (EVIDENCE) +EVIDENCE: /tmp/.../scratchpad/{ao-all.txt,ours-all.txt} | instrumented aomdec vs decode_probe, +EC_TRACE_MODE+EC_TRACE_MODE_STEP+EC_TRACE_COEFF on the 2-frame extract f2.obu, ladders aligned +element by element on msac RANGE | first diff at element 12053: key frame, **mi_row=400 +mi_col=0** (last, 8-pixel-tall superblock row of a 1608-tall frame), `name=skip` +oracle rng=34753 vs ours rng=43258. Oracle codes that superblock as one `BLOCK_64X32` +(`EC_IMODE ... bsize=11`, PARTITION_HORZ); we forced SPLIT and descended to 16x16. +After the fix the range ladder is element-exact for all 13712 shared elements of the key frame +(EVIDENCE: /tmp/.../scratchpad/{a4.n,o4.n} | awk first-diff | idx 13713, inside a later INTER +frame, i.e. past the whole key frame). + +## Fix +`crates/ec-av1/src/decode.rs` — every edge-partition site, both tile paths, all three levels +(64/32/16, intra and inter): the gathered bit now names HORZ/VERT vs SPLIT. The 64-level +HORZ/VERT arms only decode the second half when it is inside the frame (`has_rows`/`has_cols`), +mirroring libaom `decode_partition`. The intra 16x16 edge site can only walk four SPLIT leaves, +so a 0 bit refuses by name there (new string, listed in `refusal_inventory.rs`) instead of +desyncing. + +## Gates +- NEW `stream::tests::the_reelb_head_key_frame_decodes_pixel_exact` — the film itself: + `crates/ec-av1/fixtures/reelb_head_key_frame.obu` (147 B, first frame of his 3840x1608 + yuv420p10le release) decodes and matches `ffmpeg -pix_fmt yuv420p10le` on Y, U and V. + EVIDENCE: cargo test -p ec-av1 --lib -- the_reelb_head_key_frame | 1 passed | + Y/U/V all equal to ffmpeg's decode, 3840x1608. +- Full lib suite: `$HOME/.cache/golomb-suite.log` — **337 passed / 0 failed / 31 ignored**. + +## Film probes after the fix +- `hg-head.obu` (18 frames): key frame + first inter frames now entropy-exact; stops at + "an inter SB-level partition type other than NONE or SPLIT" — the same edge partition, now + correctly decoded as HORZ, on an INTER superblock row the inter path cannot code (rect inter + residual coding does not exist here). Next lane. +- `reelb5.obu`: "a 32x32-level 1:4 strip with a split transform (depth=2)" (unchanged by this lane). diff --git a/lanes/oddh-r1.report.md b/lanes/oddh-r1.report.md new file mode 100644 index 00000000..e3913c71 --- /dev/null +++ b/lanes/oddh-r1.report.md @@ -0,0 +1,76 @@ +# lane-oddh r1 — frames whose height/width is 8 mod 16 + +Branch `lane-oddh` off main `b1d8457`. Target: the user's ReelB film shape +(3840x1608, `1608 % 16 == 8`), where every inter attempt derailed. + +## What the round established (measured, not reasoned) + +1. **The charter's premise is stale in its blame, right in its shape.** The refusal + `"a non-DC chroma mode on an 8x8 inter-frame leaf"` is NOT what odd-height frames + stop at once lane-golomb's edge-partition fix is present. Cherry-picking + `eacd7fd` (clean, no conflicts) moves 192x136 to the same refusal its + *even-height control* 192x128 hits, i.e. that one is width/content-related, not + odd-height (see 4). + +2. **Minimal repro is 64x72, not 192x136.** With the standard inter-gate recipe + (`--enable-rect-partitions=0 --min/max-partition-size=8/16`, mandelbrot, cq 40): + - `64x64` decodes 4/4 frames pixel-exact (control), + - `64x72` (bottom band 8 px) stopped at the key-frame 16-level edge refusal, + - `72x64` (right band 8 px) stops in the inter tile path. + +3. **The real blocker underneath is a first-symbol desync of the KEY tile at + height 72.** Not an edge-band defect at all: the *first* partition symbol of the + frame diverges. + `EVIDENCE: /tmp/.../scratchpad/k-64x72.obu (667 B, key frame only, aomenc cq40) | EC_AV1_TRACE=1 decode_probe vs EC_TRACE=1 aomdec | first element mi=(0,0) bsize=BLOCK_64X64 ctx=0: aomdec value=3 (PARTITION_SPLIT, tell=1 rng=32768), ours value=9` + `EVIDENCE: /tmp/.../scratchpad/k-64x72.{ours,aom,ref}.y | aomdec --rawvideo + ffmpeg rawvideo vs our Y dump | aomdec == ffmpeg byte-for-byte; ours differs in 4583 of 4608 Y samples (whole frame), while the 64x64 control differs in 0` + Our tile payload starts at file offset 20 in both the 64x64 and the 64x72 stream + (`key_tile_bytes len=543`/`647`, file sizes 563/667), and `base_q_idx=160`, + `mi_cols=16`, `mi_rows=18` all parse correctly, so the header field values are + right; the divergence is in the very first symbol read off those bytes. + **Not diagnosed further — this is the handoff item.** Ruled out by reading the + source: `sb_rows`/`sb_cols` (`sequence.rs:409-422`, 18 -> 2 correct) and the + uniform-spacing tile-info loops (`frame.rs:1296-1334`, both increment loops match + spec 5.9.15, so the extra `increment_tile_rows_log2` bit that height 72 introduces + IS consumed). + +4. Pre-existing, unrelated to odd height: `192x128` and `192x136` both stop at + `"a 1:4 partition below 16x16"` with `--enable-1to4-partitions=0` on the command + line — a same-shaped refusal-from-own-desync at width 192, present on the control. + +## Code changed (all in this worktree, unproven end to end) + +- cherry-pick `eacd7fd` (lane-golomb) — the frame-edge partition bit at 6 sites in + both tile paths, plus its film key-frame fixture/gate. Clean merge. +- `crates/ec-av1/src/decode.rs:11371` — the key-frame 16-level frame-edge + `PARTITION_HORZ`/`VERT` now decodes its single visible 16x8 / 8x16 strip through + `decode_leaf_rect` instead of refusing (removes that refusal string; entry dropped + from `refusal_inventory.rs`). +- `crates/ec-av1/src/decode.rs` (inter tile path, superblock level and 16-level) — + the same edge half-strip as one 64x32 / 32x64 resp. 16x8 / 8x16 inter block + (`write_w`/`write_h`, square CDF/size-class corner-cut, exactly the accepted + corner-cut of the 32-level rect arm at `decode.rs:18448`). Interior rect + partitions still refuse by name. +- `decode.rs` — new counter `edge_rect_strip_hits()` (blocks decoded inside the 8px + edge band), for the gate a successor must write. + +`corner-cut:` the two inter edge arms read square CDFs / size classes for a +rectangular block (ceiling: coefficient and mode syntax for TX_64X32/TX_16X8 inter is +not modelled; upgrade path = the same treatment the 32-level rect arm eventually gets). + +## Verification status — honest + +- NO gate was added and NO refusal claim is proven: every stream that reaches the new + arms is desynced before them (finding 3), so a pixel compare would measure the + desync, not the arm. Writing + `a_real_aomenc_inter_sequence_with_an_8px_tall_edge_row_decodes_pixel_exact` on top + of a first-symbol desync would have produced a vacuous or a permanently-red gate. +- Suite: see `$HOME/.cache/oddh-suite.log` (run as a systemd unit, result quoted in + the handoff message). + +## Disposition + +- fix-now (next round, r2): the 64x72 key-tile first-symbol desync. It is the root + blocker; the edge arms above are dead code until it is fixed. +- deferred(the desync above): the 8px-edge-band gate + the refusal lift claim. +- deferred(width-192 defect, separate lane): the `"1:4 partition below 16x16"` stop + that both 192x128 and 192x136 share. diff --git a/lanes/oddh-r2.report.md b/lanes/oddh-r2.report.md new file mode 100644 index 00000000..6d938597 --- /dev/null +++ b/lanes/oddh-r2.report.md @@ -0,0 +1,97 @@ +# lane-oddh r2 — the 64x72 first-symbol desync is 128x128 superblocks + +## Root cause (byte-level proof, not inference) + +r1's pinned defect — a 64x72 aomenc KEY frame desyncing at the FIRST symbol +(aomdec value=3, ours 9) — is **not** an odd-height defect and **not** a header +parse defect. The stream's sequence header codes `use_128x128_superblock = 1`, +and this decoder is 64x64-superblock only (`SB_MI = 16`, no BLOCK_128X128 +partition read anywhere; `decode.rs` never reads `use_128x128_superblock`). + +libaom picks it: `av1_select_sb_size` (encoder_utils.c:1000-1003) returns +BLOCK_64X64 only when `speed >= 1 && min(w,h) <= 480`. r1's fixture was +encoded at `--cpu-used=0`, so speed 0 fell through to BLOCK_128X128. + +What the two decoders do with the same first byte: + +| | libaom (aomdec) | ours | +|---|---|---| +| first block | BLOCK_128X128 at mi (0,0): `has_cols = 0+16 < 16` false, `has_rows = 16 < 18` true | BLOCK_64X64 at mi (0,0) | +| symbol read | gathered 2-symbol partition (`partition_gather_horz_alike`) | 10-symbol `partition_cdf[12]` | +| value | 3 = PARTITION_SPLIT | 9 = PARTITION_VERT_4 | + +Ruled out first, by hand, field by field against spec 5.9.2 for this stream: +the uncompressed header is **49 bits** (3 before tile_info, 1 tile_info, 12 +quant, 1 seg, 1 delta, 29 loop filter — levels 36/38/21/19, sharpness 0, +mode_ref_delta_enabled 1, update 0 — 0 cdef, 0 lr, tx_mode 1, reduced_tx_set 1), +byte-aligning tile data to file offset 20. Our parser reads exactly the same 49 +bits. Two independent msac implementations (ours and a from-spec python one) +read symbol 9 from offset 20 with `partition_cdf[12]`, so the bytes and the +table are both ours-correct — only the *block size* is wrong. + +EVIDENCE: hand-parsed header bits + msac offset probe (both diagnostics reverted after use) | parsed k-64x72.obu, printed per-section bit positions (3/4/16/17/18/47/47/47/49), then decoded the first partition symbol at file offsets 16..24 with `PARTITION_W64[0]` in ours and in a from-spec python msac | both give 9 at offset 20 (aomdec: 3), i.e. same bytes, same table, different alphabet + +## What changed + +- `crates/ec-av1/src/stream.rs:509` — `decode_stream` now REFUSES a sequence + with `use_128x128_superblock` **on a frame larger than 64x64** by name + instead of silently decoding it as 64x64 superblocks (wrong pixels, whole + frame). The scoping is measured, not reasoned: a blanket refusal red-lined + 29 previously pixel-exact gates (29 failed / 318 passed), because at + <= 64x64 a 128x128 superblock decodes identically -- mi (0,0) has neither + `has_rows` nor `has_cols`, so BLOCK_128X128 is a forced SPLIT that reads no + symbol and only one 64x64 child is in frame. Every sibling inter gate at + 64x64 `--cpu-used=0` is exactly that case. +- `crates/ec-av1/src/stream.rs` — new gate + `a_real_aomenc_128x128_superblock_stream_is_refused_by_name`: real aomenc, + 64x72, `--cpu-used=0 --sb-size=128`; asserts the stream's sequence header + really codes `use_128x128_superblock` (knob-reached-the-tool) and then that + the refusal fires. +- `crates/ec-av1/src/stream.rs` — `a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact` + extended with the odd ladder 64x72, 72x64, 64x136, 136x64, 192x136; floor + raised 70 -> 120 pixel-exact attempts. +- `crates/ec-av1/src/refusal_inventory.rs` — the new refusal string pinned. +- `crates/ec-av1/src/stream.rs` — `a_real_aomenc_inter_frame_edge_half_strip_decodes_pixel_exact` + written and left `#[ignore]`d with its measured reason (below). + +## The size ladder (the table the charter asked for) + +`cargo test -p ec-av1 --lib -- a_real_aomenc_tiny_frame_size_sweep_decodes_pixel_exact`, +10 seeds each, real aomenc at `--cpu-used=4` (= 64x64 superblocks), 8-bit: + +| size | pixel-exact | refused | +|---|---|---| +| 8x8 | 0/10 | 10 (16x16 rect transform, pre-existing) | +| 16x16, 32x32, 16x32, 32x16, 64x64, 48x48, 24x24 | 10/10 each | 0 | +| **64x72, 72x64, 64x136, 136x64, 192x136** | **10/10 each** | 0 | + +EVIDENCE: $HOME/.cache/oddh-suite-r2.log + the run above | 13 sizes x 10 seeds, aomenc -> our decoder -> ffmpeg sample compare | 120 pixel-exact attempts, 0 mismatches, "tiny frame sweep: 120 pixel-exact attempts" + +So odd height/width at 64x64 superblocks is **clean**, including r1's +frame-edge half-strip code on the KEY path. + +## Open / deferred + +- deferred: 128x128 superblock decode — refused by name, not implemented — the + partition tree, `SB_MI`, CDEF/LR/deblock grids and the loop-filter unit size + are all 64-only; that is a lane, not a fix. Unblocked by: a lane that makes + `SB_MI` a parameter and adds the BLOCK_128X128 partition read. +- deferred: the INTER frame-edge half-strip arms r1 added are still UNGATED. + Measured this round at 192x160 (last superblock row 32 tall, so the forced + gathered edge symbol is a 64x32): with `--enable-rect-partitions=0` both bit + depths decode 6 frames **pixel-exact** but `edge_rect_strip_hits = 0` (the + encoder answers the forced symbol SPLIT every time); with rect ON the run + stops at other lanes' gaps — cq 40 "a non-skip rectangular (HORZ/VERT/HORZ_B) + strip needs rectangular residual coding", cq 62 "an INTER 32x32 partition + type this decoder does not code (value=8/9)", min-partition 16 "a HORZ/VERT + intra strip below 16x16 with a split transform". Unblocked by: the rect + inter-residual lane. + +## Suite + +`cargo test -p ec-av1 --lib` (systemd unit, log `$HOME/.cache/oddh-suite-r2.log`): +the blanket-refusal run was 318 passed / 29 failed / 32 ignored, every failure +the new refusal firing on a 64x64 `--cpu-used=0` stream. After scoping the +refusal to frames larger than 64x64, the 7-gate subset covering all of them +plus the three new/extended gates is green (7 passed, 0 failed); the full-suite +rerun on the scoped tree is launched to the same log and is r3's first read.