From 5b0ae0378148fcbccd9d25d4dbbaf80d77ba663a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 16:00:37 +0300 Subject: [PATCH] =?UTF-8?q?ec-vp8=20M2=20WIP:=20full=20key-frame=20decode?= =?UTF-8?q?=20pipeline=20(tokens/intra/transform/loopfilter/reconstruct)?= =?UTF-8?q?=20=E2=80=94=20unit=20tests=20100%=20green,=20ffmpeg=20exactnes?= =?UTF-8?q?s=20witnesses=20RED=20(luma=20bug)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tokens.rs: RFC 6386 sec 13 coefficient decoding (GetCoeffs port: bands, 3-context model, EOB-skip-after-zero, dequant-on-write, Y2-first block order, dixie skip-MB context reset with Y2 preservation). - modes.rs: all mode/MV trees + tables (kf/inter ymode, bmode, uv, mv_ref, sub_mv_ref, SPLITMV partitions with RFC enum-value indexing). - decode.rs: per-row pipeline (modes -> tokens -> reconstruct), bordered planes (127/129), above-right synthesis, B_PRED interleaved predict+residual (reconstructed-pixel chaining), Y2 WHT DC override, per-MB LF level (dixie double-clamp), LF post-pass via loopfilter. - loopfilter.rs + intra.rs + transform.rs: subagent kernels, rustc-verified vs libvpx C (differential fuzz: 400k IDCT/WHT vectors, 20k intra streams, dixie-table-exact LF limits). - FIX along the way: per-MB-row token left-context reset (dixie reset_row_context) was missing. - tests/keyframe_exact.rs: ffmpeg byte-compare witnesses — FAILING: single 16x16 black q0 frame decodes chroma exact but luma ~99-130 vs 16 (B_PRED MB, coeffs plausible); suspected in luma pred/apply path, NOT yet localized. Debug: EC_VP8_DEBUG=1 dump + examples/dbg_first. - 49 lib + 4 header tests green; zero warnings in lib. --- crates/ec-vp8/examples/dbg_first.rs | 46 ++ crates/ec-vp8/src/bool.rs | 37 +- crates/ec-vp8/src/decode.rs | 679 ++++++++++++++++ crates/ec-vp8/src/header.rs | 13 +- crates/ec-vp8/src/intra.rs | 711 +++++++++++++++++ crates/ec-vp8/src/lib.rs | 6 + crates/ec-vp8/src/loopfilter.rs | 1064 +++++++++++++++++++++++++ crates/ec-vp8/src/modes.rs | 311 ++++++++ crates/ec-vp8/src/tokens.rs | 282 +++++++ crates/ec-vp8/src/transform.rs | 640 +++++++++++++++ crates/ec-vp8/tests/keyframe_exact.rs | 114 +++ scripts/raw_to_y4m.py | 15 + 12 files changed, 3903 insertions(+), 15 deletions(-) create mode 100644 crates/ec-vp8/examples/dbg_first.rs create mode 100644 crates/ec-vp8/src/decode.rs create mode 100644 crates/ec-vp8/src/intra.rs create mode 100644 crates/ec-vp8/src/loopfilter.rs create mode 100644 crates/ec-vp8/src/modes.rs create mode 100644 crates/ec-vp8/src/tokens.rs create mode 100644 crates/ec-vp8/src/transform.rs create mode 100644 crates/ec-vp8/tests/keyframe_exact.rs create mode 100755 scripts/raw_to_y4m.py diff --git a/crates/ec-vp8/examples/dbg_first.rs b/crates/ec-vp8/examples/dbg_first.rs new file mode 100644 index 00000000..45048f1d --- /dev/null +++ b/crates/ec-vp8/examples/dbg_first.rs @@ -0,0 +1,46 @@ +// Decode one frame: print header/dequant summary + pixel stats. +use ec_vp8::decode::Decoder; +use ec_vp8::transform; +use ec_vp8::{PersistedState, frame, header::FrameHeader}; + +fn main() { + let path = std::env::args().nth(1).expect("ivf path"); + let bytes = std::fs::read(path).unwrap(); + let sz = u32::from_le_bytes([bytes[32], bytes[33], bytes[34], bytes[35]]) as usize; + let frame = &bytes[44..44 + sz]; + let mut st = PersistedState::default(); + let (h, _) = FrameHeader::parse(frame, &mut st).unwrap(); + println!( + "q={} y2dc_d={} y2ac_d={} skip={} lvl={}", + h.quant.yac_qi, + h.quant.y2dc_delta, + h.quant.y2ac_delta, + h.coeff_skip_enabled, + h.filter_level + ); + let dq = transform::dequant( + i32::from(h.quant.yac_qi), + h.quant.ydc_delta, + h.quant.y2dc_delta, + h.quant.y2ac_delta, + h.quant.uvdc_delta, + h.quant.uvac_delta, + ); + println!( + "y1dc={} y1ac={} y2dc={} y2ac={}", + dq.y1_dc, dq.y1_ac, dq.y2_dc, dq.y2_ac + ); + let mut dec = Decoder::new(); + match dec.decode(frame) { + Ok(Some(pic)) => println!( + "{}x{} y[0..8]={:?} min={} max={}", + pic.width, + pic.height, + &pic.y[..8], + pic.y.iter().min().unwrap(), + pic.y.iter().max().unwrap() + ), + Ok(None) => println!("hidden"), + Err(e) => println!("ERR {e}"), + } +} diff --git a/crates/ec-vp8/src/bool.rs b/crates/ec-vp8/src/bool.rs index 99e40613..e842f051 100644 --- a/crates/ec-vp8/src/bool.rs +++ b/crates/ec-vp8/src/bool.rs @@ -11,7 +11,7 @@ //! `bool_encoder`; the tests drive them against a test-only re-implementation //! of that encoder and assert bit-exact round-trips. -use ec_core::{Error, Result}; +use ec_core::Result; /// Boolean arithmetic decoder over one data partition (RFC 6386 §7.3). pub struct BoolDecoder<'a> { @@ -32,17 +32,28 @@ pub struct BoolDecoder<'a> { impl<'a> BoolDecoder<'a> { /// Start decoding the partition `data` (RFC `init_bool_decoder`): the - /// first two bytes are read into `value`, big-endian. + /// first two bytes are read into `value`, big-endian. A partition + /// shorter than two bytes (legal for unused token partitions of + /// multi-partition frames) is zero-extended like the reference + /// decoder does, and the shortfall shows up in [`Self::overreads`]. pub fn new(data: &'a [u8]) -> Result { - if data.len() < 2 { - return Err(Error::corrupt( - "VP8 partition shorter than the two-byte bool decoder init", - )); + if data.is_empty() { + return Ok(Self { + data, + pos: 0, + range: 255, + value: 0, + bit_count: 0, + overreads: 0, + }); + } + let mut value = u32::from(data[0]) << 8; + if data.len() > 1 { + value |= u32::from(data[1]); } - let value = (u32::from(data[0]) << 8) | u32::from(data[1]); Ok(Self { data, - pos: 2, + pos: data.len().min(2), range: 255, value, bit_count: 0, @@ -404,9 +415,13 @@ mod tests { } #[test] - fn short_partition_is_corrupt() { - assert!(BoolDecoder::new(&[]).is_err()); - assert!(BoolDecoder::new(&[7]).is_err()); + fn short_partitions_zero_extend() { + // Empty/1-byte partitions are legal for unused token partitions; + // the init shortfall counts as overreads. + let mut d = BoolDecoder::new(&[]).unwrap(); + assert_eq!(d.read_bool(128), false); + let mut d = BoolDecoder::new(&[0]).unwrap(); + assert_eq!(d.read_bool(128), false); } #[test] diff --git a/crates/ec-vp8/src/decode.rs b/crates/ec-vp8/src/decode.rs new file mode 100644 index 00000000..be914741 --- /dev/null +++ b/crates/ec-vp8/src/decode.rs @@ -0,0 +1,679 @@ +//! Frame decoding: per-row mode parsing, token decoding, intra +//! prediction and reconstruction (RFC 6386 §5, §11, §12, §13, §14). +//! +//! The decoder mirrors the reference decoder's row pipeline: per +//! macroblock row, all first-partition mode records are parsed, then +//! each macroblock's tokens are decoded from its row-assigned token +//! partition (row `r` uses partition `r % partitions`, exactly like +//! libvpx/dixie) and immediately reconstructed. The loop filter runs as +//! a post-pass in raster MB order — for a non-threaded decode this is +//! edge-for-edge identical to the reference's row-delayed filtering, +//! because an MB's filter inputs only ever come from MBs already +//! filtered earlier in that order. + +use crate::bool::BoolDecoder; +use crate::frame::{FrameType, KeyFrameDims, mb_geometry}; +use crate::header::FrameHeader; +use crate::intra; +use crate::loopfilter::{self, MbFilterInfo}; +use crate::modes; +use crate::tables::KF_BMODE_PROB; +use crate::tokens::{self, Dq, MbCoeffs, TokenContexts}; +use crate::transform; +use crate::transform::Dequant; +use crate::{Error, PersistedState, Result}; + +/// Reconstructed-image plane: a padded buffer with a 1-pixel left/top +/// border (127 on top including the corner, 129 on the left — RFC 6386 +/// §12) so intra prediction reads neighbours without special cases. +struct Plane { + data: Vec, + /// Row pitch: `1 + mb_cols * mb_size`. + stride: usize, +} + +impl Plane { + fn new(mb_cols: usize, mb_rows: usize, mb_size: usize) -> Self { + let stride = 1 + mb_cols * mb_size; + let rows = 1 + mb_rows * mb_size; + let mut data = vec![0u8; stride * rows]; + for cell in data[..stride].iter_mut() { + *cell = 127; + } + for row in 1..rows { + data[row * stride] = 129; + } + Plane { data, stride } + } + + fn resize(&mut self, mb_cols: usize, mb_rows: usize, mb_size: usize) { + *self = Plane::new(mb_cols, mb_rows, mb_size); + } + + /// Offset of pixel (x, y); the border occupies x = -1 / y = -1. + fn at(&self, x: usize, y: usize) -> usize { + (1 + y) * self.stride + 1 + x + } + + /// Offset of the pixel row ABOVE pixel row `y` (the border row for + /// y = 0), at pixel column `x`. + fn at_above(&self, x: usize, y: usize) -> usize { + y * self.stride + 1 + x + } + + /// Offset of the pixel column LEFT of pixel column `x` (the border + /// column for x = 0), at pixel row `y`. + fn at_left(&self, x: usize, y: usize) -> usize { + (1 + y) * self.stride + x + } + + /// Offset of the above-left pixel (border corner for x = y = 0). + fn at_above_left(&self, x: usize, y: usize) -> usize { + y * self.stride + x + } +} + +/// One macroblock's parsed prediction record. +#[derive(Clone, Default)] +struct MbInfo { + /// [`modes::YMode`] as its coded integer. + y_mode: u8, + uv_mode: u8, + b_modes: [u8; 16], + segment_id: u8, + skip: bool, + /// Any non-zero coefficient decoded for this MB (bit 31 of dixie's + /// eob_mask); decides the loop filter's interior edges (§15.1). + has_nz: bool, +} + +impl MbInfo { + fn has_y2(&self) -> bool { + self.y_mode != modes::YMode::BPred.as_u8() + } +} + +/// The VP8 decoder. Feed complete frames (one full VP8 frame payload, +/// exactly what a container demuxer hands over for the `VP80`/`vp08` +/// codec). +pub struct Decoder { + state: PersistedState, + dims: KeyFrameDims, + mb_cols: usize, + mb_rows: usize, + y: Plane, + u: Plane, + v: Plane, + /// `(mb_rows + 1) * (mb_cols + 1)` records; row/column index 0 is the + /// DC_PRED border (dixie's `mb_info` border trick). + mb_info: Vec, + token_ctxs: TokenContexts, + frame_decoded: bool, +} + +/// A decoded, displayable frame: cropped contiguous planes. +pub struct Picture { + /// Luma plane, `stride`-spaced rows of `width` pixels. + pub y: Vec, + /// U (Cb) plane, half resolution. + pub u: Vec, + /// V (Cr) plane, half resolution. + pub v: Vec, + pub width: u16, + pub height: u16, + /// Luma row pitch of the returned planes. + pub stride: usize, + /// Chroma row pitch of the returned planes. + pub uv_stride: usize, +} + +impl Decoder { + /// Create an empty decoder; the first key frame sets the size. + pub fn new() -> Self { + Self { + state: PersistedState::default(), + dims: KeyFrameDims { + width: 0, + height: 0, + h_scale: 0, + v_scale: 0, + }, + mb_cols: 0, + mb_rows: 0, + y: Plane { + data: Vec::new(), + stride: 0, + }, + u: Plane { + data: Vec::new(), + stride: 0, + }, + v: Plane { + data: Vec::new(), + stride: 0, + }, + mb_info: Vec::new(), + token_ctxs: TokenContexts::new(0), + frame_decoded: false, + } + } + + /// Size of the frames this decoder produces, once known. + pub fn dimensions(&self) -> Option<(u16, u16)> { + self.frame_decoded + .then_some((self.dims.width, self.dims.height)) + } + + /// Decode one frame; returns the picture when it is for display + /// (`show_frame`). Hidden frames still update the decode state. + pub fn decode(&mut self, frame: &[u8]) -> Result> { + let (header, _part0) = FrameHeader::parse(frame, &mut self.state)?; + match header.tag.frame_type { + FrameType::Key => self.decode_keyframe(frame, header), + FrameType::Inter => Err(Error::unsupported( + "VP8 inter frame", + "inter-frame decoding is the next milestone of this crate", + )), + } + } + + fn ensure_buffers(&mut self, kf: KeyFrameDims) { + let (mb_cols, mb_rows) = mb_geometry(kf.width, kf.height); + if self.mb_cols != mb_cols || self.mb_rows != mb_rows { + self.y.resize(mb_cols, mb_rows, 16); + self.u.resize(mb_cols, mb_rows, 8); + self.v.resize(mb_cols, mb_rows, 8); + self.mb_info = vec![MbInfo::default(); (mb_cols + 1) * (mb_rows + 1)]; + self.token_ctxs = TokenContexts::new(mb_cols); + } + self.mb_cols = mb_cols; + self.mb_rows = mb_rows; + self.dims = kf; + // Reset the mode border (row 0 / column 0) so the top-left mode + // contexts read DC_PRED like a fresh decode. + for col in 0..=mb_cols { + self.mb_info[col] = MbInfo::default(); + } + for row in 0..=mb_rows { + self.mb_info[row * (mb_cols + 1)] = MbInfo::default(); + } + } + + /// Mode-record index for MB (row, col); row/col 0 is the border. + fn mbi(&self, row: usize, col: usize) -> &MbInfo { + &self.mb_info[row * (self.mb_cols + 1) + col] + } + + fn mbi_mut(&mut self, row: usize, col: usize) -> &mut MbInfo { + let w = self.mb_cols + 1; + &mut self.mb_info[row * w + col] + } + + fn decode_keyframe(&mut self, frame: &[u8], header: FrameHeader) -> Result> { + let kf = header.dims.expect("key frame header carries dimensions"); + self.ensure_buffers(kf); + + // Token partition bool decoders (§9.5). + let mut partitions = Vec::with_capacity(header.partition_sizes.len()); + let mut off = header.token_data_offset + 3 * (header.partition_sizes.len() - 1); + for &sz in &header.partition_sizes { + let end = off + sz as usize; + let slice = frame + .get(off..end) + .ok_or_else(|| Error::corrupt("VP8 token partition extends past frame end"))?; + partitions.push(BoolDecoder::new(slice)?); + off = end; + } + + // Dequant factors per segment (dixie dequant_init, §10/§14.1). + let seg = &header.segmentation; + let mut dqf = [Dequant { + y1_dc: 0, + y1_ac: 0, + y2_dc: 0, + y2_ac: 0, + uv_dc: 0, + uv_ac: 0, + }; 4]; + for (i, dq) in dqf.iter_mut().enumerate() { + let q = if seg.enabled { + if seg.abs_delta { + seg.quant_idx[i] + } else { + i32::from(header.quant.yac_qi) + seg.quant_idx[i] + } + } else { + i32::from(header.quant.yac_qi) + }; + *dq = transform::dequant( + q, + header.quant.ydc_delta, + header.quant.y2dc_delta, + header.quant.y2ac_delta, + header.quant.uvdc_delta, + header.quant.uvac_delta, + ); + } + + let hdr_start = crate::frame::FRAME_TAG_SZ + crate::frame::KEYFRAME_HEADER_SZ; + let mut hdr_dec = BoolDecoder::new(&frame[hdr_start..header.token_data_offset])?; + + self.token_ctxs.reset_above_row(); + + for row in 1..=self.mb_rows { + self.token_ctxs.reset_left(); + // Phase 1: parse every mode record of the row (partition 0). + for col in 1..=self.mb_cols { + let mut mb = MbInfo::default(); + if header.segmentation.enabled && header.segmentation.update_map { + mb.segment_id = + hdr_dec.read_tree(&SEGMENT_TREE, &header.segmentation.tree_probs); + } + if header.coeff_skip_enabled { + mb.skip = hdr_dec.read_bool(header.prob_skip_false); + } + self.decode_kf_modes(&mut hdr_dec, row, col, &mut mb); + *self.mbi_mut(row, col) = mb; + } + + // Phases 2+3 per MB: tokens then reconstruction. Token row + // `r` (0-based) reads partition `r % n` like the reference. + let part = (row - 1) % partitions.len(); + for col in 1..=self.mb_cols { + let mb = self.mbi(row, col).clone(); + let has_y2 = mb.has_y2(); + let seg_i = usize::from(header.segmentation.enabled) * usize::from(mb.segment_id); + let dq = &dqf[seg_i]; + let mb_dq = Dq { + y1_dc: dq.y1_dc, + y1_ac: dq.y1_ac, + uv_dc: dq.uv_dc, + uv_ac: dq.uv_ac, + y2_dc: dq.y2_dc, + y2_ac: dq.y2_ac, + }; + let probs = self.state.coeff_probs; + let coeffs = if mb.skip { + tokens::skip_mb_tokens(&mut self.token_ctxs, col - 1, has_y2) + } else { + tokens::decode_mb_tokens( + &mut partitions[part], + &probs, + &mb_dq, + has_y2, + &mut self.token_ctxs, + col - 1, + ) + }; + self.mb_info[row * (self.mb_cols + 1) + col].has_nz = coeffs.has_nonzero(); + self.reconstruct_intra_mb(row - 1, col - 1, &mb, &coeffs); + } + } + + // Loop filter post-pass (see module docs for the ordering + // equivalence argument). + if header.filter_level > 0 { + let infos: Vec = (0..self.mb_rows) + .flat_map(|r| (0..self.mb_cols).map(move |c| (r, c))) + .map(|(r, c)| { + let mb = self.mbi(r + 1, c + 1); + MbFilterInfo { + level: self.mb_filter_level(&header, mb), + inner_edges: mb.has_nz || !mb.has_y2(), + } + }) + .collect(); + // The planes are bordered; the filter sees the unbordered + // image (same row pitch) starting at pixel (0, 0). + let (ystride, ustride, vstride) = (self.y.stride, self.u.stride, self.v.stride); + let (mcols, mrows) = (self.mb_cols, self.mb_rows); + let simple = header.filter_type == 1; + let sharpness = header.sharpness_level; + let yimg = &mut self.y.data[1 + ystride..]; + let uimg = &mut self.u.data[1 + ustride..]; + let vimg = &mut self.v.data[1 + vstride..]; + loopfilter::filter_frame_ex( + yimg, uimg, vimg, ystride, ustride, mcols, mrows, sharpness, simple, &infos, true, + ); + } + + self.frame_decoded = true; + Ok(header.tag.show_frame.then(|| self.crop())) + } + + /// Per-MB loop filter level (dixie `calculate_filter_parameters`): + /// segment adjustment, then ref/mode deltas, clamped 0..63. Key + /// frames are all intra — ref index 0 (`CURRENT_FRAME`), with + /// `mode_delta[0]` applying to B_PRED. + fn mb_filter_level(&self, header: &FrameHeader, mb: &MbInfo) -> u8 { + let seg = &header.segmentation; + let mut level = i32::from(header.filter_level); + if seg.enabled { + let d = seg.lf_level[usize::from(mb.segment_id)]; + level = if seg.abs_delta { d } else { level + d }; + } + level = level.clamp(0, 63); + if header.lf_delta_enabled { + level += self.state.ref_lf_delta[0]; + if mb.y_mode == modes::YMode::BPred.as_u8() { + level += self.state.mode_lf_delta[0]; + } + level = level.clamp(0, 63); + } + level as u8 + } + + /// Key-frame mode record (§11): Y mode at fixed probabilities, then + /// 16 context-conditioned subblock modes for B_PRED, then chroma. + fn decode_kf_modes( + &mut self, + d: &mut BoolDecoder<'_>, + row: usize, + col: usize, + mb: &mut MbInfo, + ) { + let ymode = modes::read_kf_ymode(d); + mb.y_mode = ymode.as_u8(); + if ymode == modes::YMode::BPred { + for j in 0..16u8 { + let a = self.above_block_mode(row, col, j, mb); + let l = self.left_block_mode(row, col, j, mb); + mb.b_modes[usize::from(j)] = + modes::read_bmode(d, &KF_BMODE_PROB[usize::from(a)][usize::from(l)]).as_u8(); + } + } + mb.uv_mode = modes::read_uvmode(d, &modes::KF_UV_MODE_PROBS).as_u8(); + } + + /// Above subblock mode context (dixie `above_block_mode`): subblocks + /// 0-3 take the above MB's derived mode, inner subblocks the mode + /// `j-4` of this same MB (already decoded into `mb`). + fn above_block_mode(&self, row: usize, col: usize, j: u8, mb: &MbInfo) -> u8 { + if j < 4 { + let above = self.mbi(row - 1, col); + if above.y_mode == modes::YMode::BPred.as_u8() { + above.b_modes[usize::from(j) + 12] + } else { + ymode_as_bmode(above.y_mode) + } + } else { + mb.b_modes[usize::from(j) - 4] + } + } + + /// Left subblock mode context (dixie `left_block_mode`). + fn left_block_mode(&self, row: usize, col: usize, j: u8, mb: &MbInfo) -> u8 { + if j % 4 == 0 { + let left = self.mbi(row, col - 1); + if left.y_mode == modes::YMode::BPred.as_u8() { + left.b_modes[usize::from(j) + 3] + } else { + ymode_as_bmode(left.y_mode) + } + } else { + mb.b_modes[usize::from(j) - 1] + } + } + + /// Predict and reconstruct one intra key-frame MB at pixel (x, y). + /// + /// Whole-MB modes predict once from the pre-MB edges and then fold + /// the 24 residual blocks in; B_PRED interleaves: each 4x4 subblock + /// predicts from the reconstructed image (which already carries the + /// earlier subblocks' residuals, §12.3) and is written back before + /// the next subblock is predicted. + fn reconstruct_intra_mb(&mut self, row: usize, col: usize, mb: &MbInfo, coeffs: &MbCoeffs) { + let x = col * 16; + let y = row * 16; + let y_mode = mb.y_mode; + let uv_mode = mb.uv_mode; + let b_modes = mb.b_modes; + let have_above = row > 0; + let have_left = col > 0; + + // The Y2 inverse WHT feeds the 16 Y subblock DCs (§14.2). + let y_dcs: [i16; 16] = if coeffs.has_y2 { + transform::iwht4x4(&coeffs.y2) + } else { + [0; 16] + }; + if std::env::var_os("EC_VP8_DEBUG").is_some() { + eprintln!( + "MB({row},{col}) ymode={} uv={} y2={:?} y2has={} y0[:4]={:?} eobs24={} dcs={:?}", + y_mode, + uv_mode, + coeffs.y2, + coeffs.has_y2, + &coeffs.y[0][..4], + coeffs.eobs[24], + &y_dcs[..4] + ); + } + + if y_mode == modes::YMode::BPred.as_u8() { + for b in 0..16usize { + let bx = (b % 4) * 4; + let by = (b / 4) * 4; + // A row: 4 above pixels then 4 above-right (§12.3); the + // above-right extras are shared by right-edge subblocks + // 3, 7, 11 and 15. + let mut a8 = [0u8; 8]; + let arow = self.y.at_above(x + bx, y + by); + a8[..4].copy_from_slice(&self.y.data[arow..arow + 4]); + if bx + 4 == 16 { + a8[4..].copy_from_slice(&self.above_right(x, y)); + } else { + let ar = self.y.at_above(x + bx + 4, y + by); + a8[4..].copy_from_slice(&self.y.data[ar..ar + 4]); + } + let mut l4 = [0u8; 4]; + for (i, cell) in l4.iter_mut().enumerate() { + *cell = self.y.data[self.y.at_left(x + bx, y + by + i)]; + } + let p = self.y.data[self.y.at_above_left(x + bx, y + by)]; + let mut block = [0u8; 16]; + intra::predict4(b_modes[b], &a8, &l4, p, &mut block); + for i in 0..4 { + let d = self.y.at(x + bx, y + by + i); + self.y.data[d..d + 4].copy_from_slice(&block[i * 4..i * 4 + 4]); + } + let mut c = coeffs.y[b]; + if coeffs.has_y2 { + c[0] = y_dcs[b]; + } + if c.iter().any(|&v| v != 0) { + let dst = self.y.at(x + bx, y + by); + let stride = self.y.stride; + idct_add_into(&mut self.y.data, &c, &block, 4, 0, dst, stride); + } + } + } else { + // Gather luma edges (border cells carry the 127/129 fills). + let (above, left, above_left) = { + let ay = self.y.at_above(x, y); + let mut a = [0u8; 16]; + let mut l = [0u8; 16]; + a.copy_from_slice(&self.y.data[ay..ay + 16]); + for (i, cell) in l.iter_mut().enumerate() { + *cell = self.y.data[self.y.at_left(x, y + i)]; + } + let al = self.y.data[self.y.at_above_left(x, y)]; + (a, l, al) + }; + let mut pred = [0u8; 256]; + intra::predict16( + y_mode, have_above, have_left, &above, &left, above_left, &mut pred, + ); + for b in 0..16usize { + let bx = (b % 4) * 4; + let by = (b / 4) * 4; + let mut c = coeffs.y[b]; + if coeffs.has_y2 { + c[0] = y_dcs[b]; + } + if c.iter().all(|&v| v == 0) { + for i in 0..4 { + let d = self.y.at(x + bx, y + by + i); + let s = (by + i) * 16 + bx; + self.y.data[d..d + 4].copy_from_slice(&pred[s..s + 4]); + } + } else { + let dst = self.y.at(x + bx, y + by); + let stride = self.y.stride; + idct_add_into(&mut self.y.data, &c, &pred, 16, by * 16 + bx, dst, stride); + } + } + } + + // Chroma: 8x8 prediction then four residual blocks per plane. + let (above_u, left_u, al_u) = self.chroma_edges(col, row, 0); + let (above_v, left_v, al_v) = self.chroma_edges(col, row, 1); + let mut pred_u = [0u8; 64]; + let mut pred_v = [0u8; 64]; + intra::predict8( + uv_mode, + have_above, + have_left, + &above_u, + &left_u, + al_u, + &mut pred_u, + ); + intra::predict8( + uv_mode, + have_above, + have_left, + &above_v, + &left_v, + al_v, + &mut pred_v, + ); + let (cx, cy) = (x / 2, y / 2); + for (plane_data, coeffs_uv, pred8, stride) in [ + (&mut self.u.data, &coeffs.u, &pred_u, self.u.stride), + (&mut self.v.data, &coeffs.v, &pred_v, self.v.stride), + ] { + for b in 0..4usize { + let bx = (b % 2) * 4; + let by = (b / 2) * 4; + let c = coeffs_uv[b]; + let dst = (1 + cy + by) * stride + 1 + cx + bx; + if c.iter().all(|&v| v == 0) { + for i in 0..4 { + let s = (by + i) * 8 + bx; + let d = dst + i * stride; + plane_data[d..d + 4].copy_from_slice(&pred8[s..s + 4]); + } + } else { + idct_add_into(plane_data, &c, pred8, 8, by * 8 + bx, dst, stride); + } + } + } + } + + /// Above-right extras (§12.3): real pixels from the above row, + /// replicated last pixel on the rightmost MB, 127 on the top row. + fn above_right(&self, x: usize, y: usize) -> [u8; 4] { + if y == 0 { + [127; 4] + } else if x + 16 >= self.mb_cols * 16 { + [self.y.data[self.y.at_above(x + 15, y)]; 4] + } else { + let off = self.y.at_above(x + 16, y); + [ + self.y.data[off], + self.y.data[off + 1], + self.y.data[off + 2], + self.y.data[off + 3], + ] + } + } + + fn chroma_edges(&self, col: usize, row: usize, plane: usize) -> ([u8; 8], [u8; 8], u8) { + let p = if plane == 0 { &self.u } else { &self.v }; + let x = col * 8; + let y = row * 8; + let mut a = [0u8; 8]; + let mut l = [0u8; 8]; + let aoff = p.at_above(x, y); + a.copy_from_slice(&p.data[aoff..aoff + 8]); + for (i, cell) in l.iter_mut().enumerate() { + *cell = p.data[p.at_left(x, y + i)]; + } + let al = p.data[p.at_above_left(x, y)]; + (a, l, al) + } + + /// Crop the padded planes to the real frame size. + fn crop(&self) -> Picture { + let w = usize::from(self.dims.width); + let h = usize::from(self.dims.height); + let mut y = Vec::with_capacity(w * h); + for row in 0..h { + let off = self.y.at(0, row); + y.extend_from_slice(&self.y.data[off..off + w]); + } + let (cw, ch) = ((w + 1) / 2, (h + 1) / 2); + let mut u = Vec::with_capacity(cw * ch); + let mut v = Vec::with_capacity(cw * ch); + for row in 0..ch { + let off = self.u.at(0, row); + u.extend_from_slice(&self.u.data[off..off + cw]); + let off = self.v.at(0, row); + v.extend_from_slice(&self.v.data[off..off + cw]); + } + Picture { + y, + u, + v, + width: self.dims.width, + height: self.dims.height, + stride: w, + uv_stride: cw, + } + } +} + +impl Default for Decoder { + fn default() -> Self { + Self::new() + } +} + +/// Segment-map coding tree (RFC 6386 §10): plain two-level split of 0-3. +const SEGMENT_TREE: [i8; 6] = [2, 4, 0, -1, -2, -3]; + +fn ymode_as_bmode(y: u8) -> u8 { + match y { + 0 => 0, // DC_PRED -> B_DC_PRED + 1 => 2, // V_PRED -> B_VE_PRED + 2 => 3, // H_PRED -> B_HE_PRED + 3 => 1, // TM_PRED -> B_TM_PRED + _ => unreachable!("non-B_PRED luma mode {y}"), + } +} + +/// Add one 4x4 block's dequantized-coefficient residual to its +/// prediction: reads the prediction patch from `pred`, clamps, writes +/// into the strided plane (§14.4/§14.5). +fn idct_add_into( + plane: &mut [u8], + coeffs: &[i16; 16], + pred: &[u8], + pred_stride: usize, + pred_off: usize, + dst_off: usize, + dst_stride: usize, +) { + let mut p = [0u8; 16]; + for i in 0..4 { + let s = pred_off + i * pred_stride; + p[i * 4..i * 4 + 4].copy_from_slice(&pred[s..s + 4]); + } + let mut out = [0u8; 16]; + transform::idct4x4_add(coeffs, &p, &mut out); + for i in 0..4 { + let d = dst_off + i * dst_stride; + plane[d..d + 4].copy_from_slice(&out[i * 4..i * 4 + 4]); + } +} diff --git a/crates/ec-vp8/src/header.rs b/crates/ec-vp8/src/header.rs index 6cf6d54b..097d6200 100644 --- a/crates/ec-vp8/src/header.rs +++ b/crates/ec-vp8/src/header.rs @@ -49,8 +49,10 @@ impl Default for PersistedState { Self { coeff_probs: DEFAULT_COEFF_PROBS, mv_probs: DEFAULT_MV_PROBS, - ymode_probs: [145, 156, 163, 128], - uv_mode_probs: [142, 114, 183], + // Interframe tree defaults (libvpx vp8_ymode_prob / + // vp8_uv_mode_prob); key frames reset these too. + ymode_probs: [112, 86, 140, 37], + uv_mode_probs: [162, 101, 204], segmentation: SegmentationState::default(), ref_lf_delta: [0; 4], mode_lf_delta: [0; 4], @@ -412,7 +414,7 @@ impl FrameHeader { } probs } else { - (145, 156, 163) + (112, 86, 140) // placeholders; only read on inter frames }; for c in 0..2 { for j in 0..MV_PROB_CNT { @@ -422,7 +424,10 @@ impl FrameHeader { } } - if d.overreads() > 0 { + // The reference decoder zero-fills past the end of a partition; + // tiny partitions (e.g. one-MB key frames) can legitimately + // overrun by a byte or two. Gross overruns are still desyncs. + if d.overreads() > 16 { return Err(Error::corrupt(format!( "VP8 first partition over-read by {} bytes (header desync)", d.overreads() diff --git a/crates/ec-vp8/src/intra.rs b/crates/ec-vp8/src/intra.rs new file mode 100644 index 00000000..d2d82021 --- /dev/null +++ b/crates/ec-vp8/src/intra.rs @@ -0,0 +1,711 @@ +//! Intra-frame prediction for VP8 (RFC 6386, Section 12). +//! +//! This module implements the spatial predictors a VP8 decoder applies to +//! intra-coded macroblocks: the 16x16 luma predictors and 8x8 (per-plane) +//! chroma predictors of Section 12.2/12.3, and the ten 4x4 subblock +//! predictors of Section 12.3. All functions are dependency-free, `unsafe`-free, +//! allocate nothing, and are bit-exact against the normative integer math of +//! the RFC code listings (which are in turn identical to the libvpx oracle in +//! `vp8/common/reconintra.c`, `vp8/common/reconintra4x4.c` and +//! `vpx_dsp/intrapred.c`). +//! +//! # Edge-pixel conventions (RFC 6386 Section 12, p.50) +//! +//! Pixels outside the visible frame are pre-filled by the caller: 127 for the +//! row above the top row (including the above-left pixel `P`), 129 for the +//! column left of the leftmost column. V_PRED/H_PRED/TM_PRED consume those +//! fill values directly; DC_PRED instead decides from the availability flags +//! which genuinely-visible pixels to average (RFC Section 12.2, "Note that +//! the averages used in these exceptional cases are not the same as those +//! that would be arrived at by using the out-of-bounds A and L values"). +//! +//! # 4x4 above-right synthesis +//! +//! The 4x4 predictors use an 8-pixel above row `A[0..8]`: the 4 pixels +//! immediately above the subblock plus the 4 "above-right" pixels +//! (frame positions (-1,16)..(-1,19) relative to the macroblock; RFC +//! Section 12.3, subblocks 3/7/11/15). Producing those extra four pixels is +//! the caller's job: for a macroblock not on the top frame row they come from +//! the row above (replicating pixel (-1,15) at the rightmost macroblock of a +//! row); on the top frame row they are 127. [`predict4`] only consumes +//! `A[0..8]` as given. + +#![deny(unsafe_code)] + +/// Weighted average of three adjacent pixels centered at `y` +/// (RFC 6386 Section 12.3 `avg3`: `(x + 2y + z + 2) >> 2`; libvpx `AVG3`). +/// +/// Arguments are valid pixel values, so the result always fits in `u8` and no +/// clamp is needed (RFC Section 12.3, comment above `avg3`). +#[inline] +fn avg3(x: u8, y: u8, z: u8) -> u8 { + ((u32::from(x) + 2 * u32::from(y) + u32::from(z) + 2) >> 2) as u8 +} + +/// Simple average of two pixels (RFC 6386 Section 12.3 `avg2`: +/// `(x + y + 1) >> 1`; libvpx `AVG2`). +#[inline] +fn avg2(x: u8, y: u8) -> u8 { + ((u32::from(x) + u32::from(y) + 1) >> 1) as u8 +} + +/// `clamp255(v)`: clamp an integer pixel difference into the valid `u8` range +/// (RFC 6386 Section 12.2 `TMpred` / Section 12.3 `B_TM_PRED`). +#[inline] +fn clamp255(v: i32) -> u8 { + v.clamp(0, 255) as u8 +} + +/// Shared DC/V/H/TM core for the 16x16 luma and 8x8 chroma blocks +/// (RFC 6386 Section 12.2 semantics; Section 12.3 states 16x16 luma is +/// "essentially identical" with 16-pixel edges). +/// +/// DC rounding follows the RFC formula `DCvalue = (sum + (1 << (shf-1))) >> shf` +/// with `shf` = log2 of the number of averaged pixels: 32/16 pixels for the +/// 16x16 both/single-edge cases, 16/8 for 8x8. +fn predict_block( + mode: u8, + have_above: bool, + have_left: bool, + above: &[u8; N], + left: &[u8; N], + above_left: u8, + out: &mut [u8], +) { + match mode { + // DC_PRED: fill the block with the average of the genuinely visible + // edge pixels; availability flags alone decide which edges count + // (RFC Section 12.2). Neither edge: constant 128. + 0 => { + let sum_above: u32 = above.iter().map(|&p| u32::from(p)).sum(); + let sum_left: u32 = left.iter().map(|&p| u32::from(p)).sum(); + let tz = N.trailing_zeros(); // log2(N) + let v: u32 = match (have_above, have_left) { + (true, true) => (sum_above + sum_left + N as u32) >> (tz + 1), + (false, false) => 128, + // Above available only: average the above row. + (true, false) => (sum_above + (N as u32 >> 1)) >> tz, + // Left column available only: average the left column. + (false, true) => (sum_left + (N as u32 >> 1)) >> tz, + }; + out.fill(v as u8); + } + // V_PRED: every row is a copy of the above row A (RFC Section 12.2). + 1 => { + for row in out.chunks_exact_mut(N) { + row.copy_from_slice(above); + } + } + // H_PRED: every column is a copy of the left column L (RFC Section 12.2). + 2 => { + for (row, &l) in out.chunks_exact_mut(N).zip(left.iter()) { + row.fill(l); + } + } + // TM_PRED: X_ij = clamp255(L_i + A_j - P) (RFC Section 12.2 `TMpred`). + // Unlike DC_PRED this mode does use the 127/129 out-of-bounds fills. + 3 => { + for (row, &l) in out.chunks_exact_mut(N).zip(left.iter()) { + for (o, &a) in row.iter_mut().zip(above.iter()) { + *o = clamp255(i32::from(l) + i32::from(a) - i32::from(above_left)); + } + } + } + _ => panic!("predict_block: invalid intra mode {mode} (expected 0..=3)"), + } +} + +/// 16x16 luma prediction (RFC 6386 Section 12.3; predictor math per +/// Section 12.2). +/// +/// `mode` is a u8 in `{0=DC, 1=V, 2=H, 3=TM}`. `above` holds the 16 +/// reconstructed pixels of the row above the macroblock, `left` the 16 pixels +/// of the column to its left (adjacent entries separated by one frame row), +/// `above_left` is the corner pixel `P`. `have_above`/`have_left` state +/// whether those edges are genuinely in-frame. +/// +/// For DC the flags alone decide what is averaged (the out-of-bounds fills +/// are NOT used); V/H/TM consume the caller-prepared out-of-bounds fills +/// (127 above/`above_left` on the top frame row, 129 on the left frame +/// column) written into `above`/`left`/`above_left`. +/// +/// `out` receives 256 row-major prediction pixels. +pub fn predict16( + mode: u8, + have_above: bool, + have_left: bool, + above: &[u8; 16], + left: &[u8; 16], + above_left: u8, + out: &mut [u8; 256], +) { + predict_block::<16>(mode, have_above, have_left, above, left, above_left, out); +} + +/// 8x8 chroma prediction for one plane (RFC 6386 Section 12.2). +/// +/// Identical semantics to [`predict16`] with 8-pixel edges; call it once for +/// U and once for V. `mode` is a u8 in `{0=DC, 1=V, 2=H, 3=TM}`. DC averages +/// 16 pixels (both edges: `(sumA + sumL + 8) >> 4`) or 8 pixels (one edge: +/// `(sum + 4) >> 3`), or fills 128. +/// +/// `out` receives 64 row-major prediction pixels. +pub fn predict8( + mode: u8, + have_above: bool, + have_left: bool, + above: &[u8; 8], + left: &[u8; 8], + above_left: u8, + out: &mut [u8; 64], +) { + predict_block::<8>(mode, have_above, have_left, above, left, above_left, out); +} + +/// 4x4 subblock prediction (RFC 6386 Section 12.3 `subblock_intra_predict`). +/// +/// `mode` is a BMode integer: `0=B_DC 1=B_TM 2=B_VE 3=B_HE 4=B_LD 5=B_RD +/// 6=B_VR 7=B_VL 8=B_HD 9=B_HU`. `above` is the 8-pixel row `A[0..8]` +/// (4 above + 4 above-right; see the [module docs](self) for the caller-side +/// synthesis rule), `left` is `L[0..4]`, `above_left` is `P = A[-1] = L[-1]`. +/// +/// Both edges are always considered present for subblocks: the caller +/// pre-fills out-of-bounds pixels (127 above including P, 129 left) before +/// the call, which is why no availability flags exist here. +/// +/// `out` receives 16 row-major prediction pixels. +/// +/// # RFC typo +/// +/// The RFC listing for `B_HD_PRED` contains the line +/// `B[2][0] = B[3][2] = svg2p(E + 1)`; `svg2p` is a typo for `avg2p` (there +/// is no `svg2p` definition; libvpx's `d153_predictor` computes `AVG2(K, J)` +/// there, confirming the correction implemented here). +pub fn predict4(mode: u8, above: &[u8; 8], left: &[u8; 4], above_left: u8, out: &mut [u8; 16]) { + // The 9 already-constructed edge pixels in RFC scan order: + // E[0..4] = L[3], L[2], L[1], L[0]; E[4] = P; E[5..9] = A[0..4]. + let e: [u8; 9] = [ + left[3], left[2], left[1], left[0], above_left, above[0], above[1], above[2], above[3], + ]; + // Row-major B[r][c] = b[r * 4 + c]. + let mut b = [0u8; 16]; + // avg3p(E + k) = avg3(E[k-1], E[k], E[k+1]); avg2p(E + k) = avg2(E[k], E[k+1]). + match mode { + // B_DC_PRED: DC value = (sum(A[0..4]) + sum(L[0..4]) + 4) >> 3. + 0 => { + let mut v: u32 = 4; + for i in 0..4 { + v += u32::from(above[i]) + u32::from(left[i]); + } + v >>= 3; + b.fill(v as u8); + } + // B_TM_PRED: just like 16x16 TM_PRED (RFC Section 12.3). + 1 => { + for r in 0..4 { + for c in 0..4 { + b[r * 4 + c] = + clamp255(i32::from(left[r]) + i32::from(above[c]) - i32::from(above_left)); + } + } + } + // B_VE_PRED: all four rows = smoothed top row avg3p(A + c), where + // A[-1] = P participates in column 0 (libvpx `vpx_ve_predictor_4x4`). + 2 => { + for c in 0..4usize { + let v = if c == 0 { + avg3(above_left, above[0], above[1]) + } else { + avg3(above[c - 1], above[c], above[c + 1]) + }; + b[c] = v; + b[4 + c] = v; + b[8 + c] = v; + b[12 + c] = v; + } + } + // B_HE_PRED: columns = smoothed left column; bottom row exceptional + // because L[4] does not exist: avg3(L[2], L[3], L[3]). + 3 => { + let rows = [ + avg3(above_left, left[0], left[1]), + avg3(left[0], left[1], left[2]), + avg3(left[1], left[2], left[3]), + avg3(left[2], left[3], left[3]), + ]; + for (r, &v) in rows.iter().enumerate() { + b[r * 4..r * 4 + 4].fill(v); + } + } + // B_LD_PRED: southwest (left and down) 45-degree diagonals off the + // above row; B[3][3] uses avg3(A[6], A[7], A[7]) because A[8] does + // not exist (libvpx `d45e_predictor_4x4`). + 4 => { + b[0] = avg3(above[0], above[1], above[2]); + b[1] = avg3(above[1], above[2], above[3]); + b[4] = b[1]; + b[2] = avg3(above[2], above[3], above[4]); + b[5] = b[2]; + b[8] = b[2]; + b[3] = avg3(above[3], above[4], above[5]); + b[6] = b[3]; + b[9] = b[3]; + b[12] = b[3]; + b[7] = avg3(above[4], above[5], above[6]); + b[10] = b[7]; + b[13] = b[7]; + b[11] = avg3(above[5], above[6], above[7]); + b[14] = b[11]; + b[15] = avg3(above[6], above[7], above[7]); + } + // B_RD_PRED: southeast 45-degree diagonals off the whole E edge + // (libvpx `d135_predictor_4x4`). + 5 => { + b[12] = avg3(e[0], e[1], e[2]); + b[13] = avg3(e[1], e[2], e[3]); + b[8] = b[13]; + b[14] = avg3(e[2], e[3], e[4]); + b[9] = b[14]; + b[4] = b[14]; + b[15] = avg3(e[3], e[4], e[5]); + b[10] = b[15]; + b[5] = b[15]; + b[0] = b[15]; + b[11] = avg3(e[4], e[5], e[6]); + b[6] = b[11]; + b[1] = b[11]; + b[7] = avg3(e[5], e[6], e[7]); + b[2] = b[7]; + b[3] = avg3(e[6], e[7], e[8]); + } + // B_VR_PRED: vertical-right diagonals mixing avg3/avg2 along E + // (libvpx `d117_predictor_4x4`). + 6 => { + b[12] = avg3(e[1], e[2], e[3]); + b[8] = avg3(e[2], e[3], e[4]); + b[13] = avg3(e[3], e[4], e[5]); + b[4] = b[13]; + b[9] = avg2(e[4], e[5]); + b[0] = b[9]; + b[14] = avg3(e[4], e[5], e[6]); + b[5] = b[14]; + b[10] = avg2(e[5], e[6]); + b[1] = b[10]; + b[15] = avg3(e[5], e[6], e[7]); + b[6] = b[15]; + b[11] = avg2(e[6], e[7]); + b[2] = b[11]; + b[7] = avg3(e[6], e[7], e[8]); + b[3] = avg2(e[7], e[8]); + } + // B_VL_PRED: vertical-left diagonals off the above row; the last two + // values do not strictly follow the pattern (RFC Section 12.3; + // libvpx `d63e_predictor_4x4`). + 7 => { + b[0] = avg2(above[0], above[1]); + b[4] = avg3(above[0], above[1], above[2]); + b[8] = avg2(above[1], above[2]); + b[1] = b[8]; + b[5] = avg3(above[1], above[2], above[3]); + b[12] = b[5]; + b[9] = avg2(above[2], above[3]); + b[2] = b[9]; + b[13] = avg3(above[2], above[3], above[4]); + b[6] = b[13]; + b[10] = avg2(above[3], above[4]); + b[3] = b[10]; + b[14] = avg3(above[3], above[4], above[5]); + b[7] = b[14]; + b[11] = avg3(above[4], above[5], above[6]); + b[15] = avg3(above[5], above[6], above[7]); + } + // B_HD_PRED: horizontal-down diagonals; the RFC's `svg2p(E + 1)` is + // the avg2p correction noted in this function's docs (libvpx + // `d153_predictor_4x4`). + 8 => { + b[12] = avg2(e[0], e[1]); + b[13] = avg3(e[0], e[1], e[2]); + b[8] = avg2(e[1], e[2]); // corrected svg2p -> avg2p line + b[14] = b[8]; + b[9] = avg3(e[1], e[2], e[3]); + b[15] = b[9]; + b[10] = avg2(e[2], e[3]); + b[4] = b[10]; + b[11] = avg3(e[2], e[3], e[4]); + b[5] = b[11]; + b[6] = avg2(e[3], e[4]); + b[0] = b[6]; + b[7] = avg3(e[3], e[4], e[5]); + b[1] = b[7]; + b[2] = avg3(e[4], e[5], e[6]); + b[3] = avg3(e[5], e[6], e[7]); + } + // B_HU_PRED: horizontal-up diagonals off the left column; the bottom + // rows cannot follow the pattern and collapse to L[3] (RFC + // Section 12.3; libvpx `d207_predictor_4x4`). + 9 => { + b[0] = avg2(left[0], left[1]); + b[1] = avg3(left[0], left[1], left[2]); + b[2] = avg2(left[1], left[2]); + b[4] = b[2]; + b[3] = avg3(left[1], left[2], left[3]); + b[5] = b[3]; + b[6] = avg2(left[2], left[3]); + b[8] = b[6]; + b[7] = avg3(left[2], left[3], left[3]); + b[9] = b[7]; + let v = left[3]; + b[10] = v; + b[11] = v; + b[12] = v; + b[13] = v; + b[14] = v; + b[15] = v; + } + _ => panic!("predict4: invalid intra 4x4 mode {mode} (expected 0..=9)"), + } + out.copy_from_slice(&b); +} + +#[cfg(test)] +mod tests { + use super::*; + + // ---------------------------------------------------------------- -- + // Reference model used to derive the expected vectors below. It is a + // verbatim Python transcription of RFC 6386 Section 12.3 + // subblock_intra_predict (with svg2p corrected to avg2p); outputs were + // generated with it and then hand-spot-checked: + // + // def avg2(x, y): return (x + y + 1) >> 1 + // def avg3(x, y, z): return (x + 2*y + z + 2) >> 2 + // def clamp255(v): return max(0, min(255, v)) + // # A = A[0..8], L = L[0..4], P = above-left + // E = [L[3], L[2], L[1], L[0], P, A[0], A[1], A[2], A[3]] + // B_DC: v = (4 + sum(A[0:4]) + sum(L[0:4])) >> 3 + // B_TM: B[r][c] = clamp255(L[r] + A[c] - P) + // B_VE: col c: avg3(P, A0, A1) then avg3(A[c-1], A[c], A[c+1]) + // B_HE: rows avg3(P, L0, L1), avg3(L0, L1, L2), avg3(L1, L2, L3), + // avg3(L2, L3, L3) + // B_LD: B[0][0]=avg3(A0,A1,A2); B[0][1]=B[1][0]=avg3(A1,A2,A3); ... + // B[3][3]=avg3(A6,A7,A7) + // B_RD: B[3][0]=avg3(E0,E1,E2); B[3][1]=B[2][0]=avg3(E1,E2,E3); + // B[3][2]=B[2][1]=B[1][0]=avg3(E2,E3,E4); + // diag=avg3(E3,E4,E5); ...; B[0][3]=avg3(E6,E7,E8) + // B_VR: B[3][0]=avg3(E1,E2,E3); B[2][0]=avg3(E2,E3,E4); + // B[3][1]=B[1][0]=avg3(E3,E4,E5); B[2][1]=B[0][0]=avg2(E4,E5); + // B[3][2]=B[1][1]=avg3(E4,E5,E6); B[2][2]=B[0][1]=avg2(E5,E6); + // B[3][3]=B[1][2]=avg3(E5,E6,E7); B[2][3]=B[0][2]=avg2(E6,E7); + // B[1][3]=avg3(E6,E7,E8); B[0][3]=avg2(E7,E8) + // B_VL: B[0][0]=avg2(A0,A1); B[1][0]=avg3(A0,A1,A2); + // B[2][0]=B[0][1]=avg2(A1,A2); B[1][1]=B[3][0]=avg3(A1,A2,A3); + // B[2][1]=B[0][2]=avg2(A2,A3); B[3][1]=B[1][2]=avg3(A2,A3,A4); + // B[2][2]=B[0][3]=avg2(A3,A4); B[3][2]=B[1][3]=avg3(A3,A4,A5); + // B[2][3]=avg3(A4,A5,A6); B[3][3]=avg3(A5,A6,A7) + // B_HD: B[3][0]=avg2(E0,E1); B[3][1]=avg3(E0,E1,E2); + // B[2][0]=B[3][2]=avg2(E1,E2) <- svg2p typo corrected + // B[2][1]=B[3][3]=avg3(E1,E2,E3); + // B[2][2]=B[1][0]=avg2(E2,E3); + // B[2][3]=B[1][1]=avg3(E2,E3,E4); + // B[1][2]=B[0][0]=avg2(E3,E4); + // B[1][3]=B[0][1]=avg3(E3,E4,E5); + // B[0][2]=avg3(E4,E5,E6); B[0][3]=avg3(E5,E6,E7) + // B_HU: B[0][0]=avg2(L0,L1); B[0][1]=avg3(L0,L1,L2); + // B[0][2]=B[1][0]=avg2(L1,L2); B[0][3]=B[1][1]=avg3(L1,L2,L3); + // B[1][2]=B[2][0]=avg2(L2,L3); + // B[1][3]=B[2][1]=avg3(L2,L3,L3); + // B[2][2..4]=B[3][0..4]=L3 + // ---------------------------------------------------------------- -- + + /// Fixed edge pattern shared by all ten subblock tests: + /// above = [10,20,30,40,50,60,70,80], left = [15,25,35,45], P = 5. + const EDGE_A: [u8; 8] = [10, 20, 30, 40, 50, 60, 70, 80]; + const EDGE_L: [u8; 4] = [15, 25, 35, 45]; + const EDGE_P: u8 = 5; + + fn assert_pred4(mode: u8, expected: [u8; 16]) { + let mut out = [0u8; 16]; + predict4(mode, &EDGE_A, &EDGE_L, EDGE_P, &mut out); + assert_eq!(out, expected, "predict4 mode {mode}"); + } + + #[test] + fn subblock_dc_constant() { + // v = (4 + (10+20+30+40) + (15+25+35+45)) >> 3 = (4+100+120)>>3 = 28. + assert_pred4(0, [28; 16]); + } + + #[test] + fn subblock_tm_gradient() { + // B[r][c] = L[r] + A[c] - P = L[r] + A[c] - 5. + assert_pred4( + 1, + [ + 20, 30, 40, 50, // row 0: 15 + A[c] - 5 + 30, 40, 50, 60, // row 1: 25 + A[c] - 5 + 40, 50, 60, 70, // row 2 + 50, 60, 70, 80, // row 3 + ], + ); + } + + #[test] + fn subblock_ve_smoothed_row() { + // Row = avg3(A[c-1], A[c], A[c+1]) with A[-1] = P: + // avg3(5,10,20)=11, avg3(10,20,30)=20, avg3(20,30,40)=30, + // avg3(30,40,50)=40. + let row = [11, 20, 30, 40]; + let mut expected = [0u8; 16]; + for r in 0..4 { + expected[r * 4..r * 4 + 4].copy_from_slice(&row); + } + assert_pred4(2, expected); + } + + #[test] + fn subblock_he_smoothed_column() { + // Rows: avg3(5,15,25)=15, avg3(15,25,35)=25, avg3(25,35,45)=35, + // avg3(35,45,45)=43 (bottom-row exception, L[4] absent). + assert_pred4( + 3, + [ + 15, 15, 15, 15, 25, 25, 25, 25, 35, 35, 35, 35, 43, 43, 43, 43, + ], + ); + } + + #[test] + fn subblock_ld_downright_diagonal() { + // B[3][3] = avg3(70,80,80) = (70 + 160 + 80 + 2) >> 2 = 78 (A[8] + // does not exist). + assert_pred4( + 4, + [ + 20, 30, 40, 50, // avg3(10,20,30)=20, avg3(20,30,40)=30, ... + 30, 40, 50, 60, // + 40, 50, 60, 70, // + 50, 60, 70, 78, // + ], + ); + } + + #[test] + fn subblock_rd_downright_diagonal() { + // E = [45,35,25,15,5,10,20,30,40]. + // B[3][0] = avg3(45,35,25) = 35; B[3][1]=B[2][0] = avg3(35,25,15) = 25; + // B[3][2]=B[2][1]=B[1][0] = avg3(25,15,5) = 15; + // main diagonal = avg3(15,5,10) = 9; B[2][3]=B[1][2]=B[0][1] = + // avg3(5,10,20) = 11; B[1][3]=B[0][2] = avg3(10,20,30) = 20; + // B[0][3] = avg3(20,30,40) = 30. + assert_pred4( + 5, + [ + 9, 11, 20, 30, // + 15, 9, 11, 20, // + 25, 15, 9, 11, // + 35, 25, 15, 9, // + ], + ); + } + + #[test] + fn subblock_vr_mixed_diagonal() { + // E = [45,35,25,15,5,10,20,30,40]. + // B[0][0] = avg2(E4,E5) = avg2(5,10) = 8; + // B[0][1] = avg2(10,20) = 15; B[0][2] = avg2(20,30) = 25; + // B[0][3] = avg2(30,40) = 35; B[1][0] = avg3(15,5,10) = 9; + // B[1][1] = avg3(5,10,20) = 11; B[1][2] = avg3(10,20,30) = 20; + // B[1][3] = avg3(20,30,40) = 30; B[2][0] = avg3(25,15,5) = 15; + // B[2][1] = 8; B[2][2] = 15; B[2][3] = 25; + // B[3][0] = avg3(35,25,15) = 25; B[3][1] = 9; B[3][2] = 11; B[3][3] = 20. + assert_pred4( + 6, + [ + 8, 15, 25, 35, // + 9, 11, 20, 30, // + 15, 8, 15, 25, // + 25, 9, 11, 20, // + ], + ); + } + + #[test] + fn subblock_vl_downleft_diagonal() { + // avg2/avg3 pairs along the above row: + // cols: avg2(10,20)=15, avg2(20,30)=25, avg2(30,40)=35, avg2(40,50)=45; + // rows shift by avg3: 20, 30, 40, 50; last column 45/50/60/70 with + // B[2][3]=avg3(50,60,70)=60, B[3][3]=avg3(60,70,80)=70. + assert_pred4( + 7, + [ + 15, 25, 35, 45, // + 20, 30, 40, 50, // + 25, 35, 45, 60, // + 30, 40, 50, 70, // + ], + ); + } + + #[test] + fn subblock_hd_uses_avg2p_for_svg2p_typo_line() { + // E = [45,35,25,15,5,10,20,30,40]. + // The RFC's `svg2p(E + 1)` line: B[2][0] = B[3][2] = avg2p(E+1) = + // avg2(E[1], E[2]) = avg2(35,25) = 30. A mis-transcription (any + // avg3-style or E-shifted variant) would not yield 30 here. + // B[3][0] = avg2(45,35) = 40; B[3][1] = avg3(45,35,25) = 35; + // B[2][1]=B[3][3] = avg3(35,25,15) = 25; B[2][2]=B[1][0] = + // avg2(25,15) = 20; B[2][3]=B[1][1] = avg3(25,15,5) = 15; + // B[1][2]=B[0][0] = avg2(15,5) = 10; B[1][3]=B[0][1] = + // avg3(15,5,10) = 9; B[0][2] = avg3(5,10,20) = 11; + // B[0][3] = avg3(10,20,30) = 20. + assert_pred4( + 8, + [ + 10, 9, 11, 20, // + 20, 15, 10, 9, // + 30, 25, 20, 15, // + 40, 35, 30, 25, // + ], + ); + // Directly pin the corrected-typo cells. + let mut out = [0u8; 16]; + predict4(8, &EDGE_A, &EDGE_L, EDGE_P, &mut out); + assert_eq!( + (out[8], out[14]), + (30, 30), + "B[2][0] and B[3][2] = avg2(E1,E2)" + ); + } + + #[test] + fn subblock_hu_up_diagonal() { + // B[0][0] = avg2(15,25) = 20; B[0][1] = avg3(15,25,35) = 25; + // B[0][2]=B[1][0] = avg2(25,35) = 30; B[0][3]=B[1][1] = + // avg3(25,35,45) = 35; B[1][2]=B[2][0] = avg2(35,45) = 40; + // B[1][3]=B[2][1] = avg3(35,45,45) = 43; bottom rows = L[3] = 45. + assert_pred4( + 9, + [ + 20, 25, 30, 35, // + 30, 35, 40, 43, // + 40, 43, 45, 45, // + 45, 45, 45, 45, // + ], + ); + } + + #[test] + fn dc16_all_availability_cases() { + // above = [10; 16] (sum 160), left = [20; 16] (sum 320). + let above = [10u8; 16]; + let left = [20u8; 16]; + let mut out = [0u8; 256]; + + // Both edges: (160 + 320 + 16) >> 5 = 15. + predict16(0, true, true, &above, &left, 5, &mut out); + assert_eq!(out, [15; 256]); + + // Neither edge (top-left macroblock): constant 128. The array + // contents are irrelevant here; availability flags decide. + predict16(0, false, false, &above, &left, 5, &mut out); + assert_eq!(out, [128; 256]); + + // Above only (left frame column): (160 + 8) >> 4 = 10. + predict16(0, true, false, &above, &left, 5, &mut out); + assert_eq!(out, [10; 256]); + + // Left only (top frame row): (320 + 8) >> 4 = 20. + predict16(0, false, true, &above, &left, 5, &mut out); + assert_eq!(out, [20; 256]); + } + + #[test] + fn dc8_all_availability_cases() { + // above = [10; 8] (sum 80), left = [20; 8] (sum 160). + let above = [10u8; 8]; + let left = [20u8; 8]; + let mut out = [0u8; 64]; + + // Both: (80 + 160 + 8) >> 4 = 15. + predict8(0, true, true, &above, &left, 5, &mut out); + assert_eq!(out, [15; 64]); + + // Neither: 128. + predict8(0, false, false, &above, &left, 5, &mut out); + assert_eq!(out, [128; 64]); + + // Above only: (80 + 4) >> 3 = 10. + predict8(0, true, false, &above, &left, 5, &mut out); + assert_eq!(out, [10; 64]); + + // Left only: (160 + 4) >> 3 = 20. + predict8(0, false, true, &above, &left, 5, &mut out); + assert_eq!(out, [20; 64]); + } + + #[test] + fn tm16_clamps_both_directions() { + let mut out = [0u8; 256]; + + // Negative difference clamps to 0: P high (250), L and A low (0) + // gives L + A - P = -250 everywhere. + predict16(3, true, true, &[0u8; 16], &[0u8; 16], 250, &mut out); + assert_eq!(out, [0; 256]); + + // Overflow clamps to 255: P = 0, L = A = 255 gives 510 everywhere. + predict16(3, true, true, &[255u8; 16], &[255u8; 16], 0, &mut out); + assert_eq!(out, [255; 256]); + + // Exact in-range gradient: out[r][c] = 200 + c - 50 = 150 + c, + // no clamping, verifies arithmetic (not just the clamps). + let above: [u8; 16] = core::array::from_fn(|i| i as u8); + predict16(3, true, true, &above, &[200u8; 16], 50, &mut out); + for r in 0..16 { + let row: [u8; 16] = core::array::from_fn(|c| (150 + c) as u8); + assert_eq!(out[r * 16..r * 16 + 16], row, "TM16 row {r}"); + } + } + + #[test] + fn tm4_clamps_via_predict4() { + // Same clamp contract at 4x4 (RFC B_TM_PRED == clamp255(L + A - P)). + let mut out = [0u8; 16]; + predict4(1, &[0u8; 8], &[0u8; 4], 250, &mut out); + assert_eq!(out, [0; 16]); + predict4(1, &[255u8; 8], &[255u8; 4], 0, &mut out); + assert_eq!(out, [255; 16]); + } + + #[test] + fn v_and_h_copy_edges() { + // V_PRED: every 16x16 row equals the above row. + let above: [u8; 16] = core::array::from_fn(|i| (i * 7 + 3) as u8); + let mut out = [0u8; 256]; + predict16(1, true, true, &above, &[0u8; 16], 0, &mut out); + for row in out.chunks_exact(16) { + assert_eq!(row, above); + } + + // H_PRED: every 8x8 row is the constant left[r]. + let left: [u8; 8] = core::array::from_fn(|i| (i * 11 + 1) as u8); + let mut out8 = [0u8; 64]; + predict8(2, true, true, &[0u8; 8], &left, 0, &mut out8); + for (r, row) in out8.chunks_exact(8).enumerate() { + assert_eq!(row, [left[r]; 8]); + } + } + + #[test] + #[should_panic(expected = "invalid intra mode")] + fn predict16_rejects_invalid_mode() { + let mut out = [0u8; 256]; + predict16(4, true, true, &[0u8; 16], &[0u8; 16], 0, &mut out); + } + + #[test] + #[should_panic(expected = "invalid intra 4x4 mode")] + fn predict4_rejects_invalid_mode() { + let mut out = [0u8; 16]; + predict4(10, &[0u8; 8], &[0u8; 4], 0, &mut out); + } +} diff --git a/crates/ec-vp8/src/lib.rs b/crates/ec-vp8/src/lib.rs index 2d0b2295..4ef5f415 100644 --- a/crates/ec-vp8/src/lib.rs +++ b/crates/ec-vp8/src/lib.rs @@ -15,9 +15,15 @@ #![warn(missing_docs)] pub mod bool; +pub mod decode; pub mod frame; pub mod header; +pub mod intra; +pub mod loopfilter; +pub mod modes; pub mod tables; +pub mod tokens; +pub mod transform; pub use ec_core::{Error, Result}; pub use header::PersistedState; diff --git a/crates/ec-vp8/src/loopfilter.rs b/crates/ec-vp8/src/loopfilter.rs new file mode 100644 index 00000000..2039fc19 --- /dev/null +++ b/crates/ec-vp8/src/loopfilter.rs @@ -0,0 +1,1064 @@ +//! VP8 in-loop deblocking filter — RFC 6386 Section 15. +//! +//! Implements the *normal* filter (§15.3), the *simple* filter (§15.2), the +//! per-frame macroblock-edge driver in the reference decoder's exact visit +//! order, and the per-sharpness limit-table construction of §15.4. +//! +//! The arithmetic is transcribed line-for-line from the normative reference +//! sources and is bit-identical between them (verified term-by-term): +//! +//! * `dixie_loopfilter.c` shipped with RFC 6386 (§20.6) — kernels +//! (`filter_common`, `filter_mb_edge`, thresholds) and the +//! `filter_row_normal` / `filter_row_simple` drivers, +//! * libvpx `vp8/common/loopfilter_filters.c` — the same kernels as +//! branch-free C, and `vp8/common/vp8_loopfilter.c` +//! (`vp8_loop_filter_update_sharpness`, `lf_init_lut`) — the limit and +//! high-edge-variance tables. +//! +//! C signed right-shifts are arithmetic (floor); Rust `i32 >>` has the same +//! semantics, so every `>>` below reproduces the C rounding exactly. No +//! allocation, no `unsafe`. +//! +//! Frame-type note: §15.4 (and libvpx `lf_init_lut`) makes `hev_threshold` +//! depend on whether the current frame is a key frame. [`filter_frame`] +//! keeps the crate-contract signature and applies the *inter-frame* table; +//! call [`filter_frame_ex`] with the decoded `is_keyframe` flag for fully +//! type-exact decoding (the two differ only for levels ≥ 15). + +/// Per-macroblock filter inputs the decoder derives from the frame header, +/// segmentation map and per-MB prediction info. +/// +/// `level` is the *final* per-MB loop filter level (0..=63) after the +/// segment and ref/mode delta adjustments of RFC 6386 §15.4 (implemented +/// decoder-side in `decode.rs`, mirroring dixie `calculate_filter_parameters`). +/// A level of 0 disables all filtering of that macroblock (dixie: +/// `if (edge_limit) { ... }`). +/// +/// `inner_edges` controls whether the subblock (interior) edges of the MB +/// are filtered: true iff the MB has any non-zero DCT coefficient or its +/// mode is `B_PRED`/`SPLITMV` (RFC §15.1; dixie's `eob_mask` condition, +/// `filter_row_normal` ~L9308 and `filter_row_simple` ~L9433). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MbFilterInfo { + /// Effective per-MB loop filter level after segment and ref/mode delta + /// adjustments, clamped to 0..=63. + pub level: u8, + /// Filter interior (subblock) edges of this MB (any non-zero DCT + /// coefficient, or `B_PRED`/`SPLITMV` mode). + pub inner_edges: bool, +} + +/// Per-sharpness limit tables for levels 0..=63, in the order +/// `lim` / `blim` / `mblim` of libvpx `loop_filter_info_n`. +/// +/// These are the combined edge limits of RFC §15.4: +/// `mblim[l] = (l + 2) * 2 + interior_limit(l)` (macroblock edges), +/// `blim[l] = l * 2 + interior_limit(l)` (subblock edges), and +/// `lim[l] = interior_limit(l)`. Both filter variants consume these exact +/// combined values (the simple filter directly, as dixie +/// `filter_v_edge_simple` does; the normal filter splits them back into +/// center + interior tests). +#[derive(Clone, Copy, Debug)] +pub struct LoopFilterTables { + /// Interior-difference limit per level (dixie `interior_limit`). + pub lim: [u8; 64], + /// Combined subblock-edge center limit per level (dixie `b_limit`). + pub blim: [u8; 64], + /// Combined macroblock-edge center limit per level (dixie `mb_limit`). + pub mblim: [u8; 64], +} + +impl LoopFilterTables { + /// Build the three limit tables for one frame's sharpness level. + /// + /// Port of libvpx `vp8_loop_filter_update_sharpness` + /// (vp8/common/vp8_loopfilter.c), which matches the RFC §15.4 + /// pseudocode: + /// + /// ```text + /// inside = level >> (sharpness > 0) >> (sharpness > 4) + /// if sharpness > 0 and inside > 9 - sharpness: inside = 9 - sharpness + /// inside = max(inside, 1) + /// ``` + pub fn update_sharpness(sharpness: u8) -> Self { + let s = i32::from(sharpness); + let mut t = LoopFilterTables { + lim: [0; 64], + blim: [0; 64], + mblim: [0; 64], + }; + for (lvl, slot) in t.lim.iter_mut().enumerate() { + let filt_lvl = lvl as i32; + // libvpx L59-60: two conditional single-bit shifts. + let mut inside = filt_lvl; + if s > 0 { + inside >>= 1; + } + if s > 4 { + inside >>= 1; + } + // libvpx L62-66: cap only applies when sharpness > 0. + if s > 0 && inside > 9 - s { + inside = 9 - s; + } + if inside < 1 { + inside = 1; + } + *slot = inside as u8; + t.blim[lvl] = (2 * filt_lvl + inside) as u8; + t.mblim[lvl] = (2 * (filt_lvl + 2) + inside) as u8; + } + t + } +} + +/// Interior-difference limit for one level/sharpness pair (RFC §15.4). +/// +/// Same derivation as [`LoopFilterTables::update_sharpness`] for a single +/// level; provided for callers that need the value without the tables. +pub fn interior_limit(level: u8, sharpness: u8) -> i32 { + let s = i32::from(sharpness); + let mut il = i32::from(level); + if s > 0 { + // dixie: interior_limit >>= sharpness > 4 ? 2 : 1 — the two + // conditional single-bit shifts of update_sharpness folded. + il >>= if s > 4 { 2 } else { 1 }; + if il > 9 - s { + il = 9 - s; + } + } + if il < 1 { + il = 1; + } + il +} + +/// High-edge-variance threshold for one level (RFC §15.4, last block; also +/// libvpx `lf_init_lut`'s `hev_thr_lut[KEY_FRAME|INTER_FRAME]`). +/// +/// Key frames: 2 at level ≥ 40, 1 at level ≥ 15, else 0. Inter frames: 3 at +/// level ≥ 40, 2 at level ≥ 20, 1 at level ≥ 15, else 0. +pub fn hev_threshold(level: u8, is_keyframe: bool) -> i32 { + let l = i32::from(level); + if is_keyframe { + if l >= 40 { + 2 + } else if l >= 15 { + 1 + } else { + 0 + } + } else if l >= 40 { + 3 + } else if l >= 20 { + 2 + } else if l >= 15 { + 1 + } else { + 0 + } +} + +/// Filter one frame's worth of macroblock edges, in the reference decoder's +/// exact order (dixie `filter_row_normal` / `filter_row_simple`, applied +/// row-major over MBs; each MB visits, when enabled: left MB V-edge, then +/// subblock V-edges at +4/+8/+12, then top MB H-edge, then subblock +/// H-edges at +4/+8/+12 rows). +/// +/// `y`/`u`/`v` are unbordered plane buffers starting at pixel (0,0), +/// `stride`/`uv_stride` samples apart, sized `mb_cols*16 × mb_rows*16` +/// (and halved for chroma). Frame-boundary edges (column 0, row 0) are not +/// filtered. `mb_info` is indexed `row * mb_cols + col`; a level of 0 +/// disables all filtering of that MB. The simple variant filters only the +/// Y plane (dixie `filter_row_simple`). +/// +/// This applies the inter-frame `hev_threshold` table (see the module docs); +/// use [`filter_frame_ex`] for frame-type-exact decoding. +#[allow(clippy::too_many_arguments)] +pub fn filter_frame( + y: &mut [u8], + u: &mut [u8], + v: &mut [u8], + stride: usize, + uv_stride: usize, + mb_cols: usize, + mb_rows: usize, + sharpness: u8, + simple_filter_type: bool, + mb_info: &[MbFilterInfo], +) { + filter_frame_ex( + y, + u, + v, + stride, + uv_stride, + mb_cols, + mb_rows, + sharpness, + simple_filter_type, + mb_info, + false, + ); +} + +/// [`filter_frame`] with an explicit frame type: `is_keyframe` selects the +/// §15.4 key-frame `hev_threshold` table instead of the inter-frame table +/// (dixie `calculate_filter_parameters`: +/// `if (filter_level >= 20 && !is_keyframe) hev_threshold++`). +#[allow(clippy::too_many_arguments)] +pub fn filter_frame_ex( + y: &mut [u8], + u: &mut [u8], + v: &mut [u8], + stride: usize, + uv_stride: usize, + mb_cols: usize, + mb_rows: usize, + sharpness: u8, + simple_filter_type: bool, + mb_info: &[MbFilterInfo], + is_keyframe: bool, +) { + debug_assert_eq!(mb_info.len(), mb_cols * mb_rows); + debug_assert!(y.len() >= stride * (mb_rows * 16 - 1) + mb_cols * 16); + debug_assert!(u.len() >= uv_stride * (mb_rows * 8 - 1) + mb_cols * 8); + debug_assert!(v.len() >= uv_stride * (mb_rows * 8 - 1) + mb_cols * 8); + debug_assert!(stride >= mb_cols * 16); + debug_assert!(uv_stride >= mb_cols * 8); + + let tables = LoopFilterTables::update_sharpness(sharpness); + + for row in 0..mb_rows { + for col in 0..mb_cols { + let info = &mb_info[row * mb_cols + col]; + let level = info.level as usize; + // dixie filter_row_normal L9280 / filter_row_simple L9425: + // `if (edge_limit)` — level 0 filters nothing for this MB. + if level == 0 { + continue; + } + let hev = hev_threshold(info.level, is_keyframe); + let mblim = i32::from(tables.mblim[level]); + let blim = i32::from(tables.blim[level]); + let lim = i32::from(tables.lim[level]); + let ybase = row * 16 * stride + col * 16; + let uvbase = row * 8 * uv_stride + col * 8; + + if simple_filter_type { + // dixie filter_row_simple L9436-9460. Y plane only. + if col > 0 { + filter_v_edge_simple(y, stride, ybase, mblim); + } + if info.inner_edges { + filter_v_edge_simple(y, stride, ybase + 4, blim); + filter_v_edge_simple(y, stride, ybase + 8, blim); + filter_v_edge_simple(y, stride, ybase + 12, blim); + } + if row > 0 { + filter_h_edge_simple(y, stride, ybase, mblim); + } + if info.inner_edges { + filter_h_edge_simple(y, stride, ybase + 4 * stride, blim); + filter_h_edge_simple(y, stride, ybase + 8 * stride, blim); + filter_h_edge_simple(y, stride, ybase + 12 * stride, blim); + } + continue; + } + + // dixie filter_row_normal L9282-9378. + if col > 0 { + filter_mb_v_edge(y, stride, ybase, mblim, lim, hev, 2); + filter_mb_v_edge(u, uv_stride, uvbase, mblim, lim, hev, 1); + filter_mb_v_edge(v, uv_stride, uvbase, mblim, lim, hev, 1); + } + if info.inner_edges { + filter_subblock_v_edge(y, stride, ybase + 4, blim, lim, hev, 2); + filter_subblock_v_edge(y, stride, ybase + 8, blim, lim, hev, 2); + filter_subblock_v_edge(y, stride, ybase + 12, blim, lim, hev, 2); + filter_subblock_v_edge(u, uv_stride, uvbase + 4, blim, lim, hev, 1); + filter_subblock_v_edge(v, uv_stride, uvbase + 4, blim, lim, hev, 1); + } + if row > 0 { + filter_mb_h_edge(y, stride, ybase, mblim, lim, hev, 2); + filter_mb_h_edge(u, uv_stride, uvbase, mblim, lim, hev, 1); + filter_mb_h_edge(v, uv_stride, uvbase, mblim, lim, hev, 1); + } + if info.inner_edges { + filter_subblock_h_edge(y, stride, ybase + 4 * stride, blim, lim, hev, 2); + filter_subblock_h_edge(y, stride, ybase + 8 * stride, blim, lim, hev, 2); + filter_subblock_h_edge(y, stride, ybase + 12 * stride, blim, lim, hev, 2); + filter_subblock_h_edge(u, uv_stride, uvbase + 4 * uv_stride, blim, lim, hev, 1); + filter_subblock_h_edge(v, uv_stride, uvbase + 4 * uv_stride, blim, lim, hev, 1); + } + } + } +} + +// --------------------------------------------------------------------------- +// Kernels — transcriptions of dixie_loopfilter.c (RFC 6386 §20.6). +// Pixels are handled as raw unsigned samples widened to `i32`; every clamp +// is the exact dixie saturate_int8 / saturate_uint8. +// --------------------------------------------------------------------------- + +/// dixie `saturate_int8`. +#[inline] +fn sat_i8(x: i32) -> i32 { + x.clamp(-128, 127) +} + +/// dixie `saturate_uint8` (result kept as `i32` in 0..=255). +#[inline] +fn sat_u8(x: i32) -> i32 { + x.clamp(0, 255) +} + +/// dixie `simple_threshold` (RFC §15.2/§15.3): the center test +/// `|p0-q0|*2 + |p1-q1|/2 <= limit` with `limit` already the *combined* +/// edge limit (`2*E + I`, or the tables' `blim`/`mblim`). +#[inline] +fn simple_threshold(p1: i32, p0: i32, q0: i32, q1: i32, limit: i32) -> bool { + (p0 - q0).abs() * 2 + ((p1 - q1).abs() >> 1) <= limit +} + +/// dixie `normal_threshold` (RFC §15.3 `filter_yes`): the combined center +/// test plus all six interior-difference tests against `interior`. +/// `px` is `[p3, p2, p1, p0, q0, q1, q2, q3]` across the edge. +#[inline] +fn normal_threshold(px: &[i32; 8], center_limit: i32, interior: i32) -> bool { + let [_, p2, p1, p0, q0, q1, q2, _] = *px; + simple_threshold(p1, p0, q0, q1, center_limit) + && (px[0] - p2).abs() <= interior + && (p2 - p1).abs() <= interior + && (p1 - p0).abs() <= interior + && (px[7] - q2).abs() <= interior + && (q2 - q1).abs() <= interior + && (q1 - q0).abs() <= interior +} + +/// dixie `high_edge_variance` (RFC §15.3 `hev`). +#[inline] +fn high_edge_variance(p1: i32, p0: i32, q0: i32, q1: i32, hev_threshold: i32) -> bool { + (p1 - p0).abs() > hev_threshold || (q1 - q0).abs() > hev_threshold +} + +/// dixie `filter_common` (RFC §15.3 `common_adjust`). +/// +/// `use_outer_taps` is true for the simple filter and for high-variance +/// edges. Returns `[p1, p0, q0, q1]`; the returned `p1`/`q1` equal the +/// inputs unless `!use_outer_taps` (subblock filter adjusts the inner +/// taps by half the edge adjustment). +fn filter_common(p1: i32, p0: i32, q0: i32, q1: i32, use_outer_taps: bool) -> [i32; 4] { + let mut a = 3 * (q0 - p0); + if use_outer_taps { + a += sat_i8(p1 - q1); + } + a = sat_i8(a); + // dixie clamps only the top here; a ≥ -128 makes a bottom clamp dead + // code, and the arithmetic `>> 3` reproduces the C rounding exactly. + let f1 = (if a + 4 > 127 { 127 } else { a + 4 }) >> 3; + let f2 = (if a + 3 > 127 { 127 } else { a + 3 }) >> 3; + let p0 = sat_u8(p0 + f2); + let q0 = sat_u8(q0 - f1); + let (p1, q1) = if !use_outer_taps { + let a = (f1 + 1) >> 1; + (sat_u8(p1 + a), sat_u8(q1 - a)) + } else { + (p1, q1) + }; + [p1, p0, q0, q1] +} + +/// dixie `filter_mb_edge` (RFC §15.3 `MBfilter`, non-hev branch): `w` is +/// "twice the edge difference" and the 27/18/9 coefficients approximate +/// 3/7, 2/7, 1/7 of it. Returns `[p2, p1, p0, q0, q1, q2]`. +fn filter_mb_edge(p2: i32, p1: i32, p0: i32, q0: i32, q1: i32, q2: i32) -> [i32; 6] { + let w = sat_i8(sat_i8(p1 - q1) + 3 * (q0 - p0)); + let a = (27 * w + 63) >> 7; + let (p0, q0) = (sat_u8(p0 + a), sat_u8(q0 - a)); + let a = (18 * w + 63) >> 7; + let (p1, q1) = (sat_u8(p1 + a), sat_u8(q1 - a)); + let a = (9 * w + 63) >> 7; + let (p2, q2) = (sat_u8(p2 + a), sat_u8(q2 - a)); + [p2, p1, p0, q0, q1, q2] +} + +// --------------------------------------------------------------------------- +// Edge walkers. `anchor` is the flat index of the edge's q0 sample in the +// first row (V edges) / column (H edges); `size` is the number of 8-pixel +// segments (2 = 16-pixel Y MB edge, 1 = 8-pixel chroma / subblock edge). +// Frame-boundary guarantees (anchor ≥ 4 samples from the plane edge) are +// established by `filter_frame_ex`'s `col > 0` / `row > 0` guards. +// --------------------------------------------------------------------------- + +/// dixie `filter_mb_v_edge`: vertical MB edge, normal filter. +fn filter_mb_v_edge( + plane: &mut [u8], + stride: usize, + anchor: usize, + center_limit: i32, + interior: i32, + hev: i32, + size: usize, +) { + for row in 0..8 * size { + let a = anchor + row * stride; + debug_assert!(a >= 4 && a + 3 < plane.len()); + let px = [ + i32::from(plane[a - 4]), + i32::from(plane[a - 3]), + i32::from(plane[a - 2]), + i32::from(plane[a - 1]), + i32::from(plane[a]), + i32::from(plane[a + 1]), + i32::from(plane[a + 2]), + i32::from(plane[a + 3]), + ]; + if !normal_threshold(&px, center_limit, interior) { + continue; + } + let [_, p2, p1, p0, q0, q1, q2, _] = px; + if high_edge_variance(p1, p0, q0, q1, hev) { + // dixie: filter_common with outer taps (p1/q1 unchanged). + let f = filter_common(p1, p0, q0, q1, true); + plane[a - 2] = f[0] as u8; + plane[a - 1] = f[1] as u8; + plane[a] = f[2] as u8; + plane[a + 1] = f[3] as u8; + } else { + let m = filter_mb_edge(p2, p1, p0, q0, q1, q2); + plane[a - 3] = m[0] as u8; + plane[a - 2] = m[1] as u8; + plane[a - 1] = m[2] as u8; + plane[a] = m[3] as u8; + plane[a + 1] = m[4] as u8; + plane[a + 2] = m[5] as u8; + } + } +} + +/// dixie `filter_subblock_v_edge`: vertical subblock edge, normal filter. +fn filter_subblock_v_edge( + plane: &mut [u8], + stride: usize, + anchor: usize, + center_limit: i32, + interior: i32, + hev: i32, + size: usize, +) { + for row in 0..8 * size { + let a = anchor + row * stride; + debug_assert!(a >= 4 && a + 3 < plane.len()); + let px = [ + i32::from(plane[a - 4]), + i32::from(plane[a - 3]), + i32::from(plane[a - 2]), + i32::from(plane[a - 1]), + i32::from(plane[a]), + i32::from(plane[a + 1]), + i32::from(plane[a + 2]), + i32::from(plane[a + 3]), + ]; + if normal_threshold(&px, center_limit, interior) { + let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev); + let f = filter_common(px[2], px[3], px[4], px[5], outer); + plane[a - 2] = f[0] as u8; + plane[a - 1] = f[1] as u8; + plane[a] = f[2] as u8; + plane[a + 1] = f[3] as u8; + } + } +} + +/// dixie `filter_mb_h_edge`: horizontal MB edge, normal filter. +fn filter_mb_h_edge( + plane: &mut [u8], + stride: usize, + anchor: usize, + center_limit: i32, + interior: i32, + hev: i32, + size: usize, +) { + for i in 0..8 * size { + let a = anchor + i; + debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len()); + let px = [ + i32::from(plane[a - 4 * stride]), + i32::from(plane[a - 3 * stride]), + i32::from(plane[a - 2 * stride]), + i32::from(plane[a - stride]), + i32::from(plane[a]), + i32::from(plane[a + stride]), + i32::from(plane[a + 2 * stride]), + i32::from(plane[a + 3 * stride]), + ]; + if !normal_threshold(&px, center_limit, interior) { + continue; + } + let [_, p2, p1, p0, q0, q1, q2, _] = px; + if high_edge_variance(p1, p0, q0, q1, hev) { + let f = filter_common(p1, p0, q0, q1, true); + plane[a - 2 * stride] = f[0] as u8; + plane[a - stride] = f[1] as u8; + plane[a] = f[2] as u8; + plane[a + stride] = f[3] as u8; + } else { + let m = filter_mb_edge(p2, p1, p0, q0, q1, q2); + plane[a - 3 * stride] = m[0] as u8; + plane[a - 2 * stride] = m[1] as u8; + plane[a - stride] = m[2] as u8; + plane[a] = m[3] as u8; + plane[a + stride] = m[4] as u8; + plane[a + 2 * stride] = m[5] as u8; + } + } +} + +/// dixie `filter_subblock_h_edge`: horizontal subblock edge, normal filter. +fn filter_subblock_h_edge( + plane: &mut [u8], + stride: usize, + anchor: usize, + center_limit: i32, + interior: i32, + hev: i32, + size: usize, +) { + for i in 0..8 * size { + let a = anchor + i; + debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len()); + let px = [ + i32::from(plane[a - 4 * stride]), + i32::from(plane[a - 3 * stride]), + i32::from(plane[a - 2 * stride]), + i32::from(plane[a - stride]), + i32::from(plane[a]), + i32::from(plane[a + stride]), + i32::from(plane[a + 2 * stride]), + i32::from(plane[a + 3 * stride]), + ]; + if normal_threshold(&px, center_limit, interior) { + let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev); + let f = filter_common(px[2], px[3], px[4], px[5], outer); + plane[a - 2 * stride] = f[0] as u8; + plane[a - stride] = f[1] as u8; + plane[a] = f[2] as u8; + plane[a + stride] = f[3] as u8; + } + } +} + +/// dixie `filter_v_edge_simple`: vertical edge, simple filter (2-tap; +/// consumes the combined limit directly, touches only p0/q0). +fn filter_v_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i32) { + for row in 0..16 { + let a = anchor + row * stride; + debug_assert!(a >= 2 && a + 1 < plane.len()); + let p1 = i32::from(plane[a - 2]); + let p0 = i32::from(plane[a - 1]); + let q0 = i32::from(plane[a]); + let q1 = i32::from(plane[a + 1]); + if simple_threshold(p1, p0, q0, q1, limit) { + let f = filter_common(p1, p0, q0, q1, true); + plane[a - 1] = f[1] as u8; + plane[a] = f[2] as u8; + } + } +} + +/// dixie `filter_h_edge_simple`: horizontal edge, simple filter. +fn filter_h_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i32) { + for i in 0..16 { + let a = anchor + i; + debug_assert!(a >= 2 * stride && a + stride < plane.len()); + let p1 = i32::from(plane[a - 2 * stride]); + let p0 = i32::from(plane[a - stride]); + let q0 = i32::from(plane[a]); + let q1 = i32::from(plane[a + stride]); + if simple_threshold(p1, p0, q0, q1, limit) { + let f = filter_common(p1, p0, q0, q1, true); + plane[a - stride] = f[1] as u8; + plane[a] = f[2] as u8; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // ----------------------------------------------------------------------- + // Python reference model — the SAME integer math used to derive every + // expected vector below (transcribed from dixie_loopfilter.c, RFC 6386 + // §20.6; control params from §15.4 / libvpx vp8_loopfilter.c). Run to + // regenerate the constants in these tests. + // + // def sat_i8(x): return -128 if x < -128 else (127 if x > 127 else x) + // def sat_u8(x): return 0 if x < 0 else (255 if x > 255 else x) + // + // def simple_threshold(p1, p0, q0, q1, limit): + // return (abs(p0 - q0) * 2 + (abs(p1 - q1) >> 1)) <= limit + // + // def normal_threshold(p3, p2, p1, p0, q0, q1, q2, q3, E, I): + // return simple_threshold(p1, p0, q0, q1, 2 * E + I) and \ + // abs(p3 - p2) <= I and abs(p2 - p1) <= I and abs(p1 - p0) <= I and \ + // abs(q3 - q2) <= I and abs(q2 - q1) <= I and abs(q1 - q0) <= I + // + // def high_edge_variance(p1, p0, q0, q1, t): + // return abs(p1 - p0) > t or abs(q1 - q0) > t + // + // def filter_common(p1, p0, q0, q1, outer): + // a = 3 * (q0 - p0) + // if outer: a += sat_i8(p1 - q1) + // a = sat_i8(a) + // f1 = (127 if a + 4 > 127 else a + 4) >> 3 + // f2 = (127 if a + 3 > 127 else a + 3) >> 3 + // p0 = sat_u8(p0 + f2); q0 = sat_u8(q0 - f1) + // if not outer: + // a = (f1 + 1) >> 1 + // p1 = sat_u8(p1 + a); q1 = sat_u8(q1 - a) + // return p1, p0, q0, q1 + // + // def filter_mb_edge(p2, p1, p0, q0, q1, q2): + // w = sat_i8(sat_i8(p1 - q1) + 3 * (q0 - p0)) + // a = (27 * w + 63) >> 7; p0 = sat_u8(p0 + a); q0 = sat_u8(q0 - a) + // a = (18 * w + 63) >> 7; p1 = sat_u8(p1 + a); q1 = sat_u8(q1 - a) + // a = (9 * w + 63) >> 7; p2 = sat_u8(p2 + a); q2 = sat_u8(q2 - a) + // return p2, p1, p0, q0, q1, q2 + // + // def interior_limit(level, sharpness): + // il = level + // if sharpness: + // il >>= (2 if sharpness > 4 else 1) + // if il > 9 - sharpness: il = 9 - sharpness + // return il if il >= 1 else 1 + // + // def hev_threshold(level, key): + // if key: return 2 if level >= 40 else (1 if level >= 15 else 0) + // return 3 if level >= 40 else (2 if level >= 20 else (1 if level >= 15 else 0)) + // + // # update_sharpness: inside = lvl >> (s>0) >> (s>4), capped at 9-s + // # (only when s>0), min 1; lim=inside, blim=2*lvl+inside, + // # mblim=2*(lvl+2)+inside. + // # + // # Edge walkers mirror the Rust walkers: per row (V) / column (H), + // # threshold -> hev ? filter_common(outer=True) : filter_mb_edge for + // # MB edges, threshold -> filter_common(hev) for subblock edges, + // # threshold -> filter_common(True) touching p0/q0 only for simple. + // # Driver: row-major MBs, per MB [V-mb, V+4, V+8, V+12, H-mb, + // # H+4r, H+8r, H+12r] guarded by col>0 / inner / row>0 / inner + // # (dixie filter_row_normal / filter_row_simple). + // ----------------------------------------------------------------------- + + /// Decode a (possibly newline-wrapped) hex string into bytes. + fn unhex(s: &str) -> Vec { + let hexed: String = s.chars().filter(char::is_ascii_hexdigit).collect(); + (0..hexed.len() / 2) + .map(|i| u8::from_str_radix(&hexed[2 * i..2 * i + 2], 16).unwrap()) + .collect() + } + + /// The shared 2x2-MB driver scene: `y = (x*7) ^ (y*13 + 37)`, + /// `u = x*3 + y*5 + 11`, `v = x*5 + y*3 + 77` (all mod 256). + fn scene() -> (Vec, Vec, Vec) { + let (stride, uv_stride) = (32usize, 16usize); + let mut y = vec![0u8; stride * 32]; + let mut u = vec![0u8; uv_stride * 16]; + let mut v = vec![0u8; uv_stride * 16]; + for ty in 0..32usize { + for tx in 0..32usize { + y[ty * stride + tx] = (((tx * 7) ^ (ty * 13 + 37)) & 0xFF) as u8; + } + } + for ty in 0..16usize { + for tx in 0..16usize { + u[ty * uv_stride + tx] = ((tx * 3 + ty * 5 + 11) & 0xFF) as u8; + v[ty * uv_stride + tx] = ((tx * 5 + ty * 3 + 77) & 0xFF) as u8; + } + } + (y, u, v) + } + + const NORMAL_Y: &str = "\ +25222b3039060f141d1a6368717e474c55525ba0a9b6bf848d8a9398e1eef7fc32353c272e1118030a0d747f6669505b42454cb7bea1a8939a9d848ff6f9e0eb +3f38312a231c150e070079726b645d564f4841bab3aca59e97908982fbf4ede64c4b4259506f667d74730a0118172e253c3b32c9c0dfd6ede4e3faf188879e95 +595e574c457a736861661f140d023b30292e27dcd5cac3f8f1f6efe49d928b80666168737a454c575e59202b323d040f161118e3eaf5fcc7cec9d0dba2adb4bf +73747d666f5059424b4c353e2728111a03040df6ffe0e9d2dbdcc5ceb7b8a1aa80878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b5259 +8d8a839891aea7bcb5b2cbc0d9d6efe4fdfaf308011e172c25223b3049465f549a9d948f86b9b0aba2a5dcd7cec1f8f3eaede41f1609003b32352c275e514843 +a7a0a9b2bb848d969f98e1eaf3fcc5ced7d0d9222b343d060f08111a636c757eb4b3baa1a8979e858c8bf2f9e0efd6ddc4c3ca3138272e151c1b0209707f666d +c1c6cfd4dde2ebf0f9fe878c959aa3a8b1b6bf444d525b60696e777c050a1318cec9c0dbd2ede4fff6f188839a95aca7beb9b04b425d546f666178730a051c17 +dbdcd5cec7f8f1eae3e49d968f80b9b2abaca55e5748417a73746d661f100902e8efe6fdf4cbc2d9d0d7aea5bcb38a81989f966d647b724940475e552c233a31 +f5f2fbe0e9d6dfc4cdcab3b8a1ae979c85828b7079666f545d5a4348313e272c02050c171e2128333a3d444f5659606b72757c878e9198a3aaadb4bfc6c9d0db +0f08011a132c253e373049425b546d667f78718a839c95aea7a0b9b2cbc4ddd61c1b1209003f362d24235a5148477e756c6b6299908f86bdb4b3aaa1d8d7cec5 +292e273c350a031811166f647d724b40595e57aca5bab38881869f94ede2fbf0363138232a151c070e09707b626d545f464148b3baa5ac979e99808bf2fde4ef +43444d565f6069727b7c050e1718212a33343dc6cfd0d9e2ebecf5fe8788919a50575e454c737a61686f161d040b323920272ed5dcc3caf1f8ffe6ed949b8289 +5d5a5348417e776c65621b1009063f342d2a23d8d1cec7fcf5f2ebe099968f846a6d647f7649405b52552c273e3108031a1d14efe6f9f0cbc2c5dcd7aea1b8b3 +777079626b545d464f48313a232c151e070009f2fbe4edd6dfd8c1cab3bca5ae84838a9198a7aeb5bcbbc2c9d0dfe6edf4f3fa0108171e252c2b3239404f565d +91969f848db2bba0a9aed7dcc5caf3f8e1e6ef141d020b30393e272c555a43489e99908b82bdb4afa6a1d8d3cac5fcf7eee9e01b120d043f363128235a554c47 +abaca5beb788819a9394ede6fff0c9c2dbdcd52e2738310a03041d166f607972b8bfb6ada49b92898087fef5ece3dad1c8cfc63d342b221910170e057c736a61"; + + const NORMAL_U: &str = "\ +0b0e1114171a1d202326292c2f323538101316191c1f2225282b2e3134373a3d15181b1e2124272a2d303336393c3f421a1d202326292c2f3235383b3e414447 +1f2225282b2e3134373a3d404346494c24272a2d303336393c3f4245484b4e51292c2f3235383b3e4144474a4d5053562e3134373a3d404346494c4f5255585b +3336393c3f4245484b4e5154575a5d60383b3e4144474a4d505356595c5f62653d404346494c4f5255585b5e6164676a4245484b4e5154575a5d606366696c6f +474a4d505356595c5f6265686b6e71744c4f5255585b5e6164676a6d707376795154575a5d606366696c6f7275787b7e56595c5f6265686b6e7174777a7d8083"; + + const NORMAL_V: &str = "\ +4d52575c61666b70757a7f84898e939850555a5f64696e73787d82878c91969b53585d62676c71767b80858a8f94999e565b60656a6f74797e83888d92979ca1 +595e63686d72777c81868b90959a9fa45c61666b70757a7f84898e93989da2a75f64696e73787d82878c91969ba0a5aa62676c71767b80858a8f94999ea3a8ad +656a6f74797e83888d92979ca1a6abb0686d72777c81868b90959a9fa4a9aeb36b70757a7f84898e93989da2a7acb1b66e73787d82878c91969ba0a5aaafb4b9 +71767b80858a8f94999ea3a8adb2b7bc74797e83888d92979ca1a6abb0b5babf777c81868b90959a9fa4a9aeb3b8bdc27a7f84898e93989da2a7acb1b6bbc0c5"; + + const SIMPLE_Y: &str = "\ +25222b3831060f161b1a6368717e474e53525ba0a9b6bf8e838a9398e1eef7fc32353c2f26111807060d74776e6950534a454cafc6a1a897969d848ff6f9e0eb +3f38312a231c150e070079726b645d564f4841bab3aca59e97908982fbf4ede64c4d4250596e647879730a0816172e343a3d33cbc0dfd6e4eae3edf188949e95 +595c57454c7b756762661f1507023b27252c26dad5cac3f3f9f6fce49d858b806661687a73454c585d59202a333d0410151118e3eaf5fcd0c5c9d0dba2adb4bf +73747d6f66505947464c35372e2811130a040df6ffe0e9d7d6dcc5c7beb8a1aa8083879096a39eb1adbfc6cdd4dbe2e9f0f7fe050c131a21282f363d4f4b5259 +8d8e8a959faeb3b8c4b2cbc8d1d6efecf5faf308011e172829223b3836465f549a9d94878eb9b0a9a4a5dcd7cec1f8f1ecede41f160900313c352c275e514843 +a7a0a9bab3848d989d98e1eaf3fcc5d0d5d0d9222b343d100508111a636c757eb4b5bfa8a1979e8a878bf2f0e9efd6d6cbc1cb333d272e1a171b0209707f666d +c1c4cad5dce2ebf1f8fe878d949aa3a9b0b8be4248525b61686e777c050a1318cec9c0d2dbede4fafbf1888a9395acaeb7b9b04b425d546a6b6178730a051c17 +dbdcd5c7cef8f1e9e4e49d978e80b9b1acaca55e574841717c746d661f100902e8efe6fdf4cbc2d3d6d7bbb7b7b68a87979f976c627b664a3e475e552c233a31 +f5f2fbe8e1d6dfcac7caa6a6a6ab979686828a7973667b5b575a4340393e272c02050c171e2128333a3d444f5659606b72757c878e9198a3aaadb4bfc6c9d0db +0f0801121b2c253a3b30494a53546d6e777871828b9c95aaaba0b9bac3c4ddd61c1d1200093f362c26235a5049477e746d6d6390988f86b4bdb3ada2d8d4cec5 +292c273d340a031315166f6d74724b47525c56aca6bab38b7e869c93ede5fbf03631382a23151c0c090970726b6d54584d4148b3baa5ac9c9999808bf2fde4ef +43444d575e6069737a7c050f1618212b32343dc6cfd0d9e3eaecf5fe8788919a5053573e487a7e6b696f130f07063a3c292b2fd1d5c2c6f2ffffebed91968284 +5d5e5a474d77736660621e160e0b3731242622dcd8cfcbeff7f2e6e09c9b8f896a6d647f7649405558552c2f36310809141d14efe6f9f0cdc0c5dcd7aea1b8b3 +7770796a63545d4c494831322b2c15180d0009f2fbe4eddcd9d8c1c2bbbca5ae84858f898fa7aeb6bbbbc2c8d1dfe6eef3f3fa0108171e262b2b3238414f565d +91949a8c96b2bba5a4aed7d5cccaf3f1e8e6ef141d020b2d3c3e272c555a43489e9990828bbdb4aea7a1d8d2cbc5fcf6efe9e01b120d04363f3128235a554c47 +abaca5bfb68881959894edeff6f0c9c9d4dcd52e2738310d00041d166f607972b8bfb6ada49b92878287fef5ece3dacfcacfc63d342b221712170e057c736a61"; + + /// Table sanity: lengths plus entries hand-derived from libvpx + /// `vp8_loop_filter_update_sharpness` (vp8/common/vp8_loopfilter.c + /// L49-75): inside = lvl >> (s>0) >> (s>4), capped at 9-s when s>0, + /// min 1; lim=inside, blim=2*lvl+inside, mblim=2*(lvl+2)+inside. + #[test] + fn sharpness_tables_match_libvpx() { + let t0 = LoopFilterTables::update_sharpness(0); + assert_eq!(t0.lim.len(), 64); + assert_eq!(t0.blim.len(), 64); + assert_eq!(t0.mblim.len(), 64); + // sharpness 0: lvl 0 -> (1, 1, 5), lvl 1 -> (1, 3, 7), + // lvl 15 -> (15, 45, 49), lvl 63 -> (63, 189, 193). + assert_eq!((t0.lim[0], t0.blim[0], t0.mblim[0]), (1, 1, 5)); + assert_eq!((t0.lim[1], t0.blim[1], t0.mblim[1]), (1, 3, 7)); + assert_eq!((t0.lim[15], t0.blim[15], t0.mblim[15]), (15, 45, 49)); + assert_eq!((t0.lim[63], t0.blim[63], t0.mblim[63]), (63, 189, 193)); + // sharpness 5: inside = lvl >> 2 capped at 4: + // lvl 3 -> (1, 7, 11), lvl 20 -> (4, 44, 48), lvl 63 -> (4, 130, 134). + let t5 = LoopFilterTables::update_sharpness(5); + assert_eq!((t5.lim[3], t5.blim[3], t5.mblim[3]), (1, 7, 11)); + assert_eq!((t5.lim[20], t5.blim[20], t5.mblim[20]), (4, 44, 48)); + assert_eq!((t5.lim[63], t5.blim[63], t5.mblim[63]), (4, 130, 134)); + // sharpness 7: inside capped at 2: + // lvl 4 -> (1, 9, 13), lvl 20 -> (2, 42, 46). + let t7 = LoopFilterTables::update_sharpness(7); + assert_eq!((t7.lim[4], t7.blim[4], t7.mblim[4]), (1, 9, 13)); + assert_eq!((t7.lim[20], t7.blim[20], t7.mblim[20]), (2, 42, 46)); + // The standalone helper must agree with the table for every level. + for sharpness in 0..=7u8 { + let t = LoopFilterTables::update_sharpness(sharpness); + for level in 0..=63u8 { + assert_eq!( + interior_limit(level, sharpness), + i32::from(t.lim[level as usize]) + ); + } + } + } + + /// §15.4 hev table (libvpx `lf_init_lut`): key 0/1/1/2 and inter + /// 0/1/2/3 at levels 0/15/20/40 respectively. + #[test] + fn hev_threshold_table() { + for level in [0u8, 14, 15, 19, 20, 39, 40, 63] { + let l = i32::from(level); + let want_key = if l >= 40 { + 2 + } else if l >= 15 { + 1 + } else { + 0 + }; + let want_inter = if l >= 40 { + 3 + } else if l >= 20 { + 2 + } else if l >= 15 { + 1 + } else { + 0 + }; + assert_eq!(hev_threshold(level, true), want_key); + assert_eq!(hev_threshold(level, false), want_inter); + } + assert_eq!(hev_threshold(39, true), 1); + assert_eq!(hev_threshold(39, false), 2); + } + + /// Level 0 disables all filtering: a noisy frame is byte-identical. + #[test] + fn level_zero_disables_filtering() { + let (y0, u0, v0) = scene(); + let mut y = y0.clone(); + let mut u = u0.clone(); + let mut v = v0.clone(); + filter_frame( + &mut y, + &mut u, + &mut v, + 32, + 16, + 2, + 2, + 1, + false, + &[MbFilterInfo { + level: 0, + inner_edges: true, + }; 4], + ); + assert_eq!(y, y0); + assert_eq!(u, u0); + assert_eq!(v, v0); + } + + /// Kernel: normal filter, vertical MB edge, non-hev wide path. + /// Level 30, sharpness 0 -> interior 30, mblim = 2*32+30 = 94, hev = 2. + /// Patch: cols < 16 = 110, cols >= 16 = 130. Python model row: + /// w = sat_i8(-20 + 3*20) = 40; a27 = (1080+63)>>7 = 8, a18 = 6, + /// a9 = 3 -> [110, 113, 116, 118 | 122, 124, 127, 130] at cols 12..19. + #[test] + fn mb_v_edge_normal_filter_kernel() { + let mut y = vec![0u8; 32 * 16]; + for r in 0..16 { + for c in 0..32 { + y[r * 32 + c] = if c < 16 { 110 } else { 130 }; + } + } + let mut u = vec![128u8; 16 * 8]; + let mut v = vec![128u8; 16 * 8]; + filter_frame( + &mut y, + &mut u, + &mut v, + 32, + 16, + 2, + 1, + 0, + false, + &[MbFilterInfo { + level: 30, + inner_edges: false, + }; 2], + ); + for r in 0..16 { + assert_eq!( + &y[r * 32 + 12..r * 32 + 20], + &[110, 113, 116, 118, 122, 124, 127, 130], + "row {r}" + ); + } + // Flat chroma planes are untouched (all filter deltas are 0). + assert!(u.iter().all(|&b| b == 128)); + assert!(v.iter().all(|&b| b == 128)); + } + + /// Kernel: hev edge takes the simple ±f path (p1/q1 unchanged). + /// Level 15, sharpness 0 -> interior 15, mblim = 2*17+15 = 49, hev = 1. + /// |p1-p0| = 2 > 1 triggers hev; Python model: a = 3*16 - 10 = 38, + /// f1 = 42>>3 = 5, f2 = 41>>3 = 5. + #[test] + fn hev_edge_takes_short_path() { + let mut plane = vec![0u8; 8 * 8]; + for r in 0..8 { + plane[r * 8..r * 8 + 8].copy_from_slice(&[101, 101, 102, 100, 116, 112, 112, 113]); + } + // Anchor: q0 at (row 0, col 4); 8 rows, one segment. + filter_mb_v_edge( + &mut plane, + 8, + 4, + 2 * (15 + 2) + 15, + 15, + hev_threshold(15, false), + 1, + ); + assert_eq!(&plane[0..8], &[101, 101, 102, 105, 111, 112, 112, 113]); + // Outer-tap path leaves the inner taps alone. + assert_eq!(plane[8 + 2], 102); + assert_eq!(plane[8 + 5], 112); + } + + /// Kernel: non-hev subblock edge runs the full path incl. p1/q1. + /// Level 15, sharpness 0 -> interior 15, blim = 2*15+15 = 45. + /// Python model: a = 3*10 = 30, f1 = 34>>3 = 4, f2 = 33>>3 = 4, + /// inner a = (4+1)>>1 = 2. + #[test] + fn subblock_edge_takes_full_three_tap_path() { + let mut plane = vec![0u8; 8 * 8]; + for r in 0..8 { + plane[r * 8..r * 8 + 8].copy_from_slice(&[100, 100, 100, 100, 110, 111, 111, 111]); + } + filter_subblock_v_edge( + &mut plane, + 8, + 4, + 2 * 15 + 15, + 15, + hev_threshold(15, false), + 1, + ); + assert_eq!(&plane[0..8], &[100, 100, 102, 104, 106, 109, 111, 111]); + } + + /// Simple filter: MB edge gets f = 5 (mb_limit = 94), subblock edges + /// are filtered too (no-op on flat interiors), chroma is untouched. + #[test] + fn simple_filter_leaves_chroma_untouched() { + let mut y = vec![0u8; 32 * 16]; + for r in 0..16 { + for c in 0..32 { + y[r * 32 + c] = if c < 16 { 110 } else { 130 }; + } + } + let mut u = vec![0u8; 16 * 8]; + let mut v = vec![0u8; 16 * 8]; + for r in 0..8 { + for c in 0..16 { + u[r * 16 + c] = if c < 8 { 100 } else { 150 }; + v[r * 16 + c] = if c < 8 { 90 } else { 170 }; + } + } + let u_orig = u.clone(); + let v_orig = v.clone(); + filter_frame( + &mut y, + &mut u, + &mut v, + 32, + 16, + 2, + 1, + 0, + true, + &[MbFilterInfo { + level: 30, + inner_edges: true, + }; 2], + ); + // a = 3*20 - 20 = 40 -> f1 = 44>>3 = 5, f2 = 43>>3 = 5. + for r in 0..16 { + assert_eq!( + &y[r * 32 + 12..r * 32 + 20], + &[110, 110, 110, 115, 125, 130, 130, 130], + "row {r}" + ); + } + assert_eq!(u, u_orig); + assert_eq!(v, v_orig); + } + + /// Full-frame driver, normal filter: 2x2 MBs, level 25, sharpness 1, + /// inner edges on. The whole frame must equal the Python model output + /// byte-for-byte. Sample (17,17) is q1 of MB(1,1)'s V edge and then q1 + /// of its H edge — the match proves the dixie visit order + /// (V-MB, subblock-V, H-MB, subblock-H) is reproduced. + #[test] + fn driver_normal_filter_frame_order() { + let (y0, u0, v0) = scene(); + let mut y = y0; + let mut u = u0; + let mut v = v0; + filter_frame_ex( + &mut y, + &mut u, + &mut v, + 32, + 16, + 2, + 2, + 1, + false, + &[MbFilterInfo { + level: 25, + inner_edges: true, + }; 4], + false, + ); + assert_eq!(y, unhex(NORMAL_Y)); + assert_eq!(u, unhex(NORMAL_U)); + assert_eq!(v, unhex(NORMAL_V)); + assert_eq!(y[17 * 32 + 17], 0x75, "order-probe pixel (17,17)"); + } + + /// Full-frame driver, simple filter: same scene, Y-only output. + #[test] + fn driver_simple_filter_frame() { + let (_, u0, v0) = scene(); + let (mut y, _, _) = scene(); + let mut u = u0.clone(); + let mut v = v0.clone(); + filter_frame( + &mut y, + &mut u, + &mut v, + 32, + 16, + 2, + 2, + 1, + true, + &[MbFilterInfo { + level: 25, + inner_edges: true, + }; 4], + ); + assert_eq!(y, unhex(SIMPLE_Y)); + assert_eq!(u, u0); + assert_eq!(v, v0); + } + + /// Frame type matters at level 25 (hev 2 inter / 1 key): a near-tap + /// difference of exactly 2 takes the wide MBfilter path on inter + /// frames and the hev ±f path on key frames. Python model rows: + /// inter 6e6f71706f707071, key 6e6e706f70717171. + #[test] + fn frame_type_changes_hev_path() { + let build = || { + let mut y = vec![0u8; 32 * 16]; + for r in 0..16 { + for c in 0..32 { + y[r * 32 + c] = if c == 14 { + 112 + } else if c < 16 { + 110 + } else { + 113 + }; + } + } + y + }; + let mut uy = vec![128u8; 16 * 8]; + let mut vy = vec![128u8; 16 * 8]; + let mut ky = build(); + let mut uk = uy.clone(); + let mut vk = vy.clone(); + let info = [MbFilterInfo { + level: 25, + inner_edges: false, + }; 2]; + let mut inter = build(); + filter_frame_ex( + &mut inter, &mut uy, &mut vy, 32, 16, 2, 1, 1, false, &info, false, + ); + filter_frame_ex( + &mut ky, &mut uk, &mut vk, 32, 16, 2, 1, 1, false, &info, true, + ); + assert_eq!(&inter[12..20], &[110, 111, 113, 112, 111, 112, 112, 113]); + assert_eq!(&ky[12..20], &[110, 110, 112, 111, 112, 113, 113, 113]); + } +} diff --git a/crates/ec-vp8/src/modes.rs b/crates/ec-vp8/src/modes.rs new file mode 100644 index 00000000..a0a2a4b0 --- /dev/null +++ b/crates/ec-vp8/src/modes.rs @@ -0,0 +1,311 @@ +//! Macroblock prediction modes and their coding trees +//! (RFC 6386 §8.2, §11.2, §11.4, §16.1). + +use crate::bool::BoolDecoder; + +/// Intra macroblock luma modes (RFC 6386 §8.2 enum values are normative; +/// chroma modes are the first four). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum YMode { + /// Predict DC from the row above and column to the left. + DcPred = 0, + /// Predict rows from the row above. + VPred = 1, + /// Predict columns from the column to the left. + HPred = 2, + /// True-motion (second-difference) prediction. + TmPred = 3, + /// Each 4x4 Y subblock is independently predicted. + BPred = 4, +} + +impl YMode { + /// Value as coded in the trees (the RFC's enum integers). + pub fn as_u8(self) -> u8 { + self as u8 + } + + /// The subblock mode a 16x16 mode masquerades as for B_PRED context + /// purposes (RFC 6386 §11.3 item 4). + pub fn as_bmode(self) -> BMode { + match self { + YMode::DcPred => BMode::BDCPred, + YMode::VPred => BMode::BVEPred, + YMode::HPred => BMode::BHEPred, + YMode::TmPred => BMode::BTMPred, + YMode::BPred => unreachable!("B_PRED has no single subblock mode"), + } + } +} + +/// The ten 4x4 subblock prediction modes (RFC 6386 §11.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum BMode { + /// DC from above row and left column. + BDCPred = 0, + /// True-motion. + BTMPred = 1, + /// Vertical from smoothed above row. + BVEPred = 2, + /// Horizontal from smoothed left column. + BHEPred = 3, + /// Down-left diagonal. + BLDPred = 4, + /// Down-right diagonal. + BRDPred = 5, + /// Vertical-right diagonal. + BVRPred = 6, + /// Vertical-left diagonal. + BVLPred = 7, + /// Horizontal-down diagonal. + BHDPred = 8, + /// Horizontal-up diagonal. + BHUPred = 9, +} + +impl BMode { + /// Value as coded in the bmode tree (the RFC's enum integers). + pub fn as_u8(self) -> u8 { + self as u8 + } +} + +/// Key-frame Y-mode coding tree (RFC 6386 §11.2): B_PRED, then the four +/// full-block modes. Leaf values are the [`YMode`] enum integers. +pub const KF_YMODE_TREE: [i8; 8] = [-4, 2, 4, 6, 0, -1, -2, -3]; + +/// Key-frame Y-mode probabilities (fixed; RFC 6386 §11.2 and the +/// reference decoder's `kf_y_mode_probs`). +pub const KF_YMODE_PROBS: [u8; 4] = [145, 156, 163, 128]; + +/// Interframe Y-mode coding tree (RFC 6386 §8.2). +pub const YMODE_TREE: [i8; 8] = [0, 2, 4, 6, -1, -2, -3, -4]; + +/// Chroma-mode coding tree (RFC 6386 §8.2/§11.4): DC, V, H, TM. +pub const UV_MODE_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3]; + +/// Key-frame chroma-mode probabilities (fixed; RFC 6386 §11.4). +pub const KF_UV_MODE_PROBS: [u8; 3] = [142, 114, 183]; + +/// 4x4 subblock-mode coding tree (RFC 6386 §11.2). Leaf values are the +/// [`BMode`] enum integers; note the leaf 0 (B_DC_PRED) relies on the +/// tree reader's `i <= 0` leaf test. +pub const BMODE_TREE: [i8; 18] = [ + 0, 2, // B_DC_PRED = "0" + -1, 4, // B_TM = "10" + -2, 6, // B_VE = "110" + 8, 12, // inner + -3, 10, // B_HE = "11100" + -5, -6, // B_RD = "111010", B_VR = "111011" + -4, 14, // B_LD = "111110" + -7, 16, // B_VL = "1111110" + -8, -9, // B_HD = "11111110", B_HU = "11111111" +]; + +/// Subblock modes in interframes decode with this constant probability +/// array, no context (RFC 6386 §11.3 item 5 / §16). +pub const INTER_BMODE_PROBS: [u8; 9] = [120, 90, 79, 133, 87, 85, 80, 111, 151]; + +/// Decode a key-frame Y mode (RFC 6386 §11.2). +pub fn read_kf_ymode(d: &mut BoolDecoder<'_>) -> YMode { + YMode::from_u8(d.read_tree(&KF_YMODE_TREE, &KF_YMODE_PROBS)) +} + +/// Decode an interframe Y mode at the persisted probabilities +/// (RFC 6386 §16.1; `probs` is the frame header's updated array). +pub fn read_ymode(d: &mut BoolDecoder<'_>, probs: &[u8; 4]) -> YMode { + YMode::from_u8(d.read_tree(&YMODE_TREE, probs)) +} + +/// Decode a chroma mode at the given (key-frame fixed or persisted +/// interframe) probabilities. +pub fn read_uvmode(d: &mut BoolDecoder<'_>, probs: &[u8; 3]) -> YMode { + YMode::from_u8(d.read_tree(&UV_MODE_TREE, probs)) +} + +/// Decode a 4x4 subblock mode at `probs` (RFC 6386 §11.3: in key frames +/// the probabilities come from the above/left context table). +pub fn read_bmode(d: &mut BoolDecoder<'_>, probs: &[u8]) -> BMode { + BMode::from_u8(d.read_tree(&BMODE_TREE, probs)) +} + +impl YMode { + fn from_u8(v: u8) -> YMode { + match v { + 0 => YMode::DcPred, + 1 => YMode::VPred, + 2 => YMode::HPred, + 3 => YMode::TmPred, + 4 => YMode::BPred, + _ => unreachable!("tree cannot produce mode {v}"), + } + } +} + +impl BMode { + fn from_u8(v: u8) -> BMode { + match v { + 0 => BMode::BDCPred, + 1 => BMode::BTMPred, + 2 => BMode::BVEPred, + 3 => BMode::BHEPred, + 4 => BMode::BLDPred, + 5 => BMode::BRDPred, + 6 => BMode::BVRPred, + 7 => BMode::BVLPred, + 8 => BMode::BHDPred, + 9 => BMode::BHUPred, + _ => unreachable!("tree cannot produce bmode {v}"), + } + } +} + +/// Inter-frame motion-vector reference modes (RFC 6386 §16.2), offset +/// from the intra modes by `num_ymodes` in the reference enum; here they +/// are their own small enum with the RFC's tree integers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum MvRef { + /// Zero motion vector ("10" second branch; coded 0). + Zero = 0, + /// "Nearest" vector (coded 1). + Nearest = 1, + /// "Near" vector (coded 2). + Near = 2, + /// Explicit offset from best (coded 3). + New = 3, + /// Per-subblock vectors (coded 4). + Split = 4, +} + +/// mv_ref coding tree (RFC 6386 §16.2): leaves are [`MvRef`] integers. +pub const MV_REF_TREE: [i8; 8] = [0, 2, -1, 4, -2, 6, -3, -4]; + +/// Motion-vector component: row then column, each with the 19-probability +/// table (§17.1). +pub const MVP_IS_SHORT: usize = 0; +pub const MVP_SIGN: usize = 1; +pub const MVP_SHORT: usize = 2; +pub const MVP_BITS: usize = MVP_SHORT + 7; +pub const MVP_COUNT: usize = MVP_BITS + 10; + +/// Small-value coding tree for MV components (§17.1 `small_mvtree`). +pub const SMALL_MV_TREE: [i8; 14] = [ + 2, 8, // "0" / "1" subtrees + 4, 6, // "00" / "01" + 0, -1, // 0 = "000", 1 = "001" + -2, -3, // 2, 3 + 10, 12, // "10" / "11" + -4, -5, // 4, 5 + -6, -7, // 6, 7 +]; + +/// SPLITMV partition shapes tree + fixed probs (§16.4). Leaves are the +/// RFC's `MVpartition` integers: 0 = top/bottom, 1 = left/right, +/// 2 = quarters, 3 = MV_16. +pub const MV_PARTITION_TREE: [i8; 6] = [-3, 2, -2, 4, 0, -1]; +pub const MV_PARTITION_PROBS: [u8; 3] = [110, 111, 150]; + +/// The four SPLITMV partitionings as subblock groups (§16.4), indexed +/// by the `MVpartition` integer: each group shares one motion vector, +/// decoded in the listed (leader) order. +pub const MV_PARTITIONS: [&[usize]; 4] = [ + // mv_top_bottom: {0..7} then {8..15}. + &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + // mv_left_right: {0,1,4,5,8,9,12,13} then {2,3,6,7,10,11,14,15}. + &[0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15], + // mv_quarters: {0,1,4,5} {2,3,6,7} {8,9,12,13} {10,11,14,15}. + &[0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15], + // MV_16: every subblock gets its own vector, raster order. + &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], +]; + +/// Number of distinct vectors per partition shape (§16.4). +pub const MV_PARTITION_COUNT: [usize; 4] = [2, 2, 4, 16]; + +/// Inter subblock modes (§16.4): reuse the already-coded MV left/above, +/// zero, or an explicit offset. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum SubMvRef { + /// Copy the left neighbour's MV (coded 0). + Left4x4 = 0, + /// Copy the above neighbour's MV (coded 1). + Above4x4 = 1, + /// Zero MV (coded 2). + Zero4x4 = 2, + /// Explicit offset from best (coded 3). + New4x4 = 3, +} + +pub const SUB_MV_REF_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3]; + +/// Context-conditioned sub-MV probabilities (§16.4 `sub_mv_ref_prob`). +pub const SUB_MV_REF_PROBS: [[u8; 3]; 5] = [ + [147, 136, 18], + [106, 145, 1], + [179, 121, 1], + [223, 1, 34], + [208, 1, 1], +]; + +/// Sub-MV tree context (§16.4 `vp8_mvCont`): 4 = left==above==zero, +/// 3 = left==above, 2 = above zero, 1 = left zero, 0 = normal. +pub fn mv_cont(l: (i16, i16), a: (i16, i16)) -> usize { + let lez = l == (0, 0); + let aez = a == (0, 0); + let lea = l == a; + if lea && lez { + 4 + } else if lea { + 3 + } else if aez { + 2 + } else if lez { + 1 + } else { + 0 + } +} + +/// Weighted-census probability table for the mv_ref tree +/// (§16.3 `vp8_mode_contexts`, indexed by clamped count per slot). +pub const MODE_CONTEXTS: [[u8; 4]; 6] = [ + [7, 1, 1, 143], + [14, 18, 14, 107], + [135, 64, 57, 68], + [60, 56, 128, 65], + [159, 134, 128, 34], + [234, 188, 128, 28], +]; + +/// Decode an mv_ref at the census-derived probabilities (§16.2/§16.3). +pub fn read_mv_ref(d: &mut BoolDecoder<'_>, probs: &[u8; 4]) -> MvRef { + match d.read_tree(&MV_REF_TREE, probs) { + 0 => MvRef::Zero, + 1 => MvRef::Nearest, + 2 => MvRef::Near, + 3 => MvRef::New, + 4 => MvRef::Split, + v => unreachable!("mv_ref tree produced {v}"), + } +} + +/// Decode a SPLITMV partition shape (§16.4); returns the `MVpartition` +/// integer indexing [`MV_PARTITIONS`]. +pub fn read_mv_partition(d: &mut BoolDecoder<'_>) -> usize { + usize::from(d.read_tree(&MV_PARTITION_TREE, &MV_PARTITION_PROBS)) +} + +/// Decode a sub-MV reference (§16.4) at the context's probabilities. +pub fn read_sub_mv_ref(d: &mut BoolDecoder<'_>, ctx: usize) -> SubMvRef { + match d.read_tree(&SUB_MV_REF_TREE, &SUB_MV_REF_PROBS[ctx]) { + 0 => SubMvRef::Left4x4, + 1 => SubMvRef::Above4x4, + 2 => SubMvRef::Zero4x4, + 3 => SubMvRef::New4x4, + v => unreachable!("sub_mv_ref tree produced {v}"), + } +} diff --git a/crates/ec-vp8/src/tokens.rs b/crates/ec-vp8/src/tokens.rs new file mode 100644 index 00000000..ca10511c --- /dev/null +++ b/crates/ec-vp8/src/tokens.rs @@ -0,0 +1,282 @@ +//! DCT coefficient (token) decoding — RFC 6386 §13. +//! +//! Per 4x4 block: tokens are tree-decoded at +//! `probs[type][band[position]][ctx]` where `ctx` (0..2) is the zero- +//! neighbour count — sum of the above/left block contexts for the first +//! coded coefficient, then derived from the magnitude of the previous +//! coefficient within the block (§13.3). Coefficients are written in +//! natural (de-zigzagged) order and dequantized on the fly (the first +//! coded position takes the DC factor, all others the AC factor — the +//! same arithmetic dixie applies inline and libvpx applies in +//! `vp8_dequantize_b`). +//! +//! After an EOB the block ends; after a `DCT_0` token the tree decode of +//! the next coefficient skips the EOB branch (§13.2). A block whose +//! coefficients fill all 16 positions cannot take an EOB (the decoder +//! stops at 16 exactly like the reference decoder, down to the sentinel +//! band entry). + +use crate::bool::BoolDecoder; +use crate::tables::{PCAT3, PCAT4, PCAT5, PCAT6}; + +/// De-zigzag: coefficient scan position -> natural order index +/// (RFC 6386 §13, dixie/libvpx `zigzag`). +const ZIGZAG: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; + +/// Band per coefficient position, with the reference decoder's sentinel +/// entry at 16 (band 0 on the malformed no-EOB path — libvpx `kBands`). +const BANDS: [u8; 17] = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0]; + +/// Extra-bit probability tables per category (cat3..cat6, RFC 6386 +/// §13.2; the cat1/cat2 probabilities 159/165+145 are inlined in the +/// tree decode exactly as the reference does). Trailing 0 is the +/// DCTextra sentinel. +const CAT_EXTRA: [&[u8]; 4] = [&PCAT3, &PCAT4, &PCAT5, &PCAT6]; + +/// Dequantization factors for one macroblock (already scaled: Y2 AC has +/// the ×155/100 min-8 rule applied, Y2 DC ×2, UV DC capped at 132). +#[derive(Debug, Clone, Copy)] +pub(crate) struct Dq { + pub y1_dc: i16, + pub y1_ac: i16, + pub uv_dc: i16, + pub uv_ac: i16, + pub y2_dc: i16, + pub y2_ac: i16, +} + +/// The 25 blocks of one macroblock, dequantized, in natural coefficient +/// order. `eobs[b]` is the number of significant coefficients (position +/// of the last non-zero + 1); `eob_mask` mirrors dixie's: bit b set iff +/// block b ended with more than one significant coefficient, bit 31 set +/// iff ANY block had a non-zero coefficient. +pub(crate) struct MbCoeffs { + pub y: [[i16; 16]; 16], + pub u: [[i16; 16]; 4], + pub v: [[i16; 16]; 4], + pub y2: [i16; 16], + pub has_y2: bool, + pub eobs: [u8; 25], + pub eob_mask: u32, +} + +impl MbCoeffs { + pub(crate) fn empty(has_y2: bool) -> Self { + Self { + y: [[0; 16]; 16], + u: [[0; 16]; 4], + v: [[0; 16]; 4], + y2: [0; 16], + has_y2, + eobs: [0; 25], + eob_mask: 0, + } + } + + /// Whether any block carries a non-zero coefficient (the loop + /// filter's interior-edge condition, §15.1). + pub fn has_nonzero(&self) -> bool { + self.eob_mask & (1 << 31) != 0 + } +} + +/// Left/above context slot of each block (dixie `left_context_index` / +/// `above_context_index`). +const LEFT_INDEX: [usize; 25] = [ + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, +]; +const ABOVE_INDEX: [usize; 25] = [ + 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, +]; + +/// Token entropy contexts (dixie/libvpx layout): indices 0-3 are the Y +/// subblock columns, 4-5 U, 6-7 V, 8 the Y2 block. `left` is the running +/// one-MB-wide column state; `above` is the per-MB-column state for the +/// current row (9 slots per MB column). +pub(crate) struct TokenContexts { + pub above: Vec, + pub left: [u8; 9], +} + +impl TokenContexts { + /// `mb_cols` entries of 9 slots for the above state. + pub fn new(mb_cols: usize) -> Self { + Self { + above: vec![0u8; mb_cols * 9], + left: [0; 9], + } + } + + /// Reset the above state at the start of a row (§13.3: non-existent + /// neighbours are empty). + pub fn reset_above_row(&mut self) { + self.above.iter_mut().for_each(|s| *s = 0); + } + + /// Reset the left state at the start of a row (the caller MUST call + /// this once per MB row before decoding its tokens). + pub fn reset_left(&mut self) { + self.left = [0; 9]; + } + + /// Skip-MB context reset (dixie `reset_mb_context`): everything to 0 + /// except the Y2 slots, which survive iff this MB has no Y2 block. + pub fn reset_mb(&mut self, mb_col: usize, has_y2: bool) { + let a = &mut self.above[mb_col * 9..mb_col * 9 + 9]; + a[..8].fill(0); + self.left[..8].fill(0); + if has_y2 { + a[8] = 0; + self.left[8] = 0; + } + } + + fn ctx_pair(&self, mb_col: usize, block: usize) -> (u8, u8) { + let a = &self.above[mb_col * 9..mb_col * 9 + 9]; + (self.left[LEFT_INDEX[block]], a[ABOVE_INDEX[block]]) + } + + fn set_ctx(&mut self, mb_col: usize, block: usize, v: u8) { + self.left[LEFT_INDEX[block]] = v; + self.above[mb_col * 9 + ABOVE_INDEX[block]] = v; + } +} + +/// Decode one 4x4 block's tokens (libvpx `GetCoeffs` / RFC §13.2-13.3 +/// verbatim). `probs_t` is `[band][ctx][node]` for the block's plane +/// type; `n0` the first coded position (1 for Y blocks after a Y2). +/// Returns the number of significant coefficients. Coefficients are +/// written dequantized into `out` (natural order). +fn get_coeffs( + bc: &mut BoolDecoder<'_>, + probs_t: &[[[u8; 11]; 3]; 8], + ctx: usize, + n0: usize, + dc_factor: i16, + ac_factor: i16, + out: &mut [i16; 16], +) -> usize { + let mut n = n0; + let mut p = &probs_t[BANDS[n0] as usize][ctx]; + if !bc.read_bool(p[0]) { + return 0; // immediate EOB + } + loop { + n += 1; + let mut v: i32; + if !bc.read_bool(p[1]) { + // DCT_0: next decision skips the EOB branch (§13.2). + p = &probs_t[BANDS[n] as usize][0]; + } else { + if !bc.read_bool(p[2]) { + p = &probs_t[BANDS[n] as usize][1]; + v = 1; + } else if !bc.read_bool(p[3]) { + if !bc.read_bool(p[4]) { + v = 2; + } else { + v = 3 + i32::from(bc.read_bool(p[5])); + } + } else if !bc.read_bool(p[6]) { + if !bc.read_bool(p[7]) { + v = 5 + i32::from(bc.read_bool(159)); + } else { + v = 7 + 2 * i32::from(bc.read_bool(165)); + v += i32::from(bc.read_bool(145)); + } + } else { + // Categories 3..6: two tree bits pick the category, then + // DCTextra (§13.2). + let bit1 = usize::from(bc.read_bool(p[8])); + let bit0 = usize::from(bc.read_bool(p[9 + bit1])); + let cat = 2 * bit1 + bit0; + v = 0; + for &prob in CAT_EXTRA[cat] { + if prob == 0 { + break; + } + v += v + i32::from(bc.read_bool(prob)); + } + v += 3 + (8 << cat); + } + + // Sign flag, then dequantize (first coded position is DC). + let mag = if bc.read_bool(128) { -v } else { v }; + out[ZIGZAG[n - 1]] = if n - 1 == 0 { + (mag * i32::from(dc_factor)) as i16 + } else { + (mag * i32::from(ac_factor)) as i16 + }; + if n < 16 { + // Non-zero coefficients set the magnitude context for + // the next coefficient (§13.3). + p = &probs_t[BANDS[n] as usize][2]; + } + if n == 16 || !bc.read_bool(p[0]) { + return n; + } + } + if n == 16 { + return 16; // malformed without EOB: stop like the reference + } + } +} + +/// Decode all 25 blocks of one macroblock (dixie `decode_mb_tokens`): +/// Y2 first when present, then the 16 Y, then U, then V. A skipped MB +/// must not be run through here — call [`skip_mb_tokens`] instead. +pub(crate) fn decode_mb_tokens( + bc: &mut BoolDecoder<'_>, + probs: &[[[[u8; 11]; 3]; 8]; 4], + dq: &Dq, + has_y2: bool, + ctxs: &mut TokenContexts, + mb_col: usize, +) -> MbCoeffs { + let mut out = MbCoeffs::empty(has_y2); + let mut eob_mask = 0u32; + + // Decode one block and fold its contexts/mask in. + macro_rules! block { + ($idx:expr, $ptype:expr, $dc:expr, $ac:expr, $slot:expr) => {{ + let n0 = usize::from($ptype == 0); + let (l, a) = ctxs.ctx_pair(mb_col, $idx); + let ctx = (usize::from(l) + usize::from(a)).min(2); + let eob = get_coeffs(bc, &probs[$ptype], ctx, n0, $dc, $ac, $slot); + out.eobs[$idx] = eob as u8; + let t = u8::from(eob > 0); + ctxs.set_ctx(mb_col, $idx, t); + eob_mask |= (u32::from(eob > 1)) << $idx; + eob_mask |= u32::from(t != 0) << 31; + }}; + } + + if has_y2 { + block!(24, 1, dq.y2_dc, dq.y2_ac, &mut out.y2); + for b in 0..16 { + block!(b, 0, dq.y1_dc, dq.y1_ac, &mut out.y[b]); + } + } else { + for b in 0..16 { + block!(b, 3, dq.y1_dc, dq.y1_ac, &mut out.y[b]); + } + } + for b in 0..4 { + block!(16 + b, 2, dq.uv_dc, dq.uv_ac, &mut out.u[b]); + } + for b in 0..4 { + block!(20 + b, 2, dq.uv_dc, dq.uv_ac, &mut out.v[b]); + } + + out.eob_mask = eob_mask; + out +} + +/// The context reset a skipped MB applies (dixie `reset_mb_context`): +/// the returned [`MbCoeffs`] is all-zero and the contexts look like a +/// fully-empty MB — except the Y2 slots survive when the skipped MB has +/// no Y2 block. +pub(crate) fn skip_mb_tokens(ctxs: &mut TokenContexts, mb_col: usize, has_y2: bool) -> MbCoeffs { + ctxs.reset_mb(mb_col, has_y2); + MbCoeffs::empty(has_y2) +} diff --git a/crates/ec-vp8/src/transform.rs b/crates/ec-vp8/src/transform.rs new file mode 100644 index 00000000..520d7982 --- /dev/null +++ b/crates/ec-vp8/src/transform.rs @@ -0,0 +1,640 @@ +//! Inverse transforms (inverse DCT, inverse Walsh-Hadamard) and dequant +//! factor computation for VP8 (RFC 6386 §14). +//! +//! Every function here is a bit-exact transcription of the normative +//! reference implementation in libvpx (`vp8/common/idctllm.c` and +//! `vp8/common/quant_common.c`), which is also what RFC 6386 §§14.3–14.5 +//! print as pseudocode. Bit-level fidelity of the rounding is a hard +//! requirement: arithmetic right shifts (`>>` on `i32` in Rust, as in C) +//! round toward negative infinity, and both implementations rely on that +//! floor behavior for negative operands. +//! +//! Fidelity details reproduced verbatim from the oracle: +//! - The 16-bit fixed-point constants `cospi8sqrt2minus1 = 20091` and +//! `sinpi8sqrt2 = 35468` (§14.4). The `>> 16` multiplies carry **no** +//! rounding constant; the `+4` before the final `>> 3` appears only in +//! the second DCT pass. +//! - `short output[16]` intermediates: libvpx stores the first-pass +//! results into a `short` array, truncating `i32` arithmetic to `i16` +//! between passes. We reproduce those truncation points with `as i16` +//! (wrapping two's-complement truncation, identical to the de facto C +//! behavior) so results stay oracle-exact even for adversarial inputs. +//! - The inverse WHT rounds with `(x + 3) >> 3` (§14.3); the DC-only +//! shortcut uses the same constant on `input[0]` alone. +//! +//! All functions are pure, allocation-free, and free of `unsafe`. + +#![deny(unsafe_code)] + +/// 16-bit fixed-point `sqrt(2) * cos(pi/8) - 1` (RFC 6386 §14.4). The +/// product `x * sqrt(2) * cos(pi/8)` is computed as `x + ((x * K) >> 16)` +/// because the constant exceeds 1.0 and would otherwise lose precision. +const COSPI8SQRT2MINUS1: i32 = 20091; + +/// 16-bit fixed-point `sqrt(2) * sin(pi/8)` (RFC 6386 §14.4). +const SINPI8SQRT2: i32 = 35468; + +/// DC quantizer lookup, `dc_qlookup[QINDEX_RANGE]` (RFC 6386 §14.1), +/// transcribed mechanically from libvpx `vp8/common/quant_common.c`. +const DC_QLOOKUP: [i16; 128] = [ + 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, + 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, + 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, + 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130, + 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, +]; + +/// AC quantizer lookup, `ac_qlookup[QINDEX_RANGE]` (RFC 6386 §14.1), +/// transcribed mechanically from libvpx `vp8/common/quant_common.c`. +const AC_QLOOKUP: [i16; 128] = [ + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, + 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, + 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205, + 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, +]; + +/// Clamps a (possibly delta-adjusted) quantizer index to the valid +/// qindex range `[0, 127]` — dixie `clamp_q` / libvpx bounds in +/// `quant_common.c` (RFC 6386 §14.1). +#[inline] +fn clamp_q(q: i32) -> i32 { + q.clamp(0, 127) +} + +/// `dc_qlookup[clamp(q + delta)]` — Y-after-second / per-plane DC factor +/// lookup with delta adjustment (RFC 6386 §14.1 `dc_q`). +#[inline] +fn dc_factor(q: i32, delta: i32) -> i16 { + DC_QLOOKUP[clamp_q(q + delta) as usize] +} + +/// `ac_qlookup[clamp(q + delta)]` — AC factor lookup with delta +/// adjustment (RFC 6386 §14.1 `ac_q`). +#[inline] +fn ac_factor(q: i32, delta: i32) -> i16 { + AC_QLOOKUP[clamp_q(q + delta) as usize] +} + +/// Inverse Walsh-Hadamard transform of the 16 dequantized Y2 DC +/// coefficients into the 16 Y-subblock DC residuals +/// (RFC 6386 §14.3 `vp8_short_inv_walsh4x4_c`, oracle +/// `vp8_short_inv_walsh4x4_c` in `idctllm.c`). +/// +/// `input` is the row-major 4x4 block of dequantized Y2 DCs; the returned +/// array holds the 16 Y-subblock DC values in the same row-major order +/// (the reference scatters `output[i]` to `mb_dqcoeff[i * 16]`, i.e. the +/// DC slot of the i-th Y subblock — the caller places them). Two passes +/// of the exact 4-point Hadamard butterfly, with `short` truncation of +/// the first-pass results and `(x + 3) >> 3` rounding in the second. +#[inline] +pub fn iwht4x4(input: &[i16; 16]) -> [i16; 16] { + let mut tmp = [0i16; 16]; + + // First pass: transform columns; results are stored transposed into + // rows of `tmp` (ip walks input[i], input[4+i], input[8+i], + // input[12+i]). libvpx stores into `short`: truncate to i16. + for i in 0..4 { + let a1 = input[i] as i32 + input[12 + i] as i32; + let b1 = input[4 + i] as i32 + input[8 + i] as i32; + let c1 = input[4 + i] as i32 - input[8 + i] as i32; + let d1 = input[i] as i32 - input[12 + i] as i32; + + tmp[i] = (a1 + b1) as i16; + tmp[4 + i] = (c1 + d1) as i16; + tmp[8 + i] = (a1 - b1) as i16; + tmp[12 + i] = (d1 - c1) as i16; + } + + let mut output = [0i16; 16]; + + // Second pass: transform rows in place, rounding with (x + 3) >> 3. + for r in 0..4 { + let i = 4 * r; + let a1 = tmp[i] as i32 + tmp[i + 3] as i32; + let b1 = tmp[i + 1] as i32 + tmp[i + 2] as i32; + let c1 = tmp[i + 1] as i32 - tmp[i + 2] as i32; + let d1 = tmp[i] as i32 - tmp[i + 3] as i32; + + let a2 = a1 + b1; + let b2 = c1 + d1; + let c2 = a1 - b1; + let d2 = d1 - c1; + + output[i] = ((a2 + 3) >> 3) as i16; + output[i + 1] = ((b2 + 3) >> 3) as i16; + output[i + 2] = ((c2 + 3) >> 3) as i16; + output[i + 3] = ((d2 + 3) >> 3) as i16; + } + + output +} + +/// One-nonzero-DC shortcut of the inverse WHT +/// (RFC 6386 §14.3 `vp8_short_inv_walsh4x4_1_c`, oracle +/// `vp8_short_inv_walsh4x4_1_c` in `idctllm.c`). +/// +/// When only `input[0]` is non-zero, every Y-subblock DC equals +/// `(input[0] + 3) >> 3`. Bit-identical to `iwht4x4` for such inputs. +#[inline] +pub fn iwht4x4_dc(input: &[i16; 16]) -> [i16; 16] { + let a1 = ((input[0] as i32 + 3) >> 3) as i16; + [a1; 16] +} + +/// Full inverse DCT of one dequantized 4x4 coefficient block +/// (RFC 6386 §14.4; oracle `short_idct4x4llm_c` in `idctllm.c`). +/// +/// `coeffs` is a row-major 4x4 block of **already dequantized** +/// coefficients (dequantization happens before the transform, RFC 6386 +/// §14.5). Two passes of the 4-point inverse DCT with the §14.4 +/// fixed-point constants; the `>> 16` multiplies carry no rounding +/// constant and the `(x + 4) >> 3` rounding is applied only in the +/// second pass. First-pass results are truncated to `i16` exactly where +/// the oracle stores into its `short output[16]` scratch. +/// +/// Returns the row-major 4x4 residual. Not clamped, not added to the +/// prediction — see [`idct4x4_add`] for the combined form. +#[inline] +pub fn idct4x4(coeffs: &[i16; 16]) -> [i16; 16] { + let mut tmp = [0i16; 16]; + + // First pass: transform columns; results land transposed in rows of + // `tmp` (ip walks coeffs[i], coeffs[4+i], coeffs[8+i], coeffs[12+i]). + for i in 0..4 { + let a1 = coeffs[i] as i32 + coeffs[8 + i] as i32; + let b1 = coeffs[i] as i32 - coeffs[8 + i] as i32; + + let temp1 = (coeffs[4 + i] as i32 * SINPI8SQRT2) >> 16; + let temp2 = coeffs[12 + i] as i32 + ((coeffs[12 + i] as i32 * COSPI8SQRT2MINUS1) >> 16); + let c1 = temp1 - temp2; + + let temp1 = coeffs[4 + i] as i32 + ((coeffs[4 + i] as i32 * COSPI8SQRT2MINUS1) >> 16); + let temp2 = (coeffs[12 + i] as i32 * SINPI8SQRT2) >> 16; + let d1 = temp1 + temp2; + + // libvpx stores into `short`: truncate to i16. + tmp[i] = (a1 + d1) as i16; + tmp[12 + i] = (a1 - d1) as i16; + tmp[4 + i] = (b1 + c1) as i16; + tmp[8 + i] = (b1 - c1) as i16; + } + + let mut output = [0i16; 16]; + + // Second pass: transform rows, rounding with (x + 4) >> 3. + for r in 0..4 { + let i = 4 * r; + let ip0 = tmp[i] as i32; + let ip1 = tmp[i + 1] as i32; + let ip2 = tmp[i + 2] as i32; + let ip3 = tmp[i + 3] as i32; + + let a1 = ip0 + ip2; + let b1 = ip0 - ip2; + + let temp1 = (ip1 * SINPI8SQRT2) >> 16; + let temp2 = ip3 + ((ip3 * COSPI8SQRT2MINUS1) >> 16); + let c1 = temp1 - temp2; + + let temp1 = ip1 + ((ip1 * COSPI8SQRT2MINUS1) >> 16); + let temp2 = (ip3 * SINPI8SQRT2) >> 16; + let d1 = temp1 + temp2; + + output[i] = ((a1 + d1 + 4) >> 3) as i16; + output[i + 3] = ((a1 - d1 + 4) >> 3) as i16; + output[i + 1] = ((b1 + c1 + 4) >> 3) as i16; + output[i + 2] = ((b1 - c1 + 4) >> 3) as i16; + } + + output +} + +/// DC-only inverse DCT shortcut (RFC 6386 §14.4 +/// `vp8_dc_only_idct_add_c` math; oracle `idctllm.c`): when position 0 is +/// the sole non-zero coefficient, every residual pixel is `(dc + 4) >> 3`. +/// +/// Bit-identical to `idct4x4` on such inputs. Not clamped; the caller +/// adds and clamps (or uses [`idct4x4_add`]). +#[inline] +pub fn idct4x4_dc(dc: i16) -> [i16; 16] { + let a1 = ((dc as i32 + 4) >> 3) as i16; + [a1; 16] +} + +/// Combined per-block reconstruction kernel (RFC 6386 §14.4/§14.5; oracle +/// `short_idct4x4llm_c` final loop in `idctllm.c`): inverse-transforms +/// `coeffs` and writes `clamp(predict + residual)` into `recon`. +/// +/// `coeffs` must already be dequantized (dequantization is applied before +/// the transform; for intra Y macroblocks the DC positions already hold +/// the [`iwht4x4`] output). `predict` and `recon` are row-major 4x4 +/// blocks of exactly 16 bytes each. Residuals are fully computed before +/// any output byte is written. +#[inline] +pub fn idct4x4_add(coeffs: &[i16; 16], predict: &[u8], recon: &mut [u8]) { + let residual = idct4x4(coeffs); + for i in 0..16 { + let a = residual[i] as i32 + predict[i] as i32; + recon[i] = a.clamp(0, 255) as u8; + } +} + +/// Dequantization factors for one macroblock, indexed by plane and +/// coefficient type (RFC 6386 §14.1; dixie `struct dequant_factors`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Dequant { + /// Y plane, DC coefficient (after inverse WHT for intra Y2 rows). + pub y1_dc: i16, + /// Y plane, AC coefficients. + pub y1_ac: i16, + /// Y2 plane (second-order) DC coefficient: `dc_qlookup[...] * 2`. + pub y2_dc: i16, + /// Y2 plane AC coefficient: `ac_qlookup[...] * 155 / 100`, floored at 8. + pub y2_ac: i16, + /// Chroma DC coefficient, capped at 132 after lookup. + pub uv_dc: i16, + /// Chroma AC coefficient. + pub uv_ac: i16, +} + +/// Computes the six dequantization factors for quantizer index `q` with +/// the per-frame delta updates (RFC 6386 §9.6 header fields applied per +/// §14.1; dixie `dequant_init`, oracle `vp8cx_init_quantizer` in +/// libvpx `decodframe.c` / `quant_common.c`). +/// +/// `q` is the per-macroblock segment-adjusted base qindex (already +/// absolute or offset by the segment level per the segment header); the +/// delta arguments are the frame-header updates. Each lookup clamps its +/// `q + delta` sum to `[0, 127]`. Semantics transcribed exactly: +/// - `y1_dc = dc_qlookup[clamp(q + y1_dc_delta)]`, +/// `y1_ac = ac_qlookup[clamp(q)]` (no delta exists for Y AC), +/// - `y2_dc = dc_qlookup[clamp(q + y2_dc_delta)] * 2`, +/// - `y2_ac = ac_qlookup[clamp(q + y2_ac_delta)] * 155 / 100` (integer +/// division), floored at 8, +/// - `uv_dc = min(dc_qlookup[clamp(q + uv_dc_delta)], 132)` (cap applied +/// after the lookup), +/// - `uv_ac = ac_qlookup[clamp(q + uv_ac_delta)]`. +#[must_use] +pub fn dequant( + q: i32, + y1_dc_delta: i32, + y2_dc_delta: i32, + y2_ac_delta: i32, + uv_dc_delta: i32, + uv_ac_delta: i32, +) -> Dequant { + Dequant { + y1_dc: dc_factor(q, y1_dc_delta), + y1_ac: ac_factor(q, 0), + y2_dc: dc_factor(q, y2_dc_delta) * 2, + y2_ac: { + let v = (ac_factor(q, y2_ac_delta) as i32 * 155) / 100; + (if v < 8 { 8 } else { v }) as i16 + }, + uv_dc: { + let v = dc_factor(q, uv_dc_delta); + if v > 132 { 132 } else { v } + }, + uv_ac: ac_factor(q, uv_ac_delta), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Hand-derived: impulse `input[0] = 8`, all else 0. First pass, the + /// only touched column (0) reads (8,0,0,0): a1 = 8+0 = 8, b1 = 0, + /// c1 = 0, d1 = 8, giving intermediate column 0 = [8,8,8,8]. Second + /// pass, every row reads (8,0,0,0): a2 = b2 = c2 = d2 = 8, and + /// (8 + 3) >> 3 = 1. Expected: all 16 outputs are 1. + #[test] + fn iwht_unit_impulse_yields_all_ones() { + let mut input = [0i16; 16]; + input[0] = 8; + assert_eq!(iwht4x4(&input), [1i16; 16]); + } + + /// Hand-derived: impulse `input[5] = 8` (row 1, col 1). First pass, + /// column 1 reads (0,8,0,0): a1 = 0, b1 = 8, c1 = 8, d1 = 0, giving + /// intermediate column 1 = [8, 8, -8, -8]. Second pass, rows 0-1 read + /// (0,8,0,0) → outputs (1, 1, -1, -1); rows 2-3 read (0,-8,0,0) → + /// (-1, -1, 1, 1) — the Hadamard basis pattern for position (1,1). + #[test] + fn iwht_impulse_at_row1_col1_yields_hadamard_pattern() { + let mut input = [0i16; 16]; + input[5] = 8; + assert_eq!( + iwht4x4(&input), + [ + 1, 1, -1, -1, // + 1, 1, -1, -1, // + -1, -1, 1, 1, // + -1, -1, 1, 1, + ] + ); + } + + /// Mixed-coefficient oracle: expected values computed with a Python + /// model of the exact libvpx integer algorithm (see the model in + /// `idct_mixed_block_matches_oracle` below — the WHT variant is the + /// same structure with §14.3 butterflies and `(x + 3) >> 3`). + #[test] + fn iwht_mixed_block_matches_oracle() { + let input = [ + 40, -13, 0, 7, 222, 5, -40, 1, 0, 0, 17, -9, 300, -250, 88, 3, + ]; + assert_eq!( + iwht4x4(&input), + [ + 46, 30, 95, 110, // + 9, 42, -15, -55, // + -3, -35, 37, 60, // + -36, -27, -86, -92, + ] + ); + } + + /// The `_dc` shortcut must agree with the full transform whenever + /// only `input[0]` is non-zero — across the whole practical range, + /// including negatives and both i16 extremes (arithmetic shifts are + /// floor rounding for negatives in both C and Rust). + #[test] + fn iwht_dc_shortcut_matches_full_transform() { + for v in [ + 0, + 1, + -1, + 3, + -3, + 8, + -8, + 100, + -100, + 1234, + -4321, + i16::MAX, + i16::MIN, + ] { + let input = { + let mut i = [0i16; 16]; + i[0] = v; + i + }; + assert_eq!(iwht4x4(&input), iwht4x4_dc(&input), "mismatch at dc={v}"); + } + } + + /// §14.4 DC-only math: input [40, 0, ...] gives every pixel + /// (40 + 4) >> 3 = 5. + #[test] + fn idct_dc_only_40_yields_five() { + let coeffs = { + let mut c = [0i16; 16]; + c[0] = 40; + c + }; + assert_eq!(idct4x4(&coeffs), [5i16; 16]); + assert_eq!(idct4x4_dc(40), [5i16; 16]); + } + + /// Mixed-coefficient oracle. The Python model below is a line-for-line + /// transcription of libvpx `short_idct4x4llm_c` (same integer math, + /// `short` truncation between passes via `s16`); running it on + /// `coeffs` prints the expected block embedded in the assertion. + /// + /// ```python + /// COS, SIN = 20091, 35468 + /// def s16(x): + /// x &= 0xFFFF + /// return x - 0x10000 if x >= 0x8000 else x + /// def idct(inp): + /// out = [0] * 16 + /// for i in range(4): # pass 1: columns, transposed into rows + /// a1 = inp[i] + inp[8+i]; b1 = inp[i] - inp[8+i] + /// c1 = ((inp[4+i]*SIN) >> 16) - (inp[12+i] + ((inp[12+i]*COS) >> 16)) + /// d1 = (inp[4+i] + ((inp[4+i]*COS) >> 16)) + ((inp[12+i]*SIN) >> 16) + /// out[i] = s16(a1 + d1); out[12+i] = s16(a1 - d1) + /// out[4+i] = s16(b1 + c1); out[8+i] = s16(b1 - c1) + /// res = [0] * 16 + /// for i in range(4): # pass 2: rows, rounding (x + 4) >> 3 + /// ip = out[4*i:4*i+4] + /// a1 = ip[0] + ip[2]; b1 = ip[0] - ip[2] + /// c1 = ((ip[1]*SIN) >> 16) - (ip[3] + ((ip[3]*COS) >> 16)) + /// d1 = (ip[1] + ((ip[1]*COS) >> 16)) + ((ip[3]*SIN) >> 16) + /// res[4*i+0] = s16((a1 + d1 + 4) >> 3) + /// res[4*i+3] = s16((a1 - d1 + 4) >> 3) + /// res[4*i+1] = s16((b1 + c1 + 4) >> 3) + /// res[4*i+2] = s16((b1 - c1 + 4) >> 3) + /// return res + /// ``` + #[test] + fn idct_mixed_block_matches_oracle() { + let coeffs = [ + 87, -43, 210, 5, -19, 0, 33, -77, 1234, -517, 9, 401, -88, 2100, -3, 55, + ]; + assert_eq!( + idct4x4(&coeffs), + [ + 305, 108, 139, 72, // + -508, -228, -88, 303, // + 372, 85, -443, -640, // + -48, -41, 345, 441, + ] + ); + } + + /// The DC-only shortcut must equal the full transform for any value + /// at coefficient position 0 (with the rest zero), including the i16 + /// extremes where the intermediate still fits. + #[test] + fn idct_dc_shortcut_matches_full_transform() { + for v in [ + 0, + 1, + -1, + 8, + -8, + 40, + -40, + 100, + -100, + 4088, + i16::MAX, + i16::MIN, + ] { + let coeffs = { + let mut c = [0i16; 16]; + c[0] = v; + c + }; + assert_eq!(idct4x4(&coeffs), idct4x4_dc(v), "mismatch at dc={v}"); + } + } + + /// §14.5: `idct4x4_add` is `clamp255(predict + idct4x4(coeffs))` + /// pixelwise. With a flat prediction of 100, every output byte must + /// be the saturated sum; extreme residuals clamp to 0 and 255. + #[test] + fn idct_add_equals_clamped_predict_plus_residual() { + let coeffs = [ + 87, -43, 210, 5, -19, 0, 33, -77, 1234, -517, 9, 401, -88, 2100, -3, 55, + ]; + let residual = idct4x4(&coeffs); + let predict = [100u8; 16]; + let mut recon = [0u8; 16]; + idct4x4_add(&coeffs, &predict, &mut recon); + for i in 0..16 { + let expected = (residual[i] as i32 + 100).clamp(0, 255) as u8; + assert_eq!(recon[i], expected, "pixel {i}"); + } + + // Saturation: DC 4088 → residual (4088 + 4) >> 3 = 511; 100 + 511 + // clamps to 255. Negative DC -32768 → residual (-32764) >> 3 = + // -4096; clamps to 0. + let mut hi = [0i16; 16]; + hi[0] = 4088; + let mut lo = [0i16; 16]; + lo[0] = i16::MIN; + let mut recon = [0u8; 16]; + idct4x4_add(&hi, &predict, &mut recon); + assert_eq!(recon, [255u8; 16]); + idct4x4_add(&lo, &predict, &mut recon); + assert_eq!(recon, [0u8; 16]); + } + + /// `idct4x4_add` over an existing recon block that already holds the + /// prediction (the common libvpx dst/pred shape). The `&[u8]` / + /// `&mut [u8]` signature statically excludes predict/recon aliasing. + #[test] + fn idct_add_updates_existing_recon_buffer() { + let coeffs = { + let mut c = [0i16; 16]; + c[0] = 40; + c + }; + let predict = [100u8; 16]; + let mut recon = [100u8; 16]; + idct4x4_add(&coeffs, &predict, &mut recon); + assert_eq!(recon, [105u8; 16]); + } + + /// §14.1 tables, transcribed from libvpx `quant_common.c`: exact + /// length plus boundary and known-trap entries (the duplicated 10 at + /// dc[6..7], the >89 acceleration at dc[95..96] and dc[111..112], and + /// the ac[54..55] and ac[84..85] jumps). + #[test] + fn quant_lookup_tables_match_libvpx() { + assert_eq!(DC_QLOOKUP.len(), 128); + assert_eq!(AC_QLOOKUP.len(), 128); + assert_eq!(&DC_QLOOKUP[..3], &[4, 5, 6]); + assert_eq!(DC_QLOOKUP[127], 157); + assert_eq!(AC_QLOOKUP[0], 4); + assert_eq!(AC_QLOOKUP[127], 284); + assert_eq!(&DC_QLOOKUP[6..=8], &[10, 10, 11]); + assert_eq!(&DC_QLOOKUP[95..=97], &[89, 91, 93]); + assert_eq!(&DC_QLOOKUP[111..=112], &[118, 122]); + assert_eq!(&AC_QLOOKUP[53..=55], &[57, 58, 60]); + assert_eq!(&AC_QLOOKUP[83..=85], &[116, 119, 122]); + } + + /// §14.1 boundary qindices: q=0 gives the minimum factors (with the + /// Y2 AC floor of 8 already active), q=127 gives the maxima including + /// the chroma DC cap at 132. + #[test] + fn dequant_at_qindex_boundaries() { + assert_eq!( + dequant(0, 0, 0, 0, 0, 0), + Dequant { + y1_dc: 4, + y1_ac: 4, + y2_dc: 8, + y2_ac: 8, + uv_dc: 4, + uv_ac: 4 + } + ); + assert_eq!( + dequant(127, 0, 0, 0, 0, 0), + Dequant { + y1_dc: 157, + y1_ac: 284, + y2_dc: 314, + y2_ac: 440, // 284 * 155 / 100 + uv_dc: 132, // 157 capped at 132 + uv_ac: 284, + } + ); + } + + /// Delta-adjusted qindices clamp to [0, 127] before each lookup, for + /// every delta channel (RFC 6386 §14.1 dixie `clamp_q`). + #[test] + fn dequant_delta_indices_clamp_to_qindex_range() { + let lo = dequant(0, -1000, -1000, -1000, -1000, -1000); + assert_eq!(lo.y1_dc, 4); + assert_eq!(lo.y2_dc, 8); // 4 * 2 + assert_eq!(lo.y2_ac, 8); // floor + assert_eq!(lo.uv_dc, 4); + assert_eq!(lo.uv_ac, 4); + + let hi = dequant(127, 1000, 1000, 1000, 1000, 1000); + assert_eq!(hi.y1_dc, 157); + assert_eq!(hi.y2_dc, 314); + assert_eq!(hi.y2_ac, 440); + assert_eq!(hi.uv_dc, 132); + assert_eq!(hi.uv_ac, 284); + + // A base q of 0 with positive deltas reaches mid-table: q=60 has + // dc_qlookup[60] = 55, ac_qlookup[60] = 70. + let mid = dequant(0, 60, 60, 60, 60, 60); + assert_eq!(mid.y1_dc, 55); + assert_eq!(mid.y1_ac, 4); // Y AC has no delta channel + assert_eq!(mid.y2_dc, 110); + assert_eq!(mid.y2_ac, 70 * 155 / 100); // 108 + assert_eq!(mid.uv_dc, 55); + assert_eq!(mid.uv_ac, 70); + } + + /// The Y2 AC floor: `x * 155 / 100 < 8` becomes 8. At q=0..4 + /// (ac = 4..8) the scaled values are 6, 7, 9, 10, 12 — only the first + /// two floor up. + #[test] + fn dequant_y2_ac_floor_at_eight() { + for q in 0..=4i32 { + let ac = AC_QLOOKUP[q as usize] as i32; + let scaled = ac * 155 / 100; + assert_eq!( + dequant(q, 0, 0, 0, 0, 0).y2_ac as i32, + scaled.max(8), + "q={q}" + ); + } + assert_eq!(dequant(0, 0, 0, 0, 0, 0).y2_ac, 8); // 4*155/100 = 6 → 8 + assert_eq!(dequant(1, 0, 0, 0, 0, 0).y2_ac, 8); // 5*155/100 = 7 → 8 + assert_eq!(dequant(2, 0, 0, 0, 0, 0).y2_ac, 9); // 6*155/100 = 9 + } + + /// libvpx computes the Y2 AC factor as `(x * 101581) >> 16` and its + /// comment asserts bitwise equality with `x * 155 / 100` for all + /// table entries; our transcription of dixie uses `* 155 / 100`, so + /// sweep the whole qindex range and prove the two agree through the + /// public API (with a matching delta for the Y2 AC channel). + #[test] + fn dequant_y2_ac_matches_libvpx_fixed_point_over_all_q() { + for q in 0..=127i32 { + for delta in [0, -q - 1, 127 - q] { + let x = AC_QLOOKUP[clamp_q(q + delta) as usize] as i32; + let expected = (((x * 101581) >> 16).max(8)) as i16; + assert_eq!( + dequant(q, 0, 0, delta, 0, 0).y2_ac, + expected, + "q={q}, delta={delta}" + ); + } + } + } +} diff --git a/crates/ec-vp8/tests/keyframe_exact.rs b/crates/ec-vp8/tests/keyframe_exact.rs new file mode 100644 index 00000000..2170c86c --- /dev/null +++ b/crates/ec-vp8/tests/keyframe_exact.rs @@ -0,0 +1,114 @@ +//! M2 witness: key-frame decode is sample-exact against ffmpeg/libvpx +//! (`ffmpeg -v error -i in.ivf -f rawvideo -pix_fmt yuv420p -`). + +mod ivf; + +use ec_vp8::decode::{Decoder, Picture}; + +/// ffmpeg's decoded rawvideo byte stream for the same 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 +} + +fn raw<'a>(pos: &mut usize, data: &'a [u8], len: usize) -> &'a [u8] { + let s = &data[*pos..*pos + len]; + *pos += len; + s +} + +/// Decode every frame of an IVF with our decoder and compare each +/// frame's planes against ffmpeg's byte stream. +fn compare(name: &str, skip_if_missing: bool) { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let path = dir.join(name); + if skip_if_missing && !path.exists() { + panic!("{name} missing (regenerate fixtures)"); + } + 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() % frame_len, + 0, + "{name}: ffmpeg output {}/{} not whole frames", + all.len(), + frame_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); + 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"); + } +} + +#[test] +fn keyframes_match_ffmpeg() { + for (name, _, _) in [ + ("kf-160x96-q20.ivf", 160, 96), + ("kf-160x96-q40.ivf", 160, 96), + ("kf-76x52-q30.ivf", 76, 52), + ("kf-32x16-q35.ivf", 32, 16), + ("kf-172x144-q25.ivf", 172, 144), + ("kf-96x80-q63.ivf", 96, 80), + ] { + compare(name, false); + } +} + +#[test] +fn multi_partition_keyframe_matches_ffmpeg() { + compare("mparts-160x96.ivf", false); +} + +#[test] +fn vp8_in_webp_still_matches_ffmpeg() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let bytes = std::fs::read(dir.join("still.webp")).unwrap(); + let vp8 = ivf::webp_vp8_chunk(&bytes); + let reference = std::process::Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(dir.join("still.webp")) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .unwrap(); + assert!(reference.status.success()); + let mut dec = Decoder::new(); + let pic = dec.decode(&vp8).expect("decode").expect("shown"); + assert_eq!( + pic.y.len() + pic.u.len() + pic.v.len(), + reference.stdout.len() + ); + let mut exp = &reference.stdout[..]; + assert_eq!(pic.y, &exp[..pic.y.len()]); + exp = &exp[pic.y.len()..]; + assert_eq!(pic.u, &exp[..pic.u.len()]); + exp = &exp[pic.u.len()..]; + assert_eq!(pic.v, exp); +} diff --git a/scripts/raw_to_y4m.py b/scripts/raw_to_y4m.py new file mode 100755 index 00000000..296ca2a9 --- /dev/null +++ b/scripts/raw_to_y4m.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +"""Wrap raw planar yuv420p frames into a minimal y4m (for vpxenc). + + ffmpeg ... -f rawvideo - | raw_to_y4m.py W H FPS out.y4m +""" +import sys + +w, h, fps, out = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] +frame = int(w) * int(h) * 3 // 2 +raw = sys.stdin.buffer.read() +with open(out, "wb") as f: + f.write(f"YUV4MPEG2 W{w} H{h} F{fps}:1 Ip A1:1 C420jpeg\n".encode()) + for i in range(len(raw) // frame): + f.write(b"FRAME\n") + f.write(raw[i * frame : (i + 1) * frame])