diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index a3bf499f..8f8db88b 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1374,6 +1374,24 @@ pub(crate) fn palette_split_tx_hits() -> usize { PALETTE_SPLIT_TX_HITS.with(|c| c.get()) } +// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform +// and which are therefore predicted one transform unit at a time (a skipped +// block codes no coefficients, so nothing else in the stream witnesses this +// path -- only the pixels do). +thread_local! { + static SKIP_SPLIT_TX_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units). +pub fn skip_split_tx_hits() -> usize { + SKIP_SPLIT_TX_HITS.with(|c| c.get()) +} + +/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt. +pub fn reset_skip_split_tx_hits() { + SKIP_SPLIT_TX_HITS.with(|c| c.set(0)); +} + // lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth` // symbol split their luma transform, bucketed by block side (8, 16, 32, 64) -- // the gate's proof that the lifted path actually ran, per size. @@ -1955,6 +1973,33 @@ thread_local! { } /// Current value of [`SB_RECT_HITS`]. +// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a +// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as +// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the +// non-SPLIT edge arm actually decoded (before this round the bit was read and +// thrown away, so that arm was unreachable). +thread_local! { + static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) }; +} + +/// Current value of [`EDGE_PART_HITS`]. +pub(crate) fn edge_part_hits() -> [usize; 4] { + EDGE_PART_HITS.with(|c| c.get()) +} + +/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time). +pub(crate) fn reset_edge_part_hits() { + EDGE_PART_HITS.with(|c| c.set([0; 4])); +} + +fn bump_edge_part(slot: usize) { + EDGE_PART_HITS.with(|c| { + let mut h = c.get(); + h[slot] += 1; + c.set(h); + }); +} + pub(crate) fn sb_rect_hits() -> usize { SB_RECT_HITS.with(|c| c.get()) } @@ -5639,6 +5684,16 @@ fn decode_rect_split( let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI)); let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h); let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h); + // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged): + // libaom clips `av1_foreach_transformed_block_in_plane` to + // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`, + // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose + // TOP-LEFT sample falls outside the frame is never coded. We read + // coefficients for those phantom units and desynced the stream at + // the very next symbol. + if tu_px >= y.true_width || tu_py >= y.true_height { + continue; + } // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a // transform unit INSIDE a block, which is a different rule from // the standalone-block table [`Reach::of`] applies -- and the @@ -8088,6 +8143,26 @@ fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 { /// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone. /// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written /// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`. +/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of +/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) -- +/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE). +fn dump_stage16(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf, fw: usize, fh: usize) { + use std::io::Write; + if let Ok(path) = std::env::var(var) + && let Ok(mut f) = std::fs::File::create(format!("{path}.f0")) + { + for (p, w, h) in [(y, fw, fh), (u, fw.div_ceil(2), fh.div_ceil(2)), (v, fw.div_ceil(2), fh.div_ceil(2))] { + for row in 0..h { + let mut bytes = Vec::with_capacity(w * 2); + for &s in &p.data[row * p.width..][..w] { + bytes.extend_from_slice(&s.to_le_bytes()); + } + let _ = f.write_all(&bytes); + } + } + } +} + fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) { use std::io::Write; if let Ok(path) = std::env::var(var) @@ -8233,6 +8308,7 @@ impl PlaneBuf { /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own /// already-rect-capable `(bw, bh)` pair. #[allow(clippy::too_many_arguments)] + #[track_caller] fn reconstruct_rect( &mut self, x: usize, @@ -8291,6 +8367,16 @@ impl PlaneBuf { } prediction }; + // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's + // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). + if std::env::var_os("EC_PRED").is_some() { + let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); + let row0: Vec = prediction[..bw.min(8)].to_vec(); + let col0: Vec = (0..bh.min(8)).map(|r| prediction[r * bw]).collect(); + eprintln!( + "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller() + ); + } for row in 0..bh { for col in 0..bw { let idx = row * bw + col; @@ -8310,6 +8396,7 @@ impl PlaneBuf { /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual /// order (cfl.c). + #[track_caller] fn reconstruct( &mut self, x: usize, @@ -8373,6 +8460,16 @@ impl PlaneBuf { } prediction }; + // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's + // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin). + if std::env::var_os("EC_PRED").is_some() { + let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum(); + let row0: Vec = prediction[..side.min(8)].to_vec(); + let col0: Vec = (0..side.min(8)).map(|r| prediction[r * side]).collect(); + eprintln!( + "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller() + ); + } for row in 0..side { for col in 0..side { let idx = row * side + col; @@ -8704,18 +8801,69 @@ fn decode_block( if skip { // A skipped block codes no residual syntax at all (spec 5.11.34): // straight prediction, on every plane. - y.reconstruct( - px, - py, - side, - mode, - angle_delta_y, - reach, - &vec![0i32; side * side], - None, - filter_intra, - smooth_neighbor, - ); + // + // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it + // is skipped (only an INTER skip forces the largest transform), and + // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts + // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units + // already written left/above of it inside this same block. Predicting + // the whole `side`x`side` at once gives a different (uniformly off by + // ~1) answer, which is exactly the residue this lane was chasing. + // The palette/intrabc override path keeps the single-call shape (its + // per-TU windowing is the non-skip loop's own `palette_y_buf` slice, + // untested for skip and unreachable in these streams). + let split_tx_skip = + tx_select && logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none(); + if split_tx_skip { + SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + let n_axis = side / logical_tx; + for tu_row in 0..n_axis { + for tu_col in 0..n_axis { + let tu_px = px + tu_col * logical_tx; + let tu_py = py + tu_row * logical_tx; + if tu_px >= y.true_width || tu_py >= y.true_height { + continue; + } + let tu_reach = tu_reach( + side, + side, + tu_col * logical_tx, + tu_row * logical_tx, + logical_tx, + reach, + px, + py, + y.width, + y.height, + ); + y.reconstruct( + tu_px, + tu_py, + logical_tx, + mode, + angle_delta_y, + tu_reach, + &vec![0i32; logical_tx * logical_tx], + None, + filter_intra, + smooth_neighbor, + ); + } + } + } else { + y.reconstruct( + px, + py, + side, + mode, + angle_delta_y, + reach, + &vec![0i32; side * side], + None, + filter_intra, + smooth_neighbor, + ); + } let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side)); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone()); @@ -8852,6 +9000,12 @@ fn decode_block( ); let tu_px = px + tu_col * logical_tx; let tu_py = py + tu_row * logical_tx; + // Same libaom clip as `decode_rect_split`'s loop above; a + // square block only hangs off the frame when the frame's mi + // dimensions are odd at the block's own level. + if tu_px >= y.true_width || tu_py >= y.true_height { + continue; + } let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0]; // A transform unit inside a block is NOT a block at that // position (lane-palette2 r12): `Reach::of` granted the @@ -9127,18 +9281,59 @@ fn decode_leaf8( let (cpx, cpy) = (px / 2, py / 2); let (luma_grid, u_grid, v_grid); if skip { - y.reconstruct( - px, - py, - 8, - mode, - angle_delta_y, - reach, - &vec![0i32; 64], - None, - filter_intra, - smooth_neighbor, - ); + // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an + // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4 + // transform units, each off the units already written left/above of + // it inside this same leaf -- an intra block's transform size is read + // whether or not it is skipped, and spec 7.11.2 predicts per unit. + if resolved == 4 { + SKIP_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + for tu_row in 0..2 { + for tu_col in 0..2 { + let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4); + if tu_px >= y.true_width || tu_py >= y.true_height { + continue; + } + let tu_reach = tu_reach( + 8, + 8, + tu_col * 4, + tu_row * 4, + 4, + reach, + px, + py, + y.width, + y.height, + ); + y.reconstruct( + tu_px, + tu_py, + 4, + mode, + angle_delta_y, + tu_reach, + &vec![0i32; 16], + None, + filter_intra, + smooth_neighbor, + ); + } + } + } else { + y.reconstruct( + px, + py, + 8, + mode, + angle_delta_y, + reach, + &vec![0i32; 64], + None, + filter_intra, + smooth_neighbor, + ); + } let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8)); u.reconstruct( cpx, @@ -12049,28 +12244,23 @@ 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. + // lane-hgkf r1 (class `parsed-then-discarded`, same finding as + // the unmerged lane-golomb r1): the gathered bit IS the + // partition -- libaom `ec_read_partition_impl` returns + // PARTITION_HORZ (resp. VERT) for 0 and only SPLIT for 1. + // Forcing SPLIT desynced the last superblock row of every + // frame whose height is not a multiple of 64: the ReelB key frames (3840x1608) diverge at mi_row=400 mi_col=0, + // the first block of that row. match (has_cols, has_rows) { (true, false) => { - if dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE)) == 1 { - PARTITION_SPLIT - } else { - PARTITION_HORZ - } + let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE)); + bump_edge_part(b.min(1) as usize); + if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ } } (false, true) => { - if dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE)) == 1 { - PARTITION_SPLIT - } else { - PARTITION_VERT - } + let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE)); + bump_edge_part(b.min(1) as usize); + if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } _ => PARTITION_SPLIT, } @@ -12128,26 +12318,25 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( } p } else { + // lane-hgkf r1: the 32-level frame-edge bit is the + // partition too (same libaom reader as the + // superblock level above). match (has_cols32, has_rows32) { (true, false) => { - // 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 - } + let b = dec.symbol_fixed(&gather( + &cdfs.partition_w32[ctx32], + VERT_ALIKE, + )); + bump_edge_part(2 + b.min(1) as usize); + if b == 1 { PARTITION_SPLIT } else { PARTITION_HORZ } } (false, true) => { - // 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 - } + let b = dec.symbol_fixed(&gather( + &cdfs.partition_w32[ctx32], + HORZ_ALIKE, + )); + bump_edge_part(2 + b.min(1) as usize); + if b == 1 { PARTITION_SPLIT } else { PARTITION_VERT } } _ => PARTITION_SPLIT, } @@ -12608,6 +12797,10 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( HORZ_ALIKE, )) }; + // lane-hgkf r1: slots 2/3 of + // [`EDGE_PART_HITS`], the gate's proof the + // non-SPLIT edge arm actually decoded. + bump_edge_part(if edge_split == 1 { 3 } else { 2 }); if edge_split == 0 { // lane-oddh r1: the strip IS decodable // -- libaom's `decode_partition` codes @@ -12774,22 +12967,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( tx_select, reduced_tx_set, )?; - decode_block_rect( - &mut dec, - &mut cdfs, - &mut neighbours, - (at32.0 + 1, at32.1), - 32, - 16, - &mut y, - &mut u, - &mut v, - enable_filter_intra, - allow_screen_content_tools, - base_q_idx, - tx_select, - reduced_tx_set, - )?; + // lane-hgkf r1: at the frame edge only the first half of the strip is + // coded (libaom `decode_partition` guards the second half with the same + // test that made this partition non-square). + if has_rows32 { + decode_block_rect( + &mut dec, + &mut cdfs, + &mut neighbours, + (at32.0 + 1, at32.1), + 32, + 16, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + reduced_tx_set, + )?; + } } PARTITION_VERT => { // lane-intradisp r1: mirror of PARTITION_HORZ @@ -12810,22 +13008,27 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( tx_select, reduced_tx_set, )?; - decode_block_rect( - &mut dec, - &mut cdfs, - &mut neighbours, - (at32.0, at32.1 + 1), - 16, - 32, - &mut y, - &mut u, - &mut v, - enable_filter_intra, - allow_screen_content_tools, - base_q_idx, - tx_select, - reduced_tx_set, - )?; + // lane-hgkf r1: at the frame edge only the first half of the strip is + // coded (libaom `decode_partition` guards the second half with the same + // test that made this partition non-square). + if has_cols32 { + decode_block_rect( + &mut dec, + &mut cdfs, + &mut neighbours, + (at32.0, at32.1 + 1), + 16, + 32, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + reduced_tx_set, + )?; + } } PARTITION_HORZ_A => { // lane-part32 r1: two 16x16 squares on top + @@ -13410,6 +13613,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // that isolate whether a decode-order frame's mismatch already exists // in reconstruction (this dump) vs is introduced by the loop filter // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). + dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -13453,8 +13657,10 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter // dump above these bisect WHICH filter stage introduced a mismatch. dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); + dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); + dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid); let (fw, fh) = (frame_width as usize, frame_height as usize); @@ -21193,6 +21399,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // that isolate whether a decode-order frame's mismatch already exists // in reconstruction (this dump) vs is introduced by the loop filter // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump). + dump_stage16("EC_AV1_PREFILT_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") { use std::io::Write; let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -21219,8 +21426,10 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter // dump above these bisect WHICH filter stage introduced a mismatch. dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v); + dump_stage16("EC_AV1_POSTDEBLOCK_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v); + dump_stage16("EC_AV1_POSTCDEF_DUMP16", &y, &u, &v, frame_width as usize, frame_height as usize); apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid); let motion_field = build_motion_field( diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 5033d15d..3bde2750 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -21482,4 +21482,171 @@ mod tests { yuv420p10le)" ); } + + /// lane-hgkf r1: a frame whose height (or width) is not a multiple of the + /// block size makes the last superblock row (column) read a GATHERED + /// partition bit instead of a full alphabet symbol -- and libaom's + /// `ec_read_partition_impl` answers that bit with `PARTITION_HORZ` + /// (resp. `VERT`) when it is 0, only `SPLIT` when it is 1. All three + /// key-frame edge readers (64-, 32- and 16-level) read the bit and threw + /// it away, forcing SPLIT; every such frame desynced at the first block + /// of its partial row. 192x136 / 136x192 is the smallest shape that hits + /// all three levels at once (136 = 2*64 + 8, so mi_rows = 34: the 64-, + /// 32- and 16-level halves all fall outside), and it is the shape of a + /// real 3840x1608 10-bit film key frame (1608 mod 64 == 8) that decoded + /// 51768 samples wrong before this round. + /// + /// The counter is sampled per attempt and read only on an attempt that + /// decoded AND is pixel-compared; slot 0/2 (the bit taken as HORZ/VERT) + /// must be nonzero or the gate proves nothing -- before this round that + /// arm was unreachable by construction. + #[test] + fn a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let mut compared = 0usize; + let mut edge_horz_total = 0usize; + let mut edge_sub_total = 0usize; + // The last two shapes are the ledger-measured 64-level pair: on a + // flat band (192x80 / 80x192) real aomenc answers the bottom-edge + // superblock with the 64-level HORZ/VERT, which the 136 shapes above + // never produce (their SBs always split down to the 32/16 levels). + for (width, height, flat) in [ + (192usize, 136usize, false), + (136usize, 192usize, false), + (192usize, 80usize, true), + (80usize, 192usize, true), + ] { + for depth in [8usize, 10] { + let pix = if depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", + &if flat { + format!("color=c=gray:size={width}x{height}") + } else { + format!("mandelbrot=size={width}x{height}:start_x=-0.6") + }, + "-pix_fmt", pix, "-strict", "-1", "-t", "1", "-vframes", "1", + "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg fixture ({width}x{height}, depth={depth}): {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let encode = || { + let mut child = Command::new(aomenc_path()) + .args([ + "--codec=av1", "--passes=1", "--end-usage=q", "--cq-level=32", + "--cpu-used=3", "--threads=1", "--row-mt=0", "--sb-size=64", + "--kf-max-dist=0", "--enable-rect-partitions=1", + "--enable-ab-partitions=0", "--enable-1to4-partitions=0", + "--enable-tx-size-search=0", "--reduced-tx-type-set=1", + "--min-partition-size=8", "--max-partition-size=64", + &format!("--input-bit-depth={depth}"), + &format!("--bit-depth={depth}"), + "--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("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture ({width}x{height}, depth={depth}): {}", + String::from_utf8_lossy(&out.stderr) + ); + out.stdout + }; + let stream = encode(); + assert_eq!( + stream, + encode(), + "{NAME}: aomenc output is not reproducible ({width}x{height}, depth={depth})" + ); + crate::decode::reset_edge_part_hits(); + let frames = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME}: decode failed ({width}x{height}, depth={depth}): {msg}" + ); + eprintln!( + "{NAME}: {width}x{height} depth={depth} arm refused (not compared): {msg}" + ); + continue; + } + }; + let hits = crate::decode::edge_part_hits(); + let ffmpeg_frames = if depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frames.len()) + } else { + ffmpeg_decode_sequence(&stream, width, height, frames.len()) + }; + assert_eq!(ffmpeg_frames.len(), frames.len(), "{NAME}: ffmpeg frame count"); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!( + got.y, want.y, + "{NAME} frame {i} luma vs ffmpeg ({width}x{height}, depth={depth}, \ + edge bits horz/split 64-level {}/{}, sub-level {}/{})", + hits[0], hits[1], hits[2], hits[3] + ); + assert_eq!( + got.u, want.u, + "{NAME} frame {i} U vs ffmpeg ({width}x{height}, depth={depth})" + ); + assert_eq!( + got.v, want.v, + "{NAME} frame {i} V vs ffmpeg ({width}x{height}, depth={depth})" + ); + } + compared += 1; + edge_horz_total += hits[0]; + edge_sub_total += hits[2]; + eprintln!( + "{NAME}: pixel-exact {width}x{height} at {depth}-bit, edge bits \ + 64-level horz/vert={} split={} sub-level horz/vert={} split={}", + hits[0], hits[1], hits[2], hits[3] + ); + } + } + assert!( + compared > 0, + "{NAME}: every arm refused -- the gate compared no pixels at all" + ); + assert!( + edge_horz_total > 0, + "{NAME}: no 64-level frame-edge bit was ever answered HORZ/VERT -- the arm this \ + round fixed never fired" + ); + assert!( + edge_sub_total > 0, + "{NAME}: no 32/16-level frame-edge bit was ever answered HORZ/VERT" + ); + } } diff --git a/lanes/hgkf-r1.report.md b/lanes/hgkf-r1.report.md new file mode 100644 index 00000000..7746e27e --- /dev/null +++ b/lanes/hgkf-r1.report.md @@ -0,0 +1,86 @@ +# lane-hgkf r1 — the frame-edge partition bit, all three levels + +Branch `lane-hgkf` off main `0df090a`. Two 3840x1608 10-bit key frames that +decoded without refusal but pixel-wrong (scratch: `.../scratchpad/census2/kf_0.obu`, +`kf_4500.obu`). + +## Root cause (class `parsed-then-discarded`) + +A superblock/block whose second half falls outside the frame does not carry a +full partition alphabet symbol; it carries one GATHERED bit. libaom +`ec_read_partition_impl` answers that bit with `PARTITION_HORZ` (resp. `VERT`) +when it is **0**, and only `PARTITION_SPLIT` when it is 1. All three key-frame +edge readers read the bit and threw it away, forcing SPLIT: + +* `crates/ec-av1/src/decode.rs:11373` — 64-level (superblock) +* `crates/ec-av1/src/decode.rs:11446` — 32-level +* `crates/ec-av1/src/decode.rs:11938` — 16-level (this one had no HORZ/VERT arm + at all; it now decodes the single in-frame 16x8 / 8x16 strip through + `decode_leaf_rect`) + +The HORZ/VERT arms also decode ONLY the in-frame half of the strip (libaom +`decode_partition` guards the second half with the same has_rows/has_cols test +that made the partition non-square) — `decode.rs:12480`, `12525`, `12038`, +`12086`. + +Every frame whose height or width is not a multiple of 64 desynced at the first +block of its partial row. 1608 mod 64 == 8, so both film key frames lost their +whole bottom 8-pixel band and everything the desync dragged after it. + +New counter `EDGE_PART_HITS` (`decode.rs`, `edge_part_hits()` / +`reset_edge_part_hits()`): slot 0/1 = 64-level bit taken as HORZ-VERT / SPLIT, +2/3 = the 32+16-level pair. + +Also ported (unmerged lane-golomb 791d87a) the libaom TU-origin clip: a +transform unit whose top-left sample lies outside `mi_cols*4 x mi_rows*4` is +never coded (`decode_rect_split` and `decode_block`'s multi-TU loop). Measured +INERT on both frames here (byte-identical output before/after); kept because it +is the libaom rule. + +## Evidence + +EVIDENCE: /home/user/.cache/hgkf-work/{ours,p,q,r}_kf_0.f0.yuv vs ref_kf_0.yuv | `dump_yuv kf_0.obu` vs `ffmpeg -pix_fmt yuv420p10le`, 16-bit sample compare | 3819 mismatching samples (Y 238 / U 1776 / V 1805, first Y row 1600 col 1120) -> **0, bit-exact all three planes** +EVIDENCE: /home/user/.cache/hgkf-work/r_kf_4500.f0.yuv vs ref_kf_4500.yuv | same command pair on the mid-film key frame | 51768 mismatching samples (Y 35861 / U 8419 / V 7488) -> **2403, luma only, |delta| <= 2, chroma bit-exact** +EVIDENCE: /home/user/.cache/hgkf-work/{a45.l,o45c.l} | `EC_TRACE_MODE_STEP=1` ladder, ours vs instrumented aomdec, ranges compared element by element | 0 changed lines (only oracle-side lines we do not print: `tx_depth`, `use_filter_intra`); pre-fix the ladders diverged at mi_row=400 mi_col=0, `skip` range 43258 vs 34753 +EVIDENCE: gate `a_real_aomenc_stream_whose_frame_edge_partition_bit_is_horz_decodes_pixel_exact` | `cargo test -p ec-av1 --lib frame_edge_partition_bit -- --nocapture` | 8/8 arms pixel-exact; 192x136+136x192 mandelbrot 8/10-bit sub-level HORZ-VERT bits 9/7/4/3; 192x80+80x192 flat 8/10-bit 64-level HORZ-VERT bits 3 each; **test result: ok. 1 passed** + +## Gate + +`crates/ec-av1/src/stream.rs` — one test, eight arms (two shapes x +{mandelbrot,flat} x {8,10}-bit). Both "answered HORZ/VERT" counter slots must +be nonzero, counters read only on an attempt that decoded AND is compared, Err +tolerated only for messages containing "unsupported", aomenc output hashed +twice for reproducibility. 136 = 2*64+8 is the small-scale twin of the film's +1608 mod 64 == 8; the flat 80-tall pair is the ledger-measured shape where real +aomenc answers the SUPERBLOCK edge bit non-SPLIT. + +Refusals lifted: none (this was a silent wrong-decode, not a refusal). +`refusal_inventory` and `gate_coverage` unchanged. + +## Open residue + +`fix-now` for a follow-up round, not reachable inside this one: the mid-film key +frame still has **2403 luma samples wrong, |delta| <= 2, chroma exact**, in two +clusters — SB(row 19, col 17) 1409 samples and SB(row 6..9, col 49..51) ~990, +first at Y row 416 col 3169 (mi_row 104, mi_col 792), ours 210 vs 209. The +entropy ladder is exact through the whole frame, so this is a RECONSTRUCTION +(prediction or post-filter) defect, not a symbol defect — the +-1/+-2 magnitude +and the isolated superblocks point at an intra prediction corner or a +CDEF/deblock strength on those blocks. `deferred: mid-film key frame +-2 luma +residue — needs a per-TU EC_PRED compare at mi(104,792) — unblocked by this +round's entropy exactness, any agent can start at that block.` + +Suite: `cargo test -p ec-av1 --lib` (systemd unit, log `$HOME/.cache/hgkf-suite2.log`) -- **356 passed / 0 failed / 29 ignored**, 683s. + +## Same-shape sweep (class `parsed-then-discarded`, frame-edge partition bit) + +Grepped every gathered-edge reader in `decode.rs`. Fixed: the three key-frame +ones (64/32/16-level). **Flagged, not fixed**: the INTER tile has the identical +three readers — `decode.rs:18441` (64-level, `part64` match), `decode.rs:18590` +(32-level) and `decode.rs:18755` (16-level) — all still discard the bit and +force SPLIT, so an inter frame whose height is not a multiple of 64 mis-decodes +its partial row exactly the way the key frames did. It is left alone here +because the inter edge-strip decoders do not exist yet (lane-oddh r2 measured +that no aomenc recipe even reaches that arm today, so a fix could not be gated). +`deferred: inter-frame edge partition bit — needs the inter frame-edge +half-strip decoder (lane-oddh territory) plus a recipe that reaches it.` diff --git a/lanes/hgkf-r2.report.md b/lanes/hgkf-r2.report.md new file mode 100644 index 00000000..cb1a3d66 --- /dev/null +++ b/lanes/hgkf-r2.report.md @@ -0,0 +1,90 @@ +# lane-hgkf r2 — a skipped intra block predicts per TRANSFORM UNIT + +Branch `lane-hgkf`, on top of r1 (`4939695`). Target: the r1 residue on the +mid-film 3840x1608 10-bit key frame — 2403 luma samples wrong, |delta| <= 2, +chroma exact, entropy ladder exact frame-wide. + +## Stage split (the charter's step 1) + +Both decoders' 8-bit stage rungs truncate 10-bit samples, so a |delta| <= 2 +defect is invisible in them. Added a 16-bit twin on both sides: +`ec_dump16` in the oracle (`EC_AV1_PREFILT_DUMP16` / +`EC_AV1_POSTDEBLOCK_DUMP16`, `av1/decoder/decodeframe.c`) and `dump_stage16` +in ours (same two names plus `EC_AV1_POSTCDEF_DUMP16`, `decode.rs`). + +EVIDENCE: /home/user/.cache/hgkf-work/{o,a}_pre.f0, {o,a}_pdb.f0, o_fin.f0.yuv vs ref_kf_4500.yuv | ours vs instrumented aomdec, 16-bit cropped planes at PREFILT / POSTDEBLOCK / FINAL | PREFILT Y 2372 wrong (maxabs 3, first row 416 col 3170, ours 210 vs 209), POSTDEBLOCK identical set, FINAL 2403 -> **the defect is already in reconstruction**; deblock/CDEF/LR only smear it + +## Root cause (class `decision-at-wrong-granularity`) + +An intra block's `tx_depth` is read whether or not the block is skipped (only +an INTER skip forces the largest transform), and spec 7.11.2 / libaom +`predict_and_reconstruct_intra_block` predicts **one transform unit at a +time** — each unit's above/left edges are the units already reconstructed +inside that same block. Our skip branches predicted the whole block in one +call: + +* `crates/ec-av1/src/decode.rs` `decode_block`'s `if skip` arm — a 32x32 block + with `logical_tx == 8` was one 32x32 DC prediction (123) where libaom does 16 + 8x8 DC predictions (124 each). +* `crates/ec-av1/src/decode.rs` `decode_leaf8`'s `if skip` arm — the same shape + one level down: an 8x8 leaf with `resolved == 4` is four 4x4 units. + +Both now loop the units with a zero residual, reusing the non-skip loop's own +`tu_reach` geometry and its out-of-frame TU-origin clip. The palette/intrabc +override keeps the single-call shape (its per-TU windowing is the non-skip +path's, untested for skip and unreachable in these streams). + +New counter `SKIP_SPLIT_TX_HITS` (`skip_split_tx_hits()` / +`reset_skip_split_tx_hits()`, blocks not units): the only witness this path +has, since a skipped block codes no coefficients at all. + +## Evidence + +EVIDENCE: /home/user/.cache/hgkf-work/aom_pred.txt, our_pred.txt | new oracle rung `EC_PREDND` (non-directional high-bitdepth prediction; the pre-existing `EC_PRED` rung sat AFTER the `is_hbd` early return and printed nothing on a 10-bit stream) vs our new `OUR_PRED` rung | at px(1088,1216) libaom prints 16 8x8 DC predictions of 124, ours one 32x32 of 123 — sum 7936 x16 vs 125952 +EVIDENCE: /home/user/.cache/hgkf-work/fx_kf_4500.f0.yuv vs ref_kf_4500.yuv | `dump_yuv kf_4500.obu` vs `ffmpeg -pix_fmt yuv420p10le`, 16-bit compare | 2403 wrong -> **0, all three planes bit-exact** +EVIDENCE: /home/user/.cache/hgkf-work/fx_kf_0.f0.yuv vs ref_kf_0.yuv | same command pair | **0, still bit-exact** (r1's frame did not regress) + +Scratch pin (not a repo fixture, scratch-only as the charter requires): +`.../scratchpad/census2/kf_4500.obu` sha256 +`80529979df3735bce82f9c48fb0be66ec2019f4316ad6e617def86141c2b9010` — 48 split-skip +TU predictions, decodes bit-exact; `kf_0.obu` sha256 +`53c311dec790bb2413afdde92cb24de498a7c4f66f6f0c7f4f5910ab0d2c65dc` — 0 hits, bit-exact. + +## Gate: NOT LANDED — no encoder recipe reached the path + +`deferred: an in-repo gate for split-tx skipped intra prediction — no +reproducible encoder recipe found in this round's budget — unblocked by either +an aomenc flag combination that keeps a split `tx_depth` on a block it then +skips, or by lifting the 1:4-partition refusal so an SVT-AV1 stream can be +decoded whole.` + +Swept, all 10-bit, all with the decode's success checked (a refused decode's +counter is a `counter-from-refused-stream` artefact, so every arm below reports +both): + +* aomenc `--enable-tx-size-search=1`, mandelbrot/testsrc2/low-amplitude noise, + 256x192..1280x720, cq 12..55, cpu-used 0..8, aq-mode 0/1, 8- and 10-bit: + **0 hits on every arm that decoded**. aomenc's tx search ties on a zero + residual and keeps the largest transform, so it essentially never writes this + combination. +* ffmpeg `libsvtav1` (v3.1.2) preset 4, 1280x720 10-bit: **reaches the path** + (4..24 units at crf 25..55) — but every one of those streams also uses a 1:4 + partition below 16x16 / intrabc / palette, all of which this decoder refuses, + so nothing could be pixel-compared. +* `gradients=size=1280x720:n=4` + libsvtav1 crf 30 decoded whole once with 16 + units, but lavfi `gradients` is not reproducible (3 encodes, 3 different + sha256) — the known `seeded-fixture-not-reproducible` trap, rejected as a + fixture. + +## Same-shape sweep + +Every intra skip-prediction site in `decode.rs`: `decode_block` (fixed), +`decode_leaf8` (fixed), the 4x8/8x4 leaf at `decode.rs:9570` (already per-TU, +lane-palette2), the inter-frame vartx leaf at `decode.rs:16450` (already +per-TU), the 4x4 leaf (no split exists). Chroma skip prediction is still +whole-block: for 4:2:0 the chroma transform only splits above a 64x64 luma +block, which no gate or film frame here reaches — +`deferred: chroma skip prediction per TU above 64x64 luma — no stream reaches +it — unblocked by a 128x128-superblock 10-bit gate.` + +Suite: `cargo test -p ec-av1 --lib` (user unit, log `$HOME/.cache/hgkf-suite-r2.log`) -- **356 passed / 0 failed / 29 ignored**, 416s.