forge
Explore
Log in

Don't you dare go Hollow

vp9: decode profile 2 (10-bit 4:2:0) byte-exact vs libvpx 1.15

Browse files at this commit

9025ed3c0e94139be4a2968fefee9ac9febfc18cAhmet Kaan GümüşParent: 02d10ba
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.rsmodified+114 -58
@@ -4,13 +4,14 @@
4 //! reconstruction and the loop filter (spec 6, 7, 8; libvpx4 //! reconstruction and the loop filter (spec 6, 7, 8; libvpx
5 //! `vp9_decodeframe.c`).5 //! `vp9_decodeframe.c`).
6 //!6 //!
7-//! Capability: profile-0 8-bit 4:2:0 keyframes and inter frames (motion7+//! Capability: profile-0 8-bit and profile-2 10-bit 4:2:0 keyframes and inter
8-//! compensation, residual reconstruction, the loop filter and an 8-slot8+//! frames (motion compensation, residual reconstruction, the loop filter and
9-//! reference DPB). Intra-only frames, other profiles/subsamplings and a9+//! an 8-slot reference DPB). Intra-only frames, profiles 1/3, 12-bit, other
10-//! reference whose coded size differs from the current frame are refused by10+//! subsamplings and a reference whose coded size differs from the current
11-//! name; `show_existing_frame` returns the buffered reference picture instead11+//! frame are refused by name; `show_existing_frame` returns the buffered
12-//! of pretending to decode. Odd coded extents are supported: chroma stores12+//! reference picture instead of pretending to decode. Odd coded extents are
13-//! and crops at `(w + 1) / 2` (`uv_crop_width`), matching libvpx.13+//! supported: chroma stores and crops at `(w + 1) / 2` (`uv_crop_width`),
14+//! matching libvpx.
14 15
15 use crate::header::{FrameContext, read_compressed_header};16 use crate::header::{FrameContext, read_compressed_header};
16 use crate::intra::build_intra_predictors;17 use crate::intra::build_intra_predictors;
@@ -20,7 +21,7 @@ use crate::modes::{MiInfo, MiState, read_intra_frame_mode_info};
20 use crate::tables::*;21 use crate::tables::*;
21 use crate::tokens::{PlaneContexts, decode_coefs, scan_for};22 use crate::tokens::{PlaneContexts, decode_coefs, scan_for};
22 use crate::transform::inverse_transform_add;23 use crate::transform::inverse_transform_add;
23-use crate::{Error, Result};24+use crate::{Error, Result, Sample};
24 use ec_vp9_syntax::{FrameHeader, FrameType, Vp9Parser, superframe};25 use ec_vp9_syntax::{FrameHeader, FrameType, Vp9Parser, superframe};
25 26
26 const SB_MI: usize = 8; // a 64x64 superblock in mi (8x8) units27 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
28 /// A decoded, displayable frame: cropped contiguous planes.29 /// A decoded, displayable frame: cropped contiguous planes.
29 #[derive(Clone, Debug)]30 #[derive(Clone, Debug)]
30 pub struct Picture {31 pub struct Picture {
31- /// Luma plane, `stride`-spaced rows of `width` pixels.32+ /// Luma plane, `stride`-spaced rows of `width` samples.
32- pub y: Vec<u8>,33+ pub y: Vec<Sample>,
33 /// U (Cb) plane, half resolution.34 /// U (Cb) plane, half resolution.
34- pub u: Vec<u8>,35+ pub u: Vec<Sample>,
35 /// V (Cr) plane, half resolution.36 /// V (Cr) plane, half resolution.
36- pub v: Vec<u8>,37+ pub v: Vec<Sample>,
37 /// Frame width in pixels.38 /// Frame width in pixels.
38 pub width: u16,39 pub width: u16,
39 /// Frame height in pixels.40 /// Frame height in pixels.
@@ -43,28 +44,51 @@ pub struct Picture {
43 /// Chroma row pitch of the returned planes (`(width + 1) / 2`; chroma44 /// Chroma row pitch of the returned planes (`(width + 1) / 2`; chroma
44 /// ceils an odd coded width).45 /// ceils an odd coded width).
45 pub uv_stride: usize,46 pub uv_stride: usize,
47+ /// Bits per sample (8 for profile 0, 10 for profile 2).
48+ pub bit_depth: u8,
46 }49 }
47 50
48 struct Planes {51 struct Planes {
49- y: Vec<u8>,52+ y: Vec<Sample>,
50- u: Vec<u8>,53+ u: Vec<Sample>,
51- v: Vec<u8>,54+ v: Vec<Sample>,
52 ys: usize,55 ys: usize,
53 uvs: usize,56 uvs: usize,
54 aw: usize,57 aw: usize,
55 ah: usize,58 ah: usize,
59+ /// Bits per sample this frame was decoded at.
60+ bd: u8,
56 }61 }
57 62
58 impl Planes {63 impl Planes {
64+ /// A frame scratch at the 64-multiple ALIGNED extent, filled with the
65+ /// neutral grey `1 << (bd - 1)` (`128` at 8-bit, `512` at 10-bit). The
66+ /// aligned the decode writes real samples into it (blocks at the frame
67+ /// edge decode at FULL size), so the fill only backs the never-written
68+ /// padding past the MI extent.
69+ fn new(aw: usize, ah: usize, bd: u8) -> Planes {
70+ let fill = 1u16 << (bd - 1);
71+ Planes {
72+ y: vec![fill; aw * ah],
73+ u: vec![fill; aw / 2 * ah / 2],
74+ v: vec![fill; aw / 2 * ah / 2],
75+ ys: aw,
76+ uvs: aw / 2,
77+ aw,
78+ ah,
79+ bd,
80+ }
81+ }
82+
59 /// Immutable plane + stride (the predictor reads references).83 /// Immutable plane + stride (the predictor reads references).
60- fn plane_ref(&self, plane: usize) -> (&[u8], usize) {84+ fn plane_ref(&self, plane: usize) -> (&[Sample], usize) {
61 match plane {85 match plane {
62 0 => (&self.y, self.ys),86 0 => (&self.y, self.ys),
63 1 => (&self.u, self.uvs),87 1 => (&self.u, self.uvs),
64 _ => (&self.v, self.uvs),88 _ => (&self.v, self.uvs),
65 }89 }
66 }90 }
67- fn plane(&mut self, plane: usize) -> (&mut [u8], usize) {91+ fn plane(&mut self, plane: usize) -> (&mut [Sample], usize) {
68 match plane {92 match plane {
69 0 => (&mut self.y, self.ys),93 0 => (&mut self.y, self.ys),
70 1 => (&mut self.u, self.uvs),94 1 => (&mut self.u, self.uvs),
@@ -107,10 +131,10 @@ pub struct Decoder {
107 syntax_blocks: usize,131 syntax_blocks: usize,
108 /// `twd->extend_and_predict_buf`: the per-prediction bordered reference132 /// `twd->extend_and_predict_buf`: the per-prediction bordered reference
109 /// window built when a block's read leaves the reference frame.133 /// window built when a block's read leaves the reference frame.
110- mc_scratch: Vec<u8>,134+ mc_scratch: Vec<Sample>,
111 /// The `vpx_convolve8` stride-64 intermediate plus the second scratch its135 /// The `vpx_convolve8` stride-64 intermediate plus the second scratch its
112 /// averaging variant needs.136 /// averaging variant needs.
113- mc_temp: Vec<u8>,137+ mc_temp: Vec<Sample>,
114 }138 }
115 139
116 /// One DPB slot: a decoded frame buffer at its ALIGNED (64-multiple) extent140 /// One DPB slot: a decoded frame buffer at its ALIGNED (64-multiple) extent
@@ -208,10 +232,16 @@ impl Decoder {
208 None => Err(corrupt("show_existing_frame names an empty slot")),232 None => Err(corrupt("show_existing_frame names an empty slot")),
209 };233 };
210 }234 }
211- if hdr.profile != 0 {235+ if hdr.profile != 0 && hdr.profile != 2 {
212 return Err(Error::unsupported(236 return Err(Error::unsupported(
213 format!("vp9 profile {}", hdr.profile),237 format!("vp9 profile {}", hdr.profile),
214- "this lane decodes profile 0 only",238+ "this lane decodes profiles 0 and 2 only (profiles 1 and 3 are 4:4:4)",
239+ ));
240+ }
241+ if hdr.bit_depth != 8 && hdr.bit_depth != 10 {
242+ return Err(Error::unsupported(
243+ format!("vp9 bit depth {}", hdr.bit_depth),
244+ "this lane decodes 8- and 10-bit only (12-bit is not ported)",
215 ));245 ));
216 }246 }
217 if hdr.subsampling_x != 1 || hdr.subsampling_y != 1 {247 if hdr.subsampling_x != 1 || hdr.subsampling_y != 1 {
@@ -306,10 +336,16 @@ impl Decoder {
306 if hdr.show_existing_frame {336 if hdr.show_existing_frame {
307 continue;337 continue;
308 }338 }
309- if hdr.profile != 0 {339+ if hdr.profile != 0 && hdr.profile != 2 {
310 return Err(Error::unsupported(340 return Err(Error::unsupported(
311 format!("vp9 profile {}", hdr.profile),341 format!("vp9 profile {}", hdr.profile),
312- "this lane decodes profile 0 only",342+ "this lane decodes profiles 0 and 2 only (profiles 1 and 3 are 4:4:4)",
343+ ));
344+ }
345+ if hdr.bit_depth != 8 && hdr.bit_depth != 10 {
346+ return Err(Error::unsupported(
347+ format!("vp9 bit depth {}", hdr.bit_depth),
348+ "this lane decodes 8- and 10-bit only (12-bit is not ported)",
313 ));349 ));
314 }350 }
315 if hdr.frame_type == FrameType::Key {351 if hdr.frame_type == FrameType::Key {
@@ -384,15 +420,7 @@ impl Decoder {
384 let height = hdr.height as usize;420 let height = hdr.height as usize;
385 let aw = width.div_ceil(64) * 64;421 let aw = width.div_ceil(64) * 64;
386 let ah = height.div_ceil(64) * 64;422 let ah = height.div_ceil(64) * 64;
387- self.planes = Some(Planes {423+ self.planes = Some(Planes::new(aw, ah, hdr.bit_depth));
388- y: vec![128u8; aw * ah],
389- u: vec![128u8; aw / 2 * ah / 2],
390- v: vec![128u8; aw / 2 * ah / 2],
391- ys: aw,
392- uvs: aw / 2,
393- aw,
394- ah,
395- });
396 }424 }
397 425
398 let hdr_start = hdr.uncompressed_header_size as usize;426 let hdr_start = hdr.uncompressed_header_size as usize;
@@ -596,6 +624,7 @@ impl Decoder {
596 vh,624 vh,
597 vh / 2,625 vh / 2,
598 hdr.loop_filter.sharpness,626 hdr.loop_filter.sharpness,
627+ hdr.bit_depth,
599 );628 );
600 }629 }
601 630
@@ -897,8 +926,20 @@ impl Decoder {
897 let temp = &mut self.mc_temp;926 let temp = &mut self.mc_temp;
898 for plane in 0..3usize {927 for plane in 0..3usize {
899 inter_predict_plane(928 inter_predict_plane(
900- planes, refs, scratch, temp, hdr, info, plane, row, col, &n4w, &n4h,929+ planes,
901- mb_to_right, mb_to_bottom, sb_type,930+ refs,
931+ scratch,
932+ temp,
933+ hdr,
934+ info,
935+ plane,
936+ row,
937+ col,
938+ &n4w,
939+ &n4h,
940+ mb_to_right,
941+ mb_to_bottom,
942+ sb_type,
902 )?;943 )?;
903 }944 }
904 }945 }
@@ -950,6 +991,7 @@ impl Decoder {
950 // decodeframe.c:413).991 // decodeframe.c:413).
951 let planes = self.planes.as_mut().expect("frame scratch");992 let planes = self.planes.as_mut().expect("frame scratch");
952 let stride = planes.dims(plane).0;993 let stride = planes.dims(plane).0;
994+ let bd = planes.bd;
953 let x0 = ((col * 8) >> s) + bcol * 4;995 let x0 = ((col * 8) >> s) + bcol * 4;
954 let y0 = ((row * 8) >> s) + brow * 4;996 let y0 = ((row * 8) >> s) + brow * 4;
955 let dst_off = y0 * stride + x0;997 let dst_off = y0 * stride + x0;
@@ -962,6 +1004,7 @@ impl Decoder {
962 dst_off,1004 dst_off,
963 stride,1005 stride,
964 hdr.quantization.lossless(),1006 hdr.quantization.lossless(),
1007+ bd,
965 );1008 );
966 }1009 }
967 }1010 }
@@ -990,15 +1033,7 @@ impl Decoder {
990 // mi_row 132 writes 8 rows past a 1080-row buffer).1033 // mi_row 132 writes 8 rows past a 1080-row buffer).
991 let aw = width.div_ceil(64) * 64;1034 let aw = width.div_ceil(64) * 64;
992 let ah = height.div_ceil(64) * 64;1035 let ah = height.div_ceil(64) * 64;
993- self.planes = Some(Planes {1036+ self.planes = Some(Planes::new(aw, ah, hdr.bit_depth));
994- y: vec![128u8; aw * ah],
995- u: vec![128u8; aw / 2 * ah / 2],
996- v: vec![128u8; aw / 2 * ah / 2],
997- ys: aw,
998- uvs: aw / 2,
999- aw,
1000- ah,
1001- });
1002 let tail_start = std::env::var("EC_VP9_FORCE_TAIL")1037 let tail_start = std::env::var("EC_VP9_FORCE_TAIL")
1003 .ok()1038 .ok()
1004 .and_then(|s| s.parse().ok())1039 .and_then(|s| s.parse().ok())
@@ -1131,7 +1166,12 @@ impl Decoder {
1131 )?;1166 )?;
1132 }1167 }
1133 }1168 }
1134- ensure(r.overreads() == 0, "tile bool decoder desync")?;1169+ if r.overreads() != 0 {
1170+ return Err(corrupt(format!(
1171+ "tile bool decoder desync (tile tr={tr} tc={tc} overreads={})",
1172+ r.overreads()
1173+ )));
1174+ }
1135 }1175 }
1136 }1176 }
1137 1177
@@ -1151,6 +1191,7 @@ impl Decoder {
1151 vh,1191 vh,
1152 vh / 2,1192 vh / 2,
1153 hdr.loop_filter.sharpness,1193 hdr.loop_filter.sharpness,
1194+ hdr.bit_depth,
1154 );1195 );
1155 }1196 }
1156 1197
@@ -1402,7 +1443,17 @@ impl Decoder {
1402 // mode class (`get_filter_level`), so the grids are written1443 // mode class (`get_filter_level`), so the grids are written
1403 // inside the reconstruction rather than from `level_of_seg`.1444 // inside the reconstruction rather than from `level_of_seg`.
1404 self.reconstruct_inter_pixels(1445 self.reconstruct_inter_pixels(
1405- r, ectx, grids, hdr, &info, row, col, sb_type, bw, bh, mi,1446+ r,
1447+ ectx,
1448+ grids,
1449+ hdr,
1450+ &info,
1451+ row,
1452+ col,
1453+ sb_type,
1454+ bw,
1455+ bh,
1456+ mi,
1406 tile_col_start,1457 tile_col_start,
1407 )?;1458 )?;
1408 } else {1459 } else {
@@ -1412,10 +1463,7 @@ impl Decoder {
1412 }1463 }
1413 for dy in 0..y_mis {1464 for dy in 0..y_mis {
1414 for dx in 0..x_mis {1465 for dx in 0..x_mis {
1415- if crate::mvdbg2_enabled()1466+ if crate::mvdbg2_enabled() && row + dy == 7 && col + dx >= 30 && col + dx <= 40
1416- && row + dy == 7
1417- && col + dx >= 30
1418- && col + dx <= 40
1419 {1467 {
1420 eprintln!(1468 eprintln!(
1421 "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={}",1469 "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 {
1558 };1606 };
1559 let planes = self.planes.as_mut().expect("frame scratch");1607 let planes = self.planes.as_mut().expect("frame scratch");
1560 let stride = planes.dims(plane).0;1608 let stride = planes.dims(plane).0;
1609+ let bd = planes.bd;
1561 let bs = 4 << tx_size;1610 let bs = 4 << tx_size;
1562 let x0 = ((mi_col * 8) >> s) + tx_col * 4;1611 let x0 = ((mi_col * 8) >> s) + tx_col * 4;
1563 let y0 = ((mi_row * 8) >> s) + tx_row * 4;1612 let y0 = ((mi_row * 8) >> s) + tx_row * 4;
@@ -1599,6 +1648,7 @@ impl Decoder {
1599 rgt,1648 rgt,
1600 mb_to_bottom < 0,1649 mb_to_bottom < 0,
1601 mb_to_right < 0,1650 mb_to_right < 0,
1651+ bd,
1602 );1652 );
1603 }1653 }
1604 1654
@@ -1665,6 +1715,7 @@ impl Decoder {
1665 nb,1715 nb,
1666 &self.ctx.coef[tx_size],1716 &self.ctx.coef[tx_size],
1667 false,1717 false,
1718+ bd,
1668 (x0, y0),1719 (x0, y0),
1669 plane,1720 plane,
1670 );1721 );
@@ -1710,7 +1761,7 @@ impl Decoder {
1710 Some((it.next()?.parse::<usize>().ok()?, it.next()?.parse().ok()?))1761 Some((it.next()?.parse::<usize>().ok()?, it.next()?.parse().ok()?))
1711 })1762 })
1712 .is_some_and(|(px, py)| x0 == px && y0 == py);1763 .is_some_and(|(px, py)| x0 == px && y0 == py);
1713- let t: Option<Vec<Vec<u8>>> = if probe {1764+ let t: Option<Vec<Vec<Sample>>> = if probe {
1714 Some(1765 Some(
1715 (0..4usize)1766 (0..4usize)
1716 .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec())1767 .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec())
@@ -1727,9 +1778,10 @@ impl Decoder {
1727 dst_off,1778 dst_off,
1728 stride,1779 stride,
1729 lossless,1780 lossless,
1781+ bd,
1730 );1782 );
1731 if let Some(before) = t {1783 if let Some(before) = t {
1732- let after: Vec<Vec<u8>> = (0..4usize)1784+ let after: Vec<Vec<Sample>> = (0..4usize)
1733 .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec())1785 .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec())
1734 .collect();1786 .collect();
1735 eprintln!("RC x0={x0} y0={y0} tx={tx_size} mode={mode}");1787 eprintln!("RC x0={x0} y0={y0} tx={tx_size} mode={mode}");
@@ -1764,7 +1816,7 @@ fn bsize_of_n4(n4: usize) -> usize {
1764 /// aligned decode buffer.1816 /// aligned decode buffer.
1765 fn crop_picture(planes: &Planes, width: u16, height: u16) -> Picture {1817 fn crop_picture(planes: &Planes, width: u16, height: u16) -> Picture {
1766 let (w, h) = (width as usize, height as usize);1818 let (w, h) = (width as usize, height as usize);
1767- let crop = |src: &[u8], stride: usize, cw: usize, ch: usize| -> Vec<u8> {1819+ let crop = |src: &[Sample], stride: usize, cw: usize, ch: usize| -> Vec<Sample> {
1768 let mut out = Vec::with_capacity(cw * ch);1820 let mut out = Vec::with_capacity(cw * ch);
1769 for row in 0..ch {1821 for row in 0..ch {
1770 out.extend_from_slice(&src[row * stride..row * stride + cw]);1822 out.extend_from_slice(&src[row * stride..row * stride + cw]);
@@ -1782,6 +1834,7 @@ fn crop_picture(planes: &Planes, width: u16, height: u16) -> Picture {
1782 height,1834 height,
1783 stride: w,1835 stride: w,
1784 uv_stride: cw,1836 uv_stride: cw,
1837+ bit_depth: planes.bd,
1785 }1838 }
1786 }1839 }
1787 1840
@@ -1837,7 +1890,9 @@ fn reset_skip_context(
1837 let offx = (col << 1) >> s;1890 let offx = (col << 1) >> s;
1838 let offy = (row << 1) >> s;1891 let offy = (row << 1) >> s;
1839 let lrows = 32usize >> s;1892 let lrows = 32usize >> s;
1840- let a: Vec<u8> = (0..n4w[plane]).map(|i| ectx[plane].above[offx + i]).collect();1893+ let a: Vec<u8> = (0..n4w[plane])
1894+ .map(|i| ectx[plane].above[offx + i])
1895+ .collect();
1841 let l: Vec<u8> = (0..n4h[plane].min(lrows))1896 let l: Vec<u8> = (0..n4h[plane].min(lrows))
1842 .map(|i| ectx[plane].left[(offy + i) % lrows])1897 .map(|i| ectx[plane].left[(offy + i) % lrows])
1843 .collect();1898 .collect();
@@ -1962,6 +2017,7 @@ fn decode_inter_tx_tokens(
1962 nb,2017 nb,
1963 &fc.coef[tx_size],2018 &fc.coef[tx_size],
1964 info.is_inter,2019 info.is_inter,
2020+ hdr.bit_depth,
1965 (0, 0),2021 (0, 0),
1966 plane,2022 plane,
1967 );2023 );
@@ -2001,8 +2057,8 @@ fn decode_inter_tx_tokens(
2001 fn inter_predict_plane(2057 fn inter_predict_plane(
2002 planes: &mut Planes,2058 planes: &mut Planes,
2003 refs: &[Option<RefFrame>; 8],2059 refs: &[Option<RefFrame>; 8],
2004- scratch: &mut Vec<u8>,2060+ scratch: &mut Vec<Sample>,
2005- temp: &mut Vec<u8>,2061+ temp: &mut Vec<Sample>,
2006 hdr: &FrameHeader,2062 hdr: &FrameHeader,
2007 info: &MiInfo,2063 info: &MiInfo,
2008 plane: usize,2064 plane: usize,
@@ -2043,6 +2099,7 @@ fn inter_predict_plane(
2043 // column (or row).2099 // column (or row).
2044 width: (ref_frame.width as usize + s) >> s,2100 width: (ref_frame.width as usize + s) >> s,
2045 height: (ref_frame.height as usize + s) >> s,2101 height: (ref_frame.height as usize + s) >> s,
2102+ bd: ref_frame.planes.bd,
2046 };2103 };
2047 if sb_type < 3 {2104 if sb_type < 3 {
2048 // libvpx builds one 4x4 prediction per sub-block, with the MV from2105 // libvpx builds one 4x4 prediction per sub-block, with the MV from
@@ -2059,9 +2116,8 @@ fn inter_predict_plane(
2059 average_split_mvs_chroma(&info.bmi_mv, rf)2116 average_split_mvs_chroma(&info.bmi_mv, rf)
2060 };2117 };
2061 let (data, _) = planes.plane(plane);2118 let (data, _) = planes.plane(plane);
2062- let dst_off = (((row * 8) >> s) + y * 4) * dst_stride2119+ let dst_off =
2063- + ((col * 8) >> s)2120+ (((row * 8) >> s) + y * 4) * dst_stride + ((col * 8) >> s) + xx * 4;
2064- + xx * 4;
2065 build_inter_predictors(2121 build_inter_predictors(
2066 &mut data[dst_off..],2122 &mut data[dst_off..],
2067 dst_stride,2123 dst_stride,
crates/ec-vp9/src/intra.rsmodified+61 -30
@@ -7,16 +7,18 @@
7 //! corner), `above_data[16 + i]` is `above[i]` — exactly the C's7 //! corner), `above_data[16 + i]` is `above[i]` — exactly the C's
8 //! 16-pixel offset into `above_data[64 + 16]`.8 //! 16-pixel offset into `above_data[64 + 16]`.
9 9
10+use crate::Sample;
11+
10 /// `AVG3`.12 /// `AVG3`.
11 #[inline]13 #[inline]
12-fn avg3(a: u8, b: u8, c: u8) -> u8 {14+fn avg3(a: Sample, b: Sample, c: Sample) -> Sample {
13- ((a as u32 + 2 * b as u32 + c as u32 + 2) >> 2) as u815+ ((a as u32 + 2 * b as u32 + c as u32 + 2) >> 2) as Sample
14 }16 }
15 17
16 /// `AVG2`.18 /// `AVG2`.
17 #[inline]19 #[inline]
18-fn avg2(a: u8, b: u8) -> u8 {20+fn avg2(a: Sample, b: Sample) -> Sample {
19- ((a as u32 + b as u32 + 1) >> 1) as u821+ ((a as u32 + b as u32 + 1) >> 1) as Sample
20 }22 }
21 23
22 const A: usize = 16;24 const A: usize = 16;
@@ -43,7 +45,7 @@ fn needs(mode: u8) -> (bool, bool, bool) {
43 /// block's absolute sample position; `frame_w`/`frame_h` the coded45 /// block's absolute sample position; `frame_w`/`frame_h` the coded
44 /// (aligned) plane size.46 /// (aligned) plane size.
45 pub(crate) fn build_intra_predictors(47 pub(crate) fn build_intra_predictors(
46- data: &mut [u8],48+ data: &mut [Sample],
47 stride: usize,49 stride: usize,
48 frame_w: usize,50 frame_w: usize,
49 frame_h: usize,51 frame_h: usize,
@@ -61,11 +63,16 @@ pub(crate) fn build_intra_predictors(
61 bot_ext: bool,63 bot_ext: bool,
62 // `xd->mb_to_right_edge < 0` (`vp9_reconintra.c:326/354`).64 // `xd->mb_to_right_edge < 0` (`vp9_reconintra.c:326/354`).
63 right_ext: bool,65 right_ext: bool,
66+ bd: u8,
64 ) {67 ) {
65 let (need_left, need_above, need_aboveright) = needs(mode);68 let (need_left, need_above, need_aboveright) = needs(mode);
66- let mut left_col = [0u8; 32];69+ // `int base = 128 << (bd - 8)` (`vp9_reconintra.c:132`): the 127/129
67- let mut above_data = [0u8; 64 + 16];70+ // border fills of an 8-bit frame become `base - 1` / `base + 1`, and
68- let at = |dx: isize, dy: isize| -> u8 {71+ // missing neighbours fill with the neutral grey.
72+ let base = 128u16 << (bd - 8);
73+ let mut left_col = [0u16; 32];
74+ let mut above_data = [0u16; 64 + 16];
75+ let at = |dx: isize, dy: isize| -> Sample {
69 data[(((y0 as isize + dy) * stride as isize) + x0 as isize + dx) as usize]76 data[(((y0 as isize + dy) * stride as isize) + x0 as isize + dx) as usize]
70 };77 };
71 78
@@ -89,7 +96,7 @@ pub(crate) fn build_intra_predictors(
89 left_col[n..bs].fill(v);96 left_col[n..bs].fill(v);
90 }97 }
91 } else {98 } else {
92- left_col[..bs].fill(129);99+ left_col[..bs].fill(base + 1);
93 }100 }
94 }101 }
95 102
@@ -114,17 +121,17 @@ pub(crate) fn build_intra_predictors(
114 above_data[A + i] = at(i as isize, -1);121 above_data[A + i] = at(i as isize, -1);
115 }122 }
116 }123 }
117- above_data[A - 1] = if left_available { at(-1, -1) } else { 129 };124+ above_data[A - 1] = if left_available { at(-1, -1) } else { base + 1 };
118 } else {125 } else {
119- above_data[A..A + bs].fill(127);126+ above_data[A..A + bs].fill(base - 1);
120- above_data[A - 1] = 127;127+ above_data[A - 1] = base - 1;
121 }128 }
122 }129 }
123 130
124 // NEED_ABOVERIGHT (vp9_reconintra.c:350-394).131 // NEED_ABOVERIGHT (vp9_reconintra.c:350-394).
125 if need_aboveright {132 if need_aboveright {
126 if up_available {133 if up_available {
127- let fill_bs = |d: &mut [u8; 80]| {134+ let fill_bs = |d: &mut [u16; 80]| {
128 let v = d[A + bs - 1];135 let v = d[A + bs - 1];
129 d[A + bs..A + 2 * bs].fill(v);136 d[A + bs..A + 2 * bs].fill(v);
130 };137 };
@@ -174,10 +181,10 @@ pub(crate) fn build_intra_predictors(
174 fill_bs(&mut above_data);181 fill_bs(&mut above_data);
175 }182 }
176 }183 }
177- above_data[A - 1] = if left_available { at(-1, -1) } else { 129 };184+ above_data[A - 1] = if left_available { at(-1, -1) } else { base + 1 };
178 } else {185 } else {
179- above_data[A..A + 2 * bs].fill(127);186+ above_data[A..A + 2 * bs].fill(base - 1);
180- above_data[A - 1] = 127;187+ above_data[A - 1] = base - 1;
181 }188 }
182 }189 }
183 190
@@ -201,7 +208,15 @@ pub(crate) fn build_intra_predictors(
201 }208 }
202 let dst = &mut data[y0 * stride + x0..];209 let dst = &mut data[y0 * stride + x0..];
203 dispatch(210 dispatch(
204- mode, bs, dst, stride, &above_data, &left_col, up_available, left_available,211+ mode,
212+ bs,
213+ dst,
214+ stride,
215+ &above_data,
216+ &left_col,
217+ up_available,
218+ left_available,
219+ bd,
205 );220 );
206 if crate::trace_enabled()221 if crate::trace_enabled()
207 && std::env::var("EC_VP9_PROBE_TU")222 && std::env::var("EC_VP9_PROBE_TU")
@@ -221,12 +236,13 @@ pub(crate) fn build_intra_predictors(
221 fn dispatch(236 fn dispatch(
222 mode: u8,237 mode: u8,
223 bs: usize,238 bs: usize,
224- dst: &mut [u8],239+ dst: &mut [Sample],
225 stride: usize,240 stride: usize,
226- above: &[u8],241+ above: &[Sample],
227- left: &[u8],242+ left: &[Sample],
228 up: bool,243 up: bool,
229 lft: bool,244 lft: bool,
245+ bd: u8,
230 ) {246 ) {
231 // `above` is the full above_data: [A-1] = above[-1], [A + i] = above[i].247 // `above` is the full above_data: [A-1] = above[-1], [A + i] = above[i].
232 let cor = above[A - 1];248 let cor = above[A - 1];
@@ -238,17 +254,32 @@ fn dispatch(
238 .chain(left[..bs].iter())254 .chain(left[..bs].iter())
239 .map(|&v| v as u32)255 .map(|&v| v as u32)
240 .sum();256 .sum();
241- fill_dc(dst, stride, bs, ((sum + bs as u32) / (2 * bs as u32)) as u8);257+ fill_dc(
258+ dst,
259+ stride,
260+ bs,
261+ ((sum + bs as u32) / (2 * bs as u32)) as Sample,
262+ );
242 }263 }
243 0 if lft => {264 0 if lft => {
244 let sum: u32 = left[..bs].iter().map(|&v| v as u32).sum();265 let sum: u32 = left[..bs].iter().map(|&v| v as u32).sum();
245- fill_dc(dst, stride, bs, ((sum + bs as u32 / 2) / bs as u32) as u8);266+ fill_dc(
267+ dst,
268+ stride,
269+ bs,
270+ ((sum + bs as u32 / 2) / bs as u32) as Sample,
271+ );
246 }272 }
247 0 if up => {273 0 if up => {
248 let sum: u32 = ab[..bs].iter().map(|&v| v as u32).sum();274 let sum: u32 = ab[..bs].iter().map(|&v| v as u32).sum();
249- fill_dc(dst, stride, bs, ((sum + bs as u32 / 2) / bs as u32) as u8);275+ fill_dc(
276+ dst,
277+ stride,
278+ bs,
279+ ((sum + bs as u32 / 2) / bs as u32) as Sample,
280+ );
250 }281 }
251- 0 => fill_dc(dst, stride, bs, 128),282+ 0 => fill_dc(dst, stride, bs, 128u16 << (bd - 8)),
252 1 => {283 1 => {
253 for r in 0..bs {284 for r in 0..bs {
254 dst[r * stride..r * stride + bs].copy_from_slice(&ab[..bs]);285 dst[r * stride..r * stride + bs].copy_from_slice(&ab[..bs]);
@@ -314,7 +345,7 @@ fn dispatch(
314 let mut x = 1;345 let mut x = 1;
315 let mut size = bs - 2;346 let mut size = bs - 2;
316 while x < bs {347 while x < bs {
317- let src: Vec<u8> = dst[..x + size].to_vec();348+ let src: Vec<Sample> = dst[..x + size].to_vec();
318 let off = x * stride;349 let off = x * stride;
319 dst[off..off + size].copy_from_slice(&src[x..x + size]);350 dst[off..off + size].copy_from_slice(&src[x..x + size]);
320 dst[off + size..off + bs].fill(above_right);351 dst[off + size..off + bs].fill(above_right);
@@ -324,7 +355,7 @@ fn dispatch(
324 }355 }
325 4 => {356 4 => {
326 // d135357 // d135
327- let mut border = [0u8; 64];358+ let mut border = [0u16; 64];
328 for i in 0..bs - 2 {359 for i in 0..bs - 2 {
329 border[i] = avg3(left[bs - 3 - i], left[bs - 2 - i], left[bs - 1 - i]);360 border[i] = avg3(left[bs - 3 - i], left[bs - 2 - i], left[bs - 1 - i]);
330 }361 }
@@ -411,9 +442,9 @@ fn dispatch(
411 let mut r = 2;442 let mut r = 2;
412 let mut size = bs - 2;443 let mut size = bs - 2;
413 while r < bs {444 while r < bs {
414- let src0: Vec<u8> = dst[(r >> 1)..(r >> 1) + size].to_vec();445+ let src0: Vec<Sample> = dst[(r >> 1)..(r >> 1) + size].to_vec();
415 let base1 = stride + (r >> 1);446 let base1 = stride + (r >> 1);
416- let src1: Vec<u8> = dst[base1..base1 + size].to_vec();447+ let src1: Vec<Sample> = dst[base1..base1 + size].to_vec();
417 let o0 = r * stride;448 let o0 = r * stride;
418 dst[o0..o0 + size].copy_from_slice(&src0);449 dst[o0..o0 + size].copy_from_slice(&src0);
419 dst[o0 + size..o0 + bs].fill(ab[bs - 1]);450 dst[o0 + size..o0 + bs].fill(ab[bs - 1]);
@@ -429,14 +460,14 @@ fn dispatch(
429 for r in 0..bs {460 for r in 0..bs {
430 for c in 0..bs {461 for c in 0..bs {
431 dst[r * stride + c] =462 dst[r * stride + c] =
432- (left[r] as i32 + ab[c] as i32 - cor as i32).clamp(0, 255) as u8;463+ crate::clip_pixel_bd(left[r] as i32 + ab[c] as i32 - cor as i32, bd);
433 }464 }
434 }465 }
435 }466 }
436 }467 }
437 }468 }
438 469
439-fn fill_dc(dst: &mut [u8], stride: usize, bs: usize, v: u8) {470+fn fill_dc(dst: &mut [Sample], stride: usize, bs: usize, v: Sample) {
440 for r in 0..bs {471 for r in 0..bs {
441 dst[r * stride..r * stride + bs].fill(v);472 dst[r * stride..r * stride + bs].fill(v);
442 }473 }
crates/ec-vp9/src/lib.rsmodified+28 -3
@@ -1,12 +1,18 @@
1-//! Native VP9 (profile 0, 8-bit 4:2:0) decoder.1+//! Native VP9 (profiles 0 and 2, 8- and 10-bit 4:2:0) decoder.
2 //!2 //!
3 //! The crate implements the VP9 bitstream specification directly3 //! The crate implements the VP9 bitstream specification directly
4 //! ([spec]); libvpx's output is used only as a test oracle4 //! ([spec]); libvpx's output is used only as a test oracle
5 //! (sample-exactness witnesses against ffmpeg's libvpx-based decoder),5 //! (sample-exactness witnesses against ffmpeg's libvpx-based decoder),
6 //! never as code linked at runtime. Every module documents the spec6 //! never as code linked at runtime. Every module documents the spec
7 //! section it implements. Inter frames decode through motion compensation,7 //! section it implements. Inter frames decode through motion compensation,
8-//! residual reconstruction and the loop filter; intra-only frames, other8+//! residual reconstruction and the loop filter; intra-only frames, profiles
9-//! profiles and other subsamplings are refused by name.9+//! 1/3 (4:4:4), 12-bit and other subsamplings are refused by name.
10+//!
11+//! Planes are stored as `u16` for every depth ([`Sample`]); kernels take the
12+//! frame's `bd` and clamp with `clip_pixel_bd`, so one decode walk serves
13+//! both depths. The only depth-dependent bitstream element is the CAT6
14+//! coefficient token (14 bits/`vp9_cat6_prob` at 8-bit, 16 bits/
15+//! `vp9_cat6_prob_high12 + 2` at 10- and 12-bit).
10 //!16 //!
11 //! [spec]: https://www.webmproject.org/docs/vp9/17 //! [spec]: https://www.webmproject.org/docs/vp9/
12 //!18 //!
@@ -32,6 +38,25 @@ pub mod transform;
32 38
33 pub use ec_core::{Error, Result};39 pub use ec_core::{Error, Result};
34 40
41+/// A reconstructed sample. Planes are stored as `u16` for EVERY bit depth
42+/// (8-bit values occupy the low byte), so profile-0 and profile-2 frames share
43+/// one representation and one decode walk; the kernels take the frame's
44+/// `bd` and clamp with [`clip_pixel_bd`].
45+pub type Sample = u16;
46+
47+/// `clip_pixel_highbd` (`vpx_dsp/vpx_dsp_common.h`): clamp to `[0, (1<<bd)-1]`.
48+/// For `bd == 8` this is libvpx's `clip_pixel` exactly.
49+#[inline]
50+pub(crate) fn clip_pixel_bd(v: i32, bd: u8) -> Sample {
51+ v.clamp(0, (1i32 << bd) - 1) as Sample
52+}
53+
54+/// `ROUND_POWER_OF_TWO(v, n)` (`vpx_dsp/txfm_common.h`, arithmetic shift).
55+#[inline]
56+pub(crate) fn round_pow2(v: i32, n: i32) -> i32 {
57+ (v + (1 << (n - 1))) >> n
58+}
59+
35 /// Whether `EC_VP9_TRACE` decision tracing is enabled, resolved once per60 /// Whether `EC_VP9_TRACE` decision tracing is enabled, resolved once per
36 /// process. An `var_os` per bool read would lock std's ENV lock on every61 /// process. An `var_os` per bool read would lock std's ENV lock on every
37 /// coefficient; the hot path is a single relaxed atomic load.62 /// coefficient; the hot path is a single relaxed atomic load.
crates/ec-vp9/src/loopfilter.rsmodified+131 -82
@@ -95,48 +95,60 @@ const LUMA_ABOVE_TXF: [u64; 4] = [u64::MAX, u64::MAX, 0x00ff00ff00ff00ff, 0x0000
95 const LUMA_LEFT_BORDER: u64 = 0x1111111111111111;95 const LUMA_LEFT_BORDER: u64 = 0x1111111111111111;
96 const LUMA_ABOVE_BORDER: u64 = 0x000000ff000000ff;96 const LUMA_ABOVE_BORDER: u64 = 0x000000ff000000ff;
97 97
98+use crate::Sample;
99+
100+/// `signed_char_clamp_high` (`vpx_dsp/loopfilter.c:23`): clamp to
101+/// `[-(128 << (bd-8)), (128 << (bd-8)) - 1]`. At `bd == 8` this is libvpx's
102+/// 8-bit `signed_char_clamp` (`[-128, 127]`).
98 #[inline]103 #[inline]
99-fn sc(x: i32) -> i32 {104+fn sc(x: i32, bd: u8) -> i32 {
100- x.clamp(-128, 127)105+ let shift = (bd - 8) as i32;
106+ x.clamp(-(128 << shift), (128 << shift) - 1)
101 }107 }
102 108
103-/// `filter4` kernel; `idx` = [op1, op0, oq0, oq1].109+/// `filter4` / `highbd_filter4` kernel; `idx` = [op1, op0, oq0, oq1].
104 /// `vpx_dsp filter4`: updates p1/p0/q0/q1 in place. `mask` gates the110 /// `vpx_dsp filter4`: updates p1/p0/q0/q1 in place. `mask` gates the
105-/// whole filter, `hev` the outer taps (vp9_loopfilter.c:81).111+/// whole filter, `hev` the outer taps (vp9_loopfilter.c:81). The `^ 0x80`
106-fn filter4(s: &mut [u8], idx: [usize; 4], thresh: i32, mask: bool) {112+/// of the 8-bit kernel generalizes to subtracting `0x80 << (bd - 8)`.
113+fn filter4(s: &mut [Sample], idx: [usize; 4], thresh: i32, mask: bool, bd: u8) {
107 if !mask {114 if !mask {
108 return;115 return;
109 }116 }
117+ let shift = (bd - 8) as i32;
118+ let bias = 0x80 << shift;
110 let (op1, op0, oq0, oq1) = (idx[0], idx[1], idx[2], idx[3]);119 let (op1, op0, oq0, oq1) = (idx[0], idx[1], idx[2], idx[3]);
111 let (p1, p0, q0, q1) = (s[op1], s[op0], s[oq0], s[oq1]);120 let (p1, p0, q0, q1) = (s[op1], s[op0], s[oq0], s[oq1]);
112- let hev = (p1 as i32 - p0 as i32).abs() > thresh || (q1 as i32 - q0 as i32).abs() > thresh;121+ let hev_thresh = thresh << shift;
122+ let hev =
123+ (p1 as i32 - p0 as i32).abs() > hev_thresh || (q1 as i32 - q0 as i32).abs() > hev_thresh;
113 let (ps1, ps0, qs0, qs1) = (124 let (ps1, ps0, qs0, qs1) = (
114- (p1 ^ 0x80) as i8 as i32,125+ p1 as i32 - bias,
115- (p0 ^ 0x80) as i8 as i32,126+ p0 as i32 - bias,
116- (q0 ^ 0x80) as i8 as i32,127+ q0 as i32 - bias,
117- (q1 ^ 0x80) as i8 as i32,128+ q1 as i32 - bias,
118 );129 );
119- let mut filter = sc(ps1 - qs1);130+ let mut filter = sc(ps1 - qs1, bd);
120 if hev {131 if hev {
121 // add outer taps if we have high edge variance (& hev mask)132 // add outer taps if we have high edge variance (& hev mask)
122 } else {133 } else {
123 filter = 0;134 filter = 0;
124 }135 }
125 // inner taps136 // inner taps
126- filter = sc(filter + 3 * (qs0 - ps0));137+ filter = sc(filter + 3 * (qs0 - ps0), bd);
127 // round one side +4 and the other +3138 // round one side +4 and the other +3
128- let filter1 = sc(filter + 4) >> 3;139+ let filter1 = sc(filter + 4, bd) >> 3;
129- let filter2 = sc(filter + 3) >> 3;140+ let filter2 = sc(filter + 3, bd) >> 3;
130- s[oq0] = (sc(qs0 - filter1) ^ 0x80) as u8;141+ s[oq0] = (sc(qs0 - filter1, bd) + bias) as Sample;
131- s[op0] = (sc(ps0 + filter2) ^ 0x80) as u8;142+ s[op0] = (sc(ps0 + filter2, bd) + bias) as Sample;
132 // outer tap adjustments (& ~hev)143 // outer tap adjustments (& ~hev)
133 let f = if hev { 0 } else { (filter1 + 1) >> 1 };144 let f = if hev { 0 } else { (filter1 + 1) >> 1 };
134- s[oq1] = (sc(qs1 - f) ^ 0x80) as u8;145+ s[oq1] = (sc(qs1 - f, bd) + bias) as Sample;
135- s[op1] = (sc(ps1 + f) ^ 0x80) as u8;146+ s[op1] = (sc(ps1 + f, bd) + bias) as Sample;
136 }147 }
137 148
149+#[allow(clippy::too_many_arguments)]
138 fn lpf_edge(150 fn lpf_edge(
139- data: &mut [u8],151+ data: &mut [Sample],
140 off: usize,152 off: usize,
141 stride: usize,153 stride: usize,
142 dir: u8,154 dir: u8,
@@ -145,7 +157,14 @@ fn lpf_edge(
145 limit: i32,157 limit: i32,
146 thresh: i32,158 thresh: i32,
147 nlines: isize,159 nlines: isize,
160+ bd: u8,
148 ) {161 ) {
162+ // `highbd_filter_mask` / `highbd_flat_mask*`: the coded 8-bit thresholds
163+ // scale by `1 << (bd - 8)`.
164+ let shift = (bd - 8) as i32;
165+ let limit = limit << shift;
166+ let blimit = blimit << shift;
167+ let flat_t = 1 << shift;
149 // `dir` 0 = horizontal edges (rows step by stride), 1 = vertical168 // `dir` 0 = horizontal edges (rows step by stride), 1 = vertical
150 // (columns step by 1). `taps` in {4, 8, 16}.169 // (columns step by 1). `taps` in {4, 8, 16}.
151 let step: isize = if dir == 0 { stride as isize } else { 1 };170 let step: isize = if dir == 0 { stride as isize } else { 1 };
@@ -179,23 +198,23 @@ fn lpf_edge(
179 (edge + step) as usize,198 (edge + step) as usize,
180 ];199 ];
181 if taps == 4 {200 if taps == 4 {
182- filter4(data, idx4, thresh, mask);201+ filter4(data, idx4, thresh, mask, bd);
183 continue;202 continue;
184 }203 }
185 if !mask {204 if !mask {
186 continue;205 continue;
187 }206 }
188 // flat_mask4(1, p3..q3)207 // flat_mask4(1, p3..q3)
189- let flat = (rd!(-2) - rd!(-1)).abs() <= 1208+ let flat = (rd!(-2) - rd!(-1)).abs() <= flat_t
190- && (rd!(1) - rd!(0)).abs() <= 1209+ && (rd!(1) - rd!(0)).abs() <= flat_t
191- && (rd!(-3) - rd!(-1)).abs() <= 1210+ && (rd!(-3) - rd!(-1)).abs() <= flat_t
192- && (rd!(2) - rd!(0)).abs() <= 1211+ && (rd!(2) - rd!(0)).abs() <= flat_t
193- && (rd!(-4) - rd!(-1)).abs() <= 1212+ && (rd!(-4) - rd!(-1)).abs() <= flat_t
194- && (rd!(3) - rd!(0)).abs() <= 1;213+ && (rd!(3) - rd!(0)).abs() <= flat_t;
195 if taps == 8 || !flat {214 if taps == 8 || !flat {
196 if !flat {215 if !flat {
197 // plain filter4 with the real mask and hev threshold216 // plain filter4 with the real mask and hev threshold
198- filter4(data, idx4, thresh, mask);217+ filter4(data, idx4, thresh, mask, bd);
199 continue;218 continue;
200 }219 }
201 // 7-tap [1,1,1,2,1,1,1] outputs (filter8).220 // 7-tap [1,1,1,2,1,1,1] outputs (filter8).
@@ -209,25 +228,40 @@ fn lpf_edge(
209 rd!(2),228 rd!(2),
210 rd!(3),229 rd!(3),
211 );230 );
212- put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as u8);231+ put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as Sample);
213- put!(-2, ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as u8);232+ put!(
214- put!(-1, ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as u8);233+ -2,
215- put!(0, ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as u8);234+ ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as Sample
216- put!(1, ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as u8);235+ );
217- put!(2, ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as u8);236+ put!(
237+ -1,
238+ ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as Sample
239+ );
240+ put!(
241+ 0,
242+ ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as Sample
243+ );
244+ put!(
245+ 1,
246+ ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as Sample
247+ );
248+ put!(
249+ 2,
250+ ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as Sample
251+ );
218 continue;252 continue;
219 }253 }
220 // flat_mask5(1, s[-8], s[-7], s[-6], s[-5], p0, q0, s[4], s[5], s[6], s[7]):254 // flat_mask5(1, s[-8], s[-7], s[-6], s[-5], p0, q0, s[4], s[5], s[6], s[7]):
221 // |p7..p4 - p0| and |q4..q7 - q0| (the C names are shifted; q4..q6255 // |p7..p4 - p0| and |q4..q7 - q0| (the C names are shifted; q4..q6
222 // are the q1..q3 args of the inner flat_mask4 and compare to q0).256 // are the q1..q3 args of the inner flat_mask4 and compare to q0).
223- let flat2 = (rd!(-8) - rd!(-1)).abs() <= 1257+ let flat2 = (rd!(-8) - rd!(-1)).abs() <= flat_t
224- && (rd!(-7) - rd!(-1)).abs() <= 1258+ && (rd!(-7) - rd!(-1)).abs() <= flat_t
225- && (rd!(-6) - rd!(-1)).abs() <= 1259+ && (rd!(-6) - rd!(-1)).abs() <= flat_t
226- && (rd!(-5) - rd!(-1)).abs() <= 1260+ && (rd!(-5) - rd!(-1)).abs() <= flat_t
227- && (rd!(4) - rd!(0)).abs() <= 1261+ && (rd!(4) - rd!(0)).abs() <= flat_t
228- && (rd!(5) - rd!(0)).abs() <= 1262+ && (rd!(5) - rd!(0)).abs() <= flat_t
229- && (rd!(6) - rd!(0)).abs() <= 1263+ && (rd!(6) - rd!(0)).abs() <= flat_t
230- && (rd!(7) - rd!(0)).abs() <= 1;264+ && (rd!(7) - rd!(0)).abs() <= flat_t;
231 if !flat2 {265 if !flat2 {
232 let (p3, p2, p1, p0, q0, q1, q2, q3) = (266 let (p3, p2, p1, p0, q0, q1, q2, q3) = (
233 rd!(-4),267 rd!(-4),
@@ -239,12 +273,27 @@ fn lpf_edge(
239 rd!(2),273 rd!(2),
240 rd!(3),274 rd!(3),
241 );275 );
242- put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as u8);276+ put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as Sample);
243- put!(-2, ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as u8);277+ put!(
244- put!(-1, ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as u8);278+ -2,
245- put!(0, ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as u8);279+ ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as Sample
246- put!(1, ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as u8);280+ );
247- put!(2, ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as u8);281+ put!(
282+ -1,
283+ ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as Sample
284+ );
285+ put!(
286+ 0,
287+ ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as Sample
288+ );
289+ put!(
290+ 1,
291+ ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as Sample
292+ );
293+ put!(
294+ 2,
295+ ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as Sample
296+ );
248 continue;297 continue;
249 }298 }
250 // 15-tap filter [1 x 7, 2, 1 x 7] (filter16, weights verbatim).299 // 15-tap filter [1 x 7, 2, 1 x 7] (filter16, weights verbatim).
@@ -254,65 +303,67 @@ fn lpf_edge(
254 let (q4, q5, q6, q7) = (rd!(4), rd!(5), rd!(6), rd!(7));303 let (q4, q5, q6, q7) = (rd!(4), rd!(5), rd!(6), rd!(7));
255 put!(304 put!(
256 -7,305 -7,
257- ((p7 * 7 + p6 * 2 + p5 + p4 + p3 + p2 + p1 + p0 + q0 + 8) >> 4) as u8306+ ((p7 * 7 + p6 * 2 + p5 + p4 + p3 + p2 + p1 + p0 + q0 + 8) >> 4) as Sample
258 );307 );
259 put!(308 put!(
260 -6,309 -6,
261- ((p7 * 6 + p6 + p5 * 2 + p4 + p3 + p2 + p1 + p0 + q0 + q1 + 8) >> 4) as u8310+ ((p7 * 6 + p6 + p5 * 2 + p4 + p3 + p2 + p1 + p0 + q0 + q1 + 8) >> 4) as Sample
262 );311 );
263 put!(312 put!(
264 -5,313 -5,
265- ((p7 * 5 + p6 + p5 + p4 * 2 + p3 + p2 + p1 + p0 + q0 + q1 + q2 + 8) >> 4) as u8314+ ((p7 * 5 + p6 + p5 + p4 * 2 + p3 + p2 + p1 + p0 + q0 + q1 + q2 + 8) >> 4) as Sample
266 );315 );
267 put!(316 put!(
268 -4,317 -4,
269- ((p7 * 4 + p6 + p5 + p4 + p3 * 2 + p2 + p1 + p0 + q0 + q1 + q2 + q3 + 8) >> 4) as u8318+ ((p7 * 4 + p6 + p5 + p4 + p3 * 2 + p2 + p1 + p0 + q0 + q1 + q2 + q3 + 8) >> 4)
319+ as Sample
270 );320 );
271 put!(321 put!(
272 -3,322 -3,
273 ((p7 * 3 + p6 + p5 + p4 + p3 + p2 * 2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 + 8) >> 4)323 ((p7 * 3 + p6 + p5 + p4 + p3 + p2 * 2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 + 8) >> 4)
274- as u8324+ as Sample
275 );325 );
276 put!(326 put!(
277 -2,327 -2,
278 ((p7 * 2 + p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 + q0 + q1 + q2 + q3 + q4 + q5 + 8) >> 4)328 ((p7 * 2 + p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 + q0 + q1 + q2 + q3 + q4 + q5 + 8) >> 4)
279- as u8329+ as Sample
280 );330 );
281 put!(331 put!(
282 -1,332 -1,
283 ((p7 + p6 + p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + q3 + q4 + q5 + q6 + 8)333 ((p7 + p6 + p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + q3 + q4 + q5 + q6 + 8)
284- >> 4) as u8334+ >> 4) as Sample
285 );335 );
286 put!(336 put!(
287 0,337 0,
288 ((p6 + p5 + p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + q4 + q5 + q6 + q7 + 8)338 ((p6 + p5 + p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + q4 + q5 + q6 + q7 + 8)
289- >> 4) as u8339+ >> 4) as Sample
290 );340 );
291 put!(341 put!(
292 1,342 1,
293 ((p5 + p4 + p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 + q3 + q4 + q5 + q6 + q7 * 2 + 8) >> 4)343 ((p5 + p4 + p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 + q3 + q4 + q5 + q6 + q7 * 2 + 8) >> 4)
294- as u8344+ as Sample
295 );345 );
296 put!(346 put!(
297 2,347 2,
298 ((p4 + p3 + p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 + q4 + q5 + q6 + q7 * 3 + 8) >> 4)348 ((p4 + p3 + p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 + q4 + q5 + q6 + q7 * 3 + 8) >> 4)
299- as u8349+ as Sample
300 );350 );
301 put!(351 put!(
302 3,352 3,
303- ((p3 + p2 + p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 + q5 + q6 + q7 * 4 + 8) >> 4) as u8353+ ((p3 + p2 + p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 + q5 + q6 + q7 * 4 + 8) >> 4)
354+ as Sample
304 );355 );
305 put!(356 put!(
306 4,357 4,
307- ((p2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 + q6 + q7 * 5 + 8) >> 4) as u8358+ ((p2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 + q6 + q7 * 5 + 8) >> 4) as Sample
308 );359 );
309 put!(360 put!(
310 5,361 5,
311- ((p1 + p0 + q0 + q1 + q2 + q3 + q4 + q5 * 2 + q6 + q7 * 6 + 8) >> 4) as u8362+ ((p1 + p0 + q0 + q1 + q2 + q3 + q4 + q5 * 2 + q6 + q7 * 6 + 8) >> 4) as Sample
312 );363 );
313 put!(364 put!(
314 6,365 6,
315- ((p0 + q0 + q1 + q2 + q3 + q4 + q5 + q6 * 2 + q7 * 7 + 8) >> 4) as u8366+ ((p0 + q0 + q1 + q2 + q3 + q4 + q5 + q6 * 2 + q7 * 7 + 8) >> 4) as Sample
316 );367 );
317 }368 }
318 }369 }
@@ -567,15 +618,16 @@ impl LfGrids {
567 /// writes whole 8-column groups into the padded plane).618 /// writes whole 8-column groups into the padded plane).
568 pub(crate) fn filter_frame(619 pub(crate) fn filter_frame(
569 &self,620 &self,
570- y: &mut [u8],621+ y: &mut [Sample],
571 stride: usize,622 stride: usize,
572- u: &mut [u8],623+ u: &mut [Sample],
573- v: &mut [u8],624+ v: &mut [Sample],
574 uv_stride: usize,625 uv_stride: usize,
575 y_w: usize,626 y_w: usize,
576 y_h: usize,627 y_h: usize,
577 uv_h: usize,628 uv_h: usize,
578 sharpness: u8,629 sharpness: u8,
630+ bd: u8,
579 ) {631 ) {
580 let lftrace = lftrace_on();632 let lftrace = lftrace_on();
581 // Luma masks, ported from vp9_setup_mask/build_masks and633 // Luma masks, ported from vp9_setup_mask/build_masks and
@@ -618,7 +670,7 @@ impl LfGrids {
618 if t == 16 && (xx < 8 || xx + 8 > y_w) {670 if t == 16 && (xx < 8 || xx + 8 > y_w) {
619 t = 8;671 t = 8;
620 }672 }
621- lpf_edge(y, yy * stride + xx, stride, 1, t, bl, li, th, 8);673+ lpf_edge(y, yy * stride + xx, stride, 1, t, bl, li, th, 8, bd);
622 if lftrace {674 if lftrace {
623 let kind = match t {675 let kind = match t {
624 16 => "V16",676 16 => "V16",
@@ -629,7 +681,7 @@ impl LfGrids {
629 }681 }
630 }682 }
631 if int4 & bit != 0 && xx + 8 <= y_w && yy + 8 <= y_h {683 if int4 & bit != 0 && xx + 8 <= y_w && yy + 8 <= y_h {
632- lpf_edge(y, yy * stride + xx + 4, stride, 1, 4, bl, li, th, 8);684+ lpf_edge(y, yy * stride + xx + 4, stride, 1, 4, bl, li, th, 8, bd);
633 if lftrace {685 if lftrace {
634 eprintln!("V4I {} {}", xx + 4, yy);686 eprintln!("V4I {} {}", xx + 4, yy);
635 }687 }
@@ -667,7 +719,7 @@ impl LfGrids {
667 if t == 16 && (yy < 8 || yy + 8 > y_h) {719 if t == 16 && (yy < 8 || yy + 8 > y_h) {
668 t = 8;720 t = 8;
669 }721 }
670- lpf_edge(y, yy * stride + xx, stride, 0, t, bl, li, th, 8);722+ lpf_edge(y, yy * stride + xx, stride, 0, t, bl, li, th, 8, bd);
671 if lftrace {723 if lftrace {
672 let kind = match t {724 let kind = match t {
673 16 => "H16",725 16 => "H16",
@@ -685,7 +737,7 @@ impl LfGrids {
685 // exists only in the 4:2:0-chroma path (ss11,737 // exists only in the 4:2:0-chroma path (ss11,
686 // vp9_loopfilter.c:1382) and in non420 under `ss_y`.738 // vp9_loopfilter.c:1382) and in non420 under `ss_y`.
687 if int4 & bit != 0 && yy + 8 <= y_h && xx + 8 <= y_w {739 if int4 & bit != 0 && yy + 8 <= y_h && xx + 8 <= y_w {
688- lpf_edge(y, (yy + 4) * stride + xx, stride, 0, 4, bl, li, th, 8);740+ lpf_edge(y, (yy + 4) * stride + xx, stride, 0, 4, bl, li, th, 8, bd);
689 if lftrace {741 if lftrace {
690 eprintln!("H4I {} {}", xx, yy + 4);742 eprintln!("H4I {} {}", xx, yy + 4);
691 }743 }
@@ -830,11 +882,7 @@ impl LfGrids {
830 0882 0
831 };883 };
832 if taps != 0 {884 if taps != 0 {
833- let t = if taps == 16 && x8 < 8 {885+ let t = if taps == 16 && x8 < 8 { 8 } else { taps };
834- 8
835- } else {
836- taps
837- };
838 lpf_edge(886 lpf_edge(
839 data,887 data,
840 y8 * uv_stride + x8,888 y8 * uv_stride + x8,
@@ -845,6 +893,7 @@ impl LfGrids {
845 li,893 li,
846 th,894 th,
847 8,895 8,
896+ bd,
848 );897 );
849 }898 }
850 }899 }
@@ -859,6 +908,7 @@ impl LfGrids {
859 li,908 li,
860 th,909 th,
861 8,910 8,
911+ bd,
862 );912 );
863 }913 }
864 }914 }
@@ -906,12 +956,11 @@ impl LfGrids {
906 li,956 li,
907 th,957 th,
908 8,958 8,
959+ bd,
909 );960 );
910 }961 }
911 }962 }
912- if int4 & bit != 0963+ if int4 & bit != 0 && sbr + 2 * rg != self.mi_rows - 1 && y8 + 8 <= uv_h
913- && sbr + 2 * rg != self.mi_rows - 1
914- && y8 + 8 <= uv_h
915 {964 {
916 lpf_edge(965 lpf_edge(
917 data,966 data,
@@ -923,6 +972,7 @@ impl LfGrids {
923 li,972 li,
924 th,973 th,
925 8,974 8,
975+ bd,
926 );976 );
927 }977 }
928 }978 }
@@ -952,10 +1002,10 @@ mod tests {
952 }1002 }
953 }1003 }
954 1004
955- fn run(g: &LfGrids, y: &mut [u8]) {1005+ fn run(g: &LfGrids, y: &mut [Sample]) {
956- let mut u = vec![128u8; 32 * 32];1006+ let mut u = vec![128u16; 32 * 32];
957- let mut v = vec![128u8; 32 * 32];1007+ let mut v = vec![128u16; 32 * 32];
958- g.filter_frame(y, 64, &mut u, &mut v, 32, 64, 64, 32, 0);1008+ g.filter_frame(y, 64, &mut u, &mut v, 32, 64, 64, 32, 0, 8);
959 }1009 }
960 1010
961 /// The luma internal-4x4 horizontal edge fires on the frame's LAST MI row.1011 /// The luma internal-4x4 horizontal edge fires on the frame's LAST MI row.
@@ -973,7 +1023,7 @@ mod tests {
973 let stride = 64;1023 let stride = 64;
974 // A gentle step (4) between rows 59 and 60: sharp steps fail the1024 // A gentle step (4) between rows 59 and 60: sharp steps fail the
975 // filter_mask gradient test, and a flat pattern cannot move.1025 // filter_mask gradient test, and a flat pattern cannot move.
976- let mut y = vec![100u8; 64 * 64];1026+ let mut y = vec![100u16; 64 * 64];
977 for row in 60..64 {1027 for row in 60..64 {
978 y[row * stride..row * stride + 64].fill(104);1028 y[row * stride..row * stride + 64].fill(104);
979 }1029 }
@@ -985,4 +1035,3 @@ mod tests {
985 );1035 );
986 }1036 }
987 }1037 }
988-
crates/ec-vp9/src/mc.rsmodified+53 -35
@@ -110,20 +110,12 @@ pub(crate) const FILTERS: [[[i16; TAPS]; SUBPEL_SHIFTS as usize]; 4] = [
110 ],110 ],
111 ];111 ];
112 112
113-/// `clip_pixel` (`vpx_dsp/vpx_dsp_common.h`).113+use crate::{Sample, clip_pixel_bd, round_pow2};
114-fn clip_pixel(v: i32) -> u8 {
115- v.clamp(0, 255) as u8
116-}
117-
118-/// `ROUND_POWER_OF_TWO(v, n)`.
119-fn round_pow2(v: i32, n: i32) -> i32 {
120- (v + (1 << (n - 1))) >> n
121-}
122 114
123 /// Read `buf[i]` for a possibly negative `i`. Every caller keeps `i` inside115 /// Read `buf[i]` for a possibly negative `i`. Every caller keeps `i` inside
124 /// the buffer (the border copy guarantees the tap margins exist).116 /// the buffer (the border copy guarantees the tap margins exist).
125 #[inline]117 #[inline]
126-fn at(buf: &[u8], i: isize) -> u8 {118+fn at(buf: &[Sample], i: isize) -> Sample {
127 buf[i as usize]119 buf[i as usize]
128 }120 }
129 121
@@ -162,9 +154,9 @@ pub(crate) fn clamp_mv_to_umv_border_sb(
162 /// `[0, w)` x `[0, h)`.154 /// `[0, w)` x `[0, h)`.
163 #[allow(clippy::too_many_arguments)]155 #[allow(clippy::too_many_arguments)]
164 fn build_mc_border(156 fn build_mc_border(
165- src: &[u8],157+ src: &[Sample],
166 src_stride: usize,158 src_stride: usize,
167- dst: &mut [u8],159+ dst: &mut [Sample],
168 dst_stride: usize,160 dst_stride: usize,
169 x: i32,161 x: i32,
170 mut y: i32,162 mut y: i32,
@@ -225,16 +217,17 @@ fn build_mc_border(
225 /// `origin + y*stride + (x_q4 >> SUBPEL_BITS) - (SUBPEL_TAPS / 2 - 1) + k`.217 /// `origin + y*stride + (x_q4 >> SUBPEL_BITS) - (SUBPEL_TAPS / 2 - 1) + k`.
226 #[allow(clippy::too_many_arguments)]218 #[allow(clippy::too_many_arguments)]
227 fn convolve_horiz(219 fn convolve_horiz(
228- buf: &[u8],220+ buf: &[Sample],
229 stride: usize,221 stride: usize,
230 origin: isize,222 origin: isize,
231- dst: &mut [u8],223+ dst: &mut [Sample],
232 dst_stride: usize,224 dst_stride: usize,
233 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],225 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
234 x0_q4: i32,226 x0_q4: i32,
235 w: usize,227 w: usize,
236 rows: usize,228 rows: usize,
237 avg: bool,229 avg: bool,
230+ bd: u8,
238 ) {231 ) {
239 for y in 0..rows {232 for y in 0..rows {
240 let mut x_q4 = x0_q4;233 let mut x_q4 = x0_q4;
@@ -246,12 +239,12 @@ fn convolve_horiz(
246 for k in 0..TAPS {239 for k in 0..TAPS {
247 sum += at(buf, base + k as isize) as i32 * filt[k] as i32;240 sum += at(buf, base + k as isize) as i32 * filt[k] as i32;
248 }241 }
249- let v = clip_pixel(round_pow2(sum, FILTER_BITS)) as i32;242+ let v = clip_pixel_bd(round_pow2(sum, FILTER_BITS), bd) as i32;
250 let d = y * dst_stride + x;243 let d = y * dst_stride + x;
251 dst[d] = if avg {244 dst[d] = if avg {
252- round_pow2(dst[d] as i32 + v, 1) as u8245+ round_pow2(dst[d] as i32 + v, 1) as Sample
253 } else {246 } else {
254- v as u8247+ v as Sample
255 };248 };
256 x_q4 += SUBPEL_SHIFTS;249 x_q4 += SUBPEL_SHIFTS;
257 }250 }
@@ -260,16 +253,17 @@ fn convolve_horiz(
260 253
261 /// `convolve_vert` / `convolve_avg_vert` (`vpx_dsp/vpx_convolve.c:80`).254 /// `convolve_vert` / `convolve_avg_vert` (`vpx_dsp/vpx_convolve.c:80`).
262 fn convolve_vert(255 fn convolve_vert(
263- buf: &[u8],256+ buf: &[Sample],
264 stride: usize,257 stride: usize,
265 origin: isize,258 origin: isize,
266- dst: &mut [u8],259+ dst: &mut [Sample],
267 dst_stride: usize,260 dst_stride: usize,
268 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],261 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
269 y0_q4: i32,262 y0_q4: i32,
270 w: usize,263 w: usize,
271 h: usize,264 h: usize,
272 avg: bool,265 avg: bool,
266+ bd: u8,
273 ) {267 ) {
274 for x in 0..w {268 for x in 0..w {
275 let mut y_q4 = y0_q4;269 let mut y_q4 = y0_q4;
@@ -282,12 +276,12 @@ fn convolve_vert(
282 for k in 0..TAPS {276 for k in 0..TAPS {
283 sum += at(buf, base + k as isize * stride as isize) as i32 * filt[k] as i32;277 sum += at(buf, base + k as isize * stride as isize) as i32 * filt[k] as i32;
284 }278 }
285- let v = clip_pixel(round_pow2(sum, FILTER_BITS)) as i32;279+ let v = clip_pixel_bd(round_pow2(sum, FILTER_BITS), bd) as i32;
286 let d = y * dst_stride + x;280 let d = y * dst_stride + x;
287 dst[d] = if avg {281 dst[d] = if avg {
288- round_pow2(dst[d] as i32 + v, 1) as u8282+ round_pow2(dst[d] as i32 + v, 1) as Sample
289 } else {283 } else {
290- v as u8284+ v as Sample
291 };285 };
292 y_q4 += SUBPEL_SHIFTS;286 y_q4 += SUBPEL_SHIFTS;
293 }287 }
@@ -305,10 +299,10 @@ fn convolve_vert(
305 /// the averaging variant).299 /// the averaging variant).
306 #[allow(clippy::too_many_arguments)]300 #[allow(clippy::too_many_arguments)]
307 fn inter_predictor(301 fn inter_predictor(
308- buf: &[u8],302+ buf: &[Sample],
309 stride: usize,303 stride: usize,
310 origin: isize,304 origin: isize,
311- dst: &mut [u8],305+ dst: &mut [Sample],
312 dst_stride: usize,306 dst_stride: usize,
313 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],307 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
314 subpel_x: i32,308 subpel_x: i32,
@@ -316,7 +310,8 @@ fn inter_predictor(
316 w: usize,310 w: usize,
317 h: usize,311 h: usize,
318 avg: bool,312 avg: bool,
319- temp: &mut [u8],313+ temp: &mut [Sample],
314+ bd: u8,
320 ) {315 ) {
321 if subpel_x == 0 && subpel_y == 0 {316 if subpel_x == 0 && subpel_y == 0 {
322 for y in 0..h {317 for y in 0..h {
@@ -324,20 +319,24 @@ fn inter_predictor(
324 let s = at(buf, origin + (y * stride + x) as isize) as i32;319 let s = at(buf, origin + (y * stride + x) as isize) as i32;
325 let d = y * dst_stride + x;320 let d = y * dst_stride + x;
326 dst[d] = if avg {321 dst[d] = if avg {
327- round_pow2(dst[d] as i32 + s, 1) as u8322+ round_pow2(dst[d] as i32 + s, 1) as Sample
328 } else {323 } else {
329- s as u8324+ s as Sample
330 };325 };
331 }326 }
332 }327 }
333 return;328 return;
334 }329 }
335 if subpel_y == 0 {330 if subpel_y == 0 {
336- convolve_horiz(buf, stride, origin, dst, dst_stride, f, subpel_x, w, h, avg);331+ convolve_horiz(
332+ buf, stride, origin, dst, dst_stride, f, subpel_x, w, h, avg, bd,
333+ );
337 return;334 return;
338 }335 }
339 if subpel_x == 0 {336 if subpel_x == 0 {
340- convolve_vert(buf, stride, origin, dst, dst_stride, f, subpel_y, w, h, avg);337+ convolve_vert(
338+ buf, stride, origin, dst, dst_stride, f, subpel_y, w, h, avg, bd,
339+ );
341 return;340 return;
342 }341 }
343 // vpx_convolve8_c: horizontal pass into a stride-64 intermediate with342 // vpx_convolve8_c: horizontal pass into a stride-64 intermediate with
@@ -359,6 +358,7 @@ fn inter_predictor(
359 w,358 w,
360 intermediate_height,359 intermediate_height,
361 false,360 false,
361+ bd,
362 );362 );
363 if avg {363 if avg {
364 // vpx_convolve8_avg_c: full 2D into a second scratch, then average364 // vpx_convolve8_avg_c: full 2D into a second scratch, then average
@@ -366,11 +366,23 @@ fn inter_predictor(
366 // `temp[..64 * 135]` is the horizontal intermediate; the region after366 // `temp[..64 * 135]` is the horizontal intermediate; the region after
367 // it is the 2D result.367 // it is the 2D result.
368 let (horiz, mid2) = temp.split_at_mut(64 * 135);368 let (horiz, mid2) = temp.split_at_mut(64 * 135);
369- convolve_vert(horiz, 64, temp_origin, mid2, w, f, subpel_y, w, h, false);369+ convolve_vert(
370+ horiz,
371+ 64,
372+ temp_origin,
373+ mid2,
374+ w,
375+ f,
376+ subpel_y,
377+ w,
378+ h,
379+ false,
380+ bd,
381+ );
370 for y in 0..h {382 for y in 0..h {
371 for x in 0..w {383 for x in 0..w {
372 let d = y * dst_stride + x;384 let d = y * dst_stride + x;
373- dst[d] = round_pow2(dst[d] as i32 + mid2[y * w + x] as i32, 1) as u8;385+ dst[d] = round_pow2(dst[d] as i32 + mid2[y * w + x] as i32, 1) as Sample;
374 }386 }
375 }387 }
376 return;388 return;
@@ -386,13 +398,14 @@ fn inter_predictor(
386 w,398 w,
387 h,399 h,
388 false,400 false,
401+ bd,
389 );402 );
390 }403 }
391 404
392 /// One reference plane of a stored frame.405 /// One reference plane of a stored frame.
393 pub(crate) struct RefPlane<'a> {406 pub(crate) struct RefPlane<'a> {
394 /// Plane base — the frame's first visible sample.407 /// Plane base — the frame's first visible sample.
395- pub data: &'a [u8],408+ pub data: &'a [Sample],
396 /// Row pitch.409 /// Row pitch.
397 pub stride: usize,410 pub stride: usize,
398 /// `y_crop_width` / `uv_crop_width`: the coded extent, which is what411 /// `y_crop_width` / `uv_crop_width`: the coded extent, which is what
@@ -400,6 +413,8 @@ pub(crate) struct RefPlane<'a> {
400 pub width: usize,413 pub width: usize,
401 /// `y_crop_height` / `uv_crop_height`.414 /// `y_crop_height` / `uv_crop_height`.
402 pub height: usize,415 pub height: usize,
416+ /// Bits per sample of the reference frame.
417+ pub bd: u8,
403 }418 }
404 419
405 /// `dec_build_inter_predictors` (`vp9/decoder/vp9_decodeframe.c:593`),420 /// `dec_build_inter_predictors` (`vp9/decoder/vp9_decodeframe.c:593`),
@@ -407,7 +422,7 @@ pub(crate) struct RefPlane<'a> {
407 /// `(x, y)` inside the block at MI `(mi_row, mi_col)`.422 /// `(x, y)` inside the block at MI `(mi_row, mi_col)`.
408 #[allow(clippy::too_many_arguments)]423 #[allow(clippy::too_many_arguments)]
409 pub(crate) fn build_inter_predictors(424 pub(crate) fn build_inter_predictors(
410- dst: &mut [u8],425+ dst: &mut [Sample],
411 dst_stride: usize,426 dst_stride: usize,
412 refp: &RefPlane<'_>,427 refp: &RefPlane<'_>,
413 mi_col: usize,428 mi_col: usize,
@@ -425,9 +440,10 @@ pub(crate) fn build_inter_predictors(
425 ss_y: usize,440 ss_y: usize,
426 kernel: usize,441 kernel: usize,
427 avg: bool,442 avg: bool,
428- scratch: &mut Vec<u8>,443+ scratch: &mut Vec<Sample>,
429- temp: &mut Vec<u8>,444+ temp: &mut Vec<Sample>,
430 ) {445 ) {
446+ let bd = refp.bd;
431 let mv_q4 = clamp_mv_to_umv_border_sb(447 let mv_q4 = clamp_mv_to_umv_border_sb(
432 mv, w as i32, h as i32, mb_left, mb_right, mb_top, mb_bottom, ss_x, ss_y,448 mv, w as i32, h as i32, mb_left, mb_right, mb_top, mb_bottom, ss_x, ss_y,
433 );449 );
@@ -511,6 +527,7 @@ pub(crate) fn build_inter_predictors(
511 h,527 h,
512 avg,528 avg,
513 temp,529 temp,
530+ bd,
514 );531 );
515 return;532 return;
516 }533 }
@@ -532,6 +549,7 @@ pub(crate) fn build_inter_predictors(
532 h,549 h,
533 avg,550 avg,
534 temp,551 temp,
552+ bd,
535 );553 );
536 }554 }
537 555
crates/ec-vp9/src/tokens.rsmodified+19 -2
@@ -4,6 +4,14 @@
4 use crate::bool::BoolDecoder;4 use crate::bool::BoolDecoder;
5 use crate::tables::*;5 use crate::tables::*;
6 6
7+/// `vp9_cat6_prob_high12 + 2` (`vp9/common/vp9_entropy.c`): the CAT6 token's
8+/// 16 extra bits at bit depth 10 (and the middle 16 of the 12-bit table).
9+/// The bitstream is the ONLY depth-dependent syntax element: `decode_coefs`
10+/// picks `vp9_cat6_prob`/14 bits at 8-bit and this/16 bits at 10- and 12-bit.
11+const CAT6_PROB_HIGH: [u8; 16] = [
12+ 255, 255, 254, 254, 254, 252, 249, 243, 230, 196, 177, 153, 140, 133, 130, 129,
13+];
14+
7 /// One plane's entropy contexts: a has-coefficient flag per 4x4 column15 /// One plane's entropy contexts: a has-coefficient flag per 4x4 column
8 /// above the current superblock row and per 4x4 row to the left.16 /// above the current superblock row and per 4x4 row to the left.
9 pub(crate) struct PlaneContexts {17 pub(crate) struct PlaneContexts {
@@ -63,6 +71,7 @@ pub(crate) fn decode_coefs(
63 nb: &[i16],71 nb: &[i16],
64 probs4d: &[[[[[u8; 3]; 6]; 6]; 2]; 2],72 probs4d: &[[[[[u8; 3]; 6]; 6]; 2]; 2],
65 is_inter: bool,73 is_inter: bool,
74+ bd: u8,
66 #[allow(unused_variables)] pos: (usize, usize),75 #[allow(unused_variables)] pos: (usize, usize),
67 #[allow(unused_variables)] plane: usize,76 #[allow(unused_variables)] plane: usize,
68 ) -> CoeffBlock {77 ) -> CoeffBlock {
@@ -83,7 +92,10 @@ pub(crate) fn decode_coefs(
83 92
84 while c < max_eob {93 while c < max_eob {
85 if crate::trace_enabled() {94 if crate::trace_enabled() {
86- eprintln!("TOK c={c} band={band} ctx={ctx} p0={},{},{}", prob[0], prob[1], prob[2]);95+ eprintln!(
96+ "TOK c={c} band={band} ctx={ctx} p0={},{},{}",
97+ prob[0], prob[1], prob[2]
98+ );
87 }99 }
88 if !r.read_bool(prob[0]) {100 if !r.read_bool(prob[0]) {
89 break;101 break;
@@ -108,7 +120,12 @@ pub(crate) fn decode_coefs(
108 token_cache[scan[c] as usize] = 5;120 token_cache[scan[c] as usize] = 5;
109 if r.read_bool(p[5]) {121 if r.read_bool(p[5]) {
110 if r.read_bool(p[7]) {122 if r.read_bool(p[7]) {
111- v = 67 + read_coeff(r, &CAT6_PROB, 14);123+ v = 67
124+ + if bd == 8 {
125+ read_coeff(r, &CAT6_PROB, 14)
126+ } else {
127+ read_coeff(r, &CAT6_PROB_HIGH, 16)
128+ };
112 } else {129 } else {
113 v = 35 + read_coeff(r, &CAT5_PROB, 5);130 v = 35 + read_coeff(r, &CAT5_PROB, 5);
114 }131 }
crates/ec-vp9/src/transform.rsmodified+92 -35
@@ -46,14 +46,24 @@ const S2: i64 = 9929;
46 const S3: i64 = 13377;46 const S3: i64 = 13377;
47 const S4: i64 = 15212;47 const S4: i64 = 15212;
48 48
49-/// `clip_pixel_add`.49+use crate::Sample;
50+
51+/// `detect_invalid_highbd_input` (`vpx_dsp/inv_txfm.c:1284`): a 1-D highbitdepth
52+/// transform whose input holds a magnitude `>= 1 << 25` emits all zeros instead
53+/// of reconstructing. Unreachable for valid streams; ported for fidelity.
54+#[inline]
55+fn invalid_highbd_input(input: &[i32], bd: u8) -> bool {
56+ bd != 8 && input.iter().any(|&v| v.unsigned_abs() >= (1u32 << 25))
57+}
58+
59+/// `clip_pixel_add` / `highbd_clip_pixel_add`.
50 #[inline]60 #[inline]
51-pub(crate) fn clip_add(d: u8, v: i32) -> u8 {61+pub(crate) fn clip_add(d: Sample, v: i32, bd: u8) -> Sample {
52- (d as i32 + v).clamp(0, 255) as u862+ crate::clip_pixel_bd(d as i32 + v, bd)
53 }63 }
54 64
55 /// vpx_iwht4x4_16_add_c (lossless).65 /// vpx_iwht4x4_16_add_c (lossless).
56-pub(crate) fn iwht4x4_add(input: &[i32], dest: &mut [u8], stride: usize) {66+pub(crate) fn iwht4x4_add(input: &[i32], dest: &mut [Sample], stride: usize, bd: u8) {
57 let mut output = [0i32; 16];67 let mut output = [0i32; 16];
58 for i in 0..4 {68 for i in 0..4 {
59 let ip = &input[i * 4..i * 4 + 4];69 let ip = &input[i * 4..i * 4 + 4];
@@ -82,14 +92,18 @@ pub(crate) fn iwht4x4_add(input: &[i32], dest: &mut [u8], stride: usize) {
82 let c1 = e1 - c0;92 let c1 = e1 - c0;
83 let a1 = a2 - b1;93 let a1 = a2 - b1;
84 let d1 = d2 + c1;94 let d1 = d2 + c1;
85- dest[i] = clip_add(dest[i], a1);95+ dest[i] = clip_add(dest[i], a1, bd);
86- dest[stride + i] = clip_add(dest[stride + i], b1);96+ dest[stride + i] = clip_add(dest[stride + i], b1, bd);
87- dest[stride * 2 + i] = clip_add(dest[stride * 2 + i], c1);97+ dest[stride * 2 + i] = clip_add(dest[stride * 2 + i], c1, bd);
88- dest[stride * 3 + i] = clip_add(dest[stride * 3 + i], d1);98+ dest[stride * 3 + i] = clip_add(dest[stride * 3 + i], d1, bd);
89 }99 }
90 }100 }
91 101
92-pub(crate) fn idct4(input: &[i32], output: &mut [i32]) {102+pub(crate) fn idct4(input: &[i32], output: &mut [i32], bd: u8) {
103+ if invalid_highbd_input(input, bd) {
104+ output[..4].fill(0);
105+ return;
106+ }
93 let g = |v: i32| v as i64;107 let g = |v: i32| v as i64;
94 let mut step = [0i32; 4];108 let mut step = [0i32; 4];
95 let t1 = (g(input[0]) + g(input[2])) * C16;109 let t1 = (g(input[0]) + g(input[2])) * C16;
@@ -106,7 +120,11 @@ pub(crate) fn idct4(input: &[i32], output: &mut [i32]) {
106 output[3] = step[0] - step[3];120 output[3] = step[0] - step[3];
107 }121 }
108 122
109-pub(crate) fn idct8(input: &[i32], output: &mut [i32]) {123+pub(crate) fn idct8(input: &[i32], output: &mut [i32], bd: u8) {
124+ if invalid_highbd_input(input, bd) {
125+ output[..8].fill(0);
126+ return;
127+ }
110 let g = |v: i32| v as i64;128 let g = |v: i32| v as i64;
111 let mut step1 = [0i32; 8];129 let mut step1 = [0i32; 8];
112 let mut step2 = [0i32; 8];130 let mut step2 = [0i32; 8];
@@ -144,7 +162,11 @@ pub(crate) fn idct8(input: &[i32], output: &mut [i32]) {
144 output[7] = step1[0] - step1[7];162 output[7] = step1[0] - step1[7];
145 }163 }
146 164
147-pub(crate) fn idct16(input: &[i32], output: &mut [i32]) {165+pub(crate) fn idct16(input: &[i32], output: &mut [i32], bd: u8) {
166+ if invalid_highbd_input(input, bd) {
167+ output[..16].fill(0);
168+ return;
169+ }
148 let g = |v: i32| v as i64;170 let g = |v: i32| v as i64;
149 let mut step1 = [0i32; 16];171 let mut step1 = [0i32; 16];
150 let mut step2 = [0i32; 16];172 let mut step2 = [0i32; 16];
@@ -228,12 +250,18 @@ pub(crate) fn idct16(input: &[i32], output: &mut [i32]) {
228 }250 }
229 }251 }
230 252
231-pub(crate) fn idct32(input: &[i32], output: &mut [i32]) {253+pub(crate) fn idct32(input: &[i32], output: &mut [i32], bd: u8) {
254+ if invalid_highbd_input(input, bd) {
255+ output[..32].fill(0);
256+ return;
257+ }
232 let g = |v: i32| v as i64;258 let g = |v: i32| v as i64;
233 let mut step1 = [0i32; 32];259 let mut step1 = [0i32; 32];
234 let mut step2 = [0i32; 32];260 let mut step2 = [0i32; 32];
235 for i in 0..16 {261 for i in 0..16 {
236- step1[i] = input[[0usize, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30][i]];262+ step1[i] = input[[
263+ 0usize, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30,
264+ ][i]];
237 }265 }
238 step1[16] = dcrs(g(input[1]) * C31 - g(input[31]) * C1);266 step1[16] = dcrs(g(input[1]) * C31 - g(input[31]) * C1);
239 step1[31] = dcrs(g(input[1]) * C1 + g(input[31]) * C31);267 step1[31] = dcrs(g(input[1]) * C1 + g(input[31]) * C31);
@@ -441,8 +469,17 @@ pub(crate) fn idct32(input: &[i32], output: &mut [i32]) {
441 }469 }
442 }470 }
443 471
444-pub(crate) fn iadst4(input: &[i32], output: &mut [i32]) {472+pub(crate) fn iadst4(input: &[i32], output: &mut [i32], bd: u8) {
445- let (x0, x1, x2, x3) = (input[0] as i64, input[1] as i64, input[2] as i64, input[3] as i64);473+ if invalid_highbd_input(input, bd) {
474+ output[..4].fill(0);
475+ return;
476+ }
477+ let (x0, x1, x2, x3) = (
478+ input[0] as i64,
479+ input[1] as i64,
480+ input[2] as i64,
481+ input[3] as i64,
482+ );
446 if x0 | x1 | x2 | x3 == 0 {483 if x0 | x1 | x2 | x3 == 0 {
447 output[..4].fill(0);484 output[..4].fill(0);
448 return;485 return;
@@ -458,7 +495,11 @@ pub(crate) fn iadst4(input: &[i32], output: &mut [i32]) {
458 output[3] = dcrs(s0 + s1 - s3);495 output[3] = dcrs(s0 + s1 - s3);
459 }496 }
460 497
461-pub(crate) fn iadst8(input: &[i32], output: &mut [i32]) {498+pub(crate) fn iadst8(input: &[i32], output: &mut [i32], bd: u8) {
499+ if invalid_highbd_input(input, bd) {
500+ output[..8].fill(0);
501+ return;
502+ }
462 let g = |v: i32| v as i64;503 let g = |v: i32| v as i64;
463 let mut x0 = g(input[7]);504 let mut x0 = g(input[7]);
464 let mut x1 = g(input[0]);505 let mut x1 = g(input[0]);
@@ -519,13 +560,29 @@ pub(crate) fn iadst8(input: &[i32], output: &mut [i32]) {
519 output[7] = -x1 as i32;560 output[7] = -x1 as i32;
520 }561 }
521 562
522-pub(crate) fn iadst16(input: &[i32], output: &mut [i32]) {563+pub(crate) fn iadst16(input: &[i32], output: &mut [i32], bd: u8) {
564+ if invalid_highbd_input(input, bd) {
565+ output[..16].fill(0);
566+ return;
567+ }
523 let g = |v: i32| v as i64;568 let g = |v: i32| v as i64;
524 let mut x = [569 let mut x = [
525- g(input[15]), g(input[0]), g(input[13]), g(input[2]),570+ g(input[15]),
526- g(input[11]), g(input[4]), g(input[9]), g(input[6]),571+ g(input[0]),
527- g(input[7]), g(input[8]), g(input[5]), g(input[10]),572+ g(input[13]),
528- g(input[3]), g(input[12]), g(input[1]), g(input[14]),573+ g(input[2]),
574+ g(input[11]),
575+ g(input[4]),
576+ g(input[9]),
577+ g(input[6]),
578+ g(input[7]),
579+ g(input[8]),
580+ g(input[5]),
581+ g(input[10]),
582+ g(input[3]),
583+ g(input[12]),
584+ g(input[1]),
585+ g(input[14]),
529 ];586 ];
530 if x.iter().all(|&v| v == 0) {587 if x.iter().all(|&v| v == 0) {
531 output[..16].fill(0);588 output[..16].fill(0);
@@ -615,8 +672,8 @@ pub(crate) fn iadst16(input: &[i32], output: &mut [i32]) {
615 x[14] = dcrs(s14) as i64;672 x[14] = dcrs(s14) as i64;
616 x[15] = dcrs(s15) as i64;673 x[15] = dcrs(s15) as i64;
617 let o = [674 let o = [
618- x[0], -x[8], x[12], -x[4], x[6], x[14], x[10], x[2],675+ 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],
619- x[3], x[11], x[15], x[7], x[5], -x[13], x[9], -x[1],676+ -x[13], x[9], -x[1],
620 ];677 ];
621 for (i, &v) in o.iter().enumerate() {678 for (i, &v) in o.iter().enumerate() {
622 output[i] = v as i32;679 output[i] = v as i32;
@@ -630,19 +687,20 @@ pub(crate) fn inverse_transform_add(
630 tx_size: usize,687 tx_size: usize,
631 tx_type: usize,688 tx_type: usize,
632 coeffs: &[i32],689 coeffs: &[i32],
633- dest: &mut [u8],690+ dest: &mut [Sample],
634 off: usize,691 off: usize,
635 stride: usize,692 stride: usize,
636 lossless: bool,693 lossless: bool,
694+ bd: u8,
637 ) {695 ) {
638 if lossless {696 if lossless {
639- iwht4x4_add(coeffs, &mut dest[off..], stride);697+ iwht4x4_add(coeffs, &mut dest[off..], stride, bd);
640 return;698 return;
641 }699 }
642 if tx_size == TX_32X32 {700 if tx_size == TX_32X32 {
643 let mut out = [0i32; 1024];701 let mut out = [0i32; 1024];
644 for i in 0..32 {702 for i in 0..32 {
645- idct32(&coeffs[i * 32..], &mut out[i * 32..]);703+ idct32(&coeffs[i * 32..], &mut out[i * 32..], bd);
646 }704 }
647 let mut temp_in = [0i32; 32];705 let mut temp_in = [0i32; 32];
648 let mut temp_out = [0i32; 32];706 let mut temp_out = [0i32; 32];
@@ -650,10 +708,10 @@ pub(crate) fn inverse_transform_add(
650 for (j, ti) in temp_in.iter_mut().enumerate() {708 for (j, ti) in temp_in.iter_mut().enumerate() {
651 *ti = out[j * 32 + i];709 *ti = out[j * 32 + i];
652 }710 }
653- idct32(&temp_in, &mut temp_out);711+ idct32(&temp_in, &mut temp_out, bd);
654 for j in 0..32 {712 for j in 0..32 {
655 let d = &mut dest[off + j * stride + i];713 let d = &mut dest[off + j * stride + i];
656- *d = clip_add(*d, (temp_out[j] + 32) >> 6);714+ *d = clip_add(*d, (temp_out[j] + 32) >> 6, bd);
657 }715 }
658 }716 }
659 return;717 return;
@@ -666,7 +724,7 @@ pub(crate) fn inverse_transform_add(
666 // ADST_DCT codes ADST vertical (= cols pass); DCT_ADST horizontal.724 // ADST_DCT codes ADST vertical (= cols pass); DCT_ADST horizontal.
667 let adst_cols = matches!(tx_type, ADST_DCT | ADST_ADST);725 let adst_cols = matches!(tx_type, ADST_DCT | ADST_ADST);
668 let adst_rows = matches!(tx_type, DCT_ADST | ADST_ADST);726 let adst_rows = matches!(tx_type, DCT_ADST | ADST_ADST);
669- let (row_fn, col_fn): (fn(&[i32], &mut [i32]), fn(&[i32], &mut [i32])) = match tx_size {727+ let (row_fn, col_fn): (fn(&[i32], &mut [i32], u8), fn(&[i32], &mut [i32], u8)) = match tx_size {
670 TX_4X4 => (728 TX_4X4 => (
671 if adst_rows { iadst4 } else { idct4 },729 if adst_rows { iadst4 } else { idct4 },
672 if adst_cols { iadst4 } else { idct4 },730 if adst_cols { iadst4 } else { idct4 },
@@ -682,7 +740,7 @@ pub(crate) fn inverse_transform_add(
682 };740 };
683 let mut out = vec![0i32; n * n];741 let mut out = vec![0i32; n * n];
684 for i in 0..n {742 for i in 0..n {
685- row_fn(&coeffs[i * n..], &mut out[i * n..]);743+ row_fn(&coeffs[i * n..], &mut out[i * n..], bd);
686 }744 }
687 let mut temp_in = vec![0i32; n];745 let mut temp_in = vec![0i32; n];
688 let mut temp_out = vec![0i32; n];746 let mut temp_out = vec![0i32; n];
@@ -690,15 +748,14 @@ pub(crate) fn inverse_transform_add(
690 for j in 0..n {748 for j in 0..n {
691 temp_in[j] = out[j * n + i];749 temp_in[j] = out[j * n + i];
692 }750 }
693- col_fn(&temp_in, &mut temp_out);751+ col_fn(&temp_in, &mut temp_out, bd);
694 for j in 0..n {752 for j in 0..n {
695 let d = &mut dest[off + j * stride + i];753 let d = &mut dest[off + j * stride + i];
696- *d = clip_add(*d, (temp_out[j] + (1 << (shift - 1))) >> shift);754+ *d = clip_add(*d, (temp_out[j] + (1 << (shift - 1))) >> shift, bd);
697 }755 }
698 }756 }
699 }757 }
700 758
701-
702 #[cfg(test)]759 #[cfg(test)]
703 mod scratch_probe {760 mod scratch_probe {
704 use super::*;761 use super::*;
@@ -707,8 +764,8 @@ mod scratch_probe {
707 for (name, tt) in [("dct_dct", DCT_DCT), ("dct_adst", DCT_ADST)] {764 for (name, tt) in [("dct_dct", DCT_DCT), ("dct_adst", DCT_ADST)] {
708 let mut c = [0i32; 64];765 let mut c = [0i32; 64];
709 c[0] = 38;766 c[0] = 38;
710- let mut d = vec![129u8; 64];767+ let mut d = vec![129u16; 64];
711- inverse_transform_add(TX_8X8, tt, &c, &mut d, 0, 8, false);768+ inverse_transform_add(TX_8X8, tt, &c, &mut d, 0, 8, false, 8);
712 println!("{name}: {:?}", &d[..8]);769 println!("{name}: {:?}", &d[..8]);
713 }770 }
714 }771 }
crates/ec-vp9/tests/dump_probe.rsmodified+1 -1
@@ -17,7 +17,7 @@ fn diff_stats() {
17 let mut first: Option<(usize, usize)> = None;17 let mut first: Option<(usize, usize)> = None;
18 for y in 0..240 {18 for y in 0..240 {
19 for x in 0..320 {19 for x in 0..320 {
20- let a = pic.y[y * pic.stride + x];20+ let a = pic.y[y * pic.stride + x] as u8;
21 let b = refout[y * w + x];21 let b = refout[y * w + x];
22 let (sy, sx) = (y / 64, x / 64);22 let (sy, sx) = (y / 64, x / 64);
23 sb_total[sy][sx] += 1;23 sb_total[sy][sx] += 1;
crates/ec-vp9/tests/hbd_exact.rsadded+101 -0
@@ -0,0 +1,101 @@
1+//! Profile-2 high-bit-depth witness: 10-bit 4:2:0 decode is byte-exact
2+//! against ffmpeg's libvpx (`ffmpeg -v error -i in.ivf -f rawvideo -pix_fmt
3+//! yuv420p10le -`). Pre-fix the decoder refuses `profile 2` by name, so this
4+//! test fails at the first frame; post-fix every shown frame matches.
5+//!
6+//! Media-gated: the 10-bit corpus streams are gitignored, so the test skips
7+//! by name when the fixture is absent (set the fixture tree up per the lane
8+//! notes). The other two cases pin the refusals that STAY: non-4:2:0
9+//! (profiles 1/3) and 12-bit.
10+
11+mod ivf;
12+
13+use ec_vp9::decode::Decoder;
14+use std::path::{Path, PathBuf};
15+
16+fn fixture(name: &str) -> Option<PathBuf> {
17+ let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
18+ p.pop();
19+ p.pop();
20+ p = p.join("fixtures/bitstreams").join(name);
21+ p.exists().then_some(p)
22+}
23+
24+/// ffmpeg's rawvideo `yuv420p10le` bytes (little-endian u16 samples,
25+/// stride == visible width).
26+fn ffmpeg_raw_yuv10(path: &Path) -> Vec<u8> {
27+ let out = std::process::Command::new("ffmpeg")
28+ .args(["-v", "error", "-i"])
29+ .arg(path)
30+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p10le", "-"])
31+ .output()
32+ .expect("ffmpeg must be on PATH for the witnesses");
33+ assert!(out.status.success(), "ffmpeg failed on {path:?}");
34+ out.stdout
35+}
36+
37+fn decode_all(path: &Path) -> (Vec<Vec<u8>>, u8) {
38+ let bytes = std::fs::read(path).unwrap();
39+ let (_f, _w, _h, frames) = ivf::parse_ivf(&bytes);
40+ let mut decoder = Decoder::new();
41+ let mut out = Vec::new();
42+ let mut bd = 0u8;
43+ for frame in &frames {
44+ if let Some(pic) = decoder.decode(&frame.data).expect("decode must succeed") {
45+ bd = pic.bit_depth;
46+ let mut v = Vec::with_capacity((pic.y.len() + pic.u.len() + pic.v.len()) * 2);
47+ for &s in pic.y.iter().chain(pic.u.iter()).chain(pic.v.iter()) {
48+ v.extend_from_slice(&s.to_le_bytes());
49+ }
50+ out.push(v);
51+ }
52+ }
53+ (out, bd)
54+}
55+
56+/// Both 10-bit corpus streams decode to the same pixels ffmpeg's libvpx
57+/// produces, sample for sample.
58+#[test]
59+fn profile2_10bit_is_byte_exact() {
60+ let Some(a) = fixture("vp9-1080p-23.976-10bit.ivf") else {
61+ eprintln!("SKIP profile2_10bit_is_byte_exact: 10-bit fixture absent");
62+ return;
63+ };
64+ let (ours, bd) = decode_all(&a);
65+ assert_eq!(bd, 10, "the fixture must decode at 10 bits");
66+ let want = ffmpeg_raw_yuv10(&a);
67+ assert_eq!(ours.len(), 48, "shown frames");
68+ let mut off = 0usize;
69+ for (i, got) in ours.iter().enumerate() {
70+ let n = got.len();
71+ let end = off + n;
72+ assert!(end <= want.len(), "frame {i}: ffmpeg stream too short");
73+ assert_eq!(
74+ got.as_slice(),
75+ &want[off..end],
76+ "frame {i}: 10-bit planes differ from ffmpeg"
77+ );
78+ off = end;
79+ }
80+ assert_eq!(off, want.len(), "frame count / plane size mismatch");
81+}
82+
83+/// The refusals that STAY: profile 1 (4:4:4) is still refused by name.
84+#[test]
85+fn profile1_still_refused_by_name() {
86+ let Some(p) = fixture("vp9-profile1-444.ivf") else {
87+ eprintln!("SKIP profile1_still_refused_by_name: fixture absent");
88+ return;
89+ };
90+ let bytes = std::fs::read(&p).unwrap();
91+ let (_f, _w, _h, frames) = ivf::parse_ivf(&bytes);
92+ let mut decoder = Decoder::new();
93+ let err = decoder
94+ .decode(&frames[0].data)
95+ .expect_err("profile 1 must stay refused");
96+ let msg = err.to_string();
97+ assert!(
98+ msg.contains("profile 1"),
99+ "the refusal must name the profile, got: {msg}"
100+ );
101+}
crates/ec-vp9/tests/inter_pixels_exact.rsmodified+3 -3
@@ -87,9 +87,9 @@ fn compare(path: &std::path::Path) -> usize {
87 );87 );
88 let want = &expected[off..off + frame_bytes];88 let want = &expected[off..off + frame_bytes];
89 let mut got = Vec::with_capacity(frame_bytes);89 let mut got = Vec::with_capacity(frame_bytes);
90- got.extend_from_slice(&pic.y);90+ got.extend(pic.y.iter().map(|&v| v as u8));
91- got.extend_from_slice(&pic.u);91+ got.extend(pic.u.iter().map(|&v| v as u8));
92- got.extend_from_slice(&pic.v);92+ got.extend(pic.v.iter().map(|&v| v as u8));
93 assert_eq!(93 assert_eq!(
94 got.len(),94 got.len(),
95 frame_bytes,95 frame_bytes,
crates/ec-vp9/tests/ivf.rsmodified+4 -5
@@ -31,9 +31,8 @@ pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec<IvfFrame>) {
31 let mut pos = hdr_len;31 let mut pos = hdr_len;
32 let mut frames = Vec::new();32 let mut frames = Vec::new();
33 while pos + 12 <= bytes.len() {33 while pos + 12 <= bytes.len() {
34- let sz = u32::from_le_bytes([34+ let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]])
35- bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3],35+ as usize;
36- ]) as usize;
37 let pts = u64::from_le_bytes(bytes[pos + 4..pos + 12].try_into().unwrap());36 let pts = u64::from_le_bytes(bytes[pos + 4..pos + 12].try_into().unwrap());
38 pos += 12;37 pos += 12;
39 if pos + sz > bytes.len() {38 if pos + sz > bytes.len() {
@@ -51,8 +50,8 @@ pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec<IvfFrame>) {
51 /// Root of the workspace checkout this test runs in (crates/ec-vp9/../..).50 /// Root of the workspace checkout this test runs in (crates/ec-vp9/../..).
52 #[allow(dead_code)] // shared by every test binary that does `mod ivf`51 #[allow(dead_code)] // shared by every test binary that does `mod ivf`
53 pub fn fixture_dir() -> Option<std::path::PathBuf> {52 pub fn fixture_dir() -> Option<std::path::PathBuf> {
54- let bitstreams = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))53+ let bitstreams =
55- .join("../../fixtures/bitstreams");54+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams");
56 if bitstreams.is_dir() {55 if bitstreams.is_dir() {
57 Some(bitstreams)56 Some(bitstreams)
58 } else {57 } else {
crates/ec-vp9/tests/keyframe_exact.rsmodified+9 -9
@@ -71,13 +71,13 @@ fn compare(path: &std::path::Path) {
71 assert_eq!(pic.u.len(), want_u.len());71 assert_eq!(pic.u.len(), want_u.len());
72 assert_eq!(pic.v.len(), want_v.len());72 assert_eq!(pic.v.len(), want_v.len());
73 for (i, (&a, &b)) in pic.y.iter().zip(want_y).enumerate() {73 for (i, (&a, &b)) in pic.y.iter().zip(want_y).enumerate() {
74- assert_eq!(a, b, "Y plane mismatch at pixel ({}, {}) frame {shown}", i % w, i / w);74+ assert_eq!(a as u8, b, "Y plane mismatch at pixel ({}, {}) frame {shown}", i % w, i / w);
75 }75 }
76 for (i, (&a, &b)) in pic.u.iter().zip(want_u).enumerate() {76 for (i, (&a, &b)) in pic.u.iter().zip(want_u).enumerate() {
77- assert_eq!(a, b, "U plane mismatch at ({}, {}) frame {shown}", i % (w / 2), i / (w / 2));77+ assert_eq!(a as u8, b, "U plane mismatch at ({}, {}) frame {shown}", i % (w / 2), i / (w / 2));
78 }78 }
79 for (i, (&a, &b)) in pic.v.iter().zip(want_v).enumerate() {79 for (i, (&a, &b)) in pic.v.iter().zip(want_v).enumerate() {
80- assert_eq!(a, b, "V plane mismatch at ({}, {}) frame {shown}", i % (w / 2), i / (w / 2));80+ assert_eq!(a as u8, b, "V plane mismatch at ({}, {}) frame {shown}", i % (w / 2), i / (w / 2));
81 }81 }
82 shown += 1;82 shown += 1;
83 }83 }
@@ -110,9 +110,9 @@ fn lossless_64_matches_ffmpeg() {
110 let want_y = &reference[..w * h];110 let want_y = &reference[..w * h];
111 let want_u = &reference[w * h..w * h + uv];111 let want_u = &reference[w * h..w * h + uv];
112 let want_v = &reference[w * h + uv..];112 let want_v = &reference[w * h + uv..];
113- assert!(pic.y.iter().eq(want_y.iter()), "lossless Y must be byte-exact");113+ assert!(pic.y.iter().map(|&v| v as u8).eq(want_y.iter().copied()), "lossless Y must be byte-exact");
114- assert!(pic.u.iter().eq(want_u.iter()), "lossless U must be byte-exact");114+ assert!(pic.u.iter().map(|&v| v as u8).eq(want_u.iter().copied()), "lossless U must be byte-exact");
115- assert!(pic.v.iter().eq(want_v.iter()), "lossless V must be byte-exact");115+ assert!(pic.v.iter().map(|&v| v as u8).eq(want_v.iter().copied()), "lossless V must be byte-exact");
116 assert_eq!((pic.width, pic.height), (w as u16, h as u16));116 assert_eq!((pic.width, pic.height), (w as u16, h as u16));
117 }117 }
118 118
@@ -137,9 +137,9 @@ fn inter_stream_decodes_and_matches_ffmpeg() {
137 Some(pic) => {137 Some(pic) => {
138 let off = shown * frame_bytes;138 let off = shown * frame_bytes;
139 let mut got = Vec::with_capacity(frame_bytes);139 let mut got = Vec::with_capacity(frame_bytes);
140- got.extend_from_slice(&pic.y);140+ got.extend(pic.y.iter().map(|&v| v as u8));
141- got.extend_from_slice(&pic.u);141+ got.extend(pic.u.iter().map(|&v| v as u8));
142- got.extend_from_slice(&pic.v);142+ got.extend(pic.v.iter().map(|&v| v as u8));
143 assert_eq!(143 assert_eq!(
144 got,144 got,
145 expected[off..off + frame_bytes],145 expected[off..off + frame_bytes],
crates/ec-vp9/tests/odd_dimensions_exact.rsmodified+3 -3
@@ -141,9 +141,9 @@ fn check(nw: u16, nh: u16) {
141 "frame {i}: ffmpeg has fewer frames than we show"141 "frame {i}: ffmpeg has fewer frames than we show"
142 );142 );
143 let mut got = Vec::with_capacity(frame_bytes);143 let mut got = Vec::with_capacity(frame_bytes);
144- got.extend_from_slice(&pic.y);144+ got.extend(pic.y.iter().map(|&v| v as u8));
145- got.extend_from_slice(&pic.u);145+ got.extend(pic.u.iter().map(|&v| v as u8));
146- got.extend_from_slice(&pic.v);146+ got.extend(pic.v.iter().map(|&v| v as u8));
147 assert_eq!(147 assert_eq!(
148 got,148 got,
149 expected[off..off + frame_bytes],149 expected[off..off + frame_bytes],
crates/ec-vp9/tests/scratch_lfdump.rsmodified+12 -12
@@ -39,9 +39,9 @@ fn dump_lf_diff_map() {
39 dec.decode(&frames[k].data).expect("decode");39 dec.decode(&frames[k].data).expect("decode");
40 }40 }
41 let pic_pre = dec.decode(&frames[fi].data).expect("decode").expect("shown");41 let pic_pre = dec.decode(&frames[fi].data).expect("decode").expect("shown");
42- std::fs::write("/tmp/y_pre_ours.raw", &pic_pre.y[..ysz]).unwrap();42+ std::fs::write("/tmp/y_pre_ours.raw", pic_pre.y[..ysz].iter().map(|&v| v as u8).collect::<Vec<u8>>()).unwrap();
43- std::fs::write("/tmp/u_pre_ours.raw", &pic_pre.u).unwrap();43+ std::fs::write("/tmp/u_pre_ours.raw", pic_pre.u.iter().map(|&v| v as u8).collect::<Vec<u8>>()).unwrap();
44- std::fs::write("/tmp/v_pre_ours.raw", &pic_pre.v).unwrap();44+ std::fs::write("/tmp/v_pre_ours.raw", pic_pre.v.iter().map(|&v| v as u8).collect::<Vec<u8>>()).unwrap();
45 unsafe { std::env::remove_var("EC_VP9_SKIP_LF") };45 unsafe { std::env::remove_var("EC_VP9_SKIP_LF") };
46 46
47 // Post-LF run (fresh decoder).47 // Post-LF run (fresh decoder).
@@ -50,17 +50,17 @@ fn dump_lf_diff_map() {
50 dec.decode(&frames[k].data).expect("decode");50 dec.decode(&frames[k].data).expect("decode");
51 }51 }
52 let pic_post = dec.decode(&frames[fi].data).expect("decode").expect("shown");52 let pic_post = dec.decode(&frames[fi].data).expect("decode").expect("shown");
53- std::fs::write("/tmp/y_post_ours.raw", &pic_post.y[..ysz]).unwrap();53+ std::fs::write("/tmp/y_post_ours.raw", pic_post.y[..ysz].iter().map(|&v| v as u8).collect::<Vec<u8>>()).unwrap();
54- std::fs::write("/tmp/u_post_ours.raw", &pic_post.u).unwrap();54+ std::fs::write("/tmp/u_post_ours.raw", pic_post.u.iter().map(|&v| v as u8).collect::<Vec<u8>>()).unwrap();
55- std::fs::write("/tmp/v_post_ours.raw", &pic_post.v).unwrap();55+ std::fs::write("/tmp/v_post_ours.raw", pic_post.v.iter().map(|&v| v as u8).collect::<Vec<u8>>()).unwrap();
56 56
57 let fsz = ysz + 2 * (w / 2) * (h / 2);57 let fsz = ysz + 2 * (w / 2) * (h / 2);
58 let ff = &reference[fi * fsz..fi * fsz + ysz];58 let ff = &reference[fi * fsz..fi * fsz + ysz];
59 let pre = &pic_pre.y[..ysz];59 let pre = &pic_pre.y[..ysz];
60 let post = &pic_post.y[..ysz];60 let post = &pic_post.y[..ysz];
61 61
62- let pre_diffs: Vec<usize> = (0..ysz).filter(|&i| pre[i] != ff[i]).collect();62+ let pre_diffs: Vec<usize> = (0..ysz).filter(|&i| pre[i] as u8 != ff[i]).collect();
63- let post_diffs: Vec<usize> = (0..ysz).filter(|&i| post[i] != ff[i]).collect();63+ let post_diffs: Vec<usize> = (0..ysz).filter(|&i| post[i] as u8 != ff[i]).collect();
64 let lf_changed_ours: Vec<usize> = (0..ysz).filter(|&i| pre[i] != post[i]).collect();64 let lf_changed_ours: Vec<usize> = (0..ysz).filter(|&i| pre[i] != post[i]).collect();
65 println!("pre-LF diffs vs ffmpeg : {}", pre_diffs.len());65 println!("pre-LF diffs vs ffmpeg : {}", pre_diffs.len());
66 println!("post-LF diffs vs ffmpeg: {}", post_diffs.len());66 println!("post-LF diffs vs ffmpeg: {}", post_diffs.len());
@@ -123,10 +123,10 @@ fn dump_lf_diff_map() {
123 let ff_u = &reference[fi * fsz + ysz..fi * fsz + ysz + uv];123 let ff_u = &reference[fi * fsz + ysz..fi * fsz + ysz + uv];
124 let ff_v = &reference[fi * fsz + ysz + uv..fi * fsz + ysz + 2 * uv];124 let ff_v = &reference[fi * fsz + ysz + uv..fi * fsz + ysz + 2 * uv];
125 let uw = w / 2;125 let uw = w / 2;
126- let u_d: Vec<_> = (0..uv).filter(|&i| pic_post.u[i] != ff_u[i]).collect();126+ let u_d: Vec<_> = (0..uv).filter(|&i| pic_post.u[i] as u8 != ff_u[i]).collect();
127- let v_d: Vec<_> = (0..uv).filter(|&i| pic_post.v[i] != ff_v[i]).collect();127+ let v_d: Vec<_> = (0..uv).filter(|&i| pic_post.v[i] as u8 != ff_v[i]).collect();
128- let u_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.u[i] != ff_u[i]).collect();128+ let u_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.u[i] as u8 != ff_u[i]).collect();
129- let v_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.v[i] != ff_v[i]).collect();129+ let v_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.v[i] as u8 != ff_v[i]).collect();
130 println!("U pre diffs: {} post: {}", u_pre.len(), u_d.len());130 println!("U pre diffs: {} post: {}", u_pre.len(), u_d.len());
131 for &i in &u_d {131 for &i in &u_d {
132 println!(132 println!(
crates/ec-vp9/tests/scratch_lossless.rsmodified+1 -1
@@ -12,7 +12,7 @@ fn lossless_matches() {
12 let mut d = Decoder::new();12 let mut d = Decoder::new();
13 let pic = d.decode(&frames[0].data).unwrap().unwrap();13 let pic = d.decode(&frames[0].data).unwrap().unwrap();
14 let ylen = w as usize * h as usize;14 let ylen = w as usize * h as usize;
15- let mism: Vec<usize> = (0..ylen).filter(|&i| pic.y[i] != refout[i]).collect();15+ let mism: Vec<usize> = (0..ylen).filter(|&i| pic.y[i] as u8 != refout[i]).collect();
16 println!("w={w} h={h} mismatches={} first={:?} ours={:?} ref={:?}",16 println!("w={w} h={h} mismatches={} first={:?} ours={:?} ref={:?}",
17 mism.len(), mism.first(), mism.first().map(|&i| pic.y[i]), mism.first().map(|&i| refout[i]));17 mism.len(), mism.first(), mism.first().map(|&i| pic.y[i]), mism.first().map(|&i| refout[i]));
18 }18 }
crates/ec-vp9/tests/scratch_pixdump.rsmodified+9 -9
@@ -22,9 +22,13 @@ fn pixdump() {
22 for (i, f) in frames.iter().enumerate() {22 for (i, f) in frames.iter().enumerate() {
23 match decoder.decode(&f.data) {23 match decoder.decode(&f.data) {
24 Ok(Some(pic)) => {24 Ok(Some(pic)) => {
25- dump.extend_from_slice(&pic.y);25+ for &v in pic.y.iter().chain(pic.u.iter()).chain(pic.v.iter()) {
26- dump.extend_from_slice(&pic.u);26+ if pic.bit_depth == 8 {
27- dump.extend_from_slice(&pic.v);27+ dump.push(v as u8);
28+ } else {
29+ dump.extend_from_slice(&v.to_le_bytes());
30+ }
31+ }
28 eprintln!(32 eprintln!(
29 "PIXFRAME input={i} shown={shown} {w}x{h} {}x{}",33 "PIXFRAME input={i} shown={shown} {w}x{h} {}x{}",
30 pic.width, pic.height34 pic.width, pic.height
@@ -51,12 +55,8 @@ fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec<IvfFrame>) {
51 let mut pos = hdr_len;55 let mut pos = hdr_len;
52 let mut frames = Vec::new();56 let mut frames = Vec::new();
53 while pos + 12 <= bytes.len() {57 while pos + 12 <= bytes.len() {
54- let sz = u32::from_le_bytes([58+ let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]])
55- bytes[pos],59+ as usize;
56- bytes[pos + 1],
57- bytes[pos + 2],
58- bytes[pos + 3],
59- ]) as usize;
60 let pts = u64::from_le_bytes(bytes[pos + 4..pos + 12].try_into().unwrap());60 let pts = u64::from_le_bytes(bytes[pos + 4..pos + 12].try_into().unwrap());
61 pos += 12;61 pos += 12;
62 if pos + sz > bytes.len() {62 if pos + sz > bytes.len() {
crates/ec-vp9/tests/scratch_pixdump10.rsadded+62 -0
@@ -0,0 +1,62 @@
1+//! Scratch: dump every shown frame's planes as little-endian u16 for the
2+//! high-bit-depth pixel comparator.
3+//!
4+//! `INTER_IVF=<path> EC_VP9_PIXDUMP=<out> cargo test -p ec-vp9 --test scratch_pixdump10`
5+//!
6+//! Layout matches drv_pix10: per shown frame, Y (w*h), U and V each
7+//! (((w+1)/2)*((h+1)/2)) (chroma ceils), rows packed to the visible width,
8+//! each sample written as two little-endian bytes.
9+
10+use ec_vp9::decode::Decoder;
11+
12+#[test]
13+fn pixdump10() {
14+ let (Ok(ivf), Ok(out)) = (std::env::var("INTER_IVF"), std::env::var("EC_VP9_PIXDUMP")) else {
15+ eprintln!("SKIP scratch_pixdump10: set INTER_IVF and EC_VP9_PIXDUMP");
16+ return;
17+ };
18+ let bytes = std::fs::read(&ivf).expect("read ivf");
19+ let (_, w, h, frames) = parse_ivf(&bytes);
20+ let mut decoder = Decoder::new();
21+ let mut dump = Vec::new();
22+ let mut shown = 0usize;
23+ for (i, f) in frames.iter().enumerate() {
24+ match decoder.decode(&f) {
25+ Ok(Some(pic)) => {
26+ for &v in pic.y.iter().chain(pic.u.iter()).chain(pic.v.iter()) {
27+ dump.extend_from_slice(&v.to_le_bytes());
28+ }
29+ eprintln!(
30+ "PIXFRAME input={i} shown={shown} {w}x{h} {}x{} bd={}",
31+ pic.width, pic.height, pic.bit_depth
32+ );
33+ shown += 1;
34+ }
35+ Ok(None) => eprintln!("PIXFRAME input={i} hidden"),
36+ Err(e) => {
37+ eprintln!("PIXERR input={i}: {e}");
38+ break;
39+ }
40+ }
41+ }
42+ std::fs::write(&out, &dump).expect("write dump");
43+ eprintln!("wrote {} bytes ({shown} shown frames)", dump.len());
44+}
45+
46+fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec<Vec<u8>>) {
47+ assert_eq!(&bytes[0..4], b"DKIF", "not an IVF file");
48+ let hdr_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize;
49+ let fourcc = std::str::from_utf8(&bytes[8..12]).unwrap();
50+ let width = u16::from_le_bytes([bytes[12], bytes[13]]);
51+ let height = u16::from_le_bytes([bytes[14], bytes[15]]);
52+ let mut pos = hdr_len;
53+ let mut frames = Vec::new();
54+ while pos + 12 <= bytes.len() {
55+ let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]])
56+ as usize;
57+ let data = bytes[pos + 12..pos + 12 + sz].to_vec();
58+ frames.push(data);
59+ pos += 12 + sz;
60+ }
61+ (fourcc, width, height, frames)
62+}
crates/ec-vp9/tests/scratch_realsweep.rsmodified+6 -6
@@ -99,22 +99,22 @@ fn real_content_sweep() {
99 if i == 0 {99 if i == 0 {
100 std::fs::write(dir.join("ours_f0.yuv"), {100 std::fs::write(dir.join("ours_f0.yuv"), {
101 let mut v = Vec::with_capacity(ysz + 2 * uvs);101 let mut v = Vec::with_capacity(ysz + 2 * uvs);
102- v.extend_from_slice(&pic.y[..ysz.min(pic.y.len())]);102+ v.extend(pic.y[..ysz.min(pic.y.len())].iter().map(|&x| x as u8));
103- v.extend_from_slice(&pic.u);103+ v.extend(pic.u.iter().map(|&x| x as u8));
104- v.extend_from_slice(&pic.v);104+ v.extend(pic.v.iter().map(|&x| x as u8));
105 v105 v
106 })106 })
107 .unwrap();107 .unwrap();
108 std::fs::write(dir.join("ff_f0.yuv"), &raw.stdout[..ysz + 2 * uvs]).unwrap();108 std::fs::write(dir.join("ff_f0.yuv"), &raw.stdout[..ysz + 2 * uvs]).unwrap();
109 }109 }
110 let yd = (0..ysz)110 let yd = (0..ysz)
111- .filter(|&k| pic.y[k] != raw.stdout[base + k])111+ .filter(|&k| pic.y[k] as u8 != raw.stdout[base + k])
112 .count();112 .count();
113 let ud = (0..uvs)113 let ud = (0..uvs)
114- .filter(|&k| pic.u[k] != raw.stdout[base + ysz + k])114+ .filter(|&k| pic.u[k] as u8 != raw.stdout[base + ysz + k])
115 .count();115 .count();
116 let vd = (0..uvs)116 let vd = (0..uvs)
117- .filter(|&k| pic.v[k] != raw.stdout[base + ysz + uvs + k])117+ .filter(|&k| pic.v[k] as u8 != raw.stdout[base + ysz + uvs + k])
118 .count();118 .count();
119 println!(119 println!(
120 "frame {i}: {w}x{h} stride {} uv_stride {} Y {yd} U {ud} V {vd}",120 "frame {i}: {w}x{h} stride {} uv_stride {} Y {yd} U {ud} V {vd}",
crates/ec-vp9/tests/scratch_sweep.rsmodified+1 -1
@@ -18,7 +18,7 @@ fn sweep() {
18 let mut d = Decoder::new();18 let mut d = Decoder::new();
19 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| d.decode(&frames[0].data)));19 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| d.decode(&frames[0].data)));
20 let Ok(Ok(Some(pic))) = r else { continue };20 let Ok(Ok(Some(pic))) = r else { continue };
21- let m = (0..ylen).filter(|&i| pic.y[i] == refout[i]).count();21+ let m = (0..ylen).filter(|&i| pic.y[i] as u8 == refout[i]).count();
22 if m > best.0 { best = (m, t); }22 if m > best.0 { best = (m, t); }
23 }23 }
24 unsafe { std::env::remove_var("EC_VP9_FORCE_TAIL"); }24 unsafe { std::env::remove_var("EC_VP9_FORCE_TAIL"); }
lanes/vp9hbd.report.mdadded+104 -0
@@ -0,0 +1,104 @@
1+# lane-vp9-hbd — profile 2 (10-bit 4:2:0) decode, byte-exact vs libvpx 1.15
2+
3+Base: `79984549` (main). Branch: `lane-vp9-hbd`. Worktree:
4+`~/Documents/Code/Rust/edith_codecs-vp9hbd`. Target dir:
5+`$HOME/.cache/cargo-target-vp9hbd`. Not pushed.
6+
7+## What changed
8+
9+One representation for both depths: every plane is `u16` (`ec_vp9::Sample`,
10+8-bit values in the low byte) and every pixel kernel takes the frame's `bd`
11+and clamps with `clip_pixel_bd(v, bd)`. The reconstruction walk is single;
12+8-bit and high-bit-depth kernels are the same transcribed butterflies with
13+`bd`-scaled clips/thresholds (exactly how libvpx splits its C kernels). No
14+forked decode paths.
15+
16+- `decode.rs`: `Planes`/`Picture` are u16 + `bd`; `Planes::new` fills the
17+ neutral grey `1 << (bd - 1)`; profile gate accepts 0/2, refuses 1/3;
18+ new bit-depth gate refuses 12-bit by name; subsampling gate (4:2:0 only)
19+ unchanged and STAYS. Loop filter + intra + transform calls thread `bd`.
20+- `intra.rs`: u16 staging; `base = 128 << (bd - 8)` replaces the 127/129
21+ fills; DC/`TM` use `base`/`clip_pixel_bd`.
22+- `transform.rs`: `clip_add(d, v, bd)`; idct/iadst take `bd` and port
23+ libvpx's `detect_invalid_highbd_input` guard (zero output on a
24+ magnitude ≥ 2^25 when bd ≠ 8); butterflies unchanged.
25+- `mc.rs`: u16 planes + u16 convolve intermediate; `RefPlane.bd`; the
26+ intermediate clamp is `clip_pixel_bd(v, bd)` (== `clip_pixel` at bd 8).
27+- `loopfilter.rs`: u16; `sc(x, bd)` == libvpx `signed_char_clamp_high`;
28+ `limit`/`blimit`/flat/hev thresholds scaled by `1 << (bd - 8)`.
29+- `tokens.rs`: **the one depth-dependent bitstream element** — the CAT6
30+ coefficient token. 8-bit: 14 extra bits at `vp9_cat6_prob`; 10-bit (and
31+ 12-bit): 16 extra bits at `vp9_cat6_prob_high12 + 2`. Ported.
32+- Tests updated for u16 planes; new `hbd_exact.rs`; `scratch_pixdump10.rs`
33+ (u16-LE dumper harness).
34+
35+## Fail-pre-fix witness
36+
37+Pre-fix, `Decoder::decode` on the 10-bit stream returned
38+`unsupported: vp9 profile 2 — this lane decodes profile 0 only` at
39+`decode.rs:211`. `hbd_exact.rs::profile2_10bit_is_byte_exact` fails at the
40+first frame on the pre-fix tree for that reason.
41+
42+## Oracle
43+
44+`$HOME/.cache/vp9hbd/` = a fresh libvpx 1.15.0 built with
45+`--enable-vp9-highbitdepth` (`CONFIG_VP9_HIGHBITDEPTH 1`), plus
46+`drv_pix10.c` (cropped planes as little-endian u16, frame-indexed,
47+`PIXDUMP=`). Verified against ffmpeg `rawvideo yuv420p10le`.
48+
49+## Byte-exactness (cmp of frame-aligned dumps)
50+
51+| stream | frames | ours vs libvpx 1.15 |
52+|---|---|---|
53+| vp9-1080p-23.976-10bit (profile 2) | 48 | **BYTE-IDENTICAL** |
54+| vp9-1080p-60-10bit (profile 2) | 120 | **BYTE-IDENTICAL** |
55+| vp9-1080p-23.976-8bit | 48 | BYTE-IDENTICAL |
56+| vp9-1080p-60-8bit | 120 | BYTE-IDENTICAL |
57+| vp9-2160p-23.976-8bit | — | BYTE-IDENTICAL |
58+| vp9-superframe-altref | — | BYTE-IDENTICAL |
59+| vp9-tiles-1280 | — | BYTE-IDENTICAL |
60+
61+Inter/odd fixtures are covered by the media-gated `inter_pixels_exact.rs`
62+and `odd_dimensions_exact.rs` (green). 8-bit corpus re-swept on this build;
63+all identical.
64+
65+Repro:
66+```
67+F=fixtures/bitstreams/vp9-1080p-23.976-10bit.ivf
68+CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9hbd INTER_IVF=$F \
69+ EC_VP9_PIXDUMP=$HOME/.cache/vp9hbd/ours10.pix \
70+ cargo test -q -p ec-vp9 --test scratch_pixdump10 -- --nocapture
71+PIXDUMP=$HOME/.cache/vp9hbd/or10.pix $HOME/.cache/vp9hbd/drv_pix10 $F
72+cmp $HOME/.cache/vp9hbd/ours10.pix $HOME/.cache/vp9hbd/or10.pix # identical
73+```
74+
75+## Gates
76+
77+- `cargo test -p ec-vp9` green (all suites; `hbd_exact` 2/2).
78+- Warning parity: exactly the 5 pre-existing (TM_PRED, read_partition,
79+ partition_props, x_mis, y_mis).
80+- Scoped rustfmt on touched files; main checkout untouched (only the
81+ pre-existing untracked `EDITH_FINDINGS.md`).
82+
83+## Debug technique that found the CAT6 bug (reusable)
84+
85+A 10-bit stream desynced in the tile bool decoder at 8-bit-correct syntax.
86+The depth-dependent element is invisible to code reading. Method: built an
87+HBD oracle, patched `vpx_read` to print `BR c=<count> p=<prob> b=<bit>`,
88+matched our `EC_VP9_TRACE` `B <pos> <bc> <prob> <bit>` lines, found the
89+first differing prob (ours 195 = un-updated default, oracle 85), and read
90+libvpx's `decode_coefs` CAT6 branch — 16 bits/`vp9_cat6_prob_high12 + 2` at
91+bd 10. `OMODE` (patched `read_intra_frame_mode_info`) proved the divergence
92+was AFTER mode info, not in it.
93+
94+## Deferred / out of scope (unchanged)
95+
96+- 12-bit decode (profile 2 12-bit): refused by name. No corpus stream.
97+- Profiles 1/3, non-4:2:0 subsampling: refused by name.
98+- Sibling lane owns intra-only + reference scaling; size-change refusal
99+ (`decode.rs` reference-size check) untouched.
100+
101+## Instruments left in tree
102+
103+- `decode.rs`: the tile desync error now names the tile and overread count
104+ (was a bare `ensure`); behaviour otherwise unchanged.