diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index bd60274c..2df093e1 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -15718,6 +15718,19 @@ fn decode_leaf_split4( neighbours.above[leaf_mi.1 + cell][2] = v_state; } } + // lane-dkey: a sub-8x8 leaf can never use palette (`av1_allow_palette` + // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its + // `palette_size` is 0 in every one of these mi cells, so the NEXT block's + // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder + // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette + // block above a 4x4 group left its size/colours standing in the mi-granular + // bands: the block below the group read `palette_y_mode` off CDF row 1 + // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a + // palette libaom never coded, and then skipped the `use_filter_intra` + // symbol that a palette block has none of -- one symbol short, tile + // desynced. Publishing the group's own zeros is the clear. + neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]); + neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]); Ok((leaf_modes[2], leaf_modes[1])) } @@ -16078,6 +16091,19 @@ fn decode_leaf_rect8( neighbours.above[leaf_mi.1 + cell][2] = v_state; } } + // lane-dkey (same clear as `decode_leaf_split4`): a sub-8x8 leaf can never use palette (`av1_allow_palette` + // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its + // `palette_size` is 0 in every one of these mi cells, so the NEXT block's + // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder + // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette + // block above a 4x4 group left its size/colours standing in the mi-granular + // bands: the block below the group read `palette_y_mode` off CDF row 1 + // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a + // palette libaom never coded, and then skipped the `use_filter_intra` + // symbol that a palette block has none of -- one symbol short, tile + // desynced. Publishing the group's own zeros is the clear. + neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]); + neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]); // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the // bottom one (the second under HORZ, the left one under VERT), the one a // neighbour to the right sees is the top-right (the second under VERT). diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index f92d9c83..bd1e82ca 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -13302,6 +13302,34 @@ mod tests { ); let stream = std::fs::read(&obu).expect("reference stream"); let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); + // lane-dkey: every reference point must also decode through OUR + // decoder, sample-exact against ffmpeg's decode of the same bytes. + // A BD table computed off streams we cannot read is a table about + // an encoder we cannot check; this is the assertion that would + // have caught the `force_integer_mv` defect (its stream decoded to + // 25 dB garbage while this gate stayed green) and the crf-5 key + // frame desync. A failure names the encoder, the point's flags and + // the first differing frame/plane/sample. + match crate::stream::decode_stream(&stream) { + Ok(ours) => { + assert_eq!( + ours.len(), + decoded.len(), + "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}", + ours.len(), + decoded.len(), + ); + for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() { + if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) { + panic!( + "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \ + decoder decoded {got}, ffmpeg {want}" + ); + } + } + } + Err(e) => panic!("{encoder} {params:?}: our decoder refused the stream ({e})"), + } let mean: f64 = decoded .iter() .zip(source) diff --git a/crates/ec-av1/src/motion_field.rs b/crates/ec-av1/src/motion_field.rs index 6a565113..7f006095 100644 --- a/crates/ec-av1/src/motion_field.rs +++ b/crates/ec-av1/src/motion_field.rs @@ -201,7 +201,11 @@ pub fn lower_mv_precision( _ => v - m, } }; - return (round(mv.0), round(mv.1)); + let out = (round(mv.0), round(mv.1)); + if out != mv && crate::envflags::env_flag!("EC_TRACE_TPL") { + eprintln!("EC_INTMV rounded {mv:?} -> {out:?}"); + } + return out; } if allow_high_precision_mv { return mv; diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 608967a8..c30c81f2 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -3867,6 +3867,101 @@ pub(crate) mod tests { } } + /// lane-dkey: the palette-neighbour-band gate. A palette-Y block's size and + /// colours used to stay standing in the mi-granular above/left bands after a + /// sub-8x8 group was decoded next to it -- the sub-8x8 readers published + /// skip/lf/mode state but no palette state, while libaom's mi grid carries + /// `palette_size == 0` in exactly those cells (`av1_allow_palette` needs + /// BLOCK_8X8 and up). The next intra block then read `palette_y_mode` off + /// CDF row 1 where libaom reads row 0 (class `cdf-row-held-constant`), + /// decoded a palette libaom never coded, and skipped the `use_filter_intra` + /// symbol a palette block has none of: one symbol short, tile desynced. + /// + /// Measured on the instrumented aomdec at KEY-frame block mi(76,88) of this + /// very stream (`EC_PALSYN_AOM ... ctx=0 y=0` against our `mode_ctx=1`). + /// Without the fix every one of the 12 frames differs from ffmpeg's decode + /// from luma sample 491904 on. + /// + /// The source is SYNTHETIC (no film sample lives in `fixtures`): the dark, + /// near-flat background libaom's own screen-content detector counts as + /// screen content (2..=4 distinct luma values per 16x16 block), which is + /// what turns palette on, plus one textured patch at a HALF-PEL position on + /// half the frames so the encoder splits that region down to 4x4 groups + /// beside its palette blocks. + #[test] + fn a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact() { + const NAME: &str = + "a_libaom_screen_stream_with_sub8_groups_beside_palette_blocks_decodes_exact"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + let (w, h, frames) = (1920usize, 1024usize, 12usize); + let mut raw = Vec::with_capacity(frames * w * h * 3 / 2); + for f in 0..frames { + let mut y = vec![0u8; w * h]; + for row in 0..h { + for col in 0..w { + y[row * w + col] = + 16 + ((col / 32 + row / 32) % 5) as u8 + ((col / 4 + row / 4) % 3) as u8; + } + } + // 2.5 px per pair of frames: integer on one pair, half a pixel off + // on the next (linear interpolation), so the patch's edges land + // mid-sample and the encoder splits there. + let x0 = 200.0 + 2.5 * (f / 2) as f64; + let (fx, ix) = (x0.fract(), x0.floor() as usize); + for row in 300..428 { + for col in 0..192 { + let tex = |u: f64| -> f64 { + let v = (row - 300) as f64; + 30.0 + 100.0 * (0.5 + 0.5 * ((u * 0.35).sin() * (v * 0.21).cos())) + }; + let s = tex(col as f64) * (1.0 - fx) + tex(col as f64 - 1.0) * fx; + y[row * w + ix + col] = s.round().clamp(0.0, 255.0) as u8; + } + } + raw.extend_from_slice(&y); + raw.extend(std::iter::repeat_n(128u8, w * h / 2)); + } + // [[pid-keyed-temp-path]]: parallel test binaries must not share a name. + let src = std::env::temp_dir().join(format!("ec-av1-palsub8-{}.yuv", std::process::id())); + std::fs::write(&src, &raw).expect("raw source"); + let out = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) + .args(["-s", &format!("{w}x{h}"), "-r", "24", "-i"]) + .arg(&src) + .args(["-an", "-threads", "1", "-g", "12", "-c:v", "libaom-av1"]) + .args(["-cpu-used", "6", "-b:v", "0", "-crf", "35", "-f", "obu", "-"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + let _ = std::fs::remove_file(&src); + if !out.status.success() { + eprintln!( + "SKIP {NAME}: ffmpeg has no libaom-av1 encoder ({})", + String::from_utf8_lossy(&out.stderr) + ); + return; + } + let stream = out.stdout; + let ours = decode_stream(&stream).expect("libaom screen-content stream decodes"); + let theirs = ffmpeg_decode_sequence(&stream, w, h, frames); + assert_eq!(ours.len(), frames, "{NAME}: shown frame count"); + for (i, (a, b)) in ours.iter().zip(theirs.iter()).enumerate() { + for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { + let first = l.iter().zip(r.iter()).position(|(x, y)| x != y); + assert!( + first.is_none(), + "{NAME}: frame {i} plane {plane} differs from ffmpeg at sample {}", + first.unwrap() + ); + } + } + } + /// Hardened past the report-only test above: a real libaom-av1 gradients /// stream, pinned deterministic (`gradients`' own `seed=`, plus /// `-threads 1`/`-row-mt 0`/no tiling so libaom's `cpu-used 8` RD search diff --git a/lanes/dkey.report.md b/lanes/dkey.report.md new file mode 100644 index 00000000..af2ceb44 --- /dev/null +++ b/lanes/dkey.report.md @@ -0,0 +1,120 @@ +# lane-dkey — palette state never cleared by sub-8x8 / inter blocks + +## Root cause (closed, measured) + +`crates/ec-av1/src/decode.rs`: the mi-granular above/left **palette bands** +(`Neighbours::above_palette_size/colors`, `left_palette_*`) were written ONLY by +the >=8x8 intra readers. Every other block reader — the sub-8x8 leaves +(`decode_leaf_split4`, `decode_leaf_rect8`, `decode_intra_sub8_leaf`, +`decode_inter_sub8_split4`, `decode_inter_sub8_rect2`) and the inter block +readers (`decode_inter_block`, `decode_inter_block8`) — left the previous +block's palette size/colours standing in those cells. libaom's mi grid says +`palette_size == 0` there (`av1_allow_palette` needs BLOCK_8X8 and up; an inter +block has no palette at all), so the NEXT block's `av1_get_palette_mode_ctx` +and `av1_get_palette_cache` read 0 where ours read the stale neighbour. + +**Class: `cdf-row-held-constant`** (a context read off a table row libaom never +selects), with the same shape as `trial-map-not-restored`: state published by +one block path and never cleared by the paths that cannot produce it. + +## First differing symbol (measured, two instrumented decoders) + +Synthetic 1920x1024 libaom stream (`-cpu-used 6 -crf 35 -g 12`, dark +screen-content-detected source), KEY frame, block **mi(76,88)**, BLOCK_16X16, +DC_PRED: + +* both decoders identical through `skip/cdef/dq/mode/angle_y/uv_mode/angle_uv` + (`rng=41844`); +* aomdec `EC_PALSYN_AOM mi=76,88 bsize=6 mode=0 uv=0 ctx=0 y=0` — palette ctx 0, + no palette, then `EC_ISTEP name=use_filter_intra val=0 rng=57408`; +* ours `TRACE pre_palette_y_mode bsize_ctx=2 mode_ctx=1` → `palette_y_mode + value=1` → decoded a 2-colour palette and its whole colour-index map, and + then **skipped the `use_filter_intra` symbol** (a palette-Y block has none). +* the stale `mode_ctx=1` came from the 8x8 palette block at mi(72,88); the 4x4 + group at mi(74,88) between them published nothing. + +One symbol short → tile desync → whole-frame mismatch from that block on. + +## Fix + +Publish the block's own zeros from every reader that cannot code palette, at +the same footprint it publishes skip/lf state (7 sites, `record_palette_y_rect` +/ `record_palette_uv_rect` with `size = 0`). `decode_block_128rect` already did +exactly this ("the unconditional stamp clears any stale neighbour palette +state, as every other block path does") — the comment was true of the >=8x8 +paths only. + +## Sweep + +`fill_skip_grid*` (every leaf block publishes it) vs `record_palette_*` over +all 16 block readers: 9 readers had skip but no palette publication. Stamped +7; the 5 INTER-side stamps (`decode_inter_block`, `decode_inter_block8` x2, +`decode_inter_sub8_split4`, `decode_inter_sub8_rect2`, `decode_intra_sub8_leaf`) +REGRESSED 13 tests (our own encoder's screen streams stopped decoding: "a +reference frame selected with no picture at this frame's own ref_frame_idx +slot") and were reverted -- the inter readers' `(rmi, cmi)`/`write_w`/`write_h` +are not the same footprint convention the palette bands index, so those stamps +zeroed cells belonging to real palette blocks. Only the two KEY-frame sub-8x8 +stamps ship. **Remaining, deferred:** `decode_rect_split`, +`decode_leaf_rect`, `decode_block_rect4`, `decode_rect4_16_strip` and +`decode_intra_rect_in_inter` are >=8x8 intra readers that CAN code palette +(`decode_intra_rect_in_inter` reads `palette_y_mode` at decode.rs:10131) and +publish nothing — the mirror defect (a real palette block invisible to its +neighbours). Needs each reader's decoded palette threaded to the tail. + +## Verification + +* synthetic gate stream: ours vs `ffmpeg`'s own decode — **byte-exact** + (before the fix: all 12 frames differ from sample 491904, mi(76,88)). +* film B, libaom `-cpu-used 6 -crf 5 -g 48`, 48 frames: the KEY frame's + `EC_IMODE` trace is now **identical to aomdec for all 15774 blocks** — the + charter's "first divergent intra block mi(184,344)" premise is STALE, that + desync is gone. crf 5 still fails, now in an INTER frame ("a Golomb tail + longer than this decoder reads", last block read mi(124,412)); narrowed and + deferred below. + +## Files + +* `crates/ec-av1/src/decode.rs` — 2 zero-stamps, in `decode_leaf_split4` and + `decode_leaf_rect8` (the key-frame sub-8x8 groups). +* `crates/ec-av1/src/encode.rs` — `external_ladder` now decodes EVERY reference + ladder point through `decode_stream` and asserts sample-exactness against + ffmpeg, naming encoder/params/frame/plane/sample (the assertion that would + have caught both this and the `force_integer_mv` defect). +* `crates/ec-av1/src/motion_field.rs` — `EC_INTMV` trace print when + `force_integer_mv` rounding actually changes a projected candidate. + +## The new gate assertion's first verdict (12-frame native arm) + +`cargo test -p ec-av1 --release -- --ignored --exact encode::tests::bd_rate_screen_native` +now FAILS on its FIRST reference point, exactly as the assertion is meant to: + + libaom-av1 ["-cpu-used","6","-b:v","0","-crf","45"] frame 1 plane Y sample 66: + our decoder decoded 146, ffmpeg 145 + +Clip "bars 1080p" (`testsrc2` colour bars, 1920x1024 crop, 12 frames, gop 12), +libaom crf 45, INTER frame 1, a +-1 luma sample — a reconstruction (not entropy) +gap: a rounding/filter difference, not a desync. The gate stops there, so the +other reference points of that arm and the later clips are UNMEASURED. This is +the finding the charter asked for; the fix is a separate lane (defer). + +## OPEN / deferred + +1. **crf 5 inter-frame Golomb refusal** — key frame is exact now; the failure + is in an inter frame (`EC_MM` trace, last read mi(124,412)). Unblocks: diff + aomdec `EC_MODE`/`EC_STACK` against our `EC_MM` from the first inter frame. +2. **The inter-side half of the sweep** (5 readers, reverted above) and the + palette-publishing mirror gap (`decode_intra_rect_in_inter` reads + `palette_y_mode` and publishes nothing). Unblocks: read each inter reader's + real band-index/footprint convention before stamping (the failing tests are + `encoder::tests::the_content_gate_keeps_screen_streams_flat` and the 12 + others listed in the suite log). +3. **The bars-1080p libaom crf-45 +-1** above: first reference point of the + 12-frame native arm; reproduce with `external_ladder`'s own recipe. +4. **The sensitive `force_integer_mv` fixture**: a 1920x1024 source with a + textured patch moving 2.5 px per duplicate-pair (half-pel motion, exact + duplicate frames) makes libaom round 72 projected candidates + (`EC_TRACE_TPL` → `EC_INTMV`), and the stream STILL decodes byte-exact with + the fix stubbed (`if false &&`): the rounded candidates never change a coded + block's mv. Sensitivity needs the rounded candidate to win a + NEARESTMV/NEARMV slot.