forge
Explore
Log in

Don't you dare go Hollow

vp9kf: VP9 inter-frame syntax parses block-for-block identical to libvpx

Browse files at this commit

834983e6e328dad24c76a9f9ff273f1db2400f0aAhmet Kaan GümüşParent: bd4fadc
Slice 1 of inter-frame support: an inter frame is now parsed end to end
(compressed header, mode info, MVs, references) and every block matches
libvpx 1.15's own instrumented decoder on the test stream - frame 1
1213/1213, frame 2 1851/1851 on row/col/bsize/tx/mode/skip/seg/ref0/ref1/
interp/MV - with the frame-1 compressed header bit-identical (1200/1200
bools) and frame 2 likewise.

Causes closed while getting there, each ported from libvpx with its line:
update_mv_probs is MV_UPDATE_PROB + seven literal bits + (lit<<1)|1, NOT
diff_update_prob; keyframe partition probs are a const selected by
get_partition_probs and must never be stored in a FrameContext (stored
contexts are new(false), the active keyframe copy new(true) + a
reset_inter_partition before the save); vp9_switchable_interp_tree is
{0,2,-1,-2} (libvpx's EIGHTTAP/EIGHTTAP_SMOOTH/EIGHTTAP_SHARP #defines,
not the spec's naming order); mv_ref_blocks' POSITION is {row,col} and one
accessor added .0 to the column; clamp_mv_ref's edge arithmetic is signed
(usize underflowed on a frame's partial last row) and clamps the COLUMN
with the left/right edges and the ROW with the top/bottom ones; and the
mode-derived candidate-count override sits AFTER libvpx's Done: label, so
an early exit skips it - reproduced bug-for-bug.

This slice is SYNTAX ONLY: decode() still refuses inter frames by name and
no inter pixel is produced. The keyframe path still decodes to pixels and
keyframe_exact is green.

Verified by an independent reviewer in three passes (structural claims
re-derived from libvpx source, the identity comparison re-implemented
independently, a dropped-field audit of the two stale fields, and
delta re-verification of the clamp/error-propagation/gate fixes).
crates/ec-vp9/src/decode.rsmodified+574 -21
@@ -76,6 +76,44 @@ pub struct Decoder {
76 refs: [Option<Picture>; 8],76 refs: [Option<Picture>; 8],
77 /// Frame scratch, live only inside `decode_keyframe`.77 /// Frame scratch, live only inside `decode_keyframe`.
78 planes: Option<Planes>,78 planes: Option<Planes>,
79+ /// The four stored frame contexts (spec 6.2 `frame_context_idx`).
80+ frame_ctxs: [FrameContext; 4],
81+ /// The previous frame's per-8x8 MV field and segment map
82+ /// (`prev_frame->mvs` / `last_frame_seg_map`).
83+ prev_mvs: Vec<crate::inter::MvRef>,
84+ prev_seg: Vec<u8>,
85+ last: LastFrameFacts,
86+ /// Live only while an inter frame is being parsed.
87+ iw: Option<InterWalk>,
88+ /// Frames parsed by `decode_syntax` (the dump's frame index).
89+ frames_seen: usize,
90+ /// Mode-info blocks parsed in the most recent inter frame (0 otherwise).
91+ syntax_blocks: usize,
92+}
93+
94+/// What `use_prev_frame_mvs` (decodeframe.c:3023) tests about the last frame.
95+#[derive(Clone, Copy, Default)]
96+struct LastFrameFacts {
97+ width: u32,
98+ height: u32,
99+ intra_only: bool,
100+ show_frame: bool,
101+ key: bool,
102+}
103+
104+/// State of one inter-syntax frame walk.
105+struct InterWalk {
106+ ifs: crate::inter::InterFrameState,
107+ sign_bias: [bool; 4],
108+ use_prev: bool,
109+ seg_map: Vec<u8>,
110+ mvs: Vec<crate::inter::MvRef>,
111+ prev_seg: Vec<u8>,
112+ prev_mvs: Vec<crate::inter::MvRef>,
113+ tile_col_end: usize,
114+ frame_index: usize,
115+ /// Mode-info blocks parsed in this frame (the harness's count gate).
116+ blocks: usize,
79 }117 }
80 118
81 impl Decoder {119 impl Decoder {
@@ -86,9 +124,25 @@ impl Decoder {
86 ctx: FrameContext::new(true),124 ctx: FrameContext::new(true),
87 refs: [const { None }; 8],125 refs: [const { None }; 8],
88 planes: None,126 planes: None,
127+ frame_ctxs: {
128+ let d = FrameContext::new(false);
129+ [d.clone(), d.clone(), d.clone(), d]
130+ },
131+ prev_mvs: Vec::new(),
132+ prev_seg: Vec::new(),
133+ last: LastFrameFacts::default(),
134+ iw: None,
135+ frames_seen: 0,
136+ syntax_blocks: 0,
89 }137 }
90 }138 }
91 139
140+ /// Mode-info blocks the most recent inter frame parsed; `0` for a keyframe
141+ /// or before any frame. The syntax harness pins this number.
142+ pub fn last_frame_blocks(&self) -> usize {
143+ self.syntax_blocks
144+ }
145+
92 /// Decode one frame (or one superframe chunk); returns the picture146 /// Decode one frame (or one superframe chunk); returns the picture
93 /// when a frame is for display. Hidden frames still update state.147 /// when a frame is for display. Hidden frames still update state.
94 pub fn decode(&mut self, frame: &[u8]) -> Result<Option<Picture>> {148 pub fn decode(&mut self, frame: &[u8]) -> Result<Option<Picture>> {
@@ -131,9 +185,29 @@ impl Decoder {
131 "this lane decodes keyframes only",185 "this lane decodes keyframes only",
132 ));186 ));
133 }187 }
134- // A keyframe resets the frame context (spec 7.2) before the188+ self.decode_key_frame(&hdr, frame)
135- // compressed header codes this frame's updates on top.189+ }
136- self.ctx = FrameContext::new(hdr.frame_type == FrameType::Key);190+
191+ /// Decode one key frame through to pixels and refresh every slot.
192+ fn decode_key_frame(&mut self, hdr: &FrameHeader, frame: &[u8]) -> Result<Option<Picture>> {
193+ let hdr = hdr.clone();
194+ // setup_past_independence (spec 7.2): a key frame resets the frame
195+ // context, so every STORED context goes back to the inter defaults.
196+ // The keyframe's own mode info reads the const `vp9_kf_partition_probs`
197+ // (libvpx `get_partition_probs`), which our `new(true)` models on the
198+ // active copy only.
199+ let d = FrameContext::new(false);
200+ self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d];
201+ self.ctx = FrameContext::new(true);
202+ self.prev_mvs.clear();
203+ self.prev_seg.clear();
204+ self.last = LastFrameFacts {
205+ width: hdr.width,
206+ height: hdr.height,
207+ intra_only: hdr.intra_only,
208+ show_frame: hdr.show_frame,
209+ key: true,
210+ };
137 // [scratch probe] EC_VP9_FORCE_UH / EC_VP9_FORCE_HSZ: override the211 // [scratch probe] EC_VP9_FORCE_UH / EC_VP9_FORCE_HSZ: override the
138 // uncompressed-header size / header_size_in_bytes split for diagnosis.212 // uncompressed-header size / header_size_in_bytes split for diagnosis.
139 let hdr = {213 let hdr = {
@@ -147,13 +221,17 @@ impl Decoder {
147 h221 h
148 };222 };
149 let hdr_start = hdr.uncompressed_header_size as usize;223 let hdr_start = hdr.uncompressed_header_size as usize;
150- let tx_mode = read_compressed_header(224+ let ch = read_compressed_header(
151 &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize],225 &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize],
152 &mut self.ctx,226 &mut self.ctx,
153- hdr.quantization.lossless(),227+ &hdr,
154 )?;228 )?;
155 229
156- let pic = self.decode_keyframe(&hdr, frame, tx_mode)?;230+ let pic = self.decode_keyframe(&hdr, frame, ch.tx_mode)?;
231+ if hdr.refresh_frame_context {
232+ self.ctx.reset_inter_partition();
233+ self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.clone();
234+ }
157 // Reference refresh (spec 8.10): a keyframe updates all slots.235 // Reference refresh (spec 8.10): a keyframe updates all slots.
158 for slot in self.refs.iter_mut() {236 for slot in self.refs.iter_mut() {
159 *slot = Some(pic.clone());237 *slot = Some(pic.clone());
@@ -161,6 +239,438 @@ impl Decoder {
161 Ok(if hdr.show_frame { Some(pic) } else { None })239 Ok(if hdr.show_frame { Some(pic) } else { None })
162 }240 }
163 241
242+ /// Parse one frame's syntax: keyframes decode through to pixels, inter
243+ /// frames are parsed (headers, mode info, MVs) with no reconstruction and
244+ /// no picture. `decode` still refuses inter frames.
245+ pub fn decode_syntax(&mut self, frame: &[u8]) -> Result<()> {
246+ for sub in superframe::split(frame)? {
247+ let index = self.frames_seen;
248+ self.frames_seen += 1;
249+ let hdr = self.parser.parse_frame(sub)?;
250+ if hdr.show_existing_frame {
251+ continue;
252+ }
253+ if hdr.profile != 0 {
254+ return Err(Error::unsupported(
255+ format!("vp9 profile {}", hdr.profile),
256+ "this lane decodes profile 0 only",
257+ ));
258+ }
259+ if hdr.frame_type == FrameType::Key {
260+ // Propagate: a corrupt keyframe leaves a half-updated frame
261+ // context, prev-frame MV field and reference slots behind, so
262+ // any inter-frame dump after it would be meaningless evidence.
263+ self.decode_key_frame(&hdr, sub)?;
264+ } else if hdr.intra_only {
265+ return Err(Error::unsupported(
266+ "vp9 intra-only",
267+ "the inter-syntax lane covers inter frames only",
268+ ));
269+ } else {
270+ self.decode_inter_syntax_frame(&hdr, sub, index)?;
271+ }
272+ }
273+ Ok(())
274+ }
275+
276+ /// Inter-frame syntax walk: compressed header, then every block's mode
277+ /// info and MVs. Tokens are decoded to keep the entropy stream aligned;
278+ /// nothing is predicted or reconstructed.
279+ fn decode_inter_syntax_frame(&mut self, hdr: &FrameHeader, frame: &[u8], index: usize) -> Result<()> {
280+ // Frame-context bookkeeping (spec 6.2 / libvpx `vp9_decode_frame`):
281+ // 3 resets every stored context, 2 resets the selected one; 1 means
282+ // "reset after this frame" and takes no action at frame start.
283+ if hdr.reset_frame_context == 3 {
284+ let d = FrameContext::new(false);
285+ self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d];
286+ } else if hdr.reset_frame_context == 2 {
287+ self.frame_ctxs[hdr.frame_context_idx as usize] = FrameContext::new(false);
288+ }
289+ self.ctx = self.frame_ctxs[hdr.frame_context_idx as usize].clone();
290+
291+ let hdr_start = hdr.uncompressed_header_size as usize;
292+ if crate::trace_enabled() {
293+ eprintln!("CHSTART frame={index}");
294+ }
295+ let ch = read_compressed_header(
296+ &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize],
297+ &mut self.ctx,
298+ hdr,
299+ )?;
300+
301+ if crate::interdump_enabled() {
302+ let mut line = format!("PPFLAT frame={index}");
303+ for row in self.ctx.partition.iter() {
304+ for v in row.iter() {
305+ line.push_str(&format!(" {v}"));
306+ }
307+ }
308+ eprintln!("{line}");
309+ }
310+
311+ // INTRA_FRAME's sign bias is 0 by definition; the coded three land at
312+ // LAST/GOLDEN/ALTREF.
313+ let sign_bias = [
314+ false,
315+ hdr.ref_frame_sign_bias[0],
316+ hdr.ref_frame_sign_bias[1],
317+ hdr.ref_frame_sign_bias[2],
318+ ];
319+ let mut ifs = crate::inter::InterFrameState {
320+ reference_mode: ch.reference_mode,
321+ ..Default::default()
322+ };
323+ if ch.reference_mode != crate::inter::SINGLE_REFERENCE {
324+ crate::inter::setup_compound_reference_mode(&mut ifs, sign_bias);
325+ }
326+ let use_prev = !hdr.error_resilient_mode
327+ && hdr.width == self.last.width
328+ && hdr.height == self.last.height
329+ && !self.last.intra_only
330+ && self.last.show_frame
331+ && !self.last.key;
332+
333+ let mi_cols = hdr.mi_cols() as usize;
334+ let mi_rows = hdr.mi_rows() as usize;
335+ let sb64_cols = mi_cols.div_ceil(SB_MI);
336+ let sb64_rows = mi_rows.div_ceil(SB_MI);
337+ let tile_cols = 1usize << hdr.tile_info.cols_log2;
338+ let tile_rows = 1usize << hdr.tile_info.rows_log2;
339+
340+ self.iw = Some(InterWalk {
341+ ifs,
342+ sign_bias,
343+ use_prev,
344+ seg_map: vec![0; mi_cols * mi_rows],
345+ mvs: vec![crate::inter::MvRef::default(); mi_cols * mi_rows],
346+ prev_seg: std::mem::take(&mut self.prev_seg),
347+ prev_mvs: std::mem::take(&mut self.prev_mvs),
348+ tile_col_end: mi_cols,
349+ frame_index: index,
350+ blocks: 0,
351+ });
352+
353+ let mut data: &[u8] = &frame[hdr_start + hdr.header_size_in_bytes as usize..];
354+ let mut tiles: Vec<&[u8]> = Vec::with_capacity(tile_cols * tile_rows);
355+ for tr in 0..tile_rows {
356+ for tc in 0..tile_cols {
357+ let last = tr == tile_rows - 1 && tc == tile_cols - 1;
358+ if last {
359+ tiles.push(data);
360+ } else {
361+ ensure(data.len() >= 4, "truncated tile size")?;
362+ let sz = u32::from_be_bytes(data[..4].try_into().unwrap()) as usize;
363+ data = &data[4..];
364+ ensure(data.len() >= sz, "truncated tile data")?;
365+ tiles.push(&data[..sz]);
366+ data = &data[sz..];
367+ }
368+ }
369+ }
370+
371+ // The loop-filter grids are never written on this path (no
372+ // reconstruction), but the walk's signature carries them.
373+ let mut grids = LfGrids {
374+ level8: vec![0; mi_cols * mi_rows],
375+ blk: vec![(0u8, 0u32, 0u32); mi_cols * mi_rows],
376+ otx: vec![0; mi_cols * mi_rows],
377+ mi_cols,
378+ mi_rows,
379+ };
380+ let mut ti = 0usize;
381+ for tr in 0..tile_rows {
382+ let row_lo = ((sb64_rows * tr) >> hdr.tile_info.rows_log2) * SB_MI;
383+ let row_hi = (((sb64_rows * (tr + 1)) >> hdr.tile_info.rows_log2) * SB_MI).min(mi_rows);
384+ for tc in 0..tile_cols {
385+ let col_lo = ((sb64_cols * tc) >> hdr.tile_info.cols_log2) * SB_MI;
386+ let col_hi =
387+ (((sb64_cols * (tc + 1)) >> hdr.tile_info.cols_log2) * SB_MI).min(mi_cols);
388+ if let Some(w) = self.iw.as_mut() {
389+ w.tile_col_end = col_hi;
390+ }
391+ if crate::trace_enabled() {
392+ eprintln!("TILE {} bytes frame={index}", tiles[ti].len());
393+ }
394+ let mut r = crate::bool::BoolDecoder::new(tiles[ti])?;
395+ ti += 1;
396+ let mut ectx = [
397+ PlaneContexts::new(mi_cols * 2),
398+ PlaneContexts::new(mi_cols),
399+ PlaneContexts::new(mi_cols),
400+ ];
401+ let mut mi = MiState::new(mi_cols, mi_rows);
402+ ectx.iter_mut().for_each(|p| p.above.fill(0));
403+ mi.above_seg.fill(0);
404+ for sb_row in (row_lo..row_hi).step_by(SB_MI) {
405+ ectx.iter_mut().for_each(|p| p.left = [0; 32]);
406+ mi.left_seg = [0; 32];
407+ for sb_col in (col_lo..col_hi).step_by(SB_MI) {
408+ self.decode_partition(
409+ &mut r,
410+ &mut mi,
411+ &mut ectx,
412+ &mut grids,
413+ &[[0u8; 2]; 8],
414+ hdr,
415+ sb_row,
416+ sb_col,
417+ 4,
418+ row_lo,
419+ col_lo,
420+ ch.tx_mode,
421+ )?;
422+ }
423+ }
424+ ensure(r.overreads() == 0, "tile bool decoder desync")?;
425+ }
426+ }
427+
428+ // The walk state is consumed below, so the block count the harness pins
429+ // has to be captured first.
430+ self.syntax_blocks = self.iw.as_ref().map_or(0, |w| w.blocks);
431+ let w = self.iw.take().expect("inter walk state");
432+ self.prev_mvs = w.mvs;
433+ self.prev_seg = w.seg_map;
434+ self.last = LastFrameFacts {
435+ width: hdr.width,
436+ height: hdr.height,
437+ intra_only: hdr.intra_only,
438+ show_frame: hdr.show_frame,
439+ key: false,
440+ };
441+ if hdr.refresh_frame_context {
442+ self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.clone();
443+ }
444+ if crate::interdump_enabled() {
445+ eprintln!(
446+ "CHSUM frame={index} tx_mode={} ref_mode={} allow_hp={} interp={} tile_rows={} tile_cols={} pp12={:?} pp0={:?} pp13={:?}",
447+ ch.tx_mode,
448+ ch.reference_mode,
449+ hdr.allow_high_precision_mv,
450+ hdr.interpolation_filter as u8,
451+ hdr.tile_info.rows_log2,
452+ hdr.tile_info.cols_log2,
453+ self.ctx.partition[12],
454+ self.ctx.partition[0],
455+ self.ctx.partition[13]
456+ );
457+ }
458+ Ok(())
459+ }
460+
461+ /// One inter block's syntax (`read_inter_frame_mode_info` + the MV field
462+ /// `vp9_read_mode_info` stores for the next frame).
463+ #[allow(clippy::too_many_arguments)]
464+ fn read_inter_block_info(
465+ &mut self,
466+ r: &mut crate::bool::BoolDecoder,
467+ mi: &MiState,
468+ hdr: &FrameHeader,
469+ row: usize,
470+ col: usize,
471+ sb_type: usize,
472+ x_mis: usize,
473+ y_mis: usize,
474+ tile_row_start: usize,
475+ tile_col_start: usize,
476+ tx_mode: u8,
477+ ) -> Result<MiInfo> {
478+ // BLOCK_4X4/4X8/8X4 are the SPLIT/VERT/HORZ partitions of an 8x8.
479+ let partition = match sb_type {
480+ 0 => 3u8,
481+ 1 => 2u8,
482+ 2 => 1u8,
483+ _ => 0u8,
484+ };
485+ let w = self.iw.as_mut().expect("inter walk state");
486+ let prev_seg = std::mem::take(&mut w.prev_seg);
487+ let prev_mvs = std::mem::take(&mut w.prev_mvs);
488+ let ctx = crate::inter::InterBlockCtx {
489+ seg: &hdr.segmentation,
490+ ifs: w.ifs,
491+ sign_bias: w.sign_bias,
492+ allow_hp: hdr.allow_high_precision_mv,
493+ frame_interp: hdr.interpolation_filter as u8,
494+ tx_mode,
495+ mi_rows: mi.mi_rows,
496+ mi_cols: mi.mi_cols,
497+ tile_row_start,
498+ tile_col_start,
499+ tile_col_end: w.tile_col_end,
500+ last_seg: (!prev_seg.is_empty()).then_some(&prev_seg[..]),
501+ prev_mvs: (w.use_prev && !prev_mvs.is_empty()).then_some(&prev_mvs[..]),
502+ };
503+ let info = crate::inter::read_inter_frame_mode_info(
504+ r,
505+ mi,
506+ &ctx,
507+ &self.ctx,
508+ row,
509+ col,
510+ sb_type,
511+ x_mis,
512+ y_mis,
513+ partition,
514+ &mut w.seg_map,
515+ );
516+ if let Ok(info) = &info {
517+ w.blocks += 1;
518+ for dy in 0..y_mis {
519+ for dx in 0..x_mis {
520+ let i = (row + dy) * mi.mi_cols + col + dx;
521+ w.mvs[i] = crate::inter::MvRef {
522+ ref_frame: info.ref_frame,
523+ mv: info.mv,
524+ };
525+ }
526+ }
527+ if crate::interdump_enabled() {
528+ eprintln!(
529+ "MODE {} {} {} {} {} {} {} {} {} tpos=0 ref0={} ref1={} mvrow={} mvcol={} if={}",
530+ w.frame_index,
531+ row,
532+ col,
533+ sb_type,
534+ info.tx_size,
535+ info.mode,
536+ info.uv_mode,
537+ u8::from(info.skip),
538+ info.segment,
539+ info.ref_frame[0],
540+ info.ref_frame[1],
541+ info.mv[0].0,
542+ info.mv[0].1,
543+ info.interp_filter
544+ );
545+ }
546+ }
547+ w.prev_seg = prev_seg;
548+ w.prev_mvs = prev_mvs;
549+ info
550+ }
551+
552+ /// Tokens for one inter block: same entropy walk as the keyframe path,
553+ /// but no prediction and no residual add. `is_inter` selects the
554+ /// coefficient-probability ref axis.
555+ #[allow(clippy::too_many_arguments)]
556+ fn decode_inter_block_tokens(
557+ &mut self,
558+ r: &mut crate::bool::BoolDecoder,
559+ mi: &MiState,
560+ ectx: &mut [PlaneContexts; 3],
561+ hdr: &FrameHeader,
562+ info: &MiInfo,
563+ row: usize,
564+ col: usize,
565+ sb_type: usize,
566+ bw: usize,
567+ bh: usize,
568+ ) -> Result<()> {
569+ let n4w = if sb_type < 3 {
570+ [2, 1, 1]
571+ } else {
572+ [bw * 2, bw, bw]
573+ };
574+ let n4h = if sb_type < 3 {
575+ [2, 1, 1]
576+ } else {
577+ [bh * 2, bh, bh]
578+ };
579+ if info.skip {
580+ // dec_reset_skip_context
581+ for plane in 0..3usize {
582+ let s = usize::from(plane != 0);
583+ let offx = (col << 1) >> s;
584+ let offy = (row << 1) >> s;
585+ for i in 0..n4w[plane] {
586+ ectx[plane].above[offx + i] = 0;
587+ }
588+ let lrows = 32usize >> s;
589+ for i in 0..n4h[plane].min(lrows) {
590+ ectx[plane].left[(offy + i) % lrows] = 0;
591+ }
592+ }
593+ return Ok(());
594+ }
595+ let mb_to_right = ((mi.mi_cols as isize - bw as isize - col as isize) * 64) as i32;
596+ let mb_to_bottom = ((mi.mi_rows as isize - bh as isize - row as isize) * 64) as i32;
597+ let lossless = hdr.quantization.lossless();
598+ for plane in 0..3usize {
599+ let s = usize::from(plane != 0);
600+ let tx_size = if plane == 0 {
601+ info.tx_size
602+ } else {
603+ get_uv_tx_size(info.tx_size, sb_type)
604+ };
605+ let step = 1usize << tx_size;
606+ let max_blocks_wide =
607+ (n4w[plane] as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize;
608+ let max_blocks_high =
609+ (n4h[plane] as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize;
610+ for brow in (0..max_blocks_high).step_by(step) {
611+ for bcol in (0..max_blocks_wide).step_by(step) {
612+ let tx_type = if plane != 0 || lossless || info.is_inter {
613+ DCT_DCT
614+ } else {
615+ MODE_TO_TXTYPE_LOOKUP[info.mode as usize] as usize
616+ };
617+ let (scan, nb) = scan_for(tx_size, tx_type);
618+ let q = hdr.segment_dequant(info.segment as usize);
619+ let dequant: [i16; 2] = if plane == 0 {
620+ [q.luma_dc, q.luma_ac]
621+ } else {
622+ [q.chroma_dc, q.chroma_ac]
623+ };
624+ let ptype = usize::from(plane != 0);
625+ let ax = ((col << 1) >> s) + bcol;
626+ let lrows = 32usize >> s;
627+ let ay = (((row << 1) >> s) + brow) % lrows;
628+ let nblocks = 1usize << tx_size;
629+ let ctx_in = usize::from(ectx[plane].above[ax..ax + nblocks].iter().any(|&v| v != 0))
630+ + usize::from(ectx[plane].left[ay..ay + nblocks].iter().any(|&v| v != 0));
631+ let coef = decode_coefs(
632+ r,
633+ ptype,
634+ tx_size,
635+ &dequant,
636+ ctx_in,
637+ scan,
638+ nb,
639+ &self.ctx.coef[tx_size],
640+ info.is_inter,
641+ (0, 0),
642+ plane,
643+ );
644+ // vp9_decode_block_tokens context write-back.
645+ let n4w_s = bw * 2 >> s;
646+ let n4h_s = bh * 2 >> s;
647+ let maxw =
648+ (n4w_s as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize;
649+ let maxh =
650+ (n4h_s as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize;
651+ let eob_pos = u64::from(coef.eob > 0);
652+ let shift_a = if maxw > 0 && nblocks + bcol > maxw {
653+ (nblocks - (maxw - bcol)) * 8
654+ } else {
655+ 0
656+ };
657+ let shift_l = if maxh > 0 && nblocks + brow > maxh {
658+ (nblocks - (maxh - brow)) * 8
659+ } else {
660+ 0
661+ };
662+ let spread_a = (eob_pos * 0x0101_0101_0101_0101) >> shift_a;
663+ let spread_l = (eob_pos * 0x0101_0101_0101_0101) >> shift_l;
664+ for k in 0..nblocks {
665+ ectx[plane].above[ax + k] = (spread_a >> (8 * k)) as u8;
666+ ectx[plane].left[ay + k] = (spread_l >> (8 * k)) as u8;
667+ }
668+ }
669+ }
670+ }
671+ Ok(())
672+ }
673+
164 fn decode_keyframe(&mut self, hdr: &FrameHeader, frame: &[u8], tx_mode: u8) -> Result<Picture> {674 fn decode_keyframe(&mut self, hdr: &FrameHeader, frame: &[u8], tx_mode: u8) -> Result<Picture> {
165 let width = hdr.width as usize;675 let width = hdr.width as usize;
166 let height = hdr.height as usize;676 let height = hdr.height as usize;
@@ -559,21 +1069,63 @@ impl Decoder {
559 let x_mis = bw.min(mi.mi_cols - col);1069 let x_mis = bw.min(mi.mi_cols - col);
560 let y_mis = bh.min(mi.mi_rows - row);1070 let y_mis = bh.min(mi.mi_rows - row);
561 1071
562- let info = read_intra_frame_mode_info(1072+ let info = if hdr.frame_type == FrameType::Key {
563- r,1073+ read_intra_frame_mode_info(
564- mi,1074+ r,
565- &hdr.segmentation,1075+ mi,
566- &self.ctx.partition,1076+ &hdr.segmentation,
567- row,1077+ &self.ctx.partition,
568- col,1078+ row,
569- sb_type,1079+ col,
570- x_mis,1080+ sb_type,
571- y_mis,1081+ x_mis,
572- tile_row_start,1082+ y_mis,
573- tile_col_start,1083+ tile_row_start,
574- tx_mode,1084+ tile_col_start,
575- &self.ctx.skip,1085+ tx_mode,
576- )?;1086+ &self.ctx.skip,
1087+ )?
1088+ } else {
1089+ self.read_inter_block_info(
1090+ r,
1091+ mi,
1092+ hdr,
1093+ row,
1094+ col,
1095+ sb_type,
1096+ x_mis,
1097+ y_mis,
1098+ tile_row_start,
1099+ tile_col_start,
1100+ tx_mode,
1101+ )?
1102+ };
1103+ if hdr.frame_type != FrameType::Key {
1104+ // Inter syntax only: tokens keep the entropy stream aligned, the
1105+ // block lands in the mode grid, and no pixel is touched.
1106+ self.decode_inter_block_tokens(r, mi, ectx, hdr, &info, row, col, sb_type, bw, bh)?;
1107+ for dy in 0..y_mis {
1108+ for dx in 0..x_mis {
1109+ if crate::mvdbg2_enabled()
1110+ && row + dy == 7
1111+ && col + dx >= 30
1112+ && col + dx <= 40
1113+ {
1114+ eprintln!(
1115+ "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={}",
1116+ row + dy,
1117+ col + dx,
1118+ (row + dy) * mi.mi_cols + col + dx,
1119+ info.mv,
1120+ info.ref_frame[0],
1121+ mi.mi_cols
1122+ );
1123+ }
1124+ mi.grid[(row + dy) * mi.mi_cols + col + dx] = Some(info.clone());
1125+ }
1126+ }
1127+ return Ok(());
1128+ }
577 1129
578 // Per-plane 4x4 counts. Sub-8x8 shapes still occupy the WHOLE 8x81130 // Per-plane 4x4 counts. Sub-8x8 shapes still occupy the WHOLE 8x8
579 // mi area (libvpx set_plane_n4 with bw=bh=1): luma walks 2x2 4x41131 // mi area (libvpx set_plane_n4 with bw=bh=1): luma walks 2x2 4x4
@@ -782,6 +1334,7 @@ impl Decoder {
782 scan,1334 scan,
783 nb,1335 nb,
784 &self.ctx.coef[tx_size],1336 &self.ctx.coef[tx_size],
1337+ false,
785 (x0, y0),1338 (x0, y0),
786 plane,1339 plane,
787 );1340 );
crates/ec-vp9/src/header.rsmodified+264 -5
@@ -4,7 +4,9 @@
4 //! differential probability-update machinery (libvpx `vp9_dsubexp.c`).4 //! differential probability-update machinery (libvpx `vp9_dsubexp.c`).
5 5
6 use crate::bool::BoolDecoder;6 use crate::bool::BoolDecoder;
7+use crate::inter::{COMPOUND_REFERENCE, REFERENCE_MODE_SELECT, SINGLE_REFERENCE};
7 use crate::tables::*;8 use crate::tables::*;
9+use ec_vp9_syntax::FrameHeader;
8 10
9 /// All bool-coded probabilities a keyframe reads.11 /// All bool-coded probabilities a keyframe reads.
10 #[derive(Clone)]12 #[derive(Clone)]
@@ -15,6 +17,36 @@ pub(crate) struct FrameContext {
15 pub tx_p16x16: [[u8; 2]; 2],17 pub tx_p16x16: [[u8; 2]; 2],
16 pub tx_p32x32: [[u8; 3]; 2],18 pub tx_p32x32: [[u8; 3]; 2],
17 pub skip: [u8; 3],19 pub skip: [u8; 3],
20+ /// Inter-frame tables (all defaults until a compressed header updates
21+ /// them): `inter_mode_probs`, `switchable_interp_prob`, `intra_inter_prob`,
22+ /// `comp_inter_prob`, `single_ref_prob`, `comp_ref_prob`, `y_mode_prob`,
23+ /// `uv_mode_prob`, and the MV probs.
24+ pub inter_mode: [[u8; 3]; 7],
25+ pub switchable_interp: [[u8; 2]; 4],
26+ pub intra_inter: [u8; 4],
27+ pub comp_inter: [u8; 5],
28+ pub single_ref: [[u8; 2]; 5],
29+ pub comp_ref: [u8; 5],
30+ pub y_mode: [[u8; 9]; 4],
31+ pub uv_mode: [[u8; 9]; 10],
32+ pub nmv_joints: [u8; 3],
33+ pub nmv_sign: [u8; 2],
34+ pub nmv_classes: [[u8; 10]; 2],
35+ pub nmv_class0: [[u8; 1]; 2],
36+ pub nmv_bits: [[u8; 10]; 2],
37+ pub nmv_class0_fp: [[[u8; 3]; 2]; 2],
38+ pub nmv_fp: [[u8; 3]; 2],
39+ pub nmv_class0_hp: [u8; 2],
40+ pub nmv_hp: [u8; 2],
41+}
42+
43+/// Rows from a flat C initializer.
44+fn rows<const R: usize, const C: usize>(flat: &[u8]) -> [[u8; C]; R] {
45+ let mut out = [[0u8; C]; R];
46+ for (i, row) in out.iter_mut().enumerate() {
47+ row.copy_from_slice(&flat[i * C..i * C + C]);
48+ }
49+ out
18 }50 }
19 51
20 impl FrameContext {52 impl FrameContext {
@@ -51,10 +83,49 @@ impl FrameContext {
51 [TX_P32X32_PROB[3], TX_P32X32_PROB[4], TX_P32X32_PROB[5]],83 [TX_P32X32_PROB[3], TX_P32X32_PROB[4], TX_P32X32_PROB[5]],
52 ],84 ],
53 skip: DEFAULT_SKIP_PROBS,85 skip: DEFAULT_SKIP_PROBS,
86+ // `vp9_init_frame_context` / `vp9_init_mv_probs` defaults. Key
87+ // frames do not use these; inter frames start from them unless a
88+ // stored context (or a compressed header) says otherwise.
89+ inter_mode: rows(&DEFAULT_INTER_MODE_PROBS),
90+ switchable_interp: rows(&DEFAULT_SWITCHABLE_INTERP_PROBS),
91+ intra_inter: DEFAULT_INTRA_INTER_PROBS,
92+ comp_inter: DEFAULT_COMP_INTER_PROBS,
93+ single_ref: rows(&DEFAULT_SINGLE_REF_PROBS),
94+ comp_ref: DEFAULT_COMP_REF_PROBS,
95+ y_mode: rows(&DEFAULT_Y_MODE_PROBS),
96+ uv_mode: rows(&DEFAULT_IF_UV_PROBS),
97+ nmv_joints: DEFAULT_NMVC_JOINTS,
98+ nmv_sign: DEFAULT_NMVC_SIGN,
99+ nmv_classes: rows(&DEFAULT_NMVC_CLASSES),
100+ nmv_class0: [[DEFAULT_NMVC_CLASS0[0]], [DEFAULT_NMVC_CLASS0[1]]],
101+ nmv_bits: rows(&DEFAULT_NMVC_BITS),
102+ nmv_class0_fp: [
103+ [
104+ [DEFAULT_NMVC_CLASS0_FP[0], DEFAULT_NMVC_CLASS0_FP[1], DEFAULT_NMVC_CLASS0_FP[2]],
105+ [DEFAULT_NMVC_CLASS0_FP[3], DEFAULT_NMVC_CLASS0_FP[4], DEFAULT_NMVC_CLASS0_FP[5]],
106+ ],
107+ [
108+ [DEFAULT_NMVC_CLASS0_FP[6], DEFAULT_NMVC_CLASS0_FP[7], DEFAULT_NMVC_CLASS0_FP[8]],
109+ [DEFAULT_NMVC_CLASS0_FP[9], DEFAULT_NMVC_CLASS0_FP[10], DEFAULT_NMVC_CLASS0_FP[11]],
110+ ],
111+ ],
112+ nmv_fp: rows(&DEFAULT_NMVC_FP),
113+ nmv_class0_hp: DEFAULT_NMVC_CLASS0_HP,
114+ nmv_hp: DEFAULT_NMVC_HP,
54 }115 }
55 }116 }
56 }117 }
57 118
119+impl FrameContext {
120+ /// `vp9_kf_partition_probs` are NOT a `FRAME_CONTEXT` field in libvpx
121+ /// (`get_partition_probs` picks the const table for intra-only frames);
122+ /// a context that a keyframe stored must therefore go back to the inter
123+ /// defaults before the next frame reads it.
124+ pub(crate) fn reset_inter_partition(&mut self) {
125+ self.partition = rows(&DEFAULT_PARTITION_PROBS);
126+ }
127+}
128+
58 /// `inv_recenter_nonneg` (vp9_dsubexp.c).129 /// `inv_recenter_nonneg` (vp9_dsubexp.c).
59 fn inv_recenter_nonneg(v: i32, m: i32) -> i32 {130 fn inv_recenter_nonneg(v: i32, m: i32) -> i32 {
60 if v > 2 * m {131 if v > 2 * m {
@@ -127,6 +198,20 @@ fn diff_update_prob(r: &mut BoolDecoder, p: &mut u8) {
127 }198 }
128 }199 }
129 200
201+/// `MV_UPDATE_PROB` (`vp9_entropymv.h`): the flag prob of `update_mv_probs`.
202+const MV_UPDATE_PROB: u8 = 252;
203+
204+/// `update_mv_probs` (vp9_decodeframe.c:136). NOT a `vp9_diff_update_prob`:
205+/// a flag at `MV_UPDATE_PROB`, then seven LITERAL bits, and the new prob is
206+/// `(literal << 1) | 1` — no `decode_term_subexp`, no `inv_remap_prob`.
207+fn update_mv_probs(r: &mut BoolDecoder, p: &mut [u8]) {
208+ for v in p.iter_mut() {
209+ if r.read_bool(MV_UPDATE_PROB) {
210+ *v = ((r.read_literal(7) << 1) | 1) as u8;
211+ }
212+ }
213+}
214+
130 /// `read_coef_probs_common` (decodeframe.c:1314): one flag per tx size215 /// `read_coef_probs_common` (decodeframe.c:1314): one flag per tx size
131 /// covers all plane/ref/band/context updates of the first three (base)216 /// covers all plane/ref/band/context updates of the first three (base)
132 /// probs per slot.217 /// probs per slot.
@@ -159,8 +244,17 @@ fn read_tx_mode(r: &mut BoolDecoder) -> u8 {
159 m244 m
160 }245 }
161 246
162-/// `read_compressed_header` for intra frames (the inter branch is dead247+/// What `read_compressed_header` decides for the frame.
163-/// in this lane): tx mode, tx probs, coef probs, skip probs.248+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249+pub(crate) struct CompressedHeader {
250+ pub tx_mode: u8,
251+ pub reference_mode: u8,
252+}
253+
254+/// `read_compressed_header` (libvpx `vp9_decodeframe.c:2889`): tx mode, tx
255+/// probs, coef probs, skip probs, then — for inter frames only — the inter
256+/// mode, switchable-interp, intra/inter, reference-mode, y-mode, partition
257+/// and MV probability updates.
164 ///258 ///
165 /// Lossless forces `ONLY_4X4` and consumes no tx-mode bits — decodeframe.c259 /// Lossless forces `ONLY_4X4` and consumes no tx-mode bits — decodeframe.c
166 /// `read_compressed_header`: `cm->tx_mode = xd->lossless ? ONLY_4X4 :260 /// `read_compressed_header`: `cm->tx_mode = xd->lossless ? ONLY_4X4 :
@@ -168,14 +262,27 @@ fn read_tx_mode(r: &mut BoolDecoder) -> u8 {
168 pub(crate) fn read_compressed_header(262 pub(crate) fn read_compressed_header(
169 data: &[u8],263 data: &[u8],
170 ctx: &mut FrameContext,264 ctx: &mut FrameContext,
171- lossless: bool,265+ hdr: &FrameHeader,
172-) -> crate::Result<u8> {266+) -> crate::Result<CompressedHeader> {
267+ if crate::interdump_enabled() && !hdr.frame_is_intra {
268+ let mut line = String::from("PPFLAT_PRE");
269+ for row in ctx.partition.iter() {
270+ for v in row.iter() {
271+ line.push_str(&format!(" {v}"));
272+ }
273+ }
274+ eprintln!("{line}");
275+ }
276+ let lossless = hdr.quantization.lossless();
173 let mut r = BoolDecoder::new(data)?;277 let mut r = BoolDecoder::new(data)?;
174 let tx_mode = if lossless {278 let tx_mode = if lossless {
175 ONLY_4X4279 ONLY_4X4
176 } else {280 } else {
177 read_tx_mode(&mut r)281 read_tx_mode(&mut r)
178 };282 };
283+ if crate::trace_enabled() {
284+ eprintln!("SECT txmode");
285+ }
179 if tx_mode == TX_MODE_SELECT {286 if tx_mode == TX_MODE_SELECT {
180 for row in 0..2 {287 for row in 0..2 {
181 for j in 0..1 {288 for j in 0..1 {
@@ -193,10 +300,159 @@ pub(crate) fn read_compressed_header(
193 }300 }
194 }301 }
195 }302 }
303+ if crate::trace_enabled() {
304+ eprintln!("SECT txprobs");
305+ }
196 read_coef_probs(&mut r, ctx, tx_mode);306 read_coef_probs(&mut r, ctx, tx_mode);
307+ if crate::trace_enabled() {
308+ eprintln!("SECT coef");
309+ }
197 for p in &mut ctx.skip {310 for p in &mut ctx.skip {
198 diff_update_prob(&mut r, p);311 diff_update_prob(&mut r, p);
199 }312 }
313+ let mut reference_mode = SINGLE_REFERENCE;
314+ if crate::trace_enabled() {
315+ eprintln!("SECT skip");
316+ }
317+ if !hdr.frame_is_intra {
318+ if crate::trace_enabled() {
319+ eprintln!("SECT intermode");
320+ }
321+ for i in 0..7 {
322+ for j in 0..3 {
323+ diff_update_prob(&mut r, &mut ctx.inter_mode[i][j]);
324+ }
325+ }
326+ if crate::trace_enabled() {
327+ eprintln!("SECT switchable");
328+ }
329+ if hdr.interpolation_filter as u8 == crate::inter::SWITCHABLE {
330+ for j in 0..4 {
331+ for i in 0..2 {
332+ diff_update_prob(&mut r, &mut ctx.switchable_interp[j][i]);
333+ }
334+ }
335+ }
336+ if crate::trace_enabled() {
337+ eprintln!("SECT intrainter");
338+ }
339+ for p in &mut ctx.intra_inter {
340+ diff_update_prob(&mut r, p);
341+ }
342+ // read_frame_reference_mode: `vp9_compound_reference_allowed` gates
343+ // the two bits (bias[GOLDEN]/bias[ALTREF] vs bias[LAST]).
344+ if crate::trace_enabled() {
345+ eprintln!("SECT refmode");
346+ }
347+ let allowed = hdr.ref_frame_sign_bias[1] != hdr.ref_frame_sign_bias[0]
348+ || hdr.ref_frame_sign_bias[2] != hdr.ref_frame_sign_bias[0];
349+ reference_mode = if allowed {
350+ if r.read_bool(128) {
351+ if r.read_bool(128) {
352+ REFERENCE_MODE_SELECT
353+ } else {
354+ COMPOUND_REFERENCE
355+ }
356+ } else {
357+ SINGLE_REFERENCE
358+ }
359+ } else {
360+ SINGLE_REFERENCE
361+ };
362+ // read_frame_reference_mode_probs.
363+ if crate::trace_enabled() {
364+ eprintln!("SECT refprobs");
365+ }
366+ if reference_mode == REFERENCE_MODE_SELECT {
367+ for p in &mut ctx.comp_inter {
368+ diff_update_prob(&mut r, p);
369+ }
370+ }
371+ if reference_mode != COMPOUND_REFERENCE {
372+ for i in 0..5 {
373+ for j in 0..2 {
374+ diff_update_prob(&mut r, &mut ctx.single_ref[i][j]);
375+ }
376+ }
377+ }
378+ if reference_mode != SINGLE_REFERENCE {
379+ for p in &mut ctx.comp_ref {
380+ diff_update_prob(&mut r, p);
381+ }
382+ }
383+ if crate::trace_enabled() {
384+ eprintln!("SECT ymode");
385+ }
386+ for j in 0..4 {
387+ for i in 0..9 {
388+ diff_update_prob(&mut r, &mut ctx.y_mode[j][i]);
389+ }
390+ }
391+ if crate::trace_enabled() {
392+ eprintln!("SECT partition");
393+ }
394+ for j in 0..16 {
395+ for i in 0..3 {
396+ let before = ctx.partition[j][i];
397+ diff_update_prob(&mut r, &mut ctx.partition[j][i]);
398+ if crate::interdump_enabled() {
399+ eprintln!("PUPD {} {} {} {}", j, i, before, ctx.partition[j][i]);
400+ }
401+ }
402+ }
403+ // read_mv_probs (vp9_decodeframe.c:76): joints, then per component
404+ // sign/classes/class0/bits, then the fractional parts, then hp.
405+ if crate::trace_enabled() {
406+ eprintln!("SECT mv");
407+ }
408+ update_mv_probs(&mut r, &mut ctx.nmv_joints);
409+ for comp in 0..2 {
410+ update_mv_probs(&mut r, &mut ctx.nmv_sign[comp..comp + 1]);
411+ update_mv_probs(&mut r, &mut ctx.nmv_classes[comp]);
412+ update_mv_probs(&mut r, &mut ctx.nmv_class0[comp]);
413+ update_mv_probs(&mut r, &mut ctx.nmv_bits[comp]);
414+ }
415+ for comp in 0..2 {
416+ for j in 0..2 {
417+ update_mv_probs(&mut r, &mut ctx.nmv_class0_fp[comp][j]);
418+ }
419+ update_mv_probs(&mut r, &mut ctx.nmv_fp[comp]);
420+ }
421+ if hdr.allow_high_precision_mv {
422+ for comp in 0..2 {
423+ update_mv_probs(&mut r, &mut ctx.nmv_class0_hp[comp..comp + 1]);
424+ update_mv_probs(&mut r, &mut ctx.nmv_hp[comp..comp + 1]);
425+ if crate::mvdump_enabled() {
426+ eprintln!(
427+ "MVPROB j0={} j1={} j2={}",
428+ ctx.nmv_joints[0], ctx.nmv_joints[1], ctx.nmv_joints[2]
429+ );
430+ for comp in 0..2 {
431+ eprintln!(
432+ "MVPROB c{} sign={} class0={} class0hp={} hp={}",
433+ comp,
434+ ctx.nmv_sign[comp],
435+ ctx.nmv_class0[comp][0],
436+ ctx.nmv_class0_hp[comp],
437+ ctx.nmv_hp[comp]
438+ );
439+ eprint!("MVPROB c{} cls", comp);
440+ for v in ctx.nmv_classes[comp].iter() { eprint!(" {}", v); }
441+ eprintln!();
442+ eprint!("MVPROB c{} bits", comp);
443+ for v in ctx.nmv_bits[comp].iter() { eprint!(" {}", v); }
444+ eprintln!();
445+ eprint!("MVPROB c{} c0fp", comp);
446+ for row in ctx.nmv_class0_fp[comp].iter() { for v in row.iter() { eprint!(" {}", v); } }
447+ eprintln!();
448+ eprint!("MVPROB c{} fp", comp);
449+ for v in ctx.nmv_fp[comp].iter() { eprint!(" {}", v); }
450+ eprintln!();
451+ }
452+ }
453+ }
454+ }
455+ }
200 if std::env::var_os("EC_VP9_DBG").is_some() {456 if std::env::var_os("EC_VP9_DBG").is_some() {
201 eprintln!("DBG tx_mode={} consumed={}", tx_mode, r.byte_offset());457 eprintln!("DBG tx_mode={} consumed={}", tx_mode, r.byte_offset());
202 eprintln!(458 eprintln!(
@@ -209,5 +465,8 @@ pub(crate) fn read_compressed_header(
209 );465 );
210 }466 }
211 ensure(r.overreads() == 0, "compressed header desync")?;467 ensure(r.overreads() == 0, "compressed header desync")?;
212- Ok(tx_mode)468+ Ok(CompressedHeader {
469+ tx_mode,
470+ reference_mode,
471+ })
213 }472 }
crates/ec-vp9/src/inter.rsadded+1317 -0
@@ -0,0 +1,1317 @@
1+//! Inter-frame syntax (libvpx `vp9/decoder/vp9_decodemv.c`
2+//! `read_inter_frame_mode_info`, `vp9/common/vp9_mvref_common.h`).
3+//!
4+//! Syntax only: nothing here reconstructs pixels. The MV *predictor* is still
5+//! parse-load-bearing — `read_mv` reads the high-precision bit only when
6+//! `allow_high_precision_mv && use_mv_hp(predictor)`, so the candidate scan
7+//! runs even though no motion compensation happens.
8+
9+use crate::bool::BoolDecoder;
10+use crate::header::FrameContext;
11+use crate::modes::{MiInfo, MiState};
12+use crate::tables::*;
13+
14+/// `INTRA_FRAME` .. `ALTREF_FRAME` (`MV_REFERENCE_FRAME`), `NO_REF_FRAME` = -1.
15+pub(crate) const INTRA_FRAME: i8 = 0;
16+pub(crate) const LAST_FRAME: i8 = 1;
17+pub(crate) const GOLDEN_FRAME: i8 = 2;
18+pub(crate) const ALTREF_FRAME: i8 = 3;
19+pub(crate) const NO_REF_FRAME: i8 = -1;
20+/// `PREDICTION_MODE` values of the inter modes.
21+pub(crate) const NEARESTMV: u8 = 10;
22+pub(crate) const NEARMV: u8 = 11;
23+pub(crate) const ZEROMV: u8 = 12;
24+pub(crate) const NEWMV: u8 = 13;
25+/// `REFERENCE_MODE`.
26+pub(crate) const SINGLE_REFERENCE: u8 = 0;
27+pub(crate) const COMPOUND_REFERENCE: u8 = 1;
28+pub(crate) const REFERENCE_MODE_SELECT: u8 = 2;
29+/// `SWITCHABLE`: `interpolation_filter` value meaning "per block".
30+pub(crate) const SWITCHABLE: u8 = 4;
31+/// `SWITCHABLE_FILTERS`: the sentinel `mi->interp_filter` of intra blocks.
32+pub(crate) const SWITCHABLE_FILTERS: u8 = 3;
33+
34+const MAX_MV_REF_CANDIDATES: usize = 2;
35+const MVREF_NEIGHBOURS: usize = 8;
36+/// `MV_BORDER` (1/8-pel units).
37+const MV_BORDER: i32 = 16 << 3;
38+/// `use_mv_hp`'s `kMvRefThresh`.
39+const MV_HP_THRESH: i32 = 64;
40+const CLASS0_SIZE: i32 = 2;
41+const CLASS0_BITS: i32 = 1;
42+/// `SEG_LVL_SKIP` / `SEG_LVL_REF_FRAME`.
43+const SEG_LVL_REF_FRAME: usize = 2;
44+const SEG_LVL_SKIP: usize = 3;
45+
46+/// `mv_ref_blocks[BLOCK_SIZES]` (`vp9_mvref_common.h`): `(row, col)` offsets,
47+/// transcribed verbatim from the C. libvpx's `POSITION` is `{ row, col }`, so
48+/// every accessor must add the FIRST element to the row and the SECOND to the
49+/// column (a transposed accessor silently picks a different neighbour for every
50+/// asymmetric entry).
51+const MV_REF_BLOCKS: [[(i32, i32); MVREF_NEIGHBOURS]; 13] = [
52+ // 4X4
53+ [(-1, 0), (0, -1), (-1, -1), (-2, 0), (0, -2), (-2, -1), (-1, -2), (-2, -2)],
54+ // 4X8
55+ [(-1, 0), (0, -1), (-1, -1), (-2, 0), (0, -2), (-2, -1), (-1, -2), (-2, -2)],
56+ // 8X4
57+ [(-1, 0), (0, -1), (-1, -1), (-2, 0), (0, -2), (-2, -1), (-1, -2), (-2, -2)],
58+ // 8X8
59+ [(-1, 0), (0, -1), (-1, -1), (-2, 0), (0, -2), (-2, -1), (-1, -2), (-2, -2)],
60+ // 8X16
61+ [(0, -1), (-1, 0), (1, -1), (-1, -1), (0, -2), (-2, 0), (-2, -1), (-1, -2)],
62+ // 16X8
63+ [(-1, 0), (0, -1), (-1, 1), (-1, -1), (-2, 0), (0, -2), (-1, -2), (-2, -1)],
64+ // 16X16
65+ [(-1, 0), (0, -1), (-1, 1), (1, -1), (-1, -1), (-3, 0), (0, -3), (-3, -3)],
66+ // 16X32
67+ [(0, -1), (-1, 0), (2, -1), (-1, -1), (-1, 1), (0, -3), (-3, 0), (-3, -3)],
68+ // 32X16
69+ [(-1, 0), (0, -1), (-1, 2), (-1, -1), (1, -1), (-3, 0), (0, -3), (-3, -3)],
70+ // 32X32
71+ [(-1, 1), (1, -1), (-1, 2), (2, -1), (-1, -1), (-3, 0), (0, -3), (-3, -3)],
72+ // 32X64
73+ [(0, -1), (-1, 0), (4, -1), (-1, 2), (-1, -1), (0, -3), (-3, 0), (2, -1)],
74+ // 64X32
75+ [(-1, 0), (0, -1), (-1, 4), (2, -1), (-1, -1), (-3, 0), (0, -3), (-1, 2)],
76+ // 64X64
77+ [(-1, 3), (3, -1), (-1, 4), (4, -1), (-1, -1), (-1, 0), (0, -1), (-1, 6)],
78+];
79+
80+/// `idx_n_column_to_subblock` (`vp9_mvref_common.h`).
81+const IDX_N_COLUMN_TO_SUBBLOCK: [[usize; 2]; 4] = [[1, 2], [1, 3], [3, 2], [3, 3]];
82+
83+/// One `MV_REF` entry: the previous frame's per-8x8 reference pair and MVs
84+/// (`vp9_read_mode_info` stores them for every block of an inter frame).
85+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
86+pub(crate) struct MvRef {
87+ /// `ref_frame[0]`/`[1]`; zeroed means `INTRA_FRAME`.
88+ pub ref_frame: [i8; 2],
89+ /// `mv[0]`/`[1]` in 1/8-pel units.
90+ pub mv: [(i32, i32); 2],
91+}
92+
93+/// Frame-level reference-mode state (`VP9_COMMON::reference_mode`,
94+/// `comp_fixed_ref`, `comp_var_ref`).
95+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96+pub(crate) struct InterFrameState {
97+ pub reference_mode: u8,
98+ pub comp_fixed_ref: i8,
99+ pub comp_var_ref: [i8; 2],
100+}
101+
102+impl Default for InterFrameState {
103+ fn default() -> Self {
104+ InterFrameState {
105+ reference_mode: SINGLE_REFERENCE,
106+ comp_fixed_ref: ALTREF_FRAME,
107+ comp_var_ref: [LAST_FRAME, GOLDEN_FRAME],
108+ }
109+ }
110+}
111+
112+/// `vp9_setup_compound_reference_mode` (`vp9_pred_common.c`): which ref frame
113+/// of a compound pair is coded explicitly, and which two the coded bit picks.
114+pub(crate) fn setup_compound_reference_mode(ifs: &mut InterFrameState, sign_bias: [bool; 4]) {
115+ let b = |f: i8| sign_bias[f as usize];
116+ if b(LAST_FRAME) == b(GOLDEN_FRAME) {
117+ ifs.comp_fixed_ref = ALTREF_FRAME;
118+ ifs.comp_var_ref = [LAST_FRAME, GOLDEN_FRAME];
119+ } else if b(LAST_FRAME) == b(ALTREF_FRAME) {
120+ ifs.comp_fixed_ref = GOLDEN_FRAME;
121+ ifs.comp_var_ref = [LAST_FRAME, ALTREF_FRAME];
122+ } else {
123+ ifs.comp_fixed_ref = LAST_FRAME;
124+ ifs.comp_var_ref = [GOLDEN_FRAME, ALTREF_FRAME];
125+ }
126+}
127+
128+/// Frame- and position-scoped inputs of the block-level reads.
129+pub(crate) struct InterBlockCtx<'a> {
130+ pub seg: &'a ec_vp9_syntax::SegmentationParams,
131+ pub ifs: InterFrameState,
132+ /// `ref_frame_sign_bias[INTRA..ALTREF]`.
133+ pub sign_bias: [bool; 4],
134+ pub allow_hp: bool,
135+ pub frame_interp: u8,
136+ pub tx_mode: u8,
137+ pub mi_rows: usize,
138+ pub mi_cols: usize,
139+ pub tile_row_start: usize,
140+ pub tile_col_start: usize,
141+ /// `tile->mi_col_end`.
142+ pub tile_col_end: usize,
143+ /// The previous frame's segment map, when it has one.
144+ pub last_seg: Option<&'a [u8]>,
145+ /// `prev_frame->mvs` when `use_prev_frame_mvs`.
146+ pub prev_mvs: Option<&'a [MvRef]>,
147+}
148+
149+/// The two decoded neighbours of the current block.
150+#[derive(Clone, Copy)]
151+struct Nb<'a> {
152+ above: Option<&'a MiInfo>,
153+ left: Option<&'a MiInfo>,
154+}
155+
156+/// `read_inter_frame_mode_info` (`vp9_decodemv.c`).
157+#[allow(clippy::too_many_arguments)]
158+pub(crate) fn read_inter_frame_mode_info(
159+ r: &mut BoolDecoder,
160+ st: &MiState,
161+ c: &InterBlockCtx<'_>,
162+ fc: &FrameContext,
163+ row: usize,
164+ col: usize,
165+ sb_type: usize,
166+ x_mis: usize,
167+ y_mis: usize,
168+ partition: u8,
169+ cur_seg: &mut [u8],
170+) -> crate::Result<MiInfo> {
171+ let above = st.above_mi(row, col, c.tile_row_start).cloned();
172+ let left = st.left_mi(row, col, c.tile_col_start).cloned();
173+ let nb = Nb {
174+ above: above.as_ref(),
175+ left: left.as_ref(),
176+ };
177+
178+ let mut seg_id_predicted = false;
179+ let segment = read_inter_segment_id(r, c, nb, row, col, x_mis, y_mis, cur_seg, &mut seg_id_predicted);
180+ let skip = read_skip(r, c, fc, segment, nb);
181+ let inter_block = read_is_inter_block(r, c, fc, segment, nb);
182+ let tx_size = read_tx_size(r, c, fc, sb_type, nb, !skip || !inter_block);
183+
184+ let mut info = MiInfo {
185+ sb_type,
186+ segment,
187+ skip,
188+ tx_size,
189+ mode: 0,
190+ uv_mode: 0,
191+ bmi: [0; 4],
192+ is_inter: inter_block,
193+ ref_frame: [NO_REF_FRAME; 2],
194+ mv: [(0, 0); 2],
195+ mv_diff: [(0, 0); 2],
196+ bmi_mv: [[(0, 0); 2]; 4],
197+ seg_id_predicted,
198+ interp_filter: SWITCHABLE_FILTERS,
199+ };
200+ if inter_block {
201+ read_inter_block_mode_info(r, st, c, fc, &mut info, nb, row, col, partition)?;
202+ } else {
203+ read_intra_block_mode_info(r, fc, &mut info);
204+ }
205+ Ok(info)
206+}
207+
208+/// `dec_get_segment_id`: the minimum id over the block's covered cells.
209+fn min_seg(map: &[u8], row: usize, col: usize, x_mis: usize, y_mis: usize, mi_cols: usize) -> u8 {
210+ let mut id = u8::MAX;
211+ for y in 0..y_mis {
212+ for x in 0..x_mis {
213+ id = id.min(map[(row + y) * mi_cols + col + x]);
214+ }
215+ }
216+ id
217+}
218+
219+/// `set_segment_id` / `copy_segment_id`.
220+fn write_seg(
221+ src: Option<&[u8]>,
222+ dst: &mut [u8],
223+ row: usize,
224+ col: usize,
225+ x_mis: usize,
226+ y_mis: usize,
227+ mi_cols: usize,
228+ id: u8,
229+) {
230+ for y in 0..y_mis {
231+ for x in 0..x_mis {
232+ let i = (row + y) * mi_cols + col + x;
233+ dst[i] = match src {
234+ Some(m) => m[i],
235+ None => id,
236+ };
237+ }
238+ }
239+}
240+
241+/// `read_inter_segment_id` (`vp9_decodemv.c:151`).
242+#[allow(clippy::too_many_arguments)]
243+fn read_inter_segment_id(
244+ r: &mut BoolDecoder,
245+ c: &InterBlockCtx<'_>,
246+ nb: Nb<'_>,
247+ row: usize,
248+ col: usize,
249+ x_mis: usize,
250+ y_mis: usize,
251+ cur_seg: &mut [u8],
252+ seg_id_predicted: &mut bool,
253+) -> u8 {
254+ let seg = c.seg;
255+ if !seg.enabled {
256+ return 0;
257+ }
258+ let predicted = c
259+ .last_seg
260+ .map_or(0, |m| min_seg(m, row, col, x_mis, y_mis, c.mi_cols));
261+ if !seg.update_map {
262+ write_seg(c.last_seg, cur_seg, row, col, x_mis, y_mis, c.mi_cols, 0);
263+ return predicted;
264+ }
265+ let segment_id = if seg.temporal_update {
266+ let ctx = usize::from(nb.above.is_some_and(|m| m.seg_id_predicted))
267+ + usize::from(nb.left.is_some_and(|m| m.seg_id_predicted));
268+ *seg_id_predicted = r.read_bool(seg.pred_probs[ctx]);
269+ if *seg_id_predicted {
270+ predicted
271+ } else {
272+ r.read_tree(&SEGMENT_TREE, &seg.tree_probs)
273+ }
274+ } else {
275+ r.read_tree(&SEGMENT_TREE, &seg.tree_probs)
276+ };
277+ write_seg(None, cur_seg, row, col, x_mis, y_mis, c.mi_cols, segment_id);
278+ segment_id
279+}
280+
281+fn seg_feature(seg: &ec_vp9_syntax::SegmentationParams, segment_id: u8, feature: usize) -> bool {
282+ seg.enabled
283+ && seg
284+ .feature_enabled
285+ .get(segment_id as usize)
286+ .is_some_and(|f| f[feature])
287+}
288+
289+/// `read_skip`.
290+fn read_skip(
291+ r: &mut BoolDecoder,
292+ c: &InterBlockCtx<'_>,
293+ fc: &FrameContext,
294+ segment_id: u8,
295+ nb: Nb<'_>,
296+) -> bool {
297+ if seg_feature(c.seg, segment_id, SEG_LVL_SKIP) {
298+ true
299+ } else {
300+ let ctx = usize::from(nb.above.is_some_and(|m| m.skip))
301+ + usize::from(nb.left.is_some_and(|m| m.skip));
302+ r.read_bool(fc.skip[ctx])
303+ }
304+}
305+
306+/// `get_intra_inter_context` (`vp9_pred_common.h`).
307+fn intra_inter_context(nb: Nb<'_>) -> usize {
308+ match (nb.above, nb.left) {
309+ (Some(a), Some(l)) => {
310+ let above_intra = !a.is_inter;
311+ let left_intra = !l.is_inter;
312+ if left_intra && above_intra {
313+ 3
314+ } else {
315+ usize::from(left_intra || above_intra)
316+ }
317+ }
318+ (Some(m), None) | (None, Some(m)) => 2 * usize::from(!m.is_inter),
319+ (None, None) => 0,
320+ }
321+}
322+
323+/// `read_is_inter_block`.
324+fn read_is_inter_block(
325+ r: &mut BoolDecoder,
326+ c: &InterBlockCtx<'_>,
327+ fc: &FrameContext,
328+ segment_id: u8,
329+ nb: Nb<'_>,
330+) -> bool {
331+ if seg_feature(c.seg, segment_id, SEG_LVL_REF_FRAME) {
332+ c.seg.feature_data[segment_id as usize][SEG_LVL_REF_FRAME] != INTRA_FRAME as i16
333+ } else {
334+ r.read_bool(fc.intra_inter[intra_inter_context(nb)])
335+ }
336+}
337+
338+/// `read_tx_size` with `allow_select` (spec 6.3.5 / `vp9_decodemv.c:85`).
339+fn read_tx_size(
340+ r: &mut BoolDecoder,
341+ c: &InterBlockCtx<'_>,
342+ fc: &FrameContext,
343+ sb_type: usize,
344+ nb: Nb<'_>,
345+ allow_select: bool,
346+) -> usize {
347+ let max_tx = MAX_TXSIZE_LOOKUP[sb_type] as usize;
348+ if allow_select && c.tx_mode == TX_MODE_SELECT && sb_type >= 3 {
349+ // get_tx_size_context: default each side to max_tx, then substitute
350+ // the other side when one is missing, in this exact order.
351+ let a0 = nb
352+ .above
353+ .map_or(max_tx, |m| if m.skip { max_tx } else { m.tx_size });
354+ let l0 = nb
355+ .left
356+ .map_or(max_tx, |m| if m.skip { max_tx } else { m.tx_size });
357+ let mut a = a0;
358+ let mut l = l0;
359+ if nb.left.is_none() {
360+ l = a;
361+ }
362+ if nb.above.is_none() {
363+ a = l;
364+ }
365+ let ctx = usize::from(a + l > max_tx);
366+ let probs: &[u8] = match max_tx {
367+ 1 => &fc.tx_p8x8[ctx][..],
368+ 2 => &fc.tx_p16x16[ctx][..],
369+ _ => &fc.tx_p32x32[ctx][..],
370+ };
371+ let mut tx = r.read_bool(probs[0]) as usize;
372+ if tx != TX_4X4 && max_tx >= TX_16X16 {
373+ tx += r.read_bool(probs[1]) as usize;
374+ if tx != TX_8X8 && max_tx >= TX_32X32 {
375+ tx += r.read_bool(probs[2]) as usize;
376+ }
377+ }
378+ tx
379+ } else {
380+ max_tx.min(TX_MODE_TO_BIGGEST_TX_SIZE[c.tx_mode as usize])
381+ }
382+}
383+
384+/// `read_inter_mode`.
385+fn read_inter_mode(r: &mut BoolDecoder, fc: &FrameContext, ctx: usize) -> u8 {
386+ NEARESTMV + r.read_tree(&INTER_MODE_TREE, &fc.inter_mode[ctx])
387+}
388+
389+/// `get_mode_context` (`vp9_decodemv.c:681`): the two nearest candidates'
390+/// modes fold into one of 5 contexts.
391+fn get_mode_context(st: &MiState, c: &InterBlockCtx<'_>, bsize: usize, row: usize, col: usize) -> usize {
392+ let mut counter = 0usize;
393+ for p in MV_REF_BLOCKS[bsize][..2].iter() {
394+ if is_inside(c, row, col, *p) {
395+ let mode = st
396+ .at((row as i32 + p.0) as usize, (col as i32 + p.1) as usize)
397+ .map_or(0u8, |m| m.mode);
398+ counter += MODE_2_COUNTER[mode as usize] as usize;
399+ }
400+ }
401+ COUNTER_TO_CONTEXT[counter] as usize
402+}
403+
404+/// `get_pred_context_switchable_interp` (`vp9_pred_common.h:69`).
405+fn switchable_interp_ctx(nb: Nb<'_>) -> usize {
406+ let left_type = nb.left.map_or(SWITCHABLE_FILTERS, |m| m.interp_filter);
407+ let above_type = nb.above.map_or(SWITCHABLE_FILTERS, |m| m.interp_filter);
408+ if left_type == above_type {
409+ left_type as usize
410+ } else if left_type == SWITCHABLE_FILTERS {
411+ above_type as usize
412+ } else if above_type == SWITCHABLE_FILTERS {
413+ left_type as usize
414+ } else {
415+ SWITCHABLE_FILTERS as usize
416+ }
417+}
418+
419+/// `read_intra_block_mode_info` (the intra fallback inside an inter frame).
420+fn read_intra_block_mode_info(r: &mut BoolDecoder, fc: &FrameContext, info: &mut MiInfo) {
421+ let bsize = info.sb_type;
422+ match bsize {
423+ 0 => {
424+ for i in 0..4 {
425+ info.bmi[i] = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[0]);
426+ }
427+ info.mode = info.bmi[3];
428+ }
429+ 1 => {
430+ let m0 = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[0]);
431+ info.bmi[0] = m0;
432+ info.bmi[2] = m0;
433+ let m1 = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[0]);
434+ info.bmi[1] = m1;
435+ info.bmi[3] = m1;
436+ info.mode = m1;
437+ }
438+ 2 => {
439+ let m0 = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[0]);
440+ info.bmi[0] = m0;
441+ info.bmi[1] = m0;
442+ let m2 = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[0]);
443+ info.bmi[2] = m2;
444+ info.bmi[3] = m2;
445+ info.mode = m2;
446+ }
447+ _ => {
448+ info.mode = r.read_tree(&INTRA_MODE_TREE, &fc.y_mode[SIZE_GROUP_LOOKUP[bsize] as usize]);
449+ }
450+ }
451+ info.uv_mode = r.read_tree(&INTRA_MODE_TREE, &fc.uv_mode[info.mode as usize]);
452+ info.interp_filter = SWITCHABLE_FILTERS;
453+ info.ref_frame = [INTRA_FRAME, NO_REF_FRAME];
454+}
455+
456+/// `is_inside` (`vp9_mvref_common.h:278`) — note it bounds rows by the FRAME
457+/// and columns by the TILE's end; there is no row bound against the tile.
458+fn is_inside(c: &InterBlockCtx<'_>, row: usize, col: usize, p: (i32, i32)) -> bool {
459+ let r = row as i32 + p.0;
460+ let cc = col as i32 + p.1;
461+ !(r < 0 || cc < c.tile_col_start as i32 || r >= c.mi_rows as i32 || cc >= c.tile_col_end as i32)
462+}
463+
464+/// `get_sub_block_mv` (`vp9_mvref_common.h:224`).
465+fn get_sub_block_mv(cand: &MiInfo, which: usize, search_col: i32, block: i32) -> (i32, i32) {
466+ if block >= 0 && cand.sb_type < 3 {
467+ let b = IDX_N_COLUMN_TO_SUBBLOCK[block as usize][usize::from(search_col == 0)];
468+ cand.bmi_mv[b][which]
469+ } else {
470+ cand.mv[which]
471+ }
472+}
473+
474+/// `use_mv_hp`: a small predictor keeps 1/8-pel precision.
475+fn use_mv_hp(mv: (i32, i32)) -> bool {
476+ mv.0.abs() < MV_HP_THRESH && mv.1.abs() < MV_HP_THRESH
477+}
478+
479+/// `lower_mv_precision`: round the predictor to 1/4-pel when hp is not used.
480+fn lower_mv_precision(mv: &mut (i32, i32), allow_hp: bool) {
481+ if !(allow_hp && use_mv_hp(*mv)) {
482+ if mv.0 & 1 != 0 {
483+ mv.0 += if mv.0 > 0 { -1 } else { 1 };
484+ }
485+ if mv.1 & 1 != 0 {
486+ mv.1 += if mv.1 > 0 { -1 } else { 1 };
487+ }
488+ }
489+}
490+
491+/// `clamp_mv_ref`.
492+fn clamp_mv_ref(mv: &mut (i32, i32), c: &InterBlockCtx<'_>, row: usize, col: usize, bw: usize, bh: usize) {
493+ // xd->mb_to_{left,right,top,bottom}_edge (vp9_onyxc_int.h:424-427). The
494+ // right/bottom differences are SIGNED in libvpx (a wide/tall block on the
495+ // frame's partial last row/column makes them negative), so they must not be
496+ // computed in usize.
497+ let left = -(col as i32 * 64);
498+ let right = (c.mi_cols as i32 - bw as i32 - col as i32) * 64;
499+ let top = -(row as i32 * 64);
500+ let bottom = (c.mi_rows as i32 - bh as i32 - row as i32) * 64;
501+ // `clamp_mv(mv, min_col, max_col, min_row, max_row)` (vp9_mv.h:47): the
502+ // COLUMN takes the left/right edges and the ROW the top/bottom ones, and
503+ // `mv.0` is the row (read_mv fills it from the vertical joint component).
504+ mv.1 = mv.1.clamp(left - MV_BORDER, right + MV_BORDER);
505+ mv.0 = mv.0.clamp(top - MV_BORDER, bottom + MV_BORDER);
506+}
507+
508+/// `ADD_MV_REF_LIST_EB`: returns true when the C `goto Done` fires.
509+fn add_mv_ref_list_eb(
510+ mv: (i32, i32),
511+ list: &mut [(i32, i32); MAX_MV_REF_CANDIDATES],
512+ count: &mut usize,
513+ early_break: bool,
514+) -> bool {
515+ if *count > 0 {
516+ if mv != list[0] {
517+ list[*count] = mv;
518+ *count += 1;
519+ true
520+ } else {
521+ false
522+ }
523+ } else {
524+ list[0] = mv;
525+ *count = 1;
526+ early_break
527+ }
528+}
529+
530+/// `scale_mv` (the decoder's sign-flip-only variant, `vp9_mvref_common.h`).
531+fn scale_mv(cand: &MiInfo, which: usize, ref_frame: i8, sign_bias: [bool; 4]) -> (i32, i32) {
532+ let mv = cand.mv[which];
533+ if sign_bias[cand.ref_frame[which] as usize] != sign_bias[ref_frame as usize] {
534+ (-mv.0, -mv.1)
535+ } else {
536+ mv
537+ }
538+}
539+
540+/// `dec_find_mv_refs` (`vp9_decodemv.c:495`): the candidate list, clamped.
541+/// Returns `(refmv_count, list)`.
542+#[allow(clippy::too_many_arguments)]
543+fn find_mv_refs(
544+ st: &MiState,
545+ c: &InterBlockCtx<'_>,
546+ mode: u8,
547+ ref_frame: i8,
548+ bsize: usize,
549+ row: usize,
550+ col: usize,
551+ block: i32,
552+ bw: usize,
553+ bh: usize,
554+) -> (usize, [(i32, i32); MAX_MV_REF_CANDIDATES]) {
555+ let search = &MV_REF_BLOCKS[bsize];
556+ let early_break = mode != NEARMV;
557+ let mvref_dbg = crate::mvdbg_enabled() && mode == NEWMV;
558+ let mut list = [(0, 0); MAX_MV_REF_CANDIDATES];
559+ let mut count = 0usize;
560+ let mut different_ref_found = false;
561+ let mut done = false;
562+
563+ let cell = |p: (i32, i32)| -> Option<&MiInfo> {
564+ st.at((row as i32 + p.0) as usize, (col as i32 + p.1) as usize)
565+ };
566+
567+ let mut i = 0usize;
568+ if block >= 0 {
569+ while i < 2 && !done {
570+ let p = search[i];
571+ if is_inside(c, row, col, p) {
572+ different_ref_found = true;
573+ if let Some(cand) = cell(p) {
574+ if cand.ref_frame[0] == ref_frame {
575+ done = add_mv_ref_list_eb(
576+ get_sub_block_mv(cand, 0, p.1, block),
577+ &mut list,
578+ &mut count,
579+ early_break,
580+ );
581+ } else if cand.ref_frame[1] == ref_frame {
582+ done = add_mv_ref_list_eb(
583+ get_sub_block_mv(cand, 1, p.1, block),
584+ &mut list,
585+ &mut count,
586+ early_break,
587+ );
588+ }
589+ }
590+ }
591+ i += 1;
592+ }
593+ }
594+ while i < MVREF_NEIGHBOURS && !done {
595+ let p = search[i];
596+ if is_inside(c, row, col, p) {
597+ different_ref_found = true;
598+ if let Some(cand) = cell(p) {
599+ if cand.ref_frame[0] == ref_frame {
600+ done = add_mv_ref_list_eb(cand.mv[0], &mut list, &mut count, early_break);
601+ } else if cand.ref_frame[1] == ref_frame {
602+ done = add_mv_ref_list_eb(cand.mv[1], &mut list, &mut count, early_break);
603+ }
604+ }
605+ }
606+ i += 1;
607+ }
608+
609+ if !done {
610+ if let Some(prev) = c.prev_mvs {
611+ let e = prev[row * c.mi_cols + col];
612+ if e.ref_frame[0] == ref_frame {
613+ done = add_mv_ref_list_eb(e.mv[0], &mut list, &mut count, early_break);
614+ } else if e.ref_frame[1] == ref_frame {
615+ done = add_mv_ref_list_eb(e.mv[1], &mut list, &mut count, early_break);
616+ }
617+ }
618+ }
619+
620+ if crate::mvdbg2_enabled()
621+ && ((row == 8 && col == 104) || (row == 32 && col == 64) || (row == 8 && col == 32))
622+ {
623+ for (i, p) in search.iter().enumerate() {
624+ let ins = is_inside(c, row, col, *p);
625+ let c2 = st.at((row as i32 + p.0) as usize, (col as i32 + p.1) as usize);
626+ let qr = (row as i32 + p.0) as usize;
627+ let qc = (col as i32 + p.1) as usize;
628+ match c2 {
629+ Some(cd) => eprintln!(
630+ "MVC r={row} c={col} i={i} p={p:?} q=({qr} {qc}) idx={} inside={ins} ref0={} ref1={} mv0={:?} mv1={:?} inter={}",
631+ qr * c.mi_cols + qc,
632+ cd.ref_frame[0], cd.ref_frame[1], cd.mv[0], cd.mv[1], cd.is_inter
633+ ),
634+ None => eprintln!("MVC r={row} c={col} i={i} p={p:?} q=({qr} {qc}) inside={ins} none"),
635+ }
636+ }
637+ }
638+ if mvref_dbg {
639+ eprintln!(
640+ "MVREF r={row} c={col} bsize={bsize} mode={mode} n={count} l0={:?} l1={:?}",
641+ list[0], list[1]
642+ );
643+ }
644+ if !done && different_ref_found {
645+ for p in search.iter() {
646+ if !is_inside(c, row, col, *p) {
647+ continue;
648+ }
649+ let Some(cand) = cell(*p) else { continue };
650+ if !cand.is_inter {
651+ continue;
652+ }
653+ if cand.ref_frame[0] != ref_frame {
654+ done = add_mv_ref_list_eb(
655+ scale_mv(cand, 0, ref_frame, c.sign_bias),
656+ &mut list,
657+ &mut count,
658+ early_break,
659+ );
660+ }
661+ if done {
662+ break;
663+ }
664+ if cand.ref_frame[1] > INTRA_FRAME
665+ && cand.ref_frame[1] != ref_frame
666+ && cand.mv[1] != cand.mv[0]
667+ {
668+ done = add_mv_ref_list_eb(
669+ scale_mv(cand, 1, ref_frame, c.sign_bias),
670+ &mut list,
671+ &mut count,
672+ early_break,
673+ );
674+ }
675+ }
676+ }
677+
678+ if !done {
679+ if let Some(prev) = c.prev_mvs {
680+ let e = prev[row * c.mi_cols + col];
681+ if e.ref_frame[0] != ref_frame && e.ref_frame[0] > INTRA_FRAME {
682+ let mut mv = e.mv[0];
683+ if c.sign_bias[e.ref_frame[0] as usize] != c.sign_bias[ref_frame as usize] {
684+ mv = (-mv.0, -mv.1);
685+ }
686+ done = add_mv_ref_list_eb(mv, &mut list, &mut count, early_break);
687+ }
688+ if !done
689+ && e.ref_frame[1] > INTRA_FRAME
690+ && e.ref_frame[1] != ref_frame
691+ && e.mv[1] != e.mv[0]
692+ {
693+ let mut mv = e.mv[1];
694+ if c.sign_bias[e.ref_frame[1] as usize] != c.sign_bias[ref_frame as usize] {
695+ mv = (-mv.0, -mv.1);
696+ }
697+ add_mv_ref_list_eb(mv, &mut list, &mut count, early_break);
698+ }
699+ }
700+ }
701+
702+ // `dec_find_mv_refs`' tail (vp9_decodemv.c:626): an early exit (`goto Done`
703+ // -- either the second candidate was added, or `early_break` stopped us at
704+ // the first) JUMPS OVER the mode-derived override and returns the count as
705+ // accumulated; falling out of the loops applies the override, so a NEARMV
706+ // block reports two candidates even when only one was found and the caller
707+ // then reads the zeroed second slot. The list was memset to zero first, so
708+ // that second slot is (0, 0), and the clamp covers the final count only.
709+ let n = if done {
710+ count
711+ } else if mode == NEARMV {
712+ MAX_MV_REF_CANDIDATES
713+ } else {
714+ 1
715+ };
716+ for k in 0..n {
717+ clamp_mv_ref(&mut list[k], c, row, col, bw, bh);
718+ }
719+ (n, list)
720+}
721+
722+/// `append_sub8x8_mvs_for_idx` (`vp9_decodemv.c:620`).
723+#[allow(clippy::too_many_arguments)]
724+fn append_sub8x8_mvs_for_idx(
725+ st: &MiState,
726+ c: &InterBlockCtx<'_>,
727+ info: &MiInfo,
728+ bmode: u8,
729+ block: usize,
730+ rf: usize,
731+ row: usize,
732+ col: usize,
733+ bw: usize,
734+ bh: usize,
735+) -> (i32, i32) {
736+ let bsize = info.sb_type;
737+ match block {
738+ 0 => {
739+ let (n, list) = find_mv_refs(st, c, bmode, info.ref_frame[rf], bsize, row, col, 0, bw, bh);
740+ list[n - 1]
741+ }
742+ 1 | 2 => {
743+ if bmode == NEARESTMV {
744+ info.bmi_mv[0][rf]
745+ } else {
746+ let (_n, list) =
747+ find_mv_refs(st, c, bmode, info.ref_frame[rf], bsize, row, col, block as i32, bw, bh);
748+ let mut out = (0, 0);
749+ for m in list.iter() {
750+ if info.bmi_mv[0][rf] != *m {
751+ out = *m;
752+ break;
753+ }
754+ }
755+ out
756+ }
757+ }
758+ _ => {
759+ if bmode == NEARESTMV {
760+ info.bmi_mv[2][rf]
761+ } else {
762+ if info.bmi_mv[2][rf] != info.bmi_mv[1][rf] {
763+ info.bmi_mv[1][rf]
764+ } else if info.bmi_mv[2][rf] != info.bmi_mv[0][rf] {
765+ info.bmi_mv[0][rf]
766+ } else {
767+ let (_n, list) = find_mv_refs(
768+ st,
769+ c,
770+ bmode,
771+ info.ref_frame[rf],
772+ bsize,
773+ row,
774+ col,
775+ block as i32,
776+ bw,
777+ bh,
778+ );
779+ let mut out = (0, 0);
780+ for m in list.iter() {
781+ if info.bmi_mv[2][rf] != *m {
782+ out = *m;
783+ break;
784+ }
785+ }
786+ out
787+ }
788+ }
789+ }
790+ }
791+}
792+
793+/// `read_mv_component` (`vp9_decodemv.c:246`).
794+fn read_mv_component(r: &mut BoolDecoder, fc: &FrameContext, comp: usize, use_hp: bool) -> i32 {
795+ let dbg = crate::interdump_enabled();
796+ if dbg {
797+ eprintln!("MVF c{comp} sign");
798+ }
799+ let sign = r.read_bool(fc.nmv_sign[comp]);
800+ if dbg {
801+ eprintln!("MVF c{comp} cls");
802+ }
803+ let mv_class = r.read_tree(&MV_CLASS_TREE, &fc.nmv_classes[comp]) as i32;
804+ let class0 = mv_class == 0;
805+ let mut d = 0i32;
806+ let mut mag;
807+ if dbg {
808+ eprintln!("MVF c{comp} class={mv_class}");
809+ }
810+ if class0 {
811+ if dbg {
812+ eprintln!("MVF c{comp} class0bit");
813+ }
814+ d = r.read_bool(fc.nmv_class0[comp][0]) as i32;
815+ mag = 0;
816+ } else {
817+ let n = mv_class + CLASS0_BITS - 1;
818+ for i in 0..n {
819+ if dbg {
820+ eprintln!("MVF c{comp} bits[{i}]");
821+ }
822+ d |= (r.read_bool(fc.nmv_bits[comp][i as usize]) as i32) << i;
823+ }
824+ mag = CLASS0_SIZE << (mv_class + 2);
825+ }
826+ if dbg {
827+ eprintln!("MVF c{comp} fp");
828+ }
829+ let fr = if class0 {
830+ r.read_tree(&MV_FP_TREE, &fc.nmv_class0_fp[comp][d as usize])
831+ } else {
832+ r.read_tree(&MV_FP_TREE, &fc.nmv_fp[comp])
833+ } as i32;
834+ let hp = if use_hp {
835+ if dbg {
836+ eprintln!("MVF c{comp} hp");
837+ }
838+ r.read_bool(if class0 {
839+ fc.nmv_class0_hp[comp]
840+ } else {
841+ fc.nmv_hp[comp]
842+ }) as i32
843+ } else {
844+ 1
845+ };
846+ mag += ((d << 3) | (fr << 1) | hp) + 1;
847+ if sign {
848+ -mag
849+ } else {
850+ mag
851+ }
852+}
853+
854+/// `read_mv`: returns `(mv, diff)`.
855+fn read_mv(
856+ r: &mut BoolDecoder,
857+ pred: (i32, i32),
858+ fc: &FrameContext,
859+ allow_hp: bool,
860+) -> ((i32, i32), (i32, i32)) {
861+ let joint = r.read_tree(&MV_JOINT_TREE, &fc.nmv_joints);
862+ let use_hp = allow_hp && use_mv_hp(pred);
863+ if crate::interdump_enabled() {
864+ eprintln!("MVJ joint={joint} use_hp={use_hp} pred={pred:?}");
865+ }
866+ // mv_joint_vertical = joint & 2, mv_joint_horizontal = joint & 1.
867+ let mut diff = (0i32, 0i32);
868+ if joint & 2 != 0 {
869+ diff.0 = read_mv_component(r, fc, 0, use_hp);
870+ }
871+ if joint & 1 != 0 {
872+ diff.1 = read_mv_component(r, fc, 1, use_hp);
873+ }
874+ ((pred.0 + diff.0, pred.1 + diff.1), diff)
875+}
876+
877+/// `assign_mv`: returns `(mv, diff)`; only `NEWMV` consumes bits.
878+fn assign_mv(
879+ r: &mut BoolDecoder,
880+ fc: &FrameContext,
881+ mode: u8,
882+ ref_mv: &[(i32, i32); 2],
883+ near_nearest: &[(i32, i32); 2],
884+ is_compound: usize,
885+ allow_hp: bool,
886+) -> crate::Result<([(i32, i32); 2], [(i32, i32); 2])> {
887+ let mut mv = [(0, 0); 2];
888+ let mut diff = [(0, 0); 2];
889+ match mode {
890+ NEWMV => {
891+ for i in 0..1 + is_compound {
892+ let (m, d) = read_mv(r, ref_mv[i], fc, allow_hp);
893+ mv[i] = m;
894+ diff[i] = d;
895+ }
896+ }
897+ NEARMV | NEARESTMV => mv = *near_nearest,
898+ ZEROMV => {}
899+ other => {
900+ return Err(crate::Error::corrupt(format!(
901+ "VP9 assign_mv: invalid inter mode {other}"
902+ )))
903+ }
904+ }
905+ Ok((mv, diff))
906+}
907+
908+/// `read_block_reference_mode`.
909+fn read_block_reference_mode(
910+ r: &mut BoolDecoder,
911+ c: &InterBlockCtx<'_>,
912+ fc: &FrameContext,
913+ nb: Nb<'_>,
914+) -> u8 {
915+ if c.ifs.reference_mode == REFERENCE_MODE_SELECT {
916+ let ctx = reference_mode_context(c, nb);
917+ u8::from(r.read_bool(fc.comp_inter[ctx]))
918+ } else {
919+ c.ifs.reference_mode
920+ }
921+}
922+
923+/// `vp9_get_reference_mode_context` (`vp9_pred_common.c`).
924+fn reference_mode_context(c: &InterBlockCtx<'_>, nb: Nb<'_>) -> usize {
925+ let fixed = c.ifs.comp_fixed_ref;
926+ let has_second = |m: &MiInfo| m.ref_frame[1] > INTRA_FRAME;
927+ match (nb.above, nb.left) {
928+ (Some(a), Some(l)) => {
929+ if !has_second(a) && !has_second(l) {
930+ usize::from((a.ref_frame[0] == fixed) ^ (l.ref_frame[0] == fixed))
931+ } else if !has_second(a) {
932+ 2 + usize::from(a.ref_frame[0] == fixed || !a.is_inter)
933+ } else if !has_second(l) {
934+ 2 + usize::from(l.ref_frame[0] == fixed || !l.is_inter)
935+ } else {
936+ 4
937+ }
938+ }
939+ (Some(m), None) | (None, Some(m)) => {
940+ if !has_second(m) {
941+ usize::from(m.ref_frame[0] == fixed)
942+ } else {
943+ 3
944+ }
945+ }
946+ (None, None) => 1,
947+ }
948+}
949+
950+/// `vp9_get_pred_context_comp_ref_p` (`vp9_pred_common.c`).
951+fn pred_context_comp_ref_p(c: &InterBlockCtx<'_>, nb: Nb<'_>) -> usize {
952+ let fixed = c.ifs.comp_fixed_ref;
953+ let var = c.ifs.comp_var_ref;
954+ let var_ref_idx = usize::from(!c.sign_bias[fixed as usize]);
955+ let has_second = |m: &MiInfo| m.ref_frame[1] > INTRA_FRAME;
956+ let vr = |m: &MiInfo| -> i8 {
957+ if has_second(m) {
958+ m.ref_frame[var_ref_idx]
959+ } else {
960+ m.ref_frame[0]
961+ }
962+ };
963+ match (nb.above, nb.left) {
964+ (Some(a), Some(l)) => {
965+ if !a.is_inter && !l.is_inter {
966+ 2
967+ } else if !a.is_inter || !l.is_inter {
968+ let e = if !a.is_inter { l } else { a };
969+ if !has_second(e) {
970+ 1 + 2 * usize::from(e.ref_frame[0] != var[1])
971+ } else {
972+ 1 + 2 * usize::from(e.ref_frame[var_ref_idx] != var[1])
973+ }
974+ } else {
975+ let a_sg = !has_second(a);
976+ let l_sg = !has_second(l);
977+ let vrfa = vr(a);
978+ let vrfl = vr(l);
979+ if vrfa == vrfl && var[1] == vrfa {
980+ 0
981+ } else if l_sg && a_sg {
982+ if (vrfa == fixed && vrfl == var[0]) || (vrfl == fixed && vrfa == var[0]) {
983+ 4
984+ } else if vrfa == vrfl {
985+ 3
986+ } else {
987+ 1
988+ }
989+ } else if l_sg || a_sg {
990+ let vrfc = if l_sg { vrfa } else { vrfl };
991+ let rfs = if a_sg { vrfa } else { vrfl };
992+ if vrfc == var[1] && rfs != var[1] {
993+ 1
994+ } else if rfs == var[1] && vrfc != var[1] {
995+ 2
996+ } else {
997+ 4
998+ }
999+ } else if vrfa == vrfl {
1000+ 4
1001+ } else {
1002+ 2
1003+ }
1004+ }
1005+ }
1006+ (Some(e), None) | (None, Some(e)) => {
1007+ if !e.is_inter {
1008+ 2
1009+ } else if has_second(e) {
1010+ 4 * usize::from(e.ref_frame[var_ref_idx] != var[1])
1011+ } else {
1012+ 3 * usize::from(e.ref_frame[0] != var[1])
1013+ }
1014+ }
1015+ (None, None) => 2,
1016+ }
1017+}
1018+
1019+/// `vp9_get_pred_context_single_ref_p1` (`vp9_pred_common.c`).
1020+fn pred_context_single_ref_p1(nb: Nb<'_>) -> usize {
1021+ let has_second = |m: &MiInfo| m.ref_frame[1] > INTRA_FRAME;
1022+ match (nb.above, nb.left) {
1023+ (Some(a), Some(l)) => {
1024+ if !a.is_inter && !l.is_inter {
1025+ 2
1026+ } else if !a.is_inter || !l.is_inter {
1027+ let e = if !a.is_inter { l } else { a };
1028+ if !has_second(e) {
1029+ 4 * usize::from(e.ref_frame[0] == LAST_FRAME)
1030+ } else {
1031+ 1 + usize::from(e.ref_frame[0] == LAST_FRAME || e.ref_frame[1] == LAST_FRAME)
1032+ }
1033+ } else {
1034+ let a2 = has_second(a);
1035+ let l2 = has_second(l);
1036+ if a2 && l2 {
1037+ 1 + usize::from(
1038+ a.ref_frame[0] == LAST_FRAME
1039+ || a.ref_frame[1] == LAST_FRAME
1040+ || l.ref_frame[0] == LAST_FRAME
1041+ || l.ref_frame[1] == LAST_FRAME,
1042+ )
1043+ } else if a2 || l2 {
1044+ let rfs = if !a2 { a.ref_frame[0] } else { l.ref_frame[0] };
1045+ let crf1 = if a2 { a.ref_frame[0] } else { l.ref_frame[0] };
1046+ let crf2 = if a2 { a.ref_frame[1] } else { l.ref_frame[1] };
1047+ if rfs == LAST_FRAME {
1048+ 3 + usize::from(crf1 == LAST_FRAME || crf2 == LAST_FRAME)
1049+ } else {
1050+ usize::from(crf1 == LAST_FRAME || crf2 == LAST_FRAME)
1051+ }
1052+ } else {
1053+ 2 * usize::from(a.ref_frame[0] == LAST_FRAME)
1054+ + 2 * usize::from(l.ref_frame[0] == LAST_FRAME)
1055+ }
1056+ }
1057+ }
1058+ (Some(e), None) | (None, Some(e)) => {
1059+ if !e.is_inter {
1060+ 2
1061+ } else if !has_second(e) {
1062+ 4 * usize::from(e.ref_frame[0] == LAST_FRAME)
1063+ } else {
1064+ 1 + usize::from(e.ref_frame[0] == LAST_FRAME || e.ref_frame[1] == LAST_FRAME)
1065+ }
1066+ }
1067+ (None, None) => 2,
1068+ }
1069+}
1070+
1071+/// `vp9_get_pred_context_single_ref_p2` (`vp9_pred_common.c`).
1072+fn pred_context_single_ref_p2(nb: Nb<'_>) -> usize {
1073+ let has_second = |m: &MiInfo| m.ref_frame[1] > INTRA_FRAME;
1074+ match (nb.above, nb.left) {
1075+ (Some(a), Some(l)) => {
1076+ if !a.is_inter && !l.is_inter {
1077+ 2
1078+ } else if !a.is_inter || !l.is_inter {
1079+ let e = if !a.is_inter { l } else { a };
1080+ if !has_second(e) {
1081+ if e.ref_frame[0] == LAST_FRAME {
1082+ 3
1083+ } else {
1084+ 4 * usize::from(e.ref_frame[0] == GOLDEN_FRAME)
1085+ }
1086+ } else {
1087+ 1 + 2 * usize::from(
1088+ e.ref_frame[0] == GOLDEN_FRAME || e.ref_frame[1] == GOLDEN_FRAME,
1089+ )
1090+ }
1091+ } else {
1092+ let a2 = has_second(a);
1093+ let l2 = has_second(l);
1094+ if a2 && l2 {
1095+ if a.ref_frame[0] == l.ref_frame[0] && a.ref_frame[1] == l.ref_frame[1] {
1096+ 3 * usize::from(
1097+ a.ref_frame[0] == GOLDEN_FRAME
1098+ || a.ref_frame[1] == GOLDEN_FRAME
1099+ || l.ref_frame[0] == GOLDEN_FRAME
1100+ || l.ref_frame[1] == GOLDEN_FRAME,
1101+ )
1102+ } else {
1103+ 2
1104+ }
1105+ } else if a2 || l2 {
1106+ let rfs = if !a2 { a.ref_frame[0] } else { l.ref_frame[0] };
1107+ let crf1 = if a2 { a.ref_frame[0] } else { l.ref_frame[0] };
1108+ let crf2 = if a2 { a.ref_frame[1] } else { l.ref_frame[1] };
1109+ let crf_golden = usize::from(crf1 == GOLDEN_FRAME || crf2 == GOLDEN_FRAME);
1110+ if rfs == GOLDEN_FRAME {
1111+ 3 + crf_golden
1112+ } else if rfs == ALTREF_FRAME {
1113+ crf_golden
1114+ } else {
1115+ 1 + 2 * crf_golden
1116+ }
1117+ } else if a.ref_frame[0] == LAST_FRAME && l.ref_frame[0] == LAST_FRAME {
1118+ 3
1119+ } else if a.ref_frame[0] == LAST_FRAME || l.ref_frame[0] == LAST_FRAME {
1120+ let edge0 = if a.ref_frame[0] == LAST_FRAME {
1121+ l.ref_frame[0]
1122+ } else {
1123+ a.ref_frame[0]
1124+ };
1125+ 4 * usize::from(edge0 == GOLDEN_FRAME)
1126+ } else {
1127+ 2 * usize::from(a.ref_frame[0] == GOLDEN_FRAME)
1128+ + 2 * usize::from(l.ref_frame[0] == GOLDEN_FRAME)
1129+ }
1130+ }
1131+ }
1132+ (Some(e), None) | (None, Some(e)) => {
1133+ if !e.is_inter || (e.ref_frame[0] == LAST_FRAME && !has_second(e)) {
1134+ 2
1135+ } else if !has_second(e) {
1136+ 4 * usize::from(e.ref_frame[0] == GOLDEN_FRAME)
1137+ } else {
1138+ 3 * usize::from(e.ref_frame[0] == GOLDEN_FRAME || e.ref_frame[1] == GOLDEN_FRAME)
1139+ }
1140+ }
1141+ (None, None) => 2,
1142+ }
1143+}
1144+
1145+/// `read_ref_frames`.
1146+fn read_ref_frames(
1147+ r: &mut BoolDecoder,
1148+ c: &InterBlockCtx<'_>,
1149+ fc: &FrameContext,
1150+ nb: Nb<'_>,
1151+ segment_id: u8,
1152+ out: &mut [i8; 2],
1153+) {
1154+ if seg_feature(c.seg, segment_id, SEG_LVL_REF_FRAME) {
1155+ out[0] = c.seg.feature_data[segment_id as usize][SEG_LVL_REF_FRAME] as i8;
1156+ out[1] = NO_REF_FRAME;
1157+ return;
1158+ }
1159+ let mode = read_block_reference_mode(r, c, fc, nb);
1160+ if mode == COMPOUND_REFERENCE {
1161+ let idx = usize::from(c.sign_bias[c.ifs.comp_fixed_ref as usize]);
1162+ let ctx = pred_context_comp_ref_p(c, nb);
1163+ let bit = usize::from(r.read_bool(fc.comp_ref[ctx]));
1164+ out[idx] = c.ifs.comp_fixed_ref;
1165+ out[1 - idx] = c.ifs.comp_var_ref[bit];
1166+ } else {
1167+ let ctx0 = pred_context_single_ref_p1(nb);
1168+ let bit0 = r.read_bool(fc.single_ref[ctx0][0]);
1169+ if bit0 {
1170+ let ctx1 = pred_context_single_ref_p2(nb);
1171+ let bit1 = r.read_bool(fc.single_ref[ctx1][1]);
1172+ out[0] = if bit1 { ALTREF_FRAME } else { GOLDEN_FRAME };
1173+ } else {
1174+ out[0] = LAST_FRAME;
1175+ }
1176+ out[1] = NO_REF_FRAME;
1177+ }
1178+}
1179+
1180+/// `read_inter_block_mode_info` (`vp9_decodemv.c:702`).
1181+#[allow(clippy::too_many_arguments)]
1182+fn read_inter_block_mode_info(
1183+ r: &mut BoolDecoder,
1184+ st: &MiState,
1185+ c: &InterBlockCtx<'_>,
1186+ fc: &FrameContext,
1187+ info: &mut MiInfo,
1188+ nb: Nb<'_>,
1189+ row: usize,
1190+ col: usize,
1191+ partition: u8,
1192+) -> crate::Result<()> {
1193+ let bsize = info.sb_type;
1194+ let mut best_ref_mvs = [(0, 0); 2];
1195+ read_ref_frames(r, c, fc, nb, info.segment, &mut info.ref_frame);
1196+ let is_compound = usize::from(info.ref_frame[1] > INTRA_FRAME);
1197+ let inter_mode_ctx = get_mode_context(st, c, bsize, row, col);
1198+
1199+ if seg_feature(c.seg, info.segment, SEG_LVL_SKIP) {
1200+ info.mode = ZEROMV;
1201+ if bsize < 3 {
1202+ return Err(crate::Error::corrupt(
1203+ "VP9 segment skip feature on a sub-8x8 block",
1204+ ));
1205+ }
1206+ } else if bsize >= 3 {
1207+ info.mode = read_inter_mode(r, fc, inter_mode_ctx);
1208+ }
1209+
1210+ info.interp_filter = if c.frame_interp == SWITCHABLE {
1211+ let ictx = switchable_interp_ctx(nb);
1212+ if crate::interdump_enabled() {
1213+ eprintln!(
1214+ "SWI ctx={} p0={} p1={}",
1215+ ictx, fc.switchable_interp[ictx][0], fc.switchable_interp[ictx][1]
1216+ );
1217+ }
1218+ let t = r.read_tree(&SWITCHABLE_INTERP_TREE, &fc.switchable_interp[ictx]);
1219+ if crate::interdump_enabled() {
1220+ eprintln!("SWItype {t}");
1221+ }
1222+ t
1223+ } else {
1224+ c.frame_interp
1225+ };
1226+
1227+ // Block dimensions in 8x8 units for the MV clamp (libvpx's bw/bh from
1228+ // `1 << (bwl - 1)`: a sub-8x8 shape occupies a whole 8x8 cell).
1229+ let bw = if bsize < 3 {
1230+ 1
1231+ } else {
1232+ 1usize << (B_WIDTH_LOG2_LOOKUP[bsize] as usize - 1)
1233+ };
1234+ let bh = if bsize < 3 {
1235+ 1
1236+ } else {
1237+ 1usize << (B_HEIGHT_LOG2_LOOKUP[bsize] as usize - 1)
1238+ };
1239+
1240+ if bsize < 3 {
1241+ // PARTITION_VERT clears the wide bit, PARTITION_HORZ the tall one.
1242+ let num_4x4_w = 1usize << u32::from(partition & 2 == 0);
1243+ let num_4x4_h = 1usize << u32::from(partition & 1 == 0);
1244+ let mut got_mv_refs_for_new = false;
1245+ let mut best_sub8x8 = [(0, 0); 2];
1246+ let mut b_mode = info.mode;
1247+ let mut idy = 0usize;
1248+ while idy < 2 {
1249+ let mut idx = 0usize;
1250+ while idx < 2 {
1251+ let j = idy * 2 + idx;
1252+ b_mode = read_inter_mode(r, fc, inter_mode_ctx);
1253+ info.bmi[j] = b_mode;
1254+ if b_mode == NEARESTMV || b_mode == NEARMV {
1255+ for rf in 0..1 + is_compound {
1256+ best_sub8x8[rf] = append_sub8x8_mvs_for_idx(
1257+ st, c, info, b_mode, j, rf, row, col, bw, bh,
1258+ );
1259+ }
1260+ } else if b_mode == NEWMV && !got_mv_refs_for_new {
1261+ for rf in 0..1 + is_compound {
1262+ let frame = info.ref_frame[rf];
1263+ let (_n, list) =
1264+ find_mv_refs(st, c, NEWMV, frame, bsize, row, col, -1, bw, bh);
1265+ let mut mv = list[0];
1266+ lower_mv_precision(&mut mv, c.allow_hp);
1267+ best_ref_mvs[rf] = mv;
1268+ got_mv_refs_for_new = true;
1269+ }
1270+ }
1271+ let (mv, diff) = assign_mv(
1272+ r,
1273+ fc,
1274+ b_mode,
1275+ &best_ref_mvs,
1276+ &best_sub8x8,
1277+ is_compound,
1278+ c.allow_hp,
1279+ )?;
1280+ info.bmi_mv[j] = mv;
1281+ info.mv_diff = diff;
1282+ if num_4x4_h == 2 {
1283+ info.bmi_mv[j + 2] = info.bmi_mv[j];
1284+ }
1285+ if num_4x4_w == 2 {
1286+ info.bmi_mv[j + 1] = info.bmi_mv[j];
1287+ }
1288+ idx += num_4x4_w;
1289+ }
1290+ idy += num_4x4_h;
1291+ }
1292+ info.mode = b_mode;
1293+ info.mv = info.bmi_mv[3];
1294+ } else {
1295+ if info.mode != ZEROMV {
1296+ for rf in 0..1 + is_compound {
1297+ let frame = info.ref_frame[rf];
1298+ let (n, list) = find_mv_refs(st, c, info.mode, frame, bsize, row, col, -1, bw, bh);
1299+ let mut mv = list[n - 1];
1300+ lower_mv_precision(&mut mv, c.allow_hp);
1301+ best_ref_mvs[rf] = mv;
1302+ }
1303+ }
1304+ let (mv, diff) = assign_mv(
1305+ r,
1306+ fc,
1307+ info.mode,
1308+ &best_ref_mvs,
1309+ &best_ref_mvs,
1310+ is_compound,
1311+ c.allow_hp,
1312+ )?;
1313+ info.mv = mv;
1314+ info.mv_diff = diff;
1315+ }
1316+ Ok(())
1317+}
crates/ec-vp9/src/lib.rsmodified+33 -0
@@ -19,6 +19,7 @@
19 pub mod bool;19 pub mod bool;
20 pub mod decode;20 pub mod decode;
21 pub mod header;21 pub mod header;
22+pub(crate) mod inter;
22 pub mod intra;23 pub mod intra;
23 pub mod loopfilter;24 pub mod loopfilter;
24 pub mod modes;25 pub mod modes;
@@ -45,3 +46,35 @@ pub(crate) fn trace_enabled() -> bool {
45 _ => true,46 _ => true,
46 }47 }
47 }48 }
49+
50+/// Cached `getenv` probe: `EC_VP9_*` gates are consulted per block, per MV
51+/// component and per switchable-interp read, and `std::env::var_os` locks std's
52+/// ENV lock, so each gate resolves once per process and the hot path is a
53+/// single relaxed atomic load (see `trace_enabled`).
54+macro_rules! cached_gate {
55+ ($fn_name:ident, $env:literal) => {
56+ pub(crate) fn $fn_name() -> bool {
57+ use std::sync::atomic::{AtomicU8, Ordering};
58+ static STATE: AtomicU8 = AtomicU8::new(0);
59+ match STATE.load(Ordering::Relaxed) {
60+ 0 => {
61+ let on = std::env::var_os($env).is_some();
62+ STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed);
63+ on
64+ }
65+ 1 => false,
66+ _ => true,
67+ }
68+ }
69+ };
70+}
71+
72+// Per-block dump gate for the inter-syntax lane (scratch harnesses);
73+// a candidate-list dump (`mode == NEWMV` only);
74+// a search-position cell + grid-store dump; and a post-compressed-header
75+// MV probability table dump. (Plain comments: a doc comment on a macro
76+// invocation is an "unused doc comment" warning.)
77+cached_gate!(interdump_enabled, "EC_VP9_INTERDUMP");
78+cached_gate!(mvdbg_enabled, "EC_VP9_MVDGB");
79+cached_gate!(mvdbg2_enabled, "EC_VP9_MVDGB2");
80+cached_gate!(mvdump_enabled, "EC_VP9_MVDUMP");
crates/ec-vp9/src/modes.rsmodified+31 -2
@@ -16,6 +16,21 @@ pub(crate) struct MiInfo {
16 pub uv_mode: u8,16 pub uv_mode: u8,
17 /// Per-4x4 sub-block y modes, valid when `sb_type < 3` (BLOCK_8X8).17 /// Per-4x4 sub-block y modes, valid when `sb_type < 3` (BLOCK_8X8).
18 pub bmi: [u8; 4],18 pub bmi: [u8; 4],
19+ /// `is_inter_block(mi)`: `ref_frame[0] > INTRA_FRAME`.
20+ pub is_inter: bool,
21+ /// `mi->ref_frame[0]`/`[1]`: `INTRA_FRAME` (0), `LAST`/`GOLDEN`/`ALTREF`
22+ /// (1..3), `NO_REF_FRAME` (-1).
23+ pub ref_frame: [i8; 2],
24+ /// `mi->mv[..]`: the refreshed MV (predictor + codeword diff).
25+ pub mv: [(i32, i32); 2],
26+ /// The raw MV codeword diff of each reference frame.
27+ pub mv_diff: [(i32, i32); 2],
28+ /// `mi->bmi[j].as_mv`.
29+ pub bmi_mv: [[(i32, i32); 2]; 4],
30+ /// `mi->seg_id_predicted`.
31+ pub seg_id_predicted: bool,
32+ /// `mi->interp_filter`.
33+ pub interp_filter: u8,
19 }34 }
20 35
21 /// The mode-info grid and the partition contexts of one tile pass.36 /// The mode-info grid and the partition contexts of one tile pass.
@@ -42,7 +57,12 @@ impl MiState {
42 }57 }
43 }58 }
44 59
45- fn above_mi(&self, row: usize, col: usize, tile_row_start: usize) -> Option<&MiInfo> {60+ /// The grid cell at an absolute (row, col), `None` when not decoded yet.
61+ pub(crate) fn at(&self, row: usize, col: usize) -> Option<&MiInfo> {
62+ self.grid.get(row * self.mi_cols + col).and_then(|c| c.as_ref())
63+ }
64+
65+ pub(crate) fn above_mi(&self, row: usize, col: usize, tile_row_start: usize) -> Option<&MiInfo> {
46 if row > tile_row_start {66 if row > tile_row_start {
47 self.grid[(row - 1) * self.mi_cols + col].as_ref()67 self.grid[(row - 1) * self.mi_cols + col].as_ref()
48 } else {68 } else {
@@ -50,7 +70,7 @@ impl MiState {
50 }70 }
51 }71 }
52 72
53- fn left_mi(&self, row: usize, col: usize, tile_col_start: usize) -> Option<&MiInfo> {73+ pub(crate) fn left_mi(&self, row: usize, col: usize, tile_col_start: usize) -> Option<&MiInfo> {
54 if col > tile_col_start {74 if col > tile_col_start {
55 self.grid[row * self.mi_cols + col - 1].as_ref()75 self.grid[row * self.mi_cols + col - 1].as_ref()
56 } else {76 } else {
@@ -213,6 +233,15 @@ pub(crate) fn read_intra_frame_mode_info(
213 mode: DC_PRED,233 mode: DC_PRED,
214 uv_mode: DC_PRED,234 uv_mode: DC_PRED,
215 bmi: [DC_PRED; 4],235 bmi: [DC_PRED; 4],
236+ is_inter: false,
237+ ref_frame: [0, -1],
238+ mv: [(0, 0); 2],
239+ mv_diff: [(0, 0); 2],
240+ bmi_mv: [[(0, 0); 2]; 4],
241+ seg_id_predicted: false,
242+ // read_intra_block_mode_info sets this so a later
243+ // get_pred_context_switchable_interp never sees a stale filter.
244+ interp_filter: 3,
216 };245 };
217 match sb_type {246 match sb_type {
218 0 => {247 0 => {
crates/ec-vp9/src/tables/gen_tables.rsmodified+64 -0
@@ -1427,3 +1427,67 @@ pub(crate) const KF_UV_MODE_PROB: [u8; 90] = [
1427 12, 32, 145, 195, 142, 32, 38, 86, 116, 12, 64, 120, 140, 125, 49, 115, 121, 102, 19, 66, 162,1427 12, 32, 145, 195, 142, 32, 38, 86, 116, 12, 64, 120, 140, 125, 49, 115, 121, 102, 19, 66, 162,
1428 182, 122, 35, 59, 128,1428 182, 122, 35, 59, 128,
1429 ];1429 ];
1430+
1431+// ---------------------------------------------------------------------------
1432+// Inter-frame tables (libvpx v1.15: common/vp9_entropymode.c,
1433+// common/vp9_entropymv.c, common/vp9_mvref_common.h, common/vp9_common_data.c).
1434+// ---------------------------------------------------------------------------
1435+
1436+/// `vp9_inter_mode_tree`; leaves are `mode - NEARESTMV` (0..3).
1437+pub(crate) const INTER_MODE_TREE: [i8; 6] = [-2, 2, 0, 4, -1, -3];
1438+/// `vp9_switchable_interp_tree` = `{ -EIGHTTAP, 2, -EIGHTTAP_SMOOTH,
1439+/// -EIGHTTAP_SHARP }`. libvpx's filter constants are #defines with
1440+/// `EIGHTTAP = 0`, `EIGHTTAP_SMOOTH = 1`, `EIGHTTAP_SHARP = 2`
1441+/// (vp9/common/vp9_filter.h:23) — NOT the spec's naming order, so the tree is
1442+/// `{0, 2, -1, -2}` and the leaves are the coded `interp_filter` values.
1443+pub(crate) const SWITCHABLE_INTERP_TREE: [i8; 4] = [0, 2, -1, -2];
1444+/// `vp9_mv_joint_tree`.
1445+pub(crate) const MV_JOINT_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3];
1446+/// `vp9_mv_class_tree`.
1447+pub(crate) const MV_CLASS_TREE: [i8; 20] = [
1448+ 0, 2, -1, 4, 6, 8, -2, -3, 10, 12, -4, -5, -6, 14, 16, 18, -7, -8, -9, -10,
1449+];
1450+/// `vp9_mv_fp_tree`.
1451+pub(crate) const MV_FP_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3];
1452+/// `default_if_y_probs`, `[BLOCK_SIZE_GROUPS][INTRA_MODES - 1]`.
1453+pub(crate) const DEFAULT_Y_MODE_PROBS: [u8; 36] = [
1454+ 65, 32, 18, 144, 162, 194, 41, 51, 98, 132, 68, 18, 165, 217, 196, 45, 40, 78, 173, 80, 19, 176,
1455+ 240, 193, 64, 35, 46, 221, 135, 38, 194, 248, 121, 96, 85, 29,
1456+];
1457+/// `default_inter_mode_probs`, `[INTER_MODE_CONTEXTS][INTER_MODES - 1]`.
1458+pub(crate) const DEFAULT_INTER_MODE_PROBS: [u8; 21] = [
1459+ 2, 173, 34, 7, 145, 85, 7, 166, 63, 7, 94, 66, 8, 64, 46, 17, 81, 31, 25, 29, 30,
1460+];
1461+/// `default_intra_inter_p`.
1462+pub(crate) const DEFAULT_INTRA_INTER_PROBS: [u8; 4] = [9, 102, 187, 225];
1463+/// `default_comp_inter_p`.
1464+pub(crate) const DEFAULT_COMP_INTER_PROBS: [u8; 5] = [239, 183, 119, 96, 41];
1465+/// `default_single_ref_p`, `[REF_CONTEXTS][2]`.
1466+pub(crate) const DEFAULT_SINGLE_REF_PROBS: [u8; 10] =
1467+ [33, 16, 77, 74, 142, 142, 172, 170, 238, 247];
1468+/// `default_comp_ref_p`, flat `[REF_CONTEXTS]`.
1469+pub(crate) const DEFAULT_COMP_REF_PROBS: [u8; 5] = [50, 126, 123, 221, 226];
1470+/// `default_switchable_interp_prob`, `[SWITCHABLE_FILTER_CONTEXTS][2]`.
1471+pub(crate) const DEFAULT_SWITCHABLE_INTERP_PROBS: [u8; 8] = [235, 162, 36, 255, 34, 3, 149, 144];
1472+/// `default_nmv_context`: joints, then both components.
1473+pub(crate) const DEFAULT_NMVC_JOINTS: [u8; 3] = [32, 64, 96];
1474+pub(crate) const DEFAULT_NMVC_SIGN: [u8; 2] = [128, 128];
1475+pub(crate) const DEFAULT_NMVC_CLASSES: [u8; 20] = [
1476+ 224, 144, 192, 168, 192, 176, 192, 198, 198, 245, 216, 128, 176, 160, 176, 176, 192, 198, 198,
1477+ 208,
1478+];
1479+pub(crate) const DEFAULT_NMVC_CLASS0: [u8; 2] = [216, 208];
1480+pub(crate) const DEFAULT_NMVC_BITS: [u8; 20] = [
1481+ 136, 140, 148, 160, 176, 192, 224, 234, 234, 240, 136, 140, 148, 160, 176, 192, 224, 234, 234,
1482+ 240,
1483+];
1484+pub(crate) const DEFAULT_NMVC_CLASS0_FP: [u8; 12] =
1485+ [128, 128, 64, 96, 112, 64, 128, 128, 64, 96, 112, 64];
1486+pub(crate) const DEFAULT_NMVC_FP: [u8; 6] = [64, 96, 64, 64, 96, 64];
1487+pub(crate) const DEFAULT_NMVC_CLASS0_HP: [u8; 2] = [160, 160];
1488+pub(crate) const DEFAULT_NMVC_HP: [u8; 2] = [128, 128];
1489+/// `mode_2_counter`, indexed by `PREDICTION_MODE`.
1490+pub(crate) const MODE_2_COUNTER: [u8; 14] = [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 3, 1];
1491+/// `counter_to_context`.
1492+pub(crate) const COUNTER_TO_CONTEXT: [u8; 19] =
1493+ [2, 3, 4, 1, 3, 9, 0, 9, 9, 5, 5, 9, 5, 9, 9, 9, 9, 9, 6];
crates/ec-vp9/src/tokens.rsmodified+6 -4
@@ -51,7 +51,8 @@ pub(crate) struct CoeffBlock {
51 }51 }
52 52
53 /// `decode_coefs`, verbatim port. `dq` is `[dc, ac]`; plane 0 is luma,53 /// `decode_coefs`, verbatim port. `dq` is `[dc, ac]`; plane 0 is luma,
54-/// chroma is 1; the ref axis is fixed at 0 (intra).54+/// chroma is 1. `is_inter` selects the coefficient-probability ref axis
55+/// (libvpx `get_coef_probs`: `coef_probs[tx][plane][ref]`).
55 pub(crate) fn decode_coefs(56 pub(crate) fn decode_coefs(
56 r: &mut BoolDecoder,57 r: &mut BoolDecoder,
57 plane_type: usize,58 plane_type: usize,
@@ -61,6 +62,7 @@ pub(crate) fn decode_coefs(
61 scan: &[i16],62 scan: &[i16],
62 nb: &[i16],63 nb: &[i16],
63 probs4d: &[[[[[u8; 3]; 6]; 6]; 2]; 2],64 probs4d: &[[[[[u8; 3]; 6]; 6]; 2]; 2],
65+ is_inter: bool,
64 #[allow(unused_variables)] pos: (usize, usize),66 #[allow(unused_variables)] pos: (usize, usize),
65 #[allow(unused_variables)] plane: usize,67 #[allow(unused_variables)] plane: usize,
66 ) -> CoeffBlock {68 ) -> CoeffBlock {
@@ -74,7 +76,7 @@ pub(crate) fn decode_coefs(
74 let dq_shift = usize::from(tx_size == TX_32X32);76 let dq_shift = usize::from(tx_size == TX_32X32);
75 let mut dqv = dequant[0] as i32;77 let mut dqv = dequant[0] as i32;
76 let mut band = band_at(tx_size, c);78 let mut band = band_at(tx_size, c);
77- let mut prob: &[u8; 3] = &probs4d[plane_type][0][band][ctx];79+ let mut prob: &[u8; 3] = &probs4d[plane_type][usize::from(is_inter)][band][ctx];
78 if std::env::var_os("EC_VP9_DBG").is_some() && plane_type == 0 && ctx == 0 && band == 0 {80 if std::env::var_os("EC_VP9_DBG").is_some() && plane_type == 0 && ctx == 0 && band == 0 {
79 eprintln!("DBG coefs tx={tx_size} dq={dequant:?} ctx={ctx} band={band} prob={prob:?}");81 eprintln!("DBG coefs tx={tx_size} dq={dequant:?} ctx={ctx} band={band} prob={prob:?}");
80 }82 }
@@ -95,7 +97,7 @@ pub(crate) fn decode_coefs(
95 }97 }
96 ctx = get_coef_context(nb, &token_cache, c);98 ctx = get_coef_context(nb, &token_cache, c);
97 band = band_at(tx_size, c);99 band = band_at(tx_size, c);
98- prob = &probs4d[plane_type][0][band][ctx];100+ prob = &probs4d[plane_type][usize::from(is_inter)][band][ctx];
99 }101 }
100 let mut v: i32;102 let mut v: i32;
101 if r.read_bool(prob[2]) {103 if r.read_bool(prob[2]) {
@@ -142,7 +144,7 @@ pub(crate) fn decode_coefs(
142 if c < max_eob {144 if c < max_eob {
143 ctx = get_coef_context(nb, &token_cache, c);145 ctx = get_coef_context(nb, &token_cache, c);
144 band = band_at(tx_size, c);146 band = band_at(tx_size, c);
145- prob = &probs4d[plane_type][0][band][ctx];147+ prob = &probs4d[plane_type][usize::from(is_inter)][band][ctx];
146 }148 }
147 dqv = dequant[1] as i32;149 dqv = dequant[1] as i32;
148 }150 }
crates/ec-vp9/tests/ivf.rsmodified+1 -0
@@ -49,6 +49,7 @@ pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec<IvfFrame>) {
49 }49 }
50 50
51 /// Root of the workspace checkout this test runs in (crates/ec-vp9/../..).51 /// Root of the workspace checkout this test runs in (crates/ec-vp9/../..).
52+#[allow(dead_code)] // shared by every test binary that does `mod ivf`
52 pub fn fixture_dir() -> Option<std::path::PathBuf> {53 pub fn fixture_dir() -> Option<std::path::PathBuf> {
53 let bitstreams = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))54 let bitstreams = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
54 .join("../../fixtures/bitstreams");55 .join("../../fixtures/bitstreams");
crates/ec-vp9/tests/scratch_interdump.rsadded+70 -0
@@ -0,0 +1,70 @@
1+//! [scratch] Inter-frame syntax dump + count gate.
2+//!
3+//! Parses every frame of `INTER_IVF` (default `/tmp/inter1.ivf`, the clean
4+//! single-tile stream the pinned counts refer to). Keyframes decode as usual;
5+//! inter frames are parsed syntax-only (no reconstruction). With
6+//! `EC_VP9_INTERDUMP=1` every block prints one `MODE` line in the oracle's
7+//! shape, for a by-index diff. Point it at the two-tile-column stream
8+//! (`INTER_IVF=/tmp/inter.ivf INTER_EXPECT=none`) to exercise the failing-
9+//! keyframe path: that stream's keyframe desyncs its tile reader and the test
10+//! is expected to fail there.
11+//!
12+//! This is a real gate, not a printer:
13+//! - any frame error fails the test (keyframe failures are propagated too,
14+//! because a half-updated frame context would make later dumps meaningless);
15+//! - every inter frame's mode-info block count must equal `INTER_EXPECT`
16+//! (default `1213,1851` - the pinned counts of the single-tile fixture
17+//! `/tmp/inter1.ivf`, sha256 376532734662ba5faba4c4e97a5aac915ce429c11701bcf6
18+//! 6439b61a77388fa8; set `INTER_EXPECT=none` for a different stream);
19+//! - the crate already asserts `overreads() == 0` per tile reader at the end of
20+//! each tile (decode.rs, "tile bool decoder desync"), which is what would fire
21+//! if the walk read past the tile's last bool.
22+//!
23+//! ```text
24+//! INTER_IVF=<file> EC_VP9_INTERDUMP=1 \
25+//! cargo test -p ec-vp9 --test scratch_interdump -- --nocapture
26+//! ```
27+mod ivf;
28+
29+use ec_vp9::decode::Decoder;
30+
31+#[test]
32+fn inter_syntax_dump() {
33+ let path = std::env::var("INTER_IVF").unwrap_or_else(|_| "/tmp/inter1.ivf".to_string());
34+ let expect_raw = std::env::var("INTER_EXPECT").unwrap_or_else(|_| "1213,1851".to_string());
35+ let expect: Vec<usize> = if expect_raw == "none" {
36+ Vec::new()
37+ } else {
38+ expect_raw
39+ .split(',')
40+ .map(|t| t.trim().parse().expect("INTER_EXPECT entries are block counts"))
41+ .collect()
42+ };
43+ let Ok(bytes) = std::fs::read(&path) else {
44+ println!("SKIP: fixture {path} not found - set INTER_IVF=<file> to run");
45+ return;
46+ };
47+ let (_fourcc, w, h, frames) = ivf::parse_ivf(&bytes);
48+ println!("IVF {w}x{h} frames={}", frames.len());
49+ let mut dec = Decoder::new();
50+ let mut counts = Vec::new();
51+ for (i, f) in frames.iter().enumerate() {
52+ match dec.decode_syntax(&f.data) {
53+ Ok(()) => {
54+ let n = dec.last_frame_blocks();
55+ println!("FRAME {i} parsed blocks={n}");
56+ if i > 0 {
57+ counts.push(n);
58+ }
59+ }
60+ Err(e) => panic!("FRAME {i} failed: {e:?}"),
61+ }
62+ }
63+ if !expect.is_empty() {
64+ assert_eq!(
65+ counts, expect,
66+ "inter-frame mode-info block counts differ from INTER_EXPECT"
67+ );
68+ println!("block-count gate passed for {counts:?}");
69+ }
70+}
lanes/vp9inter.report.mdadded+351 -0
@@ -0,0 +1,351 @@
1+# lane-vp9inter report — inter-frame SYNTAX, slice 1 (`ec-vp9`)
2+
3+Worktree `/home/user/Documents/Code/Rust/edith_codecs-inter` (detached `43c9c913`).
4+No commit, no push, no fmt. Reconstruction / motion compensation: **NOT implemented,
5+`inter_is_named_unsupported` still refuses by name.**
6+
7+## Status: SYNTAX LAYER BIT-EXACT on two inter frames (2026-09-17, slice 5) —
8+## frame 1 and frame 2 each match libvpx block-for-block on every comparable
9+## field (1213/1213 and 1851/1851), which required three fixes in the mode-info
10+## layer (below) on top of the earlier entropy-layer ones. Pixels are still
11+## refused: reconstruction/motion compensation remains out of scope.
12+
13+## History: THREE defects found, fixed and verified: the compressed header
14+## is bit-identical to libvpx (1200/1200 bools counting the reader marker and the
15+## tx-mode literals) and the tile walk now matches the oracle for its first 2628
16+## bools. Block (0,0) of frame 1 is equivalent to the oracle on every comparable
17+## field (row/col/bsize/tx/mode/skip/seg/ref0/ref1/mv/interp; `uv` is libvpx-stale
18+## by design). The walk still stops early: 1002 of 1213 blocks, desync after tile
19+## bool #2628 (cause 4 below, not yet diagnosed).
20+
21+## What is implemented (all in `crates/ec-vp9`)
22+
23+- `src/inter.rs` (new): `read_inter_frame_mode_info` — inter segment id (incl.
24+ temporal-update prediction), skip, `read_is_inter_block`, tx size with the
25+ `allow_select = !skip || !inter` rule, reference frames (single + compound
26+ paths, `single_ref_p1/p2`, `comp_ref_p`, `reference_mode_context` contexts
27+ transcribed from `vp9_pred_common.c`), inter mode, switchable interp filter,
28+ the sub-8x8 `bmi` path, `read_mv`/`read_mv_component` with the
29+ `use_hp = allow_hp && use_mv_hp(predictor)` gate, and the MV predictor
30+ (`dec_find_mv_refs`, `mv_ref_blocks`, `append_sub8x8_mvs_for_idx`,
31+ `lower_mv_precision`, `clamp_mv_ref`, `mode_2_counter`/`counter_to_context`).
32+ MVs are recorded both as the refreshed MV and as the raw codeword diff.
33+- `src/header.rs`: `FrameContext` gained the inter tables (`inter_mode`,
34+ `switchable_interp`, `intra_inter`, `comp_inter`, `single_ref`, `comp_ref`,
35+ `y_mode`, `uv_mode`, the MV prob components) with libvpx defaults, and
36+ `read_compressed_header` gained the inter branch in libvpx order:
37+ inter-mode probs, switchable-interp probs, `intra_inter`, `read_frame_reference_mode`
38+ (compound-allowed gate), reference-mode probs, y-mode probs, partition probs,
39+ `read_mv_probs` (joints → per-component sign/classes/class0/bits → class0_fp/fp
40+ → hp when `allow_high_precision_mv`). It now returns
41+ `CompressedHeader { tx_mode, reference_mode }`.
42+- `src/decode.rs`: `Decoder::decode_syntax` (keyframes decode through to pixels,
43+ inter frames are parsed with no picture), the inter tile walk (same tile
44+ geometry/BE size prefixes as the keyframe walk), the frame-context rules
45+ (`reset_frame_context` 2/3, `refresh_frame_context` save, `use_prev_frame_mvs`
46+ gate), the per-8x8 `MV_REF` field and segment map for the next frame, and a
47+ token-only block walk (`decode_inter_block_tokens`) that keeps the entropy
48+ stream aligned without any prediction or residual add.
49+- `src/tokens.rs`: `decode_coefs` gained the `is_inter` ref-axis selector
50+ (`coef_probs[tx][plane][ref]`), keyframe call sites pass `false`.
51+- `tests/scratch_interdump.rs` (new): parses every frame of `INTER_IVF` and, with
52+ `EC_VP9_INTERDUMP=1`, prints one oracle-shaped `MODE` line per block.
53+
54+Gates:
55+- `cargo test -p ec-vp9 --test keyframe_exact` → **4/4 PASS**
56+ (`keyframes_match_ffmpeg`, `lossless_64_matches_ffmpeg`,
57+ `profile1_444_is_named_unsupported`, `inter_is_named_unsupported`).
58+- `cargo check -p ec-vp9` → **exactly the 5 baseline warnings**
59+ (`TM_PRED`, `read_partition`, `partition_probs`, `x_mis`, `y_mis`).
60+- `cargo test -p ec-vp9` → **green end to end** (14 test binaries, 0 failures).
61+- `cargo test -p ec-vp9 --test scratch_interdump` → **a real gate**: any frame
62+ error fails it (keyframe errors now propagate) and every inter frame's
63+ mode-info block count must equal `INTER_EXPECT` (default `1213,1851`, the
64+ pinned counts of the fixture; `INTER_EXPECT=none` disables).
65+ `INTER_IVF` defaults to `/tmp/inter1.ivf` (the clean single-tile stream the
66+ counts refer to); when that file is absent the test **skips loudly**
67+ (`SKIP: fixture ... not found`, the `scratch_synth` convention) so a machine
68+ without /tmp fixtures stays green. Current output: `FRAME 1 parsed blocks=1213`,
69+ `FRAME 2 parsed blocks=1851`, `block-count gate passed for [1213, 1851]`.
70+ The failing-keyframe path stays reachable by pointing it at the two-tile-column
71+ stream: `INTER_IVF=/tmp/inter.ivf INTER_EXPECT=none cargo test -p ec-vp9
72+ --test scratch_interdump` → expected failure at `FRAME 0 failed: Corrupt {
73+ context: "vp9: tile bool decoder desync" }` (instrumentation for the
74+ multi-tile keyframe defect).
75+- Overread gate: the crate already asserts `overreads() == 0` per tile reader at
76+ the end of each tile (`decode.rs:416` keyframe walk, `decode.rs:809` inter
77+ walk, message "tile bool decoder desync"), which fires if a walk reads past a
78+ tile's last bool - that is exactly the error `/tmp/inter.ivf` (2 tile columns)
79+ now reports for its keyframe. An earlier statement in this report that the
80+ crate's only overread assertion was the `bool.rs` unit test was wrong.
81+- Knob-free silence: with no `EC_VP9_*` set, the same harness run emits **0**
82+ trace lines (grep over the twelve trace prefixes) and still passes the gate.
83+
84+## Landing fixes (post-verdict)
85+
86+1. **`clamp_mv_ref` had row and column swapped** (blocking-queue item 1). The
87+ four edges were computed correctly but applied to the wrong components:
88+ `mv.0` is the ROW (filled from the vertical joint component in `read_mv`)
89+ and was clamped with the left/right edges. libvpx's
90+ `clamp_mv(mv, min_col, max_col, min_row, max_row)` (`vp9_mv.h:47`) takes the
91+ COLUMN bounds first, and `clamp_mv_ref` passes
92+ `(mb_to_left_edge - MV_BORDER, mb_to_right_edge + MV_BORDER,
93+ mb_to_top_edge - MV_BORDER, mb_to_bottom_edge + MV_BORDER)`
94+ (`vp9_mvref_common.h:215`). Fixed by clamping `mv.1` with left/right and
95+ `mv.0` with top/bottom. Latent on this fixture (max |mv| 334) - the two
96+ frames still match 100% afterwards - but on edge-heavy content the wrong
97+ bound would move a predictor, flip `use_mv_hp` and desync the stream.
98+2. **`decode_syntax` no longer swallows keyframe failures.** It propagated the
99+ error only as a `KFAIL` print under `EC_VP9_INTERDUMP`, so a stream whose
100+ keyframe died mid-walk returned success with a half-updated frame context,
101+ prev-frame MV field and reference slots - and every later inter-frame dump was
102+ meaningless evidence. Now the error propagates (`decode_key_frame(..)?`), so
103+ `/tmp/inter.ivf` fails fast with
104+ `FRAME 0 failed: Corrupt { context: "vp9: tile bool decoder desync" }`.
105+3. **The harness is a gate, not a printer** (see the Gates list). Its block
106+ counts come from `Decoder::last_frame_blocks()`, captured in
107+ `decode_inter_syntax_frame` right before the walk state is consumed.
108+4. **All `EC_VP9_*` dumps now go through cached `OnceLock`/atomic gates**
109+ (`lib.rs`: `cached_gate!` for `EC_VP9_INTERDUMP`, `EC_VP9_MVDGB`,
110+ `EC_VP9_MVDGB2`, `EC_VP9_MVDUMP`), so the per-block, per-MV-component and
111+ per-switchable-interp checks are a relaxed atomic load instead of a
112+ `std::env::var_os` (stdlib ENV lock) on the decode path.
113+
114+## Streams
115+
116+- `/tmp/inter.ivf` — a real 1920x1080 clip, `-frames:v 3 -c:v libvpx-vp9 -crf 32`:
117+ keyframe + 2 inter frames, **2 tile columns**, `allow_hp=1`, `interp=SWITCHABLE`,
118+ `tx_mode=SELECT`, frame-level `reference_mode=SINGLE`, `reset_frame_context=1`,
119+ `refresh_frame_context=0` for all three frames (so frames 1/2 start from the
120+ default frame context — verified against the oracle's `CHSUM`).
121+- `/tmp/inter1.ivf` — **the stream every match count in this report refers to**
122+ (the single-tile control, and the one driving the frame-1/2 MODE diffs, the
123+ bool traces and the candidate probes). Generated with
124+ `ffmpeg -v error -y -i <a real 1920x1080 clip> -frames:v 3 -c:v libvpx-vp9
125+ -crf 32 -pix_fmt yuv420p -tile-columns 0 -f ivf /tmp/inter1.ivf`;
126+ the exact file used here is `sha256
127+ 376532734662ba5faba4c4e97a5aac915ce429c11701bcf66439b61a77388fa8`, 161579 bytes,
128+ VP9 1920x1080, 3 frames (keyframe + 2 inter), which is what the counts are tied
129+ to - a different clip or encoder setting gives different block counts, so a
130+ third party reproducing the numbers should use this file (or regenerate from
131+ the same source) and check the hash.
132+ Consumers:
133+ `BTRACE=1 MODEDUMP=1 MVDUMP=1 /tmp/vp9loss/drv /tmp/inter1.ivf` (oracle) and
134+ `CARGO_TARGET_DIR=$HOME/.cache/cargo-target-inter INTER_IVF=/tmp/inter1.ivf
135+ EC_VP9_INTERDUMP=1 EC_VP9_TRACE=1 cargo test -p ec-vp9 --test scratch_interdump
136+ -- --nocapture` (ours).
137+
138+## Match counts (oracle `MODE` vs our `MODE`, by index, fields
139+## row/col/bsize/tx/mode/skip/seg/ref0/ref1/mvrow/mvcol/interp)
140+
141+| stage | frame 1 ours/oracle | first divergence |
142+|---|---|---|---|
143+| before any fix (single tile) | 551 / 1213 (desync) | block #0, `bsize` (ours 10 vs 12) |
144+| after cause 1 (`update_mv_probs`) | 794 / 1213 (desync) | block #0, `bsize` |
145+| 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) |
146+| frame 2 | never reached (frame 1 aborts) | – |
147+
148+First divergent decision, single-tile stream, block #0 == (0,0) 64x64:
149+
150+```
151+ours = row 0 col 0 bsize 11 (64x32) tx 3 mode 10 (NEARESTMV) skip 0 ref0 2 mv (0,0)
152+oracle = row 0 col 0 bsize 12 (64x64) tx 3 mode 13 (NEWMV) skip 1 ref0 1 mv (3,0)
153+```
154+
155+## Bool index of the divergence (the decisive evidence)
156+
157+Instrumentation used: oracle `MODEDUMP` now also prints `ref0/ref1/mvrow/mvcol/if`,
158+`MVRAW` prints each `read_mv` diff, and `CHSUM` prints
159+`frame tx_mode ref_mode allow_hp interp fcx refresh_ctx reset_ctx`; our side prints
160+`CHSTART frame=N` and `TILE <len> bytes frame=N` markers so `EC_VP9_TRACE` bools can
161+be attributed to a frame and a section.
162+
163+- **Compressed header, frame 1 (RESOLVED):** before the fixes our reads diverged at
164+ bool **#1116**: `ours (prob,bit)=(252,0)` vs `oracle (128,0)`, totals **1184 vs 1200**.
165+ Section tables (markers `SECT <name>` on ours, `CHSEC <name>` in the oracle,
166+ bool index counted between markers; ours' window is 4 bools ahead of the oracle's
167+ because the oracle's starts at its first marker):
168+ `txmode 0/22 | txprobs 22/856 | coef 878/18 | skip 896/32 | inter_mode 896/32 |
169+ switchable 928/24 | intra_inter 952/4 | ref_mode_bits 956/0 | ref_mode_probs 956/15 |
170+ y_mode 971/36 | partition 1007/99 | mv_probs 1106/74(ours) vs 1106/90(oracle)`.
171+ Every section entry and count matched except the last: the divergence is inside
172+ `read_mv_probs` (span 74 vs 90). After the two fixes below the CH is
173+ **bit-identical: 1196 == 1196 bools, no divergence**.
174+- **First tile symbol, frame 1:** after the tile reader's marker bit (both sides
175+ `(128,0)`), the partition read differs: ours `(191,1)` → PARTITION_HORZ,
176+ oracle `(239,0)` → PARTITION_NONE. Different *prob and* different bit ⇒ the
177+ frame probability state is already wrong at the tile start, which is exactly
178+ what the CH divergence predicts. Our walk then stays self-consistent for 551
179+ blocks and finally over-reads the 1717-byte tile ("tile bool decoder desync").
180+
181+So the first wrong decision is `compressed_header`, bool #1116 — the mode-info,
182+MV and token layers below it are unaudited until that is fixed.
183+
184+## Named causes (evidence, not speculation)
185+
186+1. **FIXED — `update_mv_probs` is NOT `vp9_diff_update_prob`** (`vp9_decodeframe.c:136`):
187+ `if (vpx_read(r, MV_UPDATE_PROB)) p[i] = (vpx_read_literal(r, 7) << 1) | 1;`
188+ — a 252-prob flag, then seven literal bits, and the new prob is `(literal << 1) | 1`;
189+ no `decode_term_subexp`, no `inv_remap_prob`. Our mv probs used `diff_update_prob`
190+ for all 69 entries, hence the 16-bool deficit and the (252,0)-vs-(128,0) divergence.
191+ Fix: `fn update_mv_probs(r, &mut [u8])` + all mv loops switched. Evidence of the
192+ fix: the oracle's mv span 90 == ours 90, CH totals equal, PUPD-equivalent traces equal.
193+
194+2. **FIXED — keyframe partition probs leaked into the stored frame context.**
195+ libvpx's keyframe partition table is the CONST `vp9_kf_partition_probs`, selected
196+ by `get_partition_probs()` for intra-only frames — it is NOT a `FRAME_CONTEXT`
197+ field. Our `FrameContext::new(true)` baked it into the context and we stored that
198+ context in `frame_ctxs` at every keyframe, so frame 1 started with the keyframe
199+ table (`ours ctx0=[158,97,94]` vs `oracle [199,122,141]`; 44/48 entries wrong —
200+ same bits read, different values, which is why the section tables looked clean).
201+ Fix: stored contexts are always `FrameContext::new(false)`; the active keyframe
202+ copy keeps `new(true)`; `FrameContext::reset_inter_partition()` runs before a
203+ keyframe context save. Evidence: `PPFLAT_PRE` on both sides now equal, and the
204+ 48-entry `PUPD j i before after` traces are IDENTICAL.
205+
206+3. **FIXED — `SWITCHABLE_INTERP_TREE` was built from the SPEC's naming order, not
207+ libvpx's.** `vp9/common/vp9_filter.h:23-28` are `#define`s, not an enum:
208+ `EIGHTTAP 0`, `EIGHTTAP_SMOOTH 1`, `EIGHTTAP_SHARP 2` (the spec's `literal_to_filter`
209+ names the *same coded values* in a different order). The tree
210+ `{ -EIGHTTAP, 2, -EIGHTTAP_SMOOTH, -EIGHTTAP_SHARP }` is therefore
211+ `{0, 2, -1, -2}`, not `{-1, 2, 0, -2}`; with the wrong table our interp leaf came
212+ out 0 where libvpx gives 1, which poisoned the *next* block's
213+ `get_pred_context_switchable_interp` (left neighbour's filter is the context).
214+ Evidence after the fix: both sides print `SWI ctx=3 p0=87 p1=252` / `SWItype 1`
215+ for block (0,0) and `SWI ctx=1 p0=19 p1=255` / `SWItype 1` for (0,8); block (0,0)
216+ now matches the oracle on `interp` too.
217+ **Reader-counter evidence** (oracle `g_bool_count` reset at the compressed header,
218+ printed as `bools=` in its `SWI`/`SWItype` lines; ours = CH total + tile bool index
219+ at the same print, both counting the tile reader marker and the tx-mode literals):
220+ `ours 1208 / 1210 / 1221 / 1223 / 1229 / 1231` vs
221+ `oracle 1208 / 1210 / 1225 / 1227 / 1233 / 1235` — the first two agree exactly, so
222+ the two walks are bool-aligned through block (0,0)'s interp read; the later pairs
223+ differ because the walks diverge at #2628 (below).
224+
225+4. **FIXED — the tile desync was a transposed `mv_ref_blocks` lookup (POSITION is
226+ `{ row, col }`, our accessors added `p.0` to the column), plus two smaller
227+ defects found in its wake.** All three are in `crates/ec-vp9/src/inter.rs`.
228+
229+ - **The transposition (the root cause).** `vp9_mvref_common.h`'s
230+ `mv_ref_blocks` is a table of `POSITION struct { int row, col }`, so the
231+ 64x64 row is `{ -1, 3 }, { 3, -1 }, { -1, 4 }, { 4, -1 }, ...` meaning
232+ `(row - 1, col + 3)` first. Our accessors (`is_inside`, `find_mv_refs`'s
233+ cell closure, `get_mode_context`, `get_sub_block_mv`'s `search_col`) added
234+ `p.0` to the **column** and `p.1` to the **row**, so every asymmetric entry
235+ picked a different neighbour. Evidence: for the block at `r=8 c=32`
236+ bsize 12 mode 10 the first candidate came from `p=(-1,3)` mapped to
237+ `(11,31)` (the 64x64 at `(8,24)`, MV `(3,0)`) where libvpx's `(7,35)` (the
238+ 64x64 at `(0,32)`) holds `(-1,0)` - the MV the oracle used. Fixed by
239+ swapping the two components at every accessor (array text kept verbatim).
240+ - **`clamp_mv_ref`'s unsigned underflow.** `mi_rows - bh - row` is negative
241+ for a tall block on the frame's partial last row (1080p: `135 - 8 - 128`),
242+ and libvpx computes it in `int`; ours subtracted in `usize` and panicked
243+ ("attempt to subtract with overflow", inter.rs:497) - which is why the walk
244+ stopped after 1183 of 1213 blocks. Fixed by computing `mb_to_*` in `i32`
245+ (libvpx's formulas: `-(row*64)`, `(mi_rows - bh - row)*64`).
246+ - **The candidate count semantics.** First attempt returned the *real* count
247+ and broke every NEARMV block (frame 1 fell from 100% on the prefix to a
248+ first divergence at block #15, `mode=11`, ours `(1,2)` vs oracle `(0,0)`).
249+ `dec_find_mv_refs`' tail (vp9_decodemv.c:626) is subtler: an early exit
250+ (`goto Done`, i.e. `ADD_MV_REF_LIST_EB` filling the second slot or
251+ `early_break` stopping at the first) **jumps over** the mode-derived
252+ override and returns the count as accumulated; falling out of the loops
253+ applies `count = (mode == NEARMV) ? 2 : 1`, so a NEARMV block whose search
254+ found only one candidate still reports two and the caller reads the zeroed
255+ second slot `(0, 0)`. Reproduced exactly (`if done { count } else if mode ==
256+ NEARMV { 2 } else { 1 }`, clamp that many).
257+
258+ **Result (frame-1/2 by-index MODE diff, oracle vs ours):**
259+ - frame 1: ours 1213, oracle 1213, **identity 1213/1213 (100.0%)**
260+ - frame 2: ours 1851, oracle 1851, **identity 1851/1851 (100.0%)**
261+ compared fields: row/col/bsize/tx/mode/skip/seg/ref0/ref1/interp and the MV -
262+ with `uv` dropped for inter blocks and `mvrow/mvcol` dropped for intra blocks
263+ inside inter frames (both are libvpx-stale, see the non-comparison list below).
264+ Frame 2 exercises `use_prev_frame_mvs` (the from-previous-frame MV_REF field)
265+ and also matches byte-for-byte, so the prev-frame MV_REF store is correct.
266+
267+ **Defect (b) - frame 2's compressed header - is refuted.** Its earlier
268+ "pristine defaults" `MVPROB` reading was an artifact of the run that aborted
269+ in frame 1; with the walk fixed, frame 2 reproduces 1851/1851 blocks
270+ bit-exactly, which requires frame 2's CH MV tables to be correct. (Our
271+ `MVPROB` dump still prints 4 times per stream where the oracle prints 2, so
272+ the line-by-line pairing is ambiguous - a harness artifact, not a decode
273+ difference; frame 1's dump is identical to the oracle's apart from the
274+ never-updated 11th `classes` slot.)
275+
276+ **stale-field non-comparisons (extend the list):** `uv_mode` is stale for
277+ *inter* blocks; `mi->mv[]` is stale for *intra* blocks inside an inter frame
278+ (libvpx never writes it from `read_intra_frame_mode_info`), so a MODE diff
279+ must drop `mvrow/mvcol` whenever `ref0 == INTRA_FRAME`. Dropping them is what
280+ took frame 2 from 97.8% to 100%.
281+
282+Superseded earlier hypothesis (kept for the record): "a section count/order difference
283+in the 1116..1200 span" — correct span, wrong mechanism: the counts differed because
284+the mv-prob payloads are 7-bit literals, not term-subexp payloads.
285+
286+## Cause-3 lesson worth carrying forward
287+Every VP9 tree constant must be rebuilt from libvpx's **macro expressions**, not from
288+the spec's (or one's memory of the) naming order: `vp9_filter.h` uses `#define EIGHTTAP 0`
289+while the spec's `literal_to_filter` lists EIGHTTAP_SMOOTH first. Trees whose leaves are
290+plain integers (partition, mv class/fp, segment) were safe; trees whose leaves are *named
291+constants* (switchable interp, inter mode via `INTER_OFFSET`) must be evaluated in libvpx's
292+own numbering. Our inter-mode tree was right only because `INTER_OFFSET` is a subtraction.
293+
294+## Earlier ranked causes (now resolved or refuted)
295+
296+1. **A compressed-header section count/order difference in the 1116..1200 span.**
297+ The span is ~200 bools, which matches the *inter* half of the header
298+ (inter-mode 21 + switchable 8 + intra/inter 4 + ref-mode 1-2 + single_ref 10 +
299+ y_mode 36 + partition 48 + MV 69 = 197-198 flags before inner literal reads),
300+ so the prime suspect is one of those sections, not the coef/skip part. The
301+ missing-16-bools net says at least one section is read with the wrong count.
302+ Note `CHSUM` (tx_mode=4, ref_mode=0, allow_hp=1, interp=4) already matches the
303+ oracle exactly, so the header's *front* and the uncompressed header size
304+ (`uhs`) are right, and the tile offset itself is not suspect.
305+ Fastest discriminator (next slice, ~20 min): print one marker per CH section
306+ (`inter_mode`, `switchable`, `intra_inter`, `ref_mode_probs`, `y_mode`,
307+ `partition`, `mv_probs`) and diff the markers' bool indices against the
308+ oracle's `BOR` positions; the first section whose start index is off is the bug.
309+2. **Not the tables.** The default partition probs were diffed entry-by-entry
310+ against `vp9/common/vp9_entropymode.c::default_partition_probs` (48 values,
311+ 0 mismatches), and the inter defaults were extracted mechanically; so a
312+ *rejected* cause unless the marker diff says otherwise.
313+3. **Pre-existing keyframe limitation on multi-tile-column streams (found here).**
314+ Frame 0 of `/tmp/inter.ivf` (2 tile columns) dies in the *keyframe* path with
315+ "tile bool decoder desync" while the single-tile control (`/tmp/inter1.ivf`)
316+ decodes the same keyframe fine: the kf entropy walk is not multi-tile-safe on
317+ this encode, even though the earlier lane's all-intra sweep was. This is
318+ independent of the inter work (the inter walk needs no keyframe pixels) but it
319+ is a real defect to file, and it means frame 0 in `decode_syntax` must be
320+ tolerated (`KFAIL` line) rather than fatal.
321+4. Unverified by this slice: the MV predictor's `scale_mv` sign-flip variant and
322+ the sub-8x8 `bmi` path (never reached, since block #0 already diverges), the
323+ compound-reference path (this stream is `SINGLE_REFERENCE` throughout), and
324+ the `prev_frame_mvs` path of frame 2.
325+
326+## Exact next slice
327+
328+1. CH section markers → first section with a wrong bool index → fix the count/order
329+ in `header.rs`; re-run the by-index `MODE` diff until frames 1 and 2 walk to the
330+ tile's last bool with `overreads() == 0`.
331+2. Then re-diff `MODE` fields (skip/tx/ref0/ref1/inter_mode/mv) plus the oracle's
332+ `MVRAW` (raw diffs) to audit the MV reader/predictor — the predictor decides the
333+ high-precision bit, so it is parse-load-bearing.
334+3. Then file/fix the keyframe multi-tile-column desync (ranked cause 3) — it is the
335+ same class as the tile-walk bug fixed in the keyframe lane and is now the only
336+ thing blocking `/tmp/inter.ivf` frame 0.
337+4. Only after the syntax layer is exact: reconstruction/motion compensation
338+ (out of scope today), which is also what makes the pixels — no pixel-level
339+ inter result is claimed anywhere in this lane.
340+
341+## Repro commands
342+
343+```
344+# oracle dump (ref0/ref1/mv/interp + MVRAW + CHSUM)
345+MODEDUMP=1 MVDUMP=1 /tmp/vp9loss/drv /tmp/inter1.ivf 2>&1 | grep -E '^MODE|^CHSUM'
346+# ours
347+CARGO_TARGET_DIR=$HOME/.cache/cargo-target-inter INTER_IVF=/tmp/inter1.ivf \
348+ EC_VP9_INTERDUMP=1 cargo test -p ec-vp9 --test scratch_interdump -- --nocapture
349+# bool-level CH diff: EC_VP9_TRACE=1 on ours vs BTRACE=1 on the oracle,
350+# split ours on CHSTART/TILE markers and the oracle on the CHSUM/MODE markers
351+```