forge
Explore
Log in

Don't you dare go Hollow

Merge lane-vp9-refsetup: intra-only frames + scaled references onto the u16 planes

Browse files at this commit

c67d95ad32fef0f10f35f3cdf423d6efd53f0031Ahmet Kaan GümüşParent: 205e917e6a3f0c
The lane was cut from 79984549 and wrote its scaling against the u8 kernels;
main had since absorbed lane-vp9-hbd, which converted every ec-vp9 plane to
u16 (`ec_vp9::Sample`) and threaded `bd` through every kernel. Not a
mechanical merge — resolved by porting the lane's semantics onto the u16
substrate.

- mc.rs (conflicts at the convolve signatures / inter_predictor / the
  predictor entry): main's u16 kernels + `bd` win as the substrate; the lane's
  `ScaleFactors`, step-aware `convolve_horiz`/`convolve_vert` (x_step/y_step
  alongside bd, both defaults `SUBPEL_SHIFTS`), the scaled dispatch in
  `inter_predictor`, the extracted `convolve_2d` and the scaled block/MV
  mapping in `build_inter_predictors` are ported onto it. The scale arithmetic
  is depth-independent and kept verbatim.
- decode.rs (conflict was the capability doc only): combined doc; the lane's
  `decode_intra_only_frame`, `frame_is_intra_only` dispatch, `ScaleFactors`
  setup + `valid_ref_frame_size` refusal, and the removed size-change refusal
  kept as written.
- The lane's tests compared u16 planes against ffmpeg's u8 rawvideo; they now
  go through `as u8` like the rest of the crate.

