diff --git a/crates/ec-vp8/src/bool.rs b/crates/ec-vp8/src/bool.rs index e842f051..fb864df2 100644 --- a/crates/ec-vp8/src/bool.rs +++ b/crates/ec-vp8/src/bool.rs @@ -86,8 +86,12 @@ impl<'a> BoolDecoder<'a> { } /// Decode one bool whose zero-probability is `prob`/256 - /// (RFC `read_bool`). + /// (RFC `read_bool`). Under EC_VP8_TRACE, prints the decoder state + /// after the read — `B `, byte-exact + /// the same line scripts/vp8ref_model.py prints — so the two + /// decoders can be diffed read-for-read. pub fn read_bool(&mut self, prob: u8) -> bool { + let trace = std::env::var_os("EC_VP8_TRACE").is_some(); let prob = u32::from(prob); let split = 1 + (((self.range - 1) * prob) >> 8); let bigsplit = split << 8; @@ -108,6 +112,9 @@ impl<'a> BoolDecoder<'a> { self.value |= self.next_byte(); } } + if trace { + eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit)); + } bit } diff --git a/crates/ec-vp8/src/decode.rs b/crates/ec-vp8/src/decode.rs index c6b098fd..36bd0278 100644 --- a/crates/ec-vp8/src/decode.rs +++ b/crates/ec-vp8/src/decode.rs @@ -14,6 +14,7 @@ use crate::bool::BoolDecoder; use crate::frame::{FrameType, KeyFrameDims, mb_geometry}; use crate::header::FrameHeader; +use crate::mc; use crate::intra; use crate::loopfilter::{self, MbFilterInfo}; use crate::modes; @@ -22,6 +23,23 @@ use crate::tokens::{self, Dq, MbCoeffs, TokenContexts}; use crate::transform; use crate::transform::Dequant; use crate::{Error, PersistedState, Result}; +/// Copy a visible MB-aligned image out of the 1-pixel-bordered working +/// plane into the top-left visible corner of a bordered reference +/// buffer. +fn copy_plane( + dst: &mut [u8], + dst_stride: usize, + src: &[u8], + src_stride: usize, + w: usize, + h: usize, +) { + for r in 0..h { + let s = (1 + r) * src_stride + 1; + let d = (MC_BORDER + r) * dst_stride + MC_BORDER; + dst[d..d + w].copy_from_slice(&src[s..s + w]); + } +} /// Reconstructed-image plane: a padded buffer with a 1-pixel left/top /// border (127 on top including the corner, 129 on the left — RFC 6386 @@ -82,11 +100,39 @@ struct MbInfo { b_modes: [u8; 16], segment_id: u8, skip: bool, + /// 0 = intra, 1 = last, 2 = golden, 3 = altref (§16.2). Key-frame + /// MBs and the border are intra. + ref_frame: u8, + /// Inter mv_ref leaf (§16.2): 0 = zero, 1 = nearest, 2 = near, + /// 3 = new, 4 = split. 0 when intra. + mv_ref: u8, + /// Whole-MB motion vector in eighth-pels; the bottom-right subblock's + /// vector for SPLITMV (what future neighbours' census sees). + mv: (i16, i16), + /// Per-subblock motion vectors (SPLITMV). + bmi: [(i16, i16); 16], + /// `need_to_clamp_mvs` (§16.2): the luma MC clamps this MV into the + /// extended-frame range. + mv_clamp: bool, /// Any non-zero coefficient decoded for this MB (bit 31 of dixie's /// eob_mask); decides the loop filter's interior edges (§15.1). has_nz: bool, } +/// One reference-frame slot: bordered planes, 32-pixel edge-replicated +/// borders around the MB-aligned image (dixie `extend_frame`). +#[derive(Clone)] +struct RefFrame { + y: Vec, + u: Vec, + v: Vec, + stride: usize, + uv_stride: usize, +} + +/// MC border width in pixels (libvpx `VP8BORDERINPIXELS`). +const MC_BORDER: usize = 32; + impl MbInfo { fn has_y2(&self) -> bool { self.y_mode != modes::YMode::BPred.as_u8() @@ -108,6 +154,12 @@ pub struct Decoder { /// DC_PRED border (dixie's `mb_info` border trick). mb_info: Vec, token_ctxs: TokenContexts, + /// Reference frame slots: [unused, last, golden, altref] (§16.2 + /// indices). Empty until the first key frame. + refs: [Option; 4], + /// Persisted per-MB segment ids, `mb_rows * mb_cols` (§9.3: when a + /// frame does not re-code the map, ids carry over). + segment_map: Vec, frame_decoded: bool, } @@ -156,6 +208,8 @@ impl Decoder { }, mb_info: Vec::new(), token_ctxs: TokenContexts::new(0), + refs: [None, None, None, None], + segment_map: Vec::new(), frame_decoded: false, } } @@ -169,14 +223,28 @@ impl Decoder { /// Decode one frame; returns the picture when it is for display /// (`show_frame`). Hidden frames still update the decode state. pub fn decode(&mut self, frame: &[u8]) -> Result> { + // Entropy revert (§9.7): the probability updates this frame + // applies are transient unless `refresh_entropy` says they + // persist. Snapshots are cheap array copies; segmentation and + // loop-filter deltas live outside the frame context and never + // revert (libvpx saves only `fc`). + let coeff_probs = self.state.coeff_probs; + let mv_probs = self.state.mv_probs; + let ymode_probs = self.state.ymode_probs; + let uv_mode_probs = self.state.uv_mode_probs; let (header, hdr_dec) = FrameHeader::parse(frame, &mut self.state)?; - match header.tag.frame_type { + let refresh_entropy = header.refresh.refresh_entropy; + let pic = match header.tag.frame_type { FrameType::Key => self.decode_keyframe(frame, header, hdr_dec), - FrameType::Inter => Err(Error::unsupported( - "VP8 inter frame", - "inter-frame decoding is the next milestone of this crate", - )), + FrameType::Inter => self.decode_interframe(frame, header, hdr_dec), + }?; + if !refresh_entropy { + self.state.coeff_probs = coeff_probs; + self.state.mv_probs = mv_probs; + self.state.ymode_probs = ymode_probs; + self.state.uv_mode_probs = uv_mode_probs; } + Ok(pic) } fn ensure_buffers(&mut self, kf: KeyFrameDims) { @@ -322,39 +390,80 @@ impl Decoder { // Loop filter post-pass (see module docs for the ordering // equivalence argument). - if header.filter_level > 0 { - let infos: Vec = (0..self.mb_rows) - .flat_map(|r| (0..self.mb_cols).map(move |c| (r, c))) - .map(|(r, c)| { - let mb = self.mbi(r + 1, c + 1); - MbFilterInfo { - level: self.mb_filter_level(&header, mb), - inner_edges: mb.has_nz || !mb.has_y2(), - } - }) - .collect(); - // The planes are bordered; the filter sees the unbordered - // image (same row pitch) starting at pixel (0, 0). - let (ystride, ustride, vstride) = (self.y.stride, self.u.stride, self.v.stride); - let (mcols, mrows) = (self.mb_cols, self.mb_rows); - let simple = header.filter_type == 1; - let sharpness = header.sharpness_level; - let yimg = &mut self.y.data[1 + ystride..]; - let uimg = &mut self.u.data[1 + ustride..]; - let vimg = &mut self.v.data[1 + vstride..]; - loopfilter::filter_frame_ex( - yimg, uimg, vimg, ystride, ustride, mcols, mrows, sharpness, simple, &infos, true, - ); - } + self.run_loopfilter(&header, true); + + // A key frame refreshes every reference slot and clears the + // persisted segment map (§9.3, §9.7). + self.segment_map = vec![0; self.mb_cols * self.mb_rows]; + let rf = self.make_ref(); + self.refs[1] = Some(rf.clone()); + self.refs[2] = Some(rf.clone()); + self.refs[3] = Some(rf); self.frame_decoded = true; Ok(header.tag.show_frame.then(|| self.crop())) } - /// Per-MB loop filter level (dixie `calculate_filter_parameters`): - /// segment adjustment, then ref/mode deltas, clamped 0..63. Key - /// frames are all intra — ref index 0 (`CURRENT_FRAME`), with - /// `mode_delta[0]` applying to B_PRED. + /// Loop-filter post-pass over the whole frame (dixie order-equivalent + /// driver; `inner_edges` follows libvpx's `skip_lf`: skipped MBs + /// filter only their boundary edges, except 4x4-coded modes). + fn run_loopfilter(&mut self, header: &FrameHeader, is_keyframe: bool) { + if header.filter_level == 0 { + return; + } + let infos: Vec = (0..self.mb_rows) + .flat_map(|r| (0..self.mb_cols).map(move |c| (r, c))) + .map(|(r, c)| { + let mb = self.mbi(r + 1, c + 1); + MbFilterInfo { + level: self.mb_filter_level(header, mb), + inner_edges: mb.has_nz || !mb.has_y2(), + } + }) + .collect(); + // The planes are bordered; the filter sees the unbordered + // image (same row pitch) starting at pixel (0, 0). + let (ystride, ustride, vstride) = (self.y.stride, self.u.stride, self.v.stride); + let (mcols, mrows) = (self.mb_cols, self.mb_rows); + let simple = header.filter_type == 1; + let sharpness = header.sharpness_level; + let yimg = &mut self.y.data[1 + ystride..]; + let uimg = &mut self.u.data[1 + ustride..]; + let vimg = &mut self.v.data[1 + vstride..]; + loopfilter::filter_frame_ex( + yimg, uimg, vimg, ystride, ustride, mcols, mrows, sharpness, simple, &infos, + is_keyframe, + ); + } + + /// Snapshot the reconstructed (post-LF) frame into a bordered + /// reference buffer with 32-pixel edge-replicated borders. + fn make_ref(&self) -> RefFrame { + let w = self.mb_cols * 16; + let h = self.mb_rows * 16; + let (cw, ch) = (self.mb_cols * 8, self.mb_rows * 8); + let mut rf = RefFrame { + y: vec![0; (w + 2 * MC_BORDER) * (h + 2 * MC_BORDER)], + u: vec![0; (cw + 2 * MC_BORDER) * (ch + 2 * MC_BORDER)], + v: vec![0; (cw + 2 * MC_BORDER) * (ch + 2 * MC_BORDER)], + stride: w + 2 * MC_BORDER, + uv_stride: cw + 2 * MC_BORDER, + }; + copy_plane(&mut rf.y, rf.stride, &self.y.data, self.y.stride, w, h); + copy_plane(&mut rf.u, rf.uv_stride, &self.u.data, self.u.stride, cw, ch); + copy_plane(&mut rf.v, rf.uv_stride, &self.v.data, self.v.stride, cw, ch); + mc::extend_plane(&mut rf.y, rf.stride, w, h, MC_BORDER); + mc::extend_plane(&mut rf.u, rf.uv_stride, cw, ch, MC_BORDER); + mc::extend_plane(&mut rf.v, rf.uv_stride, cw, ch, MC_BORDER); + rf + } + + + /// Per-MB loop filter level (libvpx `loop_filter_frame_init`): + /// segment level (clamped), then the reference delta, then the mode + /// delta, clamped again. Mode slots: intra B_PRED → 0, other intra + /// and ZEROMV → 1 (no delta for other intra), the moving modes → 2, + /// SPLITMV → 3. fn mb_filter_level(&self, header: &FrameHeader, mb: &MbInfo) -> u8 { let seg = &header.segmentation; let mut level = i32::from(header.filter_level); @@ -364,14 +473,471 @@ impl Decoder { } level = level.clamp(0, 63); if header.lf_delta_enabled { - level += self.state.ref_lf_delta[0]; - if mb.y_mode == modes::YMode::BPred.as_u8() { - level += self.state.mode_lf_delta[0]; + level += self.state.ref_lf_delta[usize::from(mb.ref_frame)]; + let mode_idx = if mb.ref_frame == 0 { + if mb.y_mode == modes::YMode::BPred.as_u8() { + Some(0) + } else { + None + } + } else { + match mb.mv_ref { + 0 => Some(1), // ZEROMV + 4 => Some(3), // SPLITMV + _ => Some(2), // NEAREST / NEAR / NEW + } + }; + if let Some(mode_idx) = mode_idx { + level += self.state.mode_lf_delta[mode_idx]; } level = level.clamp(0, 63); } level as u8 } + /// Decode one inter frame (§16): all mode records off partition 0 + /// (row-major), then per-row tokens and reconstruction off the row's + /// token partition, loop filter, then the reference updates (§9.7). + fn decode_interframe( + &mut self, + frame: &[u8], + header: FrameHeader, + mut hdr_dec: BoolDecoder<'_>, + ) -> Result> { + if self.mb_cols == 0 || self.refs[1..4].iter().any(|r| r.is_none()) { + return Err(Error::corrupt("VP8 inter frame before the first key frame")); + } + + // Token partition bool decoders (§9.5) — identical tiling to + // key frames. + let mut partitions = Vec::with_capacity(header.partition_sizes.len()); + let mut off = header.token_data_offset + 3 * (header.partition_sizes.len() - 1); + for &sz in &header.partition_sizes { + let end = off + sz as usize; + let slice = frame + .get(off..end) + .ok_or_else(|| Error::corrupt("VP8 token partition extends past frame end"))?; + partitions.push(BoolDecoder::new(slice)?); + off = end; + } + + // Dequant factors per segment (persisted segmentation state). + let seg = &header.segmentation; + let mut dqf = [Dequant { + y1_dc: 0, + y1_ac: 0, + y2_dc: 0, + y2_ac: 0, + uv_dc: 0, + uv_ac: 0, + }; 4]; + for (i, dq) in dqf.iter_mut().enumerate() { + let q = if seg.enabled { + if seg.abs_delta { + seg.quant_idx[i] + } else { + i32::from(header.quant.yac_qi) + seg.quant_idx[i] + } + } else { + i32::from(header.quant.yac_qi) + }; + *dq = transform::dequant( + q, + header.quant.ydc_delta, + header.quant.y2dc_delta, + header.quant.y2ac_delta, + header.quant.uvdc_delta, + header.quant.uvac_delta, + ); + } + let ymode_probs = self.state.ymode_probs; + let uv_mode_probs = self.state.uv_mode_probs; + let sign_bias = [ + false, + header.refresh.sign_bias_golden, + header.refresh.sign_bias_altref, + ]; + + // Phase 1: every mode record of the frame, row-major (§16). + for row in 1..=self.mb_rows { + for col in 1..=self.mb_cols { + let mut mb = MbInfo::default(); + if header.segmentation.enabled { + if header.segmentation.update_map { + mb.segment_id = + hdr_dec.read_tree(&SEGMENT_TREE, &header.segmentation.tree_probs); + self.segment_map[(row - 1) * self.mb_cols + (col - 1)] = mb.segment_id; + } else { + mb.segment_id = self.segment_map[(row - 1) * self.mb_cols + (col - 1)]; + } + } + if header.coeff_skip_enabled { + mb.skip = hdr_dec.read_bool(header.prob_skip_false); + } + self.parse_inter_modes( + &mut hdr_dec, + row, + col, + &mut mb, + &header, + &ymode_probs, + &uv_mode_probs, + &sign_bias, + ); + *self.mbi_mut(row, col) = mb; + } + } + + // Phases 2+3 per row: tokens, then reconstruction (MC or intra). + for row in 1..=self.mb_rows { + self.token_ctxs.reset_left(); + let part = (row - 1) % partitions.len(); + for col in 1..=self.mb_cols { + let mb = self.mbi(row, col).clone(); + let has_y2 = mb.has_y2(); + let seg_i = usize::from(header.segmentation.enabled) * usize::from(mb.segment_id); + let dq = &dqf[seg_i]; + let mb_dq = Dq { + y1_dc: dq.y1_dc, + y1_ac: dq.y1_ac, + uv_dc: dq.uv_dc, + uv_ac: dq.uv_ac, + y2_dc: dq.y2_dc, + y2_ac: dq.y2_ac, + }; + let probs = self.state.coeff_probs; + let coeffs = if mb.skip { + tokens::skip_mb_tokens(&mut self.token_ctxs, col - 1, has_y2) + } else { + tokens::decode_mb_tokens( + &mut partitions[part], + &probs, + &mb_dq, + has_y2, + &mut self.token_ctxs, + col - 1, + ) + }; + { + // "Special case: force the loop filter to skip when + // eobtotal is zero" (libvpx decodeframe.c): a decoded + // MB without non-zero coefficients filters like a + // skipped one. + let slot = &mut self.mb_info[row * (self.mb_cols + 1) + col]; + slot.has_nz = coeffs.has_nonzero(); + slot.skip = mb.skip || !coeffs.has_nonzero(); + } + self.reconstruct_inter_mb(row - 1, col - 1, &mb, &coeffs); + } + } + + self.run_loopfilter(&header, false); + + // Reference buffer updates, libvpx `swap_frame_buffers` order: + // the copies run first (copy_gf = 2 must see a possibly + // just-updated altref), then the refreshes, then last. + let new = self.make_ref(); + match header.refresh.copy_arf { + 1 => self.refs[3] = self.refs[1].clone(), + 2 => self.refs[3] = self.refs[2].clone(), + _ => {} + } + match header.refresh.copy_gf { + 1 => self.refs[2] = self.refs[1].clone(), + 2 => self.refs[2] = self.refs[3].clone(), + _ => {} + } + if header.refresh.refresh_gf { + self.refs[2] = Some(new.clone()); + } + if header.refresh.refresh_arf { + self.refs[3] = Some(new.clone()); + } + if header.refresh.refresh_last { + self.refs[1] = Some(new); + } + + self.frame_decoded = true; + Ok(header.tag.show_frame.then(|| self.crop())) + } + + /// Inter-frame mode record (§16, libvpx `read_mb_modes_mv`): intra + /// at the persisted mode probabilities, or an inter mode with its + /// motion vectors off the neighborhood census. + #[allow(clippy::too_many_arguments)] + fn parse_inter_modes( + &mut self, + d: &mut BoolDecoder<'_>, + row: usize, + col: usize, + mb: &mut MbInfo, + header: &FrameHeader, + ymode_probs: &[u8; 4], + uv_mode_probs: &[u8; 3], + sign_bias: &[bool; 3], + ) { + if !d.read_bool(header.prob_intra) { + // Intra-coded MB inside an inter frame (§16.1). Subblock + // modes use the same fixed context table as key frames. + mb.ref_frame = 0; + let ymode = modes::read_ymode(d, ymode_probs); + mb.y_mode = ymode.as_u8(); + if ymode == modes::YMode::BPred { + for j in 0..16u8 { + let a = self.above_block_mode(row, col, j, mb); + let l = self.left_block_mode(row, col, j, mb); + mb.b_modes[usize::from(j)] = + modes::read_bmode(d, &KF_BMODE_PROB[usize::from(a)][usize::from(l)]) + .as_u8(); + } + } + mb.uv_mode = modes::read_uvmode(d, uv_mode_probs).as_u8(); + return; + } + + mb.ref_frame = if !d.read_bool(header.prob_last) { + 1 + } else if !d.read_bool(header.prob_gf) { + 2 + } else { + 3 + }; + let to_bias = sign_bias[usize::from(mb.ref_frame) - 1]; + + let edges = modes::mb_edges(col - 1, row - 1, self.mb_cols, self.mb_rows); + let above = self.mv_neighbor(row - 1, col, sign_bias); + let left = self.mv_neighbor(row, col - 1, sign_bias); + let aboveleft = self.mv_neighbor(row - 1, col - 1, sign_bias); + let (mut near_mvs, cnt) = modes::find_near_mvs(above, left, aboveleft, to_bias); + + if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_INTRA] as usize][0]) { + mb.mv_ref = 0; // ZEROMV + return; + } + if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_NEAREST] as usize][1]) { + mb.mv_ref = 1; // NEARESTMV + mb.mv = near_mvs[modes::CNT_NEAREST]; + modes::clamp_mv2(&mut mb.mv, edges); + return; + } + if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_NEAR] as usize][2]) { + mb.mv_ref = 2; // NEARMV + mb.mv = near_mvs[modes::CNT_NEAR]; + modes::clamp_mv2(&mut mb.mv, edges); + return; + } + + // NEWMV or SPLITMV: both code vectors as deltas off the best + // candidate — the nearest one when it dominates the census — + // clamped into range first (§16.2-§16.4). + let near_index = usize::from(cnt[modes::CNT_NEAREST] >= cnt[modes::CNT_INTRA]); + modes::clamp_mv2(&mut near_mvs[near_index], edges); + let best = near_mvs[near_index]; + if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_SPLITMV] as usize][3]) { + mb.mv_ref = 3; // NEWMV + let mut mv = modes::read_mv(d, &self.state.mv_probs); + mv.0 = mv.0.wrapping_add(best.0); + mv.1 = mv.1.wrapping_add(best.1); + mb.mv_clamp = modes::mv_out_of_bounds(mv, edges); + mb.mv = mv; + } else { + self.parse_split_mv(d, row, col, mb, best, edges); + } + } + + /// Census input from one neighbour slot (§16.3); border and intra + /// MBs contribute nothing, zero-vector inter MBs count like intra. + fn mv_neighbor(&self, row: usize, col: usize, sign_bias: &[bool; 3]) -> modes::MvNeighbor { + if row == 0 || col == 0 || self.mbi(row, col).ref_frame == 0 { + return modes::MvNeighbor { + intra: true, + zero: false, + mv: (0, 0), + is_split: false, + sign_bias: false, + }; + } + let mb = self.mbi(row, col); + modes::MvNeighbor { + intra: false, + zero: mb.mv == (0, 0), + mv: mb.mv, + is_split: mb.mv_ref == 4, + sign_bias: sign_bias[usize::from(mb.ref_frame) - 1], + } + } + + /// SPLITMV mode record (§16.4, libvpx `decode_split_mv`): partition + /// shape, then one vector per subset coded against its left/above + /// contexts, each filling a whole group of subblocks. + fn parse_split_mv( + &mut self, + d: &mut BoolDecoder<'_>, + row: usize, + col: usize, + mb: &mut MbInfo, + best: (i16, i16), + edges: (i32, i32, i32, i32), + ) { + let s = modes::read_mv_partition(d); + let num_p = modes::MV_PARTITION_COUNT[s]; + let mv_probs = self.state.mv_probs; + for j in 0..num_p { + let k = usize::from(modes::MBSPLIT_OFFSET[s][j]); + let leftmv = if k % 4 == 0 { + let lm = self.mbi(row, col - 1); + if lm.mv_ref == 4 { + lm.bmi[k + 3] + } else { + lm.mv + } + } else { + mb.bmi[k - 1] + }; + let abovemv = if k < 4 { + let am = self.mbi(row - 1, col); + if am.mv_ref == 4 { + am.bmi[k + 12] + } else { + am.mv + } + } else { + mb.bmi[k - 4] + }; + let ctx = modes::mv_cont(leftmv, abovemv); + let blockmv = match modes::read_sub_mv_ref(d, ctx) { + modes::SubMvRef::Left4x4 => leftmv, + modes::SubMvRef::Above4x4 => abovemv, + modes::SubMvRef::Zero4x4 => (0, 0), + modes::SubMvRef::New4x4 => { + let mut mv = modes::read_mv(d, &mv_probs); + mv.0 = mv.0.wrapping_add(best.0); + mv.1 = mv.1.wrapping_add(best.1); + mv + } + }; + mb.mv_clamp |= modes::mv_out_of_bounds(blockmv, edges); + let count = modes::MBSPLIT_FILL_COUNT[s]; + for &off in &modes::MBSPLIT_FILL_OFFSET[s][j * count..(j + 1) * count] { + mb.bmi[usize::from(off)] = blockmv; + } + } + mb.mv_ref = 4; + // 4x4 residual coding without a Y2 block (like B_PRED). + mb.y_mode = modes::YMode::BPred.as_u8(); + // Neighbours' census sees the bottom-right subblock's vector. + mb.mv = mb.bmi[15]; + } + + /// Reconstruct one inter-frame MB: motion compensation from the + /// reference (or intra prediction), then the residual (§16, §14). + fn reconstruct_inter_mb(&mut self, row: usize, col: usize, mb: &MbInfo, coeffs: &MbCoeffs) { + if mb.ref_frame == 0 { + self.reconstruct_intra_mb(row, col, mb, coeffs); + return; + } + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!( + "IMB r={} c={} ref={} mvref={} mv=({},{}) clamp={} skip={}", + row, col, mb.ref_frame, mb.mv_ref, mb.mv.0, mb.mv.1, mb.mv_clamp, mb.skip + ); + } + let reff = self.refs[usize::from(mb.ref_frame)] + .as_ref() + .expect("reference slots checked at frame start"); + let x = col * 16; + let y = row * 16; + let w = self.mb_cols * 16; + let h = self.mb_rows * 16; + let (cw, ch) = (w / 2, h / 2); + // Luma: one 16x16 predict, or 16 independent 4x4 predicts for + // SPLITMV (identical output to libvpx's grouped predicts). Each + // predict lands at its own (bx, by) slot of one 16x16 patch. + let mut py = [0u8; 256]; + if mb.mv_ref == 4 { + for b in 0..16usize { + let (bx, by) = ((b % 4) * 4, (b / 4) * 4); + mc::predict_luma( + &reff.y, reff.stride, MC_BORDER, w, h, x + bx, y + by, mb.bmi[b], false, + &mut py[by * 16 + bx..], 16, 4, 4, + ); + } + } else { + mc::predict_luma( + &reff.y, reff.stride, MC_BORDER, w, h, x, y, mb.mv, mb.mv_clamp, &mut py, 16, + 16, 16, + ); + } + + // Chroma: one 8x8 predict per quadrant per plane. Whole-MB modes + // halve the single vector; SPLITMV sums its quadrant's four + // subblock vectors (§16.4, libvpx build_4x4uvmvs). The whole-MB + // path re-clamps UNCONDITIONALLY (reconinter.c: rounding the + // derived chroma MV to full-pel can move it outside the tap + // window even when the luma MV was in range); the SPLITMV path + // clamps only under need_to_clamp_mvs. + let mut pu = [0u8; 256]; + let mut pv = [0u8; 256]; + for q in 0..4usize { + let (qx16, qy16) = ((q % 2) * 8, (q / 2) * 8); + let (cx, cy) = (x / 2 + qx16, y / 2 + qy16); + let (uvmv, uv_clamp) = if mb.mv_ref == 4 { + let (qx, qy) = ((q % 2) * 2, (q / 2) * 2); + ( + modes::chroma_mv_split(&[ + mb.bmi[qy * 4 + qx], + mb.bmi[qy * 4 + qx + 1], + mb.bmi[qy * 4 + qx + 4], + mb.bmi[qy * 4 + qx + 5], + ]), + mb.mv_clamp, + ) + } else { + (modes::chroma_mv_whole(mb.mv), true) + }; + mc::predict_chroma( + &reff.u, reff.uv_stride, MC_BORDER, cw, ch, cx, cy, uvmv, uv_clamp, + &mut pu[qy16 * 16 + qx16..], 16, 8, 8, + ); + mc::predict_chroma( + &reff.v, reff.uv_stride, MC_BORDER, cw, ch, cx, cy, uvmv, uv_clamp, + &mut pv[qy16 * 16 + qx16..], 16, 8, 8, + ); + } + if std::env::var_os("EC_VP8_TRACE").is_some() && row == 0 && col == 0 { + eprintln!( + "CHROMA pred_u[0..8]={:?} refu_vis[0..8]={:?} coeffs.u0dcsum={}", + &pu[0..8], + &reff.u[MC_BORDER * reff.uv_stride + MC_BORDER..MC_BORDER * reff.uv_stride + MC_BORDER + 8], + coeffs.u[0].iter().sum::() + ); + } + + // Residual: every block adds onto its MC prediction. + let y_dcs: [i16; 16] = if coeffs.has_y2 { + transform::iwht4x4(&coeffs.y2) + } else { + [0; 16] + }; + for b in 0..16usize { + let (bx, by) = ((b % 4) * 4, (b / 4) * 4); + let mut c = coeffs.y[b]; + if coeffs.has_y2 { + c[0] = y_dcs[b]; + } + let dst = self.y.at(x + bx, y + by); + idct_add_into(&mut self.y.data, &c, &py, 16, by * 16 + bx, dst, self.y.stride); + } + for (plane_data, coeffs_uv, pred, stride) in [ + (&mut self.u.data, &coeffs.u, &pu, self.u.stride), + (&mut self.v.data, &coeffs.v, &pv, self.v.stride), + ] { + for b in 0..4usize { + let (bx, by) = ((b % 2) * 4, (b / 2) * 4); + let dst = (1 + y / 2 + by) * stride + 1 + x / 2 + bx; + idct_add_into(plane_data, &coeffs_uv[b], pred, 16, by * 16 + bx, dst, stride); + } + } + } /// Key-frame mode record (§11): Y mode at fixed probabilities, then /// 16 context-conditioned subblock modes for B_PRED, then chroma. diff --git a/crates/ec-vp8/src/header.rs b/crates/ec-vp8/src/header.rs index 8d5930dc..1e03cc2e 100644 --- a/crates/ec-vp8/src/header.rs +++ b/crates/ec-vp8/src/header.rs @@ -372,16 +372,10 @@ impl FrameHeader { // --- entropy updates (§9.9; dixie decode_entropy_header) --- // Coefficient probability updates are read for every frame; on // key frames the tables were reset to defaults above. - let trace = std::env::var_os("EC_VP8_TRACE").is_some(); - let mut idx = 0; for i in 0..4 { for j in 0..8 { for k in 0..3 { for l in 0..11 { - if trace { - eprintln!("IDX {idx} flag={}", crate::tables::COEFF_UPDATE_PROBS[i][j][k][l]); - } - idx += 1; if d.read_bool(crate::tables::COEFF_UPDATE_PROBS[i][j][k][l]) { state.coeff_probs[i][j][k][l] = d.read_literal(8) as u8; } diff --git a/crates/ec-vp8/src/lib.rs b/crates/ec-vp8/src/lib.rs index 4ef5f415..cbe17aaa 100644 --- a/crates/ec-vp8/src/lib.rs +++ b/crates/ec-vp8/src/lib.rs @@ -20,6 +20,7 @@ pub mod frame; pub mod header; pub mod intra; pub mod loopfilter; +mod mc; pub mod modes; pub mod tables; pub mod tokens; diff --git a/crates/ec-vp8/src/mc.rs b/crates/ec-vp8/src/mc.rs new file mode 100644 index 00000000..30d846cf --- /dev/null +++ b/crates/ec-vp8/src/mc.rs @@ -0,0 +1,712 @@ +//! Motion-compensation inter predictors: reference border extension, 6-tap +//! luma prediction, bilinear chroma prediction, and the UMV-border motion +//! vector clamps. +//! +//! Normative source: [RFC 6386] §18.3 (sub-pixel interpolation, two +//! separable 1-D passes, each sample `clamp255((a + 64) >> 7)`). The loop +//! structure, intermediate widths and the border clamps follow the libvpx +//! reference implementation (`vp8/common/filter.c`, `vp8/common/ +//! reconinter.c`, `vp8/common/extend.c`) sample-for-sample; the per-pass +//! 0..=255 clamping of the 6-tap intermediate is mandated by the RFC's +//! `interp()` and is what the integer test vectors below pin down. +//! +//! Reference planes arrive already border-extended by [`extend_plane`] +//! (edge replication, `border` = 32 like libvpx's `VP8BORDERINPIXELS`); +//! `src` starts at the first byte of the bordered buffer (top-left border +//! corner) and visible pixel `(px, py)` therefore lives at +//! `src[(py + border) * stride + (px + border)]`. +//! +//! Motion vectors are `(row, col)` pairs in eighth-pel units (`i16`), and +//! the C arithmetic right shifts / two's-complement `& 7` phase extraction +//! are reproduced exactly (`i32 >> 3` and `& 7` on negatives). +//! +//! [RFC 6386]: https://www.rfc-editor.org/rfc/rfc6386 + +/// `VP8_FILTER_WEIGHT` (filter.c): tap weights sum to this, DC passes. +const VP8_FILTER_WEIGHT: i32 = 128; +/// `VP8_FILTER_SHIFT` (filter.c): normalize the 7-bit-precision result. +const VP8_FILTER_SHIFT: i32 = 7; + +/// `vp8_sub_pel_filters[8][6]` (filter.c), indexed by the 0..8 sub-pel phase. +const SUB_PEL_FILTERS: [[i32; 6]; 8] = [ + [0, 0, 128, 0, 0, 0], // degenerate whole-pel (RFC 6386 §18.3 "filters[0]") + [0, -6, 123, 12, -1, 0], + [2, -11, 108, 36, -8, 1], + [0, -9, 93, 50, -6, 0], + [3, -16, 77, 77, -16, 3], + [0, -6, 50, 93, -9, 0], + [1, -8, 36, 108, -11, 2], + [0, -1, 12, 123, -6, 0], +]; + +/// `vp8_bilinear_filters[8][2]` (filter.c); chroma prediction is always +/// bilinear (RFC 6386 §19.2). +const BILINEAR_FILTERS: [[i32; 2]; 8] = [ + [128, 0], + [112, 16], + [96, 32], + [80, 48], + [64, 64], + [48, 80], + [32, 96], + [16, 112], +]; + +#[inline] +fn clamp255(v: i32) -> i32 { + if v < 0 { + 0 + } else if v > 255 { + 255 + } else { + v + } +} + +/// Extends the visible `vis_w` x `vis_h` region of `plane` into the `border` +/// ring on all four sides by edge replication: every out-of-image sample +/// becomes the nearest in-image sample. +/// +/// Port of `copy_and_extend_plane` (extend.c) with `et = el = eb = er = +/// border` and `interleave_step = 1`, in place: first the left/right border +/// of every visible row is filled from the row's first/last column, then the +/// (already side-extended) top and bottom rows are copied into the top and +/// bottom borders — which gives the corners their corner pixels, matching +/// the C exactly. +pub(crate) fn extend_plane(plane: &mut [u8], stride: usize, vis_w: usize, vis_h: usize, border: usize) { + debug_assert!(vis_w >= 1 && vis_h >= 1); + debug_assert!(stride >= border * 2 + vis_w); + + let line = border + vis_w + border; + + // extend.c: "copy the left and right most columns out". + for r in 0..vis_h { + let base = (border + r) * stride + border; + let first = plane[base]; + let last = plane[base + vis_w - 1]; + plane[base - border..base].fill(first); + plane[base + vis_w..base + vis_w + border].fill(last); + } + + // extend.c: "Now copy the top and bottom lines into each line of the + // respective borders" — src rows are the already side-extended lines. + let top = border * stride; + let bottom = (border + vis_h - 1) * stride; + for i in 0..border { + plane.copy_within(top..top + line, (border - 1 - i) * stride); + plane.copy_within(bottom..bottom + line, (border + vis_h + i) * stride); + } +} + +/// Luma predictor for one `bw` x `bh` block (`bw`,`bh` in 4..=16, multiples +/// of 4) whose visible-image top-left pixel is `(x, y)`. +/// +/// Semantics of `vp8_build_inter_predictors_b` / +/// `vp8_build_inter16x16_predictors_mby` + `vp8_sixtap_predict*` (reconinter.c, +/// filter.c): full-pel start `(x + (mv.1 >> 3), y + (mv.0 >> 3))`, phases +/// `fx = mv.1 & 7`, `fy = mv.0 & 7`; a whole-pel MV is a plain copy, +/// otherwise the separable 6-tap filter runs horizontally into an `i32` +/// intermediate — clamped to 0..=255 per pass like libvpx's `int` `FData` — +/// then vertically, both passes computing `(dot + 64) >> 7` and clamping. +/// +/// When `need_clamp` is set, the MV is first passed through +/// [`clamp_mv_to_umv_border`]. +pub(crate) fn predict_luma( + src: &[u8], + stride: usize, + border: usize, + vis_w: usize, + vis_h: usize, + x: usize, + y: usize, + mv: (i16, i16), + need_clamp: bool, + dst: &mut [u8], + dst_stride: usize, + bw: usize, + bh: usize, +) { + debug_assert!(bw >= 4 && bw <= 16 && bw % 4 == 0); + debug_assert!(bh >= 4 && bh <= 16 && bh % 4 == 0); + + let mut mv = (i32::from(mv.0), i32::from(mv.1)); + if need_clamp { + clamp_mv_to_umv_border(&mut mv, x >> 4, y >> 4, vis_w, vis_h); + } + + let fx = (mv.1 & 7) as usize; + let fy = (mv.0 & 7) as usize; + let sx = border as i32 + x as i32 + (mv.1 >> 3); + let sy = border as i32 + y as i32 + (mv.0 >> 3); + // 6-tap reads reach 2 before / 3 after the start; the libvpx clamp + // arithmetic keeps those inside the 32-px border. + debug_assert!(sx >= 2 && sy >= 2, "reference read outside bordered plane"); + let (sx, sy) = (sx as usize, sy as usize); + + if fx == 0 && fy == 0 { + // reconinter.c build_inter_predictors_b / vp8_copy_mem*. + for r in 0..bh { + let s = (sy + r) * stride + sx; + dst[r * dst_stride..r * dst_stride + bw].copy_from_slice(&src[s..s + bw]); + } + return; + } + + let hf = &SUB_PEL_FILTERS[fx]; + let vf = &SUB_PEL_FILTERS[fy]; + + // filter.c filter_block2d_first_pass on `src - 2*stride`: `bh + 5` + // horizontal lines (2 above the block, 3 below, for the vertical taps). + // Phase 0 is the exact identity (`(p * 128 + 64) >> 7 == p`), so the + // uniform loop reproduces the C for every phase combination. + let mut tmp = [0i32; 21 * 16]; // C: int FData[21 * 24] + for i in 0..bh + 5 { + let row = (sy + i - 2) * stride + sx - 2; + for j in 0..bw { + let p = row + j; + let acc = i32::from(src[p]) * hf[0] + + i32::from(src[p + 1]) * hf[1] + + i32::from(src[p + 2]) * hf[2] + + i32::from(src[p + 3]) * hf[3] + + i32::from(src[p + 4]) * hf[4] + + i32::from(src[p + 5]) * hf[5] + + (VP8_FILTER_WEIGHT >> 1); /* Rounding */ + tmp[i * bw + j] = clamp255(acc >> VP8_FILTER_SHIFT); + } + } + + // filter.c filter_block2d_second_pass on `FData + 2*bw`: taps read the + // intermediate rows `r .. r + 5`. + for r in 0..bh { + for c in 0..bw { + let acc = tmp[r * bw + c] * vf[0] + + tmp[(r + 1) * bw + c] * vf[1] + + tmp[(r + 2) * bw + c] * vf[2] + + tmp[(r + 3) * bw + c] * vf[3] + + tmp[(r + 4) * bw + c] * vf[4] + + tmp[(r + 5) * bw + c] * vf[5] + + (VP8_FILTER_WEIGHT >> 1); /* Rounding */ + dst[r * dst_stride + c] = clamp255(acc >> VP8_FILTER_SHIFT) as u8; + } + } +} + +/// Chroma predictor for one `bw` x `bh` block whose visible-image top-left +/// chroma pixel is `(x, y)`. +/// +/// Semantics of `vp8_build_inter16x16_predictors_mbuv` / +/// `build_4x4uvmvs` consumers + `vp8_bilinear_predict*` (reconinter.c, +/// filter.c): separable 2-tap bilinear, `vp8_bilinear_filters[8][2]`, +/// weight 128 shift 7, `(dot + 64) >> 7` per pass. `mv` is the chroma MV in +/// eighth-CHROMA-pel units (the caller derives it from luma per libvpx: sum +/// of the four luma subblock MVs, rounding division by 8 with C +/// truncation-toward-zero, `& fullpixel_mask`). +/// +/// The bilinear dot products are provably in 0..=255 (taps are +/// non-negative and sum to 128 over 0..=255 inputs), which is why libvpx's +/// bilinear passes store `unsigned short` intermediates and skip the clamp; +/// the values equal the RFC 6386 §18.3 `interp()` pseudo-code (which clamps) +/// regardless. +/// +/// When `need_clamp` is set, the MV is first passed through +/// [`clamp_uvmv_to_umv_border`]. +pub(crate) fn predict_chroma( + src: &[u8], + uv_stride: usize, + border: usize, + vis_w: usize, + vis_h: usize, + x: usize, + y: usize, + mv: (i16, i16), + need_clamp: bool, + dst: &mut [u8], + dst_stride: usize, + bw: usize, + bh: usize, +) { + debug_assert!(bw >= 2 && bw <= 16 && bw % 2 == 0); + debug_assert!(bh >= 2 && bh <= 16 && bh % 2 == 0); + + let mut mv = (i32::from(mv.0), i32::from(mv.1)); + if need_clamp { + clamp_uvmv_to_umv_border(&mut mv, x >> 3, y >> 3, vis_w, vis_h); + } + + let fx = (mv.1 & 7) as usize; + let fy = (mv.0 & 7) as usize; + let sx = border as i32 + x as i32 + (mv.1 >> 3); + let sy = border as i32 + y as i32 + (mv.0 >> 3); + debug_assert!(sx >= 0 && sy >= 0, "reference read outside bordered plane"); + let (sx, sy) = (sx as usize, sy as usize); + + if fx == 0 && fy == 0 { + for r in 0..bh { + let s = (sy + r) * uv_stride + sx; + dst[r * dst_stride..r * dst_stride + bw].copy_from_slice(&src[s..s + bw]); + } + return; + } + + let hf = &BILINEAR_FILTERS[fx]; + let vf = &BILINEAR_FILTERS[fy]; + + // filter.c filter_block2d_bil_first_pass: `bh + 1` rows, horizontal + // taps [0] and [1]. Phase 0 is the exact identity, as above. + let mut tmp = [0u16; 17 * 16]; // C: unsigned short FData[17 * 16] + for i in 0..bh + 1 { + let row = (sy + i) * uv_stride + sx; + for j in 0..bw { + let p = row + j; + let acc = i32::from(src[p]) * hf[0] + i32::from(src[p + 1]) * hf[1] + + (VP8_FILTER_WEIGHT / 2); /* Rounding */ + tmp[i * bw + j] = (acc >> VP8_FILTER_SHIFT) as u16; + } + } + + // filter.c filter_block2d_bil_second_pass: vertical taps [0] and + // `[width]` (the next intermediate row). + for r in 0..bh { + for c in 0..bw { + let acc = i32::from(tmp[r * bw + c]) * vf[0] + + i32::from(tmp[(r + 1) * bw + c]) * vf[1] + + (VP8_FILTER_WEIGHT / 2); /* Rounding */ + dst[r * dst_stride + c] = (acc >> VP8_FILTER_SHIFT) as u8; + } + } +} + +/// The macroblock-level UMV border edges in eighth-pel units, exactly the +/// decoder's `xd->mb_to_{left,right,top,bottom}_edge` (decodeframe.c:503-532): +/// +/// ```c +/// xd->mb_to_top_edge = -((mb_row * 16) << 3); +/// xd->mb_to_bottom_edge = ((mb_rows - 1 - mb_row) * 16) << 3; +/// xd->mb_to_left_edge = -((mb_col * 16) << 3); +/// xd->mb_to_right_edge = ((mb_cols - 1 - mb_col) * 16) << 3; +/// ``` +/// +/// with `mb_rows`/`mb_cols` the full (partial MB inclusive) MB counts of the +/// visible frame. Returns `(left, right, top, bottom)`. +fn mb_edges(mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) -> (i32, i32, i32, i32) { + let mb_cols = (vis_w + 15) >> 4; + let mb_rows = (vis_h + 15) >> 4; + debug_assert!(mb_col < mb_cols && mb_row < mb_rows); + let left = -(((mb_col * 16) as i32) << 3); + let right = (((mb_cols - 1 - mb_col) * 16) as i32) << 3; + let top = -(((mb_row * 16) as i32) << 3); + let bottom = (((mb_rows - 1 - mb_row) * 16) as i32) << 3; + (left, right, top, bottom) +} + +/// Port of `clamp_mv_to_umv_border` (reconinter.c:257-278), luma MV in +/// eighth-pel units: +/// +/// ```c +/// if (mv->col < (xd->mb_to_left_edge - (19 << 3))) { +/// mv->col = xd->mb_to_left_edge - (16 << 3); +/// } else if (mv->col > xd->mb_to_right_edge + (18 << 3)) { +/// mv->col = xd->mb_to_right_edge + (16 << 3); +/// } +/// /* same for row with top/bottom edges */ +/// ``` +/// +/// 19 px slack toward left/top (16 px + 3 taps right of the central pixel), +/// 18 px toward right/bottom (16 px + 2 taps left of it); the clamp anchor +/// is 16 px inside the border. `mb_col`/`mb_row` locate the block's +/// macroblock; libvpx clamps with these MB-level edges for whole-MB MVs and, +/// when `need_to_clamp_mvs` is set, for each SPLITMV subblock MV too +/// (reconinter.c:370-375, 397-400). +fn clamp_mv_to_umv_border(mv: &mut (i32, i32), mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) { + let (left, right, top, bottom) = mb_edges(mb_col, mb_row, vis_w, vis_h); + if mv.1 < left - (19 << 3) { + mv.1 = left - (16 << 3); + } else if mv.1 > right + (18 << 3) { + mv.1 = right + (16 << 3); + } + + if mv.0 < top - (19 << 3) { + mv.0 = top - (16 << 3); + } else if mv.0 > bottom + (18 << 3) { + mv.0 = bottom + (16 << 3); + } +} + +/// Port of `clamp_uvmv_to_umv_border` (reconinter.c:281-295), chroma MV in +/// eighth-CHROMA-pel units. The comparison doubles the chroma MV back into +/// luma eighth-pel units (`2 * mv->col`, the "different divisor": the +/// chroma border reach is half the luma one) and the clamp target is the +/// luma anchor halved: +/// +/// ```c +/// mv->col = (2 * mv->col < (xd->mb_to_left_edge - (19 << 3))) +/// ? (xd->mb_to_left_edge - (16 << 3)) >> 1 +/// : mv->col; +/// mv->col = (2 * mv->col > xd->mb_to_right_edge + (18 << 3)) +/// ? (xd->mb_to_right_edge + (16 << 3)) >> 1 +/// : mv->col; +/// /* same for row */ +/// ``` +/// +/// The C applies the two ternaries in sequence (right check sees the +/// left-clamped value, which cannot trip it); the sequential `if`s here are +/// that verbatim. `(left - (16 << 3))` is a multiple of 256 so `>> 1` is +/// exact. Callers must re-apply this clamp AFTER full-pel rounding of a +/// derived chroma MV: rounding to full-pel can move the MV outside the +/// border tap window even though the luma MV was already clamped +/// (reconinter.c:336-339 — the 16x16 path clamps the chroma MV +/// unconditionally for exactly this reason). +fn clamp_uvmv_to_umv_border(mv: &mut (i32, i32), mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) { + let (left, right, top, bottom) = mb_edges(mb_col, mb_row, vis_w, vis_h); + + if 2 * mv.1 < left - (19 << 3) { + mv.1 = (left - (16 << 3)) >> 1; + } + if 2 * mv.1 > right + (18 << 3) { + mv.1 = (right + (16 << 3)) >> 1; + } + + if 2 * mv.0 < top - (19 << 3) { + mv.0 = (top - (16 << 3)) >> 1; + } + if 2 * mv.0 > bottom + (18 << 3) { + mv.0 = (bottom + (16 << 3)) >> 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Deterministic plane fill shared by every test (LCG, same sequence in + /// the hand-computed literals below). + fn lcg_plane(seed: u32, len: usize) -> Vec { + let mut out = vec![0u8; len]; + let mut s = seed; + for b in out.iter_mut() { + s = s.wrapping_mul(1664525).wrapping_add(1013904223); + *b = (s >> 16) as u8; + } + out + } + + const BORDER: usize = 32; + const STRIDE: usize = 104; // 40 visible + 2 * 32 border + const VIS_W: usize = 40; // 3 MB columns, last one partial + const VIS_H: usize = 36; // 3 MB rows, last one partial + const ROWS: usize = VIS_H + 2 * BORDER; + + fn plane() -> Vec { + lcg_plane(0x1234, STRIDE * ROWS) + } + + /// Reads visible-image pixel (`vx`, `vy`) out of a bordered plane. + fn vis(plane: &[u8], vx: usize, vy: usize) -> u8 { + plane[(vy + BORDER) * STRIDE + (vx + BORDER)] + } + + #[test] + fn extend_plane_replicates_edges_and_corners() { + let mut p = plane(); + // Distinct visible values, sentinel everywhere else. + for r in 0..VIS_H { + for c in 0..VIS_W { + p[(BORDER + r) * STRIDE + BORDER + c] = ((r * 7 + c * 3) % 251 + 4) as u8; + } + } + p[..BORDER * STRIDE].fill(0xEE); + p[(BORDER + VIS_H) * STRIDE..].fill(0xEE); + for r in 0..VIS_H { + let row = &mut p[(BORDER + r) * STRIDE..(BORDER + r) * STRIDE + STRIDE]; + row[..BORDER].fill(0xEE); + row[BORDER + VIS_W..].fill(0xEE); + } + + extend_plane(&mut p, STRIDE, VIS_W, VIS_H, BORDER); + + // Every sample of the bordered plane equals the nearest in-image sample. + for r in 0..ROWS { + for c in 0..STRIDE { + let vr = r.saturating_sub(BORDER).min(VIS_H - 1); + let vc = c.saturating_sub(BORDER).min(VIS_W - 1); + assert_eq!(p[r * STRIDE + c], vis(&p, vc, vr), "sample ({r},{c})"); + } + } + // Explicit corners (worst case of the rule above). + assert_eq!(p[0], vis(&p, 0, 0)); // top-left + assert_eq!(p[line_len() - 1], vis(&p, VIS_W - 1, 0)); // top-right + assert_eq!(p[(ROWS - 1) * STRIDE], vis(&p, 0, VIS_H - 1)); // bottom-left + assert_eq!( + p[ROWS * STRIDE - 1], + vis(&p, VIS_W - 1, VIS_H - 1) // bottom-right + ); + // The visible region itself is untouched. + for r in 0..VIS_H { + for c in 0..VIS_W { + assert_eq!( + p[(BORDER + r) * STRIDE + BORDER + c], + ((r * 7 + c * 3) % 251 + 4) as u8 + ); + } + } + } + + fn line_len() -> usize { + BORDER + VIS_W + BORDER + } + + #[test] + fn integer_mv_predict_is_a_plain_copy() { + let p = plane(); + let mut dst = [0u8; 16 * 16]; + + // Whole-pel luma MV (row=16, col=-8) → full-pel offset (x-1, y+2). + // mv.0 is the row component, mv.1 the column component. x=y=8 keeps + // every read inside the visible region of the unextended plane. + predict_luma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (16, -8), false, &mut dst, 16, 16, 16, + ); + for r in 0..16 { + for c in 0..16 { + assert_eq!(dst[r * 16 + c], vis(&p, 8 - 1 + c, 8 + 2 + r), "({r},{c})"); + } + } + + // Zero MV → identity copy. + predict_luma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (0, 0), false, &mut dst, 16, 16, 16, + ); + for r in 0..16 { + for c in 0..16 { + assert_eq!(dst[r * 16 + c], vis(&p, 8 + c, 8 + r), "({r},{c})"); + } + } + + // Chroma copy path, whole-pel chroma MV (row=-16, col=+8) + // → full-pel offset (x+1, y-2). + let mut dst8 = [0u8; 8 * 8]; + predict_chroma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 4, 4, (-16, 8), false, &mut dst8, 8, 8, 8, + ); + for r in 0..8 { + for c in 0..8 { + assert_eq!(dst8[r * 8 + c], vis(&p, 4 + 1 + c, 4 - 2 + r), "({r},{c})"); + } + } + } + + #[test] + fn sixtap_pure_horizontal_matches_hand_computed_values() { + let p = plane(); + let mut dst = [0u8; 4 * 4]; + + // mv = (0, 4): full-pel start (16, 12), fx = 4, fy = 0. + predict_luma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 16, 12, (0, 4), false, &mut dst, 4, 4, 4, + ); + + // Hand-computed from vp8_sub_pel_filters[4] = { 3, -16, 77, 77, -16, 3 } + // and vp8_sub_pel_filters[0] = { 0, 0, 128, 0, 0, 0 } (vertical is the + // exact identity over the clamped horizontal intermediate). + // out[0][0]: taps are visible pixels (12, 14..19) = [183, 106, 2, 87, 75, 198]: + // 183*3 - 106*16 + 2*77 + 87*77 - 75*16 + 198*3 + 64 = 5164 + // 5164 >> 7 = 40, already in 0..=255. + // out[1][2]: taps (13, 17..22) = [153, 188, 219, 13, 86, 194]: + // 153*3 - 188*16 + 219*77 + 13*77 - 86*16 + 194*3 + 64 = 14585 + // 14585 >> 7 = 113. + assert_eq!(dst[0], 40); + assert_eq!(dst[1 * 4 + 2], 113); + + // Full block against the tap-table reference formula. + for r in 0..4 { + for c in 0..4 { + let taps: Vec = (0..6) + .map(|k| i32::from(vis(&p, 16 + c - 2 + k as usize, 12 + r))) + .collect(); + let acc: i32 = taps + .iter() + .zip(SUB_PEL_FILTERS[4]) + .map(|(t, f)| t * f) + .sum::() + + 64; + assert_eq!( + dst[r * 4 + c], + (acc >> 7).clamp(0, 255) as u8, + "out[{r}][{c}] taps={taps:?} acc={acc}" + ); + } + } + } + + #[test] + fn sixtap_combined_phase_16x16_matches_hand_computed_values() { + let p = plane(); + let mut dst = [0u8; 16 * 16]; + + // mv = (14, 18): full-pel start (10, 9), fx = 2, fy = 6. + predict_luma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (14, 18), false, &mut dst, 16, 16, 16, + ); + + // vp8_sub_pel_filters[2] = { 2, -11, 108, 36, -8, 1 }, each + // intermediate clamped to 0..=255 (e.g. tmp[3][10] taps + // [75, 190, 18, 15, 104, 40], raw dot -184, -184 >> 7 = -2, clamped 0); + // vertical pass with vp8_sub_pel_filters[6] = { 1, -8, 36, 108, -11, 2 }. + // + // out[0][0]: horizontal taps are visible pixels (7, 8..13), giving the + // post-clamp intermediate column h_tmp = [41, 186, 229, 210, 95, 185]: + // 41*1 - 186*8 + 229*36 + 210*108 - 95*11 + 185*2 + 64 = 28866 + // 28866 >> 7 = 225, already in 0..=255. + // + // out[5][9]: horizontal taps are visible pixels (11, 15..20), + // h_tmp = [205, 8, 14, 189, 108, 4]: + // 205*1 - 8*8 + 14*36 + 189*108 - 108*11 + 4*2 + 64 = 19941 + // 19941 >> 7 = 155. + assert_eq!(dst[0], 225); + assert_eq!(dst[5 * 16 + 9], 155); + + // Full block against the two-pass reference formula. + let mut tmp = [0i32; 21 * 16]; + for i in 0..21 { + for j in 0..16 { + let acc: i32 = (0..6) + .map(|k| i32::from(vis(&p, 10 - 2 + j + k, 9 - 2 + i))) + .zip(SUB_PEL_FILTERS[2]) + .map(|(t, f)| t * f) + .sum::() + + 64; + tmp[i * 16 + j] = (acc >> 7).clamp(0, 255); + } + } + for r in 0..16 { + for c in 0..16 { + let acc: i32 = (0..6) + .map(|k| tmp[(r + k) * 16 + c]) + .zip(SUB_PEL_FILTERS[6]) + .map(|(t, f)| t * f) + .sum::() + + 64; + assert_eq!( + dst[r * 16 + c], + (acc >> 7).clamp(0, 255) as u8, + "out[{r}][{c}]" + ); + } + } + } + + #[test] + fn bilinear_chroma_matches_hand_computed_values() { + let p = plane(); + let mut dst = [0u8; 8 * 8]; + + // mv = (11, 5): full-pel start (4, 7), fx = 5, fy = 3. + predict_chroma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 4, 6, (11, 5), false, &mut dst, 8, 8, 8, + ); + + // Horizontal taps { 48, 80 } (phase 5), vertical { 80, 48 } (phase 3), + // both passes (dot + 64) >> 7, no clamp (provably in range). + // + // out[0][0]: tmp[0][0] = (160*48 + 96*80 + 64) >> 7 = 120 from visible + // pixels (4,7),(5,7); tmp[1][0] = (107*48 + 42*80 + 64) >> 7 = 66 + // from (4,8),(5,8). + // 120*80 + 66*48 + 64 = 12832, 12832 >> 7 = 100. + // out[3][7]: tmp[3][7] = 84, tmp[4][7] = 189; + // 84*80 + 189*48 + 64 = 15856, 15856 >> 7 = 123. + assert_eq!(dst[0], 100); + assert_eq!(dst[3 * 8 + 7], 123); + + // Full block against the two-pass reference formula. + let mut tmp = [0u16; 9 * 8]; + for i in 0..9 { + for j in 0..8 { + tmp[i * 8 + j] = ((i32::from(vis(&p, 4 + j, 7 + i)) * 48 + + i32::from(vis(&p, 4 + j + 1, 7 + i)) * 80 + + 64) + >> 7) as u16; + } + } + for r in 0..8 { + for c in 0..8 { + let acc = i32::from(tmp[r * 8 + c]) * 80 + i32::from(tmp[(r + 1) * 8 + c]) * 48 + 64; + assert_eq!(dst[r * 8 + c], (acc >> 7) as u8, "out[{r}][{c}]"); + } + } + } + + #[test] + fn umv_border_clamps_match_libvpx_arithmetic() { + let p = plane(); + let mut a = [0u8; 16 * 16]; + let mut b = [0u8; 16 * 16]; + + // Single-MB frame (vis 16x16): mb_to_left_edge = mb_to_top_edge = 0, + // mb_to_right_edge = mb_to_bottom_edge = 0. + // + // Luma: mv (-1000, -1000) < 0 - 152 → both components set to -128 + // (left - (16 << 3)); prediction must equal an explicit (-128, -128). + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-1000, -1000), true, &mut a, 16, 16, 16, + ); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-128, -128), false, &mut b, 16, 16, 16, + ); + assert_eq!(a, b); + + // Strict threshold: (-152, -152) is NOT clamped (condition is strict + // `<`), (-153, -153) IS clamped to (-128, -128). + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-152, -152), true, &mut a, 16, 16, 16, + ); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-152, -152), false, &mut b, 16, 16, 16, + ); + assert_eq!(a, b); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-153, -153), true, &mut a, 16, 16, 16, + ); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-128, -128), false, &mut b, 16, 16, 16, + ); + assert_eq!(a, b); + + // Right/bottom: mv (4000, 4000) > 0 + 144 → set to +128. + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (4000, 4000), true, &mut a, 16, 16, 16, + ); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (128, 128), false, &mut b, 16, 16, 16, + ); + assert_eq!(a, b); + + // Chroma: 2 * (-2000) < -152 → (-128 >> 1) = -64 per component. + let mut ca = [0u8; 8 * 8]; + let mut cb = [0u8; 8 * 8]; + predict_chroma( + &p, STRIDE, BORDER, 8, 8, 0, 0, (-2000, -2000), true, &mut ca, 8, 8, 8, + ); + predict_chroma( + &p, STRIDE, BORDER, 8, 8, 0, 0, (-64, -64), false, &mut cb, 8, 8, 8, + ); + assert_eq!(ca, cb); + + // Chroma right/bottom: 2 * 2000 > 144 → (128 >> 1) = 64. + predict_chroma( + &p, STRIDE, BORDER, 8, 8, 0, 0, (2000, 2000), true, &mut ca, 8, 8, 8, + ); + predict_chroma( + &p, STRIDE, BORDER, 8, 8, 0, 0, (64, 64), false, &mut cb, 8, 8, 8, + ); + assert_eq!(ca, cb); + + // An in-range MV with need_clamp=true must pass through untouched. + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (10, -10), true, &mut a, 16, 16, 16, + ); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (10, -10), false, &mut b, 16, 16, 16, + ); + assert_eq!(a, b); + } +} diff --git a/crates/ec-vp8/src/modes.rs b/crates/ec-vp8/src/modes.rs index b799e265..aceadaff 100644 --- a/crates/ec-vp8/src/modes.rs +++ b/crates/ec-vp8/src/modes.rs @@ -323,3 +323,224 @@ pub fn read_sub_mv_ref(d: &mut BoolDecoder<'_>, ctx: usize) -> SubMvRef { v => unreachable!("sub_mv_ref tree produced {v}"), } } + +/// First subblock of each SPLITMV subset, per partition shape (libvpx +/// `vp8_mbsplit_offset`; shapes 16x8, 8x16, 8x8, 4x4). +pub const MBSPLIT_OFFSET: [[u8; 16]; 4] = [ + [0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], +]; + +/// Subblocks filled by one subset, per partition shape (libvpx +/// `mbsplit_fill_count`). +pub const MBSPLIT_FILL_COUNT: [usize; 4] = [8, 8, 4, 1]; + +/// Subblock indices each subset fills, per shape (libvpx +/// `mbsplit_fill_offset`; subset j starts at j * fill_count). +pub const MBSPLIT_FILL_OFFSET: [[u8; 16]; 4] = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + [0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15], + [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], +]; + +/// Decode one motion-vector component (§17.1, libvpx `read_mvcomponent`): +/// either a 3-bit small value off [`SMALL_MV_TREE`] or a 9-bit long form +/// whose bit 3 is sometimes implicit, then a sign flag. +pub fn read_mv_component(d: &mut BoolDecoder<'_>, probs: &[u8; MVP_COUNT]) -> i16 { + let mut x: i32 = 0; + if d.read_bool(probs[MVP_IS_SHORT]) { + // Large: bits 0..2, then 8..4 (bit 3 is implicit below). + for i in 0..3 { + x += i32::from(d.read_bool(probs[MVP_BITS + i])) << i; + } + let mut i = 8; + loop { + x += i32::from(d.read_bool(probs[MVP_BITS + i])) << i; + i -= 1; + if i <= 3 { + break; + } + } + if (x & 0xFFF0) == 0 || d.read_bool(probs[MVP_BITS + 3]) { + x += 8; + } + } else { + x = i32::from(d.read_tree(&SMALL_MV_TREE, &probs[MVP_SHORT..MVP_SHORT + 7])); + } + if x != 0 && d.read_bool(probs[MVP_SIGN]) { + x = -x; + } + x as i16 +} + +/// Both components of a whole-block motion vector (§17.1); the decoded +/// quarter-pel components double into the decoder's eighth-pel units. +pub fn read_mv(d: &mut BoolDecoder<'_>, probs: &[[u8; MVP_COUNT]; 2]) -> (i16, i16) { + ( + read_mv_component(d, &probs[0]).wrapping_mul(2), + read_mv_component(d, &probs[1]).wrapping_mul(2), + ) +} + +/// Flip a candidate motion vector when the reference it was coded +/// against has a different sign bias than the current reference +/// (§16.3, libvpx `mv_bias`). +pub fn mv_bias(from_bias: bool, to_bias: bool, mv: (i16, i16)) -> (i16, i16) { + if from_bias != to_bias { + (-mv.0, -mv.1) + } else { + mv + } +} + +/// One neighbour macroblock's motion-vector census input (§16.3). +pub struct MvNeighbor { + /// The MB is intra-coded (no MV contribution at all). + pub intra: bool, + /// The MB is inter-coded with a zero motion vector (counts like + /// intra in the census). + pub zero: bool, + /// The MB's motion vector (already sign-bias-adjusted if applicable + /// — pass `sign_bias` and the census applies it). + pub mv: (i16, i16), + /// The MB is SPLITMV (feeds the split census count). + pub is_split: bool, + /// The sign bias of the reference the MB's MV points into. + pub sign_bias: bool, +} + +/// Slot indices of the census result (§16.3). +pub const CNT_INTRA: usize = 0; +/// Slot index: nearest-candidate count. +pub const CNT_NEAREST: usize = 1; +/// Slot index: near-candidate count. +pub const CNT_NEAR: usize = 2; +/// Slot index: split-neighbour count. +pub const CNT_SPLITMV: usize = 3; + +/// The neighborhood motion-vector census (§16.3, libvpx +/// `find_near_mvs` inlined in `read_mb_modes_mv`): up to three distinct +/// candidate vectors with per-slot counts, scanned above, left, +/// above-left; each inter neighbour counts 2/2/1 toward either the +/// candidate slot it extends or the zero/intra count. +pub fn find_near_mvs( + above: MvNeighbor, + left: MvNeighbor, + aboveleft: MvNeighbor, + to_bias: bool, +) -> ([(i16, i16); 4], [i32; 4]) { + let mut mvs = [(0i16, 0i16); 4]; + let mut cnt = [0i32; 4]; + let mut idx = 0usize; + let mut cntx = 0usize; + + // Above: the first candidate is pushed unconditionally. + if !above.intra { + if !above.zero { + idx += 1; + mvs[idx] = mv_bias(above.sign_bias, to_bias, above.mv); + cntx += 1; + } + cnt[cntx] += 2; + } + for (mb, w) in [(&left, 2), (&aboveleft, 1)] { + if !mb.intra { + if !mb.zero { + let this = mv_bias(mb.sign_bias, to_bias, mb.mv); + if this != mvs[idx] { + idx += 1; + mvs[idx] = this; + cntx += 1; + } + cnt[cntx] += w; + } else { + cnt[CNT_INTRA] += i32::from(w); + } + } + } + + // libvpx checks `cnt[CNT_SPLITMV]` BEFORE computing it (the write + // happens later in the same branch), so the above-left merge is + // effectively dead there; ported as-is with the same dead guard. + if cnt[CNT_SPLITMV] != 0 && mvs[idx] == mvs[CNT_NEAREST] { + cnt[CNT_NEAREST] += 1; + } + cnt[CNT_SPLITMV] = i32::from(above.is_split) * 2 + + i32::from(left.is_split) * 2 + + i32::from(aboveleft.is_split); + + if cnt[CNT_NEAR] > cnt[CNT_NEAREST] { + cnt.swap(CNT_NEAR, CNT_NEAREST); + mvs.swap(CNT_NEAR, CNT_NEAREST); + } + (mvs, cnt) +} + +/// Per-MB motion-vector clamp edges in eighth-pels (libvpx +/// `mb_to_*_edge`): distance from the MB's edge to the frame edge. +pub fn mb_edges(col: usize, row: usize, mb_cols: usize, mb_rows: usize) -> (i32, i32, i32, i32) { + ( + -((i32::try_from(col).unwrap() * 16) << 3), + ((i32::try_from(mb_cols - 1 - col).unwrap() * 16) << 3), + -((i32::try_from(row).unwrap() * 16) << 3), + ((i32::try_from(mb_rows - 1 - row).unwrap() * 16) << 3), + ) +} + +/// Clamp a candidate MV into the current MB's allowed range plus a +/// 128-eighth-pel margin (§16.2, libvpx `vp8_clamp_mv2`). +pub fn clamp_mv2(mv: &mut (i16, i16), edges: (i32, i32, i32, i32)) { + let (l, r, t, b) = edges; + let c = i32::from(mv.1); + if c < l - 128 { + mv.1 = (l - 128) as i16; + } else if c > r + 128 { + mv.1 = (r + 128) as i16; + } + let ro = i32::from(mv.0); + if ro < t - 128 { + mv.0 = (t - 128) as i16; + } else if ro > b + 128 { + mv.0 = (b + 128) as i16; + } +} + +/// Whether an explicit MV exceeds the MB's bounds (libvpx +/// `vp8_check_mv_bounds`): strictly outside, no margin. +pub fn mv_out_of_bounds(mv: (i16, i16), edges: (i32, i32, i32, i32)) -> bool { + let (l, r, t, b) = edges; + i32::from(mv.1) < l || i32::from(mv.1) > r || i32::from(mv.0) < t || i32::from(mv.0) > b +} + +/// Chroma motion vector for a whole-MB mode (libvpx +/// `vp8_build_inter16x16_predictors_mb`): halve each component with +/// round-half-away-from-zero (`x += 1 | (x >> 31); x /= 2`). +pub fn chroma_mv_whole(mv: (i16, i16)) -> (i16, i16) { + fn half(x: i16) -> i16 { + let x = i32::from(x); + ((x + (1 | (x >> 31))) / 2) as i16 + } + (half(mv.0), half(mv.1)) +} + +/// Chroma motion vector for one 8x8 quadrant of a SPLITMB (libvpx +/// `build_4x4uvmvs`): sum the quadrant's four subblock vectors, then +/// divide by 8 with round-half-away-from-zero +/// (`t += 4 + (t >> 31) * 8; t /= 8`). +pub fn chroma_mv_split(quadrant: &[(i16, i16); 4]) -> (i16, i16) { + fn eighth(parts: [i16; 4]) -> i16 { + let t = i32::from(parts[0]) + + i32::from(parts[1]) + + i32::from(parts[2]) + + i32::from(parts[3]); + let t = t + 4 + (t >> 31) * 8; + (t / 8) as i16 + } + ( + eighth([quadrant[0].0, quadrant[1].0, quadrant[2].0, quadrant[3].0]), + eighth([quadrant[0].1, quadrant[1].1, quadrant[2].1, quadrant[3].1]), + ) +} diff --git a/lanes/vp8.report.md b/lanes/vp8.report.md index e4e07888..667e781c 100644 --- a/lanes/vp8.report.md +++ b/lanes/vp8.report.md @@ -9,7 +9,7 @@ Never merged, never pushed. Pins untouched (no ec-av1 changes at all). |---|---|---| | M1 bool decoder + frame tag + full first-partition header | **done/verified** | commit `57b5a53a`; 12 unit tests green; real vpxenc/ffmpeg streams (6 sizes/q, 8-token-partition, WebP still) parse with exact partition tiling, correct dims (incl. 76x52 non-MB-aligned), 0 desyncs | | M2 key-frame-only decode, sample-exact vs ffmpeg | **root cause FIXED, verified at frame level** — decision-exact vs the reference model for the whole frame (19131 reads, 0 diffs) and frame-0 byte-exact vs ffmpeg on ALL 8 kf/mparts fixtures; the `keyframe_exact` suite goes 3/3 when inter frames land (each fixture carries 1 KF + inter frames), see M3 | commits `20f7d742`, `072f842f`, M2-fix commit (this one) | -| M3 inter frames | **not attempted** (fixtures + spec recon done) | `clip-obs-320x192.ivf` (169 fr, 4 KFs), `altref-160x96.ivf`, `mparts-160x96.ivf` (8 partitions), `gop-160x96.ivf`; §16-18 read; inter trees/tables in `modes.rs` | +| M3 inter frames | **implemented end-to-end, walled on one parse divergence** — full inter pipeline lands (mode/MV parse incl. SPLITMV, census, MC via `mc.rs` w/ libvpx-fuzzed predictors, ref buffers, entropy revert, LF deltas); inter frames decode without desync but pixels diverge from MB(0,5) of gop-160x96 frame 1 rightward (51% frame match); `EC_VP8_TRACE` B-line read tracing added to `BoolDecoder` mirroring the Python model's, diff is the next step | this commit (WIP) | | M4 public API + docs | **not attempted** | `Decoder::decode(&[u8]) -> Result>` exists; ec-av1-style `decode_stream` not yet | ## What shipped (M1 `57b5a53a`, M2 WIP `20f7d742`)