diff --git a/crates/ec-vp9/src/decode.rs b/crates/ec-vp9/src/decode.rs index 8f5b0f2f..59291de7 100644 --- a/crates/ec-vp9/src/decode.rs +++ b/crates/ec-vp9/src/decode.rs @@ -76,6 +76,44 @@ pub struct Decoder { refs: [Option; 8], /// Frame scratch, live only inside `decode_keyframe`. planes: Option, + /// The four stored frame contexts (spec 6.2 `frame_context_idx`). + frame_ctxs: [FrameContext; 4], + /// The previous frame's per-8x8 MV field and segment map + /// (`prev_frame->mvs` / `last_frame_seg_map`). + prev_mvs: Vec, + prev_seg: Vec, + last: LastFrameFacts, + /// Live only while an inter frame is being parsed. + iw: Option, + /// Frames parsed by `decode_syntax` (the dump's frame index). + frames_seen: usize, + /// Mode-info blocks parsed in the most recent inter frame (0 otherwise). + syntax_blocks: usize, +} + +/// What `use_prev_frame_mvs` (decodeframe.c:3023) tests about the last frame. +#[derive(Clone, Copy, Default)] +struct LastFrameFacts { + width: u32, + height: u32, + intra_only: bool, + show_frame: bool, + key: bool, +} + +/// State of one inter-syntax frame walk. +struct InterWalk { + ifs: crate::inter::InterFrameState, + sign_bias: [bool; 4], + use_prev: bool, + seg_map: Vec, + mvs: Vec, + prev_seg: Vec, + prev_mvs: Vec, + tile_col_end: usize, + frame_index: usize, + /// Mode-info blocks parsed in this frame (the harness's count gate). + blocks: usize, } impl Decoder { @@ -86,9 +124,25 @@ impl Decoder { ctx: FrameContext::new(true), refs: [const { None }; 8], planes: None, + frame_ctxs: { + let d = FrameContext::new(false); + [d.clone(), d.clone(), d.clone(), d] + }, + prev_mvs: Vec::new(), + prev_seg: Vec::new(), + last: LastFrameFacts::default(), + iw: None, + frames_seen: 0, + syntax_blocks: 0, } } + /// Mode-info blocks the most recent inter frame parsed; `0` for a keyframe + /// or before any frame. The syntax harness pins this number. + pub fn last_frame_blocks(&self) -> usize { + self.syntax_blocks + } + /// Decode one frame (or one superframe chunk); returns the picture /// when a frame is for display. Hidden frames still update state. pub fn decode(&mut self, frame: &[u8]) -> Result> { @@ -131,9 +185,29 @@ impl Decoder { "this lane decodes keyframes only", )); } - // A keyframe resets the frame context (spec 7.2) before the - // compressed header codes this frame's updates on top. - self.ctx = FrameContext::new(hdr.frame_type == FrameType::Key); + self.decode_key_frame(&hdr, frame) + } + + /// Decode one key frame through to pixels and refresh every slot. + fn decode_key_frame(&mut self, hdr: &FrameHeader, frame: &[u8]) -> Result> { + let hdr = hdr.clone(); + // setup_past_independence (spec 7.2): a key frame resets the frame + // context, so every STORED context goes back to the inter defaults. + // The keyframe's own mode info reads the const `vp9_kf_partition_probs` + // (libvpx `get_partition_probs`), which our `new(true)` models on the + // active copy only. + let d = FrameContext::new(false); + self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d]; + self.ctx = FrameContext::new(true); + self.prev_mvs.clear(); + self.prev_seg.clear(); + self.last = LastFrameFacts { + width: hdr.width, + height: hdr.height, + intra_only: hdr.intra_only, + show_frame: hdr.show_frame, + key: true, + }; // [scratch probe] EC_VP9_FORCE_UH / EC_VP9_FORCE_HSZ: override the // uncompressed-header size / header_size_in_bytes split for diagnosis. let hdr = { @@ -147,13 +221,17 @@ impl Decoder { h }; let hdr_start = hdr.uncompressed_header_size as usize; - let tx_mode = read_compressed_header( + let ch = read_compressed_header( &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize], &mut self.ctx, - hdr.quantization.lossless(), + &hdr, )?; - let pic = self.decode_keyframe(&hdr, frame, tx_mode)?; + let pic = self.decode_keyframe(&hdr, frame, ch.tx_mode)?; + if hdr.refresh_frame_context { + self.ctx.reset_inter_partition(); + self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.clone(); + } // Reference refresh (spec 8.10): a keyframe updates all slots. for slot in self.refs.iter_mut() { *slot = Some(pic.clone()); @@ -161,6 +239,438 @@ impl Decoder { Ok(if hdr.show_frame { Some(pic) } else { None }) } + /// Parse one frame's syntax: keyframes decode through to pixels, inter + /// frames are parsed (headers, mode info, MVs) with no reconstruction and + /// no picture. `decode` still refuses inter frames. + pub fn decode_syntax(&mut self, frame: &[u8]) -> Result<()> { + for sub in superframe::split(frame)? { + let index = self.frames_seen; + self.frames_seen += 1; + let hdr = self.parser.parse_frame(sub)?; + if hdr.show_existing_frame { + continue; + } + if hdr.profile != 0 { + return Err(Error::unsupported( + format!("vp9 profile {}", hdr.profile), + "this lane decodes profile 0 only", + )); + } + if hdr.frame_type == FrameType::Key { + // Propagate: a corrupt keyframe leaves a half-updated frame + // context, prev-frame MV field and reference slots behind, so + // any inter-frame dump after it would be meaningless evidence. + self.decode_key_frame(&hdr, sub)?; + } else if hdr.intra_only { + return Err(Error::unsupported( + "vp9 intra-only", + "the inter-syntax lane covers inter frames only", + )); + } else { + self.decode_inter_syntax_frame(&hdr, sub, index)?; + } + } + 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<()> { + // 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. + if hdr.reset_frame_context == 3 { + let d = FrameContext::new(false); + self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d]; + } else if hdr.reset_frame_context == 2 { + self.frame_ctxs[hdr.frame_context_idx as usize] = FrameContext::new(false); + } + self.ctx = self.frame_ctxs[hdr.frame_context_idx as usize].clone(); + + let hdr_start = hdr.uncompressed_header_size as usize; + if crate::trace_enabled() { + eprintln!("CHSTART frame={index}"); + } + let ch = read_compressed_header( + &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize], + &mut self.ctx, + hdr, + )?; + + if crate::interdump_enabled() { + let mut line = format!("PPFLAT frame={index}"); + for row in self.ctx.partition.iter() { + for v in row.iter() { + line.push_str(&format!(" {v}")); + } + } + eprintln!("{line}"); + } + + // INTRA_FRAME's sign bias is 0 by definition; the coded three land at + // LAST/GOLDEN/ALTREF. + let sign_bias = [ + false, + hdr.ref_frame_sign_bias[0], + hdr.ref_frame_sign_bias[1], + hdr.ref_frame_sign_bias[2], + ]; + let mut ifs = crate::inter::InterFrameState { + reference_mode: ch.reference_mode, + ..Default::default() + }; + if ch.reference_mode != crate::inter::SINGLE_REFERENCE { + crate::inter::setup_compound_reference_mode(&mut ifs, sign_bias); + } + let use_prev = !hdr.error_resilient_mode + && hdr.width == self.last.width + && hdr.height == self.last.height + && !self.last.intra_only + && self.last.show_frame + && !self.last.key; + + 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); + let sb64_rows = mi_rows.div_ceil(SB_MI); + let tile_cols = 1usize << hdr.tile_info.cols_log2; + let tile_rows = 1usize << hdr.tile_info.rows_log2; + + self.iw = Some(InterWalk { + ifs, + sign_bias, + use_prev, + seg_map: vec![0; mi_cols * mi_rows], + mvs: vec![crate::inter::MvRef::default(); mi_cols * mi_rows], + prev_seg: std::mem::take(&mut self.prev_seg), + prev_mvs: std::mem::take(&mut self.prev_mvs), + tile_col_end: mi_cols, + frame_index: index, + blocks: 0, + }); + + let mut data: &[u8] = &frame[hdr_start + hdr.header_size_in_bytes as usize..]; + let mut tiles: Vec<&[u8]> = Vec::with_capacity(tile_cols * tile_rows); + for tr in 0..tile_rows { + for tc in 0..tile_cols { + let last = tr == tile_rows - 1 && tc == tile_cols - 1; + if last { + tiles.push(data); + } else { + ensure(data.len() >= 4, "truncated tile size")?; + let sz = u32::from_be_bytes(data[..4].try_into().unwrap()) as usize; + data = &data[4..]; + ensure(data.len() >= sz, "truncated tile data")?; + tiles.push(&data[..sz]); + data = &data[sz..]; + } + } + } + + // The loop-filter grids are never written on this path (no + // reconstruction), 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], + mi_cols, + mi_rows, + }; + let mut ti = 0usize; + for tr in 0..tile_rows { + let row_lo = ((sb64_rows * tr) >> hdr.tile_info.rows_log2) * SB_MI; + let row_hi = (((sb64_rows * (tr + 1)) >> hdr.tile_info.rows_log2) * SB_MI).min(mi_rows); + for tc in 0..tile_cols { + let col_lo = ((sb64_cols * tc) >> hdr.tile_info.cols_log2) * SB_MI; + let col_hi = + (((sb64_cols * (tc + 1)) >> hdr.tile_info.cols_log2) * SB_MI).min(mi_cols); + if let Some(w) = self.iw.as_mut() { + w.tile_col_end = col_hi; + } + if crate::trace_enabled() { + eprintln!("TILE {} bytes frame={index}", tiles[ti].len()); + } + 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) { + 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) { + self.decode_partition( + &mut r, + &mut mi, + &mut ectx, + &mut grids, + &[[0u8; 2]; 8], + hdr, + sb_row, + sb_col, + 4, + row_lo, + col_lo, + ch.tx_mode, + )?; + } + } + ensure(r.overreads() == 0, "tile bool decoder desync")?; + } + } + + // The walk state is consumed below, so the block count the harness pins + // has to be captured first. + self.syntax_blocks = self.iw.as_ref().map_or(0, |w| w.blocks); + let w = self.iw.take().expect("inter walk state"); + self.prev_mvs = w.mvs; + self.prev_seg = w.seg_map; + self.last = LastFrameFacts { + width: hdr.width, + height: hdr.height, + intra_only: hdr.intra_only, + show_frame: hdr.show_frame, + key: false, + }; + if hdr.refresh_frame_context { + self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.clone(); + } + if crate::interdump_enabled() { + eprintln!( + "CHSUM frame={index} tx_mode={} ref_mode={} allow_hp={} interp={} tile_rows={} tile_cols={} pp12={:?} pp0={:?} pp13={:?}", + ch.tx_mode, + ch.reference_mode, + hdr.allow_high_precision_mv, + hdr.interpolation_filter as u8, + hdr.tile_info.rows_log2, + hdr.tile_info.cols_log2, + self.ctx.partition[12], + self.ctx.partition[0], + self.ctx.partition[13] + ); + } + Ok(()) + } + + /// One inter block's syntax (`read_inter_frame_mode_info` + the MV field + /// `vp9_read_mode_info` stores for the next frame). + #[allow(clippy::too_many_arguments)] + fn read_inter_block_info( + &mut self, + r: &mut crate::bool::BoolDecoder, + mi: &MiState, + hdr: &FrameHeader, + row: usize, + col: usize, + sb_type: usize, + x_mis: usize, + y_mis: usize, + tile_row_start: usize, + tile_col_start: usize, + tx_mode: u8, + ) -> Result { + // BLOCK_4X4/4X8/8X4 are the SPLIT/VERT/HORZ partitions of an 8x8. + let partition = match sb_type { + 0 => 3u8, + 1 => 2u8, + 2 => 1u8, + _ => 0u8, + }; + let w = self.iw.as_mut().expect("inter walk state"); + let prev_seg = std::mem::take(&mut w.prev_seg); + let prev_mvs = std::mem::take(&mut w.prev_mvs); + let ctx = crate::inter::InterBlockCtx { + seg: &hdr.segmentation, + ifs: w.ifs, + sign_bias: w.sign_bias, + allow_hp: hdr.allow_high_precision_mv, + frame_interp: hdr.interpolation_filter as u8, + tx_mode, + mi_rows: mi.mi_rows, + mi_cols: mi.mi_cols, + tile_row_start, + tile_col_start, + tile_col_end: w.tile_col_end, + last_seg: (!prev_seg.is_empty()).then_some(&prev_seg[..]), + prev_mvs: (w.use_prev && !prev_mvs.is_empty()).then_some(&prev_mvs[..]), + }; + let info = crate::inter::read_inter_frame_mode_info( + r, + mi, + &ctx, + &self.ctx, + row, + col, + sb_type, + x_mis, + y_mis, + partition, + &mut w.seg_map, + ); + if let Ok(info) = &info { + w.blocks += 1; + for dy in 0..y_mis { + for dx in 0..x_mis { + let i = (row + dy) * mi.mi_cols + col + dx; + w.mvs[i] = crate::inter::MvRef { + ref_frame: info.ref_frame, + mv: info.mv, + }; + } + } + if crate::interdump_enabled() { + eprintln!( + "MODE {} {} {} {} {} {} {} {} {} tpos=0 ref0={} ref1={} mvrow={} mvcol={} if={}", + w.frame_index, + row, + col, + sb_type, + info.tx_size, + info.mode, + info.uv_mode, + u8::from(info.skip), + info.segment, + info.ref_frame[0], + info.ref_frame[1], + info.mv[0].0, + info.mv[0].1, + info.interp_filter + ); + } + } + w.prev_seg = prev_seg; + w.prev_mvs = prev_mvs; + info + } + + /// Tokens for one inter block: same entropy walk as the keyframe path, + /// but no prediction and no residual add. `is_inter` selects the + /// coefficient-probability ref axis. + #[allow(clippy::too_many_arguments)] + fn decode_inter_block_tokens( + &mut self, + r: &mut crate::bool::BoolDecoder, + mi: &MiState, + ectx: &mut [PlaneContexts; 3], + hdr: &FrameHeader, + info: &MiInfo, + row: usize, + col: usize, + sb_type: usize, + 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] + } else { + [bh * 2, bh, bh] + }; + if info.skip { + // dec_reset_skip_context + 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; + } + } + 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(); + 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 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( + r, + ptype, + tx_size, + &dequant, + ctx_in, + scan, + nb, + &self.ctx.coef[tx_size], + info.is_inter, + (0, 0), + plane, + ); + // 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; + } + } + } + } + Ok(()) + } + fn decode_keyframe(&mut self, hdr: &FrameHeader, frame: &[u8], tx_mode: u8) -> Result { let width = hdr.width as usize; let height = hdr.height as usize; @@ -559,21 +1069,63 @@ impl Decoder { let x_mis = bw.min(mi.mi_cols - col); let y_mis = bh.min(mi.mi_rows - row); - let info = read_intra_frame_mode_info( - r, - mi, - &hdr.segmentation, - &self.ctx.partition, - row, - col, - sb_type, - x_mis, - y_mis, - tile_row_start, - tile_col_start, - tx_mode, - &self.ctx.skip, - )?; + let info = if hdr.frame_type == FrameType::Key { + read_intra_frame_mode_info( + r, + mi, + &hdr.segmentation, + &self.ctx.partition, + row, + col, + sb_type, + x_mis, + y_mis, + tile_row_start, + tile_col_start, + tx_mode, + &self.ctx.skip, + )? + } else { + self.read_inter_block_info( + r, + mi, + hdr, + row, + col, + sb_type, + x_mis, + y_mis, + tile_row_start, + tile_col_start, + tx_mode, + )? + }; + 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)?; + for dy in 0..y_mis { + for dx in 0..x_mis { + if crate::mvdbg2_enabled() + && row + dy == 7 + && col + dx >= 30 + && col + dx <= 40 + { + eprintln!( + "GWR cell=({} {}) idx={} from=({row} {col}) dy={dy} dx={dx} sb={sb_type} bw={bw} bh={bh} x_mis={x_mis} y_mis={y_mis} mv={:?} ref0={} mi_cols={}", + row + dy, + col + dx, + (row + dy) * mi.mi_cols + col + dx, + info.mv, + info.ref_frame[0], + mi.mi_cols + ); + } + mi.grid[(row + dy) * mi.mi_cols + col + dx] = Some(info.clone()); + } + } + return Ok(()); + } // Per-plane 4x4 counts. Sub-8x8 shapes still occupy the WHOLE 8x8 // mi area (libvpx set_plane_n4 with bw=bh=1): luma walks 2x2 4x4 @@ -782,6 +1334,7 @@ impl Decoder { scan, nb, &self.ctx.coef[tx_size], + false, (x0, y0), plane, ); diff --git a/crates/ec-vp9/src/header.rs b/crates/ec-vp9/src/header.rs index b36f8111..879ccc7c 100644 --- a/crates/ec-vp9/src/header.rs +++ b/crates/ec-vp9/src/header.rs @@ -4,7 +4,9 @@ //! differential probability-update machinery (libvpx `vp9_dsubexp.c`). use crate::bool::BoolDecoder; +use crate::inter::{COMPOUND_REFERENCE, REFERENCE_MODE_SELECT, SINGLE_REFERENCE}; use crate::tables::*; +use ec_vp9_syntax::FrameHeader; /// All bool-coded probabilities a keyframe reads. #[derive(Clone)] @@ -15,6 +17,36 @@ pub(crate) struct FrameContext { pub tx_p16x16: [[u8; 2]; 2], pub tx_p32x32: [[u8; 3]; 2], pub skip: [u8; 3], + /// Inter-frame tables (all defaults until a compressed header updates + /// them): `inter_mode_probs`, `switchable_interp_prob`, `intra_inter_prob`, + /// `comp_inter_prob`, `single_ref_prob`, `comp_ref_prob`, `y_mode_prob`, + /// `uv_mode_prob`, and the MV probs. + pub inter_mode: [[u8; 3]; 7], + pub switchable_interp: [[u8; 2]; 4], + pub intra_inter: [u8; 4], + pub comp_inter: [u8; 5], + pub single_ref: [[u8; 2]; 5], + pub comp_ref: [u8; 5], + pub y_mode: [[u8; 9]; 4], + pub uv_mode: [[u8; 9]; 10], + pub nmv_joints: [u8; 3], + pub nmv_sign: [u8; 2], + pub nmv_classes: [[u8; 10]; 2], + pub nmv_class0: [[u8; 1]; 2], + pub nmv_bits: [[u8; 10]; 2], + pub nmv_class0_fp: [[[u8; 3]; 2]; 2], + pub nmv_fp: [[u8; 3]; 2], + pub nmv_class0_hp: [u8; 2], + pub nmv_hp: [u8; 2], +} + +/// Rows from a flat C initializer. +fn rows(flat: &[u8]) -> [[u8; C]; R] { + let mut out = [[0u8; C]; R]; + for (i, row) in out.iter_mut().enumerate() { + row.copy_from_slice(&flat[i * C..i * C + C]); + } + out } impl FrameContext { @@ -51,10 +83,49 @@ impl FrameContext { [TX_P32X32_PROB[3], TX_P32X32_PROB[4], TX_P32X32_PROB[5]], ], skip: DEFAULT_SKIP_PROBS, + // `vp9_init_frame_context` / `vp9_init_mv_probs` defaults. Key + // frames do not use these; inter frames start from them unless a + // stored context (or a compressed header) says otherwise. + inter_mode: rows(&DEFAULT_INTER_MODE_PROBS), + switchable_interp: rows(&DEFAULT_SWITCHABLE_INTERP_PROBS), + intra_inter: DEFAULT_INTRA_INTER_PROBS, + comp_inter: DEFAULT_COMP_INTER_PROBS, + single_ref: rows(&DEFAULT_SINGLE_REF_PROBS), + comp_ref: DEFAULT_COMP_REF_PROBS, + y_mode: rows(&DEFAULT_Y_MODE_PROBS), + uv_mode: rows(&DEFAULT_IF_UV_PROBS), + nmv_joints: DEFAULT_NMVC_JOINTS, + nmv_sign: DEFAULT_NMVC_SIGN, + nmv_classes: rows(&DEFAULT_NMVC_CLASSES), + nmv_class0: [[DEFAULT_NMVC_CLASS0[0]], [DEFAULT_NMVC_CLASS0[1]]], + nmv_bits: rows(&DEFAULT_NMVC_BITS), + nmv_class0_fp: [ + [ + [DEFAULT_NMVC_CLASS0_FP[0], DEFAULT_NMVC_CLASS0_FP[1], DEFAULT_NMVC_CLASS0_FP[2]], + [DEFAULT_NMVC_CLASS0_FP[3], DEFAULT_NMVC_CLASS0_FP[4], DEFAULT_NMVC_CLASS0_FP[5]], + ], + [ + [DEFAULT_NMVC_CLASS0_FP[6], DEFAULT_NMVC_CLASS0_FP[7], DEFAULT_NMVC_CLASS0_FP[8]], + [DEFAULT_NMVC_CLASS0_FP[9], DEFAULT_NMVC_CLASS0_FP[10], DEFAULT_NMVC_CLASS0_FP[11]], + ], + ], + nmv_fp: rows(&DEFAULT_NMVC_FP), + nmv_class0_hp: DEFAULT_NMVC_CLASS0_HP, + nmv_hp: DEFAULT_NMVC_HP, } } } +impl FrameContext { + /// `vp9_kf_partition_probs` are NOT a `FRAME_CONTEXT` field in libvpx + /// (`get_partition_probs` picks the const table for intra-only frames); + /// a context that a keyframe stored must therefore go back to the inter + /// defaults before the next frame reads it. + pub(crate) fn reset_inter_partition(&mut self) { + self.partition = rows(&DEFAULT_PARTITION_PROBS); + } +} + /// `inv_recenter_nonneg` (vp9_dsubexp.c). fn inv_recenter_nonneg(v: i32, m: i32) -> i32 { if v > 2 * m { @@ -127,6 +198,20 @@ fn diff_update_prob(r: &mut BoolDecoder, p: &mut u8) { } } +/// `MV_UPDATE_PROB` (`vp9_entropymv.h`): the flag prob of `update_mv_probs`. +const MV_UPDATE_PROB: u8 = 252; + +/// `update_mv_probs` (vp9_decodeframe.c:136). NOT a `vp9_diff_update_prob`: +/// a flag at `MV_UPDATE_PROB`, then seven LITERAL bits, and the new prob is +/// `(literal << 1) | 1` — no `decode_term_subexp`, no `inv_remap_prob`. +fn update_mv_probs(r: &mut BoolDecoder, p: &mut [u8]) { + for v in p.iter_mut() { + if r.read_bool(MV_UPDATE_PROB) { + *v = ((r.read_literal(7) << 1) | 1) as u8; + } + } +} + /// `read_coef_probs_common` (decodeframe.c:1314): one flag per tx size /// covers all plane/ref/band/context updates of the first three (base) /// probs per slot. @@ -159,8 +244,17 @@ fn read_tx_mode(r: &mut BoolDecoder) -> u8 { m } -/// `read_compressed_header` for intra frames (the inter branch is dead -/// in this lane): tx mode, tx probs, coef probs, skip probs. +/// What `read_compressed_header` decides for the frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct CompressedHeader { + pub tx_mode: u8, + pub reference_mode: u8, +} + +/// `read_compressed_header` (libvpx `vp9_decodeframe.c:2889`): tx mode, tx +/// probs, coef probs, skip probs, then — for inter frames only — the inter +/// mode, switchable-interp, intra/inter, reference-mode, y-mode, partition +/// and MV probability updates. /// /// Lossless forces `ONLY_4X4` and consumes no tx-mode bits — decodeframe.c /// `read_compressed_header`: `cm->tx_mode = xd->lossless ? ONLY_4X4 : @@ -168,14 +262,27 @@ fn read_tx_mode(r: &mut BoolDecoder) -> u8 { pub(crate) fn read_compressed_header( data: &[u8], ctx: &mut FrameContext, - lossless: bool, -) -> crate::Result { + hdr: &FrameHeader, +) -> crate::Result { + if crate::interdump_enabled() && !hdr.frame_is_intra { + let mut line = String::from("PPFLAT_PRE"); + for row in ctx.partition.iter() { + for v in row.iter() { + line.push_str(&format!(" {v}")); + } + } + eprintln!("{line}"); + } + let lossless = hdr.quantization.lossless(); let mut r = BoolDecoder::new(data)?; let tx_mode = if lossless { ONLY_4X4 } else { read_tx_mode(&mut r) }; + if crate::trace_enabled() { + eprintln!("SECT txmode"); + } if tx_mode == TX_MODE_SELECT { for row in 0..2 { for j in 0..1 { @@ -193,10 +300,159 @@ pub(crate) fn read_compressed_header( } } } + if crate::trace_enabled() { + eprintln!("SECT txprobs"); + } read_coef_probs(&mut r, ctx, tx_mode); + if crate::trace_enabled() { + eprintln!("SECT coef"); + } for p in &mut ctx.skip { diff_update_prob(&mut r, p); } + let mut reference_mode = SINGLE_REFERENCE; + if crate::trace_enabled() { + eprintln!("SECT skip"); + } + if !hdr.frame_is_intra { + if crate::trace_enabled() { + eprintln!("SECT intermode"); + } + for i in 0..7 { + for j in 0..3 { + diff_update_prob(&mut r, &mut ctx.inter_mode[i][j]); + } + } + if crate::trace_enabled() { + eprintln!("SECT switchable"); + } + if hdr.interpolation_filter as u8 == crate::inter::SWITCHABLE { + for j in 0..4 { + for i in 0..2 { + diff_update_prob(&mut r, &mut ctx.switchable_interp[j][i]); + } + } + } + if crate::trace_enabled() { + eprintln!("SECT intrainter"); + } + for p in &mut ctx.intra_inter { + diff_update_prob(&mut r, p); + } + // read_frame_reference_mode: `vp9_compound_reference_allowed` gates + // the two bits (bias[GOLDEN]/bias[ALTREF] vs bias[LAST]). + if crate::trace_enabled() { + eprintln!("SECT refmode"); + } + let allowed = hdr.ref_frame_sign_bias[1] != hdr.ref_frame_sign_bias[0] + || hdr.ref_frame_sign_bias[2] != hdr.ref_frame_sign_bias[0]; + reference_mode = if allowed { + if r.read_bool(128) { + if r.read_bool(128) { + REFERENCE_MODE_SELECT + } else { + COMPOUND_REFERENCE + } + } else { + SINGLE_REFERENCE + } + } else { + SINGLE_REFERENCE + }; + // read_frame_reference_mode_probs. + if crate::trace_enabled() { + eprintln!("SECT refprobs"); + } + if reference_mode == REFERENCE_MODE_SELECT { + for p in &mut ctx.comp_inter { + diff_update_prob(&mut r, p); + } + } + if reference_mode != COMPOUND_REFERENCE { + for i in 0..5 { + for j in 0..2 { + diff_update_prob(&mut r, &mut ctx.single_ref[i][j]); + } + } + } + if reference_mode != SINGLE_REFERENCE { + for p in &mut ctx.comp_ref { + diff_update_prob(&mut r, p); + } + } + if crate::trace_enabled() { + eprintln!("SECT ymode"); + } + for j in 0..4 { + for i in 0..9 { + diff_update_prob(&mut r, &mut ctx.y_mode[j][i]); + } + } + if crate::trace_enabled() { + eprintln!("SECT partition"); + } + for j in 0..16 { + for i in 0..3 { + let before = ctx.partition[j][i]; + diff_update_prob(&mut r, &mut ctx.partition[j][i]); + if crate::interdump_enabled() { + eprintln!("PUPD {} {} {} {}", j, i, before, ctx.partition[j][i]); + } + } + } + // read_mv_probs (vp9_decodeframe.c:76): joints, then per component + // sign/classes/class0/bits, then the fractional parts, then hp. + if crate::trace_enabled() { + eprintln!("SECT mv"); + } + update_mv_probs(&mut r, &mut ctx.nmv_joints); + for comp in 0..2 { + update_mv_probs(&mut r, &mut ctx.nmv_sign[comp..comp + 1]); + update_mv_probs(&mut r, &mut ctx.nmv_classes[comp]); + update_mv_probs(&mut r, &mut ctx.nmv_class0[comp]); + update_mv_probs(&mut r, &mut ctx.nmv_bits[comp]); + } + for comp in 0..2 { + for j in 0..2 { + update_mv_probs(&mut r, &mut ctx.nmv_class0_fp[comp][j]); + } + update_mv_probs(&mut r, &mut ctx.nmv_fp[comp]); + } + if hdr.allow_high_precision_mv { + for comp in 0..2 { + update_mv_probs(&mut r, &mut ctx.nmv_class0_hp[comp..comp + 1]); + update_mv_probs(&mut r, &mut ctx.nmv_hp[comp..comp + 1]); + if crate::mvdump_enabled() { + eprintln!( + "MVPROB j0={} j1={} j2={}", + ctx.nmv_joints[0], ctx.nmv_joints[1], ctx.nmv_joints[2] + ); + for comp in 0..2 { + eprintln!( + "MVPROB c{} sign={} class0={} class0hp={} hp={}", + comp, + ctx.nmv_sign[comp], + ctx.nmv_class0[comp][0], + ctx.nmv_class0_hp[comp], + ctx.nmv_hp[comp] + ); + eprint!("MVPROB c{} cls", comp); + for v in ctx.nmv_classes[comp].iter() { eprint!(" {}", v); } + eprintln!(); + eprint!("MVPROB c{} bits", comp); + for v in ctx.nmv_bits[comp].iter() { eprint!(" {}", v); } + eprintln!(); + eprint!("MVPROB c{} c0fp", comp); + for row in ctx.nmv_class0_fp[comp].iter() { for v in row.iter() { eprint!(" {}", v); } } + eprintln!(); + eprint!("MVPROB c{} fp", comp); + for v in ctx.nmv_fp[comp].iter() { eprint!(" {}", v); } + eprintln!(); + } + } + } + } + } if std::env::var_os("EC_VP9_DBG").is_some() { eprintln!("DBG tx_mode={} consumed={}", tx_mode, r.byte_offset()); eprintln!( @@ -209,5 +465,8 @@ pub(crate) fn read_compressed_header( ); } ensure(r.overreads() == 0, "compressed header desync")?; - Ok(tx_mode) + Ok(CompressedHeader { + tx_mode, + reference_mode, + }) } diff --git a/crates/ec-vp9/src/inter.rs b/crates/ec-vp9/src/inter.rs new file mode 100644 index 00000000..3751437e --- /dev/null +++ b/crates/ec-vp9/src/inter.rs @@ -0,0 +1,1317 @@ +//! Inter-frame syntax (libvpx `vp9/decoder/vp9_decodemv.c` +//! `read_inter_frame_mode_info`, `vp9/common/vp9_mvref_common.h`). +//! +//! Syntax only: nothing here reconstructs pixels. The MV *predictor* is still +//! parse-load-bearing — `read_mv` reads the high-precision bit only when +//! `allow_high_precision_mv && use_mv_hp(predictor)`, so the candidate scan +//! runs even though no motion compensation happens. + +use crate::bool::BoolDecoder; +use crate::header::FrameContext; +use crate::modes::{MiInfo, MiState}; +use crate::tables::*; + +/// `INTRA_FRAME` .. `ALTREF_FRAME` (`MV_REFERENCE_FRAME`), `NO_REF_FRAME` = -1. +pub(crate) const INTRA_FRAME: i8 = 0; +pub(crate) const LAST_FRAME: i8 = 1; +pub(crate) const GOLDEN_FRAME: i8 = 2; +pub(crate) const ALTREF_FRAME: i8 = 3; +pub(crate) const NO_REF_FRAME: i8 = -1; +/// `PREDICTION_MODE` values of the inter modes. +pub(crate) const NEARESTMV: u8 = 10; +pub(crate) const NEARMV: u8 = 11; +pub(crate) const ZEROMV: u8 = 12; +pub(crate) const NEWMV: u8 = 13; +/// `REFERENCE_MODE`. +pub(crate) const SINGLE_REFERENCE: u8 = 0; +pub(crate) const COMPOUND_REFERENCE: u8 = 1; +pub(crate) const REFERENCE_MODE_SELECT: u8 = 2; +/// `SWITCHABLE`: `interpolation_filter` value meaning "per block". +pub(crate) const SWITCHABLE: u8 = 4; +/// `SWITCHABLE_FILTERS`: the sentinel `mi->interp_filter` of intra blocks. +pub(crate) const SWITCHABLE_FILTERS: u8 = 3; + +const MAX_MV_REF_CANDIDATES: usize = 2; +const MVREF_NEIGHBOURS: usize = 8; +/// `MV_BORDER` (1/8-pel units). +const MV_BORDER: i32 = 16 << 3; +/// `use_mv_hp`'s `kMvRefThresh`. +const MV_HP_THRESH: i32 = 64; +const CLASS0_SIZE: i32 = 2; +const CLASS0_BITS: i32 = 1; +/// `SEG_LVL_SKIP` / `SEG_LVL_REF_FRAME`. +const SEG_LVL_REF_FRAME: usize = 2; +const SEG_LVL_SKIP: usize = 3; + +/// `mv_ref_blocks[BLOCK_SIZES]` (`vp9_mvref_common.h`): `(row, col)` offsets, +/// transcribed verbatim from the C. libvpx's `POSITION` is `{ row, col }`, so +/// every accessor must add the FIRST element to the row and the SECOND to the +/// column (a transposed accessor silently picks a different neighbour for every +/// asymmetric entry). +const MV_REF_BLOCKS: [[(i32, i32); MVREF_NEIGHBOURS]; 13] = [ + // 4X4 + [(-1, 0), (0, -1), (-1, -1), (-2, 0), (0, -2), (-2, -1), (-1, -2), (-2, -2)], + // 4X8 + [(-1, 0), (0, -1), (-1, -1), (-2, 0), (0, -2), (-2, -1), (-1, -2), (-2, -2)], + // 8X4 + [(-1, 0), (0, -1), (-1, -1), (-2, 0), (0, -2), (-2, -1), (-1, -2), (-2, -2)], + // 8X8 + [(-1, 0), (0, -1), (-1, -1), (-2, 0), (0, -2), (-2, -1), (-1, -2), (-2, -2)], + // 8X16 + [(0, -1), (-1, 0), (1, -1), (-1, -1), (0, -2), (-2, 0), (-2, -1), (-1, -2)], + // 16X8 + [(-1, 0), (0, -1), (-1, 1), (-1, -1), (-2, 0), (0, -2), (-1, -2), (-2, -1)], + // 16X16 + [(-1, 0), (0, -1), (-1, 1), (1, -1), (-1, -1), (-3, 0), (0, -3), (-3, -3)], + // 16X32 + [(0, -1), (-1, 0), (2, -1), (-1, -1), (-1, 1), (0, -3), (-3, 0), (-3, -3)], + // 32X16 + [(-1, 0), (0, -1), (-1, 2), (-1, -1), (1, -1), (-3, 0), (0, -3), (-3, -3)], + // 32X32 + [(-1, 1), (1, -1), (-1, 2), (2, -1), (-1, -1), (-3, 0), (0, -3), (-3, -3)], + // 32X64 + [(0, -1), (-1, 0), (4, -1), (-1, 2), (-1, -1), (0, -3), (-3, 0), (2, -1)], + // 64X32 + [(-1, 0), (0, -1), (-1, 4), (2, -1), (-1, -1), (-3, 0), (0, -3), (-1, 2)], + // 64X64 + [(-1, 3), (3, -1), (-1, 4), (4, -1), (-1, -1), (-1, 0), (0, -1), (-1, 6)], +]; + +/// `idx_n_column_to_subblock` (`vp9_mvref_common.h`). +const IDX_N_COLUMN_TO_SUBBLOCK: [[usize; 2]; 4] = [[1, 2], [1, 3], [3, 2], [3, 3]]; + +/// One `MV_REF` entry: the previous frame's per-8x8 reference pair and MVs +/// (`vp9_read_mode_info` stores them for every block of an inter frame). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub(crate) struct MvRef { + /// `ref_frame[0]`/`[1]`; zeroed means `INTRA_FRAME`. + pub ref_frame: [i8; 2], + /// `mv[0]`/`[1]` in 1/8-pel units. + pub mv: [(i32, i32); 2], +} + +/// Frame-level reference-mode state (`VP9_COMMON::reference_mode`, +/// `comp_fixed_ref`, `comp_var_ref`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct InterFrameState { + pub reference_mode: u8, + pub comp_fixed_ref: i8, + pub comp_var_ref: [i8; 2], +} + +impl Default for InterFrameState { + fn default() -> Self { + InterFrameState { + reference_mode: SINGLE_REFERENCE, + comp_fixed_ref: ALTREF_FRAME, + comp_var_ref: [LAST_FRAME, GOLDEN_FRAME], + } + } +} + +/// `vp9_setup_compound_reference_mode` (`vp9_pred_common.c`): which ref frame +/// of a compound pair is coded explicitly, and which two the coded bit picks. +pub(crate) fn setup_compound_reference_mode(ifs: &mut InterFrameState, sign_bias: [bool; 4]) { + let b = |f: i8| sign_bias[f as usize]; + if b(LAST_FRAME) == b(GOLDEN_FRAME) { + ifs.comp_fixed_ref = ALTREF_FRAME; + ifs.comp_var_ref = [LAST_FRAME, GOLDEN_FRAME]; + } else if b(LAST_FRAME) == b(ALTREF_FRAME) { + ifs.comp_fixed_ref = GOLDEN_FRAME; + ifs.comp_var_ref = [LAST_FRAME, ALTREF_FRAME]; + } else { + ifs.comp_fixed_ref = LAST_FRAME; + ifs.comp_var_ref = [GOLDEN_FRAME, ALTREF_FRAME]; + } +} + +/// Frame- and position-scoped inputs of the block-level reads. +pub(crate) struct InterBlockCtx<'a> { + pub seg: &'a ec_vp9_syntax::SegmentationParams, + pub ifs: InterFrameState, + /// `ref_frame_sign_bias[INTRA..ALTREF]`. + pub sign_bias: [bool; 4], + pub allow_hp: bool, + pub frame_interp: u8, + pub tx_mode: u8, + pub mi_rows: usize, + pub mi_cols: usize, + pub tile_row_start: usize, + pub tile_col_start: usize, + /// `tile->mi_col_end`. + pub tile_col_end: usize, + /// The previous frame's segment map, when it has one. + pub last_seg: Option<&'a [u8]>, + /// `prev_frame->mvs` when `use_prev_frame_mvs`. + pub prev_mvs: Option<&'a [MvRef]>, +} + +/// The two decoded neighbours of the current block. +#[derive(Clone, Copy)] +struct Nb<'a> { + above: Option<&'a MiInfo>, + left: Option<&'a MiInfo>, +} + +/// `read_inter_frame_mode_info` (`vp9_decodemv.c`). +#[allow(clippy::too_many_arguments)] +pub(crate) fn read_inter_frame_mode_info( + r: &mut BoolDecoder, + st: &MiState, + c: &InterBlockCtx<'_>, + fc: &FrameContext, + row: usize, + col: usize, + sb_type: usize, + x_mis: usize, + y_mis: usize, + partition: u8, + cur_seg: &mut [u8], +) -> crate::Result { + let above = st.above_mi(row, col, c.tile_row_start).cloned(); + let left = st.left_mi(row, col, c.tile_col_start).cloned(); + let nb = Nb { + above: above.as_ref(), + left: left.as_ref(), + }; + + let mut seg_id_predicted = false; + let segment = read_inter_segment_id(r, c, nb, row, col, x_mis, y_mis, cur_seg, &mut seg_id_predicted); + let skip = read_skip(r, c, fc, segment, nb); + let inter_block = read_is_inter_block(r, c, fc, segment, nb); + let tx_size = read_tx_size(r, c, fc, sb_type, nb, !skip || !inter_block); + + let mut info = MiInfo { + sb_type, + segment, + skip, + tx_size, + mode: 0, + uv_mode: 0, + bmi: [0; 4], + is_inter: inter_block, + ref_frame: [NO_REF_FRAME; 2], + mv: [(0, 0); 2], + mv_diff: [(0, 0); 2], + bmi_mv: [[(0, 0); 2]; 4], + seg_id_predicted, + interp_filter: SWITCHABLE_FILTERS, + }; + if inter_block { + read_inter_block_mode_info(r, st, c, fc, &mut info, nb, row, col, partition)?; + } else { + read_intra_block_mode_info(r, fc, &mut info); + } + Ok(info) +} + +/// `dec_get_segment_id`: the minimum id over the block's covered cells. +fn min_seg(map: &[u8], row: usize, col: usize, x_mis: usize, y_mis: usize, mi_cols: usize) -> u8 { + let mut id = u8::MAX; + for y in 0..y_mis { + for x in 0..x_mis { + id = id.min(map[(row + y) * mi_cols + col + x]); + } + } + id +} + +/// `set_segment_id` / `copy_segment_id`. +fn write_seg( + src: Option<&[u8]>, + dst: &mut [u8], + row: usize, + col: usize, + x_mis: usize, + y_mis: usize, + mi_cols: usize, + id: u8, +) { + for y in 0..y_mis { + for x in 0..x_mis { + let i = (row + y) * mi_cols + col + x; + dst[i] = match src { + Some(m) => m[i], + None => id, + }; + } + } +} + +/// `read_inter_segment_id` (`vp9_decodemv.c:151`). +#[allow(clippy::too_many_arguments)] +fn read_inter_segment_id( + r: &mut BoolDecoder, + c: &InterBlockCtx<'_>, + nb: Nb<'_>, + row: usize, + col: usize, + x_mis: usize, + y_mis: usize, + cur_seg: &mut [u8], + seg_id_predicted: &mut bool, +) -> u8 { + let seg = c.seg; + if !seg.enabled { + return 0; + } + let predicted = c + .last_seg + .map_or(0, |m| min_seg(m, row, col, x_mis, y_mis, c.mi_cols)); + if !seg.update_map { + write_seg(c.last_seg, cur_seg, row, col, x_mis, y_mis, c.mi_cols, 0); + return predicted; + } + let segment_id = if seg.temporal_update { + let ctx = usize::from(nb.above.is_some_and(|m| m.seg_id_predicted)) + + usize::from(nb.left.is_some_and(|m| m.seg_id_predicted)); + *seg_id_predicted = r.read_bool(seg.pred_probs[ctx]); + if *seg_id_predicted { + predicted + } else { + r.read_tree(&SEGMENT_TREE, &seg.tree_probs) + } + } else { + r.read_tree(&SEGMENT_TREE, &seg.tree_probs) + }; + write_seg(None, cur_seg, row, col, x_mis, y_mis, c.mi_cols, segment_id); + segment_id +} + +fn seg_feature(seg: &ec_vp9_syntax::SegmentationParams, segment_id: u8, feature: usize) -> bool { + seg.enabled + && seg + .feature_enabled + .get(segment_id as usize) + .is_some_and(|f| f[feature]) +} + +/// `read_skip`. +fn read_skip( + r: &mut BoolDecoder, + c: &InterBlockCtx<'_>, + fc: &FrameContext, + segment_id: u8, + nb: Nb<'_>, +) -> bool { + if seg_feature(c.seg, segment_id, SEG_LVL_SKIP) { + true + } else { + let ctx = usize::from(nb.above.is_some_and(|m| m.skip)) + + usize::from(nb.left.is_some_and(|m| m.skip)); + r.read_bool(fc.skip[ctx]) + } +} + +/// `get_intra_inter_context` (`vp9_pred_common.h`). +fn intra_inter_context(nb: Nb<'_>) -> usize { + match (nb.above, nb.left) { + (Some(a), Some(l)) => { + let above_intra = !a.is_inter; + let left_intra = !l.is_inter; + if left_intra && above_intra { + 3 + } else { + usize::from(left_intra || above_intra) + } + } + (Some(m), None) | (None, Some(m)) => 2 * usize::from(!m.is_inter), + (None, None) => 0, + } +} + +/// `read_is_inter_block`. +fn read_is_inter_block( + r: &mut BoolDecoder, + c: &InterBlockCtx<'_>, + fc: &FrameContext, + segment_id: u8, + nb: Nb<'_>, +) -> bool { + if seg_feature(c.seg, segment_id, SEG_LVL_REF_FRAME) { + c.seg.feature_data[segment_id as usize][SEG_LVL_REF_FRAME] != INTRA_FRAME as i16 + } else { + r.read_bool(fc.intra_inter[intra_inter_context(nb)]) + } +} + +/// `read_tx_size` with `allow_select` (spec 6.3.5 / `vp9_decodemv.c:85`). +fn read_tx_size( + r: &mut BoolDecoder, + c: &InterBlockCtx<'_>, + fc: &FrameContext, + sb_type: usize, + nb: Nb<'_>, + allow_select: bool, +) -> usize { + let max_tx = MAX_TXSIZE_LOOKUP[sb_type] as usize; + if allow_select && c.tx_mode == TX_MODE_SELECT && sb_type >= 3 { + // get_tx_size_context: default each side to max_tx, then substitute + // the other side when one is missing, in this exact order. + let a0 = nb + .above + .map_or(max_tx, |m| if m.skip { max_tx } else { m.tx_size }); + let l0 = nb + .left + .map_or(max_tx, |m| if m.skip { max_tx } else { m.tx_size }); + let mut a = a0; + let mut l = l0; + if nb.left.is_none() { + l = a; + } + if nb.above.is_none() { + a = l; + } + let ctx = usize::from(a + l > max_tx); + let probs: &[u8] = match max_tx { + 1 => &fc.tx_p8x8[ctx][..], + 2 => &fc.tx_p16x16[ctx][..], + _ => &fc.tx_p32x32[ctx][..], + }; + let mut tx = r.read_bool(probs[0]) as usize; + if tx != TX_4X4 && max_tx >= TX_16X16 { + tx += r.read_bool(probs[1]) as usize; + if tx != TX_8X8 && max_tx >= TX_32X32 { + tx += r.read_bool(probs[2]) as usize; + } + } + tx + } else { + max_tx.min(TX_MODE_TO_BIGGEST_TX_SIZE[c.tx_mode as usize]) + } +} + +/// `read_inter_mode`. +fn read_inter_mode(r: &mut BoolDecoder, fc: &FrameContext, ctx: usize) -> u8 { + NEARESTMV + r.read_tree(&INTER_MODE_TREE, &fc.inter_mode[ctx]) +} + +/// `get_mode_context` (`vp9_decodemv.c:681`): the two nearest candidates' +/// modes fold into one of 5 contexts. +fn get_mode_context(st: &MiState, c: &InterBlockCtx<'_>, bsize: usize, row: usize, col: usize) -> usize { + let mut counter = 0usize; + for p in MV_REF_BLOCKS[bsize][..2].iter() { + if is_inside(c, row, col, *p) { + let mode = st + .at((row as i32 + p.0) as usize, (col as i32 + p.1) as usize) + .map_or(0u8, |m| m.mode); + counter += MODE_2_COUNTER[mode as usize] as usize; + } + } + COUNTER_TO_CONTEXT[counter] as usize +} + +/// `get_pred_context_switchable_interp` (`vp9_pred_common.h:69`). +fn switchable_interp_ctx(nb: Nb<'_>) -> usize { + let left_type = nb.left.map_or(SWITCHABLE_FILTERS, |m| m.interp_filter); + let above_type = nb.above.map_or(SWITCHABLE_FILTERS, |m| m.interp_filter); + if left_type == above_type { + left_type as usize + } else if left_type == SWITCHABLE_FILTERS { + above_type as usize + } else if above_type == SWITCHABLE_FILTERS { + left_type as usize + } else { + SWITCHABLE_FILTERS as usize + } +} + +/// `read_intra_block_mode_info` (the intra fallback inside an inter frame). +fn read_intra_block_mode_info(r: &mut BoolDecoder, fc: &FrameContext, info: &mut MiInfo) { + let bsize = info.sb_type; + match bsize { + 0 => { + for i in 0..4 { + info.bmi[i] = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[0]); + } + info.mode = info.bmi[3]; + } + 1 => { + let m0 = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[0]); + info.bmi[0] = m0; + info.bmi[2] = m0; + let m1 = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[0]); + info.bmi[1] = m1; + info.bmi[3] = m1; + info.mode = m1; + } + 2 => { + let m0 = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[0]); + info.bmi[0] = m0; + info.bmi[1] = m0; + let m2 = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[0]); + info.bmi[2] = m2; + info.bmi[3] = m2; + info.mode = m2; + } + _ => { + info.mode = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[SIZE_GROUP_LOOKUP[bsize] as usize]); + } + } + info.uv_mode = r.read_tree(&INTRA_MODE_TREE, &fc.uv_mode[info.mode as usize]); + info.interp_filter = SWITCHABLE_FILTERS; + info.ref_frame = [INTRA_FRAME, NO_REF_FRAME]; +} + +/// `is_inside` (`vp9_mvref_common.h:278`) — note it bounds rows by the FRAME +/// and columns by the TILE's end; there is no row bound against the tile. +fn is_inside(c: &InterBlockCtx<'_>, row: usize, col: usize, p: (i32, i32)) -> bool { + let r = row as i32 + p.0; + let cc = col as i32 + p.1; + !(r < 0 || cc < c.tile_col_start as i32 || r >= c.mi_rows as i32 || cc >= c.tile_col_end as i32) +} + +/// `get_sub_block_mv` (`vp9_mvref_common.h:224`). +fn get_sub_block_mv(cand: &MiInfo, which: usize, search_col: i32, block: i32) -> (i32, i32) { + if block >= 0 && cand.sb_type < 3 { + let b = IDX_N_COLUMN_TO_SUBBLOCK[block as usize][usize::from(search_col == 0)]; + cand.bmi_mv[b][which] + } else { + cand.mv[which] + } +} + +/// `use_mv_hp`: a small predictor keeps 1/8-pel precision. +fn use_mv_hp(mv: (i32, i32)) -> bool { + mv.0.abs() < MV_HP_THRESH && mv.1.abs() < MV_HP_THRESH +} + +/// `lower_mv_precision`: round the predictor to 1/4-pel when hp is not used. +fn lower_mv_precision(mv: &mut (i32, i32), allow_hp: bool) { + if !(allow_hp && use_mv_hp(*mv)) { + if mv.0 & 1 != 0 { + mv.0 += if mv.0 > 0 { -1 } else { 1 }; + } + if mv.1 & 1 != 0 { + mv.1 += if mv.1 > 0 { -1 } else { 1 }; + } + } +} + +/// `clamp_mv_ref`. +fn clamp_mv_ref(mv: &mut (i32, i32), c: &InterBlockCtx<'_>, row: usize, col: usize, bw: usize, bh: usize) { + // xd->mb_to_{left,right,top,bottom}_edge (vp9_onyxc_int.h:424-427). The + // right/bottom differences are SIGNED in libvpx (a wide/tall block on the + // frame's partial last row/column makes them negative), so they must not be + // computed in usize. + let left = -(col as i32 * 64); + let right = (c.mi_cols as i32 - bw as i32 - col as i32) * 64; + let top = -(row as i32 * 64); + let bottom = (c.mi_rows as i32 - bh as i32 - row as i32) * 64; + // `clamp_mv(mv, min_col, max_col, min_row, max_row)` (vp9_mv.h:47): the + // COLUMN takes the left/right edges and the ROW the top/bottom ones, and + // `mv.0` is the row (read_mv fills it from the vertical joint component). + mv.1 = mv.1.clamp(left - MV_BORDER, right + MV_BORDER); + mv.0 = mv.0.clamp(top - MV_BORDER, bottom + MV_BORDER); +} + +/// `ADD_MV_REF_LIST_EB`: returns true when the C `goto Done` fires. +fn add_mv_ref_list_eb( + mv: (i32, i32), + list: &mut [(i32, i32); MAX_MV_REF_CANDIDATES], + count: &mut usize, + early_break: bool, +) -> bool { + if *count > 0 { + if mv != list[0] { + list[*count] = mv; + *count += 1; + true + } else { + false + } + } else { + list[0] = mv; + *count = 1; + early_break + } +} + +/// `scale_mv` (the decoder's sign-flip-only variant, `vp9_mvref_common.h`). +fn scale_mv(cand: &MiInfo, which: usize, ref_frame: i8, sign_bias: [bool; 4]) -> (i32, i32) { + let mv = cand.mv[which]; + if sign_bias[cand.ref_frame[which] as usize] != sign_bias[ref_frame as usize] { + (-mv.0, -mv.1) + } else { + mv + } +} + +/// `dec_find_mv_refs` (`vp9_decodemv.c:495`): the candidate list, clamped. +/// Returns `(refmv_count, list)`. +#[allow(clippy::too_many_arguments)] +fn find_mv_refs( + st: &MiState, + c: &InterBlockCtx<'_>, + mode: u8, + ref_frame: i8, + bsize: usize, + row: usize, + col: usize, + block: i32, + bw: usize, + bh: usize, +) -> (usize, [(i32, i32); MAX_MV_REF_CANDIDATES]) { + let search = &MV_REF_BLOCKS[bsize]; + let early_break = mode != NEARMV; + let mvref_dbg = crate::mvdbg_enabled() && mode == NEWMV; + let mut list = [(0, 0); MAX_MV_REF_CANDIDATES]; + let mut count = 0usize; + let mut different_ref_found = false; + let mut done = false; + + let cell = |p: (i32, i32)| -> Option<&MiInfo> { + st.at((row as i32 + p.0) as usize, (col as i32 + p.1) as usize) + }; + + let mut i = 0usize; + if block >= 0 { + while i < 2 && !done { + let p = search[i]; + if is_inside(c, row, col, p) { + different_ref_found = true; + if let Some(cand) = cell(p) { + if cand.ref_frame[0] == ref_frame { + done = add_mv_ref_list_eb( + get_sub_block_mv(cand, 0, p.1, block), + &mut list, + &mut count, + early_break, + ); + } else if cand.ref_frame[1] == ref_frame { + done = add_mv_ref_list_eb( + get_sub_block_mv(cand, 1, p.1, block), + &mut list, + &mut count, + early_break, + ); + } + } + } + i += 1; + } + } + while i < MVREF_NEIGHBOURS && !done { + let p = search[i]; + if is_inside(c, row, col, p) { + different_ref_found = true; + if let Some(cand) = cell(p) { + if cand.ref_frame[0] == ref_frame { + done = add_mv_ref_list_eb(cand.mv[0], &mut list, &mut count, early_break); + } else if cand.ref_frame[1] == ref_frame { + done = add_mv_ref_list_eb(cand.mv[1], &mut list, &mut count, early_break); + } + } + } + i += 1; + } + + if !done { + if let Some(prev) = c.prev_mvs { + let e = prev[row * c.mi_cols + col]; + if e.ref_frame[0] == ref_frame { + done = add_mv_ref_list_eb(e.mv[0], &mut list, &mut count, early_break); + } else if e.ref_frame[1] == ref_frame { + done = add_mv_ref_list_eb(e.mv[1], &mut list, &mut count, early_break); + } + } + } + + if crate::mvdbg2_enabled() + && ((row == 8 && col == 104) || (row == 32 && col == 64) || (row == 8 && col == 32)) + { + for (i, p) in search.iter().enumerate() { + let ins = is_inside(c, row, col, *p); + let c2 = st.at((row as i32 + p.0) as usize, (col as i32 + p.1) as usize); + let qr = (row as i32 + p.0) as usize; + let qc = (col as i32 + p.1) as usize; + match c2 { + Some(cd) => eprintln!( + "MVC r={row} c={col} i={i} p={p:?} q=({qr} {qc}) idx={} inside={ins} ref0={} ref1={} mv0={:?} mv1={:?} inter={}", + qr * c.mi_cols + qc, + cd.ref_frame[0], cd.ref_frame[1], cd.mv[0], cd.mv[1], cd.is_inter + ), + None => eprintln!("MVC r={row} c={col} i={i} p={p:?} q=({qr} {qc}) inside={ins} none"), + } + } + } + if mvref_dbg { + eprintln!( + "MVREF r={row} c={col} bsize={bsize} mode={mode} n={count} l0={:?} l1={:?}", + list[0], list[1] + ); + } + if !done && different_ref_found { + for p in search.iter() { + if !is_inside(c, row, col, *p) { + continue; + } + let Some(cand) = cell(*p) else { continue }; + if !cand.is_inter { + continue; + } + if cand.ref_frame[0] != ref_frame { + done = add_mv_ref_list_eb( + scale_mv(cand, 0, ref_frame, c.sign_bias), + &mut list, + &mut count, + early_break, + ); + } + if done { + break; + } + if cand.ref_frame[1] > INTRA_FRAME + && cand.ref_frame[1] != ref_frame + && cand.mv[1] != cand.mv[0] + { + done = add_mv_ref_list_eb( + scale_mv(cand, 1, ref_frame, c.sign_bias), + &mut list, + &mut count, + early_break, + ); + } + } + } + + if !done { + if let Some(prev) = c.prev_mvs { + let e = prev[row * c.mi_cols + col]; + if e.ref_frame[0] != ref_frame && e.ref_frame[0] > INTRA_FRAME { + let mut mv = e.mv[0]; + if c.sign_bias[e.ref_frame[0] as usize] != c.sign_bias[ref_frame as usize] { + mv = (-mv.0, -mv.1); + } + done = add_mv_ref_list_eb(mv, &mut list, &mut count, early_break); + } + if !done + && e.ref_frame[1] > INTRA_FRAME + && e.ref_frame[1] != ref_frame + && e.mv[1] != e.mv[0] + { + let mut mv = e.mv[1]; + if c.sign_bias[e.ref_frame[1] as usize] != c.sign_bias[ref_frame as usize] { + mv = (-mv.0, -mv.1); + } + add_mv_ref_list_eb(mv, &mut list, &mut count, early_break); + } + } + } + + // `dec_find_mv_refs`' tail (vp9_decodemv.c:626): an early exit (`goto Done` + // -- either the second candidate was added, or `early_break` stopped us at + // the first) JUMPS OVER the mode-derived override and returns the count as + // accumulated; falling out of the loops applies the override, so a NEARMV + // block reports two candidates even when only one was found and the caller + // then reads the zeroed second slot. The list was memset to zero first, so + // that second slot is (0, 0), and the clamp covers the final count only. + let n = if done { + count + } else if mode == NEARMV { + MAX_MV_REF_CANDIDATES + } else { + 1 + }; + for k in 0..n { + clamp_mv_ref(&mut list[k], c, row, col, bw, bh); + } + (n, list) +} + +/// `append_sub8x8_mvs_for_idx` (`vp9_decodemv.c:620`). +#[allow(clippy::too_many_arguments)] +fn append_sub8x8_mvs_for_idx( + st: &MiState, + c: &InterBlockCtx<'_>, + info: &MiInfo, + bmode: u8, + block: usize, + rf: usize, + row: usize, + col: usize, + bw: usize, + bh: usize, +) -> (i32, i32) { + let bsize = info.sb_type; + match block { + 0 => { + let (n, list) = find_mv_refs(st, c, bmode, info.ref_frame[rf], bsize, row, col, 0, bw, bh); + list[n - 1] + } + 1 | 2 => { + if bmode == NEARESTMV { + info.bmi_mv[0][rf] + } else { + let (_n, list) = + find_mv_refs(st, c, bmode, info.ref_frame[rf], bsize, row, col, block as i32, bw, bh); + let mut out = (0, 0); + for m in list.iter() { + if info.bmi_mv[0][rf] != *m { + out = *m; + break; + } + } + out + } + } + _ => { + if bmode == NEARESTMV { + info.bmi_mv[2][rf] + } else { + if info.bmi_mv[2][rf] != info.bmi_mv[1][rf] { + info.bmi_mv[1][rf] + } else if info.bmi_mv[2][rf] != info.bmi_mv[0][rf] { + info.bmi_mv[0][rf] + } else { + let (_n, list) = find_mv_refs( + st, + c, + bmode, + info.ref_frame[rf], + bsize, + row, + col, + block as i32, + bw, + bh, + ); + let mut out = (0, 0); + for m in list.iter() { + if info.bmi_mv[2][rf] != *m { + out = *m; + break; + } + } + out + } + } + } + } +} + +/// `read_mv_component` (`vp9_decodemv.c:246`). +fn read_mv_component(r: &mut BoolDecoder, fc: &FrameContext, comp: usize, use_hp: bool) -> i32 { + let dbg = crate::interdump_enabled(); + if dbg { + eprintln!("MVF c{comp} sign"); + } + let sign = r.read_bool(fc.nmv_sign[comp]); + if dbg { + eprintln!("MVF c{comp} cls"); + } + let mv_class = r.read_tree(&MV_CLASS_TREE, &fc.nmv_classes[comp]) as i32; + let class0 = mv_class == 0; + let mut d = 0i32; + let mut mag; + if dbg { + eprintln!("MVF c{comp} class={mv_class}"); + } + if class0 { + if dbg { + eprintln!("MVF c{comp} class0bit"); + } + d = r.read_bool(fc.nmv_class0[comp][0]) as i32; + mag = 0; + } else { + let n = mv_class + CLASS0_BITS - 1; + for i in 0..n { + if dbg { + eprintln!("MVF c{comp} bits[{i}]"); + } + d |= (r.read_bool(fc.nmv_bits[comp][i as usize]) as i32) << i; + } + mag = CLASS0_SIZE << (mv_class + 2); + } + if dbg { + eprintln!("MVF c{comp} fp"); + } + let fr = if class0 { + r.read_tree(&MV_FP_TREE, &fc.nmv_class0_fp[comp][d as usize]) + } else { + r.read_tree(&MV_FP_TREE, &fc.nmv_fp[comp]) + } as i32; + let hp = if use_hp { + if dbg { + eprintln!("MVF c{comp} hp"); + } + r.read_bool(if class0 { + fc.nmv_class0_hp[comp] + } else { + fc.nmv_hp[comp] + }) as i32 + } else { + 1 + }; + mag += ((d << 3) | (fr << 1) | hp) + 1; + if sign { + -mag + } else { + mag + } +} + +/// `read_mv`: returns `(mv, diff)`. +fn read_mv( + r: &mut BoolDecoder, + pred: (i32, i32), + fc: &FrameContext, + allow_hp: bool, +) -> ((i32, i32), (i32, i32)) { + let joint = r.read_tree(&MV_JOINT_TREE, &fc.nmv_joints); + let use_hp = allow_hp && use_mv_hp(pred); + if crate::interdump_enabled() { + eprintln!("MVJ joint={joint} use_hp={use_hp} pred={pred:?}"); + } + // mv_joint_vertical = joint & 2, mv_joint_horizontal = joint & 1. + let mut diff = (0i32, 0i32); + if joint & 2 != 0 { + diff.0 = read_mv_component(r, fc, 0, use_hp); + } + if joint & 1 != 0 { + diff.1 = read_mv_component(r, fc, 1, use_hp); + } + ((pred.0 + diff.0, pred.1 + diff.1), diff) +} + +/// `assign_mv`: returns `(mv, diff)`; only `NEWMV` consumes bits. +fn assign_mv( + r: &mut BoolDecoder, + fc: &FrameContext, + mode: u8, + ref_mv: &[(i32, i32); 2], + near_nearest: &[(i32, i32); 2], + is_compound: usize, + allow_hp: bool, +) -> crate::Result<([(i32, i32); 2], [(i32, i32); 2])> { + let mut mv = [(0, 0); 2]; + let mut diff = [(0, 0); 2]; + match mode { + NEWMV => { + for i in 0..1 + is_compound { + let (m, d) = read_mv(r, ref_mv[i], fc, allow_hp); + mv[i] = m; + diff[i] = d; + } + } + NEARMV | NEARESTMV => mv = *near_nearest, + ZEROMV => {} + other => { + return Err(crate::Error::corrupt(format!( + "VP9 assign_mv: invalid inter mode {other}" + ))) + } + } + Ok((mv, diff)) +} + +/// `read_block_reference_mode`. +fn read_block_reference_mode( + r: &mut BoolDecoder, + c: &InterBlockCtx<'_>, + fc: &FrameContext, + nb: Nb<'_>, +) -> u8 { + if c.ifs.reference_mode == REFERENCE_MODE_SELECT { + let ctx = reference_mode_context(c, nb); + u8::from(r.read_bool(fc.comp_inter[ctx])) + } else { + c.ifs.reference_mode + } +} + +/// `vp9_get_reference_mode_context` (`vp9_pred_common.c`). +fn reference_mode_context(c: &InterBlockCtx<'_>, nb: Nb<'_>) -> usize { + let fixed = c.ifs.comp_fixed_ref; + let has_second = |m: &MiInfo| m.ref_frame[1] > INTRA_FRAME; + match (nb.above, nb.left) { + (Some(a), Some(l)) => { + if !has_second(a) && !has_second(l) { + usize::from((a.ref_frame[0] == fixed) ^ (l.ref_frame[0] == fixed)) + } else if !has_second(a) { + 2 + usize::from(a.ref_frame[0] == fixed || !a.is_inter) + } else if !has_second(l) { + 2 + usize::from(l.ref_frame[0] == fixed || !l.is_inter) + } else { + 4 + } + } + (Some(m), None) | (None, Some(m)) => { + if !has_second(m) { + usize::from(m.ref_frame[0] == fixed) + } else { + 3 + } + } + (None, None) => 1, + } +} + +/// `vp9_get_pred_context_comp_ref_p` (`vp9_pred_common.c`). +fn pred_context_comp_ref_p(c: &InterBlockCtx<'_>, nb: Nb<'_>) -> usize { + let fixed = c.ifs.comp_fixed_ref; + let var = c.ifs.comp_var_ref; + let var_ref_idx = usize::from(!c.sign_bias[fixed as usize]); + let has_second = |m: &MiInfo| m.ref_frame[1] > INTRA_FRAME; + let vr = |m: &MiInfo| -> i8 { + if has_second(m) { + m.ref_frame[var_ref_idx] + } else { + m.ref_frame[0] + } + }; + match (nb.above, nb.left) { + (Some(a), Some(l)) => { + if !a.is_inter && !l.is_inter { + 2 + } else if !a.is_inter || !l.is_inter { + let e = if !a.is_inter { l } else { a }; + if !has_second(e) { + 1 + 2 * usize::from(e.ref_frame[0] != var[1]) + } else { + 1 + 2 * usize::from(e.ref_frame[var_ref_idx] != var[1]) + } + } else { + let a_sg = !has_second(a); + let l_sg = !has_second(l); + let vrfa = vr(a); + let vrfl = vr(l); + if vrfa == vrfl && var[1] == vrfa { + 0 + } else if l_sg && a_sg { + if (vrfa == fixed && vrfl == var[0]) || (vrfl == fixed && vrfa == var[0]) { + 4 + } else if vrfa == vrfl { + 3 + } else { + 1 + } + } else if l_sg || a_sg { + let vrfc = if l_sg { vrfa } else { vrfl }; + let rfs = if a_sg { vrfa } else { vrfl }; + if vrfc == var[1] && rfs != var[1] { + 1 + } else if rfs == var[1] && vrfc != var[1] { + 2 + } else { + 4 + } + } else if vrfa == vrfl { + 4 + } else { + 2 + } + } + } + (Some(e), None) | (None, Some(e)) => { + if !e.is_inter { + 2 + } else if has_second(e) { + 4 * usize::from(e.ref_frame[var_ref_idx] != var[1]) + } else { + 3 * usize::from(e.ref_frame[0] != var[1]) + } + } + (None, None) => 2, + } +} + +/// `vp9_get_pred_context_single_ref_p1` (`vp9_pred_common.c`). +fn pred_context_single_ref_p1(nb: Nb<'_>) -> usize { + let has_second = |m: &MiInfo| m.ref_frame[1] > INTRA_FRAME; + match (nb.above, nb.left) { + (Some(a), Some(l)) => { + if !a.is_inter && !l.is_inter { + 2 + } else if !a.is_inter || !l.is_inter { + let e = if !a.is_inter { l } else { a }; + if !has_second(e) { + 4 * usize::from(e.ref_frame[0] == LAST_FRAME) + } else { + 1 + usize::from(e.ref_frame[0] == LAST_FRAME || e.ref_frame[1] == LAST_FRAME) + } + } else { + let a2 = has_second(a); + let l2 = has_second(l); + if a2 && l2 { + 1 + usize::from( + a.ref_frame[0] == LAST_FRAME + || a.ref_frame[1] == LAST_FRAME + || l.ref_frame[0] == LAST_FRAME + || l.ref_frame[1] == LAST_FRAME, + ) + } else if a2 || l2 { + let rfs = if !a2 { a.ref_frame[0] } else { l.ref_frame[0] }; + let crf1 = if a2 { a.ref_frame[0] } else { l.ref_frame[0] }; + let crf2 = if a2 { a.ref_frame[1] } else { l.ref_frame[1] }; + if rfs == LAST_FRAME { + 3 + usize::from(crf1 == LAST_FRAME || crf2 == LAST_FRAME) + } else { + usize::from(crf1 == LAST_FRAME || crf2 == LAST_FRAME) + } + } else { + 2 * usize::from(a.ref_frame[0] == LAST_FRAME) + + 2 * usize::from(l.ref_frame[0] == LAST_FRAME) + } + } + } + (Some(e), None) | (None, Some(e)) => { + if !e.is_inter { + 2 + } else if !has_second(e) { + 4 * usize::from(e.ref_frame[0] == LAST_FRAME) + } else { + 1 + usize::from(e.ref_frame[0] == LAST_FRAME || e.ref_frame[1] == LAST_FRAME) + } + } + (None, None) => 2, + } +} + +/// `vp9_get_pred_context_single_ref_p2` (`vp9_pred_common.c`). +fn pred_context_single_ref_p2(nb: Nb<'_>) -> usize { + let has_second = |m: &MiInfo| m.ref_frame[1] > INTRA_FRAME; + match (nb.above, nb.left) { + (Some(a), Some(l)) => { + if !a.is_inter && !l.is_inter { + 2 + } else if !a.is_inter || !l.is_inter { + let e = if !a.is_inter { l } else { a }; + if !has_second(e) { + if e.ref_frame[0] == LAST_FRAME { + 3 + } else { + 4 * usize::from(e.ref_frame[0] == GOLDEN_FRAME) + } + } else { + 1 + 2 * usize::from( + e.ref_frame[0] == GOLDEN_FRAME || e.ref_frame[1] == GOLDEN_FRAME, + ) + } + } else { + let a2 = has_second(a); + let l2 = has_second(l); + if a2 && l2 { + if a.ref_frame[0] == l.ref_frame[0] && a.ref_frame[1] == l.ref_frame[1] { + 3 * usize::from( + a.ref_frame[0] == GOLDEN_FRAME + || a.ref_frame[1] == GOLDEN_FRAME + || l.ref_frame[0] == GOLDEN_FRAME + || l.ref_frame[1] == GOLDEN_FRAME, + ) + } else { + 2 + } + } else if a2 || l2 { + let rfs = if !a2 { a.ref_frame[0] } else { l.ref_frame[0] }; + let crf1 = if a2 { a.ref_frame[0] } else { l.ref_frame[0] }; + let crf2 = if a2 { a.ref_frame[1] } else { l.ref_frame[1] }; + let crf_golden = usize::from(crf1 == GOLDEN_FRAME || crf2 == GOLDEN_FRAME); + if rfs == GOLDEN_FRAME { + 3 + crf_golden + } else if rfs == ALTREF_FRAME { + crf_golden + } else { + 1 + 2 * crf_golden + } + } else if a.ref_frame[0] == LAST_FRAME && l.ref_frame[0] == LAST_FRAME { + 3 + } else if a.ref_frame[0] == LAST_FRAME || l.ref_frame[0] == LAST_FRAME { + let edge0 = if a.ref_frame[0] == LAST_FRAME { + l.ref_frame[0] + } else { + a.ref_frame[0] + }; + 4 * usize::from(edge0 == GOLDEN_FRAME) + } else { + 2 * usize::from(a.ref_frame[0] == GOLDEN_FRAME) + + 2 * usize::from(l.ref_frame[0] == GOLDEN_FRAME) + } + } + } + (Some(e), None) | (None, Some(e)) => { + if !e.is_inter || (e.ref_frame[0] == LAST_FRAME && !has_second(e)) { + 2 + } else if !has_second(e) { + 4 * usize::from(e.ref_frame[0] == GOLDEN_FRAME) + } else { + 3 * usize::from(e.ref_frame[0] == GOLDEN_FRAME || e.ref_frame[1] == GOLDEN_FRAME) + } + } + (None, None) => 2, + } +} + +/// `read_ref_frames`. +fn read_ref_frames( + r: &mut BoolDecoder, + c: &InterBlockCtx<'_>, + fc: &FrameContext, + nb: Nb<'_>, + segment_id: u8, + out: &mut [i8; 2], +) { + if seg_feature(c.seg, segment_id, SEG_LVL_REF_FRAME) { + out[0] = c.seg.feature_data[segment_id as usize][SEG_LVL_REF_FRAME] as i8; + out[1] = NO_REF_FRAME; + return; + } + let mode = read_block_reference_mode(r, c, fc, nb); + if mode == COMPOUND_REFERENCE { + let idx = usize::from(c.sign_bias[c.ifs.comp_fixed_ref as usize]); + let ctx = pred_context_comp_ref_p(c, nb); + let bit = usize::from(r.read_bool(fc.comp_ref[ctx])); + out[idx] = c.ifs.comp_fixed_ref; + out[1 - idx] = c.ifs.comp_var_ref[bit]; + } else { + let ctx0 = pred_context_single_ref_p1(nb); + let bit0 = r.read_bool(fc.single_ref[ctx0][0]); + if bit0 { + let ctx1 = pred_context_single_ref_p2(nb); + let bit1 = r.read_bool(fc.single_ref[ctx1][1]); + out[0] = if bit1 { ALTREF_FRAME } else { GOLDEN_FRAME }; + } else { + out[0] = LAST_FRAME; + } + out[1] = NO_REF_FRAME; + } +} + +/// `read_inter_block_mode_info` (`vp9_decodemv.c:702`). +#[allow(clippy::too_many_arguments)] +fn read_inter_block_mode_info( + r: &mut BoolDecoder, + st: &MiState, + c: &InterBlockCtx<'_>, + fc: &FrameContext, + info: &mut MiInfo, + nb: Nb<'_>, + row: usize, + col: usize, + partition: u8, +) -> crate::Result<()> { + let bsize = info.sb_type; + let mut best_ref_mvs = [(0, 0); 2]; + read_ref_frames(r, c, fc, nb, info.segment, &mut info.ref_frame); + let is_compound = usize::from(info.ref_frame[1] > INTRA_FRAME); + let inter_mode_ctx = get_mode_context(st, c, bsize, row, col); + + if seg_feature(c.seg, info.segment, SEG_LVL_SKIP) { + info.mode = ZEROMV; + if bsize < 3 { + return Err(crate::Error::corrupt( + "VP9 segment skip feature on a sub-8x8 block", + )); + } + } else if bsize >= 3 { + info.mode = read_inter_mode(r, fc, inter_mode_ctx); + } + + info.interp_filter = if c.frame_interp == SWITCHABLE { + let ictx = switchable_interp_ctx(nb); + if crate::interdump_enabled() { + eprintln!( + "SWI ctx={} p0={} p1={}", + ictx, fc.switchable_interp[ictx][0], fc.switchable_interp[ictx][1] + ); + } + let t = r.read_tree(&SWITCHABLE_INTERP_TREE, &fc.switchable_interp[ictx]); + if crate::interdump_enabled() { + eprintln!("SWItype {t}"); + } + t + } else { + c.frame_interp + }; + + // Block dimensions in 8x8 units for the MV clamp (libvpx's bw/bh from + // `1 << (bwl - 1)`: a sub-8x8 shape occupies a whole 8x8 cell). + let bw = if bsize < 3 { + 1 + } else { + 1usize << (B_WIDTH_LOG2_LOOKUP[bsize] as usize - 1) + }; + let bh = if bsize < 3 { + 1 + } else { + 1usize << (B_HEIGHT_LOG2_LOOKUP[bsize] as usize - 1) + }; + + if bsize < 3 { + // PARTITION_VERT clears the wide bit, PARTITION_HORZ the tall one. + let num_4x4_w = 1usize << u32::from(partition & 2 == 0); + let num_4x4_h = 1usize << u32::from(partition & 1 == 0); + let mut got_mv_refs_for_new = false; + let mut best_sub8x8 = [(0, 0); 2]; + let mut b_mode = info.mode; + let mut idy = 0usize; + while idy < 2 { + let mut idx = 0usize; + while idx < 2 { + let j = idy * 2 + idx; + b_mode = read_inter_mode(r, fc, inter_mode_ctx); + info.bmi[j] = b_mode; + if b_mode == NEARESTMV || b_mode == NEARMV { + for rf in 0..1 + is_compound { + best_sub8x8[rf] = append_sub8x8_mvs_for_idx( + st, c, info, b_mode, j, rf, row, col, bw, bh, + ); + } + } else if b_mode == NEWMV && !got_mv_refs_for_new { + for rf in 0..1 + is_compound { + let frame = info.ref_frame[rf]; + let (_n, list) = + find_mv_refs(st, c, NEWMV, frame, bsize, row, col, -1, bw, bh); + let mut mv = list[0]; + lower_mv_precision(&mut mv, c.allow_hp); + best_ref_mvs[rf] = mv; + got_mv_refs_for_new = true; + } + } + let (mv, diff) = assign_mv( + r, + fc, + b_mode, + &best_ref_mvs, + &best_sub8x8, + is_compound, + c.allow_hp, + )?; + info.bmi_mv[j] = mv; + info.mv_diff = diff; + if num_4x4_h == 2 { + info.bmi_mv[j + 2] = info.bmi_mv[j]; + } + if num_4x4_w == 2 { + info.bmi_mv[j + 1] = info.bmi_mv[j]; + } + idx += num_4x4_w; + } + idy += num_4x4_h; + } + info.mode = b_mode; + info.mv = info.bmi_mv[3]; + } else { + if info.mode != ZEROMV { + for rf in 0..1 + is_compound { + let frame = info.ref_frame[rf]; + let (n, list) = find_mv_refs(st, c, info.mode, frame, bsize, row, col, -1, bw, bh); + let mut mv = list[n - 1]; + lower_mv_precision(&mut mv, c.allow_hp); + best_ref_mvs[rf] = mv; + } + } + let (mv, diff) = assign_mv( + r, + fc, + info.mode, + &best_ref_mvs, + &best_ref_mvs, + is_compound, + c.allow_hp, + )?; + info.mv = mv; + info.mv_diff = diff; + } + Ok(()) +} diff --git a/crates/ec-vp9/src/lib.rs b/crates/ec-vp9/src/lib.rs index e0c9ceb2..8d3f9771 100644 --- a/crates/ec-vp9/src/lib.rs +++ b/crates/ec-vp9/src/lib.rs @@ -19,6 +19,7 @@ pub mod bool; pub mod decode; pub mod header; +pub(crate) mod inter; pub mod intra; pub mod loopfilter; pub mod modes; @@ -45,3 +46,35 @@ pub(crate) fn trace_enabled() -> bool { _ => true, } } + +/// Cached `getenv` probe: `EC_VP9_*` gates are consulted per block, per MV +/// component and per switchable-interp read, and `std::env::var_os` locks std's +/// ENV lock, so each gate resolves once per process and the hot path is a +/// single relaxed atomic load (see `trace_enabled`). +macro_rules! cached_gate { + ($fn_name:ident, $env:literal) => { + pub(crate) fn $fn_name() -> bool { + use std::sync::atomic::{AtomicU8, Ordering}; + static STATE: AtomicU8 = AtomicU8::new(0); + match STATE.load(Ordering::Relaxed) { + 0 => { + let on = std::env::var_os($env).is_some(); + STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed); + on + } + 1 => false, + _ => true, + } + } + }; +} + +// Per-block dump gate for the inter-syntax lane (scratch harnesses); +// a candidate-list dump (`mode == NEWMV` only); +// a search-position cell + grid-store dump; and a post-compressed-header +// MV probability table dump. (Plain comments: a doc comment on a macro +// invocation is an "unused doc comment" warning.) +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"); diff --git a/crates/ec-vp9/src/modes.rs b/crates/ec-vp9/src/modes.rs index 7fa5db7e..e0b374d3 100644 --- a/crates/ec-vp9/src/modes.rs +++ b/crates/ec-vp9/src/modes.rs @@ -16,6 +16,21 @@ pub(crate) struct MiInfo { pub uv_mode: u8, /// Per-4x4 sub-block y modes, valid when `sb_type < 3` (BLOCK_8X8). pub bmi: [u8; 4], + /// `is_inter_block(mi)`: `ref_frame[0] > INTRA_FRAME`. + pub is_inter: bool, + /// `mi->ref_frame[0]`/`[1]`: `INTRA_FRAME` (0), `LAST`/`GOLDEN`/`ALTREF` + /// (1..3), `NO_REF_FRAME` (-1). + pub ref_frame: [i8; 2], + /// `mi->mv[..]`: the refreshed MV (predictor + codeword diff). + pub mv: [(i32, i32); 2], + /// The raw MV codeword diff of each reference frame. + pub mv_diff: [(i32, i32); 2], + /// `mi->bmi[j].as_mv`. + pub bmi_mv: [[(i32, i32); 2]; 4], + /// `mi->seg_id_predicted`. + pub seg_id_predicted: bool, + /// `mi->interp_filter`. + pub interp_filter: u8, } /// The mode-info grid and the partition contexts of one tile pass. @@ -42,7 +57,12 @@ impl MiState { } } - fn above_mi(&self, row: usize, col: usize, tile_row_start: usize) -> Option<&MiInfo> { + /// The grid cell at an absolute (row, col), `None` when not decoded yet. + pub(crate) fn at(&self, row: usize, col: usize) -> Option<&MiInfo> { + self.grid.get(row * self.mi_cols + col).and_then(|c| c.as_ref()) + } + + pub(crate) fn above_mi(&self, row: usize, col: usize, tile_row_start: usize) -> Option<&MiInfo> { if row > tile_row_start { self.grid[(row - 1) * self.mi_cols + col].as_ref() } else { @@ -50,7 +70,7 @@ impl MiState { } } - fn left_mi(&self, row: usize, col: usize, tile_col_start: usize) -> Option<&MiInfo> { + pub(crate) fn left_mi(&self, row: usize, col: usize, tile_col_start: usize) -> Option<&MiInfo> { if col > tile_col_start { self.grid[row * self.mi_cols + col - 1].as_ref() } else { @@ -213,6 +233,15 @@ pub(crate) fn read_intra_frame_mode_info( mode: DC_PRED, uv_mode: DC_PRED, bmi: [DC_PRED; 4], + is_inter: false, + ref_frame: [0, -1], + mv: [(0, 0); 2], + mv_diff: [(0, 0); 2], + bmi_mv: [[(0, 0); 2]; 4], + seg_id_predicted: false, + // read_intra_block_mode_info sets this so a later + // get_pred_context_switchable_interp never sees a stale filter. + interp_filter: 3, }; match sb_type { 0 => { diff --git a/crates/ec-vp9/src/tables/gen_tables.rs b/crates/ec-vp9/src/tables/gen_tables.rs index a7deca3f..e3debafc 100644 --- a/crates/ec-vp9/src/tables/gen_tables.rs +++ b/crates/ec-vp9/src/tables/gen_tables.rs @@ -1427,3 +1427,67 @@ pub(crate) const KF_UV_MODE_PROB: [u8; 90] = [ 12, 32, 145, 195, 142, 32, 38, 86, 116, 12, 64, 120, 140, 125, 49, 115, 121, 102, 19, 66, 162, 182, 122, 35, 59, 128, ]; + +// --------------------------------------------------------------------------- +// Inter-frame tables (libvpx v1.15: common/vp9_entropymode.c, +// common/vp9_entropymv.c, common/vp9_mvref_common.h, common/vp9_common_data.c). +// --------------------------------------------------------------------------- + +/// `vp9_inter_mode_tree`; leaves are `mode - NEARESTMV` (0..3). +pub(crate) const INTER_MODE_TREE: [i8; 6] = [-2, 2, 0, 4, -1, -3]; +/// `vp9_switchable_interp_tree` = `{ -EIGHTTAP, 2, -EIGHTTAP_SMOOTH, +/// -EIGHTTAP_SHARP }`. libvpx's filter constants are #defines with +/// `EIGHTTAP = 0`, `EIGHTTAP_SMOOTH = 1`, `EIGHTTAP_SHARP = 2` +/// (vp9/common/vp9_filter.h:23) — NOT the spec's naming order, so the tree is +/// `{0, 2, -1, -2}` and the leaves are the coded `interp_filter` values. +pub(crate) const SWITCHABLE_INTERP_TREE: [i8; 4] = [0, 2, -1, -2]; +/// `vp9_mv_joint_tree`. +pub(crate) const MV_JOINT_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3]; +/// `vp9_mv_class_tree`. +pub(crate) const MV_CLASS_TREE: [i8; 20] = [ + 0, 2, -1, 4, 6, 8, -2, -3, 10, 12, -4, -5, -6, 14, 16, 18, -7, -8, -9, -10, +]; +/// `vp9_mv_fp_tree`. +pub(crate) const MV_FP_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3]; +/// `default_if_y_probs`, `[BLOCK_SIZE_GROUPS][INTRA_MODES - 1]`. +pub(crate) const DEFAULT_Y_MODE_PROBS: [u8; 36] = [ + 65, 32, 18, 144, 162, 194, 41, 51, 98, 132, 68, 18, 165, 217, 196, 45, 40, 78, 173, 80, 19, 176, + 240, 193, 64, 35, 46, 221, 135, 38, 194, 248, 121, 96, 85, 29, +]; +/// `default_inter_mode_probs`, `[INTER_MODE_CONTEXTS][INTER_MODES - 1]`. +pub(crate) const DEFAULT_INTER_MODE_PROBS: [u8; 21] = [ + 2, 173, 34, 7, 145, 85, 7, 166, 63, 7, 94, 66, 8, 64, 46, 17, 81, 31, 25, 29, 30, +]; +/// `default_intra_inter_p`. +pub(crate) const DEFAULT_INTRA_INTER_PROBS: [u8; 4] = [9, 102, 187, 225]; +/// `default_comp_inter_p`. +pub(crate) const DEFAULT_COMP_INTER_PROBS: [u8; 5] = [239, 183, 119, 96, 41]; +/// `default_single_ref_p`, `[REF_CONTEXTS][2]`. +pub(crate) const DEFAULT_SINGLE_REF_PROBS: [u8; 10] = + [33, 16, 77, 74, 142, 142, 172, 170, 238, 247]; +/// `default_comp_ref_p`, flat `[REF_CONTEXTS]`. +pub(crate) const DEFAULT_COMP_REF_PROBS: [u8; 5] = [50, 126, 123, 221, 226]; +/// `default_switchable_interp_prob`, `[SWITCHABLE_FILTER_CONTEXTS][2]`. +pub(crate) const DEFAULT_SWITCHABLE_INTERP_PROBS: [u8; 8] = [235, 162, 36, 255, 34, 3, 149, 144]; +/// `default_nmv_context`: joints, then both components. +pub(crate) const DEFAULT_NMVC_JOINTS: [u8; 3] = [32, 64, 96]; +pub(crate) const DEFAULT_NMVC_SIGN: [u8; 2] = [128, 128]; +pub(crate) const DEFAULT_NMVC_CLASSES: [u8; 20] = [ + 224, 144, 192, 168, 192, 176, 192, 198, 198, 245, 216, 128, 176, 160, 176, 176, 192, 198, 198, + 208, +]; +pub(crate) const DEFAULT_NMVC_CLASS0: [u8; 2] = [216, 208]; +pub(crate) const DEFAULT_NMVC_BITS: [u8; 20] = [ + 136, 140, 148, 160, 176, 192, 224, 234, 234, 240, 136, 140, 148, 160, 176, 192, 224, 234, 234, + 240, +]; +pub(crate) const DEFAULT_NMVC_CLASS0_FP: [u8; 12] = + [128, 128, 64, 96, 112, 64, 128, 128, 64, 96, 112, 64]; +pub(crate) const DEFAULT_NMVC_FP: [u8; 6] = [64, 96, 64, 64, 96, 64]; +pub(crate) const DEFAULT_NMVC_CLASS0_HP: [u8; 2] = [160, 160]; +pub(crate) const DEFAULT_NMVC_HP: [u8; 2] = [128, 128]; +/// `mode_2_counter`, indexed by `PREDICTION_MODE`. +pub(crate) const MODE_2_COUNTER: [u8; 14] = [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 3, 1]; +/// `counter_to_context`. +pub(crate) const COUNTER_TO_CONTEXT: [u8; 19] = + [2, 3, 4, 1, 3, 9, 0, 9, 9, 5, 5, 9, 5, 9, 9, 9, 9, 9, 6]; diff --git a/crates/ec-vp9/src/tokens.rs b/crates/ec-vp9/src/tokens.rs index 1859b72d..a40ed6f1 100644 --- a/crates/ec-vp9/src/tokens.rs +++ b/crates/ec-vp9/src/tokens.rs @@ -51,7 +51,8 @@ pub(crate) struct CoeffBlock { } /// `decode_coefs`, verbatim port. `dq` is `[dc, ac]`; plane 0 is luma, -/// chroma is 1; the ref axis is fixed at 0 (intra). +/// chroma is 1. `is_inter` selects the coefficient-probability ref axis +/// (libvpx `get_coef_probs`: `coef_probs[tx][plane][ref]`). pub(crate) fn decode_coefs( r: &mut BoolDecoder, plane_type: usize, @@ -61,6 +62,7 @@ pub(crate) fn decode_coefs( scan: &[i16], nb: &[i16], probs4d: &[[[[[u8; 3]; 6]; 6]; 2]; 2], + is_inter: bool, #[allow(unused_variables)] pos: (usize, usize), #[allow(unused_variables)] plane: usize, ) -> CoeffBlock { @@ -74,7 +76,7 @@ pub(crate) fn decode_coefs( let dq_shift = usize::from(tx_size == TX_32X32); let mut dqv = dequant[0] as i32; let mut band = band_at(tx_size, c); - let mut prob: &[u8; 3] = &probs4d[plane_type][0][band][ctx]; + let mut prob: &[u8; 3] = &probs4d[plane_type][usize::from(is_inter)][band][ctx]; if std::env::var_os("EC_VP9_DBG").is_some() && plane_type == 0 && ctx == 0 && band == 0 { eprintln!("DBG coefs tx={tx_size} dq={dequant:?} ctx={ctx} band={band} prob={prob:?}"); } @@ -95,7 +97,7 @@ pub(crate) fn decode_coefs( } ctx = get_coef_context(nb, &token_cache, c); band = band_at(tx_size, c); - prob = &probs4d[plane_type][0][band][ctx]; + prob = &probs4d[plane_type][usize::from(is_inter)][band][ctx]; } let mut v: i32; if r.read_bool(prob[2]) { @@ -142,7 +144,7 @@ pub(crate) fn decode_coefs( if c < max_eob { ctx = get_coef_context(nb, &token_cache, c); band = band_at(tx_size, c); - prob = &probs4d[plane_type][0][band][ctx]; + prob = &probs4d[plane_type][usize::from(is_inter)][band][ctx]; } dqv = dequant[1] as i32; } diff --git a/crates/ec-vp9/tests/ivf.rs b/crates/ec-vp9/tests/ivf.rs index 42ee5b9e..161ff63b 100644 --- a/crates/ec-vp9/tests/ivf.rs +++ b/crates/ec-vp9/tests/ivf.rs @@ -49,6 +49,7 @@ pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec) { } /// Root of the workspace checkout this test runs in (crates/ec-vp9/../..). +#[allow(dead_code)] // shared by every test binary that does `mod ivf` pub fn fixture_dir() -> Option { let bitstreams = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../fixtures/bitstreams"); diff --git a/crates/ec-vp9/tests/scratch_interdump.rs b/crates/ec-vp9/tests/scratch_interdump.rs new file mode 100644 index 00000000..d9e57c19 --- /dev/null +++ b/crates/ec-vp9/tests/scratch_interdump.rs @@ -0,0 +1,70 @@ +//! [scratch] Inter-frame syntax dump + count gate. +//! +//! Parses every frame of `INTER_IVF` (default `/tmp/inter1.ivf`, the clean +//! single-tile stream the pinned counts refer to). Keyframes decode as usual; +//! inter frames are parsed syntax-only (no reconstruction). With +//! `EC_VP9_INTERDUMP=1` every block prints one `MODE` line in the oracle's +//! shape, for a by-index diff. Point it at the two-tile-column stream +//! (`INTER_IVF=/tmp/inter.ivf INTER_EXPECT=none`) to exercise the failing- +//! keyframe path: that stream's keyframe desyncs its tile reader and the test +//! is expected to fail there. +//! +//! This is a real gate, not a printer: +//! - any frame error fails the test (keyframe failures are propagated too, +//! because a half-updated frame context would make later dumps meaningless); +//! - every inter frame's mode-info block count must equal `INTER_EXPECT` +//! (default `1213,1851` - the pinned counts of the single-tile fixture +//! `/tmp/inter1.ivf`, sha256 376532734662ba5faba4c4e97a5aac915ce429c11701bcf6 +//! 6439b61a77388fa8; set `INTER_EXPECT=none` for a different stream); +//! - the crate already asserts `overreads() == 0` per tile reader at the end of +//! each tile (decode.rs, "tile bool decoder desync"), which is what would fire +//! if the walk read past the tile's last bool. +//! +//! ```text +//! INTER_IVF= EC_VP9_INTERDUMP=1 \ +//! cargo test -p ec-vp9 --test scratch_interdump -- --nocapture +//! ``` +mod ivf; + +use ec_vp9::decode::Decoder; + +#[test] +fn inter_syntax_dump() { + let path = std::env::var("INTER_IVF").unwrap_or_else(|_| "/tmp/inter1.ivf".to_string()); + let expect_raw = std::env::var("INTER_EXPECT").unwrap_or_else(|_| "1213,1851".to_string()); + let expect: Vec = if expect_raw == "none" { + Vec::new() + } else { + expect_raw + .split(',') + .map(|t| t.trim().parse().expect("INTER_EXPECT entries are block counts")) + .collect() + }; + let Ok(bytes) = std::fs::read(&path) else { + println!("SKIP: fixture {path} not found - set INTER_IVF= to run"); + return; + }; + let (_fourcc, w, h, frames) = ivf::parse_ivf(&bytes); + println!("IVF {w}x{h} frames={}", frames.len()); + let mut dec = Decoder::new(); + let mut counts = Vec::new(); + for (i, f) in frames.iter().enumerate() { + match dec.decode_syntax(&f.data) { + Ok(()) => { + let n = dec.last_frame_blocks(); + println!("FRAME {i} parsed blocks={n}"); + if i > 0 { + counts.push(n); + } + } + Err(e) => panic!("FRAME {i} failed: {e:?}"), + } + } + if !expect.is_empty() { + assert_eq!( + counts, expect, + "inter-frame mode-info block counts differ from INTER_EXPECT" + ); + println!("block-count gate passed for {counts:?}"); + } +} diff --git a/lanes/vp9inter.report.md b/lanes/vp9inter.report.md new file mode 100644 index 00000000..9de592c8 --- /dev/null +++ b/lanes/vp9inter.report.md @@ -0,0 +1,351 @@ +# lane-vp9inter report — inter-frame SYNTAX, slice 1 (`ec-vp9`) + +Worktree `/home/user/Documents/Code/Rust/edith_codecs-inter` (detached `43c9c913`). +No commit, no push, no fmt. Reconstruction / motion compensation: **NOT implemented, +`inter_is_named_unsupported` still refuses by name.** + +## Status: SYNTAX LAYER BIT-EXACT on two inter frames (2026-09-17, slice 5) — +## frame 1 and frame 2 each match libvpx block-for-block on every comparable +## field (1213/1213 and 1851/1851), which required three fixes in the mode-info +## layer (below) on top of the earlier entropy-layer ones. Pixels are still +## refused: reconstruction/motion compensation remains out of scope. + +## History: THREE defects found, fixed and verified: the compressed header +## is bit-identical to libvpx (1200/1200 bools counting the reader marker and the +## tx-mode literals) and the tile walk now matches the oracle for its first 2628 +## bools. Block (0,0) of frame 1 is equivalent to the oracle on every comparable +## field (row/col/bsize/tx/mode/skip/seg/ref0/ref1/mv/interp; `uv` is libvpx-stale +## by design). The walk still stops early: 1002 of 1213 blocks, desync after tile +## bool #2628 (cause 4 below, not yet diagnosed). + +## What is implemented (all in `crates/ec-vp9`) + +- `src/inter.rs` (new): `read_inter_frame_mode_info` — inter segment id (incl. + temporal-update prediction), skip, `read_is_inter_block`, tx size with the + `allow_select = !skip || !inter` rule, reference frames (single + compound + paths, `single_ref_p1/p2`, `comp_ref_p`, `reference_mode_context` contexts + transcribed from `vp9_pred_common.c`), inter mode, switchable interp filter, + the sub-8x8 `bmi` path, `read_mv`/`read_mv_component` with the + `use_hp = allow_hp && use_mv_hp(predictor)` gate, and the MV predictor + (`dec_find_mv_refs`, `mv_ref_blocks`, `append_sub8x8_mvs_for_idx`, + `lower_mv_precision`, `clamp_mv_ref`, `mode_2_counter`/`counter_to_context`). + MVs are recorded both as the refreshed MV and as the raw codeword diff. +- `src/header.rs`: `FrameContext` gained the inter tables (`inter_mode`, + `switchable_interp`, `intra_inter`, `comp_inter`, `single_ref`, `comp_ref`, + `y_mode`, `uv_mode`, the MV prob components) with libvpx defaults, and + `read_compressed_header` gained the inter branch in libvpx order: + inter-mode probs, switchable-interp probs, `intra_inter`, `read_frame_reference_mode` + (compound-allowed gate), reference-mode probs, y-mode probs, partition probs, + `read_mv_probs` (joints → per-component sign/classes/class0/bits → class0_fp/fp + → hp when `allow_high_precision_mv`). It now returns + `CompressedHeader { tx_mode, reference_mode }`. +- `src/decode.rs`: `Decoder::decode_syntax` (keyframes decode through to pixels, + inter frames are parsed with no picture), the inter tile walk (same tile + geometry/BE size prefixes as the keyframe walk), the frame-context rules + (`reset_frame_context` 2/3, `refresh_frame_context` save, `use_prev_frame_mvs` + gate), the per-8x8 `MV_REF` field and segment map for the next frame, and a + token-only block walk (`decode_inter_block_tokens`) that keeps the entropy + stream aligned without any prediction or residual add. +- `src/tokens.rs`: `decode_coefs` gained the `is_inter` ref-axis selector + (`coef_probs[tx][plane][ref]`), keyframe call sites pass `false`. +- `tests/scratch_interdump.rs` (new): parses every frame of `INTER_IVF` and, with + `EC_VP9_INTERDUMP=1`, prints one oracle-shaped `MODE` line per block. + +Gates: +- `cargo test -p ec-vp9 --test keyframe_exact` → **4/4 PASS** + (`keyframes_match_ffmpeg`, `lossless_64_matches_ffmpeg`, + `profile1_444_is_named_unsupported`, `inter_is_named_unsupported`). +- `cargo check -p ec-vp9` → **exactly the 5 baseline warnings** + (`TM_PRED`, `read_partition`, `partition_probs`, `x_mis`, `y_mis`). +- `cargo test -p ec-vp9` → **green end to end** (14 test binaries, 0 failures). +- `cargo test -p ec-vp9 --test scratch_interdump` → **a real gate**: any frame + error fails it (keyframe errors now propagate) and every inter frame's + mode-info block count must equal `INTER_EXPECT` (default `1213,1851`, the + pinned counts of the fixture; `INTER_EXPECT=none` disables). + `INTER_IVF` defaults to `/tmp/inter1.ivf` (the clean single-tile stream the + counts refer to); when that file is absent the test **skips loudly** + (`SKIP: fixture ... not found`, the `scratch_synth` convention) so a machine + without /tmp fixtures stays green. Current output: `FRAME 1 parsed blocks=1213`, + `FRAME 2 parsed blocks=1851`, `block-count gate passed for [1213, 1851]`. + The failing-keyframe path stays reachable by pointing it at the two-tile-column + stream: `INTER_IVF=/tmp/inter.ivf INTER_EXPECT=none cargo test -p ec-vp9 + --test scratch_interdump` → expected failure at `FRAME 0 failed: Corrupt { + context: "vp9: tile bool decoder desync" }` (instrumentation for the + multi-tile keyframe defect). +- Overread gate: the crate already asserts `overreads() == 0` per tile reader at + the end of each tile (`decode.rs:416` keyframe walk, `decode.rs:809` inter + walk, message "tile bool decoder desync"), which fires if a walk reads past a + tile's last bool - that is exactly the error `/tmp/inter.ivf` (2 tile columns) + now reports for its keyframe. An earlier statement in this report that the + crate's only overread assertion was the `bool.rs` unit test was wrong. +- Knob-free silence: with no `EC_VP9_*` set, the same harness run emits **0** + trace lines (grep over the twelve trace prefixes) and still passes the gate. + +## Landing fixes (post-verdict) + +1. **`clamp_mv_ref` had row and column swapped** (blocking-queue item 1). The + four edges were computed correctly but applied to the wrong components: + `mv.0` is the ROW (filled from the vertical joint component in `read_mv`) + and was clamped with the left/right edges. libvpx's + `clamp_mv(mv, min_col, max_col, min_row, max_row)` (`vp9_mv.h:47`) takes the + COLUMN bounds first, and `clamp_mv_ref` passes + `(mb_to_left_edge - MV_BORDER, mb_to_right_edge + MV_BORDER, + mb_to_top_edge - MV_BORDER, mb_to_bottom_edge + MV_BORDER)` + (`vp9_mvref_common.h:215`). Fixed by clamping `mv.1` with left/right and + `mv.0` with top/bottom. Latent on this fixture (max |mv| 334) - the two + frames still match 100% afterwards - but on edge-heavy content the wrong + bound would move a predictor, flip `use_mv_hp` and desync the stream. +2. **`decode_syntax` no longer swallows keyframe failures.** It propagated the + error only as a `KFAIL` print under `EC_VP9_INTERDUMP`, so a stream whose + keyframe died mid-walk returned success with a half-updated frame context, + prev-frame MV field and reference slots - and every later inter-frame dump was + meaningless evidence. Now the error propagates (`decode_key_frame(..)?`), so + `/tmp/inter.ivf` fails fast with + `FRAME 0 failed: Corrupt { context: "vp9: tile bool decoder desync" }`. +3. **The harness is a gate, not a printer** (see the Gates list). Its block + counts come from `Decoder::last_frame_blocks()`, captured in + `decode_inter_syntax_frame` right before the walk state is consumed. +4. **All `EC_VP9_*` dumps now go through cached `OnceLock`/atomic gates** + (`lib.rs`: `cached_gate!` for `EC_VP9_INTERDUMP`, `EC_VP9_MVDGB`, + `EC_VP9_MVDGB2`, `EC_VP9_MVDUMP`), so the per-block, per-MV-component and + per-switchable-interp checks are a relaxed atomic load instead of a + `std::env::var_os` (stdlib ENV lock) on the decode path. + +## Streams + +- `/tmp/inter.ivf` — a real 1920x1080 clip, `-frames:v 3 -c:v libvpx-vp9 -crf 32`: + keyframe + 2 inter frames, **2 tile columns**, `allow_hp=1`, `interp=SWITCHABLE`, + `tx_mode=SELECT`, frame-level `reference_mode=SINGLE`, `reset_frame_context=1`, + `refresh_frame_context=0` for all three frames (so frames 1/2 start from the + default frame context — verified against the oracle's `CHSUM`). +- `/tmp/inter1.ivf` — **the stream every match count in this report refers to** + (the single-tile control, and the one driving the frame-1/2 MODE diffs, the + bool traces and the candidate probes). Generated with + `ffmpeg -v error -y -i -frames:v 3 -c:v libvpx-vp9 + -crf 32 -pix_fmt yuv420p -tile-columns 0 -f ivf /tmp/inter1.ivf`; + the exact file used here is `sha256 + 376532734662ba5faba4c4e97a5aac915ce429c11701bcf66439b61a77388fa8`, 161579 bytes, + VP9 1920x1080, 3 frames (keyframe + 2 inter), which is what the counts are tied + to - a different clip or encoder setting gives different block counts, so a + third party reproducing the numbers should use this file (or regenerate from + the same source) and check the hash. + Consumers: + `BTRACE=1 MODEDUMP=1 MVDUMP=1 /tmp/vp9loss/drv /tmp/inter1.ivf` (oracle) and + `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-inter INTER_IVF=/tmp/inter1.ivf + EC_VP9_INTERDUMP=1 EC_VP9_TRACE=1 cargo test -p ec-vp9 --test scratch_interdump + -- --nocapture` (ours). + +## Match counts (oracle `MODE` vs our `MODE`, by index, fields +## row/col/bsize/tx/mode/skip/seg/ref0/ref1/mvrow/mvcol/interp) + +| stage | frame 1 ours/oracle | first divergence | +|---|---|---|---| +| before any fix (single tile) | 551 / 1213 (desync) | block #0, `bsize` (ours 10 vs 12) | +| after cause 1 (`update_mv_probs`) | 794 / 1213 (desync) | block #0, `bsize` | +| after cause 2 (kf partition leak) | **917 / 1213 (desync)** | block #0 compares EQUAL on row/col/bsize/tx/mode/skip/seg/ref0/ref1/mv (`uv` is libvpx-stale, `if` is cause 3) | +| frame 2 | never reached (frame 1 aborts) | – | + +First divergent decision, single-tile stream, block #0 == (0,0) 64x64: + +``` +ours = row 0 col 0 bsize 11 (64x32) tx 3 mode 10 (NEARESTMV) skip 0 ref0 2 mv (0,0) +oracle = row 0 col 0 bsize 12 (64x64) tx 3 mode 13 (NEWMV) skip 1 ref0 1 mv (3,0) +``` + +## Bool index of the divergence (the decisive evidence) + +Instrumentation used: oracle `MODEDUMP` now also prints `ref0/ref1/mvrow/mvcol/if`, +`MVRAW` prints each `read_mv` diff, and `CHSUM` prints +`frame tx_mode ref_mode allow_hp interp fcx refresh_ctx reset_ctx`; our side prints +`CHSTART frame=N` and `TILE bytes frame=N` markers so `EC_VP9_TRACE` bools can +be attributed to a frame and a section. + +- **Compressed header, frame 1 (RESOLVED):** before the fixes our reads diverged at + bool **#1116**: `ours (prob,bit)=(252,0)` vs `oracle (128,0)`, totals **1184 vs 1200**. + Section tables (markers `SECT ` on ours, `CHSEC ` in the oracle, + bool index counted between markers; ours' window is 4 bools ahead of the oracle's + because the oracle's starts at its first marker): + `txmode 0/22 | txprobs 22/856 | coef 878/18 | skip 896/32 | inter_mode 896/32 | + switchable 928/24 | intra_inter 952/4 | ref_mode_bits 956/0 | ref_mode_probs 956/15 | + y_mode 971/36 | partition 1007/99 | mv_probs 1106/74(ours) vs 1106/90(oracle)`. + Every section entry and count matched except the last: the divergence is inside + `read_mv_probs` (span 74 vs 90). After the two fixes below the CH is + **bit-identical: 1196 == 1196 bools, no divergence**. +- **First tile symbol, frame 1:** after the tile reader's marker bit (both sides + `(128,0)`), the partition read differs: ours `(191,1)` → PARTITION_HORZ, + oracle `(239,0)` → PARTITION_NONE. Different *prob and* different bit ⇒ the + frame probability state is already wrong at the tile start, which is exactly + what the CH divergence predicts. Our walk then stays self-consistent for 551 + blocks and finally over-reads the 1717-byte tile ("tile bool decoder desync"). + +So the first wrong decision is `compressed_header`, bool #1116 — the mode-info, +MV and token layers below it are unaudited until that is fixed. + +## Named causes (evidence, not speculation) + +1. **FIXED — `update_mv_probs` is NOT `vp9_diff_update_prob`** (`vp9_decodeframe.c:136`): + `if (vpx_read(r, MV_UPDATE_PROB)) p[i] = (vpx_read_literal(r, 7) << 1) | 1;` + — a 252-prob flag, then seven literal bits, and the new prob is `(literal << 1) | 1`; + no `decode_term_subexp`, no `inv_remap_prob`. Our mv probs used `diff_update_prob` + for all 69 entries, hence the 16-bool deficit and the (252,0)-vs-(128,0) divergence. + Fix: `fn update_mv_probs(r, &mut [u8])` + all mv loops switched. Evidence of the + fix: the oracle's mv span 90 == ours 90, CH totals equal, PUPD-equivalent traces equal. + +2. **FIXED — keyframe partition probs leaked into the stored frame context.** + libvpx's keyframe partition table is the CONST `vp9_kf_partition_probs`, selected + by `get_partition_probs()` for intra-only frames — it is NOT a `FRAME_CONTEXT` + field. Our `FrameContext::new(true)` baked it into the context and we stored that + context in `frame_ctxs` at every keyframe, so frame 1 started with the keyframe + table (`ours ctx0=[158,97,94]` vs `oracle [199,122,141]`; 44/48 entries wrong — + same bits read, different values, which is why the section tables looked clean). + Fix: stored contexts are always `FrameContext::new(false)`; the active keyframe + copy keeps `new(true)`; `FrameContext::reset_inter_partition()` runs before a + keyframe context save. Evidence: `PPFLAT_PRE` on both sides now equal, and the + 48-entry `PUPD j i before after` traces are IDENTICAL. + +3. **FIXED — `SWITCHABLE_INTERP_TREE` was built from the SPEC's naming order, not + libvpx's.** `vp9/common/vp9_filter.h:23-28` are `#define`s, not an enum: + `EIGHTTAP 0`, `EIGHTTAP_SMOOTH 1`, `EIGHTTAP_SHARP 2` (the spec's `literal_to_filter` + names the *same coded values* in a different order). The tree + `{ -EIGHTTAP, 2, -EIGHTTAP_SMOOTH, -EIGHTTAP_SHARP }` is therefore + `{0, 2, -1, -2}`, not `{-1, 2, 0, -2}`; with the wrong table our interp leaf came + out 0 where libvpx gives 1, which poisoned the *next* block's + `get_pred_context_switchable_interp` (left neighbour's filter is the context). + Evidence after the fix: both sides print `SWI ctx=3 p0=87 p1=252` / `SWItype 1` + for block (0,0) and `SWI ctx=1 p0=19 p1=255` / `SWItype 1` for (0,8); block (0,0) + now matches the oracle on `interp` too. + **Reader-counter evidence** (oracle `g_bool_count` reset at the compressed header, + printed as `bools=` in its `SWI`/`SWItype` lines; ours = CH total + tile bool index + at the same print, both counting the tile reader marker and the tx-mode literals): + `ours 1208 / 1210 / 1221 / 1223 / 1229 / 1231` vs + `oracle 1208 / 1210 / 1225 / 1227 / 1233 / 1235` — the first two agree exactly, so + the two walks are bool-aligned through block (0,0)'s interp read; the later pairs + differ because the walks diverge at #2628 (below). + +4. **FIXED — the tile desync was a transposed `mv_ref_blocks` lookup (POSITION is + `{ row, col }`, our accessors added `p.0` to the column), plus two smaller + defects found in its wake.** All three are in `crates/ec-vp9/src/inter.rs`. + + - **The transposition (the root cause).** `vp9_mvref_common.h`'s + `mv_ref_blocks` is a table of `POSITION struct { int row, col }`, so the + 64x64 row is `{ -1, 3 }, { 3, -1 }, { -1, 4 }, { 4, -1 }, ...` meaning + `(row - 1, col + 3)` first. Our accessors (`is_inside`, `find_mv_refs`'s + cell closure, `get_mode_context`, `get_sub_block_mv`'s `search_col`) added + `p.0` to the **column** and `p.1` to the **row**, so every asymmetric entry + picked a different neighbour. Evidence: for the block at `r=8 c=32` + bsize 12 mode 10 the first candidate came from `p=(-1,3)` mapped to + `(11,31)` (the 64x64 at `(8,24)`, MV `(3,0)`) where libvpx's `(7,35)` (the + 64x64 at `(0,32)`) holds `(-1,0)` - the MV the oracle used. Fixed by + swapping the two components at every accessor (array text kept verbatim). + - **`clamp_mv_ref`'s unsigned underflow.** `mi_rows - bh - row` is negative + for a tall block on the frame's partial last row (1080p: `135 - 8 - 128`), + and libvpx computes it in `int`; ours subtracted in `usize` and panicked + ("attempt to subtract with overflow", inter.rs:497) - which is why the walk + stopped after 1183 of 1213 blocks. Fixed by computing `mb_to_*` in `i32` + (libvpx's formulas: `-(row*64)`, `(mi_rows - bh - row)*64`). + - **The candidate count semantics.** First attempt returned the *real* count + and broke every NEARMV block (frame 1 fell from 100% on the prefix to a + first divergence at block #15, `mode=11`, ours `(1,2)` vs oracle `(0,0)`). + `dec_find_mv_refs`' tail (vp9_decodemv.c:626) is subtler: an early exit + (`goto Done`, i.e. `ADD_MV_REF_LIST_EB` filling the second slot or + `early_break` stopping at the first) **jumps over** the mode-derived + override and returns the count as accumulated; falling out of the loops + applies `count = (mode == NEARMV) ? 2 : 1`, so a NEARMV block whose search + found only one candidate still reports two and the caller reads the zeroed + second slot `(0, 0)`. Reproduced exactly (`if done { count } else if mode == + NEARMV { 2 } else { 1 }`, clamp that many). + + **Result (frame-1/2 by-index MODE diff, oracle vs ours):** + - frame 1: ours 1213, oracle 1213, **identity 1213/1213 (100.0%)** + - frame 2: ours 1851, oracle 1851, **identity 1851/1851 (100.0%)** + compared fields: row/col/bsize/tx/mode/skip/seg/ref0/ref1/interp and the MV - + with `uv` dropped for inter blocks and `mvrow/mvcol` dropped for intra blocks + inside inter frames (both are libvpx-stale, see the non-comparison list below). + Frame 2 exercises `use_prev_frame_mvs` (the from-previous-frame MV_REF field) + and also matches byte-for-byte, so the prev-frame MV_REF store is correct. + + **Defect (b) - frame 2's compressed header - is refuted.** Its earlier + "pristine defaults" `MVPROB` reading was an artifact of the run that aborted + in frame 1; with the walk fixed, frame 2 reproduces 1851/1851 blocks + bit-exactly, which requires frame 2's CH MV tables to be correct. (Our + `MVPROB` dump still prints 4 times per stream where the oracle prints 2, so + the line-by-line pairing is ambiguous - a harness artifact, not a decode + difference; frame 1's dump is identical to the oracle's apart from the + never-updated 11th `classes` slot.) + + **stale-field non-comparisons (extend the list):** `uv_mode` is stale for + *inter* blocks; `mi->mv[]` is stale for *intra* blocks inside an inter frame + (libvpx never writes it from `read_intra_frame_mode_info`), so a MODE diff + must drop `mvrow/mvcol` whenever `ref0 == INTRA_FRAME`. Dropping them is what + took frame 2 from 97.8% to 100%. + +Superseded earlier hypothesis (kept for the record): "a section count/order difference +in the 1116..1200 span" — correct span, wrong mechanism: the counts differed because +the mv-prob payloads are 7-bit literals, not term-subexp payloads. + +## Cause-3 lesson worth carrying forward +Every VP9 tree constant must be rebuilt from libvpx's **macro expressions**, not from +the spec's (or one's memory of the) naming order: `vp9_filter.h` uses `#define EIGHTTAP 0` +while the spec's `literal_to_filter` lists EIGHTTAP_SMOOTH first. Trees whose leaves are +plain integers (partition, mv class/fp, segment) were safe; trees whose leaves are *named +constants* (switchable interp, inter mode via `INTER_OFFSET`) must be evaluated in libvpx's +own numbering. Our inter-mode tree was right only because `INTER_OFFSET` is a subtraction. + +## Earlier ranked causes (now resolved or refuted) + +1. **A compressed-header section count/order difference in the 1116..1200 span.** + The span is ~200 bools, which matches the *inter* half of the header + (inter-mode 21 + switchable 8 + intra/inter 4 + ref-mode 1-2 + single_ref 10 + + y_mode 36 + partition 48 + MV 69 = 197-198 flags before inner literal reads), + so the prime suspect is one of those sections, not the coef/skip part. The + missing-16-bools net says at least one section is read with the wrong count. + Note `CHSUM` (tx_mode=4, ref_mode=0, allow_hp=1, interp=4) already matches the + oracle exactly, so the header's *front* and the uncompressed header size + (`uhs`) are right, and the tile offset itself is not suspect. + Fastest discriminator (next slice, ~20 min): print one marker per CH section + (`inter_mode`, `switchable`, `intra_inter`, `ref_mode_probs`, `y_mode`, + `partition`, `mv_probs`) and diff the markers' bool indices against the + oracle's `BOR` positions; the first section whose start index is off is the bug. +2. **Not the tables.** The default partition probs were diffed entry-by-entry + against `vp9/common/vp9_entropymode.c::default_partition_probs` (48 values, + 0 mismatches), and the inter defaults were extracted mechanically; so a + *rejected* cause unless the marker diff says otherwise. +3. **Pre-existing keyframe limitation on multi-tile-column streams (found here).** + Frame 0 of `/tmp/inter.ivf` (2 tile columns) dies in the *keyframe* path with + "tile bool decoder desync" while the single-tile control (`/tmp/inter1.ivf`) + decodes the same keyframe fine: the kf entropy walk is not multi-tile-safe on + this encode, even though the earlier lane's all-intra sweep was. This is + independent of the inter work (the inter walk needs no keyframe pixels) but it + is a real defect to file, and it means frame 0 in `decode_syntax` must be + tolerated (`KFAIL` line) rather than fatal. +4. Unverified by this slice: the MV predictor's `scale_mv` sign-flip variant and + the sub-8x8 `bmi` path (never reached, since block #0 already diverges), the + compound-reference path (this stream is `SINGLE_REFERENCE` throughout), and + the `prev_frame_mvs` path of frame 2. + +## Exact next slice + +1. CH section markers → first section with a wrong bool index → fix the count/order + in `header.rs`; re-run the by-index `MODE` diff until frames 1 and 2 walk to the + tile's last bool with `overreads() == 0`. +2. Then re-diff `MODE` fields (skip/tx/ref0/ref1/inter_mode/mv) plus the oracle's + `MVRAW` (raw diffs) to audit the MV reader/predictor — the predictor decides the + high-precision bit, so it is parse-load-bearing. +3. Then file/fix the keyframe multi-tile-column desync (ranked cause 3) — it is the + same class as the tile-walk bug fixed in the keyframe lane and is now the only + thing blocking `/tmp/inter.ivf` frame 0. +4. Only after the syntax layer is exact: reconstruction/motion compensation + (out of scope today), which is also what makes the pixels — no pixel-level + inter result is claimed anywhere in this lane. + +## Repro commands + +``` +# oracle dump (ref0/ref1/mv/interp + MVRAW + CHSUM) +MODEDUMP=1 MVDUMP=1 /tmp/vp9loss/drv /tmp/inter1.ivf 2>&1 | grep -E '^MODE|^CHSUM' +# ours +CARGO_TARGET_DIR=$HOME/.cache/cargo-target-inter INTER_IVF=/tmp/inter1.ivf \ + EC_VP9_INTERDUMP=1 cargo test -p ec-vp9 --test scratch_interdump -- --nocapture +# bool-level CH diff: EC_VP9_TRACE=1 on ours vs BTRACE=1 on the oracle, +# split ours on CHSTART/TILE markers and the oracle on the CHSUM/MODE markers +```