From 83125b413895baa34518de37b10cda1f211277b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 19 Sep 2026 01:11:17 +0300 Subject: [PATCH] vp9: decode inter-frame pixels byte-exactly (MC, residual, loop filter, ref slots) decode() no longer refuses inter frames. New mc.rs ports libvpx's inter predictor: umv-border MV clamping, per-block reference border extension (build_mc_border), the direct path window read, the four 8-tap/bilinear convolve kernels, compound averaging and average_split_mvs. decode.rs gains the prediction/residual/reconstruction driver, an 8-slot reference DPB that stores each frame at its 64-aligned extent after the loop filter, and the skip/skip_inter loop-filter mask rules. Byte-exact against a locally built libvpx 1.15 oracle: the 1080p single-tile inter stream (3/3 frames), both static fixture GOPs (48 frames at 1080p and 2160p), the altref stream (60/60) and a two-tile-column stream (3/3). Loop filter verified separately by per-superblock mask identity (0 of 510 SBs differ) and by edge-set containment. A 120-frame 60fps stream decodes identically through frame 71 and hits an open entropy desync at frame 72, filed in lanes/vp9pix.report.md with its disposition. Also fixes a two-entry mv_ref_list overflow in the merged inter syntax path: the successful second candidate add inside the different-reference loop is a goto Done in libvpx and must leave the loop; without the break a later candidate wrote past the list (the altref fixture panicked at frame 14). Refusals kept/added by name: intra-only, other profiles, other subsamplings, a reference whose coded size differs from the current frame, odd dimensions. --- crates/ec-vp9/src/decode.rs | 885 ++++++++++++++++++---- crates/ec-vp9/src/inter.rs | 7 + crates/ec-vp9/src/lib.rs | 11 +- crates/ec-vp9/src/loopfilter.rs | 64 +- crates/ec-vp9/src/mc.rs | 558 ++++++++++++++ crates/ec-vp9/tests/inter_pixels_exact.rs | 131 ++++ crates/ec-vp9/tests/keyframe_exact.rs | 48 +- crates/ec-vp9/tests/scratch_pixdump.rs | 77 ++ lanes/vp9pix.report.md | 232 ++++++ 9 files changed, 1861 insertions(+), 152 deletions(-) create mode 100644 crates/ec-vp9/src/mc.rs create mode 100644 crates/ec-vp9/tests/inter_pixels_exact.rs create mode 100644 crates/ec-vp9/tests/scratch_pixdump.rs create mode 100644 lanes/vp9pix.report.md diff --git a/crates/ec-vp9/src/decode.rs b/crates/ec-vp9/src/decode.rs index 61a7e9c2..c055f0df 100644 --- a/crates/ec-vp9/src/decode.rs +++ b/crates/ec-vp9/src/decode.rs @@ -4,14 +4,17 @@ //! reconstruction and the loop filter (spec 6, 7, 8; libvpx //! `vp9_decodeframe.c`). //! -//! Lane scope: profile-0 8-bit 4:2:0 keyframes. Inter frames and other -//! profiles/subsamplings are refused by name; `show_existing_frame` -//! returns the buffered reference picture instead of pretending to -//! decode. +//! Capability: profile-0 8-bit 4:2:0 keyframes and inter frames (motion +//! compensation, residual reconstruction, the loop filter and an 8-slot +//! reference DPB). Intra-only frames, other profiles/subsamplings, a +//! reference whose coded size differs from the current frame, and odd frame +//! dimensions are refused by name; `show_existing_frame` returns the +//! buffered reference picture instead of pretending to decode. use crate::header::{FrameContext, read_compressed_header}; use crate::intra::build_intra_predictors; use crate::loopfilter::LfGrids; +use crate::mc::{RefPlane, average_split_mvs_chroma, build_inter_predictors, split_mv}; use crate::modes::{MiInfo, MiState, read_intra_frame_mode_info}; use crate::tables::*; use crate::tokens::{PlaneContexts, decode_coefs, scan_for}; @@ -51,6 +54,14 @@ struct Planes { } impl Planes { + /// Immutable plane + stride (the predictor reads references). + fn plane_ref(&self, plane: usize) -> (&[u8], usize) { + match plane { + 0 => (&self.y, self.ys), + 1 => (&self.u, self.uvs), + _ => (&self.v, self.uvs), + } + } fn plane(&mut self, plane: usize) -> (&mut [u8], usize) { match plane { 0 => (&mut self.y, self.ys), @@ -73,7 +84,7 @@ impl Planes { pub struct Decoder { parser: Vp9Parser, ctx: FrameContext, - refs: [Option; 8], + refs: [Option; 8], /// Frame scratch, live only inside `decode_keyframe`. planes: Option, /// The four stored frame contexts (spec 6.2 `frame_context_idx`). @@ -87,8 +98,36 @@ pub struct Decoder { iw: Option, /// Frames parsed by `decode_syntax` (the dump's frame index). frames_seen: usize, + /// Frames decoded by `decode` (the dumps' `frame=` field for this path; + /// `decode_syntax` counts the same way in `frames_seen`). + decode_index: usize, /// Mode-info blocks parsed in the most recent inter frame (0 otherwise). syntax_blocks: usize, + /// `twd->extend_and_predict_buf`: the per-prediction bordered reference + /// window built when a block's read leaves the reference frame. + mc_scratch: Vec, + /// The `vpx_convolve8` stride-64 intermediate plus the second scratch its + /// averaging variant needs. + mc_temp: Vec, +} + +/// One DPB slot: a decoded frame buffer at its ALIGNED (64-multiple) extent +/// plus the coded size it was decoded at. +/// +/// The aligned extent is load-bearing, not slack: libvpx writes a block at the +/// frame edge at its FULL size (`decodeframe.c:1216`), so the rows past the +/// coded height hold real reconstructed samples, and `dec_build_inter_predictors` +/// reads them directly whenever a block's window is inside the frame with a +/// whole-pixel MV (`build_mc_border` is only reached when the window leaves the +/// frame or the coded size is not a multiple of 8). Cropping the reference to +/// the visible size would drop exactly those samples. +#[derive(Clone)] +struct RefFrame { + planes: std::sync::Arc, + /// Coded width — the predictor's `y_crop_width`. + width: u16, + /// Coded height — the predictor's `y_crop_height`. + height: u16, } /// What `use_prev_frame_mvs` (decodeframe.c:3023) tests about the last frame. @@ -133,7 +172,10 @@ impl Decoder { last: LastFrameFacts::default(), iw: None, frames_seen: 0, + decode_index: 0, syntax_blocks: 0, + mc_scratch: Vec::new(), + mc_temp: vec![0; 64 * 135 + 64 * 64], } } @@ -160,7 +202,7 @@ impl Decoder { if hdr.show_existing_frame { let slot = hdr.frame_to_show_map_idx as usize; return match self.refs.get(slot).and_then(|p| p.as_ref()) { - Some(p) => Ok(Some(p.clone())), + Some(p) => Ok(Some(crop_picture(&p.planes, p.width, p.height))), None => Err(corrupt("show_existing_frame names an empty slot")), }; } @@ -179,13 +221,20 @@ impl Decoder { ), )); } - if hdr.frame_type != FrameType::Key { + // One index per decoded frame (the dumps' `frame=` field), so this + // path and `decode_syntax` label the same frame the same way. + let index = self.decode_index; + self.decode_index += 1; + if hdr.frame_type == FrameType::Key { + return self.decode_key_frame(&hdr, frame); + } + if hdr.intra_only { return Err(Error::unsupported( - "vp9 inter", - "this lane decodes keyframes only", + "vp9 intra-only", + "this lane decodes inter frames and keyframes only", )); } - self.decode_key_frame(&hdr, frame) + self.decode_inter_frame(&hdr, frame, index, true) } /// Decode one key frame through to pixels and refresh every slot. @@ -233,8 +282,13 @@ impl Decoder { self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.clone(); } // Reference refresh (spec 8.10): a keyframe updates all slots. + let frame = RefFrame { + planes: std::sync::Arc::new(self.planes.take().expect("frame scratch")), + width: hdr.width as u16, + height: hdr.height as u16, + }; for slot in self.refs.iter_mut() { - *slot = Some(pic.clone()); + *slot = Some(frame.clone()); } Ok(if hdr.show_frame { Some(pic) } else { None }) } @@ -267,16 +321,26 @@ impl Decoder { "the inter-syntax lane covers inter frames only", )); } else { - self.decode_inter_syntax_frame(&hdr, sub, index)?; + self.decode_inter_frame(&hdr, sub, index, false)?; } } Ok(()) } - /// Inter-frame syntax walk: compressed header, then every block's mode - /// info and MVs. Tokens are decoded to keep the entropy stream aligned; - /// nothing is predicted or reconstructed. - fn decode_inter_syntax_frame(&mut self, hdr: &FrameHeader, frame: &[u8], index: usize) -> Result<()> { + /// Inter-frame decode: compressed header, the tile walk (mode info, MVs + /// and tokens always; prediction, residual and the loop filter when + /// `pixels`), then the reference refresh. + /// + /// `pixels == false` is the syntax-only walk the instrumented harnesses + /// drive: tokens keep the entropy stream aligned, no pixel is touched and + /// the reference slots are left alone. + fn decode_inter_frame( + &mut self, + hdr: &FrameHeader, + frame: &[u8], + index: usize, + pixels: bool, + ) -> Result> { // Frame-context bookkeeping (spec 6.2 / libvpx `vp9_decode_frame`): // 3 resets every stored context, 2 resets the selected one; 1 means // "reset after this frame" and takes no action at frame start. @@ -288,6 +352,58 @@ impl Decoder { } self.ctx = self.frame_ctxs[hdr.frame_context_idx as usize].clone(); + // Reference slots (spec 7.2): `ref_frame_idx[i]` names the slot LAST, + // GOLDEN and ALTREF use. libvpx validates every named reference's + // format here (`vp9_decodeframe.c:1620-1627`) and SCALES a reference + // whose size differs; this lane refuses that by name. + if pixels { + for (i, name) in ["last", "golden", "altref"].iter().enumerate() { + let slot = hdr.ref_frame_idx[i] as usize; + if slot >= self.refs.len() || hdr.ref_frame_idx[i] >= 8 { + return Err(corrupt("vp9 inter names a reference slot past the DPB")); + } + let Some(p) = self.refs[slot].as_ref() else { + return Err(Error::corrupt(format!( + "vp9 inter reference `{name}` names empty slot {slot}" + ))); + }; + if p.width as u32 != hdr.width || p.height as u32 != hdr.height { + return Err(Error::unsupported( + "vp9 inter reference size change", + format!( + "reference `{name}` in slot {slot} is {}x{} but this frame is {}x{}; \ + reference-frame scaling is not ported", + p.width, p.height, hdr.width, hdr.height + ), + )); + } + } + if hdr.width % 2 != 0 || hdr.height % 2 != 0 { + return Err(Error::unsupported( + "vp9 inter odd frame dimensions", + format!( + "{}x{}: the reference chroma planes of an odd-sized frame are \ + stored at floor(w/2) but the predictor reads libvpx's \ + uv_crop_width = (w+1)/2", + hdr.width, hdr.height + ), + )); + } + let width = hdr.width as usize; + let height = hdr.height as usize; + let aw = width.div_ceil(64) * 64; + let ah = height.div_ceil(64) * 64; + self.planes = Some(Planes { + y: vec![128u8; aw * ah], + u: vec![128u8; aw / 2 * ah / 2], + v: vec![128u8; aw / 2 * ah / 2], + ys: aw, + uvs: aw / 2, + aw, + ah, + }); + } + let hdr_start = hdr.uncompressed_header_size as usize; if crate::trace_enabled() { eprintln!("CHSTART frame={index}"); @@ -368,15 +484,33 @@ impl Decoder { } } - // The loop-filter grids are never written on this path (no - // reconstruction), but the walk's signature carries them. + // The loop-filter grids are only written when pixels are built, but + // the walk's signature carries them. let mut grids = LfGrids { level8: vec![0; mi_cols * mi_rows], blk: vec![(0u8, 0u32, 0u32); mi_cols * mi_rows], otx: vec![0; mi_cols * mi_rows], + skip_inter: vec![false; mi_cols * mi_rows], mi_cols, mi_rows, }; + // `above_context` / `above_seg_context` and the mi grid are + // FRAME-scoped in libvpx (memset once per frame before the tile loop, + // `vp9_decodeframe.c:2079-2083`; indexed by absolute mi_row/mi_col by + // `set_skip_context`). Tile rows are disjoint in COLUMN only, so a + // tile row k > 0 reads above state written by tile row k - 1 — the + // same invariant the keyframe path documents. `above_context` is + // sized by `mi_cols_aligned_to_sb`: a TX_32X32 block indexes up to 8 + // 4x4 units past the last mi col. + let aligned_cols = mi_cols.div_ceil(SB_MI) * SB_MI; + let mut ectx = [ + PlaneContexts::new(aligned_cols * 2), + PlaneContexts::new(aligned_cols), + PlaneContexts::new(aligned_cols), + ]; + ectx.iter_mut().for_each(|p| p.above.fill(0)); + let mut mi = MiState::new(mi_cols, mi_rows); + mi.above_seg.fill(0); let mut ti = 0usize; for tr in 0..tile_rows { let row_lo = ((sb64_rows * tr) >> hdr.tile_info.rows_log2) * SB_MI; @@ -393,15 +527,10 @@ impl Decoder { } let mut r = crate::bool::BoolDecoder::new(tiles[ti])?; ti += 1; - let mut ectx = [ - PlaneContexts::new(mi_cols * 2), - PlaneContexts::new(mi_cols), - PlaneContexts::new(mi_cols), - ]; - let mut mi = MiState::new(mi_cols, mi_rows); - ectx.iter_mut().for_each(|p| p.above.fill(0)); - mi.above_seg.fill(0); for sb_row in (row_lo..row_hi).step_by(SB_MI) { + // Left entropy/partition contexts are zeroed at the start + // of every superblock row (the SB row's left edge has no + // neighbours); the above contexts stay frame-scoped. ectx.iter_mut().for_each(|p| p.left = [0; 32]); mi.left_seg = [0; 32]; for sb_col in (col_lo..col_hi).step_by(SB_MI) { @@ -417,6 +546,7 @@ impl Decoder { 4, col_lo, ch.tx_mode, + pixels, )?; } } @@ -454,7 +584,56 @@ impl Decoder { self.ctx.partition[13] ); } - Ok(()) + + if !pixels { + return Ok(None); + } + + // Loop filter post-pass: same extents as the keyframe path, but the + // per-cell level comes from the block's own reference and mode class + // (`get_filter_level`, vp9_loopfilter.c:249). + if hdr.loop_filter.level > 0 && std::env::var_os("EC_VP9_SKIP_LF").is_none() { + let p = self.planes.as_mut().expect("frame scratch"); + let (vw, vh) = (mi_cols * 8, mi_rows * 8); + grids.filter_frame( + &mut p.y, + p.ys, + &mut p.u, + &mut p.v, + p.uvs, + vw, + vh, + vh / 2, + hdr.loop_filter.sharpness, + ); + } + + let pic = self.take_picture(hdr); + let frame = RefFrame { + planes: std::sync::Arc::new(self.planes.take().expect("frame scratch")), + width: hdr.width as u16, + height: hdr.height as u16, + }; + + // Reference refresh (spec 8.10 / `swap_frame_buffers`): bit i of + // `refresh_frame_flags` replaces slot i with the frame just decoded — + // the LOOP-FILTERED frame, which is what a later frame's prediction + // reads. + for slot in 0..8 { + if hdr.refresh_frame_flags & (1 << slot) != 0 { + self.refs[slot] = Some(frame.clone()); + } + } + Ok(if hdr.show_frame { Some(pic) } else { None }) + } + + /// Crop the frame scratch to a [`Picture`]. + fn take_picture(&self, hdr: &FrameHeader) -> Picture { + crop_picture( + self.planes.as_ref().expect("frame scratch"), + hdr.width as u16, + hdr.height as u16, + ) } /// One inter block's syntax (`read_inter_frame_mode_info` + the MV field @@ -488,7 +667,7 @@ impl Decoder { ifs: w.ifs, sign_bias: w.sign_bias, allow_hp: hdr.allow_high_precision_mv, - frame_interp: hdr.interpolation_filter as u8, + frame_interp: interp_filter_of(hdr), tx_mode, mi_rows: mi.mi_rows, mi_cols: mi.mi_cols, @@ -563,35 +742,182 @@ impl Decoder { bw: usize, bh: usize, ) -> Result<()> { - let n4w = if sb_type < 3 { - [2, 1, 1] - } else { - [bw * 2, bw, bw] - }; - let n4h = if sb_type < 3 { - [2, 1, 1] + let n4w = plane_n4_w(sb_type, bw); + let n4h = plane_n4_h(sb_type, bh); + if info.skip { + // dec_reset_skip_context + reset_skip_context(ectx, row, col, sb_type, n4w, n4h); + return Ok(()); + } + let mb_to_right = ((mi.mi_cols as isize - bw as isize - col as isize) * 64) as i32; + let mb_to_bottom = ((mi.mi_rows as isize - bh as isize - row as isize) * 64) as i32; + for plane in 0..3usize { + let s = usize::from(plane != 0); + let tx_size = if plane == 0 { + info.tx_size + } else { + get_uv_tx_size(info.tx_size, sb_type) + }; + let step = 1usize << tx_size; + let max_blocks_wide = + (n4w[plane] as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize; + let max_blocks_high = + (n4h[plane] as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize; + for brow in (0..max_blocks_high).step_by(step) { + for bcol in (0..max_blocks_wide).step_by(step) { + let _ = decode_inter_tx_tokens( + r, + ectx, + hdr, + info, + &self.ctx, + plane, + row, + col, + brow, + bcol, + tx_size, + sb_type, + bw, + bh, + mb_to_right, + mb_to_bottom, + ); + } + } + } + Ok(()) + } + + /// `decode_block`'s inter arm with pixels (`vp9_decodeframe.c:990-1044`): + /// `dec_build_inter_predictors_sb` for the whole block, then + /// `reconstruct_inter_block` per transform block. Intra blocks inside an + /// inter frame take the intra path (`:964-989`). + #[allow(clippy::too_many_arguments)] + fn reconstruct_inter_pixels( + &mut self, + r: &mut crate::bool::BoolDecoder, + ectx: &mut [PlaneContexts; 3], + grids: &mut LfGrids, + hdr: &FrameHeader, + info: &MiInfo, + row: usize, + col: usize, + sb_type: usize, + bw: usize, + bh: usize, + mi: &mut MiState, + tile_col_start: usize, + ) -> Result<()> { + let x_mis = bw.min(mi.mi_cols - col); + let y_mis = bh.min(mi.mi_rows - row); + let n4w = plane_n4_w(sb_type, bw); + let n4h = plane_n4_h(sb_type, bh); + let mb_to_right = ((mi.mi_cols as isize - bw as isize - col as isize) * 64) as i32; + let mb_to_bottom = ((mi.mi_rows as isize - bh as isize - row as isize) * 64) as i32; + + // `get_filter_level` (vp9_loopfilter.c:249): + // `lvl[segment_id][mi->ref_frame[0]][mode_lf_lut[mi->mode]]`, with + // `lvl` built by `vp9_loop_filter_frame_init` from the frame level, + // the per-reference deltas and the per-mode-class deltas. + let levels = hdr.loop_filter_levels(info.segment as usize); + let ref0 = if info.is_inter { + info.ref_frame[0].clamp(0, 3) as usize } else { - [bh * 2, bh, bh] + // An intra block inside an inter frame: `mi->ref_frame[0]` is + // INTRA_FRAME and its mode is an intra mode, so the mode class is + // 0 and the reference slot is intra's. + 0 }; + let level = levels[ref0][mode_lf_lut(info.mode)]; + for dy in 0..y_mis { + for dx in 0..x_mis { + let cell = (row + dy) * mi.mi_cols + col + dx; + grids.level8[cell] = level; + grids.blk[cell] = (sb_type as u8, row as u32, col as u32); + grids.otx[cell] = if sb_type < 3 { + TX_4X4 as u8 + } else { + info.tx_size as u8 + }; + // `build_masks`'s early return is gated on + // `mi->skip && is_inter_block(mi)` — a skipped inter block + // keeps ONLY the above/left prediction masks. + grids.skip_inter[cell] = info.is_inter && info.skip; + } + } + + // `if (mi->skip) dec_reset_skip_context(xd);` — libvpx does this at the + // top of `decode_block` (decodeframe.c:960), BEFORE the intra/inter + // split, so skipped intra blocks inside an inter frame reset too. if info.skip { - // dec_reset_skip_context + reset_skip_context(ectx, row, col, sb_type, n4w, n4h); + } + + if !info.is_inter { + // `predict_and_reconstruct_intra_block` per transform block. for plane in 0..3usize { let s = usize::from(plane != 0); - let offx = (col << 1) >> s; - let offy = (row << 1) >> s; - for i in 0..n4w[plane] { - ectx[plane].above[offx + i] = 0; - } - let lrows = 32usize >> s; - for i in 0..n4h[plane].min(lrows) { - ectx[plane].left[(offy + i) % lrows] = 0; + let tx_size = if plane == 0 { + info.tx_size + } else { + get_uv_tx_size(info.tx_size, sb_type) + }; + let step = 1usize << tx_size; + let max_blocks_wide = + (n4w[plane] as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize; + let max_blocks_high = + (n4h[plane] as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize; + for brow in (0..max_blocks_high).step_by(step) { + for bcol in (0..max_blocks_wide).step_by(step) { + self.predict_and_reconstruct( + r, + ectx, + hdr, + info, + plane, + row, + col, + brow, + bcol, + tx_size, + sb_type, + bw, + bh, + mb_to_right, + mb_to_bottom, + // Intra prediction's left availability is + // tile-scoped (`tile->mi_col_start`), which the + // inter walk passes as the tile's first mi col. + tile_col_start, + )?; + } } } return Ok(()); } - let mb_to_right = ((mi.mi_cols as isize - bw as isize - col as isize) * 64) as i32; - let mb_to_bottom = ((mi.mi_rows as isize - bh as isize - row as isize) * 64) as i32; - let lossless = hdr.quantization.lossless(); + + // Prediction: `dec_build_inter_predictors_sb`, every reference, every + // plane, before any token is read. + { + let planes = self.planes.as_mut().expect("frame scratch"); + let refs = &self.refs; + let scratch = &mut self.mc_scratch; + let temp = &mut self.mc_temp; + for plane in 0..3usize { + inter_predict_plane( + planes, refs, scratch, temp, hdr, info, plane, row, col, &n4w, &n4h, + mb_to_right, mb_to_bottom, sb_type, + )?; + } + } + + if info.skip { + return Ok(()); + } + + // Reconstruction: `reconstruct_inter_block` per transform block. + let mut eobtotal = 0usize; for plane in 0..3usize { let s = usize::from(plane != 0); let tx_size = if plane == 0 { @@ -606,62 +932,56 @@ impl Decoder { (n4h[plane] as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize; for brow in (0..max_blocks_high).step_by(step) { for bcol in (0..max_blocks_wide).step_by(step) { - let tx_type = if plane != 0 || lossless || info.is_inter { - DCT_DCT - } else { - MODE_TO_TXTYPE_LOOKUP[info.mode as usize] as usize - }; - let (scan, nb) = scan_for(tx_size, tx_type); - let q = hdr.segment_dequant(info.segment as usize); - let dequant: [i16; 2] = if plane == 0 { - [q.luma_dc, q.luma_ac] - } else { - [q.chroma_dc, q.chroma_ac] - }; - let ptype = usize::from(plane != 0); - let ax = ((col << 1) >> s) + bcol; - let lrows = 32usize >> s; - let ay = (((row << 1) >> s) + brow) % lrows; - let nblocks = 1usize << tx_size; - let ctx_in = usize::from(ectx[plane].above[ax..ax + nblocks].iter().any(|&v| v != 0)) - + usize::from(ectx[plane].left[ay..ay + nblocks].iter().any(|&v| v != 0)); - let coef = decode_coefs( + let coef = decode_inter_tx_tokens( r, - ptype, - tx_size, - &dequant, - ctx_in, - scan, - nb, - &self.ctx.coef[tx_size], - info.is_inter, - (0, 0), + ectx, + hdr, + info, + &self.ctx, plane, + row, + col, + brow, + bcol, + tx_size, + sb_type, + bw, + bh, + mb_to_right, + mb_to_bottom, ); - // vp9_decode_block_tokens context write-back. - let n4w_s = bw * 2 >> s; - let n4h_s = bh * 2 >> s; - let maxw = - (n4w_s as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize; - let maxh = - (n4h_s as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize; - let eob_pos = u64::from(coef.eob > 0); - let shift_a = if maxw > 0 && nblocks + bcol > maxw { - (nblocks - (maxw - bcol)) * 8 - } else { - 0 - }; - let shift_l = if maxh > 0 && nblocks + brow > maxh { - (nblocks - (maxh - brow)) * 8 - } else { - 0 - }; - let spread_a = (eob_pos * 0x0101_0101_0101_0101) >> shift_a; - let spread_l = (eob_pos * 0x0101_0101_0101_0101) >> shift_l; - for k in 0..nblocks { - ectx[plane].above[ax + k] = (spread_a >> (8 * k)) as u8; - ectx[plane].left[ay + k] = (spread_l >> (8 * k)) as u8; + eobtotal += coef.eob; + if coef.eob == 0 { + continue; } + // `inverse_transform_block_inter`: inter blocks always use + // the DEFAULT scan and DCT_DCT (`reconstruct_inter_block`, + // decodeframe.c:413). + let planes = self.planes.as_mut().expect("frame scratch"); + let stride = planes.dims(plane).0; + let x0 = ((col * 8) >> s) + bcol * 4; + let y0 = ((row * 8) >> s) + brow * 4; + let dst_off = y0 * stride + x0; + let (data, _) = planes.plane(plane); + inverse_transform_add( + tx_size, + DCT_DCT, + &coef.coeffs, + data, + dst_off, + stride, + hdr.quantization.lossless(), + ); + } + } + } + + // `if (!less8x8 && eobtotal == 0) mi->skip = 1; // skip loopfilter` + // (decodeframe.c:1043). + if sb_type >= 3 && eobtotal == 0 { + for dy in 0..y_mis { + for dx in 0..x_mis { + grids.skip_inter[(row + dy) * mi.mi_cols + col + dx] = true; } } } @@ -695,9 +1015,7 @@ impl Decoder { hdr.uncompressed_header_size as usize + hdr.header_size_in_bytes as usize }); let tail: Vec = frame[tail_start..].to_vec(); - let res = self.decode_keyframe_inner(hdr, tx_mode, &tail); - self.planes = None; - res + self.decode_keyframe_inner(hdr, tx_mode, &tail) } fn decode_keyframe_inner( @@ -706,8 +1024,6 @@ impl Decoder { tx_mode: u8, tail: &[u8], ) -> Result { - let width = hdr.width as usize; - let height = hdr.height as usize; let mi_cols = hdr.mi_cols() as usize; let mi_rows = hdr.mi_rows() as usize; let sb64_cols = mi_cols.div_ceil(SB_MI); @@ -747,6 +1063,7 @@ impl Decoder { level8: vec![0; mi_cols * mi_rows], blk: vec![(0u8, 0u32, 0u32); mi_cols * mi_rows], otx: vec![0; mi_cols * mi_rows], + skip_inter: vec![false; mi_cols * mi_rows], mi_cols, mi_rows, }; @@ -819,6 +1136,7 @@ impl Decoder { 4, col_lo, tx_mode, + true, )?; } } @@ -845,25 +1163,7 @@ impl Decoder { ); } - let crop = |src: &[u8], stride: usize, w: usize, h: usize| -> Vec { - let mut out = Vec::with_capacity(w * h); - for row in 0..h { - out.extend_from_slice(&src[row * stride..row * stride + w]); - } - out - }; - let planes = self.planes.as_ref().expect("frame scratch"); - Ok(Picture { - y: crop(&planes.y, planes.ys, width, height), - u: crop(&planes.u, planes.uvs, width / 2, height / 2), - v: crop(&planes.v, planes.uvs, width / 2, height / 2), - width: width as u16, - height: height as u16, - // The crop above packs rows: `stride` describes the RETURNED - // buffers, not the aligned decode buffer (`aw`). - stride: width, - uv_stride: width / 2, - }) + Ok(self.take_picture(hdr)) } /// `decode_partition` (decodeframe.c:1173). @@ -881,6 +1181,10 @@ impl Decoder { n4: usize, tile_col_start: usize, tx_mode: u8, + // Whether this walk reconstructs pixels. Consulted by the inter + // branch only: a keyframe always reconstructs its intra blocks, and + // the syntax-only inter walk parses tokens without predicting. + pixels: bool, ) -> Result<()> { if row >= mi.mi_rows || col >= mi.mi_cols { return Ok(()); @@ -924,6 +1228,7 @@ impl Decoder { 1, tile_col_start, tx_mode, + pixels, )?; } else { match partition { @@ -941,6 +1246,7 @@ impl Decoder { n4, tile_col_start, tx_mode, + pixels, )?, 1 => { self.decode_block( @@ -957,6 +1263,7 @@ impl Decoder { n8, tile_col_start, tx_mode, + pixels, )?; if has_rows { self.decode_block( @@ -973,6 +1280,7 @@ impl Decoder { n8, tile_col_start, tx_mode, + pixels, )?; } } @@ -991,6 +1299,7 @@ impl Decoder { n4, tile_col_start, tx_mode, + pixels, )?; if has_cols { self.decode_block( @@ -1007,6 +1316,7 @@ impl Decoder { n4, tile_col_start, tx_mode, + pixels, )?; } } @@ -1029,6 +1339,7 @@ impl Decoder { n8, tile_col_start, tx_mode, + pixels, )?; } } @@ -1057,6 +1368,7 @@ impl Decoder { bhl: usize, tile_col_start: usize, tx_mode: u8, + pixels: bool, ) -> Result<()> { let bw = 1 << (bwl - 1); let bh = 1 << (bhl - 1); @@ -1093,9 +1405,20 @@ impl Decoder { )? }; if hdr.frame_type != FrameType::Key { - // Inter syntax only: tokens keep the entropy stream aligned, the - // block lands in the mode grid, and no pixel is touched. - self.decode_inter_block_tokens(r, mi, ectx, hdr, &info, row, col, sb_type, bw, bh)?; + if pixels { + // Full inter decode: prediction, tokens, residual. The + // per-cell loop-filter level is the block's own reference and + // mode class (`get_filter_level`), so the grids are written + // inside the reconstruction rather than from `level_of_seg`. + self.reconstruct_inter_pixels( + r, ectx, grids, hdr, &info, row, col, sb_type, bw, bh, mi, + tile_col_start, + )?; + } else { + // Inter syntax only: tokens keep the entropy stream aligned, + // the block lands in the mode grid, and no pixel is touched. + self.decode_inter_block_tokens(r, mi, ectx, hdr, &info, row, col, sb_type, bw, bh)?; + } for dy in 0..y_mis { for dx in 0..x_mis { if crate::mvdbg2_enabled() @@ -1464,3 +1787,311 @@ fn bsize_of_n4(n4: usize) -> usize { _ => 0, // BLOCK_4X4 (recursion never reaches n4 == 0) } } + +/// Crop an aligned plane set to a displayable [`Picture`]: rows are packed to +/// the visible width, so `stride` describes the RETURNED buffers, not the +/// aligned decode buffer. +fn crop_picture(planes: &Planes, width: u16, height: u16) -> Picture { + let (w, h) = (width as usize, height as usize); + let crop = |src: &[u8], stride: usize, cw: usize, ch: usize| -> Vec { + let mut out = Vec::with_capacity(cw * ch); + for row in 0..ch { + out.extend_from_slice(&src[row * stride..row * stride + cw]); + } + out + }; + Picture { + y: crop(&planes.y, planes.ys, w, h), + u: crop(&planes.u, planes.uvs, w / 2, h / 2), + v: crop(&planes.v, planes.uvs, w / 2, h / 2), + width, + height, + stride: w, + uv_stride: w / 2, + } +} + +/// `pd->n4_w` (`set_plane_n4`, decodeframe.c:809): the plane block's width in +/// its own 4x4 units. Sub-8x8 shapes occupy a whole 8x8 mi cell +/// (`set_plane_n4(xd, bw=1, bh=1)`) so luma walks 2x2 and chroma 1x1. +fn plane_n4_w(sb_type: usize, bw: usize) -> [usize; 3] { + if sb_type < 3 { + [2, 1, 1] + } else { + [bw * 2, bw, bw] + } +} + +/// `pd->n4_h`, the height twin of [`plane_n4_w`]. +fn plane_n4_h(sb_type: usize, bh: usize) -> [usize; 3] { + if sb_type < 3 { + [2, 1, 1] + } else { + [bh * 2, bh, bh] + } +} + +/// `dec_reset_skip_context` (`vp9_decodeframe.c:800`). +fn reset_skip_context( + ectx: &mut [PlaneContexts; 3], + row: usize, + col: usize, + sb_type: usize, + n4w: [usize; 3], + n4h: [usize; 3], +) { + let _ = sb_type; + for plane in 0..3usize { + let s = usize::from(plane != 0); + let offx = (col << 1) >> s; + let offy = (row << 1) >> s; + for i in 0..n4w[plane] { + ectx[plane].above[offx + i] = 0; + } + let lrows = 32usize >> s; + for i in 0..n4h[plane].min(lrows) { + ectx[plane].left[(offy + i) % lrows] = 0; + } + } +} + +/// `mode_lf_lut` (`vp9/common/vp9_loopfilter.c:223`): +/// `{0 × INTRA_MODES, 1, 1, 0, 1}` — NEARESTMV, NEARMV and NEWMV take the +/// inter mode delta, ZEROMV does not, and intra modes never do. +fn mode_lf_lut(mode: u8) -> usize { + match mode { + 10 | 11 | 13 => 1, + _ => 0, + } +} + +/// One inter transform block's tokens plus the context write-back +/// (`vp9_decode_block_tokens`, `decodeframe.c:414`). Inter blocks always use +/// the DEFAULT scan and `DCT_DCT`. +#[allow(clippy::too_many_arguments)] +fn decode_inter_tx_tokens( + r: &mut crate::bool::BoolDecoder, + ectx: &mut [PlaneContexts; 3], + hdr: &FrameHeader, + info: &MiInfo, + fc: &FrameContext, + plane: usize, + row: usize, + col: usize, + brow: usize, + bcol: usize, + tx_size: usize, + sb_type: usize, + bw: usize, + bh: usize, + mb_to_right: i32, + mb_to_bottom: i32, +) -> crate::tokens::CoeffBlock { + let s = usize::from(plane != 0); + // `predict_and_reconstruct_intra_block` (decodeframe.c:320-345): the luma + // mode of a sub-8x8 block is the SUB-BLOCK's, and an intra block inside an + // inter frame picks its tx type from that mode — `reconstruct_inter_block` + // hard-codes DCT_DCT instead, which is why the inter guard is here. + let tx_type = if plane != 0 || hdr.quantization.lossless() || info.is_inter { + DCT_DCT + } else { + let mode = if sb_type < 3 { + info.bmi[(brow << 1) + bcol] + } else { + info.mode + }; + MODE_TO_TXTYPE_LOOKUP[mode as usize] as usize + }; + let (scan, nb) = scan_for(tx_size, tx_type); + let q = hdr.segment_dequant(info.segment as usize); + let dequant: [i16; 2] = if plane == 0 { + [q.luma_dc, q.luma_ac] + } else { + [q.chroma_dc, q.chroma_ac] + }; + let ptype = usize::from(plane != 0); + let ax = ((col << 1) >> s) + bcol; + let lrows = 32usize >> s; + let ay = (((row << 1) >> s) + brow) % lrows; + let nblocks = 1usize << tx_size; + let ctx_in = usize::from(ectx[plane].above[ax..ax + nblocks].iter().any(|&v| v != 0)) + + usize::from(ectx[plane].left[ay..ay + nblocks].iter().any(|&v| v != 0)); + if crate::tokdbg_enabled() { + eprintln!( + "TDB row={row} col={col} plane={plane} brow={brow} bcol={bcol} tx={tx_size} sbt={sb_type} ptype={ptype} inter={} mode={} tt={tx_type} ax={ax} ay={ay} cin={ctx_in} a={:?} l={:?}", + u8::from(info.is_inter), + info.mode, + &ectx[plane].above[ax..ax + nblocks], + &ectx[plane].left[ay..ay + nblocks], + ); + } + let coef = decode_coefs( + r, + ptype, + tx_size, + &dequant, + ctx_in, + scan, + nb, + &fc.coef[tx_size], + info.is_inter, + (0, 0), + plane, + ); + // vp9_decode_block_tokens context write-back (v1.15 edge shifts). + let n4w_s = bw * 2 >> s; + let n4h_s = bh * 2 >> s; + let maxw = (n4w_s as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize; + let maxh = (n4h_s as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize; + let eob_pos = u64::from(coef.eob > 0); + let shift_a = if maxw > 0 && nblocks + bcol > maxw { + (nblocks - (maxw - bcol)) * 8 + } else { + 0 + }; + let shift_l = if maxh > 0 && nblocks + brow > maxh { + (nblocks - (maxh - brow)) * 8 + } else { + 0 + }; + let spread_a = (eob_pos * 0x0101_0101_0101_0101) >> shift_a; + let spread_l = (eob_pos * 0x0101_0101_0101_0101) >> shift_l; + for k in 0..nblocks { + ectx[plane].above[ax + k] = (spread_a >> (8 * k)) as u8; + ectx[plane].left[ay + k] = (spread_l >> (8 * k)) as u8; + } + coef +} + +/// `dec_build_inter_predictors_sb` (`vp9_decodeframe.c:731`) for one plane: +/// every reference's prediction for one block, in reference order (compound +/// blocks average the second into the first). +#[allow(clippy::too_many_arguments)] +fn inter_predict_plane( + planes: &mut Planes, + refs: &[Option; 8], + scratch: &mut Vec, + temp: &mut Vec, + hdr: &FrameHeader, + info: &MiInfo, + plane: usize, + row: usize, + col: usize, + n4w: &[usize; 3], + n4h: &[usize; 3], + mb_to_right: i32, + mb_to_bottom: i32, + sb_type: usize, +) -> Result<()> { + let s = usize::from(plane != 0); + let ss_x = s; + let ss_y = s; + let pw = n4w[plane] * 4; + let ph = n4h[plane] * 4; + let mb_left = -((col as i32) * 64); + let mb_top = -((row as i32) * 64); + let is_compound = info.ref_frame[1] > crate::inter::INTRA_FRAME; + let refs_used = 1 + usize::from(is_compound); + let kernel = usize::from(info.interp_filter); + let dst_stride = planes.dims(plane).0; + for rf in 0..refs_used { + let ref_name = info.ref_frame[rf]; + let slot = hdr.ref_frame_idx[(ref_name - 1) as usize] as usize; + let Some(ref_frame) = refs[slot].as_ref() else { + return Err(corrupt("vp9 inter prediction read an empty reference slot")); + }; + let (ref_data, ref_stride) = ref_frame.planes.plane_ref(plane); + let refp = RefPlane { + data: ref_data, + stride: ref_stride, + width: (ref_frame.width as usize) >> s, + height: (ref_frame.height as usize) >> s, + }; + if sb_type < 3 { + // libvpx builds one 4x4 prediction per sub-block, with the MV from + // `average_split_mvs` (luma: the sub-block's own MV; 4:2:0 chroma: + // the q4-rounded average of the four). + let n4x = n4w[plane]; + let n4y = n4h[plane]; + for y in 0..n4y { + for xx in 0..n4x { + let i = y * n4x + xx; + let mv = if plane == 0 { + split_mv(&info.bmi_mv, i, rf) + } else { + average_split_mvs_chroma(&info.bmi_mv, rf) + }; + let (data, _) = planes.plane(plane); + let dst_off = (((row * 8) >> s) + y * 4) * dst_stride + + ((col * 8) >> s) + + xx * 4; + build_inter_predictors( + &mut data[dst_off..], + dst_stride, + &refp, + col, + row, + xx * 4, + y * 4, + 4, + 4, + mv, + mb_left, + mb_to_right, + mb_top, + mb_to_bottom, + ss_x, + ss_y, + kernel, + rf == 1, + scratch, + temp, + ); + } + } + } else { + let (data, _) = planes.plane(plane); + let dst_off = ((row * 8) >> s) * dst_stride + ((col * 8) >> s); + build_inter_predictors( + &mut data[dst_off..], + dst_stride, + &refp, + col, + row, + 0, + 0, + pw, + ph, + info.mv[rf], + mb_left, + mb_to_right, + mb_top, + mb_to_bottom, + ss_x, + ss_y, + kernel, + rf == 1, + scratch, + temp, + ); + } + } + Ok(()) +} + +/// `read_interp_filter` (`vp9_decodeframe.c:1482`): the header's filter is a +/// literal index through `literal_to_filter[] = {EIGHTTAP_SMOOTH, EIGHTTAP, +/// EIGHTTAP_SHARP, BILINEAR}` — the spec's literal order is NOT libvpx's +/// filter numbering (`#define EIGHTTAP 0`, `EIGHTTAP_SMOOTH 1`, +/// `EIGHTTAP_SHARP 2`, `BILINEAR 3`), and `vp9_filter_kernels` (the kernel +/// table) is indexed by the latter. A switchable frame stores SWITCHABLE (4) +/// and picks per block, where the tree's leaves already use libvpx numbering. +fn interp_filter_of(hdr: &FrameHeader) -> u8 { + const LITERAL_TO_FILTER: [u8; 4] = [1, 0, 2, 3]; + let v = hdr.interpolation_filter as u8; + if v == crate::inter::SWITCHABLE { + v + } else { + LITERAL_TO_FILTER[v as usize] + } +} diff --git a/crates/ec-vp9/src/inter.rs b/crates/ec-vp9/src/inter.rs index 4a1e535c..34f36c76 100644 --- a/crates/ec-vp9/src/inter.rs +++ b/crates/ec-vp9/src/inter.rs @@ -670,6 +670,13 @@ fn find_mv_refs( &mut count, early_break, ); + // The C macro's successful second add is `goto Done` + // (vp9_decodemv.c:475-480), which leaves the search + // loop; without this break the next candidate would + // write `mv_ref_list[2]` past the two-entry list. + if done { + break; + } } } } diff --git a/crates/ec-vp9/src/lib.rs b/crates/ec-vp9/src/lib.rs index 8d3f9771..64cb45f9 100644 --- a/crates/ec-vp9/src/lib.rs +++ b/crates/ec-vp9/src/lib.rs @@ -1,11 +1,12 @@ -//! Native VP9 (profile 0, 8-bit 4:2:0 keyframes) decoder. +//! Native VP9 (profile 0, 8-bit 4:2:0) decoder. //! //! The crate implements the VP9 bitstream specification directly //! ([spec]); libvpx's output is used only as a test oracle //! (sample-exactness witnesses against ffmpeg's libvpx-based decoder), //! never as code linked at runtime. Every module documents the spec -//! section it implements. Inter-frame prediction is refused by name; -//! this lane is keyframes only. +//! section it implements. Inter frames decode through motion compensation, +//! residual reconstruction and the loop filter; intra-only frames, other +//! profiles and other subsamplings are refused by name. //! //! [spec]: https://www.webmproject.org/docs/vp9/ //! @@ -22,6 +23,7 @@ pub mod header; pub(crate) mod inter; pub mod intra; pub mod loopfilter; +pub(crate) mod mc; pub mod modes; pub mod stream; pub mod tables; @@ -78,3 +80,6 @@ cached_gate!(interdump_enabled, "EC_VP9_INTERDUMP"); cached_gate!(mvdbg_enabled, "EC_VP9_MVDGB"); cached_gate!(mvdbg2_enabled, "EC_VP9_MVDGB2"); cached_gate!(mvdump_enabled, "EC_VP9_MVDUMP"); +// [scratch] per-transform-block token state (the inter pixel lane). +cached_gate!(tokdbg_enabled, "EC_VP9_TOKDGB"); +cached_gate!(lfmasksy_enabled, "EC_VP9_LFMASKSY"); diff --git a/crates/ec-vp9/src/loopfilter.rs b/crates/ec-vp9/src/loopfilter.rs index b85864e5..be052298 100644 --- a/crates/ec-vp9/src/loopfilter.rs +++ b/crates/ec-vp9/src/loopfilter.rs @@ -20,6 +20,26 @@ use crate::tables::*; +/// `LFTRACE` gate, optionally limited to one frame by `EC_VP9_LF_FRAME` +/// (the n-th `filter_frame` call of the process — the decode order's frame +/// index). The oracle's own LF trace is gated the same way, which is what lets +/// the two edge lists be diffed per frame. +fn lftrace_on() -> bool { + use std::sync::atomic::{AtomicUsize, Ordering}; + if std::env::var_os("LFTRACE").is_none() { + return false; + } + static CALLS: AtomicUsize = AtomicUsize::new(0); + let n = CALLS.fetch_add(1, Ordering::Relaxed); + match std::env::var("EC_VP9_LF_FRAME") + .ok() + .and_then(|v| v.parse::().ok()) + { + Some(f) => f == n, + None => true, + } +} + /// `vp9_loopfilter.c` UV mask tables (BLOCK_SIZES indexed 4X4..64X64). const UV_LEFT_PRED: [u16; 13] = [ 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0011, 0x0001, 0x0011, 0x1111, 0x0011, @@ -305,6 +325,13 @@ pub(crate) struct LfGrids { pub blk: Vec<(u8, u32, u32)>, /// Per-8x8 BLOCK-level tx size (sub-8x8 blocks record TX_4X4). pub otx: Vec, + /// Per-8x8 `mi->skip && is_inter_block(mi)` AFTER libvpx's promotion + /// (`decodeframe.c:1043`: `if (!less8x8 && eobtotal == 0) mi->skip = 1`). + /// Both mask builders return right after the prediction masks when this + /// is set, so a skipped inter block keeps only its block-edge (prediction) + /// masks. Keyframes never set it (`is_inter_block` is false); `false` is + /// the correct value there. + pub skip_inter: Vec, pub mi_cols: usize, pub mi_rows: usize, } @@ -342,6 +369,9 @@ impl LfGrids { let sh = (c & 7) + ((r & 7) << 3); left[tx] |= LUMA_LEFT_PRED[b] << sh; above[tx] |= LUMA_ABOVE_PRED[b] << sh; + if self.skip_inter[cell] { + return; + } left[tx] |= (LUMA_SIZE_MASK[b] & LUMA_LEFT_TXF[tx]) << sh; above[tx] |= (LUMA_SIZE_MASK[b] & LUMA_ABOVE_TXF[tx]) << sh; if tx == TX_4X4 { @@ -496,6 +526,24 @@ impl LfGrids { left[i] &= 0xfefefefefefefefe; } } + // [scratch] EC_VP9_LFMASKSY: per-superblock luma masks after + // `vp9_adjust_mask`, in the oracle's `LFMASKSY` field order. + if crate::lfmasksy_enabled() { + eprintln!( + "LFY {} {} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x} {:016x}", + sbr, + sbc, + left[TX_4X4], + left[TX_8X8], + left[TX_16X16], + left[TX_32X32], + above[TX_4X4], + above[TX_8X8], + above[TX_16X16], + above[TX_32X32], + int4 + ); + } (left, above, int4) } @@ -529,6 +577,7 @@ impl LfGrids { uv_h: usize, sharpness: u8, ) { + let lftrace = lftrace_on(); // Luma masks, ported from vp9_setup_mask/build_masks and // vp9_adjust_mask (bit i = MI row i>>3, MI col i&7; each bit // covers an 8x8 cell). Edges are emitted from the masks. @@ -570,7 +619,7 @@ impl LfGrids { t = 8; } lpf_edge(y, yy * stride + xx, stride, 1, t, bl, li, th, 8); - if std::env::var_os("LFTRACE").is_some() { + if lftrace { let kind = match t { 16 => "V16", 8 => "V8", @@ -581,7 +630,7 @@ impl LfGrids { } if int4 & bit != 0 && xx + 8 <= y_w && yy + 8 <= y_h { lpf_edge(y, yy * stride + xx + 4, stride, 1, 4, bl, li, th, 8); - if std::env::var_os("LFTRACE").is_some() { + if lftrace { eprintln!("V4I {} {}", xx + 4, yy); } } @@ -619,7 +668,7 @@ impl LfGrids { t = 8; } lpf_edge(y, yy * stride + xx, stride, 0, t, bl, li, th, 8); - if std::env::var_os("LFTRACE").is_some() { + if lftrace { let kind = match t { 16 => "H16", 8 => "H8", @@ -637,7 +686,7 @@ impl LfGrids { // vp9_loopfilter.c:1382) and in non420 under `ss_y`. if int4 & bit != 0 && yy + 8 <= y_h && xx + 8 <= y_w { lpf_edge(y, (yy + 4) * stride + xx, stride, 0, 4, bl, li, th, 8); - if std::env::var_os("LFTRACE").is_some() { + if lftrace { eprintln!("H4I {} {}", xx, yy + 4); } } @@ -678,8 +727,11 @@ impl LfGrids { let shift = (((r & 7) >> 1) << 2) + ((c & 7) >> 1); let b = bsize as usize; left[uv_tx] |= UV_LEFT_PRED[b] << shift; - left[uv_tx] |= (UV_SIZE_MASK[b] & UV_LEFT_TX[uv_tx]) << shift; above[uv_tx] |= UV_ABOVE_PRED[b] << shift; + if self.skip_inter[cell] { + continue; + } + left[uv_tx] |= (UV_SIZE_MASK[b] & UV_LEFT_TX[uv_tx]) << shift; above[uv_tx] |= (UV_SIZE_MASK[b] & UV_ABOVE_TX[uv_tx]) << shift; if uv_tx == TX_4X4 { int4 |= UV_SIZE_MASK[b] << shift; @@ -893,6 +945,8 @@ mod tests { level8: vec![level; mi_cols * mi_rows], blk: vec![(0u8, 0, 0); mi_cols * mi_rows], // 0 == BLOCK_4X4 otx: vec![TX_4X4 as u8; mi_cols * mi_rows], + // Keyframe-shaped fixture: no inter block, so no skip promotion. + skip_inter: vec![false; mi_cols * mi_rows], mi_cols, mi_rows, } diff --git a/crates/ec-vp9/src/mc.rs b/crates/ec-vp9/src/mc.rs new file mode 100644 index 00000000..f38335ab --- /dev/null +++ b/crates/ec-vp9/src/mc.rs @@ -0,0 +1,558 @@ +//! Motion compensation: the decoder's inter predictor (`dec_build_inter_predictors`, +//! libvpx `vp9/decoder/vp9_decodeframe.c:593`), the on-the-fly reference border +//! extension (`build_mc_border`, :473), the UMV-border MV clamp +//! (`clamp_mv_to_umv_border_sb`, `vp9/common/vp9_reconinter.c:88`), the +//! switchable filter kernels (`vp9/common/vp9_filter.c`) and the sub-pixel +//! convolve (`vpx_dsp/vpx_convolve.c`). +//! +//! The VP9 decoder does NOT extend the reference frame's borders in place: it +//! builds a bordered copy of the block's reference window per prediction +//! (`extend_and_predict`) whenever the window leaves the frame or the frame's +//! dimensions are not a multiple of 8. This module ports that path, unscaled +//! only — a reference slot whose size differs from the current frame is +//! refused by `decode` before any predictor runs. +//! +//! Indexing note: libvpx's convolve helpers take a raw pointer and subtract +//! `SUBPEL_TAPS / 2 - 1` from it, so they read taps *before* the block's first +//! sample. Rust slices cannot go negative, so every helper here takes a buffer +//! plus an `origin` (the block's first sample) and indexes with `isize`. + +/// `SUBPEL_BITS` / `SUBPEL_MASK` / `SUBPEL_SHIFTS` / `SUBPEL_TAPS` +/// (`vpx_dsp/vpx_filter.h:23-26`). +const SUBPEL_BITS: i32 = 4; +const SUBPEL_MASK: i32 = (1 << SUBPEL_BITS) - 1; +const SUBPEL_SHIFTS: i32 = 1 << SUBPEL_BITS; +const TAPS: usize = 8; +/// `FILTER_BITS` (`vpx_dsp/vpx_filter.h:21`). +const FILTER_BITS: i32 = 7; +/// `VP9_INTERP_EXTEND` (`vpx_scale/yv12config.h:25`). +const INTERP_EXTEND: i32 = 4; + +/// `vp9_filter_kernels` (`vp9/common/vp9_filter.c:79`), in libvpx's filter +/// numbering: 0 `EIGHTTAP`, 1 `EIGHTTAP_SMOOTH`, 2 `EIGHTTAP_SHARP`, +/// 3 `BILINEAR` (the 4-tap index 4 is unreachable for profile 0). +pub(crate) const FILTERS: [[[i16; TAPS]; SUBPEL_SHIFTS as usize]; 4] = [ + // sub_pel_filters_8: Lagrangian interpolation filter. + [ + [0, 0, 0, 128, 0, 0, 0, 0], + [0, 1, -5, 126, 8, -3, 1, 0], + [-1, 3, -10, 122, 18, -6, 2, 0], + [-1, 4, -13, 118, 27, -9, 3, -1], + [-1, 4, -16, 112, 37, -11, 4, -1], + [-1, 5, -18, 105, 48, -14, 4, -1], + [-1, 5, -19, 97, 58, -16, 5, -1], + [-1, 6, -19, 88, 68, -18, 5, -1], + [-1, 6, -19, 78, 78, -19, 6, -1], + [-1, 5, -18, 68, 88, -19, 6, -1], + [-1, 5, -16, 58, 97, -19, 5, -1], + [-1, 4, -14, 48, 105, -18, 5, -1], + [-1, 4, -11, 37, 112, -16, 4, -1], + [-1, 3, -9, 27, 118, -13, 4, -1], + [0, 2, -6, 18, 122, -10, 3, -1], + [0, 1, -3, 8, 126, -5, 1, 0], + ], + // sub_pel_filters_8lp: freqmultiplier = 0.5 (EIGHTTAP_SMOOTH). + [ + [0, 0, 0, 128, 0, 0, 0, 0], + [-3, -1, 32, 64, 38, 1, -3, 0], + [-2, -2, 29, 63, 41, 2, -3, 0], + [-2, -2, 26, 63, 43, 4, -4, 0], + [-2, -3, 24, 62, 46, 5, -4, 0], + [-2, -3, 21, 60, 49, 7, -4, 0], + [-1, -4, 18, 59, 51, 9, -4, 0], + [-1, -4, 16, 57, 53, 12, -4, -1], + [-1, -4, 14, 55, 55, 14, -4, -1], + [-1, -4, 12, 53, 57, 16, -4, -1], + [0, -4, 9, 51, 59, 18, -4, -1], + [0, -4, 7, 49, 60, 21, -3, -2], + [0, -4, 5, 46, 62, 24, -3, -2], + [0, -4, 4, 43, 63, 26, -2, -2], + [0, -3, 2, 41, 63, 29, -2, -2], + [0, -3, 1, 38, 64, 32, -1, -3], + ], + // sub_pel_filters_8s: DCT based filter (EIGHTTAP_SHARP). + [ + [0, 0, 0, 128, 0, 0, 0, 0], + [-1, 3, -7, 127, 8, -3, 1, 0], + [-2, 5, -13, 125, 17, -6, 3, -1], + [-3, 7, -17, 121, 27, -10, 5, -2], + [-4, 9, -20, 115, 37, -13, 6, -2], + [-4, 10, -23, 108, 48, -16, 8, -3], + [-4, 10, -24, 100, 59, -19, 9, -3], + [-4, 11, -24, 90, 70, -21, 10, -4], + [-4, 11, -23, 80, 80, -23, 11, -4], + [-4, 10, -21, 70, 90, -24, 11, -4], + [-3, 9, -19, 59, 100, -24, 10, -4], + [-3, 8, -16, 48, 108, -23, 10, -4], + [-2, 6, -13, 37, 115, -20, 9, -4], + [-2, 5, -10, 27, 121, -17, 7, -3], + [-1, 3, -6, 17, 125, -13, 5, -2], + [0, 1, -3, 8, 127, -7, 3, -1], + ], + // bilinear_filters. + [ + [0, 0, 0, 128, 0, 0, 0, 0], + [0, 0, 0, 120, 8, 0, 0, 0], + [0, 0, 0, 112, 16, 0, 0, 0], + [0, 0, 0, 104, 24, 0, 0, 0], + [0, 0, 0, 96, 32, 0, 0, 0], + [0, 0, 0, 88, 40, 0, 0, 0], + [0, 0, 0, 80, 48, 0, 0, 0], + [0, 0, 0, 72, 56, 0, 0, 0], + [0, 0, 0, 64, 64, 0, 0, 0], + [0, 0, 0, 56, 72, 0, 0, 0], + [0, 0, 0, 48, 80, 0, 0, 0], + [0, 0, 0, 40, 88, 0, 0, 0], + [0, 0, 0, 32, 96, 0, 0, 0], + [0, 0, 0, 24, 104, 0, 0, 0], + [0, 0, 0, 16, 112, 0, 0, 0], + [0, 0, 0, 8, 120, 0, 0, 0], + ], +]; + +/// `clip_pixel` (`vpx_dsp/vpx_dsp_common.h`). +fn clip_pixel(v: i32) -> u8 { + v.clamp(0, 255) as u8 +} + +/// `ROUND_POWER_OF_TWO(v, n)`. +fn round_pow2(v: i32, n: i32) -> i32 { + (v + (1 << (n - 1))) >> n +} + +/// Read `buf[i]` for a possibly negative `i`. Every caller keeps `i` inside +/// the buffer (the border copy guarantees the tap margins exist). +#[inline] +fn at(buf: &[u8], i: isize) -> u8 { + buf[i as usize] +} + +/// `clamp_mv_to_umv_border_sb` (`vp9/common/vp9_reconinter.c:88`), returning +/// the MV in 1/16-pel (`MV_PRECISION_Q4`) units. +/// +/// `mb_*` are the block's distances to the frame edges in 1/8-pel units +/// (`xd->mb_to_*_edge`, i.e. `±mi * 64`); `bw`/`bh` are the PLANE block's +/// pixel dimensions. `clamp_mv(mv, min_col, max_col, min_row, max_row)`: +/// columns are bounded by the left/right edges, rows by the top/bottom. +pub(crate) fn clamp_mv_to_umv_border_sb( + mv: (i32, i32), + bw: i32, + bh: i32, + mb_left: i32, + mb_right: i32, + mb_top: i32, + mb_bottom: i32, + ss_x: usize, + ss_y: usize, +) -> (i32, i32) { + let spel_left = (INTERP_EXTEND + bw) << SUBPEL_BITS; + let spel_right = spel_left - SUBPEL_SHIFTS; + let spel_top = (INTERP_EXTEND + bh) << SUBPEL_BITS; + let spel_bottom = spel_top - SUBPEL_SHIFTS; + let xs = 1 << (1 - ss_x); + let ys = 1 << (1 - ss_y); + let col = (mv.1 * xs).clamp(mb_left * xs - spel_left, mb_right * xs + spel_right); + let row = (mv.0 * ys).clamp(mb_top * ys - spel_top, mb_bottom * ys + spel_bottom); + (row, col) +} + +/// `build_mc_border` (`vp9/decoder/vp9_decodeframe.c:473`): copy the +/// `b_w` x `b_h` window whose top-left is frame pixel `(x, y)` into `dst`, +/// replicating the frame's first/last row and column for reads outside +/// `[0, w)` x `[0, h)`. +#[allow(clippy::too_many_arguments)] +fn build_mc_border( + src: &[u8], + src_stride: usize, + dst: &mut [u8], + dst_stride: usize, + x: i32, + mut y: i32, + b_w: usize, + mut b_h: usize, + w: i32, + h: i32, +) { + // C computes `ref_row = src - x - y * src_stride`; for negative y the + // pointer arithmetic leaves the buffer and the row-index equivalent below + // is the same read. + let mut row = if y >= h { + (h - 1) as usize + } else if y > 0 { + y as usize + } else { + 0 + }; + let mut out = 0usize; + loop { + let left = if x < 0 { (-x).min(b_w as i32) } else { 0 } as usize; + let right = if x + b_w as i32 > w { + (x + b_w as i32 - w).min(b_w as i32) + } else { + 0 + } as usize; + let copy = b_w - left - right; + + let base = row * src_stride; + if left > 0 { + let v = src[base]; + dst[out..out + left].fill(v); + } + if copy > 0 { + let from = (x + left as i32) as usize; + dst[out + left..out + left + copy] + .copy_from_slice(&src[base + from..base + from + copy]); + } + if right > 0 { + let v = src[base + (w - 1) as usize]; + dst[out + left + copy..out + left + copy + right].fill(v); + } + + out += dst_stride; + y += 1; + if y > 0 && y < h { + row += 1; + } + b_h -= 1; + if b_h == 0 { + break; + } + } +} + +/// `convolve_horiz` / `convolve_avg_horiz` (`vpx_dsp/vpx_convolve.c:22`). +/// `origin` is the block's first sample in `buf`; taps are read from +/// `origin + y*stride + (x_q4 >> SUBPEL_BITS) - (SUBPEL_TAPS / 2 - 1) + k`. +#[allow(clippy::too_many_arguments)] +fn convolve_horiz( + buf: &[u8], + stride: usize, + origin: isize, + dst: &mut [u8], + dst_stride: usize, + f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize], + x0_q4: i32, + w: usize, + rows: usize, + avg: bool, +) { + for y in 0..rows { + let mut x_q4 = x0_q4; + for x in 0..w { + let base = origin + y as isize * stride as isize + (x_q4 >> SUBPEL_BITS) as isize + - (TAPS as isize / 2 - 1); + let filt = &f[(x_q4 & SUBPEL_MASK) as usize]; + let mut sum = 0i32; + for k in 0..TAPS { + sum += at(buf, base + k as isize) as i32 * filt[k] as i32; + } + let v = clip_pixel(round_pow2(sum, FILTER_BITS)) as i32; + let d = y * dst_stride + x; + dst[d] = if avg { + round_pow2(dst[d] as i32 + v, 1) as u8 + } else { + v as u8 + }; + x_q4 += SUBPEL_SHIFTS; + } + } +} + +/// `convolve_vert` / `convolve_avg_vert` (`vpx_dsp/vpx_convolve.c:80`). +fn convolve_vert( + buf: &[u8], + stride: usize, + origin: isize, + dst: &mut [u8], + dst_stride: usize, + f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize], + y0_q4: i32, + w: usize, + h: usize, + avg: bool, +) { + for x in 0..w { + let mut y_q4 = y0_q4; + for y in 0..h { + let base = origin + + ((y_q4 >> SUBPEL_BITS) as isize - (TAPS as isize / 2 - 1)) * stride as isize + + x as isize; + let filt = &f[(y_q4 & SUBPEL_MASK) as usize]; + let mut sum = 0i32; + for k in 0..TAPS { + sum += at(buf, base + k as isize * stride as isize) as i32 * filt[k] as i32; + } + let v = clip_pixel(round_pow2(sum, FILTER_BITS)) as i32; + let d = y * dst_stride + x; + dst[d] = if avg { + round_pow2(dst[d] as i32 + v, 1) as u8 + } else { + v as u8 + }; + y_q4 += SUBPEL_SHIFTS; + } + } +} + +/// `inter_predictor` + `sf->predict` (`vp9/common/vp9_reconinter.h:23`, +/// `vp9/common/vp9_scale.c:79`): for the unscaled case `predict[0][0]` is +/// copy/avg, `predict[0][1][*]` the vertical kernel, `predict[1][0][*]` the +/// horizontal one and `predict[1][1][*]` the 2D convolve. +/// +/// `w` x `h` output samples written at `dst`; `buf`/`origin` locate the +/// block's first reference sample. `temp` is the `vpx_convolve8` intermediate +/// (stride-64 scratch of `64 * 135` bytes plus a `64 * 64` second scratch for +/// the averaging variant). +#[allow(clippy::too_many_arguments)] +fn inter_predictor( + buf: &[u8], + stride: usize, + origin: isize, + dst: &mut [u8], + dst_stride: usize, + f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize], + subpel_x: i32, + subpel_y: i32, + w: usize, + h: usize, + avg: bool, + temp: &mut [u8], +) { + if subpel_x == 0 && subpel_y == 0 { + for y in 0..h { + for x in 0..w { + let s = at(buf, origin + (y * stride + x) as isize) as i32; + let d = y * dst_stride + x; + dst[d] = if avg { + round_pow2(dst[d] as i32 + s, 1) as u8 + } else { + s as u8 + }; + } + } + return; + } + if subpel_y == 0 { + convolve_horiz(buf, stride, origin, dst, dst_stride, f, subpel_x, w, h, avg); + return; + } + if subpel_x == 0 { + convolve_vert(buf, stride, origin, dst, dst_stride, f, subpel_y, w, h, avg); + return; + } + // vpx_convolve8_c: horizontal pass into a stride-64 intermediate with + // `intermediate_height = (((h - 1) * y_step_q4 + y0_q4) >> SUBPEL_BITS) + + // SUBPEL_TAPS` — for the unscaled `y_step_q4 = 16` that is `h + SUBPEL_TAPS + // - 1`. The horizontal pass starts `SUBPEL_TAPS / 2 - 1` rows ABOVE the + // block (C passes `src - src_stride * (SUBPEL_TAPS / 2 - 1)`). + let intermediate_height = + (((h as i32 - 1) * SUBPEL_SHIFTS + subpel_y) >> SUBPEL_BITS) as usize + TAPS; + let temp_origin = (TAPS as isize / 2 - 1) * 64; + convolve_horiz( + buf, + stride, + origin - (TAPS as isize / 2 - 1) * stride as isize, + temp, + 64, + f, + subpel_x, + w, + intermediate_height, + false, + ); + if avg { + // vpx_convolve8_avg_c: full 2D into a second scratch, then average + // with the destination (which holds the first reference's block). + // `temp[..64 * 135]` is the horizontal intermediate; the region after + // it is the 2D result. + let (horiz, mid2) = temp.split_at_mut(64 * 135); + convolve_vert(horiz, 64, temp_origin, mid2, w, f, subpel_y, w, h, false); + for y in 0..h { + for x in 0..w { + let d = y * dst_stride + x; + dst[d] = round_pow2(dst[d] as i32 + mid2[y * w + x] as i32, 1) as u8; + } + } + return; + } + convolve_vert( + temp, + 64, + temp_origin, + dst, + dst_stride, + f, + subpel_y, + w, + h, + false, + ); +} + +/// One reference plane of a stored frame. +pub(crate) struct RefPlane<'a> { + /// Plane base — the frame's first visible sample. + pub data: &'a [u8], + /// Row pitch. + pub stride: usize, + /// `y_crop_width` / `uv_crop_width`: the coded extent, which is what + /// `build_mc_border` replicates past. + pub width: usize, + /// `y_crop_height` / `uv_crop_height`. + pub height: usize, +} + +/// `dec_build_inter_predictors` (`vp9/decoder/vp9_decodeframe.c:593`), +/// unscaled: predict one `w` x `h` plane block whose top-left is plane pixel +/// `(x, y)` inside the block at MI `(mi_row, mi_col)`. +#[allow(clippy::too_many_arguments)] +pub(crate) fn build_inter_predictors( + dst: &mut [u8], + dst_stride: usize, + refp: &RefPlane<'_>, + mi_col: usize, + mi_row: usize, + x: usize, + y: usize, + w: usize, + h: usize, + mv: (i32, i32), + mb_left: i32, + mb_right: i32, + mb_top: i32, + mb_bottom: i32, + ss_x: usize, + ss_y: usize, + kernel: usize, + avg: bool, + scratch: &mut Vec, + temp: &mut Vec, +) { + let mv_q4 = clamp_mv_to_umv_border_sb( + mv, w as i32, h as i32, mb_left, mb_right, mb_top, mb_bottom, ss_x, ss_y, + ); + + // Co-ordinate of the containing block, pixel precision, plus the + // block-relative offset (`x`, `y`). + let x0_pre = (-mb_left >> (3 + ss_x)) + x as i32; + let y0_pre = (-mb_top >> (3 + ss_y)) + y as i32; + let x0_16 = (x0_pre << SUBPEL_BITS) + mv_q4.1; + let y0_16 = (y0_pre << SUBPEL_BITS) + mv_q4.0; + let subpel_x = mv_q4.1 & SUBPEL_MASK; + let subpel_y = mv_q4.0 & SUBPEL_MASK; + + let frame_width = refp.width as i32; + let frame_height = refp.height as i32; + // `buf_ptr = ref_frame + y0 * stride + x0` is taken AFTER the MV integer + // part but BEFORE the tap padding below, so the direct read keeps its own + // copy of the coordinates. + let x0_mv = x0_pre + (mv_q4.1 >> SUBPEL_BITS); + let y0_mv = y0_pre + (mv_q4.0 >> SUBPEL_BITS); + let mut x0 = x0_mv; + let mut y0 = y0_mv; + + let f = &FILTERS[kernel]; + let _ = mi_col; + let _ = mi_row; + + // `is_scaled || scaled_mv.col || scaled_mv.row || (frame_width & 7) || + // (frame_height & 7)`: the border copy is skipped only when the window is + // provably inside the frame. + if mv_q4.1 != 0 || mv_q4.0 != 0 || (frame_width & 7) != 0 || (frame_height & 7) != 0 { + let mut x1 = ((x0_16 + (w as i32 - 1) * SUBPEL_SHIFTS) >> SUBPEL_BITS) + 1; + let mut y1 = ((y0_16 + (h as i32 - 1) * SUBPEL_SHIFTS) >> SUBPEL_BITS) + 1; + let mut x_pad = false; + let mut y_pad = false; + if subpel_x != 0 { + x0 -= INTERP_EXTEND - 1; + x1 += INTERP_EXTEND; + x_pad = true; + } + if subpel_y != 0 { + y0 -= INTERP_EXTEND - 1; + y1 += INTERP_EXTEND; + y_pad = true; + } + if x0 < 0 + || x0 > frame_width - 1 + || x1 < 0 + || x1 > frame_width - 1 + || y0 < 0 + || y0 > frame_height - 1 + || y1 < 0 + || y1 > frame_height - 1 + { + let b_w = (x1 - x0 + 1) as usize; + let b_h = (y1 - y0 + 1) as usize; + let border_offset = usize::from(y_pad) * 3 * b_w + usize::from(x_pad) * 3; + scratch.resize(b_w * b_h, 0); + build_mc_border( + refp.data, + refp.stride, + scratch, + b_w, + x0, + y0, + b_w, + b_h, + frame_width, + frame_height, + ); + inter_predictor( + scratch, + b_w, + border_offset as isize, + dst, + dst_stride, + f, + subpel_x, + subpel_y, + w, + h, + avg, + temp, + ); + return; + } + } + // Inside the frame: read directly. The `x0`/`y0` checks above guarantee + // the `SUBPEL_TAPS / 2 - 1` tap margin that `inter_predictor` reads + // backwards also lies inside the visible plane. + let origin = y0_mv as isize * refp.stride as isize + x0_mv as isize; + inter_predictor( + refp.data, + refp.stride, + origin, + dst, + dst_stride, + f, + subpel_x, + subpel_y, + w, + h, + avg, + temp, + ); +} + +/// `average_split_mvs` (`vp9/common/vp9_reconinter.c:113`), luma (`ss_idx 0`): +/// the sub-block's own MV. +pub(crate) fn split_mv(bmi: &[[(i32, i32); 2]; 4], block: usize, ref_idx: usize) -> (i32, i32) { + bmi[block][ref_idx] +} + +/// `average_split_mvs` for 4:2:0 chroma (`ss_idx 3`): `mi_mv_pred_q4`, the +/// q4-rounded average over the four sub-blocks. +/// +/// `round_mv_comp_q4(v) = (v < 0 ? v - 2 : v + 2) / 4` — C's truncating +/// division, which Rust's `/` on integers reproduces. +pub(crate) fn average_split_mvs_chroma(bmi: &[[(i32, i32); 2]; 4], ref_idx: usize) -> (i32, i32) { + let q4 = |v: i32| if v < 0 { (v - 2) / 4 } else { (v + 2) / 4 }; + let mut row = 0; + let mut col = 0; + for b in bmi.iter() { + row += b[ref_idx].0; + col += b[ref_idx].1; + } + (q4(row), q4(col)) +} diff --git a/crates/ec-vp9/tests/inter_pixels_exact.rs b/crates/ec-vp9/tests/inter_pixels_exact.rs new file mode 100644 index 00000000..3ac4ea64 --- /dev/null +++ b/crates/ec-vp9/tests/inter_pixels_exact.rs @@ -0,0 +1,131 @@ +//! Inter-frame pixel witness: a GOP (key frame + inter frames, with and +//! without tile columns) must decode byte-identically to ffmpeg's libvpx +//! decoder, whose rawvideo output is the oracle. Fixtures are generated +//! deterministically with ffmpeg, so the witness is self-contained. +//! +//! The 1080p private streams the lane developed against are compared through +//! `tests/scratch_pixdump.rs` (env-gated) instead; see `lanes/vp9pix.report.md`. + +mod ivf; + +use ec_vp9::decode::Decoder; + +/// Generate a GOP fixture with libvpx: 6 frames of testsrc2 at 320x240, +/// `-g 10` so frames 1..5 are inter frames. +fn ensure_fixture(path: &std::path::Path, tile_columns: u32) { + if path.exists() { + return; + } + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + let st = std::process::Command::new("ffmpeg") + .args([ + "-v", + "error", + "-y", + "-f", + "lavfi", + "-i", + "testsrc2=size=320x240:rate=24:duration=0.25", + "-c:v", + "libvpx-vp9", + "-g", + "10", + "-crf", + "32", + "-deadline", + "good", + "-cpu-used", + "4", + "-tile-columns", + ]) + .arg(tile_columns.to_string()) + .args(["-pix_fmt", "yuv420p", "-f", "ivf"]) + .arg(path) + .output() + .expect("ffmpeg with libvpx-vp9 must be on PATH for the witnesses"); + assert!(st.status.success(), "fixture generation failed: {st:?}"); +} + +/// ffmpeg's decoded rawvideo byte stream (frame-packed I420, `w`x`h`). +fn ffmpeg_raw_yuv(path: &std::path::Path, w: usize, h: usize) -> Vec { + let out = std::process::Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .expect("ffmpeg on PATH"); + assert!(out.status.success(), "ffmpeg decode failed: {out:?}"); + let frame = w * h + 2 * (w / 2) * (h / 2); + assert_eq!( + out.stdout.len() % frame, + 0, + "ffmpeg output is not frame-aligned" + ); + out.stdout +} + +/// Decode every frame with our decoder and compare each SHOWN frame's planes +/// against ffmpeg's stream; returns the number of shown frames compared. +fn compare(path: &std::path::Path) -> usize { + let bytes = std::fs::read(path).unwrap(); + let (_, w, h, frames) = ivf::parse_ivf(&bytes); + let (w, h) = (w as usize, h as usize); + let expected = ffmpeg_raw_yuv(path, w, h); + let frame_bytes = w * h + 2 * (w / 2) * (h / 2); + + let mut decoder = Decoder::new(); + let mut shown = 0usize; + let mut seen_inter = false; + for (i, f) in frames.iter().enumerate() { + if let Some(pic) = decoder.decode(&f.data).expect("frame decodes") { + let off = shown * frame_bytes; + assert!( + off + frame_bytes <= expected.len(), + "frame {i}: ffmpeg has fewer frames than we show" + ); + let want = &expected[off..off + frame_bytes]; + let mut got = Vec::with_capacity(frame_bytes); + got.extend_from_slice(&pic.y); + got.extend_from_slice(&pic.u); + got.extend_from_slice(&pic.v); + assert_eq!( + got.len(), + frame_bytes, + "frame {i}: our planes are {w}x{h} I420" + ); + let diff = got.iter().zip(want).position(|(a, b)| a != b); + assert!( + diff.is_none(), + "frame {i}: pixel mismatch at byte {:?} (ours {} ffmpeg {})", + diff, + diff.map(|d| got[d]).unwrap_or(0), + diff.map(|d| want[d]).unwrap_or(0) + ); + shown += 1; + } + if i > 0 { + seen_inter = true; + } + } + assert_eq!(shown * frame_bytes, expected.len(), "frame count mismatch"); + assert!(seen_inter, "the fixture must contain inter frames"); + shown +} + +#[test] +fn inter_gop_matches_ffmpeg() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/vp9-witness"); + let path = dir.join("inter-gop.ivf"); + ensure_fixture(&path, 0); + assert!(compare(&path) >= 2); +} + +#[test] +fn inter_gop_with_tile_columns_matches_ffmpeg() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/vp9-witness"); + let path = dir.join("inter-gop-tc1.ivf"); + ensure_fixture(&path, 1); + assert!(compare(&path) >= 2); +} diff --git a/crates/ec-vp9/tests/keyframe_exact.rs b/crates/ec-vp9/tests/keyframe_exact.rs index 40d08203..d6ca1685 100644 --- a/crates/ec-vp9/tests/keyframe_exact.rs +++ b/crates/ec-vp9/tests/keyframe_exact.rs @@ -117,30 +117,44 @@ fn lossless_64_matches_ffmpeg() { } #[test] -fn inter_is_named_unsupported() { +fn inter_stream_decodes_and_matches_ffmpeg() { + // The altref clip is a real 60-frame inter stream with hidden frames; it + // used to be the "inter is refused by name" witness. Inter frames decode + // now, so the witness is the pixels: every shown frame must match + // ffmpeg's libvpx output byte for byte. let Some(dir) = ivf::fixture_dir() else { return }; - // The altref clip contains hidden (inter) frames. let path = dir.join("vp9-superframe-altref.ivf"); let bytes = std::fs::read(&path).unwrap(); - let (_, _, _, frames) = ivf::parse_ivf(&bytes); + let (_, w, h, frames) = ivf::parse_ivf(&bytes); + let (w, h) = (w as usize, h as usize); + let expected = ffmpeg_raw_yuv(&path); + let frame_bytes = w * h + 2 * (w / 2) * (h / 2); let mut decoder = Decoder::new(); - let mut saw_inter = false; - let mut saw_named = false; - for frame in &frames { - match decoder.decode(&frame.data) { - Ok(_) => {} - Err(e) => { - saw_inter = true; - let msg = format!("{e}"); - if msg.contains("vp9 inter") { - saw_named = true; - } - break; + let mut shown = 0usize; + let mut hidden = 0usize; + for (i, frame) in frames.iter().enumerate() { + match decoder.decode(&frame.data).expect("every frame decodes") { + Some(pic) => { + let off = shown * frame_bytes; + let mut got = Vec::with_capacity(frame_bytes); + got.extend_from_slice(&pic.y); + got.extend_from_slice(&pic.u); + got.extend_from_slice(&pic.v); + assert_eq!( + got, + expected[off..off + frame_bytes], + "frame {i}: pixel mismatch" + ); + shown += 1; } + None => hidden += 1, } } - assert!(saw_inter, "the altref fixture must contain a refused frame"); - assert!(saw_named, "the refusal must name 'vp9 inter'"); + assert!(shown >= 2, "the stream shows frames"); + // The chunk-level hidden altref frames are consumed by the decoder's + // superframe split, so every IVF chunk here yields one shown frame. + assert_eq!(hidden, 0, "superframe chunks show exactly one frame each"); + assert_eq!(shown * frame_bytes, expected.len()); } #[test] diff --git a/crates/ec-vp9/tests/scratch_pixdump.rs b/crates/ec-vp9/tests/scratch_pixdump.rs new file mode 100644 index 00000000..5bd9bfd6 --- /dev/null +++ b/crates/ec-vp9/tests/scratch_pixdump.rs @@ -0,0 +1,77 @@ +//! Scratch: dump every shown frame's planes for the pixel comparator. +//! +//! `INTER_IVF= EC_VP9_PIXDUMP= cargo test -p ec-vp9 --test scratch_pixdump` +//! +//! Layout matches the oracle: per shown frame, Y (w*h), U ((w/2)*(h/2)), +//! V ((w/2)*(h/2)), rows packed to the visible width. + +use ec_vp9::decode::Decoder; + +#[test] +fn pixdump() { + let (Ok(ivf), Ok(out)) = (std::env::var("INTER_IVF"), std::env::var("EC_VP9_PIXDUMP")) else { + eprintln!("SKIP scratch_pixdump: set INTER_IVF and EC_VP9_PIXDUMP"); + return; + }; + let bytes = std::fs::read(&ivf).expect("read ivf"); + let (_, w, h, frames) = parse_ivf(&bytes); + let mut decoder = Decoder::new(); + let mut dump = Vec::new(); + let mut shown = 0usize; + for (i, f) in frames.iter().enumerate() { + match decoder.decode(&f.data) { + Ok(Some(pic)) => { + dump.extend_from_slice(&pic.y); + dump.extend_from_slice(&pic.u); + dump.extend_from_slice(&pic.v); + eprintln!( + "PIXFRAME input={i} shown={shown} {w}x{h} {}x{}", + pic.width, pic.height + ); + shown += 1; + } + Ok(None) => eprintln!("PIXFRAME input={i} hidden"), + Err(e) => { + eprintln!("PIXERR input={i}: {e}"); + break; + } + } + } + std::fs::write(&out, &dump).expect("write dump"); + eprintln!("wrote {} bytes ({shown} shown frames)", dump.len()); +} + +fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec) { + assert_eq!(&bytes[0..4], b"DKIF", "not an IVF file"); + let hdr_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize; + let fourcc = std::str::from_utf8(&bytes[8..12]).unwrap(); + let width = u16::from_le_bytes([bytes[12], bytes[13]]); + let height = u16::from_le_bytes([bytes[14], bytes[15]]); + let mut pos = hdr_len; + let mut frames = Vec::new(); + while pos + 12 <= bytes.len() { + let sz = u32::from_le_bytes([ + bytes[pos], + bytes[pos + 1], + bytes[pos + 2], + bytes[pos + 3], + ]) as usize; + let pts = u64::from_le_bytes(bytes[pos + 4..pos + 12].try_into().unwrap()); + pos += 12; + if pos + sz > bytes.len() { + break; + } + frames.push(IvfFrame { + pts, + data: bytes[pos..pos + sz].to_vec(), + }); + pos += sz; + } + (fourcc, width, height, frames) +} + +struct IvfFrame { + #[allow(dead_code)] + pts: u64, + data: Vec, +} diff --git a/lanes/vp9pix.report.md b/lanes/vp9pix.report.md new file mode 100644 index 00000000..ad678db3 --- /dev/null +++ b/lanes/vp9pix.report.md @@ -0,0 +1,232 @@ +# Lane vp9pix: VP9 inter-frame PIXELS (motion compensation → reconstruction) + +Branch `lane-vp9-pix`, base `main 597b7442`. Crate scope: `crates/ec-vp9` only. +Worktree `/home/user/Documents/Code/Rust/edith_codecs-vp9pix`, private +`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9pix`. + +Deliverable: `decode()` decodes inter frames through motion compensation, +residual reconstruction, the loop filter and reference-slot management, and is +byte-identical to a locally built libvpx 1.15 oracle on every fixture swept. + +## Baseline (milestone 0) + + $ CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9pix cargo test -p ec-vp9 + exit=0 (20 test binaries, 0 failures, 0 ignored) + +No pre-existing reds, so no base triage was needed. (Pre-existing warnings: +`crates/ec-vp9/src/modes.rs` unused `partition_probs`/`x_mis`/`y_mis` + +`read_partition`, `tables/mod.rs` `TM_PRED` — untouched files, present at base.) + +## The gate: byte-exactness against libvpx 1.15 + +Oracle: the instrumented build the syntax lane left at `/tmp/vp9loss` +(`drv_pix.c` is new here: it appends every SHOWN frame's cropped I420 planes, +frame-indexed, to `PIXDUMP`). Rich fixtures copied to `$HOME/.cache/vp9pix/` +for tmpfs insurance. Comparator: `$HOME/.cache/vp9pix/pixcmp.py` +(oracle, ours, w, h) → per-frame identical/first-diff report. + + $ python3 $HOME/.cache/vp9pix/pixcmp.py oracle_inter1.pix ours_inter1.pix 1920 1080 + oracle=9331200 bytes ours=9331200 bytes frame_bytes=3110400 + frame 0: IDENTICAL (3110400 bytes) + frame 1: IDENTICAL (3110400 bytes) + frame 2: IDENTICAL (3110400 bytes) + +That is the acceptance gate: 3/3 shown frames of the 1080p single-tile inter +stream, loop filter ON, planes byte-for-byte. + +Corroborating instruments (all agree): +- `SKIPLF` oracle + `EC_VP9_SKIP_LF=1` ours: identical too (isolates MC+residual + from the filter). +- Per-superblock LUMA loop-filter masks: oracle `LFMASKSY=1` vs our + `EC_VP9_LFMASKSY=1` → **0 of 510 SBs differ, on all three frames.** +- Emitted loop-filter edges: oracle `LFTRACE=` vs ours + `LFTRACE=1 EC_VP9_LF_FRAME=` (our per-frame gate) → every oracle edge is + emitted by us (oracle-only = 0); our extra 2660/3116 lines are the *second + column of a dual H16 pair* — libvpx prints one line for + `vpx_lpf_horizontal_16_dual`, we print one per 8x8 cell. Verified 2660/2660 + and 3116/3116 of the extras have an oracle twin at `(x-8, y)`. + +The entry-gate fixture is `/tmp/inter1.ivf` (1080p, 1 tile column). It is +reachable through `tests/scratch_pixdump.rs` +(`INTER_IVF=… EC_VP9_PIXDUMP=… cargo test -p ec-vp9 --test scratch_pixdump -- --nocapture`). + +## Corpus sweep (real content) + +| fixture | frames | result | +|---|---|---| +| `vp9-1080p-23.976-8bit.ivf` (48) | 48 | **all byte-identical** | +| `vp9-2160p-23.976-8bit.ivf` (48) | 48 | **all byte-identical** | +| `vp9-superframe-altref.ivf` (320x240, 60) | 60 | **all byte-identical** | +| `/tmp/inter1.ivf` (1080p, 1 tile col) | 3 | **all byte-identical** | +| `/tmp/inter.ivf` (1080p, 2 tile cols) | 3 | **all byte-identical** | +| `vp9-1080p-60-8bit.ivf` (120) | 72 | identical 0..71, **desync at 72** (deferred, below) | + +Sweep driver: `$HOME/.cache/vp9pix/sweep.sh ` (oracle dump + +our dump + `pixcmp.py`). + +## Milestones + +1. **Pixel plumbing** — oracle `drv_pix.c` + `tests/scratch_pixdump.rs` + + `pixcmp.py`. Done; the comparator is the instrument every claim below uses. +2. **Reference slots** — `refs: [Option; 8]`, `RefFrame` holds the + frame at its **64-aligned extent** (`Arc`) plus its coded size. + `refresh_frame_flags` is applied after the frame's loop filter + (`swap_frame_buffers`), so a later frame predicts from filtered pixels. + Evidence: the 1080p GOP and the 60-frame altref stream decode identically, + which is only possible if each frame's prediction reads exactly the frame + the header names (any slot mistake shows as a pixel diff on frame 1+). + The refusal for a size-changing reference is named (below). +3. **Motion compensation** — new `crates/ec-vp9/src/mc.rs`: libvpx's + `clamp_mv_to_umv_border_sb`, `build_mc_border` (per-block reference border + extension — the VP9 decoder does NOT extend reference borders in place), + `dec_build_inter_predictors` including the "window inside the frame" direct + read, the four convolve kernels (`EIGHTTAP`, `EIGHTTAP_SMOOTH`, + `EIGHTTAP_SHARP`, `BILINEAR`, index order = `vp9_filter_kernels`), compound + averaging, and `average_split_mvs` (luma per sub-block, 4:2:0 chroma q4 + average). +4. **Residual** — tokens via the shared `decode_inter_tx_tokens` (one read per + transform block), then `inverse_transform_add` with the DEFAULT scan and + `DCT_DCT` (`inverse_transform_block_inter`). +5. **Loop filter** — per-cell level from `get_filter_level` + (`lvl[seg][ref_frame[0]][mode_lf_lut[mode]]`), the skip promotion + (`!less8x8 && eobtotal == 0 → skip`) and the skipped-inter mask rule + (`skip && is_inter` keeps only the prediction masks). Verified by + mask-identity + edge-set + pixels (above). +6. **Gates** — `cargo test -p ec-vp9` green (below); refusals re-checked; + prose updated. + +## Bug classes found while porting (all fixed, each with its evidence) + +1. **Direct-read coordinates taken after the tap padding.** + `dec_build_inter_predictors` computes `buf_ptr = ref_frame + y0*stride + x0` + BEFORE `y0 -= INTERP_EXTEND - 1` / `x0 -= …`; our first version read the + direct path from the padded coordinates, i.e. 3 rows/cols early. Signature: + border-path blocks exact (top/bottom SB rows), direct-path blocks wrong by + up to ±5, and `SKIPLF`-style isolation shows the error is in prediction. + Independent python re-derivation of the C predictor from the oracle's + reference frame identified it in one step (oracle 45 vs ours 47). +2. **Skipped intra blocks inside an inter frame skipped + `dec_reset_skip_context`.** libvpx calls it at the top of `decode_block` + (before the intra/inter split); ours only in the inter arm, leaving stale + above-context bytes → a `tile bool decoder desync` in frame 2, with the + first divergence a *prob* difference at the same ordinal read (the skill's + "same ordinal, different question" signature). +3. **Skipped inter blocks kept full loop-filter masks.** `grids.skip_inter` + was only set by the eob promotion, so a coded-skip inter block got the + size/tx masks instead of prediction-only masks → extra 16-tap edges + (mask-identity check caught it as `L16 ⊉ L32`). +4. **Intra-in-inter tx type.** libvpx's luma mode for a sub-8x8 block is the + SUB-BLOCK's (`mi->bmi[…]`), used for `intra_mode_to_tx_type_lookup`; the + merged syntax walk used `info.mode`. Now shared by the syntax and pixel + walks (they must agree or the two paths read different tokens). +5. **`mv_ref_list[2]` write (crash).** `ADD_MV_REF_LIST_EB`'s successful + second add is `goto Done`; in the "different reference frame" loop the C + leaves the loop, our port kept iterating and wrote past the two-entry list + (`inter.rs`, now an explicit `break`). Found by the corpus sweep — + `vp9-superframe-altref.ivf` panicked at frame 14 before the fix; 60/60 + frames byte-identical after. +6. **Frame-level interpolation filter numbering** (`read_interp_filter`): + the header's literal index runs through + `literal_to_filter = {EIGHTTAP_SMOOTH, EIGHTTAP, EIGHTTAP_SHARP, BILINEAR}` + — NOT libvpx's `#define` numbering (`EIGHTTAP 0`). Converted where + `frame_interp` is built; inert on switchable streams (the fixture's), correct + for non-switchable ones. + +## Named refusals (unchanged or added) + +- `vp9 profile N` / `vp9 subsampling` — unchanged (existing tests). +- `vp9 intra-only` — unchanged refusal, now also reachable from `decode()`. +- **`vp9 inter reference size change`** (new): a named reference whose coded + size differs from the current frame is refused by name (libvpx scales it; + scaling is not ported in this lane). +- **`vp9 inter odd frame dimensions`** (new): odd width/height refused by + name — the keyframe crop stores chroma at `floor(w/2)` while the predictor + reads libvpx's `uv_crop_width = (w+1)/2`; the two disagree only for odd + extents, so those are refused rather than silently wrong. + +## Deferred + +- **`deferred(fix-now-next-lane)` — frame 72 desync on + `vp9-1080p-60-8bit.ivf`.** Frames 0..71 are byte-identical; frame 72 is an + ordinary inter frame (`MODEDUMP` CHSUM: `tx_mode=4 ref_mode=0 allow_hp=1 + interp=4 intra_only=0 er=0`, matching its neighbours) and dies with + `tile bool decoder desync`. An unexercised inter syntax path (compound + reference / sub-8x8 / a specific `use_prev_frame_mvs` state) is the likely + home; the 1080p 24fps GOP, the 4K GOP and the altref stream do not reach it. + Repro: `$HOME/.cache/vp9pix/sweep.sh vp9-1080p-60-8bit 1920 1080`. +- `deferred(unblock: odd-extent chroma layout)` — the odd-dimension refusal + above; the root fix is to store reference chroma at `(w+1)/2`, which also + changes the keyframe path's returned plane layout. +- **Superseded claim:** `lanes/vp9inter.report.md` ranked cause 3 ("keyframe + multi-tile-column desync on `/tmp/inter.ivf` frame 0") does **not** + reproduce at this lane's base — `INTER_IVF=/tmp/inter.ivf INTER_EXPECT=none + cargo test -p ec-vp9 --test scratch_interdump` passes on the untouched main + checkout (f715d70c, the tile-row fix, landed before the inter-syntax merge + 32d81e8f). `/tmp/inter.ivf` now decodes all 3 frames byte-exactly. + +## Gates + + $ CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9pix cargo test -p ec-vp9 + exit=0 — every binary green, including the new witness + tests/inter_pixels_exact.rs (2 tests: GOP + GOP with tile columns, + ffmpeg libvpx rawvideo oracle, self-generated + fixtures; non-vacuity proof: with + EC_VP9_SKIP_LF=1 both tests FAIL at frame 0 + byte 31 — ours 81 vs ffmpeg 82) + tests/keyframe_exact.rs (4 tests, incl. the rewritten + inter_stream_decodes_and_matches_ffmpeg: + 60/60 frames of the altref stream vs ffmpeg) + +## Repro (all commands) + + # gate + cd /home/user/Documents/Code/Rust/edith_codecs-vp9pix + CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9pix cargo test -p ec-vp9 + + # 1080p single-tile inter stream vs the instrumented oracle + cd $HOME/.cache/vp9pix && PIXDUMP=$HOME/.cache/vp9pix/oracle_inter1.pix ./drv_pix inter1.ivf + cd /home/user/Documents/Code/Rust/edith_codecs-vp9pix + CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9pix INTER_IVF=$HOME/.cache/vp9pix/inter1.ivf \ + EC_VP9_PIXDUMP=$HOME/.cache/vp9pix/ours_inter1.pix \ + cargo test -p ec-vp9 --test scratch_pixdump -- --nocapture + cd $HOME/.cache/vp9pix && python3 pixcmp.py oracle_inter1.pix ours_inter1.pix 1920 1080 + + # mask identity / edge sets + LFMASKSY=1 ./drv_pix inter1.ivf 2>&1 | grep '^LFY' > lfy_oracle.txt + LFTRACE=1 ./drv_pix inter1.ivf 2>&1 | grep '^LFTR' > lf_oracle_1.txt # LFTRACE= + +## VERDICT + +GATE 1 — `cargo test -p ec-vp9` green in the worktree (private target dir), +including the new pixel witnesses: **PASS**. +GATE 2 — `inter1.ivf` `decode()` returns 3 shown frames, each byte-identical to +the libvpx 1.15 oracle's planes (comparator output above): **PASS**. +GATE 3 — per-milestone evidence lines above; every pixel mismatch met during +development is named with its root cause (6 classes): **PASS**. +GATE 4 — this report: baseline, per-milestone evidence, `inter.ivf` +disposition, deferred items with dispositions, repro commands: **PASS**. +GATE 5 — committed to `lane-vp9-pix`, `git status` clean, no push/merge: see +the git log below. +GATE 6 — VERDICT section: this one. + +FLAGS (the verifier should re-derive these independently) +1. **The direct-read coordinate rule** (class 1) is the single most load-bearing + line in `mc.rs`: `origin` must come from the MV-adjusted, NOT tap-padded, + `x0`/`y0`. Re-derive from `vp9_decodeframe.c:672-728` and check our + `x0_mv`/`y0_mv` usage. +2. **`skip_inter` semantics**: `skip && is_inter` at BOTH the coded-skip and + the `eobtotal == 0` promotion, and the mask early-return placement (after + the above/left prediction masks). Mask-identity can be re-run per SB with + `EC_VP9_LFMASKSY=1` vs `LFMASKSY=1`. +3. **The `mv_ref_list[2]` fix** changes an existing (merged) syntax path: the + altref fixture panicked before it and is byte-exact after — re-run + `vp9-superframe-altref.ivf` end to end. +4. **Reference storage extent**: refs must keep the 64-aligned plane buffer + (the decoded overhang rows are readable by the direct path). Cropping them + reproduces the class-1 symptom set; confirm by checking that frames 1+ of + the 1080p GOP match (the overhang is read at the frame bottom). +5. **The 60fps frame-72 desync** is a real open defect: verify it is + independent of this lane's changes (`scratch_interdump` on the base + checkout reports the same frame-72 desync in the syntax walk). +6. Corpus sweeps were run on this workstation with `/tmp` fixtures; the + 1080p/2160p/altref dumps are regenerable from `sweep.sh`.