ec-vp9: decode intra-only frames and scaled references, byte-exact vs libvpx
Browse files at this commit2251b714aa034955fb3e5506bb137b3a14c1057cParent: 02d10ba11 changed files +978 -78
- crates/ec-vp9/src/decode.rs +147 -42
- crates/ec-vp9/src/header.rs +12 -0
- crates/ec-vp9/src/mc.rs +261 -36
- crates/ec-vp9/tests/data/intraonly.ivf +0 -0
- crates/ec-vp9/tests/data/scaledref.ivf +0 -0
- crates/ec-vp9/tests/data/scaledref_odd.ivf +0 -0
- crates/ec-vp9/tests/intraonly_exact.rs +102 -0
- crates/ec-vp9/tests/scaledref_exact.rs +171 -0
- lanes/vp9refsetup.report.md +164 -0
- lanes/vp9refsetup/gen_intraonly.py +73 -0
- lanes/vp9refsetup/gen_scaledref.c +48 -0
crates/ec-vp9/src/decode.rsmodified+147 -42
| @@ -4,18 +4,21 @@ | ||
| 4 | 4 | //! reconstruction and the loop filter (spec 6, 7, 8; libvpx |
| 5 | 5 | //! `vp9_decodeframe.c`). |
| 6 | 6 | //! |
| 7 | -//! Capability: profile-0 8-bit 4:2:0 keyframes and inter frames (motion | |
| 8 | -//! compensation, residual reconstruction, the loop filter and an 8-slot | |
| 9 | -//! reference DPB). Intra-only frames, other profiles/subsamplings and a | |
| 10 | -//! reference whose coded size differs from the current frame are refused by | |
| 11 | -//! name; `show_existing_frame` returns the buffered reference picture instead | |
| 12 | -//! of pretending to decode. Odd coded extents are supported: chroma stores | |
| 13 | -//! and crops at `(w + 1) / 2` (`uv_crop_width`), matching libvpx. | |
| 7 | +//! Capability: profile-0 8-bit 4:2:0 keyframes, intra-only frames and inter | |
| 8 | +//! frames (motion compensation, residual reconstruction, the loop filter and | |
| 9 | +//! an 8-slot reference DPB). A reference whose coded size differs from the | |
| 10 | +//! current frame is scaled during prediction; other profiles/subsamplings are | |
| 11 | +//! refused by name; `show_existing_frame` returns the buffered reference | |
| 12 | +//! picture instead of pretending to decode. Odd coded extents are supported: | |
| 13 | +//! chroma stores and crops at `(w + 1) / 2` (`uv_crop_width`), matching | |
| 14 | +//! libvpx. | |
| 14 | 15 | |
| 15 | 16 | use crate::header::{FrameContext, read_compressed_header}; |
| 16 | 17 | use crate::intra::build_intra_predictors; |
| 17 | 18 | use crate::loopfilter::LfGrids; |
| 18 | -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 | +}; | |
| 19 | 22 | use crate::modes::{MiInfo, MiState, read_intra_frame_mode_info}; |
| 20 | 23 | use crate::tables::*; |
| 21 | 24 | use crate::tokens::{PlaneContexts, decode_coefs, scan_for}; |
| @@ -231,10 +234,7 @@ impl Decoder { | ||
| 231 | 234 | return self.decode_key_frame(&hdr, frame); |
| 232 | 235 | } |
| 233 | 236 | if hdr.intra_only { |
| 234 | - return Err(Error::unsupported( | |
| 235 | - "vp9 intra-only", | |
| 236 | - "this lane decodes inter frames and keyframes only", | |
| 237 | - )); | |
| 237 | + return self.decode_intra_only_frame(&hdr, frame); | |
| 238 | 238 | } |
| 239 | 239 | self.decode_inter_frame(&hdr, frame, index, true) |
| 240 | 240 | } |
| @@ -295,6 +295,76 @@ impl Decoder { | ||
| 295 | 295 | Ok(if hdr.show_frame { Some(pic) } else { None }) |
| 296 | 296 | } |
| 297 | 297 | |
| 298 | + /// Decode an intra-only frame through to pixels. `libvpx | |
| 299 | + /// vp9_decodeframe.c:2708-2745` makes it an INTER frame that never shows | |
| 300 | + /// and refreshes only the slots its `refresh_frame_flags` names, but its | |
| 301 | + /// body is a keyframe's: intra-only mode info, intra prediction, the intra | |
| 302 | + /// coefficient axis and the intra loop-filter levels. Two header decisions | |
| 303 | + /// differ from a keyframe (`vp9_setup_past_independence`, | |
| 304 | + /// `vp9/common/vp9_entropymode.c:424`): | |
| 305 | + /// | |
| 306 | + /// - the ACTIVE frame context comes from storage | |
| 307 | + /// (`*cm->fc = cm->frame_contexts[frame_context_idx]`, | |
| 308 | + /// `vp9_decodeframe.c:3008`) — reset to the defaults only for | |
| 309 | + /// `reset_frame_context` 2 (selected) or 3 (all), or under | |
| 310 | + /// error-resilient mode, never unconditionally like a keyframe (whose | |
| 311 | + /// `cm->frame_type == KEY_FRAME` clause resets every stored context); | |
| 312 | + /// - partitions read the const `vp9_kf_partition_probs` | |
| 313 | + /// (`set_partition_probs`), so the stored context's own `partition` | |
| 314 | + /// field survives the frame untouched. | |
| 315 | + fn decode_intra_only_frame( | |
| 316 | + &mut self, | |
| 317 | + hdr: &FrameHeader, | |
| 318 | + frame: &[u8], | |
| 319 | + ) -> Result<Option<Picture>> { | |
| 320 | + let hdr = hdr.clone(); | |
| 321 | + if hdr.error_resilient_mode || hdr.reset_frame_context == 3 { | |
| 322 | + let d = FrameContext::new(false); | |
| 323 | + self.frame_ctxs = [d.clone(), d.clone(), d.clone(), d]; | |
| 324 | + } else if hdr.reset_frame_context == 2 { | |
| 325 | + self.frame_ctxs[0] = FrameContext::new(false); | |
| 326 | + } | |
| 327 | + // The parser forces frame_context_idx to 0 for an intra frame. | |
| 328 | + let mut ctx = self.frame_ctxs[0].clone(); | |
| 329 | + let stored_partition = ctx.partition; | |
| 330 | + ctx.use_key_partition(); | |
| 331 | + self.ctx = ctx; | |
| 332 | + self.prev_seg.clear(); | |
| 333 | + self.prev_mvs.clear(); | |
| 334 | + self.last = LastFrameFacts { | |
| 335 | + width: hdr.width, | |
| 336 | + height: hdr.height, | |
| 337 | + intra_only: true, | |
| 338 | + show_frame: hdr.show_frame, | |
| 339 | + key: false, | |
| 340 | + }; | |
| 341 | + let hdr_start = hdr.uncompressed_header_size as usize; | |
| 342 | + let ch = read_compressed_header( | |
| 343 | + &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize], | |
| 344 | + &mut self.ctx, | |
| 345 | + &hdr, | |
| 346 | + )?; | |
| 347 | + let pic = self.decode_keyframe(&hdr, frame, ch.tx_mode)?; | |
| 348 | + if hdr.refresh_frame_context { | |
| 349 | + // Store back with the partition probs the context arrived with: | |
| 350 | + // the const key table is not a `FRAME_CONTEXT` field. | |
| 351 | + self.ctx.partition = stored_partition; | |
| 352 | + self.frame_ctxs[0] = self.ctx.clone(); | |
| 353 | + } | |
| 354 | + // Reference refresh (spec 8.10): only `refresh_frame_flags` slots. | |
| 355 | + let frame = RefFrame { | |
| 356 | + planes: std::sync::Arc::new(self.planes.take().expect("frame scratch")), | |
| 357 | + width: hdr.width as u16, | |
| 358 | + height: hdr.height as u16, | |
| 359 | + }; | |
| 360 | + for slot in 0..8 { | |
| 361 | + if hdr.refresh_frame_flags & (1 << slot) != 0 { | |
| 362 | + self.refs[slot] = Some(frame.clone()); | |
| 363 | + } | |
| 364 | + } | |
| 365 | + Ok(if hdr.show_frame { Some(pic) } else { None }) | |
| 366 | + } | |
| 367 | + | |
| 298 | 368 | /// Parse one frame's syntax: keyframes decode through to pixels, inter |
| 299 | 369 | /// frames are parsed (headers, mode info, MVs) with no reconstruction and |
| 300 | 370 | /// no picture. `decode` still refuses inter frames. |
| @@ -318,10 +388,9 @@ impl Decoder { | ||
| 318 | 388 | // any inter-frame dump after it would be meaningless evidence. |
| 319 | 389 | self.decode_key_frame(&hdr, sub)?; |
| 320 | 390 | } else if hdr.intra_only { |
| 321 | - return Err(Error::unsupported( | |
| 322 | - "vp9 intra-only", | |
| 323 | - "the inter-syntax lane covers inter frames only", | |
| 324 | - )); | |
| 391 | + // Same body as a keyframe, but an inter frame that refreshes | |
| 392 | + // only the slots it names. | |
| 393 | + self.decode_intra_only_frame(&hdr, sub)?; | |
| 325 | 394 | } else { |
| 326 | 395 | self.decode_inter_frame(&hdr, sub, index, false)?; |
| 327 | 396 | } |
| @@ -356,28 +425,19 @@ impl Decoder { | ||
| 356 | 425 | |
| 357 | 426 | // Reference slots (spec 7.2): `ref_frame_idx[i]` names the slot LAST, |
| 358 | 427 | // GOLDEN and ALTREF use. libvpx validates every named reference's |
| 359 | - // format here (`vp9_decodeframe.c:1620-1627`) and SCALES a reference | |
| 360 | - // whose size differs; this lane refuses that by name. | |
| 428 | + // format here (`vp9_decodeframe.c:1620-1627`); a reference whose coded | |
| 429 | + // size differs from this frame's is SCALED during prediction | |
| 430 | + // (`vp9_setup_scale_factors_for_frame` per reference), not refused. | |
| 361 | 431 | if pixels { |
| 362 | 432 | for (i, name) in ["last", "golden", "altref"].iter().enumerate() { |
| 363 | 433 | let slot = hdr.ref_frame_idx[i] as usize; |
| 364 | 434 | if slot >= self.refs.len() || hdr.ref_frame_idx[i] >= 8 { |
| 365 | 435 | return Err(corrupt("vp9 inter names a reference slot past the DPB")); |
| 366 | 436 | } |
| 367 | - let Some(p) = self.refs[slot].as_ref() else { | |
| 437 | + if self.refs[slot].is_none() { | |
| 368 | 438 | return Err(Error::corrupt(format!( |
| 369 | 439 | "vp9 inter reference `{name}` names empty slot {slot}" |
| 370 | 440 | ))); |
| 371 | - }; | |
| 372 | - if p.width as u32 != hdr.width || p.height as u32 != hdr.height { | |
| 373 | - return Err(Error::unsupported( | |
| 374 | - "vp9 inter reference size change", | |
| 375 | - format!( | |
| 376 | - "reference `{name}` in slot {slot} is {}x{} but this frame is {}x{}; \ | |
| 377 | - reference-frame scaling is not ported", | |
| 378 | - p.width, p.height, hdr.width, hdr.height | |
| 379 | - ), | |
| 380 | - )); | |
| 381 | 441 | } |
| 382 | 442 | } |
| 383 | 443 | let width = hdr.width as usize; |
| @@ -897,8 +957,20 @@ impl Decoder { | ||
| 897 | 957 | let temp = &mut self.mc_temp; |
| 898 | 958 | for plane in 0..3usize { |
| 899 | 959 | inter_predict_plane( |
| 900 | - planes, refs, scratch, temp, hdr, info, plane, row, col, &n4w, &n4h, | |
| 901 | - mb_to_right, mb_to_bottom, sb_type, | |
| 960 | + planes, | |
| 961 | + refs, | |
| 962 | + scratch, | |
| 963 | + temp, | |
| 964 | + hdr, | |
| 965 | + info, | |
| 966 | + plane, | |
| 967 | + row, | |
| 968 | + col, | |
| 969 | + &n4w, | |
| 970 | + &n4h, | |
| 971 | + mb_to_right, | |
| 972 | + mb_to_bottom, | |
| 973 | + sb_type, | |
| 902 | 974 | )?; |
| 903 | 975 | } |
| 904 | 976 | } |
| @@ -1366,7 +1438,10 @@ impl Decoder { | ||
| 1366 | 1438 | let x_mis = bw.min(mi.mi_cols - col); |
| 1367 | 1439 | let y_mis = bh.min(mi.mi_rows - row); |
| 1368 | 1440 | |
| 1369 | - let info = if hdr.frame_type == FrameType::Key { | |
| 1441 | + // `frame_is_intra_only` (onyxc_int.h:363): a keyframe OR an | |
| 1442 | + // intra-only frame walks the intra mode-info path. | |
| 1443 | + let intra_frame = hdr.frame_type == FrameType::Key || hdr.intra_only; | |
| 1444 | + let info = if intra_frame { | |
| 1370 | 1445 | read_intra_frame_mode_info( |
| 1371 | 1446 | r, |
| 1372 | 1447 | mi, |
| @@ -1395,14 +1470,24 @@ impl Decoder { | ||
| 1395 | 1470 | tx_mode, |
| 1396 | 1471 | )? |
| 1397 | 1472 | }; |
| 1398 | - if hdr.frame_type != FrameType::Key { | |
| 1473 | + if !intra_frame { | |
| 1399 | 1474 | if pixels { |
| 1400 | 1475 | // Full inter decode: prediction, tokens, residual. The |
| 1401 | 1476 | // per-cell loop-filter level is the block's own reference and |
| 1402 | 1477 | // mode class (`get_filter_level`), so the grids are written |
| 1403 | 1478 | // inside the reconstruction rather than from `level_of_seg`. |
| 1404 | 1479 | self.reconstruct_inter_pixels( |
| 1405 | - r, ectx, grids, hdr, &info, row, col, sb_type, bw, bh, mi, | |
| 1480 | + r, | |
| 1481 | + ectx, | |
| 1482 | + grids, | |
| 1483 | + hdr, | |
| 1484 | + &info, | |
| 1485 | + row, | |
| 1486 | + col, | |
| 1487 | + sb_type, | |
| 1488 | + bw, | |
| 1489 | + bh, | |
| 1490 | + mi, | |
| 1406 | 1491 | tile_col_start, |
| 1407 | 1492 | )?; |
| 1408 | 1493 | } else { |
| @@ -1412,10 +1497,7 @@ impl Decoder { | ||
| 1412 | 1497 | } |
| 1413 | 1498 | for dy in 0..y_mis { |
| 1414 | 1499 | for dx in 0..x_mis { |
| 1415 | - if crate::mvdbg2_enabled() | |
| 1416 | - && row + dy == 7 | |
| 1417 | - && col + dx >= 30 | |
| 1418 | - && col + dx <= 40 | |
| 1500 | + if crate::mvdbg2_enabled() && row + dy == 7 && col + dx >= 30 && col + dx <= 40 | |
| 1419 | 1501 | { |
| 1420 | 1502 | eprintln!( |
| 1421 | 1503 | "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={}", |
| @@ -1837,7 +1919,9 @@ fn reset_skip_context( | ||
| 1837 | 1919 | let offx = (col << 1) >> s; |
| 1838 | 1920 | let offy = (row << 1) >> s; |
| 1839 | 1921 | let lrows = 32usize >> s; |
| 1840 | - let a: Vec<u8> = (0..n4w[plane]).map(|i| ectx[plane].above[offx + i]).collect(); | |
| 1922 | + let a: Vec<u8> = (0..n4w[plane]) | |
| 1923 | + .map(|i| ectx[plane].above[offx + i]) | |
| 1924 | + .collect(); | |
| 1841 | 1925 | let l: Vec<u8> = (0..n4h[plane].min(lrows)) |
| 1842 | 1926 | .map(|i| ectx[plane].left[(offy + i) % lrows]) |
| 1843 | 1927 | .collect(); |
| @@ -2032,6 +2116,26 @@ fn inter_predict_plane( | ||
| 2032 | 2116 | return Err(corrupt("vp9 inter prediction read an empty reference slot")); |
| 2033 | 2117 | }; |
| 2034 | 2118 | let (ref_data, ref_stride) = ref_frame.planes.plane_ref(plane); |
| 2119 | + // `vp9_setup_scale_factors_for_frame` (`vp9_decodeframe.c:2758`): the | |
| 2120 | + // scale from the REFERENCE's coded luma size to this frame's, shared | |
| 2121 | + // by every plane. `vp9_is_valid_scale` is enforced where libvpx | |
| 2122 | + // enforces it — at prediction time, for the references actually used. | |
| 2123 | + let sf = ScaleFactors::setup( | |
| 2124 | + ref_frame.width as usize, | |
| 2125 | + ref_frame.height as usize, | |
| 2126 | + hdr.width as usize, | |
| 2127 | + hdr.height as usize, | |
| 2128 | + ); | |
| 2129 | + if !sf.is_valid() { | |
| 2130 | + return Err(Error::unsupported( | |
| 2131 | + "vp9 reference scale", | |
| 2132 | + format!( | |
| 2133 | + "reference `{ref_name}` in slot {slot} is {}x{} against a {}x{} frame; \ | |
| 2134 | + `valid_ref_frame_size` rejects that ratio", | |
| 2135 | + ref_frame.width, ref_frame.height, hdr.width, hdr.height | |
| 2136 | + ), | |
| 2137 | + )); | |
| 2138 | + } | |
| 2035 | 2139 | let refp = RefPlane { |
| 2036 | 2140 | data: ref_data, |
| 2037 | 2141 | stride: ref_stride, |
| @@ -2059,9 +2163,8 @@ fn inter_predict_plane( | ||
| 2059 | 2163 | average_split_mvs_chroma(&info.bmi_mv, rf) |
| 2060 | 2164 | }; |
| 2061 | 2165 | let (data, _) = planes.plane(plane); |
| 2062 | - let dst_off = (((row * 8) >> s) + y * 4) * dst_stride | |
| 2063 | - + ((col * 8) >> s) | |
| 2064 | - + xx * 4; | |
| 2166 | + let dst_off = | |
| 2167 | + (((row * 8) >> s) + y * 4) * dst_stride + ((col * 8) >> s) + xx * 4; | |
| 2065 | 2168 | build_inter_predictors( |
| 2066 | 2169 | &mut data[dst_off..], |
| 2067 | 2170 | dst_stride, |
| @@ -2081,6 +2184,7 @@ fn inter_predict_plane( | ||
| 2081 | 2184 | ss_y, |
| 2082 | 2185 | kernel, |
| 2083 | 2186 | rf == 1, |
| 2187 | + &sf, | |
| 2084 | 2188 | scratch, |
| 2085 | 2189 | temp, |
| 2086 | 2190 | ); |
| @@ -2108,6 +2212,7 @@ fn inter_predict_plane( | ||
| 2108 | 2212 | ss_y, |
| 2109 | 2213 | kernel, |
| 2110 | 2214 | rf == 1, |
| 2215 | + &sf, | |
| 2111 | 2216 | scratch, |
| 2112 | 2217 | temp, |
| 2113 | 2218 | ); |
crates/ec-vp9/src/header.rsmodified+12 -0
| @@ -124,6 +124,18 @@ impl FrameContext { | ||
| 124 | 124 | pub(crate) fn reset_inter_partition(&mut self) { |
| 125 | 125 | self.partition = rows(&DEFAULT_PARTITION_PROBS); |
| 126 | 126 | } |
| 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 | + } | |
| 127 | 139 | } |
| 128 | 140 | |
| 129 | 141 | /// `inv_recenter_nonneg` (vp9_dsubexp.c). |
crates/ec-vp9/src/mc.rsmodified+261 -36
| @@ -8,9 +8,11 @@ | ||
| 8 | 8 | //! The VP9 decoder does NOT extend the reference frame's borders in place: it |
| 9 | 9 | //! builds a bordered copy of the block's reference window per prediction |
| 10 | 10 | //! (`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_*`). | |
| 14 | 16 | //! |
| 15 | 17 | //! Indexing note: libvpx's convolve helpers take a raw pointer and subtract |
| 16 | 18 | //! `SUBPEL_TAPS / 2 - 1` from it, so they read taps *before* the block's first |
| @@ -28,6 +30,93 @@ const FILTER_BITS: i32 = 7; | ||
| 28 | 30 | /// `VP9_INTERP_EXTEND` (`vpx_scale/yv12config.h:25`). |
| 29 | 31 | const INTERP_EXTEND: i32 = 4; |
| 30 | 32 | |
| 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 | + | |
| 31 | 120 | /// `vp9_filter_kernels` (`vp9/common/vp9_filter.c:79`), in libvpx's filter |
| 32 | 121 | /// numbering: 0 `EIGHTTAP`, 1 `EIGHTTAP_SMOOTH`, 2 `EIGHTTAP_SHARP`, |
| 33 | 122 | /// 3 `BILINEAR` (the 4-tap index 4 is unreachable for profile 0). |
| @@ -223,6 +312,9 @@ fn build_mc_border( | ||
| 223 | 312 | /// `convolve_horiz` / `convolve_avg_horiz` (`vpx_dsp/vpx_convolve.c:22`). |
| 224 | 313 | /// `origin` is the block's first sample in `buf`; taps are read from |
| 225 | 314 | /// `origin + y*stride + (x_q4 >> SUBPEL_BITS) - (SUBPEL_TAPS / 2 - 1) + k`. |
| 315 | +/// `x_step` advances `x_q4` per output sample — `SUBPEL_SHIFTS` for an | |
| 316 | +/// unscaled reference, `sf->x_step_q4` (the scaled sampler, also used by | |
| 317 | +/// `vpx_scaled_horiz`) otherwise. | |
| 226 | 318 | #[allow(clippy::too_many_arguments)] |
| 227 | 319 | fn convolve_horiz( |
| 228 | 320 | buf: &[u8], |
| @@ -232,6 +324,7 @@ fn convolve_horiz( | ||
| 232 | 324 | dst_stride: usize, |
| 233 | 325 | f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize], |
| 234 | 326 | x0_q4: i32, |
| 327 | + x_step: i32, | |
| 235 | 328 | w: usize, |
| 236 | 329 | rows: usize, |
| 237 | 330 | avg: bool, |
| @@ -253,12 +346,15 @@ fn convolve_horiz( | ||
| 253 | 346 | } else { |
| 254 | 347 | v as u8 |
| 255 | 348 | }; |
| 256 | - x_q4 += SUBPEL_SHIFTS; | |
| 349 | + x_q4 += x_step; | |
| 257 | 350 | } |
| 258 | 351 | } |
| 259 | 352 | } |
| 260 | 353 | |
| 261 | 354 | /// `convolve_vert` / `convolve_avg_vert` (`vpx_dsp/vpx_convolve.c:80`). |
| 355 | +/// `y_step` advances `y_q4` per output sample (`SUBPEL_SHIFTS` unscaled, | |
| 356 | +/// `sf->y_step_q4` for `vpx_scaled_vert`). | |
| 357 | +#[allow(clippy::too_many_arguments)] | |
| 262 | 358 | fn convolve_vert( |
| 263 | 359 | buf: &[u8], |
| 264 | 360 | stride: usize, |
| @@ -267,6 +363,7 @@ fn convolve_vert( | ||
| 267 | 363 | dst_stride: usize, |
| 268 | 364 | f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize], |
| 269 | 365 | y0_q4: i32, |
| 366 | + y_step: i32, | |
| 270 | 367 | w: usize, |
| 271 | 368 | h: usize, |
| 272 | 369 | avg: bool, |
| @@ -289,15 +386,18 @@ fn convolve_vert( | ||
| 289 | 386 | } else { |
| 290 | 387 | v as u8 |
| 291 | 388 | }; |
| 292 | - y_q4 += SUBPEL_SHIFTS; | |
| 389 | + y_q4 += y_step; | |
| 293 | 390 | } |
| 294 | 391 | } |
| 295 | 392 | } |
| 296 | 393 | |
| 297 | 394 | /// `inter_predictor` + `sf->predict` (`vp9/common/vp9_reconinter.h:23`, |
| 298 | -/// `vp9/common/vp9_scale.c:79`): for the unscaled case `predict[0][0]` is | |
| 299 | -/// copy/avg, `predict[0][1][*]` the vertical kernel, `predict[1][0][*]` the | |
| 300 | -/// horizontal one and `predict[1][1][*]` the 2D convolve. | |
| 395 | +/// `vp9/common/vp9_scale.c:79`): the kernel is picked by | |
| 396 | +/// `predict[subpel_x != 0][subpel_y != 0][avg]`. Unscaled that is | |
| 397 | +/// copy/avg, the vertical, the horizontal and the 2D convolve; with a scaled | |
| 398 | +/// reference the table collapses to the scaled variants (`vpx_scaled_horiz` / | |
| 399 | +/// `vpx_scaled_vert` — the same walk with `x_step_q4` / `y_step_q4` — and | |
| 400 | +/// `vpx_scaled_2d`), reproduced here by the step-aware convolve helpers. | |
| 301 | 401 | /// |
| 302 | 402 | /// `w` x `h` output samples written at `dst`; `buf`/`origin` locate the |
| 303 | 403 | /// block's first reference sample. `temp` is the `vpx_convolve8` intermediate |
| @@ -313,11 +413,37 @@ fn inter_predictor( | ||
| 313 | 413 | f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize], |
| 314 | 414 | subpel_x: i32, |
| 315 | 415 | subpel_y: i32, |
| 416 | + x_step: i32, | |
| 417 | + y_step: i32, | |
| 316 | 418 | w: usize, |
| 317 | 419 | h: usize, |
| 318 | 420 | avg: bool, |
| 319 | 421 | temp: &mut [u8], |
| 320 | 422 | ) { |
| 423 | + let scaled_x = x_step != SUBPEL_SHIFTS; | |
| 424 | + let scaled_y = y_step != SUBPEL_SHIFTS; | |
| 425 | + if scaled_x || scaled_y { | |
| 426 | + // sf->predict with a scaled axis (vp9_scale.c:79-110): an unscaled | |
| 427 | + // axis keeps its 1D kernel only when the other axis has no subpel | |
| 428 | + // offset; anything else is the 2D scaled convolve. | |
| 429 | + if !scaled_x && subpel_x == 0 { | |
| 430 | + convolve_vert( | |
| 431 | + buf, stride, origin, dst, dst_stride, f, subpel_y, y_step, w, h, avg, | |
| 432 | + ); | |
| 433 | + return; | |
| 434 | + } | |
| 435 | + if !scaled_y && subpel_y == 0 { | |
| 436 | + convolve_horiz( | |
| 437 | + buf, stride, origin, dst, dst_stride, f, subpel_x, x_step, w, h, avg, | |
| 438 | + ); | |
| 439 | + return; | |
| 440 | + } | |
| 441 | + convolve_2d( | |
| 442 | + buf, stride, origin, dst, dst_stride, f, subpel_x, subpel_y, x_step, y_step, w, h, avg, | |
| 443 | + temp, | |
| 444 | + ); | |
| 445 | + return; | |
| 446 | + } | |
| 321 | 447 | if subpel_x == 0 && subpel_y == 0 { |
| 322 | 448 | for y in 0..h { |
| 323 | 449 | for x in 0..w { |
| @@ -333,20 +459,67 @@ fn inter_predictor( | ||
| 333 | 459 | return; |
| 334 | 460 | } |
| 335 | 461 | if subpel_y == 0 { |
| 336 | - convolve_horiz(buf, stride, origin, dst, dst_stride, f, subpel_x, w, h, avg); | |
| 462 | + convolve_horiz( | |
| 463 | + buf, | |
| 464 | + stride, | |
| 465 | + origin, | |
| 466 | + dst, | |
| 467 | + dst_stride, | |
| 468 | + f, | |
| 469 | + subpel_x, | |
| 470 | + SUBPEL_SHIFTS, | |
| 471 | + w, | |
| 472 | + h, | |
| 473 | + avg, | |
| 474 | + ); | |
| 337 | 475 | return; |
| 338 | 476 | } |
| 339 | 477 | if subpel_x == 0 { |
| 340 | - convolve_vert(buf, stride, origin, dst, dst_stride, f, subpel_y, w, h, avg); | |
| 478 | + convolve_vert( | |
| 479 | + buf, | |
| 480 | + stride, | |
| 481 | + origin, | |
| 482 | + dst, | |
| 483 | + dst_stride, | |
| 484 | + f, | |
| 485 | + subpel_y, | |
| 486 | + SUBPEL_SHIFTS, | |
| 487 | + w, | |
| 488 | + h, | |
| 489 | + avg, | |
| 490 | + ); | |
| 341 | 491 | return; |
| 342 | 492 | } |
| 343 | - // vpx_convolve8_c: horizontal pass into a stride-64 intermediate with | |
| 344 | - // `intermediate_height = (((h - 1) * y_step_q4 + y0_q4) >> SUBPEL_BITS) + | |
| 345 | - // SUBPEL_TAPS` — for the unscaled `y_step_q4 = 16` that is `h + SUBPEL_TAPS | |
| 346 | - // - 1`. The horizontal pass starts `SUBPEL_TAPS / 2 - 1` rows ABOVE the | |
| 347 | - // block (C passes `src - src_stride * (SUBPEL_TAPS / 2 - 1)`). | |
| 348 | - let intermediate_height = | |
| 349 | - (((h as i32 - 1) * SUBPEL_SHIFTS + subpel_y) >> SUBPEL_BITS) as usize + TAPS; | |
| 493 | + convolve_2d( | |
| 494 | + buf, stride, origin, dst, dst_stride, f, subpel_x, subpel_y, x_step, y_step, w, h, avg, | |
| 495 | + temp, | |
| 496 | + ); | |
| 497 | +} | |
| 498 | + | |
| 499 | +/// `vpx_convolve8_c` / `vpx_convolve8_avg_c` (`vpx_dsp/vpx_convolve.c:158`) = | |
| 500 | +/// `vpx_scaled_2d` / `vpx_scaled_avg_2d`: horizontal pass into a stride-64 | |
| 501 | +/// intermediate with `intermediate_height = (((h - 1) * y_step_q4 + y0_q4) >> | |
| 502 | +/// SUBPEL_BITS) + SUBPEL_TAPS`, then the vertical pass. The horizontal pass | |
| 503 | +/// starts `SUBPEL_TAPS / 2 - 1` rows ABOVE the block (C passes | |
| 504 | +/// `src - src_stride * (SUBPEL_TAPS / 2 - 1)`). | |
| 505 | +#[allow(clippy::too_many_arguments)] | |
| 506 | +fn convolve_2d( | |
| 507 | + buf: &[u8], | |
| 508 | + stride: usize, | |
| 509 | + origin: isize, | |
| 510 | + dst: &mut [u8], | |
| 511 | + dst_stride: usize, | |
| 512 | + f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize], | |
| 513 | + subpel_x: i32, | |
| 514 | + subpel_y: i32, | |
| 515 | + x_step: i32, | |
| 516 | + y_step: i32, | |
| 517 | + w: usize, | |
| 518 | + h: usize, | |
| 519 | + avg: bool, | |
| 520 | + temp: &mut [u8], | |
| 521 | +) { | |
| 522 | + let intermediate_height = (((h as i32 - 1) * y_step + subpel_y) >> SUBPEL_BITS) as usize + TAPS; | |
| 350 | 523 | let temp_origin = (TAPS as isize / 2 - 1) * 64; |
| 351 | 524 | convolve_horiz( |
| 352 | 525 | buf, |
| @@ -356,6 +529,7 @@ fn inter_predictor( | ||
| 356 | 529 | 64, |
| 357 | 530 | f, |
| 358 | 531 | subpel_x, |
| 532 | + x_step, | |
| 359 | 533 | w, |
| 360 | 534 | intermediate_height, |
| 361 | 535 | false, |
| @@ -366,7 +540,19 @@ fn inter_predictor( | ||
| 366 | 540 | // `temp[..64 * 135]` is the horizontal intermediate; the region after |
| 367 | 541 | // it is the 2D result. |
| 368 | 542 | let (horiz, mid2) = temp.split_at_mut(64 * 135); |
| 369 | - convolve_vert(horiz, 64, temp_origin, mid2, w, f, subpel_y, w, h, false); | |
| 543 | + convolve_vert( | |
| 544 | + horiz, | |
| 545 | + 64, | |
| 546 | + temp_origin, | |
| 547 | + mid2, | |
| 548 | + w, | |
| 549 | + f, | |
| 550 | + subpel_y, | |
| 551 | + y_step, | |
| 552 | + w, | |
| 553 | + h, | |
| 554 | + false, | |
| 555 | + ); | |
| 370 | 556 | for y in 0..h { |
| 371 | 557 | for x in 0..w { |
| 372 | 558 | let d = y * dst_stride + x; |
| @@ -383,6 +569,7 @@ fn inter_predictor( | ||
| 383 | 569 | dst_stride, |
| 384 | 570 | f, |
| 385 | 571 | subpel_y, |
| 572 | + y_step, | |
| 386 | 573 | w, |
| 387 | 574 | h, |
| 388 | 575 | false, |
| @@ -402,9 +589,12 @@ pub(crate) struct RefPlane<'a> { | ||
| 402 | 589 | pub height: usize, |
| 403 | 590 | } |
| 404 | 591 | |
| 405 | -/// `dec_build_inter_predictors` (`vp9/decoder/vp9_decodeframe.c:593`), | |
| 406 | -/// unscaled: predict one `w` x `h` plane block whose top-left is plane pixel | |
| 407 | -/// `(x, y)` inside the block at MI `(mi_row, mi_col)`. | |
| 592 | +/// `dec_build_inter_predictors` (`vp9/decoder/vp9_decodeframe.c:593`): | |
| 593 | +/// predict one `w` x `h` plane block whose top-left is plane pixel `(x, y)` | |
| 594 | +/// inside the block at MI `(mi_row, mi_col)`. `sf` is the reference's scale | |
| 595 | +/// factors; when they scale, the block is mapped into the reference frame | |
| 596 | +/// (`scale_value_x/y`), the MV is scaled with it (`vp9_scale_mv`) and the | |
| 597 | +/// convolve steps by `x_step_q4` / `y_step_q4`. | |
| 408 | 598 | #[allow(clippy::too_many_arguments)] |
| 409 | 599 | pub(crate) fn build_inter_predictors( |
| 410 | 600 | dst: &mut [u8], |
| @@ -425,50 +615,81 @@ pub(crate) fn build_inter_predictors( | ||
| 425 | 615 | ss_y: usize, |
| 426 | 616 | kernel: usize, |
| 427 | 617 | avg: bool, |
| 618 | + sf: &ScaleFactors, | |
| 428 | 619 | scratch: &mut Vec<u8>, |
| 429 | 620 | temp: &mut Vec<u8>, |
| 430 | 621 | ) { |
| 622 | + let is_scaled = sf.is_scaled(); | |
| 431 | 623 | let mv_q4 = clamp_mv_to_umv_border_sb( |
| 432 | 624 | mv, w as i32, h as i32, mb_left, mb_right, mb_top, mb_bottom, ss_x, ss_y, |
| 433 | 625 | ); |
| 434 | 626 | |
| 435 | 627 | // Co-ordinate of the containing block, pixel precision, plus the |
| 436 | 628 | // block-relative offset (`x`, `y`). |
| 437 | - let x0_pre = (-mb_left >> (3 + ss_x)) + x as i32; | |
| 438 | - let y0_pre = (-mb_top >> (3 + ss_y)) + y as i32; | |
| 439 | - let x0_16 = (x0_pre << SUBPEL_BITS) + mv_q4.1; | |
| 440 | - let y0_16 = (y0_pre << SUBPEL_BITS) + mv_q4.0; | |
| 441 | - let subpel_x = mv_q4.1 & SUBPEL_MASK; | |
| 442 | - let subpel_y = mv_q4.0 & SUBPEL_MASK; | |
| 629 | + let x_pre = (-mb_left >> (3 + ss_x)) + x as i32; | |
| 630 | + let y_pre = (-mb_top >> (3 + ss_y)) + y as i32; | |
| 631 | + let (x_step, y_step, scaled_mv); | |
| 632 | + let (x0_16, y0_16, x0_pre, y0_pre); | |
| 633 | + if is_scaled { | |
| 634 | + // The block is mapped into the reference frame at 1/16-pel (the | |
| 635 | + // `x0_16` used for the border extent) and at pixel precision (`x0`, | |
| 636 | + // which shifts by the scaled MV's integer part below). | |
| 637 | + let x0 = sf.scale_x(x_pre); | |
| 638 | + let y0 = sf.scale_y(y_pre); | |
| 639 | + scaled_mv = sf.scale_mv( | |
| 640 | + mv_q4, | |
| 641 | + mi_col as i32 * 8 + x as i32, | |
| 642 | + mi_row as i32 * 8 + y as i32, | |
| 643 | + ); | |
| 644 | + x_step = sf.x_step_q4; | |
| 645 | + y_step = sf.y_step_q4; | |
| 646 | + x0_16 = sf.scale_x(x_pre << SUBPEL_BITS) + scaled_mv.1; | |
| 647 | + y0_16 = sf.scale_y(y_pre << SUBPEL_BITS) + scaled_mv.0; | |
| 648 | + x0_pre = x0; | |
| 649 | + y0_pre = y0; | |
| 650 | + } else { | |
| 651 | + scaled_mv = mv_q4; | |
| 652 | + x_step = SUBPEL_SHIFTS; | |
| 653 | + y_step = SUBPEL_SHIFTS; | |
| 654 | + x0_16 = (x_pre << SUBPEL_BITS) + scaled_mv.1; | |
| 655 | + y0_16 = (y_pre << SUBPEL_BITS) + scaled_mv.0; | |
| 656 | + x0_pre = x_pre; | |
| 657 | + y0_pre = y_pre; | |
| 658 | + } | |
| 659 | + let subpel_x = scaled_mv.1 & SUBPEL_MASK; | |
| 660 | + let subpel_y = scaled_mv.0 & SUBPEL_MASK; | |
| 443 | 661 | |
| 444 | 662 | let frame_width = refp.width as i32; |
| 445 | 663 | let frame_height = refp.height as i32; |
| 446 | 664 | // `buf_ptr = ref_frame + y0 * stride + x0` is taken AFTER the MV integer |
| 447 | 665 | // part but BEFORE the tap padding below, so the direct read keeps its own |
| 448 | 666 | // copy of the coordinates. |
| 449 | - let x0_mv = x0_pre + (mv_q4.1 >> SUBPEL_BITS); | |
| 450 | - let y0_mv = y0_pre + (mv_q4.0 >> SUBPEL_BITS); | |
| 667 | + let x0_mv = x0_pre + (scaled_mv.1 >> SUBPEL_BITS); | |
| 668 | + let y0_mv = y0_pre + (scaled_mv.0 >> SUBPEL_BITS); | |
| 451 | 669 | let mut x0 = x0_mv; |
| 452 | 670 | let mut y0 = y0_mv; |
| 453 | 671 | |
| 454 | 672 | let f = &FILTERS[kernel]; |
| 455 | - let _ = mi_col; | |
| 456 | - let _ = mi_row; | |
| 457 | 673 | |
| 458 | 674 | // `is_scaled || scaled_mv.col || scaled_mv.row || (frame_width & 7) || |
| 459 | 675 | // (frame_height & 7)`: the border copy is skipped only when the window is |
| 460 | 676 | // provably inside the frame. |
| 461 | - if mv_q4.1 != 0 || mv_q4.0 != 0 || (frame_width & 7) != 0 || (frame_height & 7) != 0 { | |
| 462 | - let mut x1 = ((x0_16 + (w as i32 - 1) * SUBPEL_SHIFTS) >> SUBPEL_BITS) + 1; | |
| 463 | - let mut y1 = ((y0_16 + (h as i32 - 1) * SUBPEL_SHIFTS) >> SUBPEL_BITS) + 1; | |
| 677 | + if is_scaled | |
| 678 | + || scaled_mv.1 != 0 | |
| 679 | + || scaled_mv.0 != 0 | |
| 680 | + || (frame_width & 7) != 0 | |
| 681 | + || (frame_height & 7) != 0 | |
| 682 | + { | |
| 683 | + let mut x1 = ((x0_16 + (w as i32 - 1) * x_step) >> SUBPEL_BITS) + 1; | |
| 684 | + let mut y1 = ((y0_16 + (h as i32 - 1) * y_step) >> SUBPEL_BITS) + 1; | |
| 464 | 685 | let mut x_pad = false; |
| 465 | 686 | let mut y_pad = false; |
| 466 | - if subpel_x != 0 { | |
| 687 | + if subpel_x != 0 || x_step != SUBPEL_SHIFTS { | |
| 467 | 688 | x0 -= INTERP_EXTEND - 1; |
| 468 | 689 | x1 += INTERP_EXTEND; |
| 469 | 690 | x_pad = true; |
| 470 | 691 | } |
| 471 | - if subpel_y != 0 { | |
| 692 | + if subpel_y != 0 || y_step != SUBPEL_SHIFTS { | |
| 472 | 693 | y0 -= INTERP_EXTEND - 1; |
| 473 | 694 | y1 += INTERP_EXTEND; |
| 474 | 695 | y_pad = true; |
| @@ -507,6 +728,8 @@ pub(crate) fn build_inter_predictors( | ||
| 507 | 728 | f, |
| 508 | 729 | subpel_x, |
| 509 | 730 | subpel_y, |
| 731 | + x_step, | |
| 732 | + y_step, | |
| 510 | 733 | w, |
| 511 | 734 | h, |
| 512 | 735 | avg, |
| @@ -528,6 +751,8 @@ pub(crate) fn build_inter_predictors( | ||
| 528 | 751 | f, |
| 529 | 752 | subpel_x, |
| 530 | 753 | subpel_y, |
| 754 | + x_step, | |
| 755 | + y_step, | |
| 531 | 756 | w, |
| 532 | 757 | h, |
| 533 | 758 | 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_from_slice(&pic.y); | |
| 81 | + got.extend_from_slice(&pic.u); | |
| 82 | + got.extend_from_slice(&pic.v); | |
| 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+171 -0
| @@ -0,0 +1,171 @@ | ||
| 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 crashes outright on a changing filter | |
| 14 | +//! output), and a hand-spliced explicit-size inter frame trips libvpx's own | |
| 15 | +//! header reparsing. The generator is recorded in | |
| 16 | +//! `lanes/vp9refsetup.report.md`: a 1280x720 one-pass CBR encode at 200 kbps, | |
| 17 | +//! whose `vp9_resize_one_pass_cbr` downscales frame 1 to 640x360 against the | |
| 18 | +//! keyframe. | |
| 19 | +//! | |
| 20 | +//! Oracle caveat: ffmpeg locks its rawvideo output size to the FIRST decoded | |
| 21 | +//! frame's, so a two-size stream cannot be dumped in one pass. Frame 0 is | |
| 22 | +//! decoded on its own (`-frames:v 1`, identity); frames 2..N are decoded with | |
| 23 | +//! `select=gte(n,1)` at the small size, where the filtergraph has | |
| 24 | +//! re-initialised and every frame passes through unchanged. The size-change | |
| 25 | +//! frame (file frame 1) is the one ffmpeg mangles during that | |
| 26 | +//! re-initialisation, so it is checked INDIRECTLY: every later frame predicts | |
| 27 | +//! from its reconstruction, so a wrong scaler fails frames 2..N. | |
| 28 | + | |
| 29 | +mod ivf; | |
| 30 | + | |
| 31 | +use ec_vp9::decode::Decoder; | |
| 32 | +use ec_vp9_syntax::{FrameType, Vp9Parser}; | |
| 33 | + | |
| 34 | +fn fixture(name: &str) -> std::path::PathBuf { | |
| 35 | + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) | |
| 36 | + .join("tests/data") | |
| 37 | + .join(name) | |
| 38 | +} | |
| 39 | + | |
| 40 | +/// Run ffmpeg over `path` with `args` and return its rawvideo stdout. | |
| 41 | +fn ffmpeg_raw(path: &std::path::Path, args: &[&str]) -> Vec<u8> { | |
| 42 | + let out = std::process::Command::new("ffmpeg") | |
| 43 | + .args(["-v", "error", "-y", "-i"]) | |
| 44 | + .arg(path) | |
| 45 | + .args(args) | |
| 46 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) | |
| 47 | + .output() | |
| 48 | + .expect("ffmpeg on PATH"); | |
| 49 | + assert!(out.status.success(), "ffmpeg decode failed: {out:?}"); | |
| 50 | + out.stdout | |
| 51 | +} | |
| 52 | + | |
| 53 | +fn frame_bytes(w: usize, h: usize) -> usize { | |
| 54 | + w * h + 2 * w.div_ceil(2) * h.div_ceil(2) | |
| 55 | +} | |
| 56 | + | |
| 57 | +fn assert_planes(pic: &ec_vp9::decode::Picture, want: &[u8], label: &str) { | |
| 58 | + let mut got = Vec::with_capacity(want.len()); | |
| 59 | + got.extend_from_slice(&pic.y); | |
| 60 | + got.extend_from_slice(&pic.u); | |
| 61 | + got.extend_from_slice(&pic.v); | |
| 62 | + assert_eq!(got.len(), want.len(), "{label}: plane size"); | |
| 63 | + let diff = got.iter().zip(want).position(|(a, b)| a != b); | |
| 64 | + assert!( | |
| 65 | + diff.is_none(), | |
| 66 | + "{label}: pixel mismatch at byte {:?} (ours {} libvpx {})", | |
| 67 | + diff, | |
| 68 | + diff.map(|d| got[d]).unwrap_or(0), | |
| 69 | + diff.map(|d| want[d]).unwrap_or(0) | |
| 70 | + ); | |
| 71 | +} | |
| 72 | + | |
| 73 | +fn check(name: &str) { | |
| 74 | + let path = fixture(name); | |
| 75 | + let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); | |
| 76 | + let (_, cw, ch, frames) = ivf::parse_ivf(&bytes); | |
| 77 | + | |
| 78 | + // Non-vacuity: the stream must carry an inter frame whose coded size | |
| 79 | + // differs from the frame before it — the only shape that makes a | |
| 80 | + // reference scale. | |
| 81 | + let mut parser = Vp9Parser::new(); | |
| 82 | + let mut sizes: Vec<(u32, u32, FrameType)> = Vec::new(); | |
| 83 | + for f in &frames { | |
| 84 | + for sub in ec_vp9_syntax::split(&f.data).unwrap() { | |
| 85 | + let hdr = parser.parse_frame(sub).unwrap(); | |
| 86 | + sizes.push((hdr.width, hdr.height, hdr.frame_type)); | |
| 87 | + } | |
| 88 | + } | |
| 89 | + let changed = sizes | |
| 90 | + .windows(2) | |
| 91 | + .filter(|p| p[0].0 != p[1].0 || p[0].1 != p[1].1) | |
| 92 | + .count(); | |
| 93 | + assert!( | |
| 94 | + changed >= 1, | |
| 95 | + "{name}: the fixture must change coded size mid-stream (sizes: {sizes:?})" | |
| 96 | + ); | |
| 97 | + assert!( | |
| 98 | + sizes | |
| 99 | + .iter() | |
| 100 | + .any(|s| s.2 == FrameType::Inter && (s.0, s.1) != (cw as u32, ch as u32)), | |
| 101 | + "{name}: an inter frame must differ from the container's declared size" | |
| 102 | + ); | |
| 103 | + | |
| 104 | + let mut decoder = Decoder::new(); | |
| 105 | + let ours: Vec<_> = frames | |
| 106 | + .iter() | |
| 107 | + .map(|f| decoder.decode(&f.data).expect("frame decodes")) | |
| 108 | + .collect(); | |
| 109 | + let shown: Vec<_> = ours.iter().filter_map(|p| p.as_ref()).collect(); | |
| 110 | + assert_eq!(shown.len(), 10, "{name}: the fixture has 10 visible frames"); | |
| 111 | + | |
| 112 | + // Frame 0 (the keyframe) alone; identity. | |
| 113 | + let oracle0 = ffmpeg_raw(&path, &["-frames:v", "1"]); | |
| 114 | + assert_eq!( | |
| 115 | + oracle0.len(), | |
| 116 | + frame_bytes(shown[0].width as usize, shown[0].height as usize), | |
| 117 | + "{name}: frame 0 oracle size" | |
| 118 | + ); | |
| 119 | + assert_planes(shown[0], &oracle0, &format!("{name} frame 0")); | |
| 120 | + | |
| 121 | + // Frames 2..N: after the size change every frame passes through the | |
| 122 | + // filtergraph unchanged at the small size. | |
| 123 | + let small = (shown[2].width as usize, shown[2].height as usize); | |
| 124 | + assert!( | |
| 125 | + small != (shown[0].width as usize, shown[0].height as usize), | |
| 126 | + "{name}: frames after the change must be resized" | |
| 127 | + ); | |
| 128 | + let oracle_rest = ffmpeg_raw( | |
| 129 | + &path, | |
| 130 | + &[ | |
| 131 | + "-vf", | |
| 132 | + "select=gte(n\\,1)", | |
| 133 | + "-fps_mode", | |
| 134 | + "passthrough", | |
| 135 | + "-s", | |
| 136 | + &format!("{}x{}", small.0, small.1), | |
| 137 | + ], | |
| 138 | + ); | |
| 139 | + let fbs = frame_bytes(small.0, small.1); | |
| 140 | + assert_eq!( | |
| 141 | + oracle_rest.len(), | |
| 142 | + fbs * (shown.len() - 2), | |
| 143 | + "{name}: ffmpeg must emit frames 2..{}", | |
| 144 | + shown.len() - 1 | |
| 145 | + ); | |
| 146 | + for (j, pic) in shown[2..].iter().enumerate() { | |
| 147 | + assert_eq!( | |
| 148 | + (pic.width as usize, pic.height as usize), | |
| 149 | + small, | |
| 150 | + "{name}: frame {} size", | |
| 151 | + j + 2 | |
| 152 | + ); | |
| 153 | + assert_planes( | |
| 154 | + pic, | |
| 155 | + &oracle_rest[j * fbs..(j + 1) * fbs], | |
| 156 | + &format!("{name} frame {}", j + 2), | |
| 157 | + ); | |
| 158 | + } | |
| 159 | +} | |
| 160 | + | |
| 161 | +#[test] | |
| 162 | +fn size_changing_reference_decodes_byte_exact() { | |
| 163 | + check("scaledref.ivf"); | |
| 164 | +} | |
| 165 | + | |
| 166 | +/// The same size change with an ODD coded reference: 1279x719 -> 640x360, | |
| 167 | +/// where the reference's chroma crop ceils (`(1279 + 1) / 2`). | |
| 168 | +#[test] | |
| 169 | +fn size_changing_odd_reference_decodes_byte_exact() { | |
| 170 | + check("scaledref_odd.ivf"); | |
| 171 | +} |
lanes/vp9refsetup.report.mdadded+164 -0
| @@ -0,0 +1,164 @@ | ||
| 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 its filtergraph SIGSEGVs (exit 139) on a | |
| 68 | + changing output size. Generated by `lanes/vp9refsetup/gen_scaledref.c` | |
| 69 | + (links the pristine libvpx 1.15.0 encoder): | |
| 70 | + ``` | |
| 71 | + gcc -I<libvpx> -I<libvpx>/vpx gen_scaledref.c <libvpx>/libvpx.a -o enc -lm -lpthread | |
| 72 | + ./enc scaledref.ivf 1280 720 10 200 # one-pass CBR, 200 kbps, lag 0 | |
| 73 | + ``` | |
| 74 | + libvpx's force-downsize rule (`>= 1280x720` input and | |
| 75 | + `avg_frame_bandwidth < 300000/30`) downscales frame 1 to 640x360 against the | |
| 76 | + 1280x720 keyframe — a genuine 2x reference scale (`x_step_q4 == 32`). | |
| 77 | +* **odd variant**: `scaledref_odd.ivf` is `scaledref.ivf` with the keyframe's | |
| 78 | + size fields patched 1280x720 -> 1279x719 (mi-grid invariant, so the tile data | |
| 79 | + stays valid) — the reference is then an odd coded extent and its chroma crop | |
| 80 | + ceils. Patch with the existing | |
| 81 | + `$HOME/.cache/vp9pix/patch_kf_size.py <in> <out> 1279 719`. | |
| 82 | + | |
| 83 | +## Gates | |
| 84 | + | |
| 85 | +`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9ref` | |
| 86 | + | |
| 87 | +1. **Suite**: `cargo test -p ec-vp9` — every binary green, **0 failed**, | |
| 88 | + 0 ignored. Warning parity: exactly the 5 pre-existing (`TM_PRED`, | |
| 89 | + `read_partition`, `partition_probs`, `x_mis`, `y_mis`). | |
| 90 | +2. **New witnesses** (byte-exact vs ffmpeg's libvpx-backed rawvideo): | |
| 91 | + * `intra_only_frame_and_its_successors_match_ffmpeg` — 10/10 shown frames | |
| 92 | + identical; the fixture is asserted to carry exactly one intra-only frame. | |
| 93 | + * `size_changing_reference_decodes_byte_exact` — 10/10 identical. | |
| 94 | + * `size_changing_odd_reference_decodes_byte_exact` — 10/10 identical. | |
| 95 | +3. **Crate-level oracle** (my dump vs libvpx's `drv_pix3`, per-shown-frame | |
| 96 | + native dims + ceil chroma, compared with `cmp`): | |
| 97 | + `scaledref.ivf` **IDENTICAL** (4,492,800 bytes, 10 frames); | |
| 98 | + `scaledref_odd.ivf` **IDENTICAL** (4,490,801 bytes, 10 frames); | |
| 99 | + `intraonly.ivf` **IDENTICAL** via drv_pix (all 10 output frames match the | |
| 100 | + source GOP's, i.e. the intra-only frame reconstructs exactly like the | |
| 101 | + keyframe it replaced). | |
| 102 | +4. **Fail-pre-fix** (throwaway base worktree at `79984549`, tests+fixtures | |
| 103 | + copied in, private target dir): | |
| 104 | + * intra-only: `Unsupported { what: "vp9 intra-only", why: "this lane decodes | |
| 105 | + inter frames and keyframes only" }` at `intraonly_exact.rs:72`. | |
| 106 | + * scaled: `Unsupported { what: "vp9 inter reference size change", why: | |
| 107 | + "reference `last` in slot 0 is 1280x720 but this frame is 640x360; | |
| 108 | + reference-frame scaling is not ported" }` (and the 1279x719 twin) at | |
| 109 | + `scaledref_exact.rs:107`. | |
| 110 | +5. **Regression corpus** (`$HOME/.cache/vp9ref-sweep.sh` = `drv_pix3` vs | |
| 111 | + `scratch_pixdump`, byte `cmp`) — all **IDENTICAL**: | |
| 112 | + | |
| 113 | +| stream | oracle frames | bytes | | |
| 114 | +| --- | --- | --- | | |
| 115 | +| `vp9-1080p-23.976-8bit.ivf` | 48 | 149,299,200 | | |
| 116 | +| `vp9-1080p-60-8bit.ivf` (120 frames, the frame-72 witness) | 120 | 373,248,000 | | |
| 117 | +| `vp9-2160p-23.976-8bit.ivf` | 48 | 597,196,800 | | |
| 118 | +| `vp9-tiles-1280.ivf` | 30 | 41,472,000 | | |
| 119 | +| `vp9-superframe-altref.ivf` | 60 | 6,912,000 | | |
| 120 | +| `$HOME/.cache/vp9pix/inter.ivf` | 3 | 9,331,200 | | |
| 121 | +| `$HOME/.cache/vp9pix/inter1.ivf` | 3 | 9,331,200 | | |
| 122 | +| odd testsrc2 321x241 (322x242 encode + `patch_kf_size.py`) | 12 | 1,395,876 | | |
| 123 | + | |
| 124 | +6. **Interaction (size change x odd dims)**: `scaledref_odd.ivf` covers it — | |
| 125 | + the scaled reference is an odd extent (1279x719, chroma `(w+1)/2`) and the | |
| 126 | + result is byte-identical to libvpx. Not deferred. | |
| 127 | + | |
| 128 | +## Oracle caveat (why the committed tests skip frame 1) | |
| 129 | + | |
| 130 | +ffmpeg locks its rawvideo output size to the FIRST decoded frame's, so a | |
| 131 | +two-size stream cannot be dumped in one pass: frames 1..N come out upscaled to | |
| 132 | +1280x720. The tests decode frame 0 alone (`-frames:v 1`, identity) and frames | |
| 133 | +2..N with `select=gte(n,1)` at the small size, where the filtergraph has | |
| 134 | +re-initialised and every frame passes through unchanged. The size-change frame | |
| 135 | +(file frame 1) is the one ffmpeg mangles during that re-initialisation, so it | |
| 136 | +is covered INDIRECTLY: every later frame predicts from its reconstruction (a | |
| 137 | +wrong scaler fails frames 2..N). Frame 1 itself is covered directly by the | |
| 138 | +crate-level `drv_pix3` comparison in gate 3. | |
| 139 | + | |
| 140 | +## Deferred / accepted | |
| 141 | + | |
| 142 | +* accepted: **profile 2 / 4:4:4** still refused by name (`decode.rs:211/217`, | |
| 143 | + and `vp9 reference scale` for a colour-format mismatch) — out of scope, owned | |
| 144 | + by the sibling lane. | |
| 145 | +* accepted: `vp9 reference scale` (the `valid_ref_frame_size` ratio bound) stays | |
| 146 | + a named refusal; libvpx errors the same way (`Reference frame has invalid | |
| 147 | + dimensions`). Reaching it needs an adversarial 2x+ ratio that no encoder | |
| 148 | + emits. | |
| 149 | +* noted, not touched: the existing inter path resets stored frame contexts for | |
| 150 | + `reset_frame_context` 2/3 even though libvpx only does that via | |
| 151 | + `vp9_setup_past_independence` (i.e. only for intra-only / error-resilient | |
| 152 | + frames). Pre-existing, unreachable on the corpus (which codes `reset = 0`), | |
| 153 | + and outside this lane's scope. | |
| 154 | +* noted: `scratch_pixdump`/`drv_pix3` are per-`inter_pixdump`-style scratch | |
| 155 | + harnesses; the new `drv_pix3` (per-frame native dims) lives only in | |
| 156 | + `$HOME/.cache/vp9pix`. | |
| 157 | + | |
| 158 | +## Test scope actually run | |
| 159 | + | |
| 160 | +* `cargo test -p ec-vp9` (whole crate) — green, 0 failed, 5 warnings. | |
| 161 | +* `cargo test -p ec-vp9 --test intraonly_exact --test scaledref_exact` — 3 | |
| 162 | + passed. | |
| 163 | +* corpus sweep above — 8 streams IDENTICAL. | |
| 164 | +* 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 | +} |