diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 1fe71148..ac0a542a 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -877,6 +877,12 @@ pub(crate) fn set_segmentation( mi_cols: usize, prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx, ) { + if crate::envflags::env_flag!("EC_HDR") { + eprintln!( + "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}", + seg.enabled, seg.update_map, seg.temporal_update, seg.seg_id_pre_skip, seg.last_active_seg_id, seg.feature_data + ); + } fctx.seg.with(|s| *s.borrow_mut() = seg); fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols))); fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]); @@ -1076,7 +1082,13 @@ fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32; hit!(SEG_ID_HITS); let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id)); - neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8 + let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active); + // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..` + // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff. + if crate::envflags::env_flag!("EC_TRACE_SEG") { + eprintln!("EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}", dec.debug_state().0); + } + id as u8 } /// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block @@ -15725,19 +15737,50 @@ fn read_intra_mode_sub8( skip_ctx: usize, allow_intrabc: bool, mi_r: usize, - mi_c: usize, fctx: &crate::decode::FrameCtx, + mi_c: usize, + // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4` + // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf + // left the second mi column at segment 0, which reads back as a + // neighbour's `cdf_index`/prediction two blocks later. + seg_w_mi: usize, + seg_h_mi: usize, fctx: &crate::decode::FrameCtx, ) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option)> { let trace = crate::envflags::env_flag!("EC_AV1_TRACE"); - if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") { + let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP"); + if ec_istep { eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0); } + // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder + // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block. + macro_rules! istep { + ($name:literal, $val:expr) => { + if ec_istep { + eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}", $name, $val, dec.debug_state().0); + } + }; + } + // lane-seg2: same `intra_segment_id` placement as the square and rect + // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id` + // like any other block, over its own 1x1 mi footprint. Dropping it here + // both ate a symbol (the tile desynced at the frame's first sub-8x8 + // split) and left `cur_segment_id` on the previous block, so the leaf + // dequantized with a neighbour's `SEG_LVL_ALT_Q`. + if seg_id_pre_skip(fctx) { + intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx); + } let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0; if trace { eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0); } + istep!("skip", skip as i32); + if !seg_id_pre_skip(fctx) { + intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx); + } maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx); + istep!("cdef", 0); maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx); maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx); + istep!("dq", 0); if allow_intrabc { let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0; if use_intrabc { @@ -15749,6 +15792,7 @@ fn read_intra_mode_sub8( let above_ctx = INTRA_MODE_CTX[above_mode]; let left_ctx = INTRA_MODE_CTX[left_mode]; let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]); + istep!("mode", mode); if trace { eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0); } @@ -15865,7 +15909,7 @@ fn decode_leaf_split4( let (skip, mode, angle_delta_y, chroma, filter_intra) = read_intra_mode_sub8( dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra, filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"), - skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx, + skip_ctx, allow_intrabc, lmi.0, lmi.1, 1, 1, fctx, )?; leaf_modes[i] = mode; leaf_skips[i] = skip; @@ -16091,7 +16135,7 @@ fn decode_leaf_rect8( dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra, filter_intra_size_class_rect(bw, bh) .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"), - skip_ctx, allow_intrabc, lmi.0, lmi.1, fctx, + skip_ctx, allow_intrabc, lmi.0, lmi.1, bw / 4, bh / 4, fctx, )?; if filter_intra.is_some() { // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 3334cb24..a8bf1197 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -35385,4 +35385,91 @@ pub(crate) mod tests { eprintln!("{NAME}: {checked} straddling reference points decoded sample-exact"); } + /// lane-seg2: a SEGMENTED key frame that also codes sub-8x8 INTRA leaves. + /// + /// WHY IT EXISTS: `read_intra_mode_sub8` -- the reader every `BLOCK_4X4` + /// split leaf and every 8x4/4x8 leaf goes through -- never called spec + /// 5.11.6's `intra_segment_id` at all. On a stream with segmentation on + /// it therefore (a) left the block's `segment_id` symbol unread, so the + /// tile desynced from the frame's first sub-8x8 partition on, and (b) + /// dequantized the leaf with the PREVIOUS block's `SEG_LVL_ALT_Q`. + /// Reading it with a hardcoded 1x1 mi footprint was the second half of + /// the same defect: an 8x4 leaf left its second mi cell at segment 0, + /// which the next block read back as its spatial prediction and CDF row. + /// + /// RECIPE: flat gray + heavy `noise` (the contrast is what turns libaom's + /// activity segmentation on -- a `testsrc2`/bars source codes ONE segment + /// and passes with the defect in, ledger dead-end `gate film rows are + /// colour bars`), at `-crf 5 -cpu-used 2`, which is the measured corner + /// where libaom answers with sub-8x8 intra partitions. Measured on this + /// exact stream: red before either half of the fix (134k/134k samples + /// off), green with both. + #[test] + fn a_segmented_key_frame_with_sub_8x8_intra_leaves_decodes_exactly() { + const NAME: &str = "a_segmented_key_frame_with_sub_8x8_intra_leaves_decodes_exactly"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + const FRAMES: usize = 4; + let (w, h) = (384usize, 152usize); + let src = format!( + "color=c=gray:s={w}x{h}:r=25,noise=alls=80:all_seed=7:allf=t+u" + ); + let args: Vec = [ + "-v", "error", "-f", "lavfi", "-i", &src, "-frames:v", "4", "-pix_fmt", "yuv420p", + "-an", "-threads", "1", "-g", "4", "-c:v", "libaom-av1", "-cpu-used", "2", "-b:v", + "0", "-crf", "5", "-aq-mode", "1", "-f", "obu", "-", + ] + .iter() + .map(|s| (*s).to_string()) + .collect(); + let out = Command::new("ffmpeg") + .args(&args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + if !out.status.success() { + eprintln!( + "SKIP {NAME}: ffmpeg cannot encode with libaom-av1 ({})", + String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("") + ); + return; + } + let stream = out.stdout; + crate::decode::reset_segment_hits(); + let want = ffmpeg_decode_sequence(&stream, w, h, FRAMES); + let got = decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME}: refused: {e}")); + assert_eq!(got.len(), want.len(), "{NAME}: frame count"); + for (f, (o, r)) in got.iter().zip(&want).enumerate() { + for (plane, a, b) in [("Y", &o.y, &r.y), ("U", &o.u, &r.u), ("V", &o.v, &r.v)] { + if let Some(i) = a.iter().zip(b.iter()).position(|(x, y)| x != y) { + let stride = if plane == "Y" { w } else { w / 2 }; + panic!( + "{NAME}: frame {f} plane {plane} sample ({}, {}): ours {} vs ffmpeg {}", + i % stride, + i / stride, + a[i], + b[i], + ); + } + } + } + // The property is asserted, not hoped for: without more than one + // segment this row would pass with the defect still in. + assert!( + crate::decode::segment_ids_seen() >= 2, + "{NAME}: vacuous run -- {} distinct segment ids", + crate::decode::segment_ids_seen() + ); + eprintln!( + "{NAME}: {FRAMES} frames sample-exact, {} segment_id symbols, {} distinct ids", + crate::decode::segment_id_hits(), + crate::decode::segment_ids_seen() + ); + } + } diff --git a/lanes/seg2.report.md b/lanes/seg2.report.md new file mode 100644 index 00000000..504074ec --- /dev/null +++ b/lanes/seg2.report.md @@ -0,0 +1,106 @@ +# lane-seg2 — libaom `-aq-mode 1` on film B: the sub-8x8 intra reader had no segment id + +Two defects, one reader. Class: **`symbol-consumption-gap`** (a syntax element +the spec codes for every block was never read on one block-shape path), with +the second half in the **`tx-grid-published-block-side`** shape (a per-mi map +stamped with the wrong footprint). + +## First divergent symbol + +`filmB_aom45.obu` (`crop=1920:1024`, 12 frames, libaom `-cpu-used 6 -crf 45 +-aq-mode 1`), frame 0 = KEY frame, first bad luma sample (883, 888). + +Cross-decoder `EC_IMODE` range ladder (aomdec `EC_TRACE_MODE_STEP` vs our +`EC_TRACE_MODE_STEP`), blocks 1..1799 identical, block 1800 diverges: + +``` +aom EC_IMODE mi_row=226 mi_col=218 bsize=0 rng=35072 (BLOCK_4X4 split leaf) +ours EC_IMODE mi_row=226 mi_col=218 fn=sub8 rng=35072 +aom ... next block EC_IMODE mi_row=226 mi_col=219 rng=43528 +ours ... next block EC_IMODE mi_row=226 mi_col=219 rng=33544 +``` + +i.e. the desync is INSIDE the frame's first sub-8x8 intra leaf. + +At `crf 5` the same ladder puts the first divergence at mi (198, 148), and the +new `EC_SEG` trace (added to both decoders) names the element exactly: + +``` +aom EC_SEG mi_row=198 mi_col=148 cdf=1 pred=1 coded=1 id=2 rng=61592 +ours EC_SEG mi_row=198 mi_col=148 cdf=0 pred=0 coded=1 id=1 rng=35672 +``` + +`cdf_index` 0 vs 1 and prediction 0 vs 1: our `av1_get_spatial_seg_pred` read +segment 0 out of the LEFT neighbour mi (198, 147). + +## Root cause + +`crates/ec-av1/src/decode.rs read_intra_mode_sub8` — the reader every +`BLOCK_4X4` split leaf AND every 8x4/4x8 leaf goes through — never called +spec 5.11.6's `intra_segment_id` at all: + +1. **the symbol was never read.** On a stream with `segmentation_enabled` the + leaf's `segment_id` symbol stayed in the bitstream, so the tile desynced + from the frame's first sub-8x8 partition on (and `cur_segment_id` kept the + PREVIOUS block's value, so the leaf also dequantized with a neighbour's + `SEG_LVL_ALT_Q`). Fixed at `098e5e1c`. +2. **the stamp was 1x1.** Reading it with a hardcoded 1x1 mi footprint is the + second half: the same reader serves 8x4/4x8 leaves, whose second mi cell + stayed at segment 0 and was read back by the NEXT block as its spatial + prediction and CDF row. Fixed at `8e58fcc7` (footprint threaded from the + leaf's own `bw`/`bh`: 1x1 for a 4x4 leaf, `bw/4 x bh/4` for a rect one). + +Both halves are needed: with only (1) the film B libaom crf 5 and 20 points are +still 9.2M/9.7M samples off; the witness below is red under either half alone. + +## Same-shape sweep — every site that reads or stamps the segment map + +| site (`decode.rs`) | reader | footprint passed | verdict | +| --- | --- | --- | --- | +| `read_intra_mode_rect` (8922/8927) | rect intra | `(bw/4, bh/4)` | ok | +| `decode_leaf8`/square (13031/13039) | square intra | `(side/4, side/4)` | ok | +| `read_intra_mode_sub8` (15747/15755) | 4x4 split + 8x4/4x8 intra leaf | **absent, then 1x1** | **FIXED (both halves)** | +| inter block reader (26625/26644) | inter | `(write_w/4, write_h/4)` | ok | +| `decode_inter_sub8_split4` (30394/30398) | 4x4 inter leaf | `(1, 1)` | ok (BLOCK_4X4 is 1x1 mi) | +| inter 4x8/8x4 leaf (31437/31441) | rect inter leaf | `(bw/MI, bh/MI)` | ok | +| inter 8x8 leaf (32181/32189) | 8x8 inter leaf | `(2, 2)` | ok | + +Consumers of the map, all reading through the two single points +`segment_id_at` / `block_q_idx` (which is why only the WRITE side was wrong): +`spatial_seg_pred`, `predicted_segment_id`, `block_q_idx` (`SEG_LVL_ALT_Q`), +the deblocker's per-segment `lf_level`. No second write path exists. + +## Witness + +`stream::tests::a_segmented_key_frame_with_sub_8x8_intra_leaves_decodes_exactly` +(new, in the existing `stream::` test binary, no fixture committed): +`color=c=gray:s=384x152 , noise=alls=80:all_seed=7:allf=t+u` -> ffmpeg +`libaom-av1 -cpu-used 2 -b:v 0 -crf 5 -aq-mode 1 -g 4`, 4 frames, decoded by +ffmpeg and by us, all three planes, plus `segment_ids_seen() >= 2` so a +one-segment (vacuous) run cannot pass. + +- green at HEAD: `4 frames sample-exact, 1963 segment_id symbols, 3 distinct ids`, 2.16 s +- red with the fix reverted: `FAILED. 0 passed; 1 failed` (measured 134464 + samples off pre-fix, 134082 off with only the first half of the fix) + +`-cpu-used 2` is load-bearing: at `-cpu-used 6` (the straddle gate's recipe) +libaom answers this source with no sub-8x8 intra partition and the row passes +with the defect in — measured on four probe recipes. + +## Ladder (12 frames, all planes, vs ffmpeg; streams from lane-golomb2) + +| stream | pre-fix | after `098e5e1c` | HEAD | +| --- | --- | --- | --- | +| film B 1920x1024 libaom crf 5 / 20 / 35 / 45, `-aq-mode 1` | 4x DIFF | 2 EXACT, 2 DIFF | **4/4 EXACT** | +| film B 1920x1024 rav1e q 50 / 100 / 150 / 200 | 4/4 EXACT | 4/4 EXACT | **4/4 EXACT** | +| film A 1920x792 libaom crf 5 / 20 / 35 / 45 | 4/4 EXACT | — | **4/4 EXACT** | +| film A 1920x792 rav1e q 50 / 100 / 150 / 200 | 4/4 EXACT | — | **4/4 EXACT** | + +## Instruments added (kept) + +- `EC_TRACE_SEG=1` on BOTH decoders: `EC_SEG mi_row= mi_col= cdf= pred= coded= id= rng=` + (libaom side patched in `~/.cache/aom-oracle/src/av1/decoder/decodemv.c`, + rebuilt in place). +- `EC_HDR=1` also prints `EC_SEGHDR enabled/update_map/temporal/preskip/last_active/data`. +- `EC_TRACE_MODE_STEP=1` now prints the `skip`/`cdef`/`dq`/`mode` ladder for + sub-8x8 leaves too, which is what separated "segment id" from "cdef".