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 @@
44 //! reconstruction and the loop filter (spec 6, 7, 8; libvpx
55 //! `vp9_decodeframe.c`).
66 //!
7-//! Capability: profile-0 8-bit 4:2:0 keyframes and inter frames (motion
8-//! compensation, residual reconstruction, the loop filter and an 8-slot
9-//! reference DPB). Intra-only frames, other profiles/subsamplings and a
10-//! reference whose coded size differs from the current frame are refused by
11-//! name; `show_existing_frame` returns the buffered reference picture instead
12-//! of pretending to decode. Odd coded extents are supported: chroma stores
13-//! and crops at `(w + 1) / 2` (`uv_crop_width`), matching libvpx.
7+//! Capability: profile-0 8-bit and profile-2 10-bit 4:2:0 keyframes and inter
8+//! frames (motion compensation, residual reconstruction, the loop filter and
9+//! an 8-slot reference DPB). Intra-only frames, profiles 1/3, 12-bit, other
10+//! subsamplings and a reference whose coded size differs from the current
11+//! frame are refused by name; `show_existing_frame` returns the buffered
12+//! reference picture instead of pretending to decode. Odd coded extents are
13+//! supported: chroma stores and crops at `(w + 1) / 2` (`uv_crop_width`),
14+//! matching libvpx.
1415
1516 use crate::header::{FrameContext, read_compressed_header};
1617 use crate::intra::build_intra_predictors;
@@ -20,7 +21,7 @@ use crate::modes::{MiInfo, MiState, read_intra_frame_mode_info};
2021 use crate::tables::*;
2122 use crate::tokens::{PlaneContexts, decode_coefs, scan_for};
2223 use crate::transform::inverse_transform_add;
23-use crate::{Error, Result};
24+use crate::{Error, Result, Sample};
2425 use ec_vp9_syntax::{FrameHeader, FrameType, Vp9Parser, superframe};
2526
2627 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
2829 /// A decoded, displayable frame: cropped contiguous planes.
2930 #[derive(Clone, Debug)]
3031 pub struct Picture {
31- /// Luma plane, `stride`-spaced rows of `width` pixels.
32- pub y: Vec<u8>,
32+ /// Luma plane, `stride`-spaced rows of `width` samples.
33+ pub y: Vec<Sample>,
3334 /// U (Cb) plane, half resolution.
34- pub u: Vec<u8>,
35+ pub u: Vec<Sample>,
3536 /// V (Cr) plane, half resolution.
36- pub v: Vec<u8>,
37+ pub v: Vec<Sample>,
3738 /// Frame width in pixels.
3839 pub width: u16,
3940 /// Frame height in pixels.
@@ -43,28 +44,51 @@ pub struct Picture {
4344 /// Chroma row pitch of the returned planes (`(width + 1) / 2`; chroma
4445 /// ceils an odd coded width).
4546 pub uv_stride: usize,
47+ /// Bits per sample (8 for profile 0, 10 for profile 2).
48+ pub bit_depth: u8,
4649 }
4750
4851 struct Planes {
49- y: Vec<u8>,
50- u: Vec<u8>,
51- v: Vec<u8>,
52+ y: Vec<Sample>,
53+ u: Vec<Sample>,
54+ v: Vec<Sample>,
5255 ys: usize,
5356 uvs: usize,
5457 aw: usize,
5558 ah: usize,
59+ /// Bits per sample this frame was decoded at.
60+ bd: u8,
5661 }
5762
5863 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+
5983 /// 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) {
6185 match plane {
6286 0 => (&self.y, self.ys),
6387 1 => (&self.u, self.uvs),
6488 _ => (&self.v, self.uvs),
6589 }
6690 }
67- fn plane(&mut self, plane: usize) -> (&mut [u8], usize) {
91+ fn plane(&mut self, plane: usize) -> (&mut [Sample], usize) {
6892 match plane {
6993 0 => (&mut self.y, self.ys),
7094 1 => (&mut self.u, self.uvs),
@@ -107,10 +131,10 @@ pub struct Decoder {
107131 syntax_blocks: usize,
108132 /// `twd->extend_and_predict_buf`: the per-prediction bordered reference
109133 /// window built when a block's read leaves the reference frame.
110- mc_scratch: Vec<u8>,
134+ mc_scratch: Vec<Sample>,
111135 /// The `vpx_convolve8` stride-64 intermediate plus the second scratch its
112136 /// averaging variant needs.
113- mc_temp: Vec<u8>,
137+ mc_temp: Vec<Sample>,
114138 }
115139
116140 /// One DPB slot: a decoded frame buffer at its ALIGNED (64-multiple) extent
@@ -208,10 +232,16 @@ impl Decoder {
208232 None => Err(corrupt("show_existing_frame names an empty slot")),
209233 };
210234 }
211- if hdr.profile != 0 {
235+ if hdr.profile != 0 && hdr.profile != 2 {
212236 return Err(Error::unsupported(
213237 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)",
215245 ));
216246 }
217247 if hdr.subsampling_x != 1 || hdr.subsampling_y != 1 {
@@ -306,10 +336,16 @@ impl Decoder {
306336 if hdr.show_existing_frame {
307337 continue;
308338 }
309- if hdr.profile != 0 {
339+ if hdr.profile != 0 && hdr.profile != 2 {
310340 return Err(Error::unsupported(
311341 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)",
313349 ));
314350 }
315351 if hdr.frame_type == FrameType::Key {
@@ -384,15 +420,7 @@ impl Decoder {
384420 let height = hdr.height as usize;
385421 let aw = width.div_ceil(64) * 64;
386422 let ah = height.div_ceil(64) * 64;
387- self.planes = Some(Planes {
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- });
423+ self.planes = Some(Planes::new(aw, ah, hdr.bit_depth));
396424 }
397425
398426 let hdr_start = hdr.uncompressed_header_size as usize;
@@ -596,6 +624,7 @@ impl Decoder {
596624 vh,
597625 vh / 2,
598626 hdr.loop_filter.sharpness,
627+ hdr.bit_depth,
599628 );
600629 }
601630
@@ -897,8 +926,20 @@ impl Decoder {
897926 let temp = &mut self.mc_temp;
898927 for plane in 0..3usize {
899928 inter_predict_plane(
900- planes, refs, scratch, temp, hdr, info, plane, row, col, &n4w, &n4h,
901- mb_to_right, mb_to_bottom, sb_type,
929+ planes,
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,
902943 )?;
903944 }
904945 }
@@ -950,6 +991,7 @@ impl Decoder {
950991 // decodeframe.c:413).
951992 let planes = self.planes.as_mut().expect("frame scratch");
952993 let stride = planes.dims(plane).0;
994+ let bd = planes.bd;
953995 let x0 = ((col * 8) >> s) + bcol * 4;
954996 let y0 = ((row * 8) >> s) + brow * 4;
955997 let dst_off = y0 * stride + x0;
@@ -962,6 +1004,7 @@ impl Decoder {
9621004 dst_off,
9631005 stride,
9641006 hdr.quantization.lossless(),
1007+ bd,
9651008 );
9661009 }
9671010 }
@@ -990,15 +1033,7 @@ impl Decoder {
9901033 // mi_row 132 writes 8 rows past a 1080-row buffer).
9911034 let aw = width.div_ceil(64) * 64;
9921035 let ah = height.div_ceil(64) * 64;
993- self.planes = Some(Planes {
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- });
1036+ self.planes = Some(Planes::new(aw, ah, hdr.bit_depth));
10021037 let tail_start = std::env::var("EC_VP9_FORCE_TAIL")
10031038 .ok()
10041039 .and_then(|s| s.parse().ok())
@@ -1131,7 +1166,12 @@ impl Decoder {
11311166 )?;
11321167 }
11331168 }
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+ }
11351175 }
11361176 }
11371177
@@ -1151,6 +1191,7 @@ impl Decoder {
11511191 vh,
11521192 vh / 2,
11531193 hdr.loop_filter.sharpness,
1194+ hdr.bit_depth,
11541195 );
11551196 }
11561197
@@ -1402,7 +1443,17 @@ impl Decoder {
14021443 // mode class (`get_filter_level`), so the grids are written
14031444 // inside the reconstruction rather than from `level_of_seg`.
14041445 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,
14061457 tile_col_start,
14071458 )?;
14081459 } else {
@@ -1412,10 +1463,7 @@ impl Decoder {
14121463 }
14131464 for dy in 0..y_mis {
14141465 for dx in 0..x_mis {
1415- if crate::mvdbg2_enabled()
1416- && row + dy == 7
1417- && col + dx >= 30
1418- && col + dx <= 40
1466+ if crate::mvdbg2_enabled() && row + dy == 7 && col + dx >= 30 && col + dx <= 40
14191467 {
14201468 eprintln!(
14211469 "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 {
15581606 };
15591607 let planes = self.planes.as_mut().expect("frame scratch");
15601608 let stride = planes.dims(plane).0;
1609+ let bd = planes.bd;
15611610 let bs = 4 << tx_size;
15621611 let x0 = ((mi_col * 8) >> s) + tx_col * 4;
15631612 let y0 = ((mi_row * 8) >> s) + tx_row * 4;
@@ -1599,6 +1648,7 @@ impl Decoder {
15991648 rgt,
16001649 mb_to_bottom < 0,
16011650 mb_to_right < 0,
1651+ bd,
16021652 );
16031653 }
16041654
@@ -1665,6 +1715,7 @@ impl Decoder {
16651715 nb,
16661716 &self.ctx.coef[tx_size],
16671717 false,
1718+ bd,
16681719 (x0, y0),
16691720 plane,
16701721 );
@@ -1710,7 +1761,7 @@ impl Decoder {
17101761 Some((it.next()?.parse::<usize>().ok()?, it.next()?.parse().ok()?))
17111762 })
17121763 .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 {
17141765 Some(
17151766 (0..4usize)
17161767 .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec())
@@ -1727,9 +1778,10 @@ impl Decoder {
17271778 dst_off,
17281779 stride,
17291780 lossless,
1781+ bd,
17301782 );
17311783 if let Some(before) = t {
1732- let after: Vec<Vec<u8>> = (0..4usize)
1784+ let after: Vec<Vec<Sample>> = (0..4usize)
17331785 .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec())
17341786 .collect();
17351787 eprintln!("RC x0={x0} y0={y0} tx={tx_size} mode={mode}");
@@ -1764,7 +1816,7 @@ fn bsize_of_n4(n4: usize) -> usize {
17641816 /// aligned decode buffer.
17651817 fn crop_picture(planes: &Planes, width: u16, height: u16) -> Picture {
17661818 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> {
17681820 let mut out = Vec::with_capacity(cw * ch);
17691821 for row in 0..ch {
17701822 out.extend_from_slice(&src[row * stride..row * stride + cw]);
@@ -1782,6 +1834,7 @@ fn crop_picture(planes: &Planes, width: u16, height: u16) -> Picture {
17821834 height,
17831835 stride: w,
17841836 uv_stride: cw,
1837+ bit_depth: planes.bd,
17851838 }
17861839 }
17871840
@@ -1837,7 +1890,9 @@ fn reset_skip_context(
18371890 let offx = (col << 1) >> s;
18381891 let offy = (row << 1) >> s;
18391892 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();
18411896 let l: Vec<u8> = (0..n4h[plane].min(lrows))
18421897 .map(|i| ectx[plane].left[(offy + i) % lrows])
18431898 .collect();
@@ -1962,6 +2017,7 @@ fn decode_inter_tx_tokens(
19622017 nb,
19632018 &fc.coef[tx_size],
19642019 info.is_inter,
2020+ hdr.bit_depth,
19652021 (0, 0),
19662022 plane,
19672023 );
@@ -2001,8 +2057,8 @@ fn decode_inter_tx_tokens(
20012057 fn inter_predict_plane(
20022058 planes: &mut Planes,
20032059 refs: &[Option<RefFrame>; 8],
2004- scratch: &mut Vec<u8>,
2005- temp: &mut Vec<u8>,
2060+ scratch: &mut Vec<Sample>,
2061+ temp: &mut Vec<Sample>,
20062062 hdr: &FrameHeader,
20072063 info: &MiInfo,
20082064 plane: usize,
@@ -2043,6 +2099,7 @@ fn inter_predict_plane(
20432099 // column (or row).
20442100 width: (ref_frame.width as usize + s) >> s,
20452101 height: (ref_frame.height as usize + s) >> s,
2102+ bd: ref_frame.planes.bd,
20462103 };
20472104 if sb_type < 3 {
20482105 // libvpx builds one 4x4 prediction per sub-block, with the MV from
@@ -2059,9 +2116,8 @@ fn inter_predict_plane(
20592116 average_split_mvs_chroma(&info.bmi_mv, rf)
20602117 };
20612118 let (data, _) = planes.plane(plane);
2062- let dst_off = (((row * 8) >> s) + y * 4) * dst_stride
2063- + ((col * 8) >> s)
2064- + xx * 4;
2119+ let dst_off =
2120+ (((row * 8) >> s) + y * 4) * dst_stride + ((col * 8) >> s) + xx * 4;
20652121 build_inter_predictors(
20662122 &mut data[dst_off..],
20672123 dst_stride,
crates/ec-vp9/src/intra.rsmodified+61 -30
@@ -7,16 +7,18 @@
77 //! corner), `above_data[16 + i]` is `above[i]` — exactly the C's
88 //! 16-pixel offset into `above_data[64 + 16]`.
99
10+use crate::Sample;
11+
1012 /// `AVG3`.
1113 #[inline]
12-fn avg3(a: u8, b: u8, c: u8) -> u8 {
13- ((a as u32 + 2 * b as u32 + c as u32 + 2) >> 2) as u8
14+fn avg3(a: Sample, b: Sample, c: Sample) -> Sample {
15+ ((a as u32 + 2 * b as u32 + c as u32 + 2) >> 2) as Sample
1416 }
1517
1618 /// `AVG2`.
1719 #[inline]
18-fn avg2(a: u8, b: u8) -> u8 {
19- ((a as u32 + b as u32 + 1) >> 1) as u8
20+fn avg2(a: Sample, b: Sample) -> Sample {
21+ ((a as u32 + b as u32 + 1) >> 1) as Sample
2022 }
2123
2224 const A: usize = 16;
@@ -43,7 +45,7 @@ fn needs(mode: u8) -> (bool, bool, bool) {
4345 /// block's absolute sample position; `frame_w`/`frame_h` the coded
4446 /// (aligned) plane size.
4547 pub(crate) fn build_intra_predictors(
46- data: &mut [u8],
48+ data: &mut [Sample],
4749 stride: usize,
4850 frame_w: usize,
4951 frame_h: usize,
@@ -61,11 +63,16 @@ pub(crate) fn build_intra_predictors(
6163 bot_ext: bool,
6264 // `xd->mb_to_right_edge < 0` (`vp9_reconintra.c:326/354`).
6365 right_ext: bool,
66+ bd: u8,
6467 ) {
6568 let (need_left, need_above, need_aboveright) = needs(mode);
66- let mut left_col = [0u8; 32];
67- let mut above_data = [0u8; 64 + 16];
68- let at = |dx: isize, dy: isize| -> u8 {
69+ // `int base = 128 << (bd - 8)` (`vp9_reconintra.c:132`): the 127/129
70+ // border fills of an 8-bit frame become `base - 1` / `base + 1`, and
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 {
6976 data[(((y0 as isize + dy) * stride as isize) + x0 as isize + dx) as usize]
7077 };
7178
@@ -89,7 +96,7 @@ pub(crate) fn build_intra_predictors(
8996 left_col[n..bs].fill(v);
9097 }
9198 } else {
92- left_col[..bs].fill(129);
99+ left_col[..bs].fill(base + 1);
93100 }
94101 }
95102
@@ -114,17 +121,17 @@ pub(crate) fn build_intra_predictors(
114121 above_data[A + i] = at(i as isize, -1);
115122 }
116123 }
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 };
118125 } else {
119- above_data[A..A + bs].fill(127);
120- above_data[A - 1] = 127;
126+ above_data[A..A + bs].fill(base - 1);
127+ above_data[A - 1] = base - 1;
121128 }
122129 }
123130
124131 // NEED_ABOVERIGHT (vp9_reconintra.c:350-394).
125132 if need_aboveright {
126133 if up_available {
127- let fill_bs = |d: &mut [u8; 80]| {
134+ let fill_bs = |d: &mut [u16; 80]| {
128135 let v = d[A + bs - 1];
129136 d[A + bs..A + 2 * bs].fill(v);
130137 };
@@ -174,10 +181,10 @@ pub(crate) fn build_intra_predictors(
174181 fill_bs(&mut above_data);
175182 }
176183 }
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 };
178185 } else {
179- above_data[A..A + 2 * bs].fill(127);
180- above_data[A - 1] = 127;
186+ above_data[A..A + 2 * bs].fill(base - 1);
187+ above_data[A - 1] = base - 1;
181188 }
182189 }
183190
@@ -201,7 +208,15 @@ pub(crate) fn build_intra_predictors(
201208 }
202209 let dst = &mut data[y0 * stride + x0..];
203210 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,
205220 );
206221 if crate::trace_enabled()
207222 && std::env::var("EC_VP9_PROBE_TU")
@@ -221,12 +236,13 @@ pub(crate) fn build_intra_predictors(
221236 fn dispatch(
222237 mode: u8,
223238 bs: usize,
224- dst: &mut [u8],
239+ dst: &mut [Sample],
225240 stride: usize,
226- above: &[u8],
227- left: &[u8],
241+ above: &[Sample],
242+ left: &[Sample],
228243 up: bool,
229244 lft: bool,
245+ bd: u8,
230246 ) {
231247 // `above` is the full above_data: [A-1] = above[-1], [A + i] = above[i].
232248 let cor = above[A - 1];
@@ -238,17 +254,32 @@ fn dispatch(
238254 .chain(left[..bs].iter())
239255 .map(|&v| v as u32)
240256 .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+ );
242263 }
243264 0 if lft => {
244265 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+ );
246272 }
247273 0 if up => {
248274 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+ );
250281 }
251- 0 => fill_dc(dst, stride, bs, 128),
282+ 0 => fill_dc(dst, stride, bs, 128u16 << (bd - 8)),
252283 1 => {
253284 for r in 0..bs {
254285 dst[r * stride..r * stride + bs].copy_from_slice(&ab[..bs]);
@@ -314,7 +345,7 @@ fn dispatch(
314345 let mut x = 1;
315346 let mut size = bs - 2;
316347 while x < bs {
317- let src: Vec<u8> = dst[..x + size].to_vec();
348+ let src: Vec<Sample> = dst[..x + size].to_vec();
318349 let off = x * stride;
319350 dst[off..off + size].copy_from_slice(&src[x..x + size]);
320351 dst[off + size..off + bs].fill(above_right);
@@ -324,7 +355,7 @@ fn dispatch(
324355 }
325356 4 => {
326357 // d135
327- let mut border = [0u8; 64];
358+ let mut border = [0u16; 64];
328359 for i in 0..bs - 2 {
329360 border[i] = avg3(left[bs - 3 - i], left[bs - 2 - i], left[bs - 1 - i]);
330361 }
@@ -411,9 +442,9 @@ fn dispatch(
411442 let mut r = 2;
412443 let mut size = bs - 2;
413444 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();
415446 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();
417448 let o0 = r * stride;
418449 dst[o0..o0 + size].copy_from_slice(&src0);
419450 dst[o0 + size..o0 + bs].fill(ab[bs - 1]);
@@ -429,14 +460,14 @@ fn dispatch(
429460 for r in 0..bs {
430461 for c in 0..bs {
431462 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);
433464 }
434465 }
435466 }
436467 }
437468 }
438469
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) {
440471 for r in 0..bs {
441472 dst[r * stride..r * stride + bs].fill(v);
442473 }
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.
22 //!
33 //! The crate implements the VP9 bitstream specification directly
44 //! ([spec]); libvpx's output is used only as a test oracle
55 //! (sample-exactness witnesses against ffmpeg's libvpx-based decoder),
66 //! never as code linked at runtime. Every module documents the spec
77 //! section it implements. Inter frames decode through motion compensation,
8-//! residual reconstruction and the loop filter; intra-only frames, other
9-//! profiles and other subsamplings are refused by name.
8+//! residual reconstruction and the loop filter; intra-only frames, profiles
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).
1016 //!
1117 //! [spec]: https://www.webmproject.org/docs/vp9/
1218 //!
@@ -32,6 +38,25 @@ pub mod transform;
3238
3339 pub use ec_core::{Error, Result};
3440
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+
3560 /// Whether `EC_VP9_TRACE` decision tracing is enabled, resolved once per
3661 /// process. An `var_os` per bool read would lock std's ENV lock on every
3762 /// 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
9595 const LUMA_LEFT_BORDER: u64 = 0x1111111111111111;
9696 const LUMA_ABOVE_BORDER: u64 = 0x000000ff000000ff;
9797
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]`).
98103 #[inline]
99-fn sc(x: i32) -> i32 {
100- x.clamp(-128, 127)
104+fn sc(x: i32, bd: u8) -> i32 {
105+ let shift = (bd - 8) as i32;
106+ x.clamp(-(128 << shift), (128 << shift) - 1)
101107 }
102108
103-/// `filter4` kernel; `idx` = [op1, op0, oq0, oq1].
109+/// `filter4` / `highbd_filter4` kernel; `idx` = [op1, op0, oq0, oq1].
104110 /// `vpx_dsp filter4`: updates p1/p0/q0/q1 in place. `mask` gates the
105-/// whole filter, `hev` the outer taps (vp9_loopfilter.c:81).
106-fn filter4(s: &mut [u8], idx: [usize; 4], thresh: i32, mask: bool) {
111+/// whole filter, `hev` the outer taps (vp9_loopfilter.c:81). The `^ 0x80`
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) {
107114 if !mask {
108115 return;
109116 }
117+ let shift = (bd - 8) as i32;
118+ let bias = 0x80 << shift;
110119 let (op1, op0, oq0, oq1) = (idx[0], idx[1], idx[2], idx[3]);
111120 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;
113124 let (ps1, ps0, qs0, qs1) = (
114- (p1 ^ 0x80) as i8 as i32,
115- (p0 ^ 0x80) as i8 as i32,
116- (q0 ^ 0x80) as i8 as i32,
117- (q1 ^ 0x80) as i8 as i32,
125+ p1 as i32 - bias,
126+ p0 as i32 - bias,
127+ q0 as i32 - bias,
128+ q1 as i32 - bias,
118129 );
119- let mut filter = sc(ps1 - qs1);
130+ let mut filter = sc(ps1 - qs1, bd);
120131 if hev {
121132 // add outer taps if we have high edge variance (& hev mask)
122133 } else {
123134 filter = 0;
124135 }
125136 // inner taps
126- filter = sc(filter + 3 * (qs0 - ps0));
137+ filter = sc(filter + 3 * (qs0 - ps0), bd);
127138 // round one side +4 and the other +3
128- let filter1 = sc(filter + 4) >> 3;
129- let filter2 = sc(filter + 3) >> 3;
130- s[oq0] = (sc(qs0 - filter1) ^ 0x80) as u8;
131- s[op0] = (sc(ps0 + filter2) ^ 0x80) as u8;
139+ let filter1 = sc(filter + 4, bd) >> 3;
140+ let filter2 = sc(filter + 3, bd) >> 3;
141+ s[oq0] = (sc(qs0 - filter1, bd) + bias) as Sample;
142+ s[op0] = (sc(ps0 + filter2, bd) + bias) as Sample;
132143 // outer tap adjustments (& ~hev)
133144 let f = if hev { 0 } else { (filter1 + 1) >> 1 };
134- s[oq1] = (sc(qs1 - f) ^ 0x80) as u8;
135- s[op1] = (sc(ps1 + f) ^ 0x80) as u8;
145+ s[oq1] = (sc(qs1 - f, bd) + bias) as Sample;
146+ s[op1] = (sc(ps1 + f, bd) + bias) as Sample;
136147 }
137148
149+#[allow(clippy::too_many_arguments)]
138150 fn lpf_edge(
139- data: &mut [u8],
151+ data: &mut [Sample],
140152 off: usize,
141153 stride: usize,
142154 dir: u8,
@@ -145,7 +157,14 @@ fn lpf_edge(
145157 limit: i32,
146158 thresh: i32,
147159 nlines: isize,
160+ bd: u8,
148161 ) {
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;
149168 // `dir` 0 = horizontal edges (rows step by stride), 1 = vertical
150169 // (columns step by 1). `taps` in {4, 8, 16}.
151170 let step: isize = if dir == 0 { stride as isize } else { 1 };
@@ -179,23 +198,23 @@ fn lpf_edge(
179198 (edge + step) as usize,
180199 ];
181200 if taps == 4 {
182- filter4(data, idx4, thresh, mask);
201+ filter4(data, idx4, thresh, mask, bd);
183202 continue;
184203 }
185204 if !mask {
186205 continue;
187206 }
188207 // flat_mask4(1, p3..q3)
189- let flat = (rd!(-2) - rd!(-1)).abs() <= 1
190- && (rd!(1) - rd!(0)).abs() <= 1
191- && (rd!(-3) - rd!(-1)).abs() <= 1
192- && (rd!(2) - rd!(0)).abs() <= 1
193- && (rd!(-4) - rd!(-1)).abs() <= 1
194- && (rd!(3) - rd!(0)).abs() <= 1;
208+ let flat = (rd!(-2) - rd!(-1)).abs() <= flat_t
209+ && (rd!(1) - rd!(0)).abs() <= flat_t
210+ && (rd!(-3) - rd!(-1)).abs() <= flat_t
211+ && (rd!(2) - rd!(0)).abs() <= flat_t
212+ && (rd!(-4) - rd!(-1)).abs() <= flat_t
213+ && (rd!(3) - rd!(0)).abs() <= flat_t;
195214 if taps == 8 || !flat {
196215 if !flat {
197216 // plain filter4 with the real mask and hev threshold
198- filter4(data, idx4, thresh, mask);
217+ filter4(data, idx4, thresh, mask, bd);
199218 continue;
200219 }
201220 // 7-tap [1,1,1,2,1,1,1] outputs (filter8).
@@ -209,25 +228,40 @@ fn lpf_edge(
209228 rd!(2),
210229 rd!(3),
211230 );
212- put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as u8);
213- put!(-2, ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as u8);
214- put!(-1, ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as u8);
215- put!(0, ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as u8);
216- put!(1, ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as u8);
217- put!(2, ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as u8);
231+ put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as Sample);
232+ put!(
233+ -2,
234+ ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as Sample
235+ );
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+ );
218252 continue;
219253 }
220254 // flat_mask5(1, s[-8], s[-7], s[-6], s[-5], p0, q0, s[4], s[5], s[6], s[7]):
221255 // |p7..p4 - p0| and |q4..q7 - q0| (the C names are shifted; q4..q6
222256 // are the q1..q3 args of the inner flat_mask4 and compare to q0).
223- let flat2 = (rd!(-8) - rd!(-1)).abs() <= 1
224- && (rd!(-7) - rd!(-1)).abs() <= 1
225- && (rd!(-6) - rd!(-1)).abs() <= 1
226- && (rd!(-5) - rd!(-1)).abs() <= 1
227- && (rd!(4) - rd!(0)).abs() <= 1
228- && (rd!(5) - rd!(0)).abs() <= 1
229- && (rd!(6) - rd!(0)).abs() <= 1
230- && (rd!(7) - rd!(0)).abs() <= 1;
257+ let flat2 = (rd!(-8) - rd!(-1)).abs() <= flat_t
258+ && (rd!(-7) - rd!(-1)).abs() <= flat_t
259+ && (rd!(-6) - rd!(-1)).abs() <= flat_t
260+ && (rd!(-5) - rd!(-1)).abs() <= flat_t
261+ && (rd!(4) - rd!(0)).abs() <= flat_t
262+ && (rd!(5) - rd!(0)).abs() <= flat_t
263+ && (rd!(6) - rd!(0)).abs() <= flat_t
264+ && (rd!(7) - rd!(0)).abs() <= flat_t;
231265 if !flat2 {
232266 let (p3, p2, p1, p0, q0, q1, q2, q3) = (
233267 rd!(-4),
@@ -239,12 +273,27 @@ fn lpf_edge(
239273 rd!(2),
240274 rd!(3),
241275 );
242- put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as u8);
243- put!(-2, ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as u8);
244- put!(-1, ((p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + 4) >> 3) as u8);
245- put!(0, ((p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + 4) >> 3) as u8);
246- put!(1, ((p1 + p0 + q0 + q1 * 2 + q2 + q3 + q3 + 4) >> 3) as u8);
247- put!(2, ((p0 + q0 + q1 + q2 * 2 + q3 + q3 + q3 + 4) >> 3) as u8);
276+ put!(-3, ((p3 * 3 + p2 * 2 + p1 + p0 + q0 + 4) >> 3) as Sample);
277+ put!(
278+ -2,
279+ ((p3 * 2 + p2 + p1 * 2 + p0 + q0 + q1 + 4) >> 3) as Sample
280+ );
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+ );
248297 continue;
249298 }
250299 // 15-tap filter [1 x 7, 2, 1 x 7] (filter16, weights verbatim).
@@ -254,65 +303,67 @@ fn lpf_edge(
254303 let (q4, q5, q6, q7) = (rd!(4), rd!(5), rd!(6), rd!(7));
255304 put!(
256305 -7,
257- ((p7 * 7 + p6 * 2 + p5 + p4 + p3 + p2 + p1 + p0 + q0 + 8) >> 4) as u8
306+ ((p7 * 7 + p6 * 2 + p5 + p4 + p3 + p2 + p1 + p0 + q0 + 8) >> 4) as Sample
258307 );
259308 put!(
260309 -6,
261- ((p7 * 6 + p6 + p5 * 2 + p4 + p3 + p2 + p1 + p0 + q0 + q1 + 8) >> 4) as u8
310+ ((p7 * 6 + p6 + p5 * 2 + p4 + p3 + p2 + p1 + p0 + q0 + q1 + 8) >> 4) as Sample
262311 );
263312 put!(
264313 -5,
265- ((p7 * 5 + p6 + p5 + p4 * 2 + p3 + p2 + p1 + p0 + q0 + q1 + q2 + 8) >> 4) as u8
314+ ((p7 * 5 + p6 + p5 + p4 * 2 + p3 + p2 + p1 + p0 + q0 + q1 + q2 + 8) >> 4) as Sample
266315 );
267316 put!(
268317 -4,
269- ((p7 * 4 + p6 + p5 + p4 + p3 * 2 + p2 + p1 + p0 + q0 + q1 + q2 + q3 + 8) >> 4) as u8
318+ ((p7 * 4 + p6 + p5 + p4 + p3 * 2 + p2 + p1 + p0 + q0 + q1 + q2 + q3 + 8) >> 4)
319+ as Sample
270320 );
271321 put!(
272322 -3,
273323 ((p7 * 3 + p6 + p5 + p4 + p3 + p2 * 2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 + 8) >> 4)
274- as u8
324+ as Sample
275325 );
276326 put!(
277327 -2,
278328 ((p7 * 2 + p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 + q0 + q1 + q2 + q3 + q4 + q5 + 8) >> 4)
279- as u8
329+ as Sample
280330 );
281331 put!(
282332 -1,
283333 ((p7 + p6 + p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 + q1 + q2 + q3 + q4 + q5 + q6 + 8)
284- >> 4) as u8
334+ >> 4) as Sample
285335 );
286336 put!(
287337 0,
288338 ((p6 + p5 + p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 + q2 + q3 + q4 + q5 + q6 + q7 + 8)
289- >> 4) as u8
339+ >> 4) as Sample
290340 );
291341 put!(
292342 1,
293343 ((p5 + p4 + p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 + q3 + q4 + q5 + q6 + q7 * 2 + 8) >> 4)
294- as u8
344+ as Sample
295345 );
296346 put!(
297347 2,
298348 ((p4 + p3 + p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 + q4 + q5 + q6 + q7 * 3 + 8) >> 4)
299- as u8
349+ as Sample
300350 );
301351 put!(
302352 3,
303- ((p3 + p2 + p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 + q5 + q6 + q7 * 4 + 8) >> 4) as u8
353+ ((p3 + p2 + p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 + q5 + q6 + q7 * 4 + 8) >> 4)
354+ as Sample
304355 );
305356 put!(
306357 4,
307- ((p2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 + q6 + q7 * 5 + 8) >> 4) as u8
358+ ((p2 + p1 + p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 + q6 + q7 * 5 + 8) >> 4) as Sample
308359 );
309360 put!(
310361 5,
311- ((p1 + p0 + q0 + q1 + q2 + q3 + q4 + q5 * 2 + q6 + q7 * 6 + 8) >> 4) as u8
362+ ((p1 + p0 + q0 + q1 + q2 + q3 + q4 + q5 * 2 + q6 + q7 * 6 + 8) >> 4) as Sample
312363 );
313364 put!(
314365 6,
315- ((p0 + q0 + q1 + q2 + q3 + q4 + q5 + q6 * 2 + q7 * 7 + 8) >> 4) as u8
366+ ((p0 + q0 + q1 + q2 + q3 + q4 + q5 + q6 * 2 + q7 * 7 + 8) >> 4) as Sample
316367 );
317368 }
318369 }
@@ -567,15 +618,16 @@ impl LfGrids {
567618 /// writes whole 8-column groups into the padded plane).
568619 pub(crate) fn filter_frame(
569620 &self,
570- y: &mut [u8],
621+ y: &mut [Sample],
571622 stride: usize,
572- u: &mut [u8],
573- v: &mut [u8],
623+ u: &mut [Sample],
624+ v: &mut [Sample],
574625 uv_stride: usize,
575626 y_w: usize,
576627 y_h: usize,
577628 uv_h: usize,
578629 sharpness: u8,
630+ bd: u8,
579631 ) {
580632 let lftrace = lftrace_on();
581633 // Luma masks, ported from vp9_setup_mask/build_masks and
@@ -618,7 +670,7 @@ impl LfGrids {
618670 if t == 16 && (xx < 8 || xx + 8 > y_w) {
619671 t = 8;
620672 }
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);
622674 if lftrace {
623675 let kind = match t {
624676 16 => "V16",
@@ -629,7 +681,7 @@ impl LfGrids {
629681 }
630682 }
631683 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);
633685 if lftrace {
634686 eprintln!("V4I {} {}", xx + 4, yy);
635687 }
@@ -667,7 +719,7 @@ impl LfGrids {
667719 if t == 16 && (yy < 8 || yy + 8 > y_h) {
668720 t = 8;
669721 }
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);
671723 if lftrace {
672724 let kind = match t {
673725 16 => "H16",
@@ -685,7 +737,7 @@ impl LfGrids {
685737 // exists only in the 4:2:0-chroma path (ss11,
686738 // vp9_loopfilter.c:1382) and in non420 under `ss_y`.
687739 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);
689741 if lftrace {
690742 eprintln!("H4I {} {}", xx, yy + 4);
691743 }
@@ -830,11 +882,7 @@ impl LfGrids {
830882 0
831883 };
832884 if taps != 0 {
833- let t = if taps == 16 && x8 < 8 {
834- 8
835- } else {
836- taps
837- };
885+ let t = if taps == 16 && x8 < 8 { 8 } else { taps };
838886 lpf_edge(
839887 data,
840888 y8 * uv_stride + x8,
@@ -845,6 +893,7 @@ impl LfGrids {
845893 li,
846894 th,
847895 8,
896+ bd,
848897 );
849898 }
850899 }
@@ -859,6 +908,7 @@ impl LfGrids {
859908 li,
860909 th,
861910 8,
911+ bd,
862912 );
863913 }
864914 }
@@ -906,12 +956,11 @@ impl LfGrids {
906956 li,
907957 th,
908958 8,
959+ bd,
909960 );
910961 }
911962 }
912- if int4 & bit != 0
913- && sbr + 2 * rg != self.mi_rows - 1
914- && y8 + 8 <= uv_h
963+ if int4 & bit != 0 && sbr + 2 * rg != self.mi_rows - 1 && y8 + 8 <= uv_h
915964 {
916965 lpf_edge(
917966 data,
@@ -923,6 +972,7 @@ impl LfGrids {
923972 li,
924973 th,
925974 8,
975+ bd,
926976 );
927977 }
928978 }
@@ -952,10 +1002,10 @@ mod tests {
9521002 }
9531003 }
9541004
955- fn run(g: &LfGrids, y: &mut [u8]) {
956- let mut u = vec![128u8; 32 * 32];
957- let mut v = vec![128u8; 32 * 32];
958- g.filter_frame(y, 64, &mut u, &mut v, 32, 64, 64, 32, 0);
1005+ fn run(g: &LfGrids, y: &mut [Sample]) {
1006+ let mut u = vec![128u16; 32 * 32];
1007+ let mut v = vec![128u16; 32 * 32];
1008+ g.filter_frame(y, 64, &mut u, &mut v, 32, 64, 64, 32, 0, 8);
9591009 }
9601010
9611011 /// The luma internal-4x4 horizontal edge fires on the frame's LAST MI row.
@@ -973,7 +1023,7 @@ mod tests {
9731023 let stride = 64;
9741024 // A gentle step (4) between rows 59 and 60: sharp steps fail the
9751025 // 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];
9771027 for row in 60..64 {
9781028 y[row * stride..row * stride + 64].fill(104);
9791029 }
@@ -985,4 +1035,3 @@ mod tests {
9851035 );
9861036 }
9871037 }
988-
crates/ec-vp9/src/mc.rsmodified+53 -35
@@ -110,20 +110,12 @@ pub(crate) const FILTERS: [[[i16; TAPS]; SUBPEL_SHIFTS as usize]; 4] = [
110110 ],
111111 ];
112112
113-/// `clip_pixel` (`vpx_dsp/vpx_dsp_common.h`).
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-}
113+use crate::{Sample, clip_pixel_bd, round_pow2};
122114
123115 /// Read `buf[i]` for a possibly negative `i`. Every caller keeps `i` inside
124116 /// the buffer (the border copy guarantees the tap margins exist).
125117 #[inline]
126-fn at(buf: &[u8], i: isize) -> u8 {
118+fn at(buf: &[Sample], i: isize) -> Sample {
127119 buf[i as usize]
128120 }
129121
@@ -162,9 +154,9 @@ pub(crate) fn clamp_mv_to_umv_border_sb(
162154 /// `[0, w)` x `[0, h)`.
163155 #[allow(clippy::too_many_arguments)]
164156 fn build_mc_border(
165- src: &[u8],
157+ src: &[Sample],
166158 src_stride: usize,
167- dst: &mut [u8],
159+ dst: &mut [Sample],
168160 dst_stride: usize,
169161 x: i32,
170162 mut y: i32,
@@ -225,16 +217,17 @@ fn build_mc_border(
225217 /// `origin + y*stride + (x_q4 >> SUBPEL_BITS) - (SUBPEL_TAPS / 2 - 1) + k`.
226218 #[allow(clippy::too_many_arguments)]
227219 fn convolve_horiz(
228- buf: &[u8],
220+ buf: &[Sample],
229221 stride: usize,
230222 origin: isize,
231- dst: &mut [u8],
223+ dst: &mut [Sample],
232224 dst_stride: usize,
233225 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
234226 x0_q4: i32,
235227 w: usize,
236228 rows: usize,
237229 avg: bool,
230+ bd: u8,
238231 ) {
239232 for y in 0..rows {
240233 let mut x_q4 = x0_q4;
@@ -246,12 +239,12 @@ fn convolve_horiz(
246239 for k in 0..TAPS {
247240 sum += at(buf, base + k as isize) as i32 * filt[k] as i32;
248241 }
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;
250243 let d = y * dst_stride + x;
251244 dst[d] = if avg {
252- round_pow2(dst[d] as i32 + v, 1) as u8
245+ round_pow2(dst[d] as i32 + v, 1) as Sample
253246 } else {
254- v as u8
247+ v as Sample
255248 };
256249 x_q4 += SUBPEL_SHIFTS;
257250 }
@@ -260,16 +253,17 @@ fn convolve_horiz(
260253
261254 /// `convolve_vert` / `convolve_avg_vert` (`vpx_dsp/vpx_convolve.c:80`).
262255 fn convolve_vert(
263- buf: &[u8],
256+ buf: &[Sample],
264257 stride: usize,
265258 origin: isize,
266- dst: &mut [u8],
259+ dst: &mut [Sample],
267260 dst_stride: usize,
268261 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
269262 y0_q4: i32,
270263 w: usize,
271264 h: usize,
272265 avg: bool,
266+ bd: u8,
273267 ) {
274268 for x in 0..w {
275269 let mut y_q4 = y0_q4;
@@ -282,12 +276,12 @@ fn convolve_vert(
282276 for k in 0..TAPS {
283277 sum += at(buf, base + k as isize * stride as isize) as i32 * filt[k] as i32;
284278 }
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;
286280 let d = y * dst_stride + x;
287281 dst[d] = if avg {
288- round_pow2(dst[d] as i32 + v, 1) as u8
282+ round_pow2(dst[d] as i32 + v, 1) as Sample
289283 } else {
290- v as u8
284+ v as Sample
291285 };
292286 y_q4 += SUBPEL_SHIFTS;
293287 }
@@ -305,10 +299,10 @@ fn convolve_vert(
305299 /// the averaging variant).
306300 #[allow(clippy::too_many_arguments)]
307301 fn inter_predictor(
308- buf: &[u8],
302+ buf: &[Sample],
309303 stride: usize,
310304 origin: isize,
311- dst: &mut [u8],
305+ dst: &mut [Sample],
312306 dst_stride: usize,
313307 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
314308 subpel_x: i32,
@@ -316,7 +310,8 @@ fn inter_predictor(
316310 w: usize,
317311 h: usize,
318312 avg: bool,
319- temp: &mut [u8],
313+ temp: &mut [Sample],
314+ bd: u8,
320315 ) {
321316 if subpel_x == 0 && subpel_y == 0 {
322317 for y in 0..h {
@@ -324,20 +319,24 @@ fn inter_predictor(
324319 let s = at(buf, origin + (y * stride + x) as isize) as i32;
325320 let d = y * dst_stride + x;
326321 dst[d] = if avg {
327- round_pow2(dst[d] as i32 + s, 1) as u8
322+ round_pow2(dst[d] as i32 + s, 1) as Sample
328323 } else {
329- s as u8
324+ s as Sample
330325 };
331326 }
332327 }
333328 return;
334329 }
335330 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+ );
337334 return;
338335 }
339336 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+ );
341340 return;
342341 }
343342 // vpx_convolve8_c: horizontal pass into a stride-64 intermediate with
@@ -359,6 +358,7 @@ fn inter_predictor(
359358 w,
360359 intermediate_height,
361360 false,
361+ bd,
362362 );
363363 if avg {
364364 // vpx_convolve8_avg_c: full 2D into a second scratch, then average
@@ -366,11 +366,23 @@ fn inter_predictor(
366366 // `temp[..64 * 135]` is the horizontal intermediate; the region after
367367 // it is the 2D result.
368368 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+ );
370382 for y in 0..h {
371383 for x in 0..w {
372384 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;
374386 }
375387 }
376388 return;
@@ -386,13 +398,14 @@ fn inter_predictor(
386398 w,
387399 h,
388400 false,
401+ bd,
389402 );
390403 }
391404
392405 /// One reference plane of a stored frame.
393406 pub(crate) struct RefPlane<'a> {
394407 /// Plane base — the frame's first visible sample.
395- pub data: &'a [u8],
408+ pub data: &'a [Sample],
396409 /// Row pitch.
397410 pub stride: usize,
398411 /// `y_crop_width` / `uv_crop_width`: the coded extent, which is what
@@ -400,6 +413,8 @@ pub(crate) struct RefPlane<'a> {
400413 pub width: usize,
401414 /// `y_crop_height` / `uv_crop_height`.
402415 pub height: usize,
416+ /// Bits per sample of the reference frame.
417+ pub bd: u8,
403418 }
404419
405420 /// `dec_build_inter_predictors` (`vp9/decoder/vp9_decodeframe.c:593`),
@@ -407,7 +422,7 @@ pub(crate) struct RefPlane<'a> {
407422 /// `(x, y)` inside the block at MI `(mi_row, mi_col)`.
408423 #[allow(clippy::too_many_arguments)]
409424 pub(crate) fn build_inter_predictors(
410- dst: &mut [u8],
425+ dst: &mut [Sample],
411426 dst_stride: usize,
412427 refp: &RefPlane<'_>,
413428 mi_col: usize,
@@ -425,9 +440,10 @@ pub(crate) fn build_inter_predictors(
425440 ss_y: usize,
426441 kernel: usize,
427442 avg: bool,
428- scratch: &mut Vec<u8>,
429- temp: &mut Vec<u8>,
443+ scratch: &mut Vec<Sample>,
444+ temp: &mut Vec<Sample>,
430445 ) {
446+ let bd = refp.bd;
431447 let mv_q4 = clamp_mv_to_umv_border_sb(
432448 mv, w as i32, h as i32, mb_left, mb_right, mb_top, mb_bottom, ss_x, ss_y,
433449 );
@@ -511,6 +527,7 @@ pub(crate) fn build_inter_predictors(
511527 h,
512528 avg,
513529 temp,
530+ bd,
514531 );
515532 return;
516533 }
@@ -532,6 +549,7 @@ pub(crate) fn build_inter_predictors(
532549 h,
533550 avg,
534551 temp,
552+ bd,
535553 );
536554 }
537555
crates/ec-vp9/src/tokens.rsmodified+19 -2
@@ -4,6 +4,14 @@
44 use crate::bool::BoolDecoder;
55 use crate::tables::*;
66
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+
715 /// One plane's entropy contexts: a has-coefficient flag per 4x4 column
816 /// above the current superblock row and per 4x4 row to the left.
917 pub(crate) struct PlaneContexts {
@@ -63,6 +71,7 @@ pub(crate) fn decode_coefs(
6371 nb: &[i16],
6472 probs4d: &[[[[[u8; 3]; 6]; 6]; 2]; 2],
6573 is_inter: bool,
74+ bd: u8,
6675 #[allow(unused_variables)] pos: (usize, usize),
6776 #[allow(unused_variables)] plane: usize,
6877 ) -> CoeffBlock {
@@ -83,7 +92,10 @@ pub(crate) fn decode_coefs(
8392
8493 while c < max_eob {
8594 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+ );
8799 }
88100 if !r.read_bool(prob[0]) {
89101 break;
@@ -108,7 +120,12 @@ pub(crate) fn decode_coefs(
108120 token_cache[scan[c] as usize] = 5;
109121 if r.read_bool(p[5]) {
110122 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+ };
112129 } else {
113130 v = 35 + read_coeff(r, &CAT5_PROB, 5);
114131 }
crates/ec-vp9/src/transform.rsmodified+92 -35
@@ -46,14 +46,24 @@ const S2: i64 = 9929;
4646 const S3: i64 = 13377;
4747 const S4: i64 = 15212;
4848
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`.
5060 #[inline]
51-pub(crate) fn clip_add(d: u8, v: i32) -> u8 {
52- (d as i32 + v).clamp(0, 255) as u8
61+pub(crate) fn clip_add(d: Sample, v: i32, bd: u8) -> Sample {
62+ crate::clip_pixel_bd(d as i32 + v, bd)
5363 }
5464
5565 /// 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) {
5767 let mut output = [0i32; 16];
5868 for i in 0..4 {
5969 let ip = &input[i * 4..i * 4 + 4];
@@ -82,14 +92,18 @@ pub(crate) fn iwht4x4_add(input: &[i32], dest: &mut [u8], stride: usize) {
8292 let c1 = e1 - c0;
8393 let a1 = a2 - b1;
8494 let d1 = d2 + c1;
85- dest[i] = clip_add(dest[i], a1);
86- dest[stride + i] = clip_add(dest[stride + i], b1);
87- dest[stride * 2 + i] = clip_add(dest[stride * 2 + i], c1);
88- dest[stride * 3 + i] = clip_add(dest[stride * 3 + i], d1);
95+ dest[i] = clip_add(dest[i], a1, bd);
96+ dest[stride + i] = clip_add(dest[stride + i], b1, bd);
97+ dest[stride * 2 + i] = clip_add(dest[stride * 2 + i], c1, bd);
98+ dest[stride * 3 + i] = clip_add(dest[stride * 3 + i], d1, bd);
8999 }
90100 }
91101
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+ }
93107 let g = |v: i32| v as i64;
94108 let mut step = [0i32; 4];
95109 let t1 = (g(input[0]) + g(input[2])) * C16;
@@ -106,7 +120,11 @@ pub(crate) fn idct4(input: &[i32], output: &mut [i32]) {
106120 output[3] = step[0] - step[3];
107121 }
108122
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+ }
110128 let g = |v: i32| v as i64;
111129 let mut step1 = [0i32; 8];
112130 let mut step2 = [0i32; 8];
@@ -144,7 +162,11 @@ pub(crate) fn idct8(input: &[i32], output: &mut [i32]) {
144162 output[7] = step1[0] - step1[7];
145163 }
146164
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+ }
148170 let g = |v: i32| v as i64;
149171 let mut step1 = [0i32; 16];
150172 let mut step2 = [0i32; 16];
@@ -228,12 +250,18 @@ pub(crate) fn idct16(input: &[i32], output: &mut [i32]) {
228250 }
229251 }
230252
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+ }
232258 let g = |v: i32| v as i64;
233259 let mut step1 = [0i32; 32];
234260 let mut step2 = [0i32; 32];
235261 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]];
237265 }
238266 step1[16] = dcrs(g(input[1]) * C31 - g(input[31]) * C1);
239267 step1[31] = dcrs(g(input[1]) * C1 + g(input[31]) * C31);
@@ -441,8 +469,17 @@ pub(crate) fn idct32(input: &[i32], output: &mut [i32]) {
441469 }
442470 }
443471
444-pub(crate) fn iadst4(input: &[i32], output: &mut [i32]) {
445- let (x0, x1, x2, x3) = (input[0] as i64, input[1] as i64, input[2] as i64, input[3] as i64);
472+pub(crate) fn iadst4(input: &[i32], output: &mut [i32], bd: u8) {
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+ );
446483 if x0 | x1 | x2 | x3 == 0 {
447484 output[..4].fill(0);
448485 return;
@@ -458,7 +495,11 @@ pub(crate) fn iadst4(input: &[i32], output: &mut [i32]) {
458495 output[3] = dcrs(s0 + s1 - s3);
459496 }
460497
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+ }
462503 let g = |v: i32| v as i64;
463504 let mut x0 = g(input[7]);
464505 let mut x1 = g(input[0]);
@@ -519,13 +560,29 @@ pub(crate) fn iadst8(input: &[i32], output: &mut [i32]) {
519560 output[7] = -x1 as i32;
520561 }
521562
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+ }
523568 let g = |v: i32| v as i64;
524569 let mut x = [
525- g(input[15]), g(input[0]), g(input[13]), g(input[2]),
526- g(input[11]), g(input[4]), g(input[9]), g(input[6]),
527- g(input[7]), g(input[8]), g(input[5]), g(input[10]),
528- g(input[3]), g(input[12]), g(input[1]), g(input[14]),
570+ g(input[15]),
571+ g(input[0]),
572+ g(input[13]),
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]),
529586 ];
530587 if x.iter().all(|&v| v == 0) {
531588 output[..16].fill(0);
@@ -615,8 +672,8 @@ pub(crate) fn iadst16(input: &[i32], output: &mut [i32]) {
615672 x[14] = dcrs(s14) as i64;
616673 x[15] = dcrs(s15) as i64;
617674 let o = [
618- x[0], -x[8], x[12], -x[4], x[6], x[14], x[10], x[2],
619- x[3], x[11], x[15], x[7], x[5], -x[13], x[9], -x[1],
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],
676+ -x[13], x[9], -x[1],
620677 ];
621678 for (i, &v) in o.iter().enumerate() {
622679 output[i] = v as i32;
@@ -630,19 +687,20 @@ pub(crate) fn inverse_transform_add(
630687 tx_size: usize,
631688 tx_type: usize,
632689 coeffs: &[i32],
633- dest: &mut [u8],
690+ dest: &mut [Sample],
634691 off: usize,
635692 stride: usize,
636693 lossless: bool,
694+ bd: u8,
637695 ) {
638696 if lossless {
639- iwht4x4_add(coeffs, &mut dest[off..], stride);
697+ iwht4x4_add(coeffs, &mut dest[off..], stride, bd);
640698 return;
641699 }
642700 if tx_size == TX_32X32 {
643701 let mut out = [0i32; 1024];
644702 for i in 0..32 {
645- idct32(&coeffs[i * 32..], &mut out[i * 32..]);
703+ idct32(&coeffs[i * 32..], &mut out[i * 32..], bd);
646704 }
647705 let mut temp_in = [0i32; 32];
648706 let mut temp_out = [0i32; 32];
@@ -650,10 +708,10 @@ pub(crate) fn inverse_transform_add(
650708 for (j, ti) in temp_in.iter_mut().enumerate() {
651709 *ti = out[j * 32 + i];
652710 }
653- idct32(&temp_in, &mut temp_out);
711+ idct32(&temp_in, &mut temp_out, bd);
654712 for j in 0..32 {
655713 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);
657715 }
658716 }
659717 return;
@@ -666,7 +724,7 @@ pub(crate) fn inverse_transform_add(
666724 // ADST_DCT codes ADST vertical (= cols pass); DCT_ADST horizontal.
667725 let adst_cols = matches!(tx_type, ADST_DCT | ADST_ADST);
668726 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 {
670728 TX_4X4 => (
671729 if adst_rows { iadst4 } else { idct4 },
672730 if adst_cols { iadst4 } else { idct4 },
@@ -682,7 +740,7 @@ pub(crate) fn inverse_transform_add(
682740 };
683741 let mut out = vec![0i32; n * n];
684742 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);
686744 }
687745 let mut temp_in = vec![0i32; n];
688746 let mut temp_out = vec![0i32; n];
@@ -690,15 +748,14 @@ pub(crate) fn inverse_transform_add(
690748 for j in 0..n {
691749 temp_in[j] = out[j * n + i];
692750 }
693- col_fn(&temp_in, &mut temp_out);
751+ col_fn(&temp_in, &mut temp_out, bd);
694752 for j in 0..n {
695753 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);
697755 }
698756 }
699757 }
700758
701-
702759 #[cfg(test)]
703760 mod scratch_probe {
704761 use super::*;
@@ -707,8 +764,8 @@ mod scratch_probe {
707764 for (name, tt) in [("dct_dct", DCT_DCT), ("dct_adst", DCT_ADST)] {
708765 let mut c = [0i32; 64];
709766 c[0] = 38;
710- let mut d = vec![129u8; 64];
711- inverse_transform_add(TX_8X8, tt, &c, &mut d, 0, 8, false);
767+ let mut d = vec![129u16; 64];
768+ inverse_transform_add(TX_8X8, tt, &c, &mut d, 0, 8, false, 8);
712769 println!("{name}: {:?}", &d[..8]);
713770 }
714771 }
crates/ec-vp9/tests/dump_probe.rsmodified+1 -1
@@ -17,7 +17,7 @@ fn diff_stats() {
1717 let mut first: Option<(usize, usize)> = None;
1818 for y in 0..240 {
1919 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;
2121 let b = refout[y * w + x];
2222 let (sy, sx) = (y / 64, x / 64);
2323 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 {
8787 );
8888 let want = &expected[off..off + frame_bytes];
8989 let mut got = Vec::with_capacity(frame_bytes);
90- got.extend_from_slice(&pic.y);
91- got.extend_from_slice(&pic.u);
92- got.extend_from_slice(&pic.v);
90+ got.extend(pic.y.iter().map(|&v| v as u8));
91+ got.extend(pic.u.iter().map(|&v| v as u8));
92+ got.extend(pic.v.iter().map(|&v| v as u8));
9393 assert_eq!(
9494 got.len(),
9595 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>) {
3131 let mut pos = hdr_len;
3232 let mut frames = Vec::new();
3333 while pos + 12 <= bytes.len() {
34- let sz = u32::from_le_bytes([
35- bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3],
36- ]) as usize;
34+ let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]])
35+ as usize;
3736 let pts = u64::from_le_bytes(bytes[pos + 4..pos + 12].try_into().unwrap());
3837 pos += 12;
3938 if pos + sz > bytes.len() {
@@ -51,8 +50,8 @@ pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec<IvfFrame>) {
5150 /// Root of the workspace checkout this test runs in (crates/ec-vp9/../..).
5251 #[allow(dead_code)] // shared by every test binary that does `mod ivf`
5352 pub fn fixture_dir() -> Option<std::path::PathBuf> {
54- let bitstreams = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
55- .join("../../fixtures/bitstreams");
53+ let bitstreams =
54+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/bitstreams");
5655 if bitstreams.is_dir() {
5756 Some(bitstreams)
5857 } else {
crates/ec-vp9/tests/keyframe_exact.rsmodified+9 -9
@@ -71,13 +71,13 @@ fn compare(path: &std::path::Path) {
7171 assert_eq!(pic.u.len(), want_u.len());
7272 assert_eq!(pic.v.len(), want_v.len());
7373 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);
7575 }
7676 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));
7878 }
7979 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));
8181 }
8282 shown += 1;
8383 }
@@ -110,9 +110,9 @@ fn lossless_64_matches_ffmpeg() {
110110 let want_y = &reference[..w * h];
111111 let want_u = &reference[w * h..w * h + uv];
112112 let want_v = &reference[w * h + uv..];
113- assert!(pic.y.iter().eq(want_y.iter()), "lossless Y must be byte-exact");
114- assert!(pic.u.iter().eq(want_u.iter()), "lossless U must be byte-exact");
115- assert!(pic.v.iter().eq(want_v.iter()), "lossless V 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().map(|&v| v as u8).eq(want_u.iter().copied()), "lossless U 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");
116116 assert_eq!((pic.width, pic.height), (w as u16, h as u16));
117117 }
118118
@@ -137,9 +137,9 @@ fn inter_stream_decodes_and_matches_ffmpeg() {
137137 Some(pic) => {
138138 let off = shown * frame_bytes;
139139 let mut got = Vec::with_capacity(frame_bytes);
140- got.extend_from_slice(&pic.y);
141- got.extend_from_slice(&pic.u);
142- got.extend_from_slice(&pic.v);
140+ got.extend(pic.y.iter().map(|&v| v as u8));
141+ got.extend(pic.u.iter().map(|&v| v as u8));
142+ got.extend(pic.v.iter().map(|&v| v as u8));
143143 assert_eq!(
144144 got,
145145 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) {
141141 "frame {i}: ffmpeg has fewer frames than we show"
142142 );
143143 let mut got = Vec::with_capacity(frame_bytes);
144- got.extend_from_slice(&pic.y);
145- got.extend_from_slice(&pic.u);
146- got.extend_from_slice(&pic.v);
144+ got.extend(pic.y.iter().map(|&v| v as u8));
145+ got.extend(pic.u.iter().map(|&v| v as u8));
146+ got.extend(pic.v.iter().map(|&v| v as u8));
147147 assert_eq!(
148148 got,
149149 expected[off..off + frame_bytes],
crates/ec-vp9/tests/scratch_lfdump.rsmodified+12 -12
@@ -39,9 +39,9 @@ fn dump_lf_diff_map() {
3939 dec.decode(&frames[k].data).expect("decode");
4040 }
4141 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();
43- std::fs::write("/tmp/u_pre_ours.raw", &pic_pre.u).unwrap();
44- std::fs::write("/tmp/v_pre_ours.raw", &pic_pre.v).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.iter().map(|&v| v as u8).collect::<Vec<u8>>()).unwrap();
44+ std::fs::write("/tmp/v_pre_ours.raw", pic_pre.v.iter().map(|&v| v as u8).collect::<Vec<u8>>()).unwrap();
4545 unsafe { std::env::remove_var("EC_VP9_SKIP_LF") };
4646
4747 // Post-LF run (fresh decoder).
@@ -50,17 +50,17 @@ fn dump_lf_diff_map() {
5050 dec.decode(&frames[k].data).expect("decode");
5151 }
5252 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();
54- std::fs::write("/tmp/u_post_ours.raw", &pic_post.u).unwrap();
55- std::fs::write("/tmp/v_post_ours.raw", &pic_post.v).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.iter().map(|&v| v as u8).collect::<Vec<u8>>()).unwrap();
55+ std::fs::write("/tmp/v_post_ours.raw", pic_post.v.iter().map(|&v| v as u8).collect::<Vec<u8>>()).unwrap();
5656
5757 let fsz = ysz + 2 * (w / 2) * (h / 2);
5858 let ff = &reference[fi * fsz..fi * fsz + ysz];
5959 let pre = &pic_pre.y[..ysz];
6060 let post = &pic_post.y[..ysz];
6161
62- let pre_diffs: Vec<usize> = (0..ysz).filter(|&i| pre[i] != ff[i]).collect();
63- let post_diffs: Vec<usize> = (0..ysz).filter(|&i| post[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] as u8 != ff[i]).collect();
6464 let lf_changed_ours: Vec<usize> = (0..ysz).filter(|&i| pre[i] != post[i]).collect();
6565 println!("pre-LF diffs vs ffmpeg : {}", pre_diffs.len());
6666 println!("post-LF diffs vs ffmpeg: {}", post_diffs.len());
@@ -123,10 +123,10 @@ fn dump_lf_diff_map() {
123123 let ff_u = &reference[fi * fsz + ysz..fi * fsz + ysz + uv];
124124 let ff_v = &reference[fi * fsz + ysz + uv..fi * fsz + ysz + 2 * uv];
125125 let uw = w / 2;
126- let u_d: Vec<_> = (0..uv).filter(|&i| pic_post.u[i] != ff_u[i]).collect();
127- let v_d: Vec<_> = (0..uv).filter(|&i| pic_post.v[i] != ff_v[i]).collect();
128- let u_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.u[i] != ff_u[i]).collect();
129- let v_pre: Vec<_> = (0..uv).filter(|&i| pic_pre.v[i] != ff_v[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] as u8 != ff_v[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] as u8 != ff_v[i]).collect();
130130 println!("U pre diffs: {} post: {}", u_pre.len(), u_d.len());
131131 for &i in &u_d {
132132 println!(
crates/ec-vp9/tests/scratch_lossless.rsmodified+1 -1
@@ -12,7 +12,7 @@ fn lossless_matches() {
1212 let mut d = Decoder::new();
1313 let pic = d.decode(&frames[0].data).unwrap().unwrap();
1414 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();
1616 println!("w={w} h={h} mismatches={} first={:?} ours={:?} ref={:?}",
1717 mism.len(), mism.first(), mism.first().map(|&i| pic.y[i]), mism.first().map(|&i| refout[i]));
1818 }
crates/ec-vp9/tests/scratch_pixdump.rsmodified+9 -9
@@ -22,9 +22,13 @@ fn pixdump() {
2222 for (i, f) in frames.iter().enumerate() {
2323 match decoder.decode(&f.data) {
2424 Ok(Some(pic)) => {
25- dump.extend_from_slice(&pic.y);
26- dump.extend_from_slice(&pic.u);
27- dump.extend_from_slice(&pic.v);
25+ for &v in pic.y.iter().chain(pic.u.iter()).chain(pic.v.iter()) {
26+ if pic.bit_depth == 8 {
27+ dump.push(v as u8);
28+ } else {
29+ dump.extend_from_slice(&v.to_le_bytes());
30+ }
31+ }
2832 eprintln!(
2933 "PIXFRAME input={i} shown={shown} {w}x{h} {}x{}",
3034 pic.width, pic.height
@@ -51,12 +55,8 @@ fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec<IvfFrame>) {
5155 let mut pos = hdr_len;
5256 let mut frames = Vec::new();
5357 while pos + 12 <= bytes.len() {
54- let sz = u32::from_le_bytes([
55- bytes[pos],
56- bytes[pos + 1],
57- bytes[pos + 2],
58- bytes[pos + 3],
59- ]) as usize;
58+ let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]])
59+ as usize;
6060 let pts = u64::from_le_bytes(bytes[pos + 4..pos + 12].try_into().unwrap());
6161 pos += 12;
6262 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() {
9999 if i == 0 {
100100 std::fs::write(dir.join("ours_f0.yuv"), {
101101 let mut v = Vec::with_capacity(ysz + 2 * uvs);
102- v.extend_from_slice(&pic.y[..ysz.min(pic.y.len())]);
103- v.extend_from_slice(&pic.u);
104- v.extend_from_slice(&pic.v);
102+ v.extend(pic.y[..ysz.min(pic.y.len())].iter().map(|&x| x as u8));
103+ v.extend(pic.u.iter().map(|&x| x as u8));
104+ v.extend(pic.v.iter().map(|&x| x as u8));
105105 v
106106 })
107107 .unwrap();
108108 std::fs::write(dir.join("ff_f0.yuv"), &raw.stdout[..ysz + 2 * uvs]).unwrap();
109109 }
110110 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])
112112 .count();
113113 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])
115115 .count();
116116 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])
118118 .count();
119119 println!(
120120 "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() {
1818 let mut d = Decoder::new();
1919 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| d.decode(&frames[0].data)));
2020 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();
2222 if m > best.0 { best = (m, t); }
2323 }
2424 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.