forge
Explore
Log in

Don't you dare go Hollow

vp9kf: libvpx-1.15 marker bit, lossless ONLY_4X4 header, tile-info rows/cols bounds, tx-row left-ctx fix; oracle-diff HANDOFF #3

Browse files at this commit

76c8a7751336d7967f2567f17dda6a6316cf1cc1Ahmet Kaan GümüşParent: c445467
crates/ec-vp9-syntax/src/header.rsmodified+8 -7
@@ -893,15 +893,14 @@ fn read_tile_info(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
893 break;893 break;
894 }894 }
895 }895 }
896- let sb64_rows = h.mi_rows().div_ceil(8);896+ // Rows: one bit always codes whether log2_tile_rows is nonzero, and a
897- let (_, max_log2_rows) = tile_cols_log2_bounds(sb64_rows);897+ // second bit only follows when it is (decodeframe.c `setup_tile_info`:
898+ // `cm->log2_tile_rows = vpx_rb_read_bit(rb);
899+ // if (cm->log2_tile_rows) cm->log2_tile_rows += vpx_rb_read_bit(rb);`).
900+ // This is not a min..max walk like the columns side.
898 let mut rows_log2 = 0u8;901 let mut rows_log2 = 0u8;
899- while rows_log2 < max_log2_rows {
900 if r.read_bit()? {902 if r.read_bit()? {
901- rows_log2 += 1;903+ rows_log2 = 1 + u8::from(r.read_bit()?);
902- } else {
903- break;
904- }
905 }904 }
906 h.tile_info = TileInfo {905 h.tile_info = TileInfo {
907 cols_log2,906 cols_log2,
@@ -927,6 +926,8 @@ fn tile_cols_log2_bounds(sb64_cols: u32) -> (u8, u8) {
927 while (sb64_cols >> max_log2) >= MIN_TILE_WIDTH_B64 {926 while (sb64_cols >> max_log2) >= MIN_TILE_WIDTH_B64 {
928 max_log2 += 1;927 max_log2 += 1;
929 }928 }
929+ // libvpx `get_max_log2_tile_cols` returns max_log2 - 1 (tile_common.c:48).
930+ let max_log2 = max_log2 - 1;
930 (min_log2, max_log2)931 (min_log2, max_log2)
931 }932 }
932 933
crates/ec-vp9/src/bool.rsmodified+18 -5
@@ -13,7 +13,7 @@
13 //! spec's reference encoder (8.3.3, the carry-propagating writer) and13 //! spec's reference encoder (8.3.3, the carry-propagating writer) and
14 //! assert bit-exact round-trips.14 //! assert bit-exact round-trips.
15 15
16-use ec_core::Result;16+use ec_core::{Error, Result};
17 17
18 /// Boolean arithmetic decoder over one data partition (spec 8.3.2).18 /// Boolean arithmetic decoder over one data partition (spec 8.3.2).
19 pub struct BoolDecoder<'a> {19 pub struct BoolDecoder<'a> {
@@ -52,14 +52,23 @@ impl<'a> BoolDecoder<'a> {
52 if data.len() > 1 {52 if data.len() > 1 {
53 value |= u32::from(data[1]);53 value |= u32::from(data[1]);
54 }54 }
55- Ok(Self {55+ let mut dec = Self {
56 data,56 data,
57 pos: data.len().min(2),57 pos: data.len().min(2),
58 range: 255,58 range: 255,
59 value,59 value,
60 bit_count: 0,60 bit_count: 0,
61 overreads: 0,61 overreads: 0,
62- })62+ };
63+ // libvpx 1.15 consumes one marker bit per partition right after the
64+ // initial fill (bitreader.c `vpx_reader_init`:
65+ // `return vpx_read_bit(r) != 0; // marker bit`); the matching writer
66+ // (`vpx_start_encode`) emits a leading 0 bit per partition. A 1 here
67+ // means the partition is not a libvpx bool stream.
68+ if dec.read_bool(128) {
69+ return Err(Error::corrupt("bool decoder marker bit is set"));
70+ }
71+ Ok(dec)
63 }72 }
64 73
65 /// Bytes consumed past the end of the partition, read as zero. Any74 /// Bytes consumed past the end of the partition, read as zero. Any
@@ -171,12 +180,16 @@ struct BoolEncoder {
171 #[cfg(test)]180 #[cfg(test)]
172 impl BoolEncoder {181 impl BoolEncoder {
173 fn new() -> Self {182 fn new() -> Self {
174- Self {183+ let mut e = Self {
175 out: Vec::new(),184 out: Vec::new(),
176 range: 255,185 range: 255,
177 bottom: 0,186 bottom: 0,
178 bit_count: 24,187 bit_count: 24,
179- }188+ };
189+ // `vpx_start_encode` parity: the writer emits a leading 0 bit per
190+ // partition, which the decoder consumes as its marker bit.
191+ e.write_bool(false, 128);
192+ e
180 }193 }
181 194
182 fn add_one_to_output(out: &mut [u8]) {195 fn add_one_to_output(out: &mut [u8]) {
crates/ec-vp9/src/decode.rsmodified+16 -1
@@ -134,10 +134,23 @@ impl Decoder {
134 // A keyframe resets the frame context (spec 7.2) before the134 // A keyframe resets the frame context (spec 7.2) before the
135 // compressed header codes this frame's updates on top.135 // compressed header codes this frame's updates on top.
136 self.ctx = FrameContext::new(hdr.frame_type == FrameType::Key);136 self.ctx = FrameContext::new(hdr.frame_type == FrameType::Key);
137+ // [scratch probe] EC_VP9_FORCE_UH / EC_VP9_FORCE_HSZ: override the
138+ // uncompressed-header size / header_size_in_bytes split for diagnosis.
139+ let hdr = {
140+ let mut h = hdr;
141+ if let Ok(v) = std::env::var("EC_VP9_FORCE_UH") {
142+ h.uncompressed_header_size = v.parse().unwrap_or(h.uncompressed_header_size);
143+ }
144+ if let Ok(v) = std::env::var("EC_VP9_FORCE_HSZ") {
145+ h.header_size_in_bytes = v.parse().unwrap_or(h.header_size_in_bytes);
146+ }
147+ h
148+ };
137 let hdr_start = hdr.uncompressed_header_size as usize;149 let hdr_start = hdr.uncompressed_header_size as usize;
138 let tx_mode = read_compressed_header(150 let tx_mode = read_compressed_header(
139 &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize],151 &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize],
140 &mut self.ctx,152 &mut self.ctx,
153+ hdr.quantization.lossless(),
141 )?;154 )?;
142 155
143 let pic = self.decode_keyframe(&hdr, frame, tx_mode)?;156 let pic = self.decode_keyframe(&hdr, frame, tx_mode)?;
@@ -725,7 +738,7 @@ impl Decoder {
725 let ptype = usize::from(plane != 0);738 let ptype = usize::from(plane != 0);
726 let ax = ((mi_col << 1) >> s) + tx_col;739 let ax = ((mi_col << 1) >> s) + tx_col;
727 let lrows = 32usize >> s;740 let lrows = 32usize >> s;
728- let ay = ((mi_row << 1) >> s) % lrows;741+ let ay = (((mi_row << 1) >> s) + tx_row) % lrows;
729 let ctx_in =742 let ctx_in =
730 usize::from(ectx[plane].above[ax] != 0) + usize::from(ectx[plane].left[ay] != 0);743 usize::from(ectx[plane].above[ax] != 0) + usize::from(ectx[plane].left[ay] != 0);
731 let coef = decode_coefs(744 let coef = decode_coefs(
@@ -737,6 +750,8 @@ impl Decoder {
737 scan,750 scan,
738 nb,751 nb,
739 &self.ctx.coef[tx_size],752 &self.ctx.coef[tx_size],
753+ (x0, y0),
754+ plane,
740 );755 );
741 756
742 // 3. Context write-back (vp9_decode_block_tokens, v1.15 shifts).757 // 3. Context write-back (vp9_decode_block_tokens, v1.15 shifts).
crates/ec-vp9/src/header.rsmodified+14 -2
@@ -161,9 +161,21 @@ fn read_tx_mode(r: &mut BoolDecoder) -> u8 {
161 161
162 /// `read_compressed_header` for intra frames (the inter branch is dead162 /// `read_compressed_header` for intra frames (the inter branch is dead
163 /// in this lane): tx mode, tx probs, coef probs, skip probs.163 /// in this lane): tx mode, tx probs, coef probs, skip probs.
164-pub(crate) fn read_compressed_header(data: &[u8], ctx: &mut FrameContext) -> crate::Result<u8> {164+///
165+/// Lossless forces `ONLY_4X4` and consumes no tx-mode bits — decodeframe.c
166+/// `read_compressed_header`: `cm->tx_mode = xd->lossless ? ONLY_4X4 :
167+/// read_tx_mode(&r);`.
168+pub(crate) fn read_compressed_header(
169+ data: &[u8],
170+ ctx: &mut FrameContext,
171+ lossless: bool,
172+) -> crate::Result<u8> {
165 let mut r = BoolDecoder::new(data)?;173 let mut r = BoolDecoder::new(data)?;
166- let tx_mode = read_tx_mode(&mut r);174+ let tx_mode = if lossless {
175+ ONLY_4X4
176+ } else {
177+ read_tx_mode(&mut r)
178+ };
167 if tx_mode == TX_MODE_SELECT {179 if tx_mode == TX_MODE_SELECT {
168 for row in 0..2 {180 for row in 0..2 {
169 for j in 0..1 {181 for j in 0..1 {
crates/ec-vp9/src/tables/mod.rsmodified+1 -0
@@ -31,6 +31,7 @@ pub(crate) const ADST_ADST: usize = 3;
31 pub(crate) const BLOCK_INVALID: u8 = 255;31 pub(crate) const BLOCK_INVALID: u8 = 255;
32 32
33 // spec 5.3 (TX_MODE)33 // spec 5.3 (TX_MODE)
34+pub(crate) const ONLY_4X4: u8 = 0;
34 pub(crate) const TX_MODE_SELECT: u8 = 4;35 pub(crate) const TX_MODE_SELECT: u8 = 4;
35 /// decodeframe.c `tx_mode_to_biggest_tx_size`.36 /// decodeframe.c `tx_mode_to_biggest_tx_size`.
36 pub(crate) const TX_MODE_TO_BIGGEST_TX_SIZE: [usize; 5] =37 pub(crate) const TX_MODE_TO_BIGGEST_TX_SIZE: [usize; 5] =
crates/ec-vp9/src/tokens.rsmodified+4 -2
@@ -61,6 +61,8 @@ pub(crate) fn decode_coefs(
61 scan: &[i16],61 scan: &[i16],
62 nb: &[i16],62 nb: &[i16],
63 probs4d: &[[[[[u8; 3]; 6]; 6]; 2]; 2],63 probs4d: &[[[[[u8; 3]; 6]; 6]; 2]; 2],
64+ #[allow(unused_variables)] pos: (usize, usize),
65+ #[allow(unused_variables)] plane: usize,
64 ) -> CoeffBlock {66 ) -> CoeffBlock {
65 let max_eob = 16 << (tx_size << 1);67 let max_eob = 16 << (tx_size << 1);
66 let mut coef = CoeffBlock {68 let mut coef = CoeffBlock {
@@ -144,8 +146,8 @@ pub(crate) fn decode_coefs(
144 coef.eob = c;146 coef.eob = c;
145 if crate::trace_enabled() {147 if crate::trace_enabled() {
146 eprintln!(148 eprintln!(
147- "C pt={} tx={} eob={} c0={}",149+ "C p={} x={} y={} tx={} eob={} c0={}",
148- plane_type, tx_size, c, coef.coeffs[0]150+ plane, pos.0, pos.1, tx_size, c, coef.coeffs[0]
149 );151 );
150 }152 }
151 coef153 coef
crates/ec-vp9/tests/scratch_bool.rsadded+14 -0
@@ -0,0 +1,14 @@
1+mod ivf;
2+use ec_vp9::bool::BoolDecoder;
3+
4+#[test]
5+fn probe_first_bools() {
6+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
7+ let bytes = std::fs::read(dir.join("fixtures/vp9/lossless-64.ivf")).unwrap();
8+ let (_, _, _, frames) = ivf::parse_ivf(&bytes);
9+ let frame = &frames[0].data;
10+ println!("slice bytes: {:02x?}", &frame[18..26]);
11+ let mut r = BoolDecoder::new(&frame[18..18 + 113]).unwrap();
12+ let bits: Vec<u8> = (0..8).map(|_| u8::from(r.read_bool(128))).collect();
13+ println!("first 8 bools(128): {bits:?}");
14+}
crates/ec-vp9/tests/scratch_err.rsadded+17 -0
@@ -0,0 +1,17 @@
1+mod ivf;
2+use ec_vp9::decode::Decoder;
3+#[test]
4+fn show_err() {
5+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
6+ let bytes = std::fs::read(dir.join("fixtures/bitstreams/vp9-superframe-altref.ivf")).unwrap();
7+ let (_, _, _, frames) = ivf::parse_ivf(&bytes);
8+ let mut d = Decoder::new();
9+ let dir2 = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
10+ let b2 = std::fs::read(dir2.join("fixtures/bitstreams/vp9-superframe-altref.ivf")).unwrap();
11+ let (_, _, _, f2) = ivf::parse_ivf(&b2);
12+ println!("f0 bytes: {:02x?}", &f2[0].data[16..24]);
13+ match d.decode(&frames[0].data) {
14+ Ok(_) => println!("OK"),
15+ Err(e) => println!("ERR: {e}"),
16+ }
17+}
crates/ec-vp9/tests/scratch_hdr2.rsadded+12 -0
@@ -0,0 +1,12 @@
1+mod ivf;
2+use ec_vp9_syntax::Vp9Parser;
3+#[test]
4+fn dump_hdr() {
5+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
6+ let bytes = std::fs::read(dir.join("fixtures/vp9/lossless-64.ivf")).unwrap();
7+ let (_, _, _, frames) = ivf::parse_ivf(&bytes);
8+ let mut p = Vp9Parser::new();
9+ let h = p.parse_frame(&frames[0].data).unwrap();
10+ println!("q={:#?} lf={:#?} seg={:#?}", h.quantization, h.loop_filter, h.segmentation);
11+ println!("uh={} hsz={} tile={:#?} w={} h={}", h.uncompressed_header_size, h.header_size_in_bytes, h.tile_info, h.width, h.height);
12+}
crates/ec-vp9/tests/scratch_hdr3.rsadded+14 -0
@@ -0,0 +1,14 @@
1+mod ivf;
2+use ec_vp9_syntax::Vp9Parser;
3+#[test]
4+fn dump_hdr() {
5+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
6+ let bytes = std::fs::read(dir.join("fixtures/bitstreams/vp9-superframe-altref.ivf")).unwrap();
7+ let (_, _, _, frames) = ivf::parse_ivf(&bytes);
8+ let subs = ec_vp9_syntax::superframe::split(&frames[0].data).unwrap();
9+ println!("subframes: {}", subs.len());
10+ let mut p = Vp9Parser::new();
11+ let h = p.parse_frame(subs[0]).unwrap();
12+ println!("q={:#?} lf={:#?} seg={:#?}", h.quantization, h.loop_filter, h.segmentation);
13+ println!("uh={} hsz={} tile={:#?} w={} h={}", h.uncompressed_header_size, h.header_size_in_bytes, h.tile_info, h.width, h.height);
14+}
lanes/vp9kf.report.mdmodified+92 -0
@@ -97,3 +97,95 @@ CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9 cargo test -p ec-vp9 --test keyfr
97 see "Fixed this round" item 4 for the rationale; merge reviewer must approve.97 see "Fixed this round" item 4 for the rationale; merge reviewer must approve.
98 - No edits to `ec-vp8`, `ec-hw`, or `edith`. Workspace `Cargo.toml` untouched98 - No edits to `ec-vp8`, `ec-hw`, or `edith`. Workspace `Cargo.toml` untouched
99 (members glob covers the new crate, same as `ec-vp8`).99 (members glob covers the new crate, same as `ec-vp8`).
100+
101+## HANDOFF #3 (lossless-64 lane, 2026-09-14) — FIRST DISAGREEING STEP: bool-decoder init + lossless tx_mode; FAIL (4009/4096)
102+
103+Root causes found this round (all proven against an instrumented libvpx 1.15.0 oracle,
104+see "Oracle" below — bit-level diffs, not structural reads):
105+
106+1. **Bool decoder marker bit (FIXED, ec-vp9/src/bool.rs `BoolDecoder::new`).** libvpx 1.15
107+ `vpx_reader_init` consumes one marker bit per partition right after the initial fill
108+ (bitreader.c:34 `return vpx_read_bit(r) != 0; // marker bit`); the writer
109+ (`vpx_start_encode`, bitwriter.c:22) emits a leading 0 bit per partition. Our spec-8.3.2
110+ init did not → one-bit desync on the compressed header AND every tile. Now read and
111+ validated; test-only `BoolEncoder::new` writes the parity bit. This is a libvpx-1.15
112+ format quirk, not in the VP9 spec document — the spec-based roundtrip hid it.
113+2. **Lossless forces ONLY_4X4 in the compressed header (FIXED, ec-vp9/src/header.rs
114+ `read_compressed_header(data, ctx, lossless)` + decode.rs call).** decodeframe.c:
115+ `cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);` — lossless consumes NO
116+ tx-mode bits and skips tx-prob updates. We parsed a tx_mode symbol and desynced the
117+ whole compressed header for q=0 streams. (read_tx_size needs no lossless branch: 1.15
118+ has none; ONLY_4X4 propagates via tx_mode.)
119+3. **Tile-info rows walk (FIXED, ec-vp9-syntax/src/header.rs `read_tile_info`).** Rows are
120+ NOT a min..max walk: `log2_tile_rows = read_bit(); if (..) += read_bit();` — always ≥1
121+ bit. We read 0 bits for 64x64 → header_size_in_bytes read one bit early (113 became 226
122+ = 113<<1).
123+4. **Tile-info cols max bound (FIXED, same file `tile_cols_log2_bounds`).** max_log2
124+ started at 1 and used `>=`: for sb64_cols=1 it returned 1 (reads an extra increment
125+ bit). Correct shape: start 0, `while (sb64_cols >> max_log2) > MIN_TILE_WIDTH_B64`.
126+
127+Two syntax-crate edits this round — same justification as round 2 (hard blockers, libvpx
128+line citations above). Merge reviewer must approve.
129+
130+**Progress:** lossless-64.ivf mismatches 4092/4096 → 4009/4096; first diff moved from
131+pixel (0,0) to (8,0). First 6 token blocks byte-match the oracle exactly
132+(eob/c0: 4/-1056, 0, 0, 14/464, U 16/760, V 15/408). Pixel (0,0) reconstructs correctly
133+now. `scratch_lossless` still FAIL; `lossless_64_matches_ffmpeg` NOT ADDED YET (do not
134+write the byte-compare test until the plane matches; scratch_lossless covers it for now).
135+keyframes_match_ffmpeg NOT re-run to green (will share whatever the remaining bug is —
136+lossless-only forcing is not on key-320's path, but the marker-bit and tile-info fixes are).
137+
138+**Remaining divergence (next session's first step):** the second 8x8 area at MI (0,1).
139+Oracle: `PART row=0 col=1 bsl=0 p=3` (SPLIT → BLOCK_4X4, 4 bmi y-modes, first 4x4
140+eob=2 c0=72). Ours: decoded 3 luma 4x4 TUs + chroma for that area — a different
141+subshape → our partition read or the sub8x8 mode-info read diverges there. Suspects in
142+order: (a) sub8x8 bmi mode loop in modes.rs (`get_y_mode_probs` / bmi above-left
143+adjustment per sub-block), (b) `dec_update_partition_context` after sub8x8 blocks
144+(above_seg/left_seg bit state feeding the next partition ctx), (c) skip-flag context
145+after sub8x8. Diff method: run our `EC_VP9_TRACE=1` (C lines now carry p/x/y/tx) against
146+oracle EOB lines; first mismatch at block 7 of 416.
147+
148+**Oracle (reusable):** instrumented libvpx 1.15.0 built from source at
149+`/tmp/vp9loss/libvpx-src` (git clone --depth 1 --branch v1.15.0 webmproject/libvpx;
150+./configure --disable-unit-tests --disable-vp8 --disable-vp9-encoder --disable-examples
151+--disable-tools; make -j6; ~10 s). Driver `/tmp/vp9loss/drv.c` decodes an IVF frame.
152+With `VP9TRACE=1` it prints PART/PARTIN (partition symbol+ctx+probs+reader state),
153+MODE (bsize/skip/tx/y/uv per block), TXB (ctx a/l + dequant per token block), EOB
154+(eob + c0), CH (compressed-header tx_mode + updated probs), CHDATA. Diff its trace
155+against ours line-by-line — this found all four root causes above in one session.
156+/tmp is volatile; rebuild takes ~1 min.
157+
158+Note: CAT6_MIN_VAL is 67 in this libvpx (contiguous 5,7,11,19,35,67) — NOT 1344; our
159+tokens.rs is correct. read_tx_size/decode_coefs structural port re-verified clean.
160+Scratch: `tests/scratch_bool.rs`, `tests/scratch_hdr2.rs` added; `EC_VP9_FORCE_UH/HSZ`
161+probe override in decode.rs (decode_one) — all removable after match.
162+
163+### HANDOFF #3 addendum (same session, post-commit draft)
164+
165+5. **Left-context row index ignored tx_row (FIXED, ec-vp9/src/decode.rs decode_txb).**
166+ `ay = ((mi_row<<1)>>s) % lrows` dropped the tx-block row → for the 2nd 4x4 row of any
167+ block the left entropy context aliased row 0 (ax already had +tx_col). Now
168+ `ay = (((mi_row<<1)>>s) + tx_row) % lrows`. Found by per-symbol TOK diff against the
169+ oracle: altref f0 block (0,4) decoded with ctx=2 vs oracle ctx=1.
170+ lossless-64: first diff now pixel (16,0) (was (8,0)); matches through the whole first
171+ 8x8 including its BLOCK_4X4 neighbour group start.
172+6. **tile_cols_log2_bounds max side (FIXED AGAIN, ec-vp9-syntax).** My earlier `> MIN`
173+ rewrite was wrong: libvpx `get_max_log2_tile_cols` = the `>= MIN` loop returning
174+ **max_log2 - 1** (tile_common.c:40-49). Original syntax code had the right loop but
175+ dropped the `-1`; for sb64_cols=5 (320px) that read a phantom cols increment bit →
176+ hsz 498 instead of 249 → key-320 frame 0 errored ("marker bit") after fix #1.
177+ Now: loop unchanged, `max_log2 - 1` applied.
178+
179+**State at yield:** lossless-64 3960/4096 mismatching, first diff (16,0) ours 135 ref 145;
180+key-320 f0 decodes without error, `keyframes_match_ffmpeg` fails on CONTENT only at
181+pixel (7,0): ours 74 vs ref 75 (single-rounding-class errors now, not desync).
182+`inter_is_named_unsupported` fails: altref f0 (single-subframe keyframe, 320x240,
183+q=36, lf=2) hits "vp9: tile bool decoder desync" in OUR tile decode — oracle decodes
184+it fine, headers parse identical (uh=18 hsz=225 verified both sides). Suspect: another
185+entropy-context bookkeeping bug of the same class as #5 (above/left write-back spans or
186+skip-context clearing), NOT the header. Next steps: (1) diff altref f0 first tile with
187+oracle TOK/TXB line-by-line from block (4,4) onward using per-symbol probs — instrument
188+ours with a TOK-style trace in tokens.rs decode_coefs (oracle TOK print is in
189+/tmp/vp9loss/libvpx-src/vp9/decoder/vp9_detokenize.c decode_coefs loop top);
190+(2) re-check `lossless_64_matches_ffmpeg` after; keep scratch files until green.
191+Oracle: /tmp/vp9loss/{libvpx-src,drv} (see above; TOK c/band/ctx/p0 print per symbol).