forge
Explore
Log in

Don't you dare go Hollow

vp9kf: real-content sweep -- SB-padded plane buffers, honest Picture strides, and the desync it found

Browse files at this commit

3678cfd9d3c1ede06427297ef16378fa506ef65bAhmet Kaan GümüşParent: 0f31b1d
Adds crates/ec-vp9/tests/scratch_realsweep.rs (all-intra VP9 transcode of a real
video, ours vs ffmpeg, per-frame diff counts) and scratch_tiledbg.rs. The
library holds no VP9 content of its own, so this is the first time the keyframe
path has seen real imagery - and it is NOT byte-exact: a real 320x240 frame is
exact for rows 0-127 and wrong from row 128 down (19477/15337 diffs), i.e. the
entropy decoder diverges at a block in SB row 2. "Byte-exact" was
fixture-exact.

Two real defects fixed (fixture suite re-verified green, 17 binaries):

1. Plane buffers were 8-aligned; libvpx decodes an edge block at full size and
   lets the overhang land in the frame border (decodeframe.c:1216). A 32x32
   block at mi_row 132 of a 1080-row frame wrote 8 rows past the buffer and
   panicked at intra.rs:380. Buffers are now SB-aligned, and filter_frame gets
   the MI-aligned visible extent (the padded size OOB'd the level grid).
2. Picture::stride/uv_stride reported the aligned aw while the crop packs rows;
   a consumer trusting stride misread any non-64-aligned width. Now width/2.

Reported, not fixed: multi-tile frames (ffmpeg's default at 1080p) refuse with
'Corrupt: truncated tile data' - either the tile walk or the tile-data offset
is wrong for >1 tile, and 'corrupt' is the wrong claim until that is known.
lanes/vp9kf.report.md carries the table, the next-lane charter seed, and a note
that the fixture recipes were never recorded.
crates/ec-vp9/src/decode.rsmodified+27 -24
@@ -9,15 +9,15 @@
9 //! returns the buffered reference picture instead of pretending to9 //! returns the buffered reference picture instead of pretending to
10 //! decode.10 //! decode.
11 11
12-use crate::header::{read_compressed_header, FrameContext};12+use crate::header::{FrameContext, read_compressed_header};
13 use crate::intra::build_intra_predictors;13 use crate::intra::build_intra_predictors;
14 use crate::loopfilter::LfGrids;14 use crate::loopfilter::LfGrids;
15-use crate::modes::{read_intra_frame_mode_info, MiInfo, MiState};15+use crate::modes::{MiInfo, MiState, read_intra_frame_mode_info};
16 use crate::tables::*;16 use crate::tables::*;
17-use crate::tokens::{decode_coefs, scan_for, PlaneContexts};17+use crate::tokens::{PlaneContexts, decode_coefs, scan_for};
18 use crate::transform::inverse_transform_add;18 use crate::transform::inverse_transform_add;
19 use crate::{Error, Result};19 use crate::{Error, Result};
20-use ec_vp9_syntax::{superframe, FrameHeader, FrameType, Vp9Parser};20+use ec_vp9_syntax::{FrameHeader, FrameType, Vp9Parser, superframe};
21 21
22 const SB_MI: usize = 8; // a 64x64 superblock in mi (8x8) units22 const SB_MI: usize = 8; // a 64x64 superblock in mi (8x8) units
23 23
@@ -34,9 +34,9 @@ pub struct Picture {
34 pub width: u16,34 pub width: u16,
35 /// Frame height in pixels.35 /// Frame height in pixels.
36 pub height: u16,36 pub height: u16,
37- /// Luma row pitch of the returned planes.37+ /// Luma row pitch of the returned planes (== `width`; the crop packs rows).
38 pub stride: usize,38 pub stride: usize,
39- /// Chroma row pitch of the returned planes.39+ /// Chroma row pitch of the returned planes (== `width / 2`).
40 pub uv_stride: usize,40 pub uv_stride: usize,
41 }41 }
42 42
@@ -164,8 +164,14 @@ impl Decoder {
164 fn decode_keyframe(&mut self, hdr: &FrameHeader, frame: &[u8], tx_mode: u8) -> Result<Picture> {164 fn decode_keyframe(&mut self, hdr: &FrameHeader, frame: &[u8], tx_mode: u8) -> Result<Picture> {
165 let width = hdr.width as usize;165 let width = hdr.width as usize;
166 let height = hdr.height as usize;166 let height = hdr.height as usize;
167- let aw = width.div_ceil(8) * 8;167+ // The decode buffer is padded to whole superblocks: libvpx decodes a
168- let ah = height.div_ceil(8) * 8;168+ // block at the frame edge at its FULL size (decodeframe.c:1216,
169+ // `PARTITION_NONE` needs only `mi_row < mi_rows`) and writes the
170+ // overhang into the frame buffer's border. Clipping to 8 pixels
171+ // instead panicked on real 1080p content (a 32x32 block starting at
172+ // mi_row 132 writes 8 rows past a 1080-row buffer).
173+ let aw = width.div_ceil(64) * 64;
174+ let ah = height.div_ceil(64) * 64;
169 self.planes = Some(Planes {175 self.planes = Some(Planes {
170 y: vec![128u8; aw * ah],176 y: vec![128u8; aw * ah],
171 u: vec![128u8; aw / 2 * ah / 2],177 u: vec![128u8; aw / 2 * ah / 2],
@@ -290,18 +296,21 @@ impl Decoder {
290 }296 }
291 297
292 // Loop filter post-pass (level 0 disables it for the frame).298 // Loop filter post-pass (level 0 disables it for the frame).
299+ // The extents are the MI-aligned VISIBLE plane (libvpx's masks clear
300+ // everything past `mi_cols`/`mi_rows`), not the padded buffer size.
293 if hdr.loop_filter.level > 0 && std::env::var_os("EC_VP9_SKIP_LF").is_none() {301 if hdr.loop_filter.level > 0 && std::env::var_os("EC_VP9_SKIP_LF").is_none() {
294 let p = self.planes.as_mut().expect("frame scratch");302 let p = self.planes.as_mut().expect("frame scratch");
303+ let (vw, vh) = (mi_cols * 8, mi_rows * 8);
295 grids.filter_frame(304 grids.filter_frame(
296 &mut p.y,305 &mut p.y,
297 p.ys,306 p.ys,
298 &mut p.u,307 &mut p.u,
299 &mut p.v,308 &mut p.v,
300 p.uvs,309 p.uvs,
301- aw,310+ vw,
302- ah,311+ vh,
303- aw / 2,312+ vw / 2,
304- ah / 2,313+ vh / 2,
305 hdr.loop_filter.sharpness,314 hdr.loop_filter.sharpness,
306 );315 );
307 }316 }
@@ -320,8 +329,10 @@ impl Decoder {
320 v: crop(&planes.v, planes.uvs, width / 2, height / 2),329 v: crop(&planes.v, planes.uvs, width / 2, height / 2),
321 width: width as u16,330 width: width as u16,
322 height: height as u16,331 height: height as u16,
323- stride: aw,332+ // The crop above packs rows: `stride` describes the RETURNED
324- uv_stride: aw / 2,333+ // buffers, not the aligned decode buffer (`aw`).
334+ stride: width,
335+ uv_stride: width / 2,
325 })336 })
326 }337 }
327 338
@@ -360,17 +371,9 @@ impl Decoder {
360 if has_rows && has_cols {371 if has_rows && has_cols {
361 r.read_tree(&PARTITION_TREE, probs)372 r.read_tree(&PARTITION_TREE, probs)
362 } else if !has_rows && has_cols {373 } else if !has_rows && has_cols {
363- if r.read_bool(probs[1]) {374+ if r.read_bool(probs[1]) { 3 } else { 1 }
364- 3
365- } else {
366- 1
367- }
368 } else if has_rows && !has_cols {375 } else if has_rows && !has_cols {
369- if r.read_bool(probs[2]) {376+ if r.read_bool(probs[2]) { 3 } else { 2 }
370- 3
371- } else {
372- 2
373- }
374 } else {377 } else {
375 3378 3
376 }379 }
crates/ec-vp9/tests/scratch_realsweep.rsadded+134 -0
@@ -0,0 +1,134 @@
1+//! [scratch] Real-content keyframe sweep.
2+//!
3+//! The library carries no VP9 content of its own (its one webm, in
4+//! `~/Downloads`, is VP8), so the keyframe path only ever sees real imagery
5+//! through a transcode: encode `SWEEP_SRC` as all-intra VP9 with ffmpeg
6+//! (`-g 1`, so every frame is a keyframe), decode every frame with `ec-vp9`,
7+//! and diff Y/U/V against ffmpeg's own decode of the same file.
8+//!
9+//! ```text
10+//! SWEEP_SRC=<video> [SWEEP_N=<frames>] \
11+//! cargo test -p ec-vp9 --test scratch_realsweep -- --nocapture
12+//! ```
13+//!
14+//! Prints one line per frame plus a `RESULT` line; fails if any frame differs.
15+mod ivf;
16+
17+use ec_vp9::decode::Decoder;
18+
19+#[test]
20+fn real_content_sweep() {
21+ let src = std::env::var("SWEEP_SRC").unwrap_or_default();
22+ let prebuilt = std::env::var("SWEEP_IVF").ok();
23+ if src.is_empty() && prebuilt.is_none() {
24+ println!("SKIP: set SWEEP_SRC=<video> [SWEEP_N=<frames>] or SWEEP_IVF=<ivf>");
25+ return;
26+ }
27+ let n: usize = std::env::var("SWEEP_N")
28+ .ok()
29+ .and_then(|v| v.parse().ok())
30+ .unwrap_or(3);
31+ let dir = std::env::temp_dir().join("ec-vp9-sweep");
32+ std::fs::create_dir_all(&dir).unwrap();
33+ let ivf_path = dir.join("allintra.ivf");
34+ if let Some(p) = &prebuilt {
35+ std::fs::copy(p, &ivf_path).unwrap();
36+ } else {
37+ let enc = std::process::Command::new("ffmpeg")
38+ .args(["-v", "error", "-y", "-i", &src, "-frames:v"])
39+ .arg(n.to_string())
40+ .args([
41+ "-c:v",
42+ "libvpx-vp9",
43+ "-g",
44+ "1",
45+ "-deadline",
46+ "good",
47+ "-cpu-used",
48+ "4",
49+ "-crf",
50+ "32",
51+ "-pix_fmt",
52+ "yuv420p",
53+ ])
54+ // `SWEEP_TILE0=1` pins a single tile: the multi-tile path is what
55+ // ffmpeg picks by default at 1080p+ and it is diagnosed separately.
56+ .args(if std::env::var_os("SWEEP_TILE0").is_some() {
57+ vec!["-tile-columns", "0", "-tile-rows", "0"]
58+ } else {
59+ vec![]
60+ })
61+ .args(["-f", "ivf"])
62+ .arg(&ivf_path)
63+ .status()
64+ .expect("ffmpeg encode");
65+ assert!(enc.success(), "ffmpeg encode of {src} failed");
66+ }
67+ // Decode list as a human would, to prove our YUV probe is honest.
68+ let raw = std::process::Command::new("ffmpeg")
69+ .args(["-v", "error", "-i"])
70+ .arg(&ivf_path)
71+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
72+ .output()
73+ .expect("ffmpeg decode");
74+ assert!(raw.status.success(), "ffmpeg decode of the IVF failed");
75+
76+ let bytes = std::fs::read(&ivf_path).unwrap();
77+ let (_fourcc, w, h, frames) = ivf::parse_ivf(&bytes);
78+ let (w, h) = (w as usize, h as usize);
79+ let ysz = w * h;
80+ let uvs = (w / 2) * (h / 2);
81+ assert_eq!(
82+ raw.stdout.len(),
83+ frames.len() * (ysz + 2 * uvs),
84+ "reference frame size mismatch"
85+ );
86+
87+ let mut bad = 0usize;
88+ for (i, frame) in frames.iter().enumerate() {
89+ let mut dec = Decoder::new();
90+ let pic = match dec.decode(&frame.data) {
91+ Ok(Some(p)) => p,
92+ other => {
93+ println!("frame {i}: DECODE REFUSED/ERR {other:?}");
94+ bad += 1;
95+ continue;
96+ }
97+ };
98+ let base = i * (ysz + 2 * uvs);
99+ if i == 0 {
100+ std::fs::write(dir.join("ours_f0.yuv"), {
101+ let mut v = Vec::with_capacity(ysz + 2 * uvs);
102+ v.extend_from_slice(&pic.y[..ysz.min(pic.y.len())]);
103+ v.extend_from_slice(&pic.u);
104+ v.extend_from_slice(&pic.v);
105+ v
106+ })
107+ .unwrap();
108+ std::fs::write(dir.join("ff_f0.yuv"), &raw.stdout[..ysz + 2 * uvs]).unwrap();
109+ }
110+ let yd = (0..ysz)
111+ .filter(|&k| pic.y[k] != raw.stdout[base + k])
112+ .count();
113+ let ud = (0..uvs)
114+ .filter(|&k| pic.u[k] != raw.stdout[base + ysz + k])
115+ .count();
116+ let vd = (0..uvs)
117+ .filter(|&k| pic.v[k] != raw.stdout[base + ysz + uvs + k])
118+ .count();
119+ println!(
120+ "frame {i}: {w}x{h} stride {} uv_stride {} Y {yd} U {ud} V {vd}",
121+ pic.stride, pic.uv_stride
122+ );
123+ if yd + ud + vd > 0 {
124+ bad += 1;
125+ }
126+ }
127+ println!(
128+ "RESULT {} of {} frames byte-exact (source {})",
129+ frames.len() - bad,
130+ frames.len(),
131+ if src.is_empty() { ivf_path.display().to_string() } else { src.clone() }
132+ );
133+ assert_eq!(bad, 0, "{bad} frame(s) differ from ffmpeg");
134+}
crates/ec-vp9/tests/scratch_tiledbg.rsadded+51 -0
@@ -0,0 +1,51 @@
1+//! [scratch] Tile-layout diagnosis for a VP9 IVF: print the parsed header
2+//! sizes and the tile size prefixes at the header's end.
3+//! `TILE_SRC=<ivf> cargo test -p ec-vp9 --test scratch_tiledbg -- --nocapture`
4+mod ivf;
5+
6+use ec_vp9_syntax::Vp9Parser;
7+
8+#[test]
9+fn tile_dbg() {
10+ let Ok(src) = std::env::var("TILE_SRC") else {
11+ println!("SKIP: set TILE_SRC=<ivf>");
12+ return;
13+ };
14+ let bytes = std::fs::read(&src).unwrap();
15+ let (_f, w, h, frames) = ivf::parse_ivf(&bytes);
16+ println!("ivf {w}x{h} frames {}", frames.len());
17+ for (i, fr) in frames.iter().enumerate().take(2) {
18+ let mut p = Vp9Parser::new();
19+ match p.parse_frame(&fr.data) {
20+ Ok(hdr) => {
21+ // Tile data starts after BOTH headers (libvpx: `data +=
22+ // vpx_rb_bytes_read(&rb)` then the compressed header).
23+ let off = hdr.uncompressed_header_size as usize + hdr.header_size_in_bytes as usize;
24+ println!(
25+ "frame {i}: len {} uhs {} hsib {} tile cols {} rows {} mi {}x{}",
26+ fr.data.len(),
27+ hdr.uncompressed_header_size,
28+ hdr.header_size_in_bytes,
29+ hdr.tile_info.cols_log2,
30+ hdr.tile_info.rows_log2,
31+ hdr.mi_cols(),
32+ hdr.mi_rows()
33+ );
34+ let tail = &fr.data[off..];
35+ println!(
36+ " tail len {} first16 {:?}",
37+ tail.len(),
38+ &tail[..16.min(tail.len())]
39+ );
40+ if tail.len() >= 4 {
41+ let sz = u32::from_le_bytes(tail[..4].try_into().unwrap()) as usize;
42+ println!(
43+ " first tile size prefix {sz} (tail-4 = {})",
44+ tail.len() - 4
45+ );
46+ }
47+ }
48+ Err(e) => println!("frame {i}: parse ERR {e}"),
49+ }
50+ }
51+}
lanes/vp9kf.report.mdmodified+55 -0
@@ -455,3 +455,58 @@ commands are the charter's ffmpeg invocations.
455 - **non-420 / high-bitdepth / profiles 1 and 3** (only profile 0 8-bit is ported);455 - **non-420 / high-bitdepth / profiles 1 and 3** (only profile 0 8-bit is ported);
456 - the 12 trace hooks and 10 `scratch_*` harnesses from HANDOFF #8's "not cleaned up"456 - the 12 trace hooks and 10 `scratch_*` harnesses from HANDOFF #8's "not cleaned up"
457 list, if a future lane wants a bare tree.457 list, if a future lane wants a bare tree.
458+
459+## OPEN DEFECT LANE (2026-09-16) — the fixtures were too weak: real content desyncs mid-frame
460+
461+Found by sweeping REAL content through the merged decoder
462+(`crates/ec-vp9/tests/scratch_realsweep.rs`, added here). The library has **no VP9
463+content at all** (the only webm under `~/Downloads` is VP8), so the sweep encodes an
464+all-intra VP9 (`-g 1`, every frame a keyframe) from a real file and diffs Y/U/V against
465+ffmpeg's decode of the same IVF.
466+
467+| source (real, 3 frames, all-intra) | result |
468+|---|---|
469+| `~/Downloads/reelk.mp4` 1920x1080, default tiles | REFUSED (`truncated tile data`, see below) |
470+| same, `-tile-columns 0 -tile-rows 0` | PANICKED at `intra.rs:380` before the buffer fix; now decodes but **Y differs in 1.8M/2.07M px** |
471+| `~/Videos/reela.mp4` 3840x1608 | REFUSED (same) |
472+| `~/Downloads/reelj.mp4` 576x1024 | REFUSED (same) |
473+| real 320x240 (`scale=320:240`, same encoder) | **rows 0-127 exact, rows 128+ garbage** |
474+
475+The 320x240 case is the sharp one: **the first two superblock rows are byte-exact and
476+every row from 128 down is wrong** (0 diffs for rows 0-127, 19477 for 128-191, 15337 for
477+192-239). Same for 1080p — the rendered frame shows the true image at the top and a
478+blocky mess below. A desync that leaves a clean SB-row boundary means the entropy
479+decoder diverged at a block in SB row 2, so **the fixtures (`key-320.ivf` = testsrc2,
480+`lossless-64.ivf` = testsrc2) never reach the syntax real imagery uses**. Weakening the
481+claim: "byte-exact" is *fixture-exact*; it does not generalise.
482+
483+Two defects were fixed on the way (both real, both verified against the fixture suite):
484+
485+1. **Plane buffers were 8-aligned, not superblock-padded** — libvpx decodes an edge block
486+ at its full size and lets the overhang land in the frame border
487+ (`decodeframe.c:1216`), so a 32x32 block starting at mi_row 132 of a 1080-row frame
488+ wrote 8 rows past the buffer (`intra.rs:380` panic). Buffers are now SB-aligned
489+ (`decode.rs`), and `filter_frame` receives the MI-aligned *visible* extent, not the
490+ padded one (passing the padded size OOB'd the level grid).
491+2. **`Picture::stride`/`uv_stride` lied** — the crop packs rows (`width` per row) but the
492+ fields reported the aligned `aw`; a consumer reading with `stride` would misread any
493+ frame whose width is not 64-aligned. Now `width` / `width / 2`.
494+
495+Third finding, not fixed: **multi-tile frames fail with a wrong message**. Default
496+ffmpeg tiles at 1080p (`cols_log2 == 2`), and the decoder reports
497+`Corrupt: truncated tile data` — the tile-size prefix it reads at
498+`uhs + header_size_in_bytes` is implausible. Either the tile walk or the tile-data offset
499+is wrong for >1 tile; "corrupt" is the wrong claim until that is known.
500+
501+### Next lane charter seed (in priority order)
502+
503+1. Localize the real-content desync with the existing oracle (`/tmp/vp9loss/drv` +
504+ `scratch_lfdump`-style dumps): first differing block, then mode/tx/coef trace. Start
505+ with the 320x240 real frame — SB row 2, mi_row 16.
506+2. Multi-tile: decide whether the offset or the walk is wrong; if multi-tile is genuinely
507+ unsupported, say so in the error instead of "corrupt".
508+3. Re-record the fixture recipes (they are not in this report): the two `ffmpeg` commands
509+ that generated `fixtures/vp9/*.ivf` must be written down next to a real-content
510+ fixture, otherwise "byte-exact" keeps meaning "testsrc2-exact".
511+
512+`scratch_tiledbg.rs` (header/tile-offset dump) is the companion probe.