Verified on the merged tree: full `cargo test -p ec-vp9` green (0 failed,
0 ignored), warning parity = the 5 pre-existing, and the 10-stream corpus
re-swept from this build byte-identical vs libvpx 1.15.0 (8-bit, 10-bit,
odd, scaled-reference, intra-only).
crates/ec-vp9/src/decode.rsmodified+116 -32
@@ -4,19 +4,21 @@
44 //! reconstruction and the loop filter (spec 6, 7, 8; libvpx
55 //! `vp9_decodeframe.c`).
66 //!
7-//! Capability: profile-0 8-bit and profile-2 10-bit 4:2:0 keyframes and inter
8-//! frames (motion compensation, residual reconstruction, the loop filter and
9-//! an 8-slot reference DPB). Intra-only frames, profiles 1/3, 12-bit, other
10-//! subsamplings and a reference whose coded size differs from the current
11-//! frame are refused by name; `show_existing_frame` returns the buffered
12-//! reference picture instead of pretending to decode. Odd coded extents are
13-//! supported: chroma stores and crops at `(w + 1) / 2` (`uv_crop_width`),
14-//! matching libvpx.
7+//! Capability: profile-0 8-bit and profile-2 10-bit 4:2:0 keyframes,
8+//! intra-only frames and inter frames (motion compensation, residual
9+//! reconstruction, the loop filter and an 8-slot reference DPB). A reference
10+//! whose coded size differs from the current frame is scaled during
11+//! prediction; profiles 1/3, 12-bit and other subsamplings are refused by
12+//! name; `show_existing_frame` returns the buffered reference picture instead
13+//! of pretending to decode. Odd coded extents are supported: chroma stores
14+//! and crops at `(w + 1) / 2` (`uv_crop_width`), matching libvpx.
1515
1616 use crate::header::{FrameContext, read_compressed_header};
1717 use crate::intra::build_intra_predictors;
1818 use crate::loopfilter::LfGrids;
19-use crate::mc::{RefPlane, average_split_mvs_chroma, build_inter_predictors, split_mv};
19+use crate::mc::{
20+ RefPlane, ScaleFactors, average_split_mvs_chroma, build_inter_predictors, split_mv,
21+};
2022 use crate::modes::{MiInfo, MiState, read_intra_frame_mode_info};
2123 use crate::tables::*;
2224 use crate::tokens::{PlaneContexts, decode_coefs, scan_for};
@@ -261,10 +263,7 @@ impl Decoder {
261263 return self.decode_key_frame(&hdr, frame);
262264 }
263265 if hdr.intra_only {
264- return Err(Error::unsupported(
265- "vp9 intra-only",
266- "this lane decodes inter frames and keyframes only",
267- ));
266+ return self.decode_intra_only_frame(&hdr, frame);
268267 }
269268 self.decode_inter_frame(&hdr, frame, index, true)
270269 }
@@ -325,6 +324,76 @@ impl Decoder {
325324 Ok(if hdr.show_frame { Some(pic) } else { None })
326325 }
327326
327+ /// Decode an intra-only frame through to pixels. `libvpx
328+ /// vp9_decodeframe.c:2708-2745` makes it an INTER frame that never shows
329+ /// and refreshes only the slots its `refresh_frame_flags` names, but its
330+ /// body is a keyframe's: intra-only mode info, intra prediction, the intra
331+ /// coefficient axis and the intra loop-filter levels. Two header decisions
332+ /// differ from a keyframe (`vp9_setup_past_independence`,
333+ /// `vp9/common/vp9_entropymode.c:424`):
334+ ///
335+ /// - the ACTIVE frame context comes from storage
336+ /// (`*cm->fc = cm->frame_contexts[frame_context_idx]`,
337+ /// `vp9_decodeframe.c:3008`) — reset to the defaults only for
338+ /// `reset_frame_context` 2 (selected) or 3 (all), or under
339+ /// error-resilient mode, never unconditionally like a keyframe (whose
340+ /// `cm->frame_type == KEY_FRAME` clause resets every stored context);
341+ /// - partitions read the const `vp9_kf_partition_probs`
342+ /// (`set_partition_probs`), so the stored context's own `partition`
343+ /// field survives the frame untouched.
344+ fn decode_intra_only_frame(
345+ &mut self,
346+ hdr: &FrameHeader,
347+ frame: &[u8],
348+ ) -> Result<Option<Picture>> {
349+ let hdr = hdr.clone();
350+ if hdr.error_resilient_mode || hdr.reset_frame_context == 3 {
351+ let d = FrameContext::new(false);
352+ self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d];
353+ } else if hdr.reset_frame_context == 2 {
354+ self.frame_ctxs[0] = FrameContext::new(false);
355+ }
356+ // The parser forces frame_context_idx to 0 for an intra frame.
357+ let mut ctx = self.frame_ctxs[0].clone();
358+ let stored_partition = ctx.partition;
359+ ctx.use_key_partition();
360+ self.ctx = ctx;
361+ self.prev_seg.clear();
362+ self.prev_mvs.clear();
363+ self.last = LastFrameFacts {
364+ width: hdr.width,
365+ height: hdr.height,
366+ intra_only: true,
367+ show_frame: hdr.show_frame,
368+ key: false,
369+ };
370+ let hdr_start = hdr.uncompressed_header_size as usize;
371+ let ch = read_compressed_header(
372+ &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize],
373+ &mut self.ctx,
374+ &hdr,
375+ )?;
376+ let pic = self.decode_keyframe(&hdr, frame, ch.tx_mode)?;
377+ if hdr.refresh_frame_context {
378+ // Store back with the partition probs the context arrived with:
379+ // the const key table is not a `FRAME_CONTEXT` field.
380+ self.ctx.partition = stored_partition;
381+ self.frame_ctxs[0] = self.ctx.clone();
382+ }
383+ // Reference refresh (spec 8.10): only `refresh_frame_flags` slots.
384+ let frame = RefFrame {
385+ planes: std::sync::Arc::new(self.planes.take().expect("frame scratch")),
386+ width: hdr.width as u16,
387+ height: hdr.height as u16,
388+ };
389+ for slot in 0..8 {
390+ if hdr.refresh_frame_flags & (1 << slot) != 0 {
391+ self.refs[slot] = Some(frame.clone());
392+ }
393+ }
394+ Ok(if hdr.show_frame { Some(pic) } else { None })
395+ }
396+
328397 /// Parse one frame's syntax: keyframes decode through to pixels, inter
329398 /// frames are parsed (headers, mode info, MVs) with no reconstruction and
330399 /// no picture. `decode` still refuses inter frames.
@@ -354,10 +423,9 @@ impl Decoder {
354423 // any inter-frame dump after it would be meaningless evidence.
355424 self.decode_key_frame(&hdr, sub)?;
356425 } else if hdr.intra_only {
357- return Err(Error::unsupported(
358- "vp9 intra-only",
359- "the inter-syntax lane covers inter frames only",
360- ));
426+ // Same body as a keyframe, but an inter frame that refreshes
427+ // only the slots it names.
428+ self.decode_intra_only_frame(&hdr, sub)?;
361429 } else {
362430 self.decode_inter_frame(&hdr, sub, index, false)?;
363431 }
@@ -392,28 +460,19 @@ impl Decoder {
392460
393461 // Reference slots (spec 7.2): `ref_frame_idx[i]` names the slot LAST,
394462 // GOLDEN and ALTREF use. libvpx validates every named reference's
395- // format here (`vp9_decodeframe.c:1620-1627`) and SCALES a reference
396- // whose size differs; this lane refuses that by name.
463+ // format here (`vp9_decodeframe.c:1620-1627`); a reference whose coded
464+ // size differs from this frame's is SCALED during prediction
465+ // (`vp9_setup_scale_factors_for_frame` per reference), not refused.
397466 if pixels {
398467 for (i, name) in ["last", "golden", "altref"].iter().enumerate() {
399468 let slot = hdr.ref_frame_idx[i] as usize;
400469 if slot >= self.refs.len() || hdr.ref_frame_idx[i] >= 8 {
401470 return Err(corrupt("vp9 inter names a reference slot past the DPB"));
402471 }
403- let Some(p) = self.refs[slot].as_ref() else {
472+ if self.refs[slot].is_none() {
404473 return Err(Error::corrupt(format!(
405474 "vp9 inter reference `{name}` names empty slot {slot}"
406475 )));
407- };
408- if p.width as u32 != hdr.width || p.height as u32 != hdr.height {
409- return Err(Error::unsupported(
410- "vp9 inter reference size change",
411- format!(
412- "reference `{name}` in slot {slot} is {}x{} but this frame is {}x{}; \
413- reference-frame scaling is not ported",
414- p.width, p.height, hdr.width, hdr.height
415- ),
416- ));
417476 }
418477 }
419478 let width = hdr.width as usize;
@@ -1407,7 +1466,10 @@ impl Decoder {
14071466 let x_mis = bw.min(mi.mi_cols - col);
14081467 let y_mis = bh.min(mi.mi_rows - row);
14091468
1410- let info = if hdr.frame_type == FrameType::Key {
1469+ // `frame_is_intra_only` (onyxc_int.h:363): a keyframe OR an
1470+ // intra-only frame walks the intra mode-info path.
1471+ let intra_frame = hdr.frame_type == FrameType::Key || hdr.intra_only;
1472+ let info = if intra_frame {
14111473 read_intra_frame_mode_info(
14121474 r,
14131475 mi,
@@ -1436,7 +1498,7 @@ impl Decoder {
14361498 tx_mode,
14371499 )?
14381500 };
1439- if hdr.frame_type != FrameType::Key {
1501+ if !intra_frame {
14401502 if pixels {
14411503 // Full inter decode: prediction, tokens, residual. The
14421504 // per-cell loop-filter level is the block's own reference and
@@ -2088,6 +2150,26 @@ fn inter_predict_plane(
20882150 return Err(corrupt("vp9 inter prediction read an empty reference slot"));
20892151 };
20902152 let (ref_data, ref_stride) = ref_frame.planes.plane_ref(plane);
2153+ // `vp9_setup_scale_factors_for_frame` (`vp9_decodeframe.c:2758`): the
2154+ // scale from the REFERENCE's coded luma size to this frame's, shared
2155+ // by every plane. `vp9_is_valid_scale` is enforced where libvpx
2156+ // enforces it — at prediction time, for the references actually used.
2157+ let sf = ScaleFactors::setup(
2158+ ref_frame.width as usize,
2159+ ref_frame.height as usize,
2160+ hdr.width as usize,
2161+ hdr.height as usize,
2162+ );
2163+ if !sf.is_valid() {
2164+ return Err(Error::unsupported(
2165+ "vp9 reference scale",
2166+ format!(
2167+ "reference `{ref_name}` in slot {slot} is {}x{} against a {}x{} frame; \
2168+ `valid_ref_frame_size` rejects that ratio",
2169+ ref_frame.width, ref_frame.height, hdr.width, hdr.height
2170+ ),
2171+ ));
2172+ }
20912173 let refp = RefPlane {
20922174 data: ref_data,
20932175 stride: ref_stride,
@@ -2137,6 +2219,7 @@ fn inter_predict_plane(
21372219 ss_y,
21382220 kernel,
21392221 rf == 1,
2222+ &sf,
21402223 scratch,
21412224 temp,
21422225 );
@@ -2164,6 +2247,7 @@ fn inter_predict_plane(
21642247 ss_y,
21652248 kernel,
21662249 rf == 1,
2250+ &sf,
21672251 scratch,
21682252 temp,
21692253 );
crates/ec-vp9/src/header.rsmodified+12 -0
@@ -124,6 +124,18 @@ impl FrameContext {
124124 pub(crate) fn reset_inter_partition(&mut self) {
125125 self.partition = rows(&DEFAULT_PARTITION_PROBS);
126126 }
127+
128+ /// `set_partition_probs` (`vp9/onyxc_int.h:367`): a key frame OR an
129+ /// intra-only frame reads partitions from the const
130+ /// `vp9_kf_partition_probs`, never from the stored `FRAME_CONTEXT`. An
131+ /// intra-only frame's context otherwise comes from storage, so its own
132+ /// `partition` field must be left alone (this only swaps the field on the
133+ /// active read copy).
134+ pub(crate) fn use_key_partition(&mut self) {
135+ for (i, row) in self.partition.iter_mut().enumerate() {
136+ row.copy_from_slice(&KF_PARTITION_PROBS[i * 3..i * 3 + 3]);
137+ }
138+ }
127139 }
128140
129141 /// `inv_recenter_nonneg` (vp9_dsubexp.c).
crates/ec-vp9/src/mc.rsmodified+226 -35
@@ -8,9 +8,11 @@
88 //! The VP9 decoder does NOT extend the reference frame's borders in place: it
99 //! builds a bordered copy of the block's reference window per prediction
1010 //! (`extend_and_predict`) whenever the window leaves the frame or the frame's
11-//! dimensions are not a multiple of 8. This module ports that path, unscaled
12-//! only — a reference slot whose size differs from the current frame is
13-//! refused by `decode` before any predictor runs.
11+//! dimensions are not a multiple of 8. A reference slot whose size differs
12+//! from the current frame is SCALED: [`ScaleFactors`] carries
13+//! `vp9_setup_scale_factors_for_frame`, the block/MV are mapped into the
14+//! reference with `vp9_scale_mv`, and the convolve steps by `x_step_q4` /
15+//! `y_step_q4` (`sf->predict`, `vpx_scaled_*`).
1416 //!
1517 //! Indexing note: libvpx's convolve helpers take a raw pointer and subtract
1618 //! `SUBPEL_TAPS / 2 - 1` from it, so they read taps *before* the block's first
@@ -28,6 +30,93 @@ const FILTER_BITS: i32 = 7;
2830 /// `VP9_INTERP_EXTEND` (`vpx_scale/yv12config.h:25`).
2931 const INTERP_EXTEND: i32 = 4;
3032
33+/// `REF_SCALE_SHIFT` / `REF_NO_SCALE` / `REF_INVALID_SCALE`
34+/// (`vp9/common/vp9_scale.h:21-23`): the fixed-point precision of a reference
35+/// frame's scale factor.
36+const REF_SCALE_SHIFT: i32 = 14;
37+const REF_NO_SCALE: i32 = 1 << REF_SCALE_SHIFT;
38+const REF_INVALID_SCALE: i32 = -1;
39+
40+/// `scaled_x` / `scaled_y` (`vp9_scale.c:22`).
41+fn scale_value(val: i32, scale_fp: i32) -> i32 {
42+ (((val as i64) * scale_fp as i64) >> REF_SCALE_SHIFT) as i32
43+}
44+
45+/// `struct scale_factors` (`vp9/common/vp9_scale.h:27`) set up by
46+/// `vp9_setup_scale_factors_for_frame` (`vp9_scale.c:44`): the scale from a
47+/// reference frame's coded size to this frame's, its derived 1/16-pel step
48+/// (`x_step_q4`/`y_step_q4`; 16 means "no scaling on that axis") and
49+/// `vp9_scale_mv`.
50+#[derive(Clone, Copy)]
51+pub(crate) struct ScaleFactors {
52+ x_scale_fp: i32,
53+ y_scale_fp: i32,
54+ x_step_q4: i32,
55+ y_step_q4: i32,
56+}
57+
58+impl ScaleFactors {
59+ /// `vp9_setup_scale_factors_for_frame(other_w, other_h, this_w, this_h)`:
60+ /// `other_*` is the REFERENCE's coded size, `this_*` the frame being
61+ /// decoded. An out-of-range ratio leaves `REF_INVALID_SCALE`, which
62+ /// libvpx turns into `Reference frame has invalid dimensions` when the
63+ /// reference is actually predicted from.
64+ pub(crate) fn setup(other_w: usize, other_h: usize, this_w: usize, this_h: usize) -> Self {
65+ // `valid_ref_frame_size` (`vp9_scale.h:61`): at most 2x down, 16x up.
66+ let valid = 2 * this_w >= other_w
67+ && 2 * this_h >= other_h
68+ && this_w <= 16 * other_w
69+ && this_h <= 16 * other_h;
70+ if !valid {
71+ return ScaleFactors {
72+ x_scale_fp: REF_INVALID_SCALE,
73+ y_scale_fp: REF_INVALID_SCALE,
74+ x_step_q4: 0,
75+ y_step_q4: 0,
76+ };
77+ }
78+ let x_scale_fp = (((other_w as i64) << REF_SCALE_SHIFT) / this_w as i64) as i32;
79+ let y_scale_fp = (((other_h as i64) << REF_SCALE_SHIFT) / this_h as i64) as i32;
80+ ScaleFactors {
81+ x_scale_fp,
82+ y_scale_fp,
83+ x_step_q4: scale_value(SUBPEL_SHIFTS, x_scale_fp),
84+ y_step_q4: scale_value(SUBPEL_SHIFTS, y_scale_fp),
85+ }
86+ }
87+
88+ /// `vp9_is_valid_scale`.
89+ pub(crate) fn is_valid(&self) -> bool {
90+ self.x_scale_fp != REF_INVALID_SCALE && self.y_scale_fp != REF_INVALID_SCALE
91+ }
92+
93+ /// `vp9_is_scaled`.
94+ pub(crate) fn is_scaled(&self) -> bool {
95+ self.is_valid() && (self.x_scale_fp != REF_NO_SCALE || self.y_scale_fp != REF_NO_SCALE)
96+ }
97+
98+ fn scale_x(&self, val: i32) -> i32 {
99+ scale_value(val, self.x_scale_fp)
100+ }
101+
102+ fn scale_y(&self, val: i32) -> i32 {
103+ scale_value(val, self.y_scale_fp)
104+ }
105+
106+ /// `vp9_scale_mv` (`vp9_scale.c:29`): the block MV scaled to the
107+ /// reference's resolution plus the sub-pixel offset of the block's own
108+ /// scaled position. Returns `(row, col)` in 1/16-pel units.
109+ ///
110+ /// `x`/`y` are the block's coordinates in the CURRENT frame (libvpx
111+ /// passes `mi_x + x`, `mi_y + y` — luma units even for chroma planes; the
112+ /// sub-8x8 chroma offsets are always 0, so the mismatch never bites).
113+ pub(crate) fn scale_mv(&self, mv: (i32, i32), x: i32, y: i32) -> (i32, i32) {
114+ let x_off_q4 = self.scale_x(x << SUBPEL_BITS) & SUBPEL_MASK;
115+ let y_off_q4 = self.scale_y(y << SUBPEL_BITS) & SUBPEL_MASK;
116+ (self.scale_y(mv.0) + y_off_q4, self.scale_x(mv.1) + x_off_q4)
117+ }
118+}
119+
31120 /// `vp9_filter_kernels` (`vp9/common/vp9_filter.c:79`), in libvpx's filter
32121 /// numbering: 0 `EIGHTTAP`, 1 `EIGHTTAP_SMOOTH`, 2 `EIGHTTAP_SHARP`,
33122 /// 3 `BILINEAR` (the 4-tap index 4 is unreachable for profile 0).
@@ -215,6 +304,9 @@ fn build_mc_border(
215304 /// `convolve_horiz` / `convolve_avg_horiz` (`vpx_dsp/vpx_convolve.c:22`).
216305 /// `origin` is the block's first sample in `buf`; taps are read from
217306 /// `origin + y*stride + (x_q4 >> SUBPEL_BITS) - (SUBPEL_TAPS / 2 - 1) + k`.
307+/// `x_step` advances `x_q4` per output sample — `SUBPEL_SHIFTS` for an
308+/// unscaled reference, `sf->x_step_q4` (the scaled sampler, also used by
309+/// `vpx_scaled_horiz`) otherwise.
218310 #[allow(clippy::too_many_arguments)]
219311 fn convolve_horiz(
220312 buf: &[Sample],
@@ -224,6 +316,7 @@ fn convolve_horiz(
224316 dst_stride: usize,
225317 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
226318 x0_q4: i32,
319+ x_step: i32,
227320 w: usize,
228321 rows: usize,
229322 avg: bool,
@@ -246,12 +339,15 @@ fn convolve_horiz(
246339 } else {
247340 v as Sample
248341 };
249- x_q4 += SUBPEL_SHIFTS;
342+ x_q4 += x_step;
250343 }
251344 }
252345 }
253346
254347 /// `convolve_vert` / `convolve_avg_vert` (`vpx_dsp/vpx_convolve.c:80`).
348+/// `y_step` advances `y_q4` per output sample (`SUBPEL_SHIFTS` unscaled,
349+/// `sf->y_step_q4` for `vpx_scaled_vert`).
350+#[allow(clippy::too_many_arguments)]
255351 fn convolve_vert(
256352 buf: &[Sample],
257353 stride: usize,
@@ -260,6 +356,7 @@ fn convolve_vert(
260356 dst_stride: usize,
261357 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
262358 y0_q4: i32,
359+ y_step: i32,
263360 w: usize,
264361 h: usize,
265362 avg: bool,
@@ -283,15 +380,18 @@ fn convolve_vert(
283380 } else {
284381 v as Sample
285382 };
286- y_q4 += SUBPEL_SHIFTS;
383+ y_q4 += y_step;
287384 }
288385 }
289386 }
290387
291388 /// `inter_predictor` + `sf->predict` (`vp9/common/vp9_reconinter.h:23`,
292-/// `vp9/common/vp9_scale.c:79`): for the unscaled case `predict[0][0]` is
293-/// copy/avg, `predict[0][1][*]` the vertical kernel, `predict[1][0][*]` the
294-/// horizontal one and `predict[1][1][*]` the 2D convolve.
389+/// `vp9/common/vp9_scale.c:79`): the kernel is picked by
390+/// `predict[subpel_x != 0][subpel_y != 0][avg]`. Unscaled that is
391+/// copy/avg, the vertical, the horizontal and the 2D convolve; with a scaled
392+/// reference the table collapses to the scaled variants (`vpx_scaled_horiz` /
393+/// `vpx_scaled_vert` — the same walk with `x_step_q4` / `y_step_q4` — and
394+/// `vpx_scaled_2d`), reproduced here by the step-aware convolve helpers.
295395 ///
296396 /// `w` x `h` output samples written at `dst`; `buf`/`origin` locate the
297397 /// block's first reference sample. `temp` is the `vpx_convolve8` intermediate
@@ -307,12 +407,38 @@ fn inter_predictor(
307407 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
308408 subpel_x: i32,
309409 subpel_y: i32,
410+ x_step: i32,
411+ y_step: i32,
310412 w: usize,
311413 h: usize,
312414 avg: bool,
313415 temp: &mut [Sample],
314416 bd: u8,
315417 ) {
418+ let scaled_x = x_step != SUBPEL_SHIFTS;
419+ let scaled_y = y_step != SUBPEL_SHIFTS;
420+ if scaled_x || scaled_y {
421+ // sf->predict with a scaled axis (vp9_scale.c:79-110): an unscaled
422+ // axis keeps its 1D kernel only when the other axis has no subpel
423+ // offset; anything else is the 2D scaled convolve.
424+ if !scaled_x && subpel_x == 0 {
425+ convolve_vert(
426+ buf, stride, origin, dst, dst_stride, f, subpel_y, y_step, w, h, avg, bd,
427+ );
428+ return;
429+ }
430+ if !scaled_y && subpel_y == 0 {
431+ convolve_horiz(
432+ buf, stride, origin, dst, dst_stride, f, subpel_x, x_step, w, h, avg, bd,
433+ );
434+ return;
435+ }
436+ convolve_2d(
437+ buf, stride, origin, dst, dst_stride, f, subpel_x, subpel_y, x_step, y_step, w, h, avg,
438+ temp, bd,
439+ );
440+ return;
441+ }
316442 if subpel_x == 0 && subpel_y == 0 {
317443 for y in 0..h {
318444 for x in 0..w {
@@ -329,23 +455,47 @@ fn inter_predictor(
329455 }
330456 if subpel_y == 0 {
331457 convolve_horiz(
332- buf, stride, origin, dst, dst_stride, f, subpel_x, w, h, avg, bd,
458+ buf, stride, origin, dst, dst_stride, f, subpel_x, SUBPEL_SHIFTS, w, h, avg, bd,
333459 );
334460 return;
335461 }
336462 if subpel_x == 0 {
337463 convolve_vert(
338- buf, stride, origin, dst, dst_stride, f, subpel_y, w, h, avg, bd,
464+ buf, stride, origin, dst, dst_stride, f, subpel_y, SUBPEL_SHIFTS, w, h, avg, bd,
339465 );
340466 return;
341467 }
342- // vpx_convolve8_c: horizontal pass into a stride-64 intermediate with
343- // `intermediate_height = (((h - 1) * y_step_q4 + y0_q4) >> SUBPEL_BITS) +
344- // SUBPEL_TAPS` — for the unscaled `y_step_q4 = 16` that is `h + SUBPEL_TAPS
345- // - 1`. The horizontal pass starts `SUBPEL_TAPS / 2 - 1` rows ABOVE the
346- // block (C passes `src - src_stride * (SUBPEL_TAPS / 2 - 1)`).
347- let intermediate_height =
348- (((h as i32 - 1) * SUBPEL_SHIFTS + subpel_y) >> SUBPEL_BITS) as usize + TAPS;
468+ convolve_2d(
469+ buf, stride, origin, dst, dst_stride, f, subpel_x, subpel_y, x_step, y_step, w, h, avg,
470+ temp, bd,
471+ );
472+}
473+
474+/// `vpx_convolve8_c` / `vpx_convolve8_avg_c` (`vpx_dsp/vpx_convolve.c:158`) =
475+/// `vpx_scaled_2d` / `vpx_scaled_avg_2d`: horizontal pass into a stride-64
476+/// intermediate with `intermediate_height = (((h - 1) * y_step_q4 + y0_q4) >>
477+/// SUBPEL_BITS) + SUBPEL_TAPS`, then the vertical pass. The horizontal pass
478+/// starts `SUBPEL_TAPS / 2 - 1` rows ABOVE the block (C passes
479+/// `src - src_stride * (SUBPEL_TAPS / 2 - 1)`).
480+#[allow(clippy::too_many_arguments)]
481+fn convolve_2d(
482+ buf: &[Sample],
483+ stride: usize,
484+ origin: isize,
485+ dst: &mut [Sample],
486+ dst_stride: usize,
487+ f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
488+ subpel_x: i32,
489+ subpel_y: i32,
490+ x_step: i32,
491+ y_step: i32,
492+ w: usize,
493+ h: usize,
494+ avg: bool,
495+ temp: &mut [Sample],
496+ bd: u8,
497+) {
498+ let intermediate_height = (((h as i32 - 1) * y_step + subpel_y) >> SUBPEL_BITS) as usize + TAPS;
349499 let temp_origin = (TAPS as isize / 2 - 1) * 64;
350500 convolve_horiz(
351501 buf,
@@ -355,6 +505,7 @@ fn inter_predictor(
355505 64,
356506 f,
357507 subpel_x,
508+ x_step,
358509 w,
359510 intermediate_height,
360511 false,
@@ -374,6 +525,7 @@ fn inter_predictor(
374525 w,
375526 f,
376527 subpel_y,
528+ y_step,
377529 w,
378530 h,
379531 false,
@@ -395,6 +547,7 @@ fn inter_predictor(
395547 dst_stride,
396548 f,
397549 subpel_y,
550+ y_step,
398551 w,
399552 h,
400553 false,
@@ -417,9 +570,12 @@ pub(crate) struct RefPlane<'a> {
417570 pub bd: u8,
418571 }
419572
420-/// `dec_build_inter_predictors` (`vp9/decoder/vp9_decodeframe.c:593`),
421-/// unscaled: predict one `w` x `h` plane block whose top-left is plane pixel
422-/// `(x, y)` inside the block at MI `(mi_row, mi_col)`.
573+/// `dec_build_inter_predictors` (`vp9/decoder/vp9_decodeframe.c:593`):
574+/// predict one `w` x `h` plane block whose top-left is plane pixel `(x, y)`
575+/// inside the block at MI `(mi_row, mi_col)`. `sf` is the reference's scale
576+/// factors; when they scale, the block is mapped into the reference frame
577+/// (`scale_value_x/y`), the MV is scaled with it (`vp9_scale_mv`) and the
578+/// convolve steps by `x_step_q4` / `y_step_q4`.
423579 #[allow(clippy::too_many_arguments)]
424580 pub(crate) fn build_inter_predictors(
425581 dst: &mut [Sample],
@@ -440,51 +596,82 @@ pub(crate) fn build_inter_predictors(
440596 ss_y: usize,
441597 kernel: usize,
442598 avg: bool,
599+ sf: &ScaleFactors,
443600 scratch: &mut Vec<Sample>,
444601 temp: &mut Vec<Sample>,
445602 ) {
446603 let bd = refp.bd;
604+ let is_scaled = sf.is_scaled();
447605 let mv_q4 = clamp_mv_to_umv_border_sb(
448606 mv, w as i32, h as i32, mb_left, mb_right, mb_top, mb_bottom, ss_x, ss_y,
449607 );
450608
451609 // Co-ordinate of the containing block, pixel precision, plus the
452610 // block-relative offset (`x`, `y`).
453- let x0_pre = (-mb_left >> (3 + ss_x)) + x as i32;
454- let y0_pre = (-mb_top >> (3 + ss_y)) + y as i32;
455- let x0_16 = (x0_pre << SUBPEL_BITS) + mv_q4.1;
456- let y0_16 = (y0_pre << SUBPEL_BITS) + mv_q4.0;
457- let subpel_x = mv_q4.1 & SUBPEL_MASK;
458- let subpel_y = mv_q4.0 & SUBPEL_MASK;
611+ let x_pre = (-mb_left >> (3 + ss_x)) + x as i32;
612+ let y_pre = (-mb_top >> (3 + ss_y)) + y as i32;
613+ let (x_step, y_step, scaled_mv);
614+ let (x0_16, y0_16, x0_pre, y0_pre);
615+ if is_scaled {
616+ // The block is mapped into the reference frame at 1/16-pel (the
617+ // `x0_16` used for the border extent) and at pixel precision (`x0`,
618+ // which shifts by the scaled MV's integer part below).
619+ let x0 = sf.scale_x(x_pre);
620+ let y0 = sf.scale_y(y_pre);
621+ scaled_mv = sf.scale_mv(
622+ mv_q4,
623+ mi_col as i32 * 8 + x as i32,
624+ mi_row as i32 * 8 + y as i32,
625+ );
626+ x_step = sf.x_step_q4;
627+ y_step = sf.y_step_q4;
628+ x0_16 = sf.scale_x(x_pre << SUBPEL_BITS) + scaled_mv.1;
629+ y0_16 = sf.scale_y(y_pre << SUBPEL_BITS) + scaled_mv.0;
630+ x0_pre = x0;
631+ y0_pre = y0;
632+ } else {
633+ scaled_mv = mv_q4;
634+ x_step = SUBPEL_SHIFTS;
635+ y_step = SUBPEL_SHIFTS;
636+ x0_16 = (x_pre << SUBPEL_BITS) + scaled_mv.1;
637+ y0_16 = (y_pre << SUBPEL_BITS) + scaled_mv.0;
638+ x0_pre = x_pre;
639+ y0_pre = y_pre;
640+ }
641+ let subpel_x = scaled_mv.1 & SUBPEL_MASK;
642+ let subpel_y = scaled_mv.0 & SUBPEL_MASK;
459643
460644 let frame_width = refp.width as i32;
461645 let frame_height = refp.height as i32;
462646 // `buf_ptr = ref_frame + y0 * stride + x0` is taken AFTER the MV integer
463647 // part but BEFORE the tap padding below, so the direct read keeps its own
464648 // copy of the coordinates.
465- let x0_mv = x0_pre + (mv_q4.1 >> SUBPEL_BITS);
466- let y0_mv = y0_pre + (mv_q4.0 >> SUBPEL_BITS);
649+ let x0_mv = x0_pre + (scaled_mv.1 >> SUBPEL_BITS);
650+ let y0_mv = y0_pre + (scaled_mv.0 >> SUBPEL_BITS);
467651 let mut x0 = x0_mv;
468652 let mut y0 = y0_mv;
469653
470654 let f = &FILTERS[kernel];
471- let _ = mi_col;
472- let _ = mi_row;
473655
474656 // `is_scaled || scaled_mv.col || scaled_mv.row || (frame_width & 7) ||
475657 // (frame_height & 7)`: the border copy is skipped only when the window is
476658 // provably inside the frame.
477- if mv_q4.1 != 0 || mv_q4.0 != 0 || (frame_width & 7) != 0 || (frame_height & 7) != 0 {
478- let mut x1 = ((x0_16 + (w as i32 - 1) * SUBPEL_SHIFTS) >> SUBPEL_BITS) + 1;
479- let mut y1 = ((y0_16 + (h as i32 - 1) * SUBPEL_SHIFTS) >> SUBPEL_BITS) + 1;
659+ if is_scaled
660+ || scaled_mv.1 != 0
661+ || scaled_mv.0 != 0
662+ || (frame_width & 7) != 0
663+ || (frame_height & 7) != 0
664+ {
665+ let mut x1 = ((x0_16 + (w as i32 - 1) * x_step) >> SUBPEL_BITS) + 1;
666+ let mut y1 = ((y0_16 + (h as i32 - 1) * y_step) >> SUBPEL_BITS) + 1;
480667 let mut x_pad = false;
481668 let mut y_pad = false;
482- if subpel_x != 0 {
669+ if subpel_x != 0 || x_step != SUBPEL_SHIFTS {
483670 x0 -= INTERP_EXTEND - 1;
484671 x1 += INTERP_EXTEND;
485672 x_pad = true;
486673 }
487- if subpel_y != 0 {
674+ if subpel_y != 0 || y_step != SUBPEL_SHIFTS {
488675 y0 -= INTERP_EXTEND - 1;
489676 y1 += INTERP_EXTEND;
490677 y_pad = true;
@@ -523,6 +710,8 @@ pub(crate) fn build_inter_predictors(
523710 f,
524711 subpel_x,
525712 subpel_y,
713+ x_step,
714+ y_step,
526715 w,
527716 h,
528717 avg,
@@ -545,6 +734,8 @@ pub(crate) fn build_inter_predictors(
545734 f,
546735 subpel_x,
547736 subpel_y,
737+ x_step,
738+ y_step,
548739 w,
549740 h,
550741 avg,
crates/ec-vp9/tests/data/intraonly.ivfadded+0 -0

Binary file changed

crates/ec-vp9/tests/data/scaledref.ivfadded+0 -0

Binary file changed

crates/ec-vp9/tests/data/scaledref_odd.ivfadded+0 -0

Binary file changed

crates/ec-vp9/tests/intraonly_exact.rsadded+102 -0
@@ -0,0 +1,102 @@
1+//! Intra-only witness: a VP9 intra-only frame — an INTER frame with
2+//! `intra_only = 1` and `show_frame = 0` — must decode byte-identically to
3+//! ffmpeg's libvpx decoder. Its body is a keyframe's (intra mode info, intra
4+//! prediction, the intra coefficient axis), but it loads its frame context
5+//! from storage and refreshes only the slots its `refresh_frame_flags`
6+//! names, so the frames that follow it prove the reconstruction.
7+//!
8+//! The fixture is committed under `tests/data/` because no ffmpeg invocation
9+//! emits an intra-only frame (libvpx's encoder produces them only through its
10+//! SVC path, which the libvpx-vp9 wrapper does not expose). The generator is
11+//! recorded in `lanes/vp9refsetup.report.md`; the stream is an ordinary
12+//! 10-frame 320x240 testsrc2 GOP whose visible keyframe is re-headed as an
13+//! intra-only inter frame with a matching `refresh_frame_flags`, so its
14+//! reconstruction must equal the keyframe's and the whole GOP must come out
15+//! identical to the source.
16+
17+mod ivf;
18+
19+use ec_vp9::decode::Decoder;
20+use ec_vp9_syntax::{FrameType, Vp9Parser};
21+
22+fn fixture() -> std::path::PathBuf {
23+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/intraonly.ivf")
24+}
25+
26+/// ffmpeg's decoded rawvideo byte stream (frame-packed I420, `w`x`h`).
27+fn ffmpeg_raw_yuv(path: &std::path::Path, w: usize, h: usize) -> Vec<u8> {
28+ let out = std::process::Command::new("ffmpeg")
29+ .args(["-v", "error", "-i"])
30+ .arg(path)
31+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
32+ .output()
33+ .expect("ffmpeg on PATH");
34+ assert!(out.status.success(), "ffmpeg decode failed: {out:?}");
35+ let frame = w * h + 2 * (w / 2) * (h / 2);
36+ assert_eq!(
37+ out.stdout.len() % frame,
38+ 0,
39+ "ffmpeg output is not frame-aligned"
40+ );
41+ out.stdout
42+}
43+
44+#[test]
45+fn intra_only_frame_and_its_successors_match_ffmpeg() {
46+ let path = fixture();
47+ let bytes = std::fs::read(&path).expect("tests/data/intraonly.ivf is committed");
48+ let (_, w, h, frames) = ivf::parse_ivf(&bytes);
49+ let (w, h) = (w as usize, h as usize);
50+
51+ // Non-vacuity: the stream must really carry an intra-only frame.
52+ let mut parser = Vp9Parser::new();
53+ let mut intra_only = 0usize;
54+ for f in &frames {
55+ for sub in ec_vp9_syntax::split(&f.data).unwrap() {
56+ let hdr = parser.parse_frame(sub).unwrap();
57+ if hdr.frame_type == FrameType::Inter && hdr.intra_only {
58+ intra_only += 1;
59+ }
60+ }
61+ }
62+ assert_eq!(
63+ intra_only, 1,
64+ "the fixture must carry exactly one intra-only frame"
65+ );
66+
67+ let expected = ffmpeg_raw_yuv(&path, w, h);
68+ let frame_bytes = w * h + 2 * (w / 2) * (h / 2);
69+ let mut decoder = Decoder::new();
70+ let mut shown = 0usize;
71+ for (i, f) in frames.iter().enumerate() {
72+ if let Some(pic) = decoder.decode(&f.data).expect("frame decodes") {
73+ let off = shown * frame_bytes;
74+ assert!(
75+ off + frame_bytes <= expected.len(),
76+ "frame {i}: ffmpeg has fewer frames than we show"
77+ );
78+ let want = &expected[off..off + frame_bytes];
79+ let mut got = Vec::with_capacity(frame_bytes);
80+ got.extend(pic.y.iter().map(|&v| v as u8));
81+ got.extend(pic.u.iter().map(|&v| v as u8));
82+ got.extend(pic.v.iter().map(|&v| v as u8));
83+ let diff = got.iter().zip(want).position(|(a, b)| a != b);
84+ assert!(
85+ diff.is_none(),
86+ "frame {i}: pixel mismatch at byte {:?} (ours {} ffmpeg {})",
87+ diff,
88+ diff.map(|d| got[d]).unwrap_or(0),
89+ diff.map(|d| want[d]).unwrap_or(0)
90+ );
91+ shown += 1;
92+ }
93+ }
94+ assert_eq!(
95+ shown * frame_bytes,
96+ expected.len(),
97+ "shown frame count mismatch"
98+ );
99+ // 11 input frames: a visible keyframe, the hidden intra-only frame and 9
100+ // visible inter frames — 10 shown.
101+ assert_eq!(shown, 10, "the witness must show past the intra-only frame");
102+}
crates/ec-vp9/tests/scaledref_exact.rsadded+172 -0
@@ -0,0 +1,172 @@
1+//! Scaled-reference witness: an inter frame whose reference slot holds a
2+//! picture of a DIFFERENT coded size must scale that reference during
3+//! prediction (`vp9_setup_scale_factors_for_frame` + the scaled convolve
4+//! walk) and come out byte-identical to libvpx. `scaledref.ivf` scales
5+//! 1280x720 -> 640x360 (`x_step_q4 == y_step_q4 == 32`); the paired
6+//! `scaledref_odd.ivf` is the same stream with the keyframe patched to
7+//! 1279x719, so the reference is an ODD coded extent and its chroma crop
8+//! ceils — the interaction with the odd-dimension layout.
9+//!
10+//! The fixtures are committed under `tests/data/` because no ffmpeg
11+//! invocation can produce a size change: libvpx's encoder emits one only
12+//! through its rate-control resize path (ffmpeg exposes neither
13+//! `rc_resize_allowed` nor SVC), and a hand-spliced explicit-size inter frame trips
14+//! libvpx's own header reparsing. The generator is recorded in
15+//! `lanes/vp9refsetup.report.md`: a 1280x720 one-pass CBR encode at 200 kbps,
16+//! whose `vp9_resize_one_pass_cbr` downscales frame 1 to 640x360 against the
17+//! keyframe. `scaledref_odd.ivf` is that same file through
18+//! `$HOME/.cache/vp9pix/patch_kf_size.py <in> <out> 1279 719` (which rewrites
19+//! the IVF container size too).
20+//!
21+//! Oracle caveat: ffmpeg locks its rawvideo output size to the FIRST decoded
22+//! frame's, so a two-size stream cannot be dumped in one pass. Frame 0 is
23+//! decoded on its own (`-frames:v 1`, identity); frames 2..N are decoded with
24+//! `select=gte(n,1)` at the small size, where the filtergraph has
25+//! re-initialised and every frame passes through unchanged. The size-change
26+//! frame (file frame 1) is the one ffmpeg mangles during that
27+//! re-initialisation, so it is checked INDIRECTLY: every later frame predicts
28+//! from its reconstruction, so a wrong scaler fails frames 2..N.
29+
30+mod ivf;
31+
32+use ec_vp9::decode::Decoder;
33+use ec_vp9_syntax::{FrameType, Vp9Parser};
34+
35+fn fixture(name: &str) -> std::path::PathBuf {
36+ std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
37+ .join("tests/data")
38+ .join(name)
39+}
40+
41+/// Run ffmpeg over `path` with `args` and return its rawvideo stdout.
42+fn ffmpeg_raw(path: &std::path::Path, args: &[&str]) -> Vec<u8> {
43+ let out = std::process::Command::new("ffmpeg")
44+ .args(["-v", "error", "-y", "-i"])
45+ .arg(path)
46+ .args(args)
47+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
48+ .output()
49+ .expect("ffmpeg on PATH");
50+ assert!(out.status.success(), "ffmpeg decode failed: {out:?}");
51+ out.stdout
52+}
53+
54+fn frame_bytes(w: usize, h: usize) -> usize {
55+ w * h + 2 * w.div_ceil(2) * h.div_ceil(2)
56+}
57+
58+fn assert_planes(pic: &ec_vp9::decode::Picture, want: &[u8], label: &str) {
59+ let mut got = Vec::with_capacity(want.len());
60+ got.extend(pic.y.iter().map(|&v| v as u8));
61+ got.extend(pic.u.iter().map(|&v| v as u8));
62+ got.extend(pic.v.iter().map(|&v| v as u8));
63+ assert_eq!(got.len(), want.len(), "{label}: plane size");
64+ let diff = got.iter().zip(want).position(|(a, b)| a != b);
65+ assert!(
66+ diff.is_none(),
67+ "{label}: pixel mismatch at byte {:?} (ours {} libvpx {})",
68+ diff,
69+ diff.map(|d| got[d]).unwrap_or(0),
70+ diff.map(|d| want[d]).unwrap_or(0)
71+ );
72+}
73+
74+fn check(name: &str) {
75+ let path = fixture(name);
76+ let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
77+ let (_, cw, ch, frames) = ivf::parse_ivf(&bytes);
78+
79+ // Non-vacuity: the stream must carry an inter frame whose coded size
80+ // differs from the frame before it — the only shape that makes a
81+ // reference scale.
82+ let mut parser = Vp9Parser::new();
83+ let mut sizes: Vec<(u32, u32, FrameType)> = Vec::new();
84+ for f in &frames {
85+ for sub in ec_vp9_syntax::split(&f.data).unwrap() {
86+ let hdr = parser.parse_frame(sub).unwrap();
87+ sizes.push((hdr.width, hdr.height, hdr.frame_type));
88+ }
89+ }
90+ let changed = sizes
91+ .windows(2)
92+ .filter(|p| p[0].0 != p[1].0 || p[0].1 != p[1].1)
93+ .count();
94+ assert!(
95+ changed >= 1,
96+ "{name}: the fixture must change coded size mid-stream (sizes: {sizes:?})"
97+ );
98+ assert!(
99+ sizes
100+ .iter()
101+ .any(|s| s.2 == FrameType::Inter && (s.0, s.1) != (cw as u32, ch as u32)),
102+ "{name}: an inter frame must differ from the container's declared size"
103+ );
104+
105+ let mut decoder = Decoder::new();
106+ let ours: Vec<_> = frames
107+ .iter()
108+ .map(|f| decoder.decode(&f.data).expect("frame decodes"))
109+ .collect();
110+ let shown: Vec<_> = ours.iter().filter_map(|p| p.as_ref()).collect();
111+ assert_eq!(shown.len(), 10, "{name}: the fixture has 10 visible frames");
112+
113+ // Frame 0 (the keyframe) alone; identity.
114+ let oracle0 = ffmpeg_raw(&path, &["-frames:v", "1"]);
115+ assert_eq!(
116+ oracle0.len(),
117+ frame_bytes(shown[0].width as usize, shown[0].height as usize),
118+ "{name}: frame 0 oracle size"
119+ );
120+ assert_planes(shown[0], &oracle0, &format!("{name} frame 0"));
121+
122+ // Frames 2..N: after the size change every frame passes through the
123+ // filtergraph unchanged at the small size.
124+ let small = (shown[2].width as usize, shown[2].height as usize);
125+ assert!(
126+ small != (shown[0].width as usize, shown[0].height as usize),
127+ "{name}: frames after the change must be resized"
128+ );
129+ let oracle_rest = ffmpeg_raw(
130+ &path,
131+ &[
132+ "-vf",
133+ "select=gte(n\\,1)",
134+ "-fps_mode",
135+ "passthrough",
136+ "-s",
137+ &format!("{}x{}", small.0, small.1),
138+ ],
139+ );
140+ let fbs = frame_bytes(small.0, small.1);
141+ assert_eq!(
142+ oracle_rest.len(),
143+ fbs * (shown.len() - 2),
144+ "{name}: ffmpeg must emit frames 2..{}",
145+ shown.len() - 1
146+ );
147+ for (j, pic) in shown[2..].iter().enumerate() {
148+ assert_eq!(
149+ (pic.width as usize, pic.height as usize),
150+ small,
151+ "{name}: frame {} size",
152+ j + 2
153+ );
154+ assert_planes(
155+ pic,
156+ &oracle_rest[j * fbs..(j + 1) * fbs],
157+ &format!("{name} frame {}", j + 2),
158+ );
159+ }
160+}
161+
162+#[test]
163+fn size_changing_reference_decodes_byte_exact() {
164+ check("scaledref.ivf");
165+}
166+
167+/// The same size change with an ODD coded reference: 1279x719 -> 640x360,
168+/// where the reference's chroma crop ceils (`(1279 + 1) / 2`).
169+#[test]
170+fn size_changing_odd_reference_decodes_byte_exact() {
171+ check("scaledref_odd.ivf");
172+}
lanes/vp9refsetup.report.mdadded+167 -0
@@ -0,0 +1,167 @@
1+# lane-vp9-refsetup — intra-only frames + scaled references
2+
3+Branch `lane-vp9-refsetup`, off main `79984549`. Two named refusals removed:
4+
5+1. `vp9 intra-only` — an INTER frame with `intra_only = 1`, `show_frame = 0`
6+ (`decode.rs:233`, `:320`).
7+2. `vp9 inter reference size change` — an inter frame whose reference slot
8+ holds a picture of a different coded size (`decode.rs:372`).
9+
10+Acceptance bar: byte-exact vs libvpx 1.15 (the frozen oracle drivers
11+`$HOME/.cache/vp9pix/drv_pix3`, `drv_err`, statically linked to the 1.15 build)
12+on real streams, plus the full 8-bit regression corpus unchanged.
13+
14+## What changed
15+
16+| path | why |
17+| --- | --- |
18+| `crates/ec-vp9/src/decode.rs` `decode_one` / `decode_syntax` | intra-only routes to the new `decode_intra_only_frame` instead of refusing |
19+| `crates/ec-vp9/src/decode.rs` `decode_intra_only_frame` | new: keyframe body, storage-loaded frame context (reset only for `reset_frame_context` 2/3 / error-resilient), `refresh_frame_flags`-scoped reference refresh |
20+| `crates/ec-vp9/src/decode.rs` `decode_block` | intra dispatch keys on `frame_is_intra_only` (keyframe OR intra-only), not `frame_type == Key` |
21+| `crates/ec-vp9/src/decode.rs` `decode_inter_frame` | size-change refusal removed; slot-existence checks kept |
22+| `crates/ec-vp9/src/decode.rs` `inter_predict_plane` | `ScaleFactors::setup` per reference (`valid_ref_frame_size` -> `vp9 reference scale` refusal where libvpx errors) |
23+| `crates/ec-vp9/src/mc.rs` | `ScaleFactors` (`vp9_setup_scale_factors_for_frame`, `vp9_scale_mv`), step-aware `convolve_horiz`/`convolve_vert`, `sf->predict` kernel selection, scaled block/MV mapping in `build_inter_predictors` |
24+| `crates/ec-vp9/src/header.rs` | `FrameContext::use_key_partition` (`set_partition_probs`) |
25+| `crates/ec-vp9/tests/{intraonly,scaledref}_exact.rs` + `tests/data/*.ivf` | regression witnesses |
26+
27+### Semantics ported (bug-for-bug, libvpx 1.15.0)
28+
29+* `vp9_setup_past_independence` (`vp9/common/vp9_entropymode.c:424`) is called
30+ for intra-only frames, but `cm->frame_type != KEY_FRAME`, so the stored
31+ contexts are reset only for `reset_frame_context` 2 (selected) / 3 (all) or
32+ error-resilient mode. The ACTIVE context is then
33+ `*cm->fc = cm->frame_contexts[frame_context_idx]`
34+ (`vp9_decodeframe.c:3008`) — storage, not the defaults.
35+* Partitions for intra-only (and key) frames come from the const
36+ `vp9_kf_partition_probs` (`set_partition_probs`, `onyxc_int.h:367`), which is
37+ NOT a `FRAME_CONTEXT` field: the stored context's `partition` survives the
38+ frame untouched (restored before storing).
39+* Reference refresh is `refresh_frame_flags`-scoped; `show_frame` stays 0 (an
40+ intra-only frame is never displayable — the parser only reads `intra_only`
41+ when `show_frame == 0`).
42+* Scaling: `x_scale_fp = (other << 14) / this`, `x_step_q4 = scaled_x(16)`;
43+ the block maps with `scale_value_x/y`, the MV with `vp9_scale_mv`
44+ (`vp9_scale.c:29`), and `sf->predict[subpel_x != 0][subpel_y != 0]` picks the
45+ kernel (`vpx_scaled_horiz/vert/2d` == the step-aware convolve helpers).
46+ The tap-padding branch is `subpel || step != 16`; the direct read keeps the
47+ pre-padding coordinates.
48+
49+## Fixtures and generators (reproducibility)
50+
51+None of these can be produced by an ffmpeg invocation:
52+
53+* **intra-only**: libvpx's encoder emits intra-only frames only through its SVC
54+ path (`set_intra_only_frame`, `vp9_ratectrl.c:2211`), which ffmpeg does not
55+ expose. Generated by `lanes/vp9refsetup/gen_intraonly.py` from a plain
56+ ffmpeg keyframe GOP:
57+ ```
58+ ffmpeg -v error -y -f lavfi -i testsrc2=size=320x240:rate=24:duration=0.4 \
59+ -c:v libvpx-vp9 -g 999 -auto-alt-ref 0 -crf 32 -deadline good -cpu-used 4 \
60+ -pix_fmt yuv420p -f ivf S.ivf
61+ python3 lanes/vp9refsetup/gen_intraonly.py S.ivf intraonly.ivf
62+ ```
63+ The generator reproduces the committed `tests/data/intraonly.ivf` byte for
64+ byte (`cmp` verified). 11 frames: keyframe, hidden intra-only twin, 9 inter.
65+* **size change**: libvpx's encoder resizes only through rate control
66+ (`vp9_resize_one_pass_cbr`, `vp9_ratectrl.c:2728`); ffmpeg exposes neither
67+ `rc_resize_allowed` nor SVC, and ffmpeg's rawvideo output size is locked to
68+ the first decoded frame (see the oracle caveat), so a two-size stream cannot
69+ be dumped in one pass. Generated by
70+ `lanes/vp9refsetup/gen_scaledref.c` (links the pristine libvpx 1.15.0
71+ encoder):
72+ ```
73+ gcc -I<libvpx> -I<libvpx>/vpx gen_scaledref.c <libvpx>/libvpx.a -o enc -lm -lpthread
74+ ./enc scaledref.ivf 1280 720 10 200 # one-pass CBR, 200 kbps, lag 0
75+ ```
76+ libvpx's force-downsize rule (`>= 1280x720` input and
77+ `avg_frame_bandwidth < 300000/30`) downscales frame 1 to 640x360 against the
78+ 1280x720 keyframe — a genuine 2x reference scale (`x_step_q4 == 32`).
79+* **odd variant**: `scaledref_odd.ivf` is `scaledref.ivf` with the keyframe's
80+ size fields patched 1280x720 -> 1279x719 (mi-grid invariant, so the tile data
81+ stays valid) — the reference is then an odd coded extent and its chroma crop
82+ ceils. Patch with the existing
83+ `$HOME/.cache/vp9pix/patch_kf_size.py <in> <out> 1279 719`, which rewrites the
84+ IVF container size as well (`sha256 af289a0f8dd91bfa854adeac1814dc77644ad87b9df0af884d33abaae2595413`).
85+
86+## Gates
87+
88+`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9ref`
89+
90+1. **Suite**: `cargo test -p ec-vp9` — every binary green, **0 failed**,
91+ 0 ignored. Warning parity: exactly the 5 pre-existing (`TM_PRED`,
92+ `read_partition`, `partition_probs`, `x_mis`, `y_mis`).
93+2. **New witnesses** (byte-exact vs ffmpeg's libvpx-backed rawvideo):
94+ * `intra_only_frame_and_its_successors_match_ffmpeg` — 10/10 shown frames
95+ identical; the fixture is asserted to carry exactly one intra-only frame.
96+ * `size_changing_reference_decodes_byte_exact` — 10/10 identical.
97+ * `size_changing_odd_reference_decodes_byte_exact` — 10/10 identical.
98+3. **Crate-level oracle** (my dump vs libvpx's `drv_pix3`, per-shown-frame
99+ native dims + ceil chroma, compared with `cmp`):
100+ `scaledref.ivf` **IDENTICAL** (4,492,800 bytes, 10 frames);
101+ `scaledref_odd.ivf` **IDENTICAL** (4,490,801 bytes, 10 frames);
102+ `intraonly.ivf` **IDENTICAL** via drv_pix (all 10 output frames match the
103+ source GOP's, i.e. the intra-only frame reconstructs exactly like the
104+ keyframe it replaced).
105+4. **Fail-pre-fix** (throwaway base worktree at `79984549`, tests+fixtures
106+ copied in, private target dir):
107+ * intra-only: `Unsupported { what: "vp9 intra-only", why: "this lane decodes
108+ inter frames and keyframes only" }` at `intraonly_exact.rs:72`.
109+ * scaled: `Unsupported { what: "vp9 inter reference size change", why:
110+ "reference `last` in slot 0 is 1280x720 but this frame is 640x360;
111+ reference-frame scaling is not ported" }` (and the 1279x719 twin) at
112+ `scaledref_exact.rs:107`.
113+5. **Regression corpus** (`$HOME/.cache/vp9ref-sweep.sh` = `drv_pix3` vs
114+ `scratch_pixdump`, byte `cmp`) — all **IDENTICAL**:
115+
116+| stream | oracle frames | bytes |
117+| --- | --- | --- |
118+| `vp9-1080p-23.976-8bit.ivf` | 48 | 149,299,200 |
119+| `vp9-1080p-60-8bit.ivf` (120 frames, the frame-72 witness) | 120 | 373,248,000 |
120+| `vp9-2160p-23.976-8bit.ivf` | 48 | 597,196,800 |
121+| `vp9-tiles-1280.ivf` | 30 | 41,472,000 |
122+| `vp9-superframe-altref.ivf` | 60 | 6,912,000 |
123+| `$HOME/.cache/vp9pix/inter.ivf` | 3 | 9,331,200 |
124+| `$HOME/.cache/vp9pix/inter1.ivf` | 3 | 9,331,200 |
125+| odd testsrc2 321x241 (322x242 encode + `patch_kf_size.py`) | 12 | 1,395,876 |
126+
127+6. **Interaction (size change x odd dims)**: `scaledref_odd.ivf` covers it —
128+ the scaled reference is an odd extent (1279x719, chroma `(w+1)/2`) and the
129+ result is byte-identical to libvpx. Not deferred.
130+
131+## Oracle caveat (why the committed tests skip frame 1)
132+
133+ffmpeg locks its rawvideo output size to the FIRST decoded frame's, so a
134+two-size stream cannot be dumped in one pass: frames 1..N come out upscaled to
135+1280x720. The tests decode frame 0 alone (`-frames:v 1`, identity) and frames
136+2..N with `select=gte(n,1)` at the small size, where the filtergraph has
137+re-initialised and every frame passes through unchanged. The size-change frame
138+(file frame 1) is the one ffmpeg mangles during that re-initialisation, so it
139+is covered INDIRECTLY: every later frame predicts from its reconstruction (a
140+wrong scaler fails frames 2..N). Frame 1 itself is covered directly by the
141+crate-level `drv_pix3` comparison in gate 3.
142+
143+## Deferred / accepted
144+
145+* accepted: **profile 2 / 4:4:4** still refused by name (`decode.rs:211/217`,
146+ and `vp9 reference scale` for a colour-format mismatch) — out of scope, owned
147+ by the sibling lane.
148+* accepted: `vp9 reference scale` (the `valid_ref_frame_size` ratio bound) stays
149+ a named refusal; libvpx errors the same way (`Reference frame has invalid
150+ dimensions`). Reaching it needs an adversarial 2x+ ratio that no encoder
151+ emits.
152+* noted, not touched: the existing inter path resets stored frame contexts for
153+ `reset_frame_context` 2/3 even though libvpx only does that via
154+ `vp9_setup_past_independence` (i.e. only for intra-only / error-resilient
155+ frames). Pre-existing, unreachable on the corpus (which codes `reset = 0`),
156+ and outside this lane's scope.
157+* noted: `scratch_pixdump`/`drv_pix3` are per-`inter_pixdump`-style scratch
158+ harnesses; the new `drv_pix3` (per-frame native dims) lives only in
159+ `$HOME/.cache/vp9pix`.
160+
161+## Test scope actually run
162+
163+* `cargo test -p ec-vp9` (whole crate) — green, 0 failed, 5 warnings.
164+* `cargo test -p ec-vp9 --test intraonly_exact --test scaledref_exact` — 3
165+ passed.
166+* corpus sweep above — 8 streams IDENTICAL.
167+* base-worktree fail-pre-fix — 3 failures with the named refusals.
lanes/vp9refsetup/gen_intraonly.pyadded+73 -0
@@ -0,0 +1,73 @@
1+#!/usr/bin/env python3
2+"""Turn an ffmpeg VP9 keyframe GOP into the intra-only witness.
3+
4+Re-heads frame 0 (a visible keyframe) as an INTRA-ONLY inter frame
5+(frame_type=1, show_frame=0, intra_only=1, reset_frame_context=2,
6+refresh_frame_flags=0xff) and keeps every later frame as-is: the intra-only
7+frame must reconstruct exactly like the keyframe it replaces, so the whole GOP
8+decodes to the same shown frames.
9+
10+reset_frame_context=2 matters: `vp9_setup_past_independence` resets the
11+selected stored context to the defaults, and the keyframe's compressed header
12+was coded against the defaults. With reset 0/1 the frame would read whatever
13+context the previous frame stored and the bool stream desyncs.
14+
15+usage: gen_intraonly.py <keyframe-gop.ivf> <out.ivf>
16+The keyframe uncompressed header (profile 0, 8-bit, 4:2:0, error_resilient=0)
17+is 8 bits + 24 sync + 3 color_space + 1 color_range => the render flag sits at
18+bit 68 and the fields from bit 69 on (loop filter, quant, segmentation, tile
19+info, header_size) are copied verbatim. The new prefix is 76 bits, so the
20+field bits shift by 7 and the compressed header + tiles (orig[U:], with
21+U = ceil(E/8)) follow the re-padded header. E was found by trying every byte
22+offset until libvpx accepted the frame; the committed fixture's E is 140.
23+"""
24+import struct, sys
25+
26+src, dst = sys.argv[1], sys.argv[2]
27+d = open(src, 'rb').read()
28+off, frames = 32, []
29+while off + 12 <= len(d):
30+ sz = struct.unpack('<I', d[off:off+4])[0]
31+ frames.append((d[off+4:off+12], d[off+12:off+12+sz]))
32+ off += 12 + sz
33+
34+def bits_of(b):
35+ return [(x >> i) & 1 for x in b for i in range(7, -1, -1)]
36+
37+K = frames[0][1]
38+kb = bits_of(K)
39+assert kb[5] == 0 and kb[6] == 1 and kb[7] == 0, "expected a visible, non-ER keyframe"
40+rf = kb[68]
41+p1 = 69 if rf == 0 else 101
42+prefix = kb[0:5] + [1, 0, kb[7], 1] + [1, 0] + kb[8:32] + [1] * 8 + kb[36:52] + kb[52:68] + [rf]
43+if rf:
44+ prefix += kb[69:101]
45+assert len(prefix) == 76
46+
47+E = 140 # committed fixture; any E whose (E+7)>>3 == 18 also decodes
48+post = kb[p1:E]
49+nb = prefix + post
50+while len(nb) % 8:
51+ nb.append(0)
52+hdr = bytearray()
53+for i in range(0, len(nb), 8):
54+ v = 0
55+ for j in range(8):
56+ v = (v << 1) | nb[i+j]
57+ hdr.append(v)
58+Kp = bytes(hdr) + K[(E + 7) >> 3:]
59+
60+out = bytearray(b'DKIF' + b'\0' * 28)
61+out[6:8] = struct.pack('<H', 32)
62+out[8:12] = b'VP90'
63+out[12:14] = struct.pack('<H', 320)
64+out[14:16] = struct.pack('<H', 240)
65+out[16:20] = struct.pack('<I', 24)
66+out[20:24] = struct.pack('<I', 1)
67+out[24:28] = struct.pack('<I', len(frames) + 1)
68+out += struct.pack('<I', len(K)) + frames[0][0] + K
69+out += struct.pack('<I', len(Kp)) + frames[0][0] + Kp
70+for ts, f in frames[1:]:
71+ out += struct.pack('<I', len(f)) + ts + f
72+open(dst, 'wb').write(out)
73+print("wrote", dst)
lanes/vp9refsetup/gen_scaledref.cadded+48 -0
@@ -0,0 +1,48 @@
1+#include <stdio.h>
2+#include <stdlib.h>
3+#include <string.h>
4+#include <stdint.h>
5+#include <vpx/vpx_encoder.h>
6+#include <vpx/vp8cx.h>
7+static FILE *O;
8+static void drain(vpx_codec_ctx_t *c){
9+ const vpx_codec_cx_pkt_t *pkt; vpx_codec_iter_t it=NULL;
10+ while((pkt=vpx_codec_get_cx_data(c,&it))) if(pkt->kind==VPX_CODEC_CX_FRAME_PKT){
11+ unsigned char sz[4]; uint32_t n=pkt->data.frame.sz; memcpy(sz,&n,4); fwrite(sz,1,4,O);
12+ unsigned long ts=(unsigned long)pkt->data.frame.pts; unsigned char t[8]; memcpy(t,&ts,8); fwrite(t,1,8,O);
13+ fwrite(pkt->data.frame.buf,1,n,O);
14+ }
15+}
16+static void fill(vpx_image_t*img,int f){
17+ int W=img->d_w,H=img->d_h;
18+ for(int y=0;y<H;y++)for(int x=0;x<W;x++){
19+ int v=(x*160/W)+(y*120/H)+f*4;
20+ img->planes[0][y*img->stride[0]+x]=(unsigned char)(v&0xff);}
21+ // A moving 200x120 high-contrast box (nonzero MVs + residual under scaling).
22+ int bx=(f*37)%(W-200), by=(f*23)%(H-120);
23+ for(int y=by;y<by+120;y++)for(int x=bx;x<bx+200;x++)
24+ img->planes[0][y*img->stride[0]+x]=(((x/16+y/16)&1)?230:25);
25+ for(int p=1;p<3;p++){int cw=(W+1)/2,ch=(H+1)/2;
26+ for(int y=0;y<ch;y++)for(int x=0;x<cw;x++){
27+ int v=128+(x*40/cw)-(y*30/ch)+f*(p?2:-2);
28+ img->planes[p][y*img->stride[p]+x]=(unsigned char)(v&0xff);}}
29+}
30+int main(int argc,char**argv){
31+ const char*out=argv[1]; int W=atoi(argv[2]),H=atoi(argv[3]),N=atoi(argv[4]),br=atoi(argv[5]);
32+ vpx_codec_enc_cfg_t cfg; vpx_codec_enc_config_default(vpx_codec_vp9_cx(),&cfg,0);
33+ cfg.g_w=W;cfg.g_h=H;cfg.g_timebase.num=1;cfg.g_timebase.den=30;
34+ cfg.rc_end_usage=VPX_CBR;cfg.rc_target_bitrate=br;cfg.g_lag_in_frames=0;
35+ cfg.rc_resize_allowed=1; cfg.rc_buf_sz=200; cfg.rc_buf_initial_sz=100; cfg.rc_buf_optimal_sz=150;
36+ cfg.rc_min_quantizer=4; cfg.rc_max_quantizer=56;
37+ cfg.kf_min_dist=9999;cfg.kf_max_dist=9999;
38+ vpx_codec_ctx_t c;
39+ if(vpx_codec_enc_init(&c,vpx_codec_vp9_cx(),&cfg,0)){fprintf(stderr,"init %s\n",vpx_codec_error(&c));return 1;}
40+ vpx_codec_control(&c,VP8E_SET_CPUUSED,5);
41+ O=fopen(out,"wb"); unsigned char hdr[32];memset(hdr,0,32);memcpy(hdr,"DKIF",4);hdr[6]=32;memcpy(hdr+8,"VP90",4);
42+ hdr[12]=W&0xff;hdr[13]=W>>8;hdr[14]=H&0xff;hdr[15]=H>>8;hdr[16]=30;hdr[17]=1;hdr[20]=1;
43+ uint32_t nf=N;memcpy(hdr+24,&nf,4);fwrite(hdr,1,32,O);
44+ vpx_image_t*img=vpx_img_alloc(NULL,VPX_IMG_FMT_I420,W,H,1);
45+ for(int i=0;i<N;i++){ fill(img,i); if(vpx_codec_encode(&c,img,i,1,0,VPX_DL_GOOD_QUALITY)){fprintf(stderr,"enc %d %s\n",i,vpx_codec_error(&c));return 1;} drain(&c); }
46+ for(;;){vpx_codec_encode(&c,NULL,N,1,0,VPX_DL_GOOD_QUALITY);int b=ftell(O);drain(&c);if(ftell(O)==b)break;}
47+ fclose(O);vpx_codec_destroy(&c);fprintf(stderr,"wrote %s %dx%d n=%d br=%d\n",out,W,H,N,br);return 0;
48+}