diff --git a/crates/ec-vp8/src/decode.rs b/crates/ec-vp8/src/decode.rs index 224c6a7d..9aeaaf7d 100644 --- a/crates/ec-vp8/src/decode.rs +++ b/crates/ec-vp8/src/decode.rs @@ -171,6 +171,7 @@ pub struct Decoder { } /// A decoded, displayable frame: cropped contiguous planes. +#[derive(Clone)] pub struct Picture { /// Luma plane, `stride`-spaced rows of `width` pixels. pub y: Vec, diff --git a/crates/ec-vp8/src/lib.rs b/crates/ec-vp8/src/lib.rs index cbe17aaa..051e93a7 100644 --- a/crates/ec-vp8/src/lib.rs +++ b/crates/ec-vp8/src/lib.rs @@ -22,6 +22,7 @@ pub mod intra; pub mod loopfilter; mod mc; pub mod modes; +pub mod stream; pub mod tables; pub mod tokens; pub mod transform; diff --git a/crates/ec-vp8/src/stream.rs b/crates/ec-vp8/src/stream.rs new file mode 100644 index 00000000..4f3b98a8 --- /dev/null +++ b/crates/ec-vp8/src/stream.rs @@ -0,0 +1,134 @@ +//! Whole-stream decoding: an IVF file in, decoded pictures out. +//! +//! VP8 frames are not self-delimiting — a bare frame is a 3-byte +//! uncompressed tag followed by partitions whose total size only the +//! container knows — so the whole-stream API takes the stream in the +//! container VP8 actually ships in: IVF (the RFC's companion container, +//! `DKIF`/`VP80`; also what vpxenc, ffmpeg and the WebM toolchain emit +//! for raw VP8 elementaries). Single frames from any other demuxer feed +//! [`crate::decode::Decoder::decode`] directly. +//! +//! The shape mirrors `ec_av1::stream`: [`decode_stream`] collects every +//! shown picture into a `Vec`, and [`decode_stream_with`] hands each +//! picture to a sink the moment it exists. + +use crate::decode::{Decoder, Picture}; +use crate::{Error, Result}; + +/// The IVF file magic, `DKIF`. +const DKIF: &[u8; 4] = b"DKIF"; +/// The fourcc for VP8 video (`VP80`; `VP8L`/`VP8x` are WebP-lossless/alpha). +const VP80: &[u8; 4] = b"VP80"; + +/// One demuxed IVF frame: presentation timestamp plus the compressed +/// VP8 payload. +struct IvfFrame<'a> { + pts: u64, + data: &'a [u8], +} + +/// Split an IVF byte stream into its frames, validating the container +/// envelope (magic, fourcc, framing arithmetic) as [`Error`]s rather +/// than panics. +fn demux(data: &[u8]) -> Result>> { + if data.len() < 32 || &data[0..4] != DKIF { + return Err(Error::corrupt("not an IVF stream (missing DKIF magic)")); + } + // Bytes 4..6 version (informational), 6..8 header length, 8..12 fourcc. + let hdr_len = u16::from_le_bytes([data[6], data[7]]) as usize; + if data.len() < hdr_len || hdr_len < 12 { + return Err(Error::corrupt("IVF header length out of range")); + } + if &data[8..12] != VP80 { + return Err(Error::unsupported( + "IVF fourcc", + "the stream is not VP80 (VP8 video)", + )); + } + // Bytes 12..16 carry the nominal width/height; VP8 streams set them + // to 0 and take the real dimensions from the key frame, so the + // decoder does not consult them. + let _ = u16::from_le_bytes([data[12], data[13]]); + let _ = u16::from_le_bytes([data[14], data[15]]); + let mut frames = Vec::new(); + let mut pos = hdr_len; + while pos + 12 <= data.len() { + let sz = + u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) + as usize; + let pts = u64::from_le_bytes([ + data[pos + 4], + data[pos + 5], + data[pos + 6], + data[pos + 7], + data[pos + 8], + data[pos + 9], + data[pos + 10], + data[pos + 11], + ]); + pos += 12; + if pos + sz > data.len() { + return Err(Error::corrupt(format!( + "IVF frame {} extends past end of stream (need {} bytes \ + at offset {})", + frames.len(), + sz, + pos + ))); + } + frames.push(IvfFrame { + pts, + data: &data[pos..pos + sz], + }); + pos += sz; + } + Ok(frames) +} + +/// Decode every frame in an IVF VP8 stream, in presentation order. +/// +/// The stream must start with a key frame; hidden frames (alternate +/// references, `show_frame == 0`) update the reference buffers but are +/// not part of the output, exactly as a player would not display them. +/// +/// # Errors +/// Returns an error when the container is truncated or not VP80 (as +/// [`demux`] reports it), when a frame is malformed (as +/// [`crate::decode::Decoder::decode`] reports it), or when an inter +/// frame appears before any key frame has supplied references. +pub fn decode_stream(data: &[u8]) -> Result> { + let mut pictures: Vec = Vec::new(); + decode_stream_with(data, |picture, _decode_idx, _pts| { + pictures.push(picture.clone()); + Ok(()) + })?; + Ok(pictures) +} + +/// Streaming form of [`decode_stream`]: hand every shown picture to +/// `sink` the moment it exists and drop it right after, so peak memory +/// is one output picture plus the reference frames instead of the whole +/// decoded stream. `decode_stream` itself is this function collecting +/// into a `Vec`. +/// +/// `sink` is called with the picture, the decode-order index of the +/// coded frame it came from, and the IVF presentation timestamp. A +/// hidden frame (`show_frame == 0`) updates the decoder state but +/// produces no picture, so the sink is not called for it. An `Err` the +/// sink returns aborts the decode and is returned unchanged. +/// +/// # Errors +/// As [`decode_stream`], plus whatever `sink` returns. +pub fn decode_stream_with( + data: &[u8], + mut sink: impl FnMut(&Picture, usize, u64) -> Result<()>, +) -> Result<()> { + let frames = demux(data)?; + let mut dec = Decoder::new(); + for (decode_idx, frame) in frames.iter().enumerate() { + if let Some(picture) = dec.decode(frame.data)? { + sink(&picture, decode_idx, frame.pts)?; + } + } + Ok(()) +} diff --git a/crates/ec-vp8/tests/ivf.rs b/crates/ec-vp8/tests/ivf.rs index 324242d1..d77a1591 100644 --- a/crates/ec-vp8/tests/ivf.rs +++ b/crates/ec-vp8/tests/ivf.rs @@ -7,6 +7,7 @@ pub struct IvfFrame { #[allow(dead_code)] pub pts: u64, /// The compressed VP8 frame payload. + #[allow(dead_code)] // pts-only consumers exist in the stream witnesses pub data: Vec, } @@ -47,6 +48,7 @@ pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec) { /// Extract the VP8 payload from a lossy WebP file (RIFF/WEBP with a VP8 /// chunk) — the same VP8 key-frame bytes in a different container. +#[allow(dead_code)] // only the keyframe_exact binary exercises WebP pub fn webp_vp8_chunk(bytes: &[u8]) -> Vec { assert_eq!(&bytes[0..4], b"RIFF"); assert_eq!(&bytes[8..12], b"WEBP"); diff --git a/crates/ec-vp8/tests/stream_exact.rs b/crates/ec-vp8/tests/stream_exact.rs new file mode 100644 index 00000000..ef743e61 --- /dev/null +++ b/crates/ec-vp8/tests/stream_exact.rs @@ -0,0 +1,87 @@ +//! M4 witness: the whole-stream public API (`ec_vp8::stream`) decodes +//! every fixture byte-exact against ffmpeg and refuses malformed +//! containers with errors, not panics. + +mod ivf; + +use ec_vp8::stream::decode_stream; + +/// Every IVF fixture in the witness set (the WebP still is covered by +/// `keyframe_exact::vp8_in_webp_still_matches_ffmpeg`). +const FIXTURES: &[&str] = &[ + "kf-16x16-black-q0.ivf", + "kf-32x16-q35.ivf", + "kf-76x52-q30.ivf", + "kf-96x80-q63.ivf", + "kf-160x96-q20.ivf", + "kf-160x96-q40.ivf", + "kf-172x144-q25.ivf", + "gop-96x80-v1.ivf", + "gop-160x96.ivf", + "mparts-160x96.ivf", + "altref-160x96.ivf", + "clip-obs-320x192.ivf", +]; + +#[test] +fn decode_stream_matches_ffmpeg_on_every_fixture() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + for name in FIXTURES { + let path = dir.join(name); + let bytes = std::fs::read(&path).unwrap(); + 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"); + 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"); + 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); + assert_eq!(pic.y, &expect[..usize::from(w) * usize::from(h)], "{name} frame {i}: Y"); + assert_eq!(pic.u, &expect[usize::from(w) * usize::from(h)..][..cw * ch], "{name} frame {i}: U"); + assert_eq!(pic.v, &expect[usize::from(w) * usize::from(h) + cw * ch..], "{name} frame {i}: V"); + } + } +} + +/// 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") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .expect("ffmpeg must be on PATH for the witnesses"); + assert!(out.status.success(), "ffmpeg failed on {path:?}"); + out.stdout +} + +#[test] +fn decode_stream_is_error_not_panic_on_bad_containers() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let bytes = std::fs::read(dir.join("gop-160x96.ivf")).unwrap(); + + // Missing magic. + let mut bad = bytes.clone(); + bad[0..4].copy_from_slice(b"JUNK"); + assert!(decode_stream(&bad).is_err(), "non-DKIF accepted"); + + // Wrong fourcc (a WebP-lossless VP8L tag is not a VP8 video stream). + let mut bad = bytes.clone(); + bad[8..12].copy_from_slice(b"VP8L"); + assert!(decode_stream(&bad).is_err(), "non-VP80 fourcc accepted"); + + // A frame header claiming more payload than the stream carries. + let mut bad = bytes.clone(); + bad[32..36].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(decode_stream(&bad).is_err(), "truncated frame accepted"); +} +