diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 53cc82b8..46ff6993 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -8564,6 +8564,9 @@ pub(crate) fn encode_key_frame_inner( &mut tiles, search.lambda, fctx, + // A key frame codes no 128x128 root block (the writer has no intra + // path at that size), so every unit carries its own literal. + &[], // Every re-code starts from this frame's OWN starting tables, never // from where the first write left them: the second tile is the same // symbol sequence plus new ones, so it must adapt from the same @@ -8656,6 +8659,10 @@ fn pick_and_apply_filters( tiles: &mut Vec>, lambda: f64, fctx: &crate::decode::FrameCtx, + // lane-edge128: `crate::tile::cdef_unit_owner` for the blocks these tiles + // carry -- empty (the identity map) for a frame whose every block covers + // one 64x64 CDEF unit. + cdef_owner: &[u32], recode: impl Fn( u8, usize, @@ -8708,6 +8715,7 @@ fn pick_and_apply_filters( damping, (sb_cols, sb_rows), lambda, + cdef_owner, ); drop(ft); let (lf, cdef, idx_grid, picture) = search_result?; @@ -13228,6 +13236,7 @@ pub(crate) fn encode_inter_frame( &mut tiles, search.lambda, fctx, + &crate::tile::cdef_unit_owner(&blocks, mi_cols, mi_rows), // As in `encode_key_frame_inner`, but this frame's end-of-tile tables // are what the NEXT frame writes from, so the winning re-code // publishes its own into `end_cdfs` -- the first write's are stale @@ -16376,6 +16385,90 @@ mod tests { } } + /// lane-edge128: a 128x128 root block WITH a residual on a clip whose + /// CDEF search codes a per-64x64 `cdef_idx` list. `read_cdef` (spec + /// 5.11.56) codes ONE literal for the block that first reaches a unit and + /// copies it over every unit the block SPANS, so the four units of a 128 + /// root share one index -- while the encoder's CDEF search prices a + /// preset per unit and its filter replay applied all four. Only the first + /// reached the stream, so every decoder filtered the other three with the + /// origin's strengths and the encoder's reconstruction (the picture the + /// next frame predicts from) was a filter apart from what a decoder + /// produces. RED before this lane on the native BD gate's bars 2160p row + /// (`EC_AV1_B128RES=1`, q=90, frame 11: 8 luma and 702 chroma samples, + /// the rows above the 128 superblock's own edge); the stream itself was + /// always right -- ffmpeg and our own decoder agreed with each other and + /// disagreed with the encoder. + /// + /// `take_cdef_covered_units` is the gate on the fixture (class + /// `gate-blind-to-feature`): a clip whose CDEF picks one strength pair + /// for the whole frame codes no literal at all and witnesses nothing. + /// + /// cargo test -p ec-av1 --release --lib -- --ignored \ + /// a_128_root_residual_block_under_a_per_unit_cdef --nocapture + #[test] + #[ignore = "sets the process-global superblock size: run it alone"] + fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() { + let _knobs = crate::speed::knob_write(); + if !have_ffmpeg() { + eprintln!("SKIP: no ffmpeg"); + return; + } + force_sb128(true); + let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let clip = dir.join("testsrc2-1280x768.y4m"); + // Detailed synthetic content: its CDEF search spends more than one + // strength pair, which is what puts a `cdef_idx` literal in the tile. + let ok = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-f", "lavfi"]) + .args(["-i", "testsrc2=size=1280x768:rate=24"]) + .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) + .arg(&clip) + .status() + .expect("ffmpeg failed to run") + .success(); + assert!(ok, "ffmpeg could not write the synthetic clip"); + let (width, height) = (1280usize, 768usize); + let pictures = + crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); + force_b128_root(true); + force_b128_residual(true); + let _ = crate::tile::take_sb128_residual_hits(); + let _ = crate::filter_search::take_cdef_covered_units(); + let encoded = encode_sequence(&pictures, 90, 0.5).unwrap(); + let coded = crate::tile::take_sb128_residual_hits(); + let covered = crate::filter_search::take_cdef_covered_units(); + eprintln!( + "128x128 blocks WITH a residual: writer coded {coded}; 64x64 CDEF units taking \ + another unit's literal: {covered}" + ); + assert!(coded > 0, "no 128x128 block carried a residual on this clip"); + assert!( + covered > 0, + "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \ + cannot witness the rule", + ); + let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); + assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); + for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { + for (plane, got, want) in [ + ("luma", &dec.y, &frame.reconstruction.y), + ("U", &dec.u, &frame.reconstruction.u), + ("V", &dec.v, &frame.reconstruction.v), + ] { + let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); + assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ"); + } + } + let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); + for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { + assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); + assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); + assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); + } + } + /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same /// `write_compound_block` chain every smaller compound block takes, at a @@ -17606,32 +17699,6 @@ mod tests { ); for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() { if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) { - // TEMPORARY (lane-b128r bisect): the whole mismatch map. - let (l, r) = match plane { - "Y" => (&d.y, &e.reconstruction.y), - "U" => (&d.u, &e.reconstruction.u), - _ => (&d.v, &e.reconstruction.v), - }; - let w = if plane == "Y" { width } else { width / 2 }; - let bad: Vec = l - .iter() - .zip(r.iter()) - .enumerate() - .filter(|(_, (a, b))| a != b) - .map(|(i, _)| i) - .collect(); - let rows: Vec = bad.iter().map(|i| i / w).collect(); - let cols: Vec = bad.iter().map(|i| i % w).collect(); - eprintln!( - "B128R MISMATCH {name} q={q} frame {i} plane {plane}: {} samples, \ - rows {}..{}, cols {}..{}, first 8 {:?}", - bad.len(), - rows.iter().min().copied().unwrap_or(0), - rows.iter().max().copied().unwrap_or(0), - cols.iter().min().copied().unwrap_or(0), - cols.iter().max().copied().unwrap_or(0), - bad.iter().take(8).map(|i| (i / w, i % w)).collect::>(), - ); panic!( "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \ {got}, the encoder reconstructed {want}" diff --git a/crates/ec-av1/src/filter_search.rs b/crates/ec-av1/src/filter_search.rs index 0e398bae..828c6e7a 100644 --- a/crates/ec-av1/src/filter_search.rs +++ b/crates/ec-av1/src/filter_search.rs @@ -48,6 +48,18 @@ thread_local! { const { std::cell::RefCell::new(Vec::new()) }; } +/// lane-edge128: 64x64 CDEF units that took a NON-ZERO preset index from +/// another unit's `cdef_idx` literal -- the units of a whole 128x128 root +/// block, the only shape whose literal covers more than one unit. Zero makes +/// any witness for that rule vacuous (class `gate-blind-to-feature`). +static CDEF_COVERED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Takes and clears [`CDEF_COVERED`]. +#[allow(dead_code)] // read from the `#[cfg(test)]` witness +pub(crate) fn take_cdef_covered_units() -> usize { + CDEF_COVERED.swap(0, std::sync::atomic::Ordering::Relaxed) +} + /// Takes and clears [`PRESET_COUNTS`]. #[allow(dead_code)] // read from the `#[cfg(test)]` BD gate pub(crate) fn take_cdef_presets() -> Vec<(u8, Vec)> { @@ -203,6 +215,12 @@ pub(crate) fn pick_filters( damping: u8, (sb_cols, sb_rows): (usize, usize), lambda: f64, + // lane-edge128: which unit's `cdef_idx` literal covers each 64x64 unit + // (`crate::tile::cdef_unit_owner`). A unit covered by ANOTHER unit's + // literal -- the four units of a whole 128x128 root block -- cannot be + // given a preset of its own, so its error is scored into its owner's and + // it takes its owner's index. Empty means the identity map. + cdef_owner: &[u32], ) -> Result<(LoopFilterParams, CdefParams, Vec, Picture)> { let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); let nsb = sb_cols * sb_rows; @@ -252,11 +270,19 @@ pub(crate) fn pick_filters( st.chroma.push((ckey, (sse, units))); } drop(sst); - let (sse_y, sse_uv, sse64) = { + let (sse_y, sse_uv, mut sse64): (u64, u64, Vec) = { let l = &st.luma.iter().find(|(k, _)| *k == lkey).expect("just inserted").1; let c = &st.chroma.iter().find(|(k, _)| *k == ckey).expect("just inserted").1; (l.0, c.0, l.1.iter().zip(&c.1).map(|(a, b)| a + b).collect()) }; + // A unit that codes no literal of its own carries its error into the + // one that does, so every choice below is made per GROUP. + for (u, &owner) in cdef_owner.iter().enumerate() { + if owner as usize != u { + sse64[owner as usize] += sse64[u]; + sse64[u] = 0; + } + } st.trials.push(Trial { cand, picture, sse_y, sse_uv, sse64 }); Ok(st.trials.len() - 1) }; @@ -382,7 +408,7 @@ pub(crate) fn pick_filters( bits = b; } } - let grid: Vec = if bits == 0 { + let mut grid: Vec = if bits == 0 { Vec::new() } else { let n = 1usize << bits; @@ -394,6 +420,17 @@ pub(crate) fn pick_filters( }) .collect() }; + // The covered units scored zero above, so they would all read preset 0 + // here: give them the index their owner's literal actually carries. + if !grid.is_empty() { + for u in 0..nsb { + let owner = cdef_owner.get(u).map_or(u, |&o| o as usize); + if owner != u && grid[owner] != 0 { + CDEF_COVERED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + grid[u] = grid[owner]; + } + } let mut params = cdef(best, damping); params.bits = bits; for (i, c) in presets.iter().take(1usize << bits).enumerate() { diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index a935fd4e..86081a95 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -669,6 +669,44 @@ impl TileLayout { } } +/// lane-edge128: which 64x64 CDEF unit's `cdef_idx` literal covers each unit +/// of this frame, in the same raster order [`arm_cdef_idx`]'s grid is in. +/// +/// `read_cdef` (spec 5.11.56) codes ONE literal for the block that first +/// reaches a unit and copies it over every unit that block SPANS, so a whole +/// 128x128 root block puts one literal in the stream for all four of its +/// units -- the encoder's CDEF search, which prices a preset per unit, may +/// not hand those four units different presets: only the first would be +/// coded, and every decoder (ours and ffmpeg's alike) would apply it to all +/// four while the encoder's own filter replay applied four different ones. +/// That is the shape this map exists to collapse +/// ([`crate::filter_search::pick_filters`]). +/// +/// Identity everywhere else: every block this writer codes at 64x64 or below +/// covers exactly one unit. +pub(crate) fn cdef_unit_owner(blocks: &[Quadrant], mi_cols: u32, mi_rows: u32) -> Vec { + let (cols, rows) = block_grid(mi_cols, mi_rows); + let (sb_cols, sb_rows) = (cols.div_ceil(2) as usize, rows.div_ceil(2) as usize); + let mut owner: Vec = (0..(sb_cols * sb_rows) as u32).collect(); + for sb_r in (0..sb_rows).step_by(2) { + for sb_c in (0..sb_cols).step_by(2) { + let root = ((sb_r * 2) < rows as usize && (sb_c * 2) < cols as usize) + .then(|| &blocks[(sb_r * 2) * cols as usize + sb_c * 2]) + .is_some_and(|q| matches!(q, Quadrant::Whole128(_))); + if !root { + continue; + } + let origin = (sb_r * sb_cols + sb_c) as u32; + for r in sb_r..(sb_r + 2).min(sb_rows) { + for c in sb_c..(sb_c + 2).min(sb_cols) { + owner[r * sb_cols + c] = origin; + } + } + } + } + owner +} + /// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]). struct CdefIdxPlan { /// The header's `cdef_bits`; never 0 while armed. diff --git a/lanes/edge128.report.md b/lanes/edge128.report.md new file mode 100644 index 00000000..91d05a3a --- /dev/null +++ b/lanes/edge128.report.md @@ -0,0 +1,167 @@ +# lane-edge128 — the 8-sample diff at the 128 superblock's edge + +The charter's premise was that reader and writer shared a wrong assumption +about something read per 64x64 unit under a 128 block (deblock levels, tx +sizes, skip, `delta_lf`, LR). **They do not.** The bitstream was always +right: on the exact stream that fails, ffmpeg's decode and this crate's +`decode_stream` are byte-identical over all 12 frames and all three planes. +What disagreed with both of them is the ENCODER's own reconstruction — the +picture the next frame predicts from — and the stage is CDEF, on the +encoder's side of it alone. + +## 1. Reproduced + +`bd_rate_screen_native` with `EC_AV1_B128RES=1 EC_AV1_NATIVE_FILM4K=1`: + + B128R MISMATCH bars 2160p q=90 frame 11 plane Y: 8 samples, + rows 126..127, cols 1611..1616 + panicked: sample 243531: ffmpeg decoded 106, the encoder reconstructed 107 + +The gate's own q=90 stream (dumped from the failing run) is **byte-identical** +to the one `enc_probe` writes for that row (411920 bytes, `fnv1a +d36717e86823f28f`), so the defect reproduces outside the gate. Decoding that +stream two ways: + +| pair | differing samples, frame 11 | +|---|---| +| ffmpeg vs `decode_stream` | **0** (and 0 over the whole 12-frame sequence) | +| encoder reconstruction vs either decoder | **710** — Y 8, U 9, V 693 | + +The luma 8 the gate reports are the visible corner of a 710-sample block: +V rows 0..63 cols 801..815 and U rows 62..63 cols 802..809 in chroma +samples, i.e. **luma columns 1600..1663 of the 128x128 superblock at columns +1536..1663** — the RIGHT half of one 128 superblock, its whole height. Not a +band along an edge: two whole 64x64 CDEF units. + +## 2. The first divergent stage, and the rule + +There is no divergent DECODE stage — the pre-filter, post-deblock and +post-CDEF planes are moot when both decoders agree byte for byte with each +other. The divergence is between the stream and the encoder's +`Encoded::reconstruction`, which is not a decode of the final tile at all: +`pick_and_apply_filters` gets it from `crate::decode::replay_final`, a +replay of deblock+CDEF over the captured pre-filter planes driven by the +CDEF search's own per-64x64 `idx_grid`. + +**The rule the encoder broke** — `read_cdef`, spec 5.11.56: + + cdefSize4 = Num_4x4_Blocks_Wide[BLOCK_64X64] + r = MiRow & ~(cdefSize4-1); c = MiCol & ~(cdefSize4-1) + if (cdef_idx[r][c] == -1) { + cdef_idx[r][c] = L(cdef_bits) + for (i = r; i < r + h4; i += cdefSize4) + for (j = c; j < c + w4; j += cdefSize4) + cdef_idx[i][j] = cdef_idx[r][c] // every unit the BLOCK spans + } + +One literal per block, copied over every 64x64 unit that block spans. A +whole 128x128 root block therefore puts **one** `cdef_idx` in the stream for +all **four** of its units — which is exactly what `tile::write_cdef_idx` +writes (one literal per superblock, at the first non-skip block) and exactly +what `decode::maybe_read_cdef_idx` reads back since lane-b128r stamped the +block's mi span. Both are right. + +`filter_search::pick_filters` priced a preset per 64x64 unit and handed all +four to the replay. Only the origin unit's index reached the tile, so every +decoder filtered the other three with the origin's strengths while the +encoder's reconstruction carried three other strength pairs. Frame 11 is +where the residual 128 root and a per-unit `cdef_idx` list finally met. + +**Class: `plan finer than its syntax`** — an encoder-side per-unit plan for +a parameter the bitstream can only carry once per block. It is invisible to +every stream-level gate (the stream is legal and decodes identically +everywhere); it surfaces only where the encoder's reconstruction is compared +against a decoder's, and then as a reference-chain error, not a syntax one. + +## 3. The fix (one shared map, both consumers) + +`tile::cdef_unit_owner(blocks, mi_cols, mi_rows)` maps each 64x64 unit to +the unit whose literal covers it — identity for every block of one unit or +less, and the root's top-left unit for the four units of a `Whole128` root. +`pick_filters` takes it and decides per GROUP: a covered unit's per-unit SSE +is summed into its owner's before the preset histogram and the `cdef_bits` +cost are read off it, and after the grid is built each covered unit takes +its owner's index. The identity map (`&[]`, the key-frame path, which has no +128 root) is the behaviour this function always had. + +The map is built where the coded blocks are (`encode_inter_frame`) and +travels through `pick_and_apply_filters` to the search, so the writer's +`recode` and the encoder's filter replay read the same indices a decoder +does. + +## 4. Same-shape sweep — every per-64x64-unit plan under a 128 block + +Three writer-side plans are keyed per 64x64 unit; the sweep is all three: + +| plan | state | +|---|---| +| `cdef_idx` (`arm_cdef_idx`) | **the defect, fixed here** | +| `delta_q` (`arm_delta_q`) | already correct: `write_delta_q` gates on the 128-wide superblock (lane-b128m) AND `encode_inter_frame` collapses `sb_q` to the root's top-left cell before the search quantizes with it — the same shape, closed one lane earlier | +| loop restoration (`arm_lr`) | not per-64 at all: `lr_unit()` is 128 under `EC_AV1_SB128`, `write_lr` writes it once at the root, and `pick_restoration` builds its grid from the same `lr_unit()` | + +The reads the charter suspected — deblock filter levels, the tx-size lookup +for a TX_64X64 unit inside a 128 block, `delta_lf`, the per-unit CDEF skip +decision — are all in the DECODER, which the encoder runs verbatim as its +own filter stage, so reader and writer cannot disagree there by +construction; and ffmpeg agreeing with `decode_stream` sample for sample on +this exact stream clears them empirically as well. + +## 5. Witness + +`encode::tests::a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact` +(`--ignored`, 128 superblocks + the 128 root + its residual arm forced), +`testsrc2` 1280x768, 12 frames, q=90: + + 128x128 blocks WITH a residual: writer coded 1440; + 64x64 CDEF units taking another unit's literal: 168 + test ... ok + +Both readers, every frame, every plane: `decode_stream` and ffmpeg against +the encoder's own reconstruction. `take_cdef_covered_units` is the gate on +the fixture (class `gate-blind-to-feature`): a clip whose CDEF spends one +strength pair codes no literal and would witness nothing. + +**RED before the fix** (collapse disabled on this same tree, everything else +identical): + + assertion `left == right` failed: frame 1: U -- 521 samples differ + +## 6. The residual arm, re-measured with the fix + +`bd_rate_screen_native`, 12 frames, `EC_AV1_B128RES=1` (control = the +standing table, i.e. the arm off): + +| row | control | + the residual arm, fixed | +|---|---|---| +| bars 2160p | +8.6 / −13.7 | +8.6 / −13.7 | +| film B (2160p) | +23.6 / −3.1 | +23.4 / −3.2 | + +This is the first COMPLETE measurement of the arm — before the fix the row +panicked instead of finishing. It stays **behind `EC_AV1_B128RES=1`**: the +arm is still inert on content (0–2 blocks per frame against ~90 whole 128 +roots) and the two rows are inside the flat band. What the lane buys is not +the arm; it is that the encoder's reconstruction is no longer a filter apart +from what a decoder produces the moment a 128 root carries a residual. + +**The default encoder is byte-identical**: both pins hold at default and at +`EC_AV1_SPEED=6`. They must — a default 128 root is always skipped, CDEF +does not filter a unit whose blocks are all skip, and the fold it now goes +through adds candidate-independent constants that cannot move an argmin. + +## 7. Suite / checks + + s1 --skip stream:: 344 passed; 0 failed; 38 ignored RC=0 + s2 stream:: --skip 10bit 202 passed; 0 failed; 15 ignored RC=0 + s3 10bit 42 passed; 0 failed; 1 ignored RC=0 + --ignored every_speed_preset_decodes_sample_exact_through_both_decoders ok + --ignored a_128_root_residual_block_under_a_per_unit_cdef_list... ok (1440 blocks, 168 covered units) + --ignored a_128_superblock_clip_whose_root_search... ok + --ignored a_128_root_block_with_a_real_residual... ok + --ignored a_128_root_compound_block... ok + the_encoders_own_streams_are_byte_identical_to_their_pins ok, and ok at EC_AV1_SPEED=6 + cargo check --workspace --all-targets -j4 0 errors, 0 ec-av1 warnings + +## Pins + +NOT re-taken: 8364 / 33257 stand, at default and at `EC_AV1_SPEED=6`. The +fix cannot reach a default stream (see §6).