From 9025ed3c0e94139be4a2968fefee9ac9febfc18c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 19 Sep 2026 18:07:45 +0300 Subject: [PATCH] vp9: decode profile 2 (10-bit 4:2:0) byte-exact vs libvpx 1.15 Store every plane as u16 and thread the frame's bd through the pixel kernels (clip_pixel_bd, bd-scaled loop-filter thresholds, base = 128 << (bd-8) intra fills, highbd idct guard), so one decode walk serves 8- and 10-bit. The one depth-dependent bitstream element is the CAT6 coefficient token: 14 bits/vp9_cat6_prob at 8-bit, 16 bits/ vp9_cat6_prob_high12 + 2 at 10/12-bit -- ported. Profile gate now accepts 0 and 2; profiles 1/3 and 12-bit are refused by name; non-4:2:0 subsampling stays refused. Byte-exact vs libvpx 1.15 on both 10-bit corpus streams (48 and 120 frames) and the whole 8-bit regression corpus. cargo test -p ec-vp9 green; warning parity (the 5 pre-existing). See lanes/vp9hbd.report.md. --- crates/ec-vp9/src/decode.rs | 172 ++++++++++------ crates/ec-vp9/src/intra.rs | 91 ++++++--- crates/ec-vp9/src/lib.rs | 31 ++- crates/ec-vp9/src/loopfilter.rs | 213 ++++++++++++-------- crates/ec-vp9/src/mc.rs | 88 ++++---- crates/ec-vp9/src/tokens.rs | 21 +- crates/ec-vp9/src/transform.rs | 127 ++++++++---- crates/ec-vp9/tests/dump_probe.rs | 2 +- crates/ec-vp9/tests/hbd_exact.rs | 101 ++++++++++ crates/ec-vp9/tests/inter_pixels_exact.rs | 6 +- crates/ec-vp9/tests/ivf.rs | 9 +- crates/ec-vp9/tests/keyframe_exact.rs | 18 +- crates/ec-vp9/tests/odd_dimensions_exact.rs | 6 +- crates/ec-vp9/tests/scratch_lfdump.rs | 24 +-- crates/ec-vp9/tests/scratch_lossless.rs | 2 +- crates/ec-vp9/tests/scratch_pixdump.rs | 18 +- crates/ec-vp9/tests/scratch_pixdump10.rs | 62 ++++++ crates/ec-vp9/tests/scratch_realsweep.rs | 12 +- crates/ec-vp9/tests/scratch_sweep.rs | 2 +- lanes/vp9hbd.report.md | 104 ++++++++++ 20 files changed, 814 insertions(+), 295 deletions(-) create mode 100644 crates/ec-vp9/tests/hbd_exact.rs create mode 100644 crates/ec-vp9/tests/scratch_pixdump10.rs create mode 100644 lanes/vp9hbd.report.md diff --git a/crates/ec-vp9/src/decode.rs b/crates/ec-vp9/src/decode.rs index 89595545..f3903bfc 100644 --- a/crates/ec-vp9/src/decode.rs +++ b/crates/ec-vp9/src/decode.rs @@ -4,13 +4,14 @@ //! reconstruction and the loop filter (spec 6, 7, 8; libvpx //! `vp9_decodeframe.c`). //! -//! Capability: profile-0 8-bit 4:2:0 keyframes and inter frames (motion -//! compensation, residual reconstruction, the loop filter and an 8-slot -//! reference DPB). Intra-only frames, other profiles/subsamplings and a -//! reference whose coded size differs from the current frame are refused by -//! name; `show_existing_frame` returns the buffered reference picture instead -//! of pretending to decode. Odd coded extents are supported: chroma stores -//! and crops at `(w + 1) / 2` (`uv_crop_width`), matching libvpx. +//! Capability: profile-0 8-bit and profile-2 10-bit 4:2:0 keyframes and inter +//! frames (motion compensation, residual reconstruction, the loop filter and +//! an 8-slot reference DPB). Intra-only frames, profiles 1/3, 12-bit, other +//! subsamplings and a reference whose coded size differs from the current +//! frame are refused by name; `show_existing_frame` returns the buffered +//! reference picture instead of pretending to decode. Odd coded extents are +//! supported: chroma stores and crops at `(w + 1) / 2` (`uv_crop_width`), +//! matching libvpx. use crate::header::{FrameContext, read_compressed_header}; use crate::intra::build_intra_predictors; @@ -20,7 +21,7 @@ use crate::modes::{MiInfo, MiState, read_intra_frame_mode_info}; use crate::tables::*; use crate::tokens::{PlaneContexts, decode_coefs, scan_for}; use crate::transform::inverse_transform_add; -use crate::{Error, Result}; +use crate::{Error, Result, Sample}; use ec_vp9_syntax::{FrameHeader, FrameType, Vp9Parser, superframe}; const SB_MI: usize = 8; // a 64x64 superblock in mi (8x8) units @@ -28,12 +29,12 @@ const SB_MI: usize = 8; // a 64x64 superblock in mi (8x8) units /// A decoded, displayable frame: cropped contiguous planes. #[derive(Clone, Debug)] pub struct Picture { - /// Luma plane, `stride`-spaced rows of `width` pixels. - pub y: Vec, + /// Luma plane, `stride`-spaced rows of `width` samples. + pub y: Vec, /// U (Cb) plane, half resolution. - pub u: Vec, + pub u: Vec, /// V (Cr) plane, half resolution. - pub v: Vec, + pub v: Vec, /// Frame width in pixels. pub width: u16, /// Frame height in pixels. @@ -43,28 +44,51 @@ pub struct Picture { /// Chroma row pitch of the returned planes (`(width + 1) / 2`; chroma /// ceils an odd coded width). pub uv_stride: usize, + /// Bits per sample (8 for profile 0, 10 for profile 2). + pub bit_depth: u8, } struct Planes { - y: Vec, - u: Vec, - v: Vec, + y: Vec, + u: Vec, + v: Vec, ys: usize, uvs: usize, aw: usize, ah: usize, + /// Bits per sample this frame was decoded at. + bd: u8, } impl Planes { + /// A frame scratch at the 64-multiple ALIGNED extent, filled with the + /// neutral grey `1 << (bd - 1)` (`128` at 8-bit, `512` at 10-bit). The + /// aligned the decode writes real samples into it (blocks at the frame + /// edge decode at FULL size), so the fill only backs the never-written + /// padding past the MI extent. + fn new(aw: usize, ah: usize, bd: u8) -> Planes { + let fill = 1u16 << (bd - 1); + Planes { + y: vec![fill; aw * ah], + u: vec![fill; aw / 2 * ah / 2], + v: vec![fill; aw / 2 * ah / 2], + ys: aw, + uvs: aw / 2, + aw, + ah, + bd, + } + } + /// Immutable plane + stride (the predictor reads references). - fn plane_ref(&self, plane: usize) -> (&[u8], usize) { + fn plane_ref(&self, plane: usize) -> (&[Sample], usize) { match plane { 0 => (&self.y, self.ys), 1 => (&self.u, self.uvs), _ => (&self.v, self.uvs), } } - fn plane(&mut self, plane: usize) -> (&mut [u8], usize) { + fn plane(&mut self, plane: usize) -> (&mut [Sample], usize) { match plane { 0 => (&mut self.y, self.ys), 1 => (&mut self.u, self.uvs), @@ -107,10 +131,10 @@ pub struct Decoder { syntax_blocks: usize, /// `twd->extend_and_predict_buf`: the per-prediction bordered reference /// window built when a block's read leaves the reference frame. - mc_scratch: Vec, + mc_scratch: Vec, /// The `vpx_convolve8` stride-64 intermediate plus the second scratch its /// averaging variant needs. - mc_temp: Vec, + mc_temp: Vec, } /// One DPB slot: a decoded frame buffer at its ALIGNED (64-multiple) extent @@ -208,10 +232,16 @@ impl Decoder { None => Err(corrupt("show_existing_frame names an empty slot")), }; } - if hdr.profile != 0 { + if hdr.profile != 0 && hdr.profile != 2 { return Err(Error::unsupported( format!("vp9 profile {}", hdr.profile), - "this lane decodes profile 0 only", + "this lane decodes profiles 0 and 2 only (profiles 1 and 3 are 4:4:4)", + )); + } + if hdr.bit_depth != 8 && hdr.bit_depth != 10 { + return Err(Error::unsupported( + format!("vp9 bit depth {}", hdr.bit_depth), + "this lane decodes 8- and 10-bit only (12-bit is not ported)", )); } if hdr.subsampling_x != 1 || hdr.subsampling_y != 1 { @@ -306,10 +336,16 @@ impl Decoder { if hdr.show_existing_frame { continue; } - if hdr.profile != 0 { + if hdr.profile != 0 && hdr.profile != 2 { return Err(Error::unsupported( format!("vp9 profile {}", hdr.profile), - "this lane decodes profile 0 only", + "this lane decodes profiles 0 and 2 only (profiles 1 and 3 are 4:4:4)", + )); + } + if hdr.bit_depth != 8 && hdr.bit_depth != 10 { + return Err(Error::unsupported( + format!("vp9 bit depth {}", hdr.bit_depth), + "this lane decodes 8- and 10-bit only (12-bit is not ported)", )); } if hdr.frame_type == FrameType::Key { @@ -384,15 +420,7 @@ impl Decoder { let height = hdr.height as usize; let aw = width.div_ceil(64) * 64; let ah = height.div_ceil(64) * 64; - self.planes = Some(Planes { - y: vec![128u8; aw * ah], - u: vec![128u8; aw / 2 * ah / 2], - v: vec![128u8; aw / 2 * ah / 2], - ys: aw, - uvs: aw / 2, - aw, - ah, - }); + self.planes = Some(Planes::new(aw, ah, hdr.bit_depth)); } let hdr_start = hdr.uncompressed_header_size as usize; @@ -596,6 +624,7 @@ impl Decoder { vh, vh / 2, hdr.loop_filter.sharpness, + hdr.bit_depth, ); } @@ -897,8 +926,20 @@ impl Decoder { let temp = &mut self.mc_temp; for plane in 0..3usize { inter_predict_plane( - planes, refs, scratch, temp, hdr, info, plane, row, col, &n4w, &n4h, - mb_to_right, mb_to_bottom, sb_type, + planes, + refs, + scratch, + temp, + hdr, + info, + plane, + row, + col, + &n4w, + &n4h, + mb_to_right, + mb_to_bottom, + sb_type, )?; } } @@ -950,6 +991,7 @@ impl Decoder { // decodeframe.c:413). let planes = self.planes.as_mut().expect("frame scratch"); let stride = planes.dims(plane).0; + let bd = planes.bd; let x0 = ((col * 8) >> s) + bcol * 4; let y0 = ((row * 8) >> s) + brow * 4; let dst_off = y0 * stride + x0; @@ -962,6 +1004,7 @@ impl Decoder { dst_off, stride, hdr.quantization.lossless(), + bd, ); } } @@ -990,15 +1033,7 @@ impl Decoder { // mi_row 132 writes 8 rows past a 1080-row buffer). let aw = width.div_ceil(64) * 64; let ah = height.div_ceil(64) * 64; - self.planes = Some(Planes { - y: vec![128u8; aw * ah], - u: vec![128u8; aw / 2 * ah / 2], - v: vec![128u8; aw / 2 * ah / 2], - ys: aw, - uvs: aw / 2, - aw, - ah, - }); + self.planes = Some(Planes::new(aw, ah, hdr.bit_depth)); let tail_start = std::env::var("EC_VP9_FORCE_TAIL") .ok() .and_then(|s| s.parse().ok()) @@ -1131,7 +1166,12 @@ impl Decoder { )?; } } - ensure(r.overreads() == 0, "tile bool decoder desync")?; + if r.overreads() != 0 { + return Err(corrupt(format!( + "tile bool decoder desync (tile tr={tr} tc={tc} overreads={})", + r.overreads() + ))); + } } } @@ -1151,6 +1191,7 @@ impl Decoder { vh, vh / 2, hdr.loop_filter.sharpness, + hdr.bit_depth, ); } @@ -1402,7 +1443,17 @@ impl Decoder { // mode class (`get_filter_level`), so the grids are written // inside the reconstruction rather than from `level_of_seg`. self.reconstruct_inter_pixels( - r, ectx, grids, hdr, &info, row, col, sb_type, bw, bh, mi, + r, + ectx, + grids, + hdr, + &info, + row, + col, + sb_type, + bw, + bh, + mi, tile_col_start, )?; } else { @@ -1412,10 +1463,7 @@ impl Decoder { } for dy in 0..y_mis { for dx in 0..x_mis { - if crate::mvdbg2_enabled() - && row + dy == 7 - && col + dx >= 30 - && col + dx <= 40 + if crate::mvdbg2_enabled() && row + dy == 7 && col + dx >= 30 && col + dx <= 40 { eprintln!( "GWR cell=({} {}) idx={} from=({row} {col}) dy={dy} dx={dx} sb={sb_type} bw={bw} bh={bh} x_mis={x_mis} y_mis={y_mis} mv={:?} ref0={} mi_cols={}", @@ -1558,6 +1606,7 @@ impl Decoder { }; let planes = self.planes.as_mut().expect("frame scratch"); let stride = planes.dims(plane).0; + let bd = planes.bd; let bs = 4 << tx_size; let x0 = ((mi_col * 8) >> s) + tx_col * 4; let y0 = ((mi_row * 8) >> s) + tx_row * 4; @@ -1599,6 +1648,7 @@ impl Decoder { rgt, mb_to_bottom < 0, mb_to_right < 0, + bd, ); } @@ -1665,6 +1715,7 @@ impl Decoder { nb, &self.ctx.coef[tx_size], false, + bd, (x0, y0), plane, ); @@ -1710,7 +1761,7 @@ impl Decoder { Some((it.next()?.parse::().ok()?, it.next()?.parse().ok()?)) }) .is_some_and(|(px, py)| x0 == px && y0 == py); - let t: Option>> = if probe { + let t: Option>> = if probe { Some( (0..4usize) .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec()) @@ -1727,9 +1778,10 @@ impl Decoder { dst_off, stride, lossless, + bd, ); if let Some(before) = t { - let after: Vec> = (0..4usize) + let after: Vec> = (0..4usize) .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec()) .collect(); eprintln!("RC x0={x0} y0={y0} tx={tx_size} mode={mode}"); @@ -1764,7 +1816,7 @@ fn bsize_of_n4(n4: usize) -> usize { /// aligned decode buffer. fn crop_picture(planes: &Planes, width: u16, height: u16) -> Picture { let (w, h) = (width as usize, height as usize); - let crop = |src: &[u8], stride: usize, cw: usize, ch: usize| -> Vec { + let crop = |src: &[Sample], stride: usize, cw: usize, ch: usize| -> Vec { let mut out = Vec::with_capacity(cw * ch); for row in 0..ch { out.extend_from_slice(&src[row * stride..row * stride + cw]); @@ -1782,6 +1834,7 @@ fn crop_picture(planes: &Planes, width: u16, height: u16) -> Picture { height, stride: w, uv_stride: cw, + bit_depth: planes.bd, } } @@ -1837,7 +1890,9 @@ fn reset_skip_context( let offx = (col << 1) >> s; let offy = (row << 1) >> s; let lrows = 32usize >> s; - let a: Vec = (0..n4w[plane]).map(|i| ectx[plane].above[offx + i]).collect(); + let a: Vec = (0..n4w[plane]) + .map(|i| ectx[plane].above[offx + i]) + .collect(); let l: Vec = (0..n4h[plane].min(lrows)) .map(|i| ectx[plane].left[(offy + i) % lrows]) .collect(); @@ -1962,6 +2017,7 @@ fn decode_inter_tx_tokens( nb, &fc.coef[tx_size], info.is_inter, + hdr.bit_depth, (0, 0), plane, ); @@ -2001,8 +2057,8 @@ fn decode_inter_tx_tokens( fn inter_predict_plane( planes: &mut Planes, refs: &[Option; 8], - scratch: &mut Vec, - temp: &mut Vec, + scratch: &mut Vec, + temp: &mut Vec, hdr: &FrameHeader, info: &MiInfo, plane: usize, @@ -2043,6 +2099,7 @@ fn inter_predict_plane( // column (or row). width: (ref_frame.width as usize + s) >> s, height: (ref_frame.height as usize + s) >> s, + bd: ref_frame.planes.bd, }; if sb_type < 3 { // libvpx builds one 4x4 prediction per sub-block, with the MV from @@ -2059,9 +2116,8 @@ fn inter_predict_plane( average_split_mvs_chroma(&info.bmi_mv, rf) }; let (data, _) = planes.plane(plane); - let dst_off = (((row * 8) >> s) + y * 4) * dst_stride - + ((col * 8) >> s) - + xx * 4; + let dst_off = + (((row * 8) >> s) + y * 4) * dst_stride + ((col * 8) >> s) + xx * 4; build_inter_predictors( &mut data[dst_off..], dst_stride, diff --git a/crates/ec-vp9/src/intra.rs b/crates/ec-vp9/src/intra.rs index c72a1d2c..bf8bcab1 100644 --- a/crates/ec-vp9/src/intra.rs +++ b/crates/ec-vp9/src/intra.rs @@ -7,16 +7,18 @@ //! corner), `above_data[16 + i]` is `above[i]` — exactly the C's //! 16-pixel offset into `above_data[64 + 16]`. +use crate::Sample; + /// `AVG3`. #[inline] -fn avg3(a: u8, b: u8, c: u8) -> u8 { - ((a as u32 + 2 * b as u32 + c as u32 + 2) >> 2) as u8 +fn avg3(a: Sample, b: Sample, c: Sample) -> Sample { + ((a as u32 + 2 * b as u32 + c as u32 + 2) >> 2) as Sample } /// `AVG2`. #[inline] -fn avg2(a: u8, b: u8) -> u8 { - ((a as u32 + b as u32 + 1) >> 1) as u8 +fn avg2(a: Sample, b: Sample) -> Sample { + ((a as u32 + b as u32 + 1) >> 1) as Sample } const A: usize = 16; @@ -43,7 +45,7 @@ fn needs(mode: u8) -> (bool, bool, bool) { /// block's absolute sample position; `frame_w`/`frame_h` the coded /// (aligned) plane size. pub(crate) fn build_intra_predictors( - data: &mut [u8], + data: &mut [Sample], stride: usize, frame_w: usize, frame_h: usize, @@ -61,11 +63,16 @@ pub(crate) fn build_intra_predictors( bot_ext: bool, // `xd->mb_to_right_edge < 0` (`vp9_reconintra.c:326/354`). right_ext: bool, + bd: u8, ) { let (need_left, need_above, need_aboveright) = needs(mode); - let mut left_col = [0u8; 32]; - let mut above_data = [0u8; 64 + 16]; - let at = |dx: isize, dy: isize| -> u8 { + // `int base = 128 << (bd - 8)` (`vp9_reconintra.c:132`): the 127/129 + // border fills of an 8-bit frame become `base - 1` / `base + 1`, and + // missing neighbours fill with the neutral grey. + let base = 128u16 << (bd - 8); + let mut left_col = [0u16; 32]; + let mut above_data = [0u16; 64 + 16]; + let at = |dx: isize, dy: isize| -> Sample { data[(((y0 as isize + dy) * stride as isize) + x0 as isize + dx) as usize] }; @@ -89,7 +96,7 @@ pub(crate) fn build_intra_predictors( left_col[n..bs].fill(v); } } else { - left_col[..bs].fill(129); + left_col[..bs].fill(base + 1); } } @@ -114,17 +121,17 @@ pub(crate) fn build_intra_predictors( above_data[A + i] = at(i as isize, -1); } } - above_data[A - 1] = if left_available { at(-1, -1) } else { 129 }; + above_data[A - 1] = if left_available { at(-1, -1) } else { base + 1 }; } else { - above_data[A..A + bs].fill(127); - above_data[A - 1] = 127; + above_data[A..A + bs].fill(base - 1); + above_data[A - 1] = base - 1; } } // NEED_ABOVERIGHT (vp9_reconintra.c:350-394). if need_aboveright { if up_available { - let fill_bs = |d: &mut [u8; 80]| { + let fill_bs = |d: &mut [u16; 80]| { let v = d[A + bs - 1]; d[A + bs..A + 2 * bs].fill(v); }; @@ -174,10 +181,10 @@ pub(crate) fn build_intra_predictors( fill_bs(&mut above_data); } } - above_data[A - 1] = if left_available { at(-1, -1) } else { 129 }; + above_data[A - 1] = if left_available { at(-1, -1) } else { base + 1 }; } else { - above_data[A..A + 2 * bs].fill(127); - above_data[A - 1] = 127; + above_data[A..A + 2 * bs].fill(base - 1); + above_data[A - 1] = base - 1; } } @@ -201,7 +208,15 @@ pub(crate) fn build_intra_predictors( } let dst = &mut data[y0 * stride + x0..]; dispatch( - mode, bs, dst, stride, &above_data, &left_col, up_available, left_available, + mode, + bs, + dst, + stride, + &above_data, + &left_col, + up_available, + left_available, + bd, ); if crate::trace_enabled() && std::env::var("EC_VP9_PROBE_TU") @@ -221,12 +236,13 @@ pub(crate) fn build_intra_predictors( fn dispatch( mode: u8, bs: usize, - dst: &mut [u8], + dst: &mut [Sample], stride: usize, - above: &[u8], - left: &[u8], + above: &[Sample], + left: &[Sample], up: bool, lft: bool, + bd: u8, ) { // `above` is the full above_data: [A-1] = above[-1], [A + i] = above[i]. let cor = above[A - 1]; @@ -238,17 +254,32 @@ fn dispatch( .chain(left[..bs].iter()) .map(|&v| v as u32) .sum(); - fill_dc(dst, stride, bs, ((sum + bs as u32) / (2 * bs as u32)) as u8); + fill_dc( + dst, + stride, + bs, + ((sum + bs as u32) / (2 * bs as u32)) as Sample, + ); } 0 if lft => { let sum: u32 = left[..bs].iter().map(|&v| v as u32).sum(); - fill_dc(dst, stride, bs, ((sum + bs as u32 / 2) / bs as u32) as u8); + fill_dc( + dst, + stride, + bs, + ((sum + bs as u32 / 2) / bs as u32) as Sample, + ); } 0 if up => { let sum: u32 = ab[..bs].iter().map(|&v| v as u32).sum(); - fill_dc(dst, stride, bs, ((sum + bs as u32 / 2) / bs as u32) as u8); + fill_dc( + dst, + stride, + bs, + ((sum + bs as u32 / 2) / bs as u32) as Sample, + ); } - 0 => fill_dc(dst, stride, bs, 128), + 0 => fill_dc(dst, stride, bs, 128u16 << (bd - 8)), 1 => { for r in 0..bs { dst[r * stride..r * stride + bs].copy_from_slice(&ab[..bs]); @@ -314,7 +345,7 @@ fn dispatch( let mut x = 1; let mut size = bs - 2; while x < bs { - let src: Vec = dst[..x + size].to_vec(); + let src: Vec = dst[..x + size].to_vec(); let off = x * stride; dst[off..off + size].copy_from_slice(&src[x..x + size]); dst[off + size..off + bs].fill(above_right); @@ -324,7 +355,7 @@ fn dispatch( } 4 => { // d135 - let mut border = [0u8; 64]; + let mut border = [0u16; 64]; for i in 0..bs - 2 { border[i] = avg3(left[bs - 3 - i], left[bs - 2 - i], left[bs - 1 - i]); } @@ -411,9 +442,9 @@ fn dispatch( let mut r = 2; let mut size = bs - 2; while r < bs { - let src0: Vec = dst[(r >> 1)..(r >> 1) + size].to_vec(); + let src0: Vec = dst[(r >> 1)..(r >> 1) + size].to_vec(); let base1 = stride + (r >> 1); - let src1: Vec = dst[base1..base1 + size].to_vec(); + let src1: Vec = dst[base1..base1 + size].to_vec(); let o0 = r * stride; dst[o0..o0 + size].copy_from_slice(&src0); dst[o0 + size..o0 + bs].fill(ab[bs - 1]); @@ -429,14 +460,14 @@ fn dispatch( for r in 0..bs { for c in 0..bs { dst[r * stride + c] = - (left[r] as i32 + ab[c] as i32 - cor as i32).clamp(0, 255) as u8; + crate::clip_pixel_bd(left[r] as i32 + ab[c] as i32 - cor as i32, bd); } } } } } -fn fill_dc(dst: &mut [u8], stride: usize, bs: usize, v: u8) { +fn fill_dc(dst: &mut [Sample], stride: usize, bs: usize, v: Sample) { for r in 0..bs { dst[r * stride..r * stride + bs].fill(v); } diff --git a/crates/ec-vp9/src/lib.rs b/crates/ec-vp9/src/lib.rs index 64cb45f9..e3f9ffea 100644 --- a/crates/ec-vp9/src/lib.rs +++ b/crates/ec-vp9/src/lib.rs @@ -1,12 +1,18 @@ -//! Native VP9 (profile 0, 8-bit 4:2:0) decoder. +//! Native VP9 (profiles 0 and 2, 8- and 10-bit 4:2:0) decoder. //! //! The crate implements the VP9 bitstream specification directly //! ([spec]); libvpx's output is used only as a test oracle //! (sample-exactness witnesses against ffmpeg's libvpx-based decoder), //! never as code linked at runtime. Every module documents the spec //! section it implements. Inter frames decode through motion compensation, -//! residual reconstruction and the loop filter; intra-only frames, other -//! profiles and other subsamplings are refused by name. +//! residual reconstruction and the loop filter; intra-only frames, profiles +//! 1/3 (4:4:4), 12-bit and other subsamplings are refused by name. +//! +//! Planes are stored as `u16` for every depth ([`Sample`]); kernels take the +//! frame's `bd` and clamp with `clip_pixel_bd`, so one decode walk serves +//! both depths. The only depth-dependent bitstream element is the CAT6 +//! coefficient token (14 bits/`vp9_cat6_prob` at 8-bit, 16 bits/ +//! `vp9_cat6_prob_high12 + 2` at 10- and 12-bit). //! //! [spec]: https://www.webmproject.org/docs/vp9/ //! @@ -32,6 +38,25 @@ pub mod transform; pub use ec_core::{Error, Result}; +/// A reconstructed sample. Planes are stored as `u16` for EVERY bit depth +/// (8-bit values occupy the low byte), so profile-0 and profile-2 frames share +/// one representation and one decode walk; the kernels take the frame's +/// `bd` and clamp with [`clip_pixel_bd`]. +pub type Sample = u16; + +/// `clip_pixel_highbd` (`vpx_dsp/vpx_dsp_common.h`): clamp to `[0, (1< Sample { + v.clamp(0, (1i32 << bd) - 1) as Sample +} + +/// `ROUND_POWER_OF_TWO(v, n)` (`vpx_dsp/txfm_common.h`, arithmetic shift). +#[inline] +pub(crate) fn round_pow2(v: i32, n: i32) -> i32 { + (v + (1 << (n - 1))) >> n +} + /// Whether `EC_VP9_TRACE` decision tracing is enabled, resolved once per /// process. An `var_os` per bool read would lock std's ENV lock on every /// coefficient; the hot path is a single relaxed atomic load. diff --git a/crates/ec-vp9/src/loopfilter.rs b/crates/ec-vp9/src/loopfilter.rs index be052298..c87c2f9d 100644 --- a/crates/ec-vp9/src/loopfilter.rs +++ b/crates/ec-vp9/src/loopfilter.rs @@ -95,48 +95,60 @@ const LUMA_ABOVE_TXF: [u64; 4] = [u64::MAX, u64::MAX, 0x00ff00ff00ff00ff, 0x0000 const LUMA_LEFT_BORDER: u64 = 0x1111111111111111; const LUMA_ABOVE_BORDER: u64 = 0x000000ff000000ff; +use crate::Sample; + +/// `signed_char_clamp_high` (`vpx_dsp/loopfilter.c:23`): clamp to +/// `[-(128 << (bd-8)), (128 << (bd-8)) - 1]`. At `bd == 8` this is libvpx's +/// 8-bit `signed_char_clamp` (`[-128, 127]`). #[inline] -fn sc(x: i32) -> i32 { - x.clamp(-128, 127) +fn sc(x: i32, bd: u8) -> i32 { + let shift = (bd - 8) as i32; + x.clamp(-(128 << shift), (128 << shift) - 1) } -/// `filter4` kernel; `idx` = [op1, op0, oq0, oq1]. +/// `filter4` / `highbd_filter4` kernel; `idx` = [op1, op0, oq0, oq1]. /// `vpx_dsp filter4`: updates p1/p0/q0/q1 in place. `mask` gates the -/// whole filter, `hev` the outer taps (vp9_loopfilter.c:81). -fn filter4(s: &mut [u8], idx: [usize; 4], thresh: i32, mask: bool) { +/// whole filter, `hev` the outer taps (vp9_loopfilter.c:81). The `^ 0x80` +/// of the 8-bit kernel generalizes to subtracting `0x80 << (bd - 8)`. +fn filter4(s: &mut [Sample], idx: [usize; 4], thresh: i32, mask: bool, bd: u8) { if !mask { return; } + let shift = (bd - 8) as i32; + let bias = 0x80 << shift; let (op1, op0, oq0, oq1) = (idx[0], idx[1], idx[2], idx[3]); let (p1, p0, q0, q1) = (s[op1], s[op0], s[oq0], s[oq1]); - let hev = (p1 as i32 - p0 as i32).abs() > thresh || (q1 as i32 - q0 as i32).abs() > thresh; + let hev_thresh = thresh << shift; + let hev = + (p1 as i32 - p0 as i32).abs() > hev_thresh || (q1 as i32 - q0 as i32).abs() > hev_thresh; let (ps1, ps0, qs0, qs1) = ( - (p1 ^ 0x80) as i8 as i32, - (p0 ^ 0x80) as i8 as i32, - (q0 ^ 0x80) as i8 as i32, - (q1 ^ 0x80) as i8 as i32, + p1 as i32 - bias, + p0 as i32 - bias, + q0 as i32 - bias, + q1 as i32 - bias, ); - let mut filter = sc(ps1 - qs1); + let mut filter = sc(ps1 - qs1, bd); if hev { // add outer taps if we have high edge variance (& hev mask) } else { filter = 0; } // inner taps - filter = sc(filter + 3 * (qs0 - ps0)); + filter = sc(filter + 3 * (qs0 - ps0), bd); // round one side +4 and the other +3 - let filter1 = sc(filter + 4) >> 3; - let filter2 = sc(filter + 3) >> 3; - s[oq0] = (sc(qs0 - filter1) ^ 0x80) as u8; - s[op0] = (sc(ps0 + filter2) ^ 0x80) as u8; + let filter1 = sc(filter + 4, bd) >> 3; + let filter2 = sc(filter + 3, bd) >> 3; + s[oq0] = (sc(qs0 - filter1, bd) + bias) as Sample; + s[op0] = (sc(ps0 + filter2, bd) + bias) as Sample; // outer tap adjustments (& ~hev) let f = if hev { 0 } else { (filter1 + 1) >> 1 }; - s[oq1] = (sc(qs1 - f) ^ 0x80) as u8; - s[op1] = (sc(ps1 + f) ^ 0x80) as u8; + s[oq1] = (sc(qs1 - f, bd) + bias) as Sample; + s[op1] = (sc(ps1 + f, bd) + bias) as Sample; } +#[allow(clippy::too_many_arguments)] fn lpf_edge( - data: &mut [u8], + data: &mut [Sample], off: usize, stride: usize, dir: u8, @@ -145,7 +157,14 @@ fn lpf_edge( limit: i32, thresh: i32, nlines: isize, + bd: u8, ) { + // `highbd_filter_mask` / `highbd_flat_mask*`: the coded 8-bit thresholds + // scale by `1 << (bd - 8)`. + let shift = (bd - 8) as i32; + let limit = limit << shift; + let blimit = blimit << shift; + let flat_t = 1 << shift; // `dir` 0 = horizontal edges (rows step by stride), 1 = vertical // (columns step by 1). `taps` in {4, 8, 16}. let step: isize = if dir == 0 { stride as isize } else { 1 }; @@ -179,23 +198,23 @@ fn lpf_edge( (edge + step) as usize, ]; if taps == 4 { - filter4(data, idx4, thresh, mask); + filter4(data, idx4, thresh, mask, bd); continue; } if !mask { continue; } // flat_mask4(1, p3..q3) - let flat = (rd!(-2) - rd!(-1)).abs() <= 1 - && (rd!(1) - rd!(0)).abs() <= 1 - && (rd!(-3) - rd!(-1)).abs() <= 1 - && (rd!(2) - rd!(0)).abs() <= 1 - && (rd!(-4) - rd!(-1)).abs() <= 1 - && (rd!(3) - rd!(0)).abs() <= 1; + let flat = (rd!(-2) - rd!(-1)).abs() <= flat_t + && (rd!(1) - rd!(0)).abs() <= flat_t + && (rd!(-3) - rd!(-1)).abs() <= flat_t + && (rd!(2) - rd!(0)).abs() <= flat_t + && (rd!(-4) - rd!(-1)).abs() <= flat_t + && (rd!(3) - rd!(0)).abs() <= flat_t; if taps == 8 || !flat { if !flat { // plain filter4 with the real mask and hev threshold - filter4(data, idx4, thresh, mask); + filter4(data, idx4, thresh, mask, bd); continue; } // 7-tap [1,1,1,2,1,1,1] outputs (filter8). @@ -209,25 +228,40 @@ fn lpf_edge( rd!(2), rd!(3), ); - put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as u8); - put!(-2, ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as u8); - put!(-1, ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as u8); - put!(0, ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as u8); - put!(1, ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as u8); - put!(2, ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as u8); + put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as Sample); + put!( + -2, + ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as Sample + ); + put!( + -1, + ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as Sample + ); + put!( + 0, + ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as Sample + ); + put!( + 1, + ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as Sample + ); + put!( + 2, + ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as Sample + ); continue; } // flat_mask5(1, s[-8], s[-7], s[-6], s[-5], p0, q0, s[4], s[5], s[6], s[7]): // |p7..p4 - p0| and |q4..q7 - q0| (the C names are shifted; q4..q6 // are the q1..q3 args of the inner flat_mask4 and compare to q0). - let flat2 = (rd!(-8) - rd!(-1)).abs() <= 1 - && (rd!(-7) - rd!(-1)).abs() <= 1 - && (rd!(-6) - rd!(-1)).abs() <= 1 - && (rd!(-5) - rd!(-1)).abs() <= 1 - && (rd!(4) - rd!(0)).abs() <= 1 - && (rd!(5) - rd!(0)).abs() <= 1 - && (rd!(6) - rd!(0)).abs() <= 1 - && (rd!(7) - rd!(0)).abs() <= 1; + let flat2 = (rd!(-8) - rd!(-1)).abs() <= flat_t + && (rd!(-7) - rd!(-1)).abs() <= flat_t + && (rd!(-6) - rd!(-1)).abs() <= flat_t + && (rd!(-5) - rd!(-1)).abs() <= flat_t + && (rd!(4) - rd!(0)).abs() <= flat_t + && (rd!(5) - rd!(0)).abs() <= flat_t + && (rd!(6) - rd!(0)).abs() <= flat_t + && (rd!(7) - rd!(0)).abs() <= flat_t; if !flat2 { let (p3, p2, p1, p0, q0, q1, q2, q3) = ( rd!(-4), @@ -239,12 +273,27 @@ fn lpf_edge( rd!(2), rd!(3), ); - put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as u8); - put!(-2, ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as u8); - put!(-1, ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as u8); - put!(0, ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as u8); - put!(1, ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as u8); - put!(2, ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as u8); + put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as Sample); + put!( + -2, + ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as Sample + ); + put!( + -1, + ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as Sample + ); + put!( + 0, + ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as Sample + ); + put!( + 1, + ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as Sample + ); + put!( + 2, + ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as Sample + ); continue; } // 15-tap filter [1 x 7, 2, 1 x 7] (filter16, weights verbatim). @@ -254,65 +303,67 @@ fn lpf_edge( let (q4, q5, q6, q7) = (rd!(4), rd!(5), rd!(6), rd!(7)); put!( -7, - ((p7 * 7 + p6 * 2 + p5 + p4 + p3 + p2 + p1 + p0 + q0 + 8) >> 4) as u8 + ((p7 * 7 + p6 * 2 + p5 + p4 + p3 + p2 + p1 + p0 + q0 + 8) >> 4) as Sample ); put!( -6, - ((p7 * 6 + p6 + p5 * 2 + p4 + p3 + p2 + p1 + p0 + q0 + q1 + 8) >> 4) as u8 + ((p7 * 6 + p6 + p5 * 2 + p4 + p3 + p2 + p1 + p0 + q0 + q1 + 8) >> 4) as Sample ); put!( -5, - ((p7 * 5 + p6 + p5 + p4 * 2 + p3 + p2 + p1 + p0 + q0 + q1 + q2 + 8) >> 4) as u8 + ((p7 * 5 + p6 + p5 + p4 * 2 + p3 + p2 + p1 + p0 + q0 + q1 + q2 + 8) >> 4) as Sample ); put!( -4, - ((p7 * 4 + p6 + p5 + p4 + p3 * 2 + p2 + p1 + p0 + q0 + q1 + q2 + q3 + 8) >> 4) as u8 + ((p7 * 4 + p6 + p5 + p4 + p3 * 2 + p2 + p1 + p0 + q0 + q1 + q2 + q3 + 8) >> 4) + as Sample ); put!( -3, ((p7 * 3 + p6 + p5 + p4 + p3 + p2 * 2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 + 8) >> 4) - as u8 + as Sample ); put!( -2, ((p7 * 2 + p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 + q0 + q1 + q2 + q3 + q4 + q5 + 8) >> 4) - as u8 + as Sample ); put!( -1, ((p7 + p6 + p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + q3 + q4 + q5 + q6 + 8) - >> 4) as u8 + >> 4) as Sample ); put!( 0, ((p6 + p5 + p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + q4 + q5 + q6 + q7 + 8) - >> 4) as u8 + >> 4) as Sample ); put!( 1, ((p5 + p4 + p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 + q3 + q4 + q5 + q6 + q7 * 2 + 8) >> 4) - as u8 + as Sample ); put!( 2, ((p4 + p3 + p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 + q4 + q5 + q6 + q7 * 3 + 8) >> 4) - as u8 + as Sample ); put!( 3, - ((p3 + p2 + p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 + q5 + q6 + q7 * 4 + 8) >> 4) as u8 + ((p3 + p2 + p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 + q5 + q6 + q7 * 4 + 8) >> 4) + as Sample ); put!( 4, - ((p2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 + q6 + q7 * 5 + 8) >> 4) as u8 + ((p2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 + q6 + q7 * 5 + 8) >> 4) as Sample ); put!( 5, - ((p1 + p0 + q0 + q1 + q2 + q3 + q4 + q5 * 2 + q6 + q7 * 6 + 8) >> 4) as u8 + ((p1 + p0 + q0 + q1 + q2 + q3 + q4 + q5 * 2 + q6 + q7 * 6 + 8) >> 4) as Sample ); put!( 6, - ((p0 + q0 + q1 + q2 + q3 + q4 + q5 + q6 * 2 + q7 * 7 + 8) >> 4) as u8 + ((p0 + q0 + q1 + q2 + q3 + q4 + q5 + q6 * 2 + q7 * 7 + 8) >> 4) as Sample ); } } @@ -567,15 +618,16 @@ impl LfGrids { /// writes whole 8-column groups into the padded plane). pub(crate) fn filter_frame( &self, - y: &mut [u8], + y: &mut [Sample], stride: usize, - u: &mut [u8], - v: &mut [u8], + u: &mut [Sample], + v: &mut [Sample], uv_stride: usize, y_w: usize, y_h: usize, uv_h: usize, sharpness: u8, + bd: u8, ) { let lftrace = lftrace_on(); // Luma masks, ported from vp9_setup_mask/build_masks and @@ -618,7 +670,7 @@ impl LfGrids { if t == 16 && (xx < 8 || xx + 8 > y_w) { t = 8; } - lpf_edge(y, yy * stride + xx, stride, 1, t, bl, li, th, 8); + lpf_edge(y, yy * stride + xx, stride, 1, t, bl, li, th, 8, bd); if lftrace { let kind = match t { 16 => "V16", @@ -629,7 +681,7 @@ impl LfGrids { } } if int4 & bit != 0 && xx + 8 <= y_w && yy + 8 <= y_h { - lpf_edge(y, yy * stride + xx + 4, stride, 1, 4, bl, li, th, 8); + lpf_edge(y, yy * stride + xx + 4, stride, 1, 4, bl, li, th, 8, bd); if lftrace { eprintln!("V4I {} {}", xx + 4, yy); } @@ -667,7 +719,7 @@ impl LfGrids { if t == 16 && (yy < 8 || yy + 8 > y_h) { t = 8; } - lpf_edge(y, yy * stride + xx, stride, 0, t, bl, li, th, 8); + lpf_edge(y, yy * stride + xx, stride, 0, t, bl, li, th, 8, bd); if lftrace { let kind = match t { 16 => "H16", @@ -685,7 +737,7 @@ impl LfGrids { // exists only in the 4:2:0-chroma path (ss11, // vp9_loopfilter.c:1382) and in non420 under `ss_y`. if int4 & bit != 0 && yy + 8 <= y_h && xx + 8 <= y_w { - lpf_edge(y, (yy + 4) * stride + xx, stride, 0, 4, bl, li, th, 8); + lpf_edge(y, (yy + 4) * stride + xx, stride, 0, 4, bl, li, th, 8, bd); if lftrace { eprintln!("H4I {} {}", xx, yy + 4); } @@ -830,11 +882,7 @@ impl LfGrids { 0 }; if taps != 0 { - let t = if taps == 16 && x8 < 8 { - 8 - } else { - taps - }; + let t = if taps == 16 && x8 < 8 { 8 } else { taps }; lpf_edge( data, y8 * uv_stride + x8, @@ -845,6 +893,7 @@ impl LfGrids { li, th, 8, + bd, ); } } @@ -859,6 +908,7 @@ impl LfGrids { li, th, 8, + bd, ); } } @@ -906,12 +956,11 @@ impl LfGrids { li, th, 8, + bd, ); } } - if int4 & bit != 0 - && sbr + 2 * rg != self.mi_rows - 1 - && y8 + 8 <= uv_h + if int4 & bit != 0 && sbr + 2 * rg != self.mi_rows - 1 && y8 + 8 <= uv_h { lpf_edge( data, @@ -923,6 +972,7 @@ impl LfGrids { li, th, 8, + bd, ); } } @@ -952,10 +1002,10 @@ mod tests { } } - fn run(g: &LfGrids, y: &mut [u8]) { - let mut u = vec![128u8; 32 * 32]; - let mut v = vec![128u8; 32 * 32]; - g.filter_frame(y, 64, &mut u, &mut v, 32, 64, 64, 32, 0); + fn run(g: &LfGrids, y: &mut [Sample]) { + let mut u = vec![128u16; 32 * 32]; + let mut v = vec![128u16; 32 * 32]; + g.filter_frame(y, 64, &mut u, &mut v, 32, 64, 64, 32, 0, 8); } /// The luma internal-4x4 horizontal edge fires on the frame's LAST MI row. @@ -973,7 +1023,7 @@ mod tests { let stride = 64; // A gentle step (4) between rows 59 and 60: sharp steps fail the // filter_mask gradient test, and a flat pattern cannot move. - let mut y = vec![100u8; 64 * 64]; + let mut y = vec![100u16; 64 * 64]; for row in 60..64 { y[row * stride..row * stride + 64].fill(104); } @@ -985,4 +1035,3 @@ mod tests { ); } } - diff --git a/crates/ec-vp9/src/mc.rs b/crates/ec-vp9/src/mc.rs index f38335ab..b9021c79 100644 --- a/crates/ec-vp9/src/mc.rs +++ b/crates/ec-vp9/src/mc.rs @@ -110,20 +110,12 @@ pub(crate) const FILTERS: [[[i16; TAPS]; SUBPEL_SHIFTS as usize]; 4] = [ ], ]; -/// `clip_pixel` (`vpx_dsp/vpx_dsp_common.h`). -fn clip_pixel(v: i32) -> u8 { - v.clamp(0, 255) as u8 -} - -/// `ROUND_POWER_OF_TWO(v, n)`. -fn round_pow2(v: i32, n: i32) -> i32 { - (v + (1 << (n - 1))) >> n -} +use crate::{Sample, clip_pixel_bd, round_pow2}; /// Read `buf[i]` for a possibly negative `i`. Every caller keeps `i` inside /// the buffer (the border copy guarantees the tap margins exist). #[inline] -fn at(buf: &[u8], i: isize) -> u8 { +fn at(buf: &[Sample], i: isize) -> Sample { buf[i as usize] } @@ -162,9 +154,9 @@ pub(crate) fn clamp_mv_to_umv_border_sb( /// `[0, w)` x `[0, h)`. #[allow(clippy::too_many_arguments)] fn build_mc_border( - src: &[u8], + src: &[Sample], src_stride: usize, - dst: &mut [u8], + dst: &mut [Sample], dst_stride: usize, x: i32, mut y: i32, @@ -225,16 +217,17 @@ fn build_mc_border( /// `origin + y*stride + (x_q4 >> SUBPEL_BITS) - (SUBPEL_TAPS / 2 - 1) + k`. #[allow(clippy::too_many_arguments)] fn convolve_horiz( - buf: &[u8], + buf: &[Sample], stride: usize, origin: isize, - dst: &mut [u8], + dst: &mut [Sample], dst_stride: usize, f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize], x0_q4: i32, w: usize, rows: usize, avg: bool, + bd: u8, ) { for y in 0..rows { let mut x_q4 = x0_q4; @@ -246,12 +239,12 @@ fn convolve_horiz( for k in 0..TAPS { sum += at(buf, base + k as isize) as i32 * filt[k] as i32; } - let v = clip_pixel(round_pow2(sum, FILTER_BITS)) as i32; + let v = clip_pixel_bd(round_pow2(sum, FILTER_BITS), bd) as i32; let d = y * dst_stride + x; dst[d] = if avg { - round_pow2(dst[d] as i32 + v, 1) as u8 + round_pow2(dst[d] as i32 + v, 1) as Sample } else { - v as u8 + v as Sample }; x_q4 += SUBPEL_SHIFTS; } @@ -260,16 +253,17 @@ fn convolve_horiz( /// `convolve_vert` / `convolve_avg_vert` (`vpx_dsp/vpx_convolve.c:80`). fn convolve_vert( - buf: &[u8], + buf: &[Sample], stride: usize, origin: isize, - dst: &mut [u8], + dst: &mut [Sample], dst_stride: usize, f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize], y0_q4: i32, w: usize, h: usize, avg: bool, + bd: u8, ) { for x in 0..w { let mut y_q4 = y0_q4; @@ -282,12 +276,12 @@ fn convolve_vert( for k in 0..TAPS { sum += at(buf, base + k as isize * stride as isize) as i32 * filt[k] as i32; } - let v = clip_pixel(round_pow2(sum, FILTER_BITS)) as i32; + let v = clip_pixel_bd(round_pow2(sum, FILTER_BITS), bd) as i32; let d = y * dst_stride + x; dst[d] = if avg { - round_pow2(dst[d] as i32 + v, 1) as u8 + round_pow2(dst[d] as i32 + v, 1) as Sample } else { - v as u8 + v as Sample }; y_q4 += SUBPEL_SHIFTS; } @@ -305,10 +299,10 @@ fn convolve_vert( /// the averaging variant). #[allow(clippy::too_many_arguments)] fn inter_predictor( - buf: &[u8], + buf: &[Sample], stride: usize, origin: isize, - dst: &mut [u8], + dst: &mut [Sample], dst_stride: usize, f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize], subpel_x: i32, @@ -316,7 +310,8 @@ fn inter_predictor( w: usize, h: usize, avg: bool, - temp: &mut [u8], + temp: &mut [Sample], + bd: u8, ) { if subpel_x == 0 && subpel_y == 0 { for y in 0..h { @@ -324,20 +319,24 @@ fn inter_predictor( let s = at(buf, origin + (y * stride + x) as isize) as i32; let d = y * dst_stride + x; dst[d] = if avg { - round_pow2(dst[d] as i32 + s, 1) as u8 + round_pow2(dst[d] as i32 + s, 1) as Sample } else { - s as u8 + s as Sample }; } } return; } if subpel_y == 0 { - convolve_horiz(buf, stride, origin, dst, dst_stride, f, subpel_x, w, h, avg); + convolve_horiz( + buf, stride, origin, dst, dst_stride, f, subpel_x, w, h, avg, bd, + ); return; } if subpel_x == 0 { - convolve_vert(buf, stride, origin, dst, dst_stride, f, subpel_y, w, h, avg); + convolve_vert( + buf, stride, origin, dst, dst_stride, f, subpel_y, w, h, avg, bd, + ); return; } // vpx_convolve8_c: horizontal pass into a stride-64 intermediate with @@ -359,6 +358,7 @@ fn inter_predictor( w, intermediate_height, false, + bd, ); if avg { // vpx_convolve8_avg_c: full 2D into a second scratch, then average @@ -366,11 +366,23 @@ fn inter_predictor( // `temp[..64 * 135]` is the horizontal intermediate; the region after // it is the 2D result. let (horiz, mid2) = temp.split_at_mut(64 * 135); - convolve_vert(horiz, 64, temp_origin, mid2, w, f, subpel_y, w, h, false); + convolve_vert( + horiz, + 64, + temp_origin, + mid2, + w, + f, + subpel_y, + w, + h, + false, + bd, + ); for y in 0..h { for x in 0..w { let d = y * dst_stride + x; - dst[d] = round_pow2(dst[d] as i32 + mid2[y * w + x] as i32, 1) as u8; + dst[d] = round_pow2(dst[d] as i32 + mid2[y * w + x] as i32, 1) as Sample; } } return; @@ -386,13 +398,14 @@ fn inter_predictor( w, h, false, + bd, ); } /// One reference plane of a stored frame. pub(crate) struct RefPlane<'a> { /// Plane base — the frame's first visible sample. - pub data: &'a [u8], + pub data: &'a [Sample], /// Row pitch. pub stride: usize, /// `y_crop_width` / `uv_crop_width`: the coded extent, which is what @@ -400,6 +413,8 @@ pub(crate) struct RefPlane<'a> { pub width: usize, /// `y_crop_height` / `uv_crop_height`. pub height: usize, + /// Bits per sample of the reference frame. + pub bd: u8, } /// `dec_build_inter_predictors` (`vp9/decoder/vp9_decodeframe.c:593`), @@ -407,7 +422,7 @@ pub(crate) struct RefPlane<'a> { /// `(x, y)` inside the block at MI `(mi_row, mi_col)`. #[allow(clippy::too_many_arguments)] pub(crate) fn build_inter_predictors( - dst: &mut [u8], + dst: &mut [Sample], dst_stride: usize, refp: &RefPlane<'_>, mi_col: usize, @@ -425,9 +440,10 @@ pub(crate) fn build_inter_predictors( ss_y: usize, kernel: usize, avg: bool, - scratch: &mut Vec, - temp: &mut Vec, + scratch: &mut Vec, + temp: &mut Vec, ) { + let bd = refp.bd; let mv_q4 = clamp_mv_to_umv_border_sb( mv, w as i32, h as i32, mb_left, mb_right, mb_top, mb_bottom, ss_x, ss_y, ); @@ -511,6 +527,7 @@ pub(crate) fn build_inter_predictors( h, avg, temp, + bd, ); return; } @@ -532,6 +549,7 @@ pub(crate) fn build_inter_predictors( h, avg, temp, + bd, ); } diff --git a/crates/ec-vp9/src/tokens.rs b/crates/ec-vp9/src/tokens.rs index a40ed6f1..86ef0fca 100644 --- a/crates/ec-vp9/src/tokens.rs +++ b/crates/ec-vp9/src/tokens.rs @@ -4,6 +4,14 @@ use crate::bool::BoolDecoder; use crate::tables::*; +/// `vp9_cat6_prob_high12 + 2` (`vp9/common/vp9_entropy.c`): the CAT6 token's +/// 16 extra bits at bit depth 10 (and the middle 16 of the 12-bit table). +/// The bitstream is the ONLY depth-dependent syntax element: `decode_coefs` +/// picks `vp9_cat6_prob`/14 bits at 8-bit and this/16 bits at 10- and 12-bit. +const CAT6_PROB_HIGH: [u8; 16] = [ + 255, 255, 254, 254, 254, 252, 249, 243, 230, 196, 177, 153, 140, 133, 130, 129, +]; + /// One plane's entropy contexts: a has-coefficient flag per 4x4 column /// above the current superblock row and per 4x4 row to the left. pub(crate) struct PlaneContexts { @@ -63,6 +71,7 @@ pub(crate) fn decode_coefs( nb: &[i16], probs4d: &[[[[[u8; 3]; 6]; 6]; 2]; 2], is_inter: bool, + bd: u8, #[allow(unused_variables)] pos: (usize, usize), #[allow(unused_variables)] plane: usize, ) -> CoeffBlock { @@ -83,7 +92,10 @@ pub(crate) fn decode_coefs( while c < max_eob { if crate::trace_enabled() { - eprintln!("TOK c={c} band={band} ctx={ctx} p0={},{},{}", prob[0], prob[1], prob[2]); + eprintln!( + "TOK c={c} band={band} ctx={ctx} p0={},{},{}", + prob[0], prob[1], prob[2] + ); } if !r.read_bool(prob[0]) { break; @@ -108,7 +120,12 @@ pub(crate) fn decode_coefs( token_cache[scan[c] as usize] = 5; if r.read_bool(p[5]) { if r.read_bool(p[7]) { - v = 67 + read_coeff(r, &CAT6_PROB, 14); + v = 67 + + if bd == 8 { + read_coeff(r, &CAT6_PROB, 14) + } else { + read_coeff(r, &CAT6_PROB_HIGH, 16) + }; } else { v = 35 + read_coeff(r, &CAT5_PROB, 5); } diff --git a/crates/ec-vp9/src/transform.rs b/crates/ec-vp9/src/transform.rs index 2b5f70f7..15e8dc3a 100644 --- a/crates/ec-vp9/src/transform.rs +++ b/crates/ec-vp9/src/transform.rs @@ -46,14 +46,24 @@ const S2: i64 = 9929; const S3: i64 = 13377; const S4: i64 = 15212; -/// `clip_pixel_add`. +use crate::Sample; + +/// `detect_invalid_highbd_input` (`vpx_dsp/inv_txfm.c:1284`): a 1-D highbitdepth +/// transform whose input holds a magnitude `>= 1 << 25` emits all zeros instead +/// of reconstructing. Unreachable for valid streams; ported for fidelity. +#[inline] +fn invalid_highbd_input(input: &[i32], bd: u8) -> bool { + bd != 8 && input.iter().any(|&v| v.unsigned_abs() >= (1u32 << 25)) +} + +/// `clip_pixel_add` / `highbd_clip_pixel_add`. #[inline] -pub(crate) fn clip_add(d: u8, v: i32) -> u8 { - (d as i32 + v).clamp(0, 255) as u8 +pub(crate) fn clip_add(d: Sample, v: i32, bd: u8) -> Sample { + crate::clip_pixel_bd(d as i32 + v, bd) } /// vpx_iwht4x4_16_add_c (lossless). -pub(crate) fn iwht4x4_add(input: &[i32], dest: &mut [u8], stride: usize) { +pub(crate) fn iwht4x4_add(input: &[i32], dest: &mut [Sample], stride: usize, bd: u8) { let mut output = [0i32; 16]; for i in 0..4 { let ip = &input[i * 4..i * 4 + 4]; @@ -82,14 +92,18 @@ pub(crate) fn iwht4x4_add(input: &[i32], dest: &mut [u8], stride: usize) { let c1 = e1 - c0; let a1 = a2 - b1; let d1 = d2 + c1; - dest[i] = clip_add(dest[i], a1); - dest[stride + i] = clip_add(dest[stride + i], b1); - dest[stride * 2 + i] = clip_add(dest[stride * 2 + i], c1); - dest[stride * 3 + i] = clip_add(dest[stride * 3 + i], d1); + dest[i] = clip_add(dest[i], a1, bd); + dest[stride + i] = clip_add(dest[stride + i], b1, bd); + dest[stride * 2 + i] = clip_add(dest[stride * 2 + i], c1, bd); + dest[stride * 3 + i] = clip_add(dest[stride * 3 + i], d1, bd); } } -pub(crate) fn idct4(input: &[i32], output: &mut [i32]) { +pub(crate) fn idct4(input: &[i32], output: &mut [i32], bd: u8) { + if invalid_highbd_input(input, bd) { + output[..4].fill(0); + return; + } let g = |v: i32| v as i64; let mut step = [0i32; 4]; let t1 = (g(input[0]) + g(input[2])) * C16; @@ -106,7 +120,11 @@ pub(crate) fn idct4(input: &[i32], output: &mut [i32]) { output[3] = step[0] - step[3]; } -pub(crate) fn idct8(input: &[i32], output: &mut [i32]) { +pub(crate) fn idct8(input: &[i32], output: &mut [i32], bd: u8) { + if invalid_highbd_input(input, bd) { + output[..8].fill(0); + return; + } let g = |v: i32| v as i64; let mut step1 = [0i32; 8]; let mut step2 = [0i32; 8]; @@ -144,7 +162,11 @@ pub(crate) fn idct8(input: &[i32], output: &mut [i32]) { output[7] = step1[0] - step1[7]; } -pub(crate) fn idct16(input: &[i32], output: &mut [i32]) { +pub(crate) fn idct16(input: &[i32], output: &mut [i32], bd: u8) { + if invalid_highbd_input(input, bd) { + output[..16].fill(0); + return; + } let g = |v: i32| v as i64; let mut step1 = [0i32; 16]; let mut step2 = [0i32; 16]; @@ -228,12 +250,18 @@ pub(crate) fn idct16(input: &[i32], output: &mut [i32]) { } } -pub(crate) fn idct32(input: &[i32], output: &mut [i32]) { +pub(crate) fn idct32(input: &[i32], output: &mut [i32], bd: u8) { + if invalid_highbd_input(input, bd) { + output[..32].fill(0); + return; + } let g = |v: i32| v as i64; let mut step1 = [0i32; 32]; let mut step2 = [0i32; 32]; for i in 0..16 { - step1[i] = input[[0usize, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30][i]]; + step1[i] = input[[ + 0usize, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30, + ][i]]; } step1[16] = dcrs(g(input[1]) * C31 - g(input[31]) * C1); step1[31] = dcrs(g(input[1]) * C1 + g(input[31]) * C31); @@ -441,8 +469,17 @@ pub(crate) fn idct32(input: &[i32], output: &mut [i32]) { } } -pub(crate) fn iadst4(input: &[i32], output: &mut [i32]) { - let (x0, x1, x2, x3) = (input[0] as i64, input[1] as i64, input[2] as i64, input[3] as i64); +pub(crate) fn iadst4(input: &[i32], output: &mut [i32], bd: u8) { + if invalid_highbd_input(input, bd) { + output[..4].fill(0); + return; + } + let (x0, x1, x2, x3) = ( + input[0] as i64, + input[1] as i64, + input[2] as i64, + input[3] as i64, + ); if x0 | x1 | x2 | x3 == 0 { output[..4].fill(0); return; @@ -458,7 +495,11 @@ pub(crate) fn iadst4(input: &[i32], output: &mut [i32]) { output[3] = dcrs(s0 + s1 - s3); } -pub(crate) fn iadst8(input: &[i32], output: &mut [i32]) { +pub(crate) fn iadst8(input: &[i32], output: &mut [i32], bd: u8) { + if invalid_highbd_input(input, bd) { + output[..8].fill(0); + return; + } let g = |v: i32| v as i64; let mut x0 = g(input[7]); let mut x1 = g(input[0]); @@ -519,13 +560,29 @@ pub(crate) fn iadst8(input: &[i32], output: &mut [i32]) { output[7] = -x1 as i32; } -pub(crate) fn iadst16(input: &[i32], output: &mut [i32]) { +pub(crate) fn iadst16(input: &[i32], output: &mut [i32], bd: u8) { + if invalid_highbd_input(input, bd) { + output[..16].fill(0); + return; + } let g = |v: i32| v as i64; let mut x = [ - g(input[15]), g(input[0]), g(input[13]), g(input[2]), - g(input[11]), g(input[4]), g(input[9]), g(input[6]), - g(input[7]), g(input[8]), g(input[5]), g(input[10]), - g(input[3]), g(input[12]), g(input[1]), g(input[14]), + g(input[15]), + g(input[0]), + g(input[13]), + g(input[2]), + g(input[11]), + g(input[4]), + g(input[9]), + g(input[6]), + g(input[7]), + g(input[8]), + g(input[5]), + g(input[10]), + g(input[3]), + g(input[12]), + g(input[1]), + g(input[14]), ]; if x.iter().all(|&v| v == 0) { output[..16].fill(0); @@ -615,8 +672,8 @@ pub(crate) fn iadst16(input: &[i32], output: &mut [i32]) { x[14] = dcrs(s14) as i64; x[15] = dcrs(s15) as i64; let o = [ - x[0], -x[8], x[12], -x[4], x[6], x[14], x[10], x[2], - x[3], x[11], x[15], x[7], x[5], -x[13], x[9], -x[1], + x[0], -x[8], x[12], -x[4], x[6], x[14], x[10], x[2], x[3], x[11], x[15], x[7], x[5], + -x[13], x[9], -x[1], ]; for (i, &v) in o.iter().enumerate() { output[i] = v as i32; @@ -630,19 +687,20 @@ pub(crate) fn inverse_transform_add( tx_size: usize, tx_type: usize, coeffs: &[i32], - dest: &mut [u8], + dest: &mut [Sample], off: usize, stride: usize, lossless: bool, + bd: u8, ) { if lossless { - iwht4x4_add(coeffs, &mut dest[off..], stride); + iwht4x4_add(coeffs, &mut dest[off..], stride, bd); return; } if tx_size == TX_32X32 { let mut out = [0i32; 1024]; for i in 0..32 { - idct32(&coeffs[i * 32..], &mut out[i * 32..]); + idct32(&coeffs[i * 32..], &mut out[i * 32..], bd); } let mut temp_in = [0i32; 32]; let mut temp_out = [0i32; 32]; @@ -650,10 +708,10 @@ pub(crate) fn inverse_transform_add( for (j, ti) in temp_in.iter_mut().enumerate() { *ti = out[j * 32 + i]; } - idct32(&temp_in, &mut temp_out); + idct32(&temp_in, &mut temp_out, bd); for j in 0..32 { let d = &mut dest[off + j * stride + i]; - *d = clip_add(*d, (temp_out[j] + 32) >> 6); + *d = clip_add(*d, (temp_out[j] + 32) >> 6, bd); } } return; @@ -666,7 +724,7 @@ pub(crate) fn inverse_transform_add( // ADST_DCT codes ADST vertical (= cols pass); DCT_ADST horizontal. let adst_cols = matches!(tx_type, ADST_DCT | ADST_ADST); let adst_rows = matches!(tx_type, DCT_ADST | ADST_ADST); - let (row_fn, col_fn): (fn(&[i32], &mut [i32]), fn(&[i32], &mut [i32])) = match tx_size { + let (row_fn, col_fn): (fn(&[i32], &mut [i32], u8), fn(&[i32], &mut [i32], u8)) = match tx_size { TX_4X4 => ( if adst_rows { iadst4 } else { idct4 }, if adst_cols { iadst4 } else { idct4 }, @@ -682,7 +740,7 @@ pub(crate) fn inverse_transform_add( }; let mut out = vec![0i32; n * n]; for i in 0..n { - row_fn(&coeffs[i * n..], &mut out[i * n..]); + row_fn(&coeffs[i * n..], &mut out[i * n..], bd); } let mut temp_in = vec![0i32; n]; let mut temp_out = vec![0i32; n]; @@ -690,15 +748,14 @@ pub(crate) fn inverse_transform_add( for j in 0..n { temp_in[j] = out[j * n + i]; } - col_fn(&temp_in, &mut temp_out); + col_fn(&temp_in, &mut temp_out, bd); for j in 0..n { let d = &mut dest[off + j * stride + i]; - *d = clip_add(*d, (temp_out[j] + (1 << (shift - 1))) >> shift); + *d = clip_add(*d, (temp_out[j] + (1 << (shift - 1))) >> shift, bd); } } } - #[cfg(test)] mod scratch_probe { use super::*; @@ -707,8 +764,8 @@ mod scratch_probe { for (name, tt) in [("dct_dct", DCT_DCT), ("dct_adst", DCT_ADST)] { let mut c = [0i32; 64]; c[0] = 38; - let mut d = vec![129u8; 64]; - inverse_transform_add(TX_8X8, tt, &c, &mut d, 0, 8, false); + let mut d = vec![129u16; 64]; + inverse_transform_add(TX_8X8, tt, &c, &mut d, 0, 8, false, 8); println!("{name}: {:?}", &d[..8]); } } diff --git a/crates/ec-vp9/tests/dump_probe.rs b/crates/ec-vp9/tests/dump_probe.rs index fbcece6b..93018e2e 100644 --- a/crates/ec-vp9/tests/dump_probe.rs +++ b/crates/ec-vp9/tests/dump_probe.rs @@ -17,7 +17,7 @@ fn diff_stats() { let mut first: Option<(usize, usize)> = None; for y in 0..240 { for x in 0..320 { - let a = pic.y[y * pic.stride + x]; + let a = pic.y[y * pic.stride + x] as u8; let b = refout[y * w + x]; let (sy, sx) = (y / 64, x / 64); sb_total[sy][sx] += 1; diff --git a/crates/ec-vp9/tests/hbd_exact.rs b/crates/ec-vp9/tests/hbd_exact.rs new file mode 100644 index 00000000..3a2c48e2 --- /dev/null +++ b/crates/ec-vp9/tests/hbd_exact.rs @@ -0,0 +1,101 @@ +//! Profile-2 high-bit-depth witness: 10-bit 4:2:0 decode is byte-exact +//! against ffmpeg's libvpx (`ffmpeg -v error -i in.ivf -f rawvideo -pix_fmt +//! yuv420p10le -`). Pre-fix the decoder refuses `profile 2` by name, so this +//! test fails at the first frame; post-fix every shown frame matches. +//! +//! Media-gated: the 10-bit corpus streams are gitignored, so the test skips +//! by name when the fixture is absent (set the fixture tree up per the lane +//! notes). The other two cases pin the refusals that STAY: non-4:2:0 +//! (profiles 1/3) and 12-bit. + +mod ivf; + +use ec_vp9::decode::Decoder; +use std::path::{Path, PathBuf}; + +fn fixture(name: &str) -> Option { + let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + p.pop(); + p.pop(); + p = p.join("fixtures/bitstreams").join(name); + p.exists().then_some(p) +} + +/// ffmpeg's rawvideo `yuv420p10le` bytes (little-endian u16 samples, +/// stride == visible width). +fn ffmpeg_raw_yuv10(path: &Path) -> Vec { + let out = std::process::Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p10le", "-"]) + .output() + .expect("ffmpeg must be on PATH for the witnesses"); + assert!(out.status.success(), "ffmpeg failed on {path:?}"); + out.stdout +} + +fn decode_all(path: &Path) -> (Vec>, u8) { + let bytes = std::fs::read(path).unwrap(); + let (_f, _w, _h, frames) = ivf::parse_ivf(&bytes); + let mut decoder = Decoder::new(); + let mut out = Vec::new(); + let mut bd = 0u8; + for frame in &frames { + if let Some(pic) = decoder.decode(&frame.data).expect("decode must succeed") { + bd = pic.bit_depth; + let mut v = Vec::with_capacity((pic.y.len() + pic.u.len() + pic.v.len()) * 2); + for &s in pic.y.iter().chain(pic.u.iter()).chain(pic.v.iter()) { + v.extend_from_slice(&s.to_le_bytes()); + } + out.push(v); + } + } + (out, bd) +} + +/// Both 10-bit corpus streams decode to the same pixels ffmpeg's libvpx +/// produces, sample for sample. +#[test] +fn profile2_10bit_is_byte_exact() { + let Some(a) = fixture("vp9-1080p-23.976-10bit.ivf") else { + eprintln!("SKIP profile2_10bit_is_byte_exact: 10-bit fixture absent"); + return; + }; + let (ours, bd) = decode_all(&a); + assert_eq!(bd, 10, "the fixture must decode at 10 bits"); + let want = ffmpeg_raw_yuv10(&a); + assert_eq!(ours.len(), 48, "shown frames"); + let mut off = 0usize; + for (i, got) in ours.iter().enumerate() { + let n = got.len(); + let end = off + n; + assert!(end <= want.len(), "frame {i}: ffmpeg stream too short"); + assert_eq!( + got.as_slice(), + &want[off..end], + "frame {i}: 10-bit planes differ from ffmpeg" + ); + off = end; + } + assert_eq!(off, want.len(), "frame count / plane size mismatch"); +} + +/// The refusals that STAY: profile 1 (4:4:4) is still refused by name. +#[test] +fn profile1_still_refused_by_name() { + let Some(p) = fixture("vp9-profile1-444.ivf") else { + eprintln!("SKIP profile1_still_refused_by_name: fixture absent"); + return; + }; + let bytes = std::fs::read(&p).unwrap(); + let (_f, _w, _h, frames) = ivf::parse_ivf(&bytes); + let mut decoder = Decoder::new(); + let err = decoder + .decode(&frames[0].data) + .expect_err("profile 1 must stay refused"); + let msg = err.to_string(); + assert!( + msg.contains("profile 1"), + "the refusal must name the profile, got: {msg}" + ); +} diff --git a/crates/ec-vp9/tests/inter_pixels_exact.rs b/crates/ec-vp9/tests/inter_pixels_exact.rs index 5d2f6ea0..689beed4 100644 --- a/crates/ec-vp9/tests/inter_pixels_exact.rs +++ b/crates/ec-vp9/tests/inter_pixels_exact.rs @@ -87,9 +87,9 @@ fn compare(path: &std::path::Path) -> usize { ); let want = &expected[off..off + frame_bytes]; let mut got = Vec::with_capacity(frame_bytes); - got.extend_from_slice(&pic.y); - got.extend_from_slice(&pic.u); - got.extend_from_slice(&pic.v); + got.extend(pic.y.iter().map(|&v| v as u8)); + got.extend(pic.u.iter().map(|&v| v as u8)); + got.extend(pic.v.iter().map(|&v| v as u8)); assert_eq!( got.len(), frame_bytes, diff --git a/crates/ec-vp9/tests/ivf.rs b/crates/ec-vp9/tests/ivf.rs index 161ff63b..cbafe2f1 100644 --- a/crates/ec-vp9/tests/ivf.rs +++ b/crates/ec-vp9/tests/ivf.rs @@ -31,9 +31,8 @@ pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec) { let mut pos = hdr_len; let mut frames = Vec::new(); while pos + 12 <= bytes.len() { - let sz = u32::from_le_bytes([ - bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3], - ]) as usize; + let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) + as usize; let pts = u64::from_le_bytes(bytes[pos + 4..pos + 12].try_into().unwrap()); pos += 12; if pos + sz > bytes.len() { @@ -51,8 +50,8 @@ pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec) { /// Root of the workspace checkout this test runs in (crates/ec-vp9/../..). #[allow(dead_code)] // shared by every test binary that does `mod ivf` pub fn fixture_dir() -> Option { - let bitstreams = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures/bitstreams"); + let bitstreams = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams"); if bitstreams.is_dir() { Some(bitstreams) } else { diff --git a/crates/ec-vp9/tests/keyframe_exact.rs b/crates/ec-vp9/tests/keyframe_exact.rs index d6ca1685..c4ac2a3c 100644 --- a/crates/ec-vp9/tests/keyframe_exact.rs +++ b/crates/ec-vp9/tests/keyframe_exact.rs @@ -71,13 +71,13 @@ fn compare(path: &std::path::Path) { assert_eq!(pic.u.len(), want_u.len()); assert_eq!(pic.v.len(), want_v.len()); for (i, (&a, &b)) in pic.y.iter().zip(want_y).enumerate() { - assert_eq!(a, b, "Y plane mismatch at pixel ({}, {}) frame {shown}", i % w, i / w); + assert_eq!(a as u8, b, "Y plane mismatch at pixel ({}, {}) frame {shown}", i % w, i / w); } for (i, (&a, &b)) in pic.u.iter().zip(want_u).enumerate() { - assert_eq!(a, b, "U plane mismatch at ({}, {}) frame {shown}", i % (w / 2), i / (w / 2)); + assert_eq!(a as u8, b, "U plane mismatch at ({}, {}) frame {shown}", i % (w / 2), i / (w / 2)); } for (i, (&a, &b)) in pic.v.iter().zip(want_v).enumerate() { - assert_eq!(a, b, "V plane mismatch at ({}, {}) frame {shown}", i % (w / 2), i / (w / 2)); + assert_eq!(a as u8, b, "V plane mismatch at ({}, {}) frame {shown}", i % (w / 2), i / (w / 2)); } shown += 1; } @@ -110,9 +110,9 @@ fn lossless_64_matches_ffmpeg() { let want_y = &reference[..w * h]; let want_u = &reference[w * h..w * h + uv]; let want_v = &reference[w * h + uv..]; - assert!(pic.y.iter().eq(want_y.iter()), "lossless Y must be byte-exact"); - assert!(pic.u.iter().eq(want_u.iter()), "lossless U must be byte-exact"); - assert!(pic.v.iter().eq(want_v.iter()), "lossless V must be byte-exact"); + assert!(pic.y.iter().map(|&v| v as u8).eq(want_y.iter().copied()), "lossless Y must be byte-exact"); + assert!(pic.u.iter().map(|&v| v as u8).eq(want_u.iter().copied()), "lossless U must be byte-exact"); + assert!(pic.v.iter().map(|&v| v as u8).eq(want_v.iter().copied()), "lossless V must be byte-exact"); assert_eq!((pic.width, pic.height), (w as u16, h as u16)); } @@ -137,9 +137,9 @@ fn inter_stream_decodes_and_matches_ffmpeg() { Some(pic) => { let off = shown * frame_bytes; let mut got = Vec::with_capacity(frame_bytes); - got.extend_from_slice(&pic.y); - got.extend_from_slice(&pic.u); - got.extend_from_slice(&pic.v); + got.extend(pic.y.iter().map(|&v| v as u8)); + got.extend(pic.u.iter().map(|&v| v as u8)); + got.extend(pic.v.iter().map(|&v| v as u8)); assert_eq!( got, expected[off..off + frame_bytes], diff --git a/crates/ec-vp9/tests/odd_dimensions_exact.rs b/crates/ec-vp9/tests/odd_dimensions_exact.rs index e21f7c6a..1bea8ab5 100644 --- a/crates/ec-vp9/tests/odd_dimensions_exact.rs +++ b/crates/ec-vp9/tests/odd_dimensions_exact.rs @@ -141,9 +141,9 @@ fn check(nw: u16, nh: u16) { "frame {i}: ffmpeg has fewer frames than we show" ); let mut got = Vec::with_capacity(frame_bytes); - got.extend_from_slice(&pic.y); - got.extend_from_slice(&pic.u); - got.extend_from_slice(&pic.v); + got.extend(pic.y.iter().map(|&v| v as u8)); + got.extend(pic.u.iter().map(|&v| v as u8)); + got.extend(pic.v.iter().map(|&v| v as u8)); assert_eq!( got, expected[off..off + frame_bytes], diff --git a/crates/ec-vp9/tests/scratch_lfdump.rs b/crates/ec-vp9/tests/scratch_lfdump.rs index 003fc5b8..5dec42fa 100644 --- a/crates/ec-vp9/tests/scratch_lfdump.rs +++ b/crates/ec-vp9/tests/scratch_lfdump.rs @@ -39,9 +39,9 @@ fn dump_lf_diff_map() { dec.decode(&frames[k].data).expect("decode"); } let pic_pre = dec.decode(&frames[fi].data).expect("decode").expect("shown"); - std::fs::write("/tmp/y_pre_ours.raw", &pic_pre.y[..ysz]).unwrap(); - std::fs::write("/tmp/u_pre_ours.raw", &pic_pre.u).unwrap(); - std::fs::write("/tmp/v_pre_ours.raw", &pic_pre.v).unwrap(); + std::fs::write("/tmp/y_pre_ours.raw", pic_pre.y[..ysz].iter().map(|&v| v as u8).collect::>()).unwrap(); + std::fs::write("/tmp/u_pre_ours.raw", pic_pre.u.iter().map(|&v| v as u8).collect::>()).unwrap(); + std::fs::write("/tmp/v_pre_ours.raw", pic_pre.v.iter().map(|&v| v as u8).collect::>()).unwrap(); unsafe { std::env::remove_var("EC_VP9_SKIP_LF") }; // Post-LF run (fresh decoder). @@ -50,17 +50,17 @@ fn dump_lf_diff_map() { dec.decode(&frames[k].data).expect("decode"); } let pic_post = dec.decode(&frames[fi].data).expect("decode").expect("shown"); - std::fs::write("/tmp/y_post_ours.raw", &pic_post.y[..ysz]).unwrap(); - std::fs::write("/tmp/u_post_ours.raw", &pic_post.u).unwrap(); - std::fs::write("/tmp/v_post_ours.raw", &pic_post.v).unwrap(); + std::fs::write("/tmp/y_post_ours.raw", pic_post.y[..ysz].iter().map(|&v| v as u8).collect::>()).unwrap(); + std::fs::write("/tmp/u_post_ours.raw", pic_post.u.iter().map(|&v| v as u8).collect::>()).unwrap(); + std::fs::write("/tmp/v_post_ours.raw", pic_post.v.iter().map(|&v| v as u8).collect::>()).unwrap(); let fsz = ysz + 2 * (w / 2) * (h / 2); let ff = &reference[fi * fsz..fi * fsz + ysz]; let pre = &pic_pre.y[..ysz]; let post = &pic_post.y[..ysz]; - let pre_diffs: Vec = (0..ysz).filter(|&i| pre[i] != ff[i]).collect(); - let post_diffs: Vec = (0..ysz).filter(|&i| post[i] != ff[i]).collect(); + let pre_diffs: Vec = (0..ysz).filter(|&i| pre[i] as u8 != ff[i]).collect(); + let post_diffs: Vec = (0..ysz).filter(|&i| post[i] as u8 != ff[i]).collect(); let lf_changed_ours: Vec = (0..ysz).filter(|&i| pre[i] != post[i]).collect(); println!("pre-LF diffs vs ffmpeg : {}", pre_diffs.len()); println!("post-LF diffs vs ffmpeg: {}", post_diffs.len()); @@ -123,10 +123,10 @@ fn dump_lf_diff_map() { let ff_u = &reference[fi * fsz + ysz..fi * fsz + ysz + uv]; let ff_v = &reference[fi * fsz + ysz + uv..fi * fsz + ysz + 2 * uv]; let uw = w / 2; - let u_d: Vec<_> = (0..uv).filter(|&i| pic_post.u[i] != ff_u[i]).collect(); - let v_d: Vec<_> = (0..uv).filter(|&i| pic_post.v[i] != ff_v[i]).collect(); - let u_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.u[i] != ff_u[i]).collect(); - let v_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.v[i] != ff_v[i]).collect(); + let u_d: Vec<_> = (0..uv).filter(|&i| pic_post.u[i] as u8 != ff_u[i]).collect(); + let v_d: Vec<_> = (0..uv).filter(|&i| pic_post.v[i] as u8 != ff_v[i]).collect(); + let u_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.u[i] as u8 != ff_u[i]).collect(); + let v_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.v[i] as u8 != ff_v[i]).collect(); println!("U pre diffs: {} post: {}", u_pre.len(), u_d.len()); for &i in &u_d { println!( diff --git a/crates/ec-vp9/tests/scratch_lossless.rs b/crates/ec-vp9/tests/scratch_lossless.rs index 2b1c9048..65d76c7d 100644 --- a/crates/ec-vp9/tests/scratch_lossless.rs +++ b/crates/ec-vp9/tests/scratch_lossless.rs @@ -12,7 +12,7 @@ fn lossless_matches() { let mut d = Decoder::new(); let pic = d.decode(&frames[0].data).unwrap().unwrap(); let ylen = w as usize * h as usize; - let mism: Vec = (0..ylen).filter(|&i| pic.y[i] != refout[i]).collect(); + let mism: Vec = (0..ylen).filter(|&i| pic.y[i] as u8 != refout[i]).collect(); println!("w={w} h={h} mismatches={} first={:?} ours={:?} ref={:?}", mism.len(), mism.first(), mism.first().map(|&i| pic.y[i]), mism.first().map(|&i| refout[i])); } diff --git a/crates/ec-vp9/tests/scratch_pixdump.rs b/crates/ec-vp9/tests/scratch_pixdump.rs index f2c9f1f1..6d343184 100644 --- a/crates/ec-vp9/tests/scratch_pixdump.rs +++ b/crates/ec-vp9/tests/scratch_pixdump.rs @@ -22,9 +22,13 @@ fn pixdump() { for (i, f) in frames.iter().enumerate() { match decoder.decode(&f.data) { Ok(Some(pic)) => { - dump.extend_from_slice(&pic.y); - dump.extend_from_slice(&pic.u); - dump.extend_from_slice(&pic.v); + for &v in pic.y.iter().chain(pic.u.iter()).chain(pic.v.iter()) { + if pic.bit_depth == 8 { + dump.push(v as u8); + } else { + dump.extend_from_slice(&v.to_le_bytes()); + } + } eprintln!( "PIXFRAME input={i} shown={shown} {w}x{h} {}x{}", pic.width, pic.height @@ -51,12 +55,8 @@ fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec) { let mut pos = hdr_len; let mut frames = Vec::new(); while pos + 12 <= bytes.len() { - let sz = u32::from_le_bytes([ - bytes[pos], - bytes[pos + 1], - bytes[pos + 2], - bytes[pos + 3], - ]) as usize; + let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) + as usize; let pts = u64::from_le_bytes(bytes[pos + 4..pos + 12].try_into().unwrap()); pos += 12; if pos + sz > bytes.len() { diff --git a/crates/ec-vp9/tests/scratch_pixdump10.rs b/crates/ec-vp9/tests/scratch_pixdump10.rs new file mode 100644 index 00000000..ab2d2f44 --- /dev/null +++ b/crates/ec-vp9/tests/scratch_pixdump10.rs @@ -0,0 +1,62 @@ +//! Scratch: dump every shown frame's planes as little-endian u16 for the +//! high-bit-depth pixel comparator. +//! +//! `INTER_IVF= EC_VP9_PIXDUMP= cargo test -p ec-vp9 --test scratch_pixdump10` +//! +//! Layout matches drv_pix10: per shown frame, Y (w*h), U and V each +//! (((w+1)/2)*((h+1)/2)) (chroma ceils), rows packed to the visible width, +//! each sample written as two little-endian bytes. + +use ec_vp9::decode::Decoder; + +#[test] +fn pixdump10() { + let (Ok(ivf), Ok(out)) = (std::env::var("INTER_IVF"), std::env::var("EC_VP9_PIXDUMP")) else { + eprintln!("SKIP scratch_pixdump10: set INTER_IVF and EC_VP9_PIXDUMP"); + return; + }; + let bytes = std::fs::read(&ivf).expect("read ivf"); + let (_, w, h, frames) = parse_ivf(&bytes); + let mut decoder = Decoder::new(); + let mut dump = Vec::new(); + let mut shown = 0usize; + for (i, f) in frames.iter().enumerate() { + match decoder.decode(&f) { + Ok(Some(pic)) => { + for &v in pic.y.iter().chain(pic.u.iter()).chain(pic.v.iter()) { + dump.extend_from_slice(&v.to_le_bytes()); + } + eprintln!( + "PIXFRAME input={i} shown={shown} {w}x{h} {}x{} bd={}", + pic.width, pic.height, pic.bit_depth + ); + shown += 1; + } + Ok(None) => eprintln!("PIXFRAME input={i} hidden"), + Err(e) => { + eprintln!("PIXERR input={i}: {e}"); + break; + } + } + } + std::fs::write(&out, &dump).expect("write dump"); + eprintln!("wrote {} bytes ({shown} shown frames)", dump.len()); +} + +fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec>) { + assert_eq!(&bytes[0..4], b"DKIF", "not an IVF file"); + let hdr_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize; + let fourcc = std::str::from_utf8(&bytes[8..12]).unwrap(); + let width = u16::from_le_bytes([bytes[12], bytes[13]]); + let height = u16::from_le_bytes([bytes[14], bytes[15]]); + let mut pos = hdr_len; + let mut frames = Vec::new(); + while pos + 12 <= bytes.len() { + let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) + as usize; + let data = bytes[pos + 12..pos + 12 + sz].to_vec(); + frames.push(data); + pos += 12 + sz; + } + (fourcc, width, height, frames) +} diff --git a/crates/ec-vp9/tests/scratch_realsweep.rs b/crates/ec-vp9/tests/scratch_realsweep.rs index da02791f..7bf27071 100644 --- a/crates/ec-vp9/tests/scratch_realsweep.rs +++ b/crates/ec-vp9/tests/scratch_realsweep.rs @@ -99,22 +99,22 @@ fn real_content_sweep() { if i == 0 { std::fs::write(dir.join("ours_f0.yuv"), { let mut v = Vec::with_capacity(ysz + 2 * uvs); - v.extend_from_slice(&pic.y[..ysz.min(pic.y.len())]); - v.extend_from_slice(&pic.u); - v.extend_from_slice(&pic.v); + v.extend(pic.y[..ysz.min(pic.y.len())].iter().map(|&x| x as u8)); + v.extend(pic.u.iter().map(|&x| x as u8)); + v.extend(pic.v.iter().map(|&x| x as u8)); v }) .unwrap(); std::fs::write(dir.join("ff_f0.yuv"), &raw.stdout[..ysz + 2 * uvs]).unwrap(); } let yd = (0..ysz) - .filter(|&k| pic.y[k] != raw.stdout[base + k]) + .filter(|&k| pic.y[k] as u8 != raw.stdout[base + k]) .count(); let ud = (0..uvs) - .filter(|&k| pic.u[k] != raw.stdout[base + ysz + k]) + .filter(|&k| pic.u[k] as u8 != raw.stdout[base + ysz + k]) .count(); let vd = (0..uvs) - .filter(|&k| pic.v[k] != raw.stdout[base + ysz + uvs + k]) + .filter(|&k| pic.v[k] as u8 != raw.stdout[base + ysz + uvs + k]) .count(); println!( "frame {i}: {w}x{h} stride {} uv_stride {} Y {yd} U {ud} V {vd}", diff --git a/crates/ec-vp9/tests/scratch_sweep.rs b/crates/ec-vp9/tests/scratch_sweep.rs index 87e981fa..fc05abbd 100644 --- a/crates/ec-vp9/tests/scratch_sweep.rs +++ b/crates/ec-vp9/tests/scratch_sweep.rs @@ -18,7 +18,7 @@ fn sweep() { let mut d = Decoder::new(); let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| d.decode(&frames[0].data))); let Ok(Ok(Some(pic))) = r else { continue }; - let m = (0..ylen).filter(|&i| pic.y[i] == refout[i]).count(); + let m = (0..ylen).filter(|&i| pic.y[i] as u8 == refout[i]).count(); if m > best.0 { best = (m, t); } } unsafe { std::env::remove_var("EC_VP9_FORCE_TAIL"); } diff --git a/lanes/vp9hbd.report.md b/lanes/vp9hbd.report.md new file mode 100644 index 00000000..dbaea001 --- /dev/null +++ b/lanes/vp9hbd.report.md @@ -0,0 +1,104 @@ +# lane-vp9-hbd — profile 2 (10-bit 4:2:0) decode, byte-exact vs libvpx 1.15 + +Base: `79984549` (main). Branch: `lane-vp9-hbd`. Worktree: +`~/Documents/Code/Rust/edith_codecs-vp9hbd`. Target dir: +`$HOME/.cache/cargo-target-vp9hbd`. Not pushed. + +## What changed + +One representation for both depths: every plane is `u16` (`ec_vp9::Sample`, +8-bit values in the low byte) and every pixel kernel takes the frame's `bd` +and clamps with `clip_pixel_bd(v, bd)`. The reconstruction walk is single; +8-bit and high-bit-depth kernels are the same transcribed butterflies with +`bd`-scaled clips/thresholds (exactly how libvpx splits its C kernels). No +forked decode paths. + +- `decode.rs`: `Planes`/`Picture` are u16 + `bd`; `Planes::new` fills the + neutral grey `1 << (bd - 1)`; profile gate accepts 0/2, refuses 1/3; + new bit-depth gate refuses 12-bit by name; subsampling gate (4:2:0 only) + unchanged and STAYS. Loop filter + intra + transform calls thread `bd`. +- `intra.rs`: u16 staging; `base = 128 << (bd - 8)` replaces the 127/129 + fills; DC/`TM` use `base`/`clip_pixel_bd`. +- `transform.rs`: `clip_add(d, v, bd)`; idct/iadst take `bd` and port + libvpx's `detect_invalid_highbd_input` guard (zero output on a + magnitude ≥ 2^25 when bd ≠ 8); butterflies unchanged. +- `mc.rs`: u16 planes + u16 convolve intermediate; `RefPlane.bd`; the + intermediate clamp is `clip_pixel_bd(v, bd)` (== `clip_pixel` at bd 8). +- `loopfilter.rs`: u16; `sc(x, bd)` == libvpx `signed_char_clamp_high`; + `limit`/`blimit`/flat/hev thresholds scaled by `1 << (bd - 8)`. +- `tokens.rs`: **the one depth-dependent bitstream element** — the CAT6 + coefficient token. 8-bit: 14 extra bits at `vp9_cat6_prob`; 10-bit (and + 12-bit): 16 extra bits at `vp9_cat6_prob_high12 + 2`. Ported. +- Tests updated for u16 planes; new `hbd_exact.rs`; `scratch_pixdump10.rs` + (u16-LE dumper harness). + +## Fail-pre-fix witness + +Pre-fix, `Decoder::decode` on the 10-bit stream returned +`unsupported: vp9 profile 2 — this lane decodes profile 0 only` at +`decode.rs:211`. `hbd_exact.rs::profile2_10bit_is_byte_exact` fails at the +first frame on the pre-fix tree for that reason. + +## Oracle + +`$HOME/.cache/vp9hbd/` = a fresh libvpx 1.15.0 built with +`--enable-vp9-highbitdepth` (`CONFIG_VP9_HIGHBITDEPTH 1`), plus +`drv_pix10.c` (cropped planes as little-endian u16, frame-indexed, +`PIXDUMP=`). Verified against ffmpeg `rawvideo yuv420p10le`. + +## Byte-exactness (cmp of frame-aligned dumps) + +| stream | frames | ours vs libvpx 1.15 | +|---|---|---| +| vp9-1080p-23.976-10bit (profile 2) | 48 | **BYTE-IDENTICAL** | +| vp9-1080p-60-10bit (profile 2) | 120 | **BYTE-IDENTICAL** | +| vp9-1080p-23.976-8bit | 48 | BYTE-IDENTICAL | +| vp9-1080p-60-8bit | 120 | BYTE-IDENTICAL | +| vp9-2160p-23.976-8bit | — | BYTE-IDENTICAL | +| vp9-superframe-altref | — | BYTE-IDENTICAL | +| vp9-tiles-1280 | — | BYTE-IDENTICAL | + +Inter/odd fixtures are covered by the media-gated `inter_pixels_exact.rs` +and `odd_dimensions_exact.rs` (green). 8-bit corpus re-swept on this build; +all identical. + +Repro: +``` +F=fixtures/bitstreams/vp9-1080p-23.976-10bit.ivf +CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9hbd INTER_IVF=$F \ + EC_VP9_PIXDUMP=$HOME/.cache/vp9hbd/ours10.pix \ + cargo test -q -p ec-vp9 --test scratch_pixdump10 -- --nocapture +PIXDUMP=$HOME/.cache/vp9hbd/or10.pix $HOME/.cache/vp9hbd/drv_pix10 $F +cmp $HOME/.cache/vp9hbd/ours10.pix $HOME/.cache/vp9hbd/or10.pix # identical +``` + +## Gates + +- `cargo test -p ec-vp9` green (all suites; `hbd_exact` 2/2). +- Warning parity: exactly the 5 pre-existing (TM_PRED, read_partition, + partition_props, x_mis, y_mis). +- Scoped rustfmt on touched files; main checkout untouched (only the + pre-existing untracked `EDITH_FINDINGS.md`). + +## Debug technique that found the CAT6 bug (reusable) + +A 10-bit stream desynced in the tile bool decoder at 8-bit-correct syntax. +The depth-dependent element is invisible to code reading. Method: built an +HBD oracle, patched `vpx_read` to print `BR c= p= b=`, +matched our `EC_VP9_TRACE` `B ` lines, found the +first differing prob (ours 195 = un-updated default, oracle 85), and read +libvpx's `decode_coefs` CAT6 branch — 16 bits/`vp9_cat6_prob_high12 + 2` at +bd 10. `OMODE` (patched `read_intra_frame_mode_info`) proved the divergence +was AFTER mode info, not in it. + +## Deferred / out of scope (unchanged) + +- 12-bit decode (profile 2 12-bit): refused by name. No corpus stream. +- Profiles 1/3, non-4:2:0 subsampling: refused by name. +- Sibling lane owns intra-only + reference scaling; size-change refusal + (`decode.rs` reference-size check) untouched. + +## Instruments left in tree + +- `decode.rs`: the tile desync error now names the tile and overread count + (was a bare `ensure`); behaviour otherwise unchanged.