diff --git a/crates/ec-vp8/tests/ivf.rs b/crates/ec-vp8/tests/ivf.rs index d77a1591..ef184c56 100644 --- a/crates/ec-vp8/tests/ivf.rs +++ b/crates/ec-vp8/tests/ivf.rs @@ -11,6 +11,13 @@ pub struct IvfFrame { pub data: Vec, } +/// The frame tag's `show_frame` bit (RFC 6386 §9.1): hidden frames +/// (`false`) update the reference buffers but are never displayed. +#[allow(dead_code)] // not every witness binary needs the census +pub fn show_frame(data: &[u8]) -> bool { + (data[0] >> 4) & 1 == 1 +} + /// Parse an IVF file into (fourcc, width, height, frames). pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec) { assert_eq!(&bytes[0..4], b"DKIF", "not an IVF file"); diff --git a/crates/ec-vp8/tests/keyframe_exact.rs b/crates/ec-vp8/tests/keyframe_exact.rs index 2debeef9..41be707d 100644 --- a/crates/ec-vp8/tests/keyframe_exact.rs +++ b/crates/ec-vp8/tests/keyframe_exact.rs @@ -3,7 +3,7 @@ mod ivf; -use ec_vp8::decode::{Decoder, Picture}; +use ec_vp8::decode::Decoder; /// ffmpeg's decoded rawvideo byte stream for the same file. fn ffmpeg_raw_yuv(path: &std::path::Path) -> Vec { @@ -23,8 +23,9 @@ fn raw<'a>(pos: &mut usize, data: &'a [u8], len: usize) -> &'a [u8] { s } -/// Decode every frame of an IVF with our decoder and compare each -/// frame's planes against ffmpeg's byte stream. +/// Decode every frame of an IVF with our decoder and compare each SHOWN +/// frame's planes against ffmpeg's byte stream (ffmpeg skips hidden +/// `show_frame == 0` frames exactly like a player). fn compare(name: &str, skip_if_missing: bool) { let Some(dir) = ivf::fixture_dir() else { panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); @@ -37,33 +38,42 @@ fn compare(name: &str, skip_if_missing: bool) { let (_, w, h, frames) = ivf::parse_ivf(&bytes); let all = ffmpeg_raw_yuv(&path); let frame_len = usize::from(w) * usize::from(h) * 3 / 2; + let shown: Vec<&ivf::IvfFrame> = + frames.iter().filter(|f| ivf::show_frame(&f.data)).collect(); assert_eq!( - all.len() % frame_len, - 0, - "{name}: ffmpeg output {}/{} not whole frames", all.len(), - frame_len + shown.len() * frame_len, + "{name}: ffmpeg output {}/{} not {} whole shown frames", + all.len(), + frame_len, + shown.len() ); - let count = all.len() / frame_len; - assert_eq!(frames.len(), count, "{name}: frame count vs ffmpeg"); let mut dec = Decoder::new(); let (cw, ch) = (usize::from(w + 1) / 2, usize::from(h + 1) / 2); + let mut shown_idx = 0; for (i, f) in frames.iter().enumerate() { - let pic: Picture = dec - .decode(&f.data) - .expect("decode succeeds") - .expect("shown"); - assert_eq!(pic.width, w); - assert_eq!(pic.height, h); - let mut pos = i * frame_len; - let exp_y = raw(&mut pos, &all, usize::from(w) * usize::from(h)); - let exp_u = raw(&mut pos, &all, cw * ch); - let exp_v = raw(&mut pos, &all, cw * ch); - assert_eq!(pic.y, exp_y, "{name} frame {i}: luma mismatch"); - assert_eq!(pic.u, exp_u, "{name} frame {i}: U mismatch"); - assert_eq!(pic.v, exp_v, "{name} frame {i}: V mismatch"); + match dec.decode(&f.data).expect("decode succeeds") { + Some(pic) => { + assert!(ivf::show_frame(&f.data), "{name} frame {i}: picture for hidden frame"); + assert_eq!(pic.width, w); + assert_eq!(pic.height, h); + let mut pos = shown_idx * frame_len; + shown_idx += 1; + let exp_y = raw(&mut pos, &all, usize::from(w) * usize::from(h)); + let exp_u = raw(&mut pos, &all, cw * ch); + let exp_v = raw(&mut pos, &all, cw * ch); + assert_eq!(pic.y, exp_y, "{name} frame {i}: luma mismatch"); + assert_eq!(pic.u, exp_u, "{name} frame {i}: U mismatch"); + assert_eq!(pic.v, exp_v, "{name} frame {i}: V mismatch"); + } + None => assert!( + !ivf::show_frame(&f.data), + "{name} frame {i}: shown frame produced no picture" + ), + } } + assert_eq!(shown_idx, shown.len(), "{name}: shown picture count"); } #[test] @@ -87,7 +97,9 @@ fn multi_partition_keyframe_matches_ffmpeg() { /// M3 witness: full inter-frame streams — simple-filter GOP, multi-token- /// partition, hidden-altref and the OBS screen-content clip — decode -/// byte-exact against ffmpeg, every frame. +/// byte-exact against ffmpeg, every frame. The altref vector must +/// actually CONTAIN hidden frames (census the tags; a shown-only stream +/// would silently stop exercising the hidden-frame contract). #[test] fn interframe_streams_match_ffmpeg() { for name in [ @@ -95,9 +107,26 @@ fn interframe_streams_match_ffmpeg() { "clip-obs-320x192.ivf", "altref-160x96.ivf", ] { + if name == "altref-160x96.ivf" { + let dir = ivf::fixture_dir().expect("fixtures dir"); + let bytes = std::fs::read(dir.join(name)).unwrap(); + let hidden = census_hidden(&bytes); + assert!( + hidden >= 6, + "{name}: only {hidden} hidden frames — regenerate with \ + scripts/gen_vp8_fixtures.sh (--auto-alt-ref=1 --passes=2)" + ); + } compare(name, false); } } + +/// Number of hidden (`show_frame == 0`) frames in an IVF stream. +fn census_hidden(bytes: &[u8]) -> usize { + let (_, _, _, frames) = ivf::parse_ivf(bytes); + frames.iter().filter(|f| !ivf::show_frame(&f.data)).count() +} + #[test] fn vp8_in_webp_still_matches_ffmpeg() { let Some(dir) = ivf::fixture_dir() else { diff --git a/crates/ec-vp8/tests/stream_exact.rs b/crates/ec-vp8/tests/stream_exact.rs index ef743e61..5fcba76d 100644 --- a/crates/ec-vp8/tests/stream_exact.rs +++ b/crates/ec-vp8/tests/stream_exact.rs @@ -4,6 +4,7 @@ mod ivf; +use ec_vp8::decode::Decoder; use ec_vp8::stream::decode_stream; /// Every IVF fixture in the witness set (the WebP still is covered by @@ -34,12 +35,13 @@ fn decode_stream_matches_ffmpeg_on_every_fixture() { let (_, w, h, frames) = ivf::parse_ivf(&bytes); let all = ffmpeg_raw_yuv(&path); let frame_len = usize::from(w) * usize::from(h) * 3 / 2; - assert_eq!(all.len(), frames.len() * frame_len, "{name}: ffmpeg output size"); + let shown = frames.iter().filter(|f| ivf::show_frame(&f.data)).count(); + assert_eq!(all.len(), shown * frame_len, "{name}: ffmpeg output size"); assert!(!frames[0].data.is_empty(), "{name}: empty first frame"); let pictures = decode_stream(&bytes).unwrap_or_else(|e| panic!("{name}: decode failed: {e}")); - assert_eq!(pictures.len(), frames.len(), "{name}: picture count"); + assert_eq!(pictures.len(), shown, "{name}: picture count (shown only)"); for (i, pic) in pictures.iter().enumerate() { let expect = &all[i * frame_len..(i + 1) * frame_len]; let (cw, ch) = (usize::from(w + 1) / 2, usize::from(h + 1) / 2); @@ -50,6 +52,58 @@ fn decode_stream_matches_ffmpeg_on_every_fixture() { } } +/// The hidden-frame contract, end to end on a REAL auto-alt-ref stream: +/// `Decoder::decode` returns `Ok(None)` for a hidden frame while its +/// reference content stays live — the frames that follow (which the +/// encoder predicted across the hidden altref) stay byte-exact against +/// ffmpeg. +#[test] +fn hidden_frames_update_references_and_produce_no_picture() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let path = dir.join("altref-160x96.ivf"); + let bytes = std::fs::read(&path).unwrap(); + let (_, w, h, frames) = ivf::parse_ivf(&bytes); + let hidden_at: Vec = frames + .iter() + .enumerate() + .filter(|(_, f)| !ivf::show_frame(&f.data)) + .map(|(i, _)| i) + .collect(); + assert!( + hidden_at.len() >= 6, + "altref-160x96.ivf lost its hidden frames ({}) — regenerate", + hidden_at.len() + ); + + // ffmpeg's display stream, shown-frame-indexed. + let all = ffmpeg_raw_yuv(&path); + let frame_len = usize::from(w) * usize::from(h) * 3 / 2; + let mut dec = Decoder::new(); + let mut shown_seen = 0; + for (i, f) in frames.iter().enumerate() { + let pic = dec.decode(&f.data).expect("hidden frame decodes"); + if ivf::show_frame(&f.data) { + let expect = &all[shown_seen * frame_len..(shown_seen + 1) * frame_len]; + let y = &pic.as_ref().expect("shown frame has picture").y; + assert_eq!(y, &expect[..usize::from(w) * usize::from(h)], "frame {i}: Y"); + // The frame right after the FIRST hidden altref must already + // be byte-exact: it predicts across the hidden reference. + if i == hidden_at[0] + 1 { + assert!( + y[..32] == expect[..32] && y == &expect[..y.len()], + "frame after hidden altref diverges" + ); + } + shown_seen += 1; + } else { + assert!(pic.is_none(), "hidden frame {i} produced a picture"); + } + } + assert_eq!(shown_seen * frame_len, all.len()); +} + /// ffmpeg's decoded rawvideo byte stream for an IVF file. fn ffmpeg_raw_yuv(path: &std::path::Path) -> Vec { let out = std::process::Command::new("ffmpeg") diff --git a/lanes/vp8.report.md b/lanes/vp8.report.md index 6d9ec550..262754b0 100644 --- a/lanes/vp8.report.md +++ b/lanes/vp8.report.md @@ -9,8 +9,8 @@ Never merged, never pushed. Pins untouched (no ec-av1 changes at all). |---|---|---| | M1 bool decoder + frame tag + full first-partition header | **done/verified** | commit `57b5a53a`; 12 unit tests green; real vpxenc/ffmpeg streams (6 sizes/q, 8-token-partition, WebP still) parse with exact partition tiling, correct dims (incl. 76x52 non-MB-aligned), 0 desyncs | | M2 key-frame-only decode, sample-exact vs ffmpeg | **root cause FIXED, verified at frame level** — decision-exact vs the reference model for the whole frame (19131 reads, 0 diffs) and frame-0 byte-exact vs ffmpeg on ALL 8 kf/mparts fixtures; the `keyframe_exact` suite goes 3/3 when inter frames land (each fixture carries 1 KF + inter frames), see M3 | commits `20f7d742`, `072f842f`, M2-fix commit (this one) | -| M3 inter frames | **done/verified — ALL fixtures byte-exact vs ffmpeg, every frame** | commits `151ef8ff`..`8e1a04a9` (M3 campaign) + `b0a648b0` (completion). Completion-pass fixes: (4) inter-frame B_PRED subblock modes use the FLAT vp8_bmode_prob `{120,90,79,133,87,85,80,111,151}` with no above/left context (libvpx decodemv.c:467 `fc.bmode_prob`; the kf_bmode context table is key-frame-only) — `decode.rs` `parse_inter_modes`; (5) MC filter is per-frame from the tag version bits (`vp8_setup_version`): version 0 = six-tap for BOTH planes — chroma was hardcoded bilinear; version 3 `fullpixel_mask` (~7) applied to chroma MV derivation (`decode.rs` Decoder::mc_bilinear/mc_fullpel, `mc.rs` sixtap/bilinear dispatch, `modes.rs` chroma_mv_*); (6) SPLITMV chroma quadrants are 4×4 CHROMA pixels at 4-px offsets predicted per quadrant — the old loop wrote 8×8 at 8-px offsets and the residual add read only the top-left quadrant's prediction (whole-MB modes masked it; every SPLITMV MB had wrong chroma); (7) key frame with refresh_entropy==0 reverts entropy to DEFAULTS (libvpx init_frame resets fc before lfc=fc), not the pre-keyframe context. Witnesses: `interframe_streams_match_ffmpeg` — gop-160x96 (60f), clip-obs-320x192 (169f), altref-160x96 (90f, frame-35 Err resolved) + mparts (30f) + all kf fixtures byte-exact; B-stream trace Rust↔model 0 diffs across full streams. Oracle model fixed to match libvpx (inter ymode/uv defaults [112,86,140,37]/[162,101,204], flat inter bmode). Suite 55 lib + 4 header_parse + 4 keyframe_exact, zero rustc warnings | -| M4 public API + docs | **done/verified** | commit `4b8b11d3`: `stream::decode_stream(IVF) -> Result>` + `stream::decode_stream_with` sink form `(picture, decode_idx, pts)` (hidden frames produce no sink call); container validated as ec_core::Error (DKIF/VP80/framing); `Picture: Clone`. Witness `tests/stream_exact.rs`: byte-exact vs ffmpeg on ALL 12 IVF fixtures + malformed-container error tests. Suite totals 55+4+4+2 green, zero warnings | +| M3 inter frames | **done/verified — ALL fixtures byte-exact vs ffmpeg, every frame** | commits `151ef8ff`..`8e1a04a9` (M3 campaign) + `b0a648b0` (completion). Completion-pass fixes: (4) inter-frame B_PRED subblock modes use the FLAT vp8_bmode_prob `{120,90,79,133,87,85,80,111,151}` with no above/left context (libvpx decodemv.c:467 `fc.bmode_prob`; the kf_bmode context table is key-frame-only) — `decode.rs` `parse_inter_modes`; (5) MC filter is per-frame from the tag version bits (`vp8_setup_version`): version 0 = six-tap for BOTH planes — chroma was hardcoded bilinear; version 3 `fullpixel_mask` (~7) applied to chroma MV derivation (`decode.rs` Decoder::mc_bilinear/mc_fullpel, `mc.rs` sixtap/bilinear dispatch, `modes.rs` chroma_mv_*); (6) SPLITMV chroma quadrants are 4×4 CHROMA pixels at 4-px offsets predicted per quadrant — the old loop wrote 8×8 at 8-px offsets and the residual add read only the top-left quadrant's prediction (whole-MB modes masked it; every SPLITMV MB had wrong chroma); (7) key frame with refresh_entropy==0 reverts entropy to DEFAULTS (libvpx init_frame resets fc before lfc=fc), not the pre-keyframe context. Witnesses: `interframe_streams_match_ffmpeg` — gop-160x96 (60f), clip-obs-320x192 (169f), altref-160x96 (96f: 90 shown + 6 HIDDEN altrefs at decode-idx 1,17,33,49,65,81; frame-35 Err resolved) + mparts (30f) + all kf fixtures byte-exact; B-stream trace Rust↔model 0 diffs across full streams. Oracle model fixed to match libvpx (inter ymode/uv defaults [112,86,140,37]/[162,101,204], flat inter bmode). Suite 55 lib + 4 header_parse + 4 keyframe_exact, zero rustc warnings | +| M4 public API + docs | **done/verified** (review flags fixed: all 12 fixtures script-generated; hidden-frame coverage real) | commit `4b8b11d3` + review-fix commit: `stream::decode_stream(IVF) -> Result>` + `stream::decode_stream_with` sink form `(picture, decode_idx, pts)` (hidden frames produce no sink call); container validated as ec_core::Error (DKIF/VP80/framing); `Picture: Clone`. Witness `tests/stream_exact.rs`: byte-exact vs ffmpeg on ALL 12 IVF fixtures + malformed-container error tests + `hidden_frames_update_references_and_produce_no_picture` (real auto-alt-ref stream: hidden -> Ok(None), following frames byte-exact). Suite totals 55+4+4+3 green; every fixture now regenerated by `scripts/gen_vp8_fixtures.sh` (9/9 pre-existing outputs byte-identical on regen), zero warnings | ## What shipped (M1 `57b5a53a`, M2 WIP `20f7d742`) diff --git a/scripts/gen_vp8_fixtures.sh b/scripts/gen_vp8_fixtures.sh index eaee5bb5..551064b9 100755 --- a/scripts/gen_vp8_fixtures.sh +++ b/scripts/gen_vp8_fixtures.sh @@ -80,4 +80,44 @@ else rm -f "$OUT/still.png" fi +# Note on the three vectors below (review flag): every fixture in the set +# must come from THIS script — no ad-hoc leftovers. +# +# kf-16x16-black-q0: 1-MB all-black frame at q0 (the M2 "no ONE tokens" +# degenerate vector: exercises the zero-coefficient and overread paths). +enc kf-16x16-black-q0 16x16 1 0 color=black:size=16x16:rate=30 + +# clip-obs-320x192: screen-content-shaped 320x192 clip. The original was +# an OBS window capture; the recorded reproducible stand-in is testsrc2 +# at the same size (same decoder paths: 20x12 MB grid, small-MV motion). +enc clip-obs-320x192 320x192 169 28 testsrc2=size=320x192:rate=30 + +# altref-160x96: vpxenc --auto-alt-ref=1 in TWO passes (one-pass CQ/VBR +# never inserts hidden altrefs for this content) with --lag-in-frames, so +# libvpx emits HIDDEN alternate-reference frames (frame tag show_frame=0, +# currently 6 of 90 at decode indices 1,17,33,49,65,81). The witnesses +# census the tags and refuse a shown-only stream: the hidden-frame +# contract (no output, reference buffers still update, later frames +# reference the hidden altref) must be exercised. +ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i testsrc2=size=160x96:rate=30 -frames:v 90 \ + -pix_fmt yuv420p -f rawvideo /tmp/ecvp8-altref.raw +# Two passes need a seekable input (stdin cannot rewind for pass 2), so +# the y4m goes through a temp FILE, not a pipe. +{ printf 'YUV4MPEG2 W160 H96 F30:1 Ip A1:1 C420jpeg\n' + cat /tmp/ecvp8-altref.raw | python3 -c ' +import sys +raw = sys.stdin.buffer.read() +frame = 160 * 96 * 3 // 2 +for i in range(len(raw) // frame): + sys.stdout.buffer.write(b"FRAME\n" + raw[i*frame:(i+1)*frame]) +' > /tmp/ecvp8-altref.y4m +} +"$VPXENC" --codec=vp8 -w 160 -h 96 --limit=90 --ivf --cpu-used=1 \ + --end-usage=vbr --target-bitrate=400 --kf-max-dist=15 \ + --auto-alt-ref=1 --lag-in-frames=15 --passes=2 --fpf=/tmp/ecvp8-altref.fpf \ + --quiet -o "$OUT/altref-160x96.ivf" /tmp/ecvp8-altref.y4m +rm -f /tmp/ecvp8-altref.raw /tmp/ecvp8-altref.y4m /tmp/ecvp8-altref.fpf +echo "wrote $OUT/altref-160x96.ivf" + ls -la "$OUT"