ec-vp8 M2 WIP: full key-frame decode pipeline (tokens/intra/transform/loopfilter/reconstruct) — unit tests 100% green, ffmpeg exactness witnesses RED (luma bug)
Browse files at this commit5b0ae0378148fcbccd9d25d4dbbaf80d77ba663aParent: 5233d8812 changed files +3903 -15
- crates/ec-vp8/examples/dbg_first.rs +46 -0
- crates/ec-vp8/src/bool.rs +26 -11
- crates/ec-vp8/src/decode.rs +679 -0
- crates/ec-vp8/src/header.rs +9 -4
- crates/ec-vp8/src/intra.rs +711 -0
- crates/ec-vp8/src/lib.rs +6 -0
- crates/ec-vp8/src/loopfilter.rs +1064 -0
- crates/ec-vp8/src/modes.rs +311 -0
- crates/ec-vp8/src/tokens.rs +282 -0
- crates/ec-vp8/src/transform.rs +640 -0
- crates/ec-vp8/tests/keyframe_exact.rs +114 -0
- scripts/raw_to_y4m.py +15 -0
crates/ec-vp8/examples/dbg_first.rsadded+46 -0
| @@ -0,0 +1,46 @@ | |||
| 1 | +// Decode one frame: print header/dequant summary + pixel stats. | ||
| 2 | +use ec_vp8::decode::Decoder; | ||
| 3 | +use ec_vp8::transform; | ||
| 4 | +use ec_vp8::{PersistedState, frame, header::FrameHeader}; | ||
| 5 | + | ||
| 6 | +fn main() { | ||
| 7 | + let path = std::env::args().nth(1).expect("ivf path"); | ||
| 8 | + let bytes = std::fs::read(path).unwrap(); | ||
| 9 | + let sz = u32::from_le_bytes([bytes[32], bytes[33], bytes[34], bytes[35]]) as usize; | ||
| 10 | + let frame = &bytes[44..44 + sz]; | ||
| 11 | + let mut st = PersistedState::default(); | ||
| 12 | + let (h, _) = FrameHeader::parse(frame, &mut st).unwrap(); | ||
| 13 | + println!( | ||
| 14 | + "q={} y2dc_d={} y2ac_d={} skip={} lvl={}", | ||
| 15 | + h.quant.yac_qi, | ||
| 16 | + h.quant.y2dc_delta, | ||
| 17 | + h.quant.y2ac_delta, | ||
| 18 | + h.coeff_skip_enabled, | ||
| 19 | + h.filter_level | ||
| 20 | + ); | ||
| 21 | + let dq = transform::dequant( | ||
| 22 | + i32::from(h.quant.yac_qi), | ||
| 23 | + h.quant.ydc_delta, | ||
| 24 | + h.quant.y2dc_delta, | ||
| 25 | + h.quant.y2ac_delta, | ||
| 26 | + h.quant.uvdc_delta, | ||
| 27 | + h.quant.uvac_delta, | ||
| 28 | + ); | ||
| 29 | + println!( | ||
| 30 | + "y1dc={} y1ac={} y2dc={} y2ac={}", | ||
| 31 | + dq.y1_dc, dq.y1_ac, dq.y2_dc, dq.y2_ac | ||
| 32 | + ); | ||
| 33 | + let mut dec = Decoder::new(); | ||
| 34 | + match dec.decode(frame) { | ||
| 35 | + Ok(Some(pic)) => println!( | ||
| 36 | + "{}x{} y[0..8]={:?} min={} max={}", | ||
| 37 | + pic.width, | ||
| 38 | + pic.height, | ||
| 39 | + &pic.y[..8], | ||
| 40 | + pic.y.iter().min().unwrap(), | ||
| 41 | + pic.y.iter().max().unwrap() | ||
| 42 | + ), | ||
| 43 | + Ok(None) => println!("hidden"), | ||
| 44 | + Err(e) => println!("ERR {e}"), | ||
| 45 | + } | ||
| 46 | +} | ||
crates/ec-vp8/src/bool.rsmodified+26 -11
| @@ -11,7 +11,7 @@ | |||
| 11 | //! `bool_encoder`; the tests drive them against a test-only re-implementation | 11 | //! `bool_encoder`; the tests drive them against a test-only re-implementation |
| 12 | //! of that encoder and assert bit-exact round-trips. | 12 | //! of that encoder and assert bit-exact round-trips. |
| 13 | 13 | ||
| 14 | -use ec_core::{Error, Result}; | 14 | +use ec_core::Result; |
| 15 | 15 | ||
| 16 | /// Boolean arithmetic decoder over one data partition (RFC 6386 §7.3). | 16 | /// Boolean arithmetic decoder over one data partition (RFC 6386 §7.3). |
| 17 | pub struct BoolDecoder<'a> { | 17 | pub struct BoolDecoder<'a> { |
| @@ -32,17 +32,28 @@ pub struct BoolDecoder<'a> { | |||
| 32 | 32 | ||
| 33 | impl<'a> BoolDecoder<'a> { | 33 | impl<'a> BoolDecoder<'a> { |
| 34 | /// Start decoding the partition `data` (RFC `init_bool_decoder`): the | 34 | /// Start decoding the partition `data` (RFC `init_bool_decoder`): the |
| 35 | - /// first two bytes are read into `value`, big-endian. | 35 | + /// first two bytes are read into `value`, big-endian. A partition |
| 36 | + /// shorter than two bytes (legal for unused token partitions of | ||
| 37 | + /// multi-partition frames) is zero-extended like the reference | ||
| 38 | + /// decoder does, and the shortfall shows up in [`Self::overreads`]. | ||
| 36 | pub fn new(data: &'a [u8]) -> Result<Self> { | 39 | pub fn new(data: &'a [u8]) -> Result<Self> { |
| 37 | - if data.len() < 2 { | 40 | + if data.is_empty() { |
| 38 | - return Err(Error::corrupt( | 41 | + return Ok(Self { |
| 39 | - "VP8 partition shorter than the two-byte bool decoder init", | 42 | + data, |
| 40 | - )); | 43 | + pos: 0, |
| 44 | + range: 255, | ||
| 45 | + value: 0, | ||
| 46 | + bit_count: 0, | ||
| 47 | + overreads: 0, | ||
| 48 | + }); | ||
| 49 | + } | ||
| 50 | + let mut value = u32::from(data[0]) << 8; | ||
| 51 | + if data.len() > 1 { | ||
| 52 | + value |= u32::from(data[1]); | ||
| 41 | } | 53 | } |
| 42 | - let value = (u32::from(data[0]) << 8) | u32::from(data[1]); | ||
| 43 | Ok(Self { | 54 | Ok(Self { |
| 44 | data, | 55 | data, |
| 45 | - pos: 2, | 56 | + pos: data.len().min(2), |
| 46 | range: 255, | 57 | range: 255, |
| 47 | value, | 58 | value, |
| 48 | bit_count: 0, | 59 | bit_count: 0, |
| @@ -404,9 +415,13 @@ mod tests { | |||
| 404 | } | 415 | } |
| 405 | 416 | ||
| 406 | #[test] | 417 | #[test] |
| 407 | - fn short_partition_is_corrupt() { | 418 | + fn short_partitions_zero_extend() { |
| 408 | - assert!(BoolDecoder::new(&[]).is_err()); | 419 | + // Empty/1-byte partitions are legal for unused token partitions; |
| 409 | - assert!(BoolDecoder::new(&[7]).is_err()); | 420 | + // the init shortfall counts as overreads. |
| 421 | + let mut d = BoolDecoder::new(&[]).unwrap(); | ||
| 422 | + assert_eq!(d.read_bool(128), false); | ||
| 423 | + let mut d = BoolDecoder::new(&[0]).unwrap(); | ||
| 424 | + assert_eq!(d.read_bool(128), false); | ||
| 410 | } | 425 | } |
| 411 | 426 | ||
| 412 | #[test] | 427 | #[test] |
crates/ec-vp8/src/decode.rsadded+679 -0
| @@ -0,0 +1,679 @@ | |||
| 1 | +//! Frame decoding: per-row mode parsing, token decoding, intra | ||
| 2 | +//! prediction and reconstruction (RFC 6386 §5, §11, §12, §13, §14). | ||
| 3 | +//! | ||
| 4 | +//! The decoder mirrors the reference decoder's row pipeline: per | ||
| 5 | +//! macroblock row, all first-partition mode records are parsed, then | ||
| 6 | +//! each macroblock's tokens are decoded from its row-assigned token | ||
| 7 | +//! partition (row `r` uses partition `r % partitions`, exactly like | ||
| 8 | +//! libvpx/dixie) and immediately reconstructed. The loop filter runs as | ||
| 9 | +//! a post-pass in raster MB order — for a non-threaded decode this is | ||
| 10 | +//! edge-for-edge identical to the reference's row-delayed filtering, | ||
| 11 | +//! because an MB's filter inputs only ever come from MBs already | ||
| 12 | +//! filtered earlier in that order. | ||
| 13 | + | ||
| 14 | +use crate::bool::BoolDecoder; | ||
| 15 | +use crate::frame::{FrameType, KeyFrameDims, mb_geometry}; | ||
| 16 | +use crate::header::FrameHeader; | ||
| 17 | +use crate::intra; | ||
| 18 | +use crate::loopfilter::{self, MbFilterInfo}; | ||
| 19 | +use crate::modes; | ||
| 20 | +use crate::tables::KF_BMODE_PROB; | ||
| 21 | +use crate::tokens::{self, Dq, MbCoeffs, TokenContexts}; | ||
| 22 | +use crate::transform; | ||
| 23 | +use crate::transform::Dequant; | ||
| 24 | +use crate::{Error, PersistedState, Result}; | ||
| 25 | + | ||
| 26 | +/// Reconstructed-image plane: a padded buffer with a 1-pixel left/top | ||
| 27 | +/// border (127 on top including the corner, 129 on the left — RFC 6386 | ||
| 28 | +/// §12) so intra prediction reads neighbours without special cases. | ||
| 29 | +struct Plane { | ||
| 30 | + data: Vec<u8>, | ||
| 31 | + /// Row pitch: `1 + mb_cols * mb_size`. | ||
| 32 | + stride: usize, | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +impl Plane { | ||
| 36 | + fn new(mb_cols: usize, mb_rows: usize, mb_size: usize) -> Self { | ||
| 37 | + let stride = 1 + mb_cols * mb_size; | ||
| 38 | + let rows = 1 + mb_rows * mb_size; | ||
| 39 | + let mut data = vec![0u8; stride * rows]; | ||
| 40 | + for cell in data[..stride].iter_mut() { | ||
| 41 | + *cell = 127; | ||
| 42 | + } | ||
| 43 | + for row in 1..rows { | ||
| 44 | + data[row * stride] = 129; | ||
| 45 | + } | ||
| 46 | + Plane { data, stride } | ||
| 47 | + } | ||
| 48 | + | ||
| 49 | + fn resize(&mut self, mb_cols: usize, mb_rows: usize, mb_size: usize) { | ||
| 50 | + *self = Plane::new(mb_cols, mb_rows, mb_size); | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + /// Offset of pixel (x, y); the border occupies x = -1 / y = -1. | ||
| 54 | + fn at(&self, x: usize, y: usize) -> usize { | ||
| 55 | + (1 + y) * self.stride + 1 + x | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + /// Offset of the pixel row ABOVE pixel row `y` (the border row for | ||
| 59 | + /// y = 0), at pixel column `x`. | ||
| 60 | + fn at_above(&self, x: usize, y: usize) -> usize { | ||
| 61 | + y * self.stride + 1 + x | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + /// Offset of the pixel column LEFT of pixel column `x` (the border | ||
| 65 | + /// column for x = 0), at pixel row `y`. | ||
| 66 | + fn at_left(&self, x: usize, y: usize) -> usize { | ||
| 67 | + (1 + y) * self.stride + x | ||
| 68 | + } | ||
| 69 | + | ||
| 70 | + /// Offset of the above-left pixel (border corner for x = y = 0). | ||
| 71 | + fn at_above_left(&self, x: usize, y: usize) -> usize { | ||
| 72 | + y * self.stride + x | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// One macroblock's parsed prediction record. | ||
| 77 | +#[derive(Clone, Default)] | ||
| 78 | +struct MbInfo { | ||
| 79 | + /// [`modes::YMode`] as its coded integer. | ||
| 80 | + y_mode: u8, | ||
| 81 | + uv_mode: u8, | ||
| 82 | + b_modes: [u8; 16], | ||
| 83 | + segment_id: u8, | ||
| 84 | + skip: bool, | ||
| 85 | + /// Any non-zero coefficient decoded for this MB (bit 31 of dixie's | ||
| 86 | + /// eob_mask); decides the loop filter's interior edges (§15.1). | ||
| 87 | + has_nz: bool, | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +impl MbInfo { | ||
| 91 | + fn has_y2(&self) -> bool { | ||
| 92 | + self.y_mode != modes::YMode::BPred.as_u8() | ||
| 93 | + } | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// The VP8 decoder. Feed complete frames (one full VP8 frame payload, | ||
| 97 | +/// exactly what a container demuxer hands over for the `VP80`/`vp08` | ||
| 98 | +/// codec). | ||
| 99 | +pub struct Decoder { | ||
| 100 | + state: PersistedState, | ||
| 101 | + dims: KeyFrameDims, | ||
| 102 | + mb_cols: usize, | ||
| 103 | + mb_rows: usize, | ||
| 104 | + y: Plane, | ||
| 105 | + u: Plane, | ||
| 106 | + v: Plane, | ||
| 107 | + /// `(mb_rows + 1) * (mb_cols + 1)` records; row/column index 0 is the | ||
| 108 | + /// DC_PRED border (dixie's `mb_info` border trick). | ||
| 109 | + mb_info: Vec<MbInfo>, | ||
| 110 | + token_ctxs: TokenContexts, | ||
| 111 | + frame_decoded: bool, | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// A decoded, displayable frame: cropped contiguous planes. | ||
| 115 | +pub struct Picture { | ||
| 116 | + /// Luma plane, `stride`-spaced rows of `width` pixels. | ||
| 117 | + pub y: Vec<u8>, | ||
| 118 | + /// U (Cb) plane, half resolution. | ||
| 119 | + pub u: Vec<u8>, | ||
| 120 | + /// V (Cr) plane, half resolution. | ||
| 121 | + pub v: Vec<u8>, | ||
| 122 | + pub width: u16, | ||
| 123 | + pub height: u16, | ||
| 124 | + /// Luma row pitch of the returned planes. | ||
| 125 | + pub stride: usize, | ||
| 126 | + /// Chroma row pitch of the returned planes. | ||
| 127 | + pub uv_stride: usize, | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +impl Decoder { | ||
| 131 | + /// Create an empty decoder; the first key frame sets the size. | ||
| 132 | + pub fn new() -> Self { | ||
| 133 | + Self { | ||
| 134 | + state: PersistedState::default(), | ||
| 135 | + dims: KeyFrameDims { | ||
| 136 | + width: 0, | ||
| 137 | + height: 0, | ||
| 138 | + h_scale: 0, | ||
| 139 | + v_scale: 0, | ||
| 140 | + }, | ||
| 141 | + mb_cols: 0, | ||
| 142 | + mb_rows: 0, | ||
| 143 | + y: Plane { | ||
| 144 | + data: Vec::new(), | ||
| 145 | + stride: 0, | ||
| 146 | + }, | ||
| 147 | + u: Plane { | ||
| 148 | + data: Vec::new(), | ||
| 149 | + stride: 0, | ||
| 150 | + }, | ||
| 151 | + v: Plane { | ||
| 152 | + data: Vec::new(), | ||
| 153 | + stride: 0, | ||
| 154 | + }, | ||
| 155 | + mb_info: Vec::new(), | ||
| 156 | + token_ctxs: TokenContexts::new(0), | ||
| 157 | + frame_decoded: false, | ||
| 158 | + } | ||
| 159 | + } | ||
| 160 | + | ||
| 161 | + /// Size of the frames this decoder produces, once known. | ||
| 162 | + pub fn dimensions(&self) -> Option<(u16, u16)> { | ||
| 163 | + self.frame_decoded | ||
| 164 | + .then_some((self.dims.width, self.dims.height)) | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + /// Decode one frame; returns the picture when it is for display | ||
| 168 | + /// (`show_frame`). Hidden frames still update the decode state. | ||
| 169 | + pub fn decode(&mut self, frame: &[u8]) -> Result<Option<Picture>> { | ||
| 170 | + let (header, _part0) = FrameHeader::parse(frame, &mut self.state)?; | ||
| 171 | + match header.tag.frame_type { | ||
| 172 | + FrameType::Key => self.decode_keyframe(frame, header), | ||
| 173 | + FrameType::Inter => Err(Error::unsupported( | ||
| 174 | + "VP8 inter frame", | ||
| 175 | + "inter-frame decoding is the next milestone of this crate", | ||
| 176 | + )), | ||
| 177 | + } | ||
| 178 | + } | ||
| 179 | + | ||
| 180 | + fn ensure_buffers(&mut self, kf: KeyFrameDims) { | ||
| 181 | + let (mb_cols, mb_rows) = mb_geometry(kf.width, kf.height); | ||
| 182 | + if self.mb_cols != mb_cols || self.mb_rows != mb_rows { | ||
| 183 | + self.y.resize(mb_cols, mb_rows, 16); | ||
| 184 | + self.u.resize(mb_cols, mb_rows, 8); | ||
| 185 | + self.v.resize(mb_cols, mb_rows, 8); | ||
| 186 | + self.mb_info = vec![MbInfo::default(); (mb_cols + 1) * (mb_rows + 1)]; | ||
| 187 | + self.token_ctxs = TokenContexts::new(mb_cols); | ||
| 188 | + } | ||
| 189 | + self.mb_cols = mb_cols; | ||
| 190 | + self.mb_rows = mb_rows; | ||
| 191 | + self.dims = kf; | ||
| 192 | + // Reset the mode border (row 0 / column 0) so the top-left mode | ||
| 193 | + // contexts read DC_PRED like a fresh decode. | ||
| 194 | + for col in 0..=mb_cols { | ||
| 195 | + self.mb_info[col] = MbInfo::default(); | ||
| 196 | + } | ||
| 197 | + for row in 0..=mb_rows { | ||
| 198 | + self.mb_info[row * (mb_cols + 1)] = MbInfo::default(); | ||
| 199 | + } | ||
| 200 | + } | ||
| 201 | + | ||
| 202 | + /// Mode-record index for MB (row, col); row/col 0 is the border. | ||
| 203 | + fn mbi(&self, row: usize, col: usize) -> &MbInfo { | ||
| 204 | + &self.mb_info[row * (self.mb_cols + 1) + col] | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + fn mbi_mut(&mut self, row: usize, col: usize) -> &mut MbInfo { | ||
| 208 | + let w = self.mb_cols + 1; | ||
| 209 | + &mut self.mb_info[row * w + col] | ||
| 210 | + } | ||
| 211 | + | ||
| 212 | + fn decode_keyframe(&mut self, frame: &[u8], header: FrameHeader) -> Result<Option<Picture>> { | ||
| 213 | + let kf = header.dims.expect("key frame header carries dimensions"); | ||
| 214 | + self.ensure_buffers(kf); | ||
| 215 | + | ||
| 216 | + // Token partition bool decoders (§9.5). | ||
| 217 | + let mut partitions = Vec::with_capacity(header.partition_sizes.len()); | ||
| 218 | + let mut off = header.token_data_offset + 3 * (header.partition_sizes.len() - 1); | ||
| 219 | + for &sz in &header.partition_sizes { | ||
| 220 | + let end = off + sz as usize; | ||
| 221 | + let slice = frame | ||
| 222 | + .get(off..end) | ||
| 223 | + .ok_or_else(|| Error::corrupt("VP8 token partition extends past frame end"))?; | ||
| 224 | + partitions.push(BoolDecoder::new(slice)?); | ||
| 225 | + off = end; | ||
| 226 | + } | ||
| 227 | + | ||
| 228 | + // Dequant factors per segment (dixie dequant_init, §10/§14.1). | ||
| 229 | + let seg = &header.segmentation; | ||
| 230 | + let mut dqf = [Dequant { | ||
| 231 | + y1_dc: 0, | ||
| 232 | + y1_ac: 0, | ||
| 233 | + y2_dc: 0, | ||
| 234 | + y2_ac: 0, | ||
| 235 | + uv_dc: 0, | ||
| 236 | + uv_ac: 0, | ||
| 237 | + }; 4]; | ||
| 238 | + for (i, dq) in dqf.iter_mut().enumerate() { | ||
| 239 | + let q = if seg.enabled { | ||
| 240 | + if seg.abs_delta { | ||
| 241 | + seg.quant_idx[i] | ||
| 242 | + } else { | ||
| 243 | + i32::from(header.quant.yac_qi) + seg.quant_idx[i] | ||
| 244 | + } | ||
| 245 | + } else { | ||
| 246 | + i32::from(header.quant.yac_qi) | ||
| 247 | + }; | ||
| 248 | + *dq = transform::dequant( | ||
| 249 | + q, | ||
| 250 | + header.quant.ydc_delta, | ||
| 251 | + header.quant.y2dc_delta, | ||
| 252 | + header.quant.y2ac_delta, | ||
| 253 | + header.quant.uvdc_delta, | ||
| 254 | + header.quant.uvac_delta, | ||
| 255 | + ); | ||
| 256 | + } | ||
| 257 | + | ||
| 258 | + let hdr_start = crate::frame::FRAME_TAG_SZ + crate::frame::KEYFRAME_HEADER_SZ; | ||
| 259 | + let mut hdr_dec = BoolDecoder::new(&frame[hdr_start..header.token_data_offset])?; | ||
| 260 | + | ||
| 261 | + self.token_ctxs.reset_above_row(); | ||
| 262 | + | ||
| 263 | + for row in 1..=self.mb_rows { | ||
| 264 | + self.token_ctxs.reset_left(); | ||
| 265 | + // Phase 1: parse every mode record of the row (partition 0). | ||
| 266 | + for col in 1..=self.mb_cols { | ||
| 267 | + let mut mb = MbInfo::default(); | ||
| 268 | + if header.segmentation.enabled && header.segmentation.update_map { | ||
| 269 | + mb.segment_id = | ||
| 270 | + hdr_dec.read_tree(&SEGMENT_TREE, &header.segmentation.tree_probs); | ||
| 271 | + } | ||
| 272 | + if header.coeff_skip_enabled { | ||
| 273 | + mb.skip = hdr_dec.read_bool(header.prob_skip_false); | ||
| 274 | + } | ||
| 275 | + self.decode_kf_modes(&mut hdr_dec, row, col, &mut mb); | ||
| 276 | + *self.mbi_mut(row, col) = mb; | ||
| 277 | + } | ||
| 278 | + | ||
| 279 | + // Phases 2+3 per MB: tokens then reconstruction. Token row | ||
| 280 | + // `r` (0-based) reads partition `r % n` like the reference. | ||
| 281 | + let part = (row - 1) % partitions.len(); | ||
| 282 | + for col in 1..=self.mb_cols { | ||
| 283 | + let mb = self.mbi(row, col).clone(); | ||
| 284 | + let has_y2 = mb.has_y2(); | ||
| 285 | + let seg_i = usize::from(header.segmentation.enabled) * usize::from(mb.segment_id); | ||
| 286 | + let dq = &dqf[seg_i]; | ||
| 287 | + let mb_dq = Dq { | ||
| 288 | + y1_dc: dq.y1_dc, | ||
| 289 | + y1_ac: dq.y1_ac, | ||
| 290 | + uv_dc: dq.uv_dc, | ||
| 291 | + uv_ac: dq.uv_ac, | ||
| 292 | + y2_dc: dq.y2_dc, | ||
| 293 | + y2_ac: dq.y2_ac, | ||
| 294 | + }; | ||
| 295 | + let probs = self.state.coeff_probs; | ||
| 296 | + let coeffs = if mb.skip { | ||
| 297 | + tokens::skip_mb_tokens(&mut self.token_ctxs, col - 1, has_y2) | ||
| 298 | + } else { | ||
| 299 | + tokens::decode_mb_tokens( | ||
| 300 | + &mut partitions[part], | ||
| 301 | + &probs, | ||
| 302 | + &mb_dq, | ||
| 303 | + has_y2, | ||
| 304 | + &mut self.token_ctxs, | ||
| 305 | + col - 1, | ||
| 306 | + ) | ||
| 307 | + }; | ||
| 308 | + self.mb_info[row * (self.mb_cols + 1) + col].has_nz = coeffs.has_nonzero(); | ||
| 309 | + self.reconstruct_intra_mb(row - 1, col - 1, &mb, &coeffs); | ||
| 310 | + } | ||
| 311 | + } | ||
| 312 | + | ||
| 313 | + // Loop filter post-pass (see module docs for the ordering | ||
| 314 | + // equivalence argument). | ||
| 315 | + if header.filter_level > 0 { | ||
| 316 | + let infos: Vec<MbFilterInfo> = (0..self.mb_rows) | ||
| 317 | + .flat_map(|r| (0..self.mb_cols).map(move |c| (r, c))) | ||
| 318 | + .map(|(r, c)| { | ||
| 319 | + let mb = self.mbi(r + 1, c + 1); | ||
| 320 | + MbFilterInfo { | ||
| 321 | + level: self.mb_filter_level(&header, mb), | ||
| 322 | + inner_edges: mb.has_nz || !mb.has_y2(), | ||
| 323 | + } | ||
| 324 | + }) | ||
| 325 | + .collect(); | ||
| 326 | + // The planes are bordered; the filter sees the unbordered | ||
| 327 | + // image (same row pitch) starting at pixel (0, 0). | ||
| 328 | + let (ystride, ustride, vstride) = (self.y.stride, self.u.stride, self.v.stride); | ||
| 329 | + let (mcols, mrows) = (self.mb_cols, self.mb_rows); | ||
| 330 | + let simple = header.filter_type == 1; | ||
| 331 | + let sharpness = header.sharpness_level; | ||
| 332 | + let yimg = &mut self.y.data[1 + ystride..]; | ||
| 333 | + let uimg = &mut self.u.data[1 + ustride..]; | ||
| 334 | + let vimg = &mut self.v.data[1 + vstride..]; | ||
| 335 | + loopfilter::filter_frame_ex( | ||
| 336 | + yimg, uimg, vimg, ystride, ustride, mcols, mrows, sharpness, simple, &infos, true, | ||
| 337 | + ); | ||
| 338 | + } | ||
| 339 | + | ||
| 340 | + self.frame_decoded = true; | ||
| 341 | + Ok(header.tag.show_frame.then(|| self.crop())) | ||
| 342 | + } | ||
| 343 | + | ||
| 344 | + /// Per-MB loop filter level (dixie `calculate_filter_parameters`): | ||
| 345 | + /// segment adjustment, then ref/mode deltas, clamped 0..63. Key | ||
| 346 | + /// frames are all intra — ref index 0 (`CURRENT_FRAME`), with | ||
| 347 | + /// `mode_delta[0]` applying to B_PRED. | ||
| 348 | + fn mb_filter_level(&self, header: &FrameHeader, mb: &MbInfo) -> u8 { | ||
| 349 | + let seg = &header.segmentation; | ||
| 350 | + let mut level = i32::from(header.filter_level); | ||
| 351 | + if seg.enabled { | ||
| 352 | + let d = seg.lf_level[usize::from(mb.segment_id)]; | ||
| 353 | + level = if seg.abs_delta { d } else { level + d }; | ||
| 354 | + } | ||
| 355 | + level = level.clamp(0, 63); | ||
| 356 | + if header.lf_delta_enabled { | ||
| 357 | + level += self.state.ref_lf_delta[0]; | ||
| 358 | + if mb.y_mode == modes::YMode::BPred.as_u8() { | ||
| 359 | + level += self.state.mode_lf_delta[0]; | ||
| 360 | + } | ||
| 361 | + level = level.clamp(0, 63); | ||
| 362 | + } | ||
| 363 | + level as u8 | ||
| 364 | + } | ||
| 365 | + | ||
| 366 | + /// Key-frame mode record (§11): Y mode at fixed probabilities, then | ||
| 367 | + /// 16 context-conditioned subblock modes for B_PRED, then chroma. | ||
| 368 | + fn decode_kf_modes( | ||
| 369 | + &mut self, | ||
| 370 | + d: &mut BoolDecoder<'_>, | ||
| 371 | + row: usize, | ||
| 372 | + col: usize, | ||
| 373 | + mb: &mut MbInfo, | ||
| 374 | + ) { | ||
| 375 | + let ymode = modes::read_kf_ymode(d); | ||
| 376 | + mb.y_mode = ymode.as_u8(); | ||
| 377 | + if ymode == modes::YMode::BPred { | ||
| 378 | + for j in 0..16u8 { | ||
| 379 | + let a = self.above_block_mode(row, col, j, mb); | ||
| 380 | + let l = self.left_block_mode(row, col, j, mb); | ||
| 381 | + mb.b_modes[usize::from(j)] = | ||
| 382 | + modes::read_bmode(d, &KF_BMODE_PROB[usize::from(a)][usize::from(l)]).as_u8(); | ||
| 383 | + } | ||
| 384 | + } | ||
| 385 | + mb.uv_mode = modes::read_uvmode(d, &modes::KF_UV_MODE_PROBS).as_u8(); | ||
| 386 | + } | ||
| 387 | + | ||
| 388 | + /// Above subblock mode context (dixie `above_block_mode`): subblocks | ||
| 389 | + /// 0-3 take the above MB's derived mode, inner subblocks the mode | ||
| 390 | + /// `j-4` of this same MB (already decoded into `mb`). | ||
| 391 | + fn above_block_mode(&self, row: usize, col: usize, j: u8, mb: &MbInfo) -> u8 { | ||
| 392 | + if j < 4 { | ||
| 393 | + let above = self.mbi(row - 1, col); | ||
| 394 | + if above.y_mode == modes::YMode::BPred.as_u8() { | ||
| 395 | + above.b_modes[usize::from(j) + 12] | ||
| 396 | + } else { | ||
| 397 | + ymode_as_bmode(above.y_mode) | ||
| 398 | + } | ||
| 399 | + } else { | ||
| 400 | + mb.b_modes[usize::from(j) - 4] | ||
| 401 | + } | ||
| 402 | + } | ||
| 403 | + | ||
| 404 | + /// Left subblock mode context (dixie `left_block_mode`). | ||
| 405 | + fn left_block_mode(&self, row: usize, col: usize, j: u8, mb: &MbInfo) -> u8 { | ||
| 406 | + if j % 4 == 0 { | ||
| 407 | + let left = self.mbi(row, col - 1); | ||
| 408 | + if left.y_mode == modes::YMode::BPred.as_u8() { | ||
| 409 | + left.b_modes[usize::from(j) + 3] | ||
| 410 | + } else { | ||
| 411 | + ymode_as_bmode(left.y_mode) | ||
| 412 | + } | ||
| 413 | + } else { | ||
| 414 | + mb.b_modes[usize::from(j) - 1] | ||
| 415 | + } | ||
| 416 | + } | ||
| 417 | + | ||
| 418 | + /// Predict and reconstruct one intra key-frame MB at pixel (x, y). | ||
| 419 | + /// | ||
| 420 | + /// Whole-MB modes predict once from the pre-MB edges and then fold | ||
| 421 | + /// the 24 residual blocks in; B_PRED interleaves: each 4x4 subblock | ||
| 422 | + /// predicts from the reconstructed image (which already carries the | ||
| 423 | + /// earlier subblocks' residuals, §12.3) and is written back before | ||
| 424 | + /// the next subblock is predicted. | ||
| 425 | + fn reconstruct_intra_mb(&mut self, row: usize, col: usize, mb: &MbInfo, coeffs: &MbCoeffs) { | ||
| 426 | + let x = col * 16; | ||
| 427 | + let y = row * 16; | ||
| 428 | + let y_mode = mb.y_mode; | ||
| 429 | + let uv_mode = mb.uv_mode; | ||
| 430 | + let b_modes = mb.b_modes; | ||
| 431 | + let have_above = row > 0; | ||
| 432 | + let have_left = col > 0; | ||
| 433 | + | ||
| 434 | + // The Y2 inverse WHT feeds the 16 Y subblock DCs (§14.2). | ||
| 435 | + let y_dcs: [i16; 16] = if coeffs.has_y2 { | ||
| 436 | + transform::iwht4x4(&coeffs.y2) | ||
| 437 | + } else { | ||
| 438 | + [0; 16] | ||
| 439 | + }; | ||
| 440 | + if std::env::var_os("EC_VP8_DEBUG").is_some() { | ||
| 441 | + eprintln!( | ||
| 442 | + "MB({row},{col}) ymode={} uv={} y2={:?} y2has={} y0[:4]={:?} eobs24={} dcs={:?}", | ||
| 443 | + y_mode, | ||
| 444 | + uv_mode, | ||
| 445 | + coeffs.y2, | ||
| 446 | + coeffs.has_y2, | ||
| 447 | + &coeffs.y[0][..4], | ||
| 448 | + coeffs.eobs[24], | ||
| 449 | + &y_dcs[..4] | ||
| 450 | + ); | ||
| 451 | + } | ||
| 452 | + | ||
| 453 | + if y_mode == modes::YMode::BPred.as_u8() { | ||
| 454 | + for b in 0..16usize { | ||
| 455 | + let bx = (b % 4) * 4; | ||
| 456 | + let by = (b / 4) * 4; | ||
| 457 | + // A row: 4 above pixels then 4 above-right (§12.3); the | ||
| 458 | + // above-right extras are shared by right-edge subblocks | ||
| 459 | + // 3, 7, 11 and 15. | ||
| 460 | + let mut a8 = [0u8; 8]; | ||
| 461 | + let arow = self.y.at_above(x + bx, y + by); | ||
| 462 | + a8[..4].copy_from_slice(&self.y.data[arow..arow + 4]); | ||
| 463 | + if bx + 4 == 16 { | ||
| 464 | + a8[4..].copy_from_slice(&self.above_right(x, y)); | ||
| 465 | + } else { | ||
| 466 | + let ar = self.y.at_above(x + bx + 4, y + by); | ||
| 467 | + a8[4..].copy_from_slice(&self.y.data[ar..ar + 4]); | ||
| 468 | + } | ||
| 469 | + let mut l4 = [0u8; 4]; | ||
| 470 | + for (i, cell) in l4.iter_mut().enumerate() { | ||
| 471 | + *cell = self.y.data[self.y.at_left(x + bx, y + by + i)]; | ||
| 472 | + } | ||
| 473 | + let p = self.y.data[self.y.at_above_left(x + bx, y + by)]; | ||
| 474 | + let mut block = [0u8; 16]; | ||
| 475 | + intra::predict4(b_modes[b], &a8, &l4, p, &mut block); | ||
| 476 | + for i in 0..4 { | ||
| 477 | + let d = self.y.at(x + bx, y + by + i); | ||
| 478 | + self.y.data[d..d + 4].copy_from_slice(&block[i * 4..i * 4 + 4]); | ||
| 479 | + } | ||
| 480 | + let mut c = coeffs.y[b]; | ||
| 481 | + if coeffs.has_y2 { | ||
| 482 | + c[0] = y_dcs[b]; | ||
| 483 | + } | ||
| 484 | + if c.iter().any(|&v| v != 0) { | ||
| 485 | + let dst = self.y.at(x + bx, y + by); | ||
| 486 | + let stride = self.y.stride; | ||
| 487 | + idct_add_into(&mut self.y.data, &c, &block, 4, 0, dst, stride); | ||
| 488 | + } | ||
| 489 | + } | ||
| 490 | + } else { | ||
| 491 | + // Gather luma edges (border cells carry the 127/129 fills). | ||
| 492 | + let (above, left, above_left) = { | ||
| 493 | + let ay = self.y.at_above(x, y); | ||
| 494 | + let mut a = [0u8; 16]; | ||
| 495 | + let mut l = [0u8; 16]; | ||
| 496 | + a.copy_from_slice(&self.y.data[ay..ay + 16]); | ||
| 497 | + for (i, cell) in l.iter_mut().enumerate() { | ||
| 498 | + *cell = self.y.data[self.y.at_left(x, y + i)]; | ||
| 499 | + } | ||
| 500 | + let al = self.y.data[self.y.at_above_left(x, y)]; | ||
| 501 | + (a, l, al) | ||
| 502 | + }; | ||
| 503 | + let mut pred = [0u8; 256]; | ||
| 504 | + intra::predict16( | ||
| 505 | + y_mode, have_above, have_left, &above, &left, above_left, &mut pred, | ||
| 506 | + ); | ||
| 507 | + for b in 0..16usize { | ||
| 508 | + let bx = (b % 4) * 4; | ||
| 509 | + let by = (b / 4) * 4; | ||
| 510 | + let mut c = coeffs.y[b]; | ||
| 511 | + if coeffs.has_y2 { | ||
| 512 | + c[0] = y_dcs[b]; | ||
| 513 | + } | ||
| 514 | + if c.iter().all(|&v| v == 0) { | ||
| 515 | + for i in 0..4 { | ||
| 516 | + let d = self.y.at(x + bx, y + by + i); | ||
| 517 | + let s = (by + i) * 16 + bx; | ||
| 518 | + self.y.data[d..d + 4].copy_from_slice(&pred[s..s + 4]); | ||
| 519 | + } | ||
| 520 | + } else { | ||
| 521 | + let dst = self.y.at(x + bx, y + by); | ||
| 522 | + let stride = self.y.stride; | ||
| 523 | + idct_add_into(&mut self.y.data, &c, &pred, 16, by * 16 + bx, dst, stride); | ||
| 524 | + } | ||
| 525 | + } | ||
| 526 | + } | ||
| 527 | + | ||
| 528 | + // Chroma: 8x8 prediction then four residual blocks per plane. | ||
| 529 | + let (above_u, left_u, al_u) = self.chroma_edges(col, row, 0); | ||
| 530 | + let (above_v, left_v, al_v) = self.chroma_edges(col, row, 1); | ||
| 531 | + let mut pred_u = [0u8; 64]; | ||
| 532 | + let mut pred_v = [0u8; 64]; | ||
| 533 | + intra::predict8( | ||
| 534 | + uv_mode, | ||
| 535 | + have_above, | ||
| 536 | + have_left, | ||
| 537 | + &above_u, | ||
| 538 | + &left_u, | ||
| 539 | + al_u, | ||
| 540 | + &mut pred_u, | ||
| 541 | + ); | ||
| 542 | + intra::predict8( | ||
| 543 | + uv_mode, | ||
| 544 | + have_above, | ||
| 545 | + have_left, | ||
| 546 | + &above_v, | ||
| 547 | + &left_v, | ||
| 548 | + al_v, | ||
| 549 | + &mut pred_v, | ||
| 550 | + ); | ||
| 551 | + let (cx, cy) = (x / 2, y / 2); | ||
| 552 | + for (plane_data, coeffs_uv, pred8, stride) in [ | ||
| 553 | + (&mut self.u.data, &coeffs.u, &pred_u, self.u.stride), | ||
| 554 | + (&mut self.v.data, &coeffs.v, &pred_v, self.v.stride), | ||
| 555 | + ] { | ||
| 556 | + for b in 0..4usize { | ||
| 557 | + let bx = (b % 2) * 4; | ||
| 558 | + let by = (b / 2) * 4; | ||
| 559 | + let c = coeffs_uv[b]; | ||
| 560 | + let dst = (1 + cy + by) * stride + 1 + cx + bx; | ||
| 561 | + if c.iter().all(|&v| v == 0) { | ||
| 562 | + for i in 0..4 { | ||
| 563 | + let s = (by + i) * 8 + bx; | ||
| 564 | + let d = dst + i * stride; | ||
| 565 | + plane_data[d..d + 4].copy_from_slice(&pred8[s..s + 4]); | ||
| 566 | + } | ||
| 567 | + } else { | ||
| 568 | + idct_add_into(plane_data, &c, pred8, 8, by * 8 + bx, dst, stride); | ||
| 569 | + } | ||
| 570 | + } | ||
| 571 | + } | ||
| 572 | + } | ||
| 573 | + | ||
| 574 | + /// Above-right extras (§12.3): real pixels from the above row, | ||
| 575 | + /// replicated last pixel on the rightmost MB, 127 on the top row. | ||
| 576 | + fn above_right(&self, x: usize, y: usize) -> [u8; 4] { | ||
| 577 | + if y == 0 { | ||
| 578 | + [127; 4] | ||
| 579 | + } else if x + 16 >= self.mb_cols * 16 { | ||
| 580 | + [self.y.data[self.y.at_above(x + 15, y)]; 4] | ||
| 581 | + } else { | ||
| 582 | + let off = self.y.at_above(x + 16, y); | ||
| 583 | + [ | ||
| 584 | + self.y.data[off], | ||
| 585 | + self.y.data[off + 1], | ||
| 586 | + self.y.data[off + 2], | ||
| 587 | + self.y.data[off + 3], | ||
| 588 | + ] | ||
| 589 | + } | ||
| 590 | + } | ||
| 591 | + | ||
| 592 | + fn chroma_edges(&self, col: usize, row: usize, plane: usize) -> ([u8; 8], [u8; 8], u8) { | ||
| 593 | + let p = if plane == 0 { &self.u } else { &self.v }; | ||
| 594 | + let x = col * 8; | ||
| 595 | + let y = row * 8; | ||
| 596 | + let mut a = [0u8; 8]; | ||
| 597 | + let mut l = [0u8; 8]; | ||
| 598 | + let aoff = p.at_above(x, y); | ||
| 599 | + a.copy_from_slice(&p.data[aoff..aoff + 8]); | ||
| 600 | + for (i, cell) in l.iter_mut().enumerate() { | ||
| 601 | + *cell = p.data[p.at_left(x, y + i)]; | ||
| 602 | + } | ||
| 603 | + let al = p.data[p.at_above_left(x, y)]; | ||
| 604 | + (a, l, al) | ||
| 605 | + } | ||
| 606 | + | ||
| 607 | + /// Crop the padded planes to the real frame size. | ||
| 608 | + fn crop(&self) -> Picture { | ||
| 609 | + let w = usize::from(self.dims.width); | ||
| 610 | + let h = usize::from(self.dims.height); | ||
| 611 | + let mut y = Vec::with_capacity(w * h); | ||
| 612 | + for row in 0..h { | ||
| 613 | + let off = self.y.at(0, row); | ||
| 614 | + y.extend_from_slice(&self.y.data[off..off + w]); | ||
| 615 | + } | ||
| 616 | + let (cw, ch) = ((w + 1) / 2, (h + 1) / 2); | ||
| 617 | + let mut u = Vec::with_capacity(cw * ch); | ||
| 618 | + let mut v = Vec::with_capacity(cw * ch); | ||
| 619 | + for row in 0..ch { | ||
| 620 | + let off = self.u.at(0, row); | ||
| 621 | + u.extend_from_slice(&self.u.data[off..off + cw]); | ||
| 622 | + let off = self.v.at(0, row); | ||
| 623 | + v.extend_from_slice(&self.v.data[off..off + cw]); | ||
| 624 | + } | ||
| 625 | + Picture { | ||
| 626 | + y, | ||
| 627 | + u, | ||
| 628 | + v, | ||
| 629 | + width: self.dims.width, | ||
| 630 | + height: self.dims.height, | ||
| 631 | + stride: w, | ||
| 632 | + uv_stride: cw, | ||
| 633 | + } | ||
| 634 | + } | ||
| 635 | +} | ||
| 636 | + | ||
| 637 | +impl Default for Decoder { | ||
| 638 | + fn default() -> Self { | ||
| 639 | + Self::new() | ||
| 640 | + } | ||
| 641 | +} | ||
| 642 | + | ||
| 643 | +/// Segment-map coding tree (RFC 6386 §10): plain two-level split of 0-3. | ||
| 644 | +const SEGMENT_TREE: [i8; 6] = [2, 4, 0, -1, -2, -3]; | ||
| 645 | + | ||
| 646 | +fn ymode_as_bmode(y: u8) -> u8 { | ||
| 647 | + match y { | ||
| 648 | + 0 => 0, // DC_PRED -> B_DC_PRED | ||
| 649 | + 1 => 2, // V_PRED -> B_VE_PRED | ||
| 650 | + 2 => 3, // H_PRED -> B_HE_PRED | ||
| 651 | + 3 => 1, // TM_PRED -> B_TM_PRED | ||
| 652 | + _ => unreachable!("non-B_PRED luma mode {y}"), | ||
| 653 | + } | ||
| 654 | +} | ||
| 655 | + | ||
| 656 | +/// Add one 4x4 block's dequantized-coefficient residual to its | ||
| 657 | +/// prediction: reads the prediction patch from `pred`, clamps, writes | ||
| 658 | +/// into the strided plane (§14.4/§14.5). | ||
| 659 | +fn idct_add_into( | ||
| 660 | + plane: &mut [u8], | ||
| 661 | + coeffs: &[i16; 16], | ||
| 662 | + pred: &[u8], | ||
| 663 | + pred_stride: usize, | ||
| 664 | + pred_off: usize, | ||
| 665 | + dst_off: usize, | ||
| 666 | + dst_stride: usize, | ||
| 667 | +) { | ||
| 668 | + let mut p = [0u8; 16]; | ||
| 669 | + for i in 0..4 { | ||
| 670 | + let s = pred_off + i * pred_stride; | ||
| 671 | + p[i * 4..i * 4 + 4].copy_from_slice(&pred[s..s + 4]); | ||
| 672 | + } | ||
| 673 | + let mut out = [0u8; 16]; | ||
| 674 | + transform::idct4x4_add(coeffs, &p, &mut out); | ||
| 675 | + for i in 0..4 { | ||
| 676 | + let d = dst_off + i * dst_stride; | ||
| 677 | + plane[d..d + 4].copy_from_slice(&out[i * 4..i * 4 + 4]); | ||
| 678 | + } | ||
| 679 | +} | ||
crates/ec-vp8/src/header.rsmodified+9 -4
| @@ -49,8 +49,10 @@ impl Default for PersistedState { | |||
| 49 | Self { | 49 | Self { |
| 50 | coeff_probs: DEFAULT_COEFF_PROBS, | 50 | coeff_probs: DEFAULT_COEFF_PROBS, |
| 51 | mv_probs: DEFAULT_MV_PROBS, | 51 | mv_probs: DEFAULT_MV_PROBS, |
| 52 | - ymode_probs: [145, 156, 163, 128], | 52 | + // Interframe tree defaults (libvpx vp8_ymode_prob / |
| 53 | - uv_mode_probs: [142, 114, 183], | 53 | + // vp8_uv_mode_prob); key frames reset these too. |
| 54 | + ymode_probs: [112, 86, 140, 37], | ||
| 55 | + uv_mode_probs: [162, 101, 204], | ||
| 54 | segmentation: SegmentationState::default(), | 56 | segmentation: SegmentationState::default(), |
| 55 | ref_lf_delta: [0; 4], | 57 | ref_lf_delta: [0; 4], |
| 56 | mode_lf_delta: [0; 4], | 58 | mode_lf_delta: [0; 4], |
| @@ -412,7 +414,7 @@ impl FrameHeader { | |||
| 412 | } | 414 | } |
| 413 | probs | 415 | probs |
| 414 | } else { | 416 | } else { |
| 415 | - (145, 156, 163) | 417 | + (112, 86, 140) // placeholders; only read on inter frames |
| 416 | }; | 418 | }; |
| 417 | for c in 0..2 { | 419 | for c in 0..2 { |
| 418 | for j in 0..MV_PROB_CNT { | 420 | for j in 0..MV_PROB_CNT { |
| @@ -422,7 +424,10 @@ impl FrameHeader { | |||
| 422 | } | 424 | } |
| 423 | } | 425 | } |
| 424 | 426 | ||
| 425 | - if d.overreads() > 0 { | 427 | + // The reference decoder zero-fills past the end of a partition; |
| 428 | + // tiny partitions (e.g. one-MB key frames) can legitimately | ||
| 429 | + // overrun by a byte or two. Gross overruns are still desyncs. | ||
| 430 | + if d.overreads() > 16 { | ||
| 426 | return Err(Error::corrupt(format!( | 431 | return Err(Error::corrupt(format!( |
| 427 | "VP8 first partition over-read by {} bytes (header desync)", | 432 | "VP8 first partition over-read by {} bytes (header desync)", |
| 428 | d.overreads() | 433 | d.overreads() |
crates/ec-vp8/src/intra.rsadded+711 -0
| @@ -0,0 +1,711 @@ | |||
| 1 | +//! Intra-frame prediction for VP8 (RFC 6386, Section 12). | ||
| 2 | +//! | ||
| 3 | +//! This module implements the spatial predictors a VP8 decoder applies to | ||
| 4 | +//! intra-coded macroblocks: the 16x16 luma predictors and 8x8 (per-plane) | ||
| 5 | +//! chroma predictors of Section 12.2/12.3, and the ten 4x4 subblock | ||
| 6 | +//! predictors of Section 12.3. All functions are dependency-free, `unsafe`-free, | ||
| 7 | +//! allocate nothing, and are bit-exact against the normative integer math of | ||
| 8 | +//! the RFC code listings (which are in turn identical to the libvpx oracle in | ||
| 9 | +//! `vp8/common/reconintra.c`, `vp8/common/reconintra4x4.c` and | ||
| 10 | +//! `vpx_dsp/intrapred.c`). | ||
| 11 | +//! | ||
| 12 | +//! # Edge-pixel conventions (RFC 6386 Section 12, p.50) | ||
| 13 | +//! | ||
| 14 | +//! Pixels outside the visible frame are pre-filled by the caller: 127 for the | ||
| 15 | +//! row above the top row (including the above-left pixel `P`), 129 for the | ||
| 16 | +//! column left of the leftmost column. V_PRED/H_PRED/TM_PRED consume those | ||
| 17 | +//! fill values directly; DC_PRED instead decides from the availability flags | ||
| 18 | +//! which genuinely-visible pixels to average (RFC Section 12.2, "Note that | ||
| 19 | +//! the averages used in these exceptional cases are not the same as those | ||
| 20 | +//! that would be arrived at by using the out-of-bounds A and L values"). | ||
| 21 | +//! | ||
| 22 | +//! # 4x4 above-right synthesis | ||
| 23 | +//! | ||
| 24 | +//! The 4x4 predictors use an 8-pixel above row `A[0..8]`: the 4 pixels | ||
| 25 | +//! immediately above the subblock plus the 4 "above-right" pixels | ||
| 26 | +//! (frame positions (-1,16)..(-1,19) relative to the macroblock; RFC | ||
| 27 | +//! Section 12.3, subblocks 3/7/11/15). Producing those extra four pixels is | ||
| 28 | +//! the caller's job: for a macroblock not on the top frame row they come from | ||
| 29 | +//! the row above (replicating pixel (-1,15) at the rightmost macroblock of a | ||
| 30 | +//! row); on the top frame row they are 127. [`predict4`] only consumes | ||
| 31 | +//! `A[0..8]` as given. | ||
| 32 | + | ||
| 33 | +#![deny(unsafe_code)] | ||
| 34 | + | ||
| 35 | +/// Weighted average of three adjacent pixels centered at `y` | ||
| 36 | +/// (RFC 6386 Section 12.3 `avg3`: `(x + 2y + z + 2) >> 2`; libvpx `AVG3`). | ||
| 37 | +/// | ||
| 38 | +/// Arguments are valid pixel values, so the result always fits in `u8` and no | ||
| 39 | +/// clamp is needed (RFC Section 12.3, comment above `avg3`). | ||
| 40 | +#[inline] | ||
| 41 | +fn avg3(x: u8, y: u8, z: u8) -> u8 { | ||
| 42 | + ((u32::from(x) + 2 * u32::from(y) + u32::from(z) + 2) >> 2) as u8 | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +/// Simple average of two pixels (RFC 6386 Section 12.3 `avg2`: | ||
| 46 | +/// `(x + y + 1) >> 1`; libvpx `AVG2`). | ||
| 47 | +#[inline] | ||
| 48 | +fn avg2(x: u8, y: u8) -> u8 { | ||
| 49 | + ((u32::from(x) + u32::from(y) + 1) >> 1) as u8 | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// `clamp255(v)`: clamp an integer pixel difference into the valid `u8` range | ||
| 53 | +/// (RFC 6386 Section 12.2 `TMpred` / Section 12.3 `B_TM_PRED`). | ||
| 54 | +#[inline] | ||
| 55 | +fn clamp255(v: i32) -> u8 { | ||
| 56 | + v.clamp(0, 255) as u8 | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// Shared DC/V/H/TM core for the 16x16 luma and 8x8 chroma blocks | ||
| 60 | +/// (RFC 6386 Section 12.2 semantics; Section 12.3 states 16x16 luma is | ||
| 61 | +/// "essentially identical" with 16-pixel edges). | ||
| 62 | +/// | ||
| 63 | +/// DC rounding follows the RFC formula `DCvalue = (sum + (1 << (shf-1))) >> shf` | ||
| 64 | +/// with `shf` = log2 of the number of averaged pixels: 32/16 pixels for the | ||
| 65 | +/// 16x16 both/single-edge cases, 16/8 for 8x8. | ||
| 66 | +fn predict_block<const N: usize>( | ||
| 67 | + mode: u8, | ||
| 68 | + have_above: bool, | ||
| 69 | + have_left: bool, | ||
| 70 | + above: &[u8; N], | ||
| 71 | + left: &[u8; N], | ||
| 72 | + above_left: u8, | ||
| 73 | + out: &mut [u8], | ||
| 74 | +) { | ||
| 75 | + match mode { | ||
| 76 | + // DC_PRED: fill the block with the average of the genuinely visible | ||
| 77 | + // edge pixels; availability flags alone decide which edges count | ||
| 78 | + // (RFC Section 12.2). Neither edge: constant 128. | ||
| 79 | + 0 => { | ||
| 80 | + let sum_above: u32 = above.iter().map(|&p| u32::from(p)).sum(); | ||
| 81 | + let sum_left: u32 = left.iter().map(|&p| u32::from(p)).sum(); | ||
| 82 | + let tz = N.trailing_zeros(); // log2(N) | ||
| 83 | + let v: u32 = match (have_above, have_left) { | ||
| 84 | + (true, true) => (sum_above + sum_left + N as u32) >> (tz + 1), | ||
| 85 | + (false, false) => 128, | ||
| 86 | + // Above available only: average the above row. | ||
| 87 | + (true, false) => (sum_above + (N as u32 >> 1)) >> tz, | ||
| 88 | + // Left column available only: average the left column. | ||
| 89 | + (false, true) => (sum_left + (N as u32 >> 1)) >> tz, | ||
| 90 | + }; | ||
| 91 | + out.fill(v as u8); | ||
| 92 | + } | ||
| 93 | + // V_PRED: every row is a copy of the above row A (RFC Section 12.2). | ||
| 94 | + 1 => { | ||
| 95 | + for row in out.chunks_exact_mut(N) { | ||
| 96 | + row.copy_from_slice(above); | ||
| 97 | + } | ||
| 98 | + } | ||
| 99 | + // H_PRED: every column is a copy of the left column L (RFC Section 12.2). | ||
| 100 | + 2 => { | ||
| 101 | + for (row, &l) in out.chunks_exact_mut(N).zip(left.iter()) { | ||
| 102 | + row.fill(l); | ||
| 103 | + } | ||
| 104 | + } | ||
| 105 | + // TM_PRED: X_ij = clamp255(L_i + A_j - P) (RFC Section 12.2 `TMpred`). | ||
| 106 | + // Unlike DC_PRED this mode does use the 127/129 out-of-bounds fills. | ||
| 107 | + 3 => { | ||
| 108 | + for (row, &l) in out.chunks_exact_mut(N).zip(left.iter()) { | ||
| 109 | + for (o, &a) in row.iter_mut().zip(above.iter()) { | ||
| 110 | + *o = clamp255(i32::from(l) + i32::from(a) - i32::from(above_left)); | ||
| 111 | + } | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | + _ => panic!("predict_block: invalid intra mode {mode} (expected 0..=3)"), | ||
| 115 | + } | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +/// 16x16 luma prediction (RFC 6386 Section 12.3; predictor math per | ||
| 119 | +/// Section 12.2). | ||
| 120 | +/// | ||
| 121 | +/// `mode` is a u8 in `{0=DC, 1=V, 2=H, 3=TM}`. `above` holds the 16 | ||
| 122 | +/// reconstructed pixels of the row above the macroblock, `left` the 16 pixels | ||
| 123 | +/// of the column to its left (adjacent entries separated by one frame row), | ||
| 124 | +/// `above_left` is the corner pixel `P`. `have_above`/`have_left` state | ||
| 125 | +/// whether those edges are genuinely in-frame. | ||
| 126 | +/// | ||
| 127 | +/// For DC the flags alone decide what is averaged (the out-of-bounds fills | ||
| 128 | +/// are NOT used); V/H/TM consume the caller-prepared out-of-bounds fills | ||
| 129 | +/// (127 above/`above_left` on the top frame row, 129 on the left frame | ||
| 130 | +/// column) written into `above`/`left`/`above_left`. | ||
| 131 | +/// | ||
| 132 | +/// `out` receives 256 row-major prediction pixels. | ||
| 133 | +pub fn predict16( | ||
| 134 | + mode: u8, | ||
| 135 | + have_above: bool, | ||
| 136 | + have_left: bool, | ||
| 137 | + above: &[u8; 16], | ||
| 138 | + left: &[u8; 16], | ||
| 139 | + above_left: u8, | ||
| 140 | + out: &mut [u8; 256], | ||
| 141 | +) { | ||
| 142 | + predict_block::<16>(mode, have_above, have_left, above, left, above_left, out); | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +/// 8x8 chroma prediction for one plane (RFC 6386 Section 12.2). | ||
| 146 | +/// | ||
| 147 | +/// Identical semantics to [`predict16`] with 8-pixel edges; call it once for | ||
| 148 | +/// U and once for V. `mode` is a u8 in `{0=DC, 1=V, 2=H, 3=TM}`. DC averages | ||
| 149 | +/// 16 pixels (both edges: `(sumA + sumL + 8) >> 4`) or 8 pixels (one edge: | ||
| 150 | +/// `(sum + 4) >> 3`), or fills 128. | ||
| 151 | +/// | ||
| 152 | +/// `out` receives 64 row-major prediction pixels. | ||
| 153 | +pub fn predict8( | ||
| 154 | + mode: u8, | ||
| 155 | + have_above: bool, | ||
| 156 | + have_left: bool, | ||
| 157 | + above: &[u8; 8], | ||
| 158 | + left: &[u8; 8], | ||
| 159 | + above_left: u8, | ||
| 160 | + out: &mut [u8; 64], | ||
| 161 | +) { | ||
| 162 | + predict_block::<8>(mode, have_above, have_left, above, left, above_left, out); | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +/// 4x4 subblock prediction (RFC 6386 Section 12.3 `subblock_intra_predict`). | ||
| 166 | +/// | ||
| 167 | +/// `mode` is a BMode integer: `0=B_DC 1=B_TM 2=B_VE 3=B_HE 4=B_LD 5=B_RD | ||
| 168 | +/// 6=B_VR 7=B_VL 8=B_HD 9=B_HU`. `above` is the 8-pixel row `A[0..8]` | ||
| 169 | +/// (4 above + 4 above-right; see the [module docs](self) for the caller-side | ||
| 170 | +/// synthesis rule), `left` is `L[0..4]`, `above_left` is `P = A[-1] = L[-1]`. | ||
| 171 | +/// | ||
| 172 | +/// Both edges are always considered present for subblocks: the caller | ||
| 173 | +/// pre-fills out-of-bounds pixels (127 above including P, 129 left) before | ||
| 174 | +/// the call, which is why no availability flags exist here. | ||
| 175 | +/// | ||
| 176 | +/// `out` receives 16 row-major prediction pixels. | ||
| 177 | +/// | ||
| 178 | +/// # RFC typo | ||
| 179 | +/// | ||
| 180 | +/// The RFC listing for `B_HD_PRED` contains the line | ||
| 181 | +/// `B[2][0] = B[3][2] = svg2p(E + 1)`; `svg2p` is a typo for `avg2p` (there | ||
| 182 | +/// is no `svg2p` definition; libvpx's `d153_predictor` computes `AVG2(K, J)` | ||
| 183 | +/// there, confirming the correction implemented here). | ||
| 184 | +pub fn predict4(mode: u8, above: &[u8; 8], left: &[u8; 4], above_left: u8, out: &mut [u8; 16]) { | ||
| 185 | + // The 9 already-constructed edge pixels in RFC scan order: | ||
| 186 | + // E[0..4] = L[3], L[2], L[1], L[0]; E[4] = P; E[5..9] = A[0..4]. | ||
| 187 | + let e: [u8; 9] = [ | ||
| 188 | + left[3], left[2], left[1], left[0], above_left, above[0], above[1], above[2], above[3], | ||
| 189 | + ]; | ||
| 190 | + // Row-major B[r][c] = b[r * 4 + c]. | ||
| 191 | + let mut b = [0u8; 16]; | ||
| 192 | + // avg3p(E + k) = avg3(E[k-1], E[k], E[k+1]); avg2p(E + k) = avg2(E[k], E[k+1]). | ||
| 193 | + match mode { | ||
| 194 | + // B_DC_PRED: DC value = (sum(A[0..4]) + sum(L[0..4]) + 4) >> 3. | ||
| 195 | + 0 => { | ||
| 196 | + let mut v: u32 = 4; | ||
| 197 | + for i in 0..4 { | ||
| 198 | + v += u32::from(above[i]) + u32::from(left[i]); | ||
| 199 | + } | ||
| 200 | + v >>= 3; | ||
| 201 | + b.fill(v as u8); | ||
| 202 | + } | ||
| 203 | + // B_TM_PRED: just like 16x16 TM_PRED (RFC Section 12.3). | ||
| 204 | + 1 => { | ||
| 205 | + for r in 0..4 { | ||
| 206 | + for c in 0..4 { | ||
| 207 | + b[r * 4 + c] = | ||
| 208 | + clamp255(i32::from(left[r]) + i32::from(above[c]) - i32::from(above_left)); | ||
| 209 | + } | ||
| 210 | + } | ||
| 211 | + } | ||
| 212 | + // B_VE_PRED: all four rows = smoothed top row avg3p(A + c), where | ||
| 213 | + // A[-1] = P participates in column 0 (libvpx `vpx_ve_predictor_4x4`). | ||
| 214 | + 2 => { | ||
| 215 | + for c in 0..4usize { | ||
| 216 | + let v = if c == 0 { | ||
| 217 | + avg3(above_left, above[0], above[1]) | ||
| 218 | + } else { | ||
| 219 | + avg3(above[c - 1], above[c], above[c + 1]) | ||
| 220 | + }; | ||
| 221 | + b[c] = v; | ||
| 222 | + b[4 + c] = v; | ||
| 223 | + b[8 + c] = v; | ||
| 224 | + b[12 + c] = v; | ||
| 225 | + } | ||
| 226 | + } | ||
| 227 | + // B_HE_PRED: columns = smoothed left column; bottom row exceptional | ||
| 228 | + // because L[4] does not exist: avg3(L[2], L[3], L[3]). | ||
| 229 | + 3 => { | ||
| 230 | + let rows = [ | ||
| 231 | + avg3(above_left, left[0], left[1]), | ||
| 232 | + avg3(left[0], left[1], left[2]), | ||
| 233 | + avg3(left[1], left[2], left[3]), | ||
| 234 | + avg3(left[2], left[3], left[3]), | ||
| 235 | + ]; | ||
| 236 | + for (r, &v) in rows.iter().enumerate() { | ||
| 237 | + b[r * 4..r * 4 + 4].fill(v); | ||
| 238 | + } | ||
| 239 | + } | ||
| 240 | + // B_LD_PRED: southwest (left and down) 45-degree diagonals off the | ||
| 241 | + // above row; B[3][3] uses avg3(A[6], A[7], A[7]) because A[8] does | ||
| 242 | + // not exist (libvpx `d45e_predictor_4x4`). | ||
| 243 | + 4 => { | ||
| 244 | + b[0] = avg3(above[0], above[1], above[2]); | ||
| 245 | + b[1] = avg3(above[1], above[2], above[3]); | ||
| 246 | + b[4] = b[1]; | ||
| 247 | + b[2] = avg3(above[2], above[3], above[4]); | ||
| 248 | + b[5] = b[2]; | ||
| 249 | + b[8] = b[2]; | ||
| 250 | + b[3] = avg3(above[3], above[4], above[5]); | ||
| 251 | + b[6] = b[3]; | ||
| 252 | + b[9] = b[3]; | ||
| 253 | + b[12] = b[3]; | ||
| 254 | + b[7] = avg3(above[4], above[5], above[6]); | ||
| 255 | + b[10] = b[7]; | ||
| 256 | + b[13] = b[7]; | ||
| 257 | + b[11] = avg3(above[5], above[6], above[7]); | ||
| 258 | + b[14] = b[11]; | ||
| 259 | + b[15] = avg3(above[6], above[7], above[7]); | ||
| 260 | + } | ||
| 261 | + // B_RD_PRED: southeast 45-degree diagonals off the whole E edge | ||
| 262 | + // (libvpx `d135_predictor_4x4`). | ||
| 263 | + 5 => { | ||
| 264 | + b[12] = avg3(e[0], e[1], e[2]); | ||
| 265 | + b[13] = avg3(e[1], e[2], e[3]); | ||
| 266 | + b[8] = b[13]; | ||
| 267 | + b[14] = avg3(e[2], e[3], e[4]); | ||
| 268 | + b[9] = b[14]; | ||
| 269 | + b[4] = b[14]; | ||
| 270 | + b[15] = avg3(e[3], e[4], e[5]); | ||
| 271 | + b[10] = b[15]; | ||
| 272 | + b[5] = b[15]; | ||
| 273 | + b[0] = b[15]; | ||
| 274 | + b[11] = avg3(e[4], e[5], e[6]); | ||
| 275 | + b[6] = b[11]; | ||
| 276 | + b[1] = b[11]; | ||
| 277 | + b[7] = avg3(e[5], e[6], e[7]); | ||
| 278 | + b[2] = b[7]; | ||
| 279 | + b[3] = avg3(e[6], e[7], e[8]); | ||
| 280 | + } | ||
| 281 | + // B_VR_PRED: vertical-right diagonals mixing avg3/avg2 along E | ||
| 282 | + // (libvpx `d117_predictor_4x4`). | ||
| 283 | + 6 => { | ||
| 284 | + b[12] = avg3(e[1], e[2], e[3]); | ||
| 285 | + b[8] = avg3(e[2], e[3], e[4]); | ||
| 286 | + b[13] = avg3(e[3], e[4], e[5]); | ||
| 287 | + b[4] = b[13]; | ||
| 288 | + b[9] = avg2(e[4], e[5]); | ||
| 289 | + b[0] = b[9]; | ||
| 290 | + b[14] = avg3(e[4], e[5], e[6]); | ||
| 291 | + b[5] = b[14]; | ||
| 292 | + b[10] = avg2(e[5], e[6]); | ||
| 293 | + b[1] = b[10]; | ||
| 294 | + b[15] = avg3(e[5], e[6], e[7]); | ||
| 295 | + b[6] = b[15]; | ||
| 296 | + b[11] = avg2(e[6], e[7]); | ||
| 297 | + b[2] = b[11]; | ||
| 298 | + b[7] = avg3(e[6], e[7], e[8]); | ||
| 299 | + b[3] = avg2(e[7], e[8]); | ||
| 300 | + } | ||
| 301 | + // B_VL_PRED: vertical-left diagonals off the above row; the last two | ||
| 302 | + // values do not strictly follow the pattern (RFC Section 12.3; | ||
| 303 | + // libvpx `d63e_predictor_4x4`). | ||
| 304 | + 7 => { | ||
| 305 | + b[0] = avg2(above[0], above[1]); | ||
| 306 | + b[4] = avg3(above[0], above[1], above[2]); | ||
| 307 | + b[8] = avg2(above[1], above[2]); | ||
| 308 | + b[1] = b[8]; | ||
| 309 | + b[5] = avg3(above[1], above[2], above[3]); | ||
| 310 | + b[12] = b[5]; | ||
| 311 | + b[9] = avg2(above[2], above[3]); | ||
| 312 | + b[2] = b[9]; | ||
| 313 | + b[13] = avg3(above[2], above[3], above[4]); | ||
| 314 | + b[6] = b[13]; | ||
| 315 | + b[10] = avg2(above[3], above[4]); | ||
| 316 | + b[3] = b[10]; | ||
| 317 | + b[14] = avg3(above[3], above[4], above[5]); | ||
| 318 | + b[7] = b[14]; | ||
| 319 | + b[11] = avg3(above[4], above[5], above[6]); | ||
| 320 | + b[15] = avg3(above[5], above[6], above[7]); | ||
| 321 | + } | ||
| 322 | + // B_HD_PRED: horizontal-down diagonals; the RFC's `svg2p(E + 1)` is | ||
| 323 | + // the avg2p correction noted in this function's docs (libvpx | ||
| 324 | + // `d153_predictor_4x4`). | ||
| 325 | + 8 => { | ||
| 326 | + b[12] = avg2(e[0], e[1]); | ||
| 327 | + b[13] = avg3(e[0], e[1], e[2]); | ||
| 328 | + b[8] = avg2(e[1], e[2]); // corrected svg2p -> avg2p line | ||
| 329 | + b[14] = b[8]; | ||
| 330 | + b[9] = avg3(e[1], e[2], e[3]); | ||
| 331 | + b[15] = b[9]; | ||
| 332 | + b[10] = avg2(e[2], e[3]); | ||
| 333 | + b[4] = b[10]; | ||
| 334 | + b[11] = avg3(e[2], e[3], e[4]); | ||
| 335 | + b[5] = b[11]; | ||
| 336 | + b[6] = avg2(e[3], e[4]); | ||
| 337 | + b[0] = b[6]; | ||
| 338 | + b[7] = avg3(e[3], e[4], e[5]); | ||
| 339 | + b[1] = b[7]; | ||
| 340 | + b[2] = avg3(e[4], e[5], e[6]); | ||
| 341 | + b[3] = avg3(e[5], e[6], e[7]); | ||
| 342 | + } | ||
| 343 | + // B_HU_PRED: horizontal-up diagonals off the left column; the bottom | ||
| 344 | + // rows cannot follow the pattern and collapse to L[3] (RFC | ||
| 345 | + // Section 12.3; libvpx `d207_predictor_4x4`). | ||
| 346 | + 9 => { | ||
| 347 | + b[0] = avg2(left[0], left[1]); | ||
| 348 | + b[1] = avg3(left[0], left[1], left[2]); | ||
| 349 | + b[2] = avg2(left[1], left[2]); | ||
| 350 | + b[4] = b[2]; | ||
| 351 | + b[3] = avg3(left[1], left[2], left[3]); | ||
| 352 | + b[5] = b[3]; | ||
| 353 | + b[6] = avg2(left[2], left[3]); | ||
| 354 | + b[8] = b[6]; | ||
| 355 | + b[7] = avg3(left[2], left[3], left[3]); | ||
| 356 | + b[9] = b[7]; | ||
| 357 | + let v = left[3]; | ||
| 358 | + b[10] = v; | ||
| 359 | + b[11] = v; | ||
| 360 | + b[12] = v; | ||
| 361 | + b[13] = v; | ||
| 362 | + b[14] = v; | ||
| 363 | + b[15] = v; | ||
| 364 | + } | ||
| 365 | + _ => panic!("predict4: invalid intra 4x4 mode {mode} (expected 0..=9)"), | ||
| 366 | + } | ||
| 367 | + out.copy_from_slice(&b); | ||
| 368 | +} | ||
| 369 | + | ||
| 370 | +#[cfg(test)] | ||
| 371 | +mod tests { | ||
| 372 | + use super::*; | ||
| 373 | + | ||
| 374 | + // ---------------------------------------------------------------- -- | ||
| 375 | + // Reference model used to derive the expected vectors below. It is a | ||
| 376 | + // verbatim Python transcription of RFC 6386 Section 12.3 | ||
| 377 | + // subblock_intra_predict (with svg2p corrected to avg2p); outputs were | ||
| 378 | + // generated with it and then hand-spot-checked: | ||
| 379 | + // | ||
| 380 | + // def avg2(x, y): return (x + y + 1) >> 1 | ||
| 381 | + // def avg3(x, y, z): return (x + 2*y + z + 2) >> 2 | ||
| 382 | + // def clamp255(v): return max(0, min(255, v)) | ||
| 383 | + // # A = A[0..8], L = L[0..4], P = above-left | ||
| 384 | + // E = [L[3], L[2], L[1], L[0], P, A[0], A[1], A[2], A[3]] | ||
| 385 | + // B_DC: v = (4 + sum(A[0:4]) + sum(L[0:4])) >> 3 | ||
| 386 | + // B_TM: B[r][c] = clamp255(L[r] + A[c] - P) | ||
| 387 | + // B_VE: col c: avg3(P, A0, A1) then avg3(A[c-1], A[c], A[c+1]) | ||
| 388 | + // B_HE: rows avg3(P, L0, L1), avg3(L0, L1, L2), avg3(L1, L2, L3), | ||
| 389 | + // avg3(L2, L3, L3) | ||
| 390 | + // B_LD: B[0][0]=avg3(A0,A1,A2); B[0][1]=B[1][0]=avg3(A1,A2,A3); ... | ||
| 391 | + // B[3][3]=avg3(A6,A7,A7) | ||
| 392 | + // B_RD: B[3][0]=avg3(E0,E1,E2); B[3][1]=B[2][0]=avg3(E1,E2,E3); | ||
| 393 | + // B[3][2]=B[2][1]=B[1][0]=avg3(E2,E3,E4); | ||
| 394 | + // diag=avg3(E3,E4,E5); ...; B[0][3]=avg3(E6,E7,E8) | ||
| 395 | + // B_VR: B[3][0]=avg3(E1,E2,E3); B[2][0]=avg3(E2,E3,E4); | ||
| 396 | + // B[3][1]=B[1][0]=avg3(E3,E4,E5); B[2][1]=B[0][0]=avg2(E4,E5); | ||
| 397 | + // B[3][2]=B[1][1]=avg3(E4,E5,E6); B[2][2]=B[0][1]=avg2(E5,E6); | ||
| 398 | + // B[3][3]=B[1][2]=avg3(E5,E6,E7); B[2][3]=B[0][2]=avg2(E6,E7); | ||
| 399 | + // B[1][3]=avg3(E6,E7,E8); B[0][3]=avg2(E7,E8) | ||
| 400 | + // B_VL: B[0][0]=avg2(A0,A1); B[1][0]=avg3(A0,A1,A2); | ||
| 401 | + // B[2][0]=B[0][1]=avg2(A1,A2); B[1][1]=B[3][0]=avg3(A1,A2,A3); | ||
| 402 | + // B[2][1]=B[0][2]=avg2(A2,A3); B[3][1]=B[1][2]=avg3(A2,A3,A4); | ||
| 403 | + // B[2][2]=B[0][3]=avg2(A3,A4); B[3][2]=B[1][3]=avg3(A3,A4,A5); | ||
| 404 | + // B[2][3]=avg3(A4,A5,A6); B[3][3]=avg3(A5,A6,A7) | ||
| 405 | + // B_HD: B[3][0]=avg2(E0,E1); B[3][1]=avg3(E0,E1,E2); | ||
| 406 | + // B[2][0]=B[3][2]=avg2(E1,E2) <- svg2p typo corrected | ||
| 407 | + // B[2][1]=B[3][3]=avg3(E1,E2,E3); | ||
| 408 | + // B[2][2]=B[1][0]=avg2(E2,E3); | ||
| 409 | + // B[2][3]=B[1][1]=avg3(E2,E3,E4); | ||
| 410 | + // B[1][2]=B[0][0]=avg2(E3,E4); | ||
| 411 | + // B[1][3]=B[0][1]=avg3(E3,E4,E5); | ||
| 412 | + // B[0][2]=avg3(E4,E5,E6); B[0][3]=avg3(E5,E6,E7) | ||
| 413 | + // B_HU: B[0][0]=avg2(L0,L1); B[0][1]=avg3(L0,L1,L2); | ||
| 414 | + // B[0][2]=B[1][0]=avg2(L1,L2); B[0][3]=B[1][1]=avg3(L1,L2,L3); | ||
| 415 | + // B[1][2]=B[2][0]=avg2(L2,L3); | ||
| 416 | + // B[1][3]=B[2][1]=avg3(L2,L3,L3); | ||
| 417 | + // B[2][2..4]=B[3][0..4]=L3 | ||
| 418 | + // ---------------------------------------------------------------- -- | ||
| 419 | + | ||
| 420 | + /// Fixed edge pattern shared by all ten subblock tests: | ||
| 421 | + /// above = [10,20,30,40,50,60,70,80], left = [15,25,35,45], P = 5. | ||
| 422 | + const EDGE_A: [u8; 8] = [10, 20, 30, 40, 50, 60, 70, 80]; | ||
| 423 | + const EDGE_L: [u8; 4] = [15, 25, 35, 45]; | ||
| 424 | + const EDGE_P: u8 = 5; | ||
| 425 | + | ||
| 426 | + fn assert_pred4(mode: u8, expected: [u8; 16]) { | ||
| 427 | + let mut out = [0u8; 16]; | ||
| 428 | + predict4(mode, &EDGE_A, &EDGE_L, EDGE_P, &mut out); | ||
| 429 | + assert_eq!(out, expected, "predict4 mode {mode}"); | ||
| 430 | + } | ||
| 431 | + | ||
| 432 | + #[test] | ||
| 433 | + fn subblock_dc_constant() { | ||
| 434 | + // v = (4 + (10+20+30+40) + (15+25+35+45)) >> 3 = (4+100+120)>>3 = 28. | ||
| 435 | + assert_pred4(0, [28; 16]); | ||
| 436 | + } | ||
| 437 | + | ||
| 438 | + #[test] | ||
| 439 | + fn subblock_tm_gradient() { | ||
| 440 | + // B[r][c] = L[r] + A[c] - P = L[r] + A[c] - 5. | ||
| 441 | + assert_pred4( | ||
| 442 | + 1, | ||
| 443 | + [ | ||
| 444 | + 20, 30, 40, 50, // row 0: 15 + A[c] - 5 | ||
| 445 | + 30, 40, 50, 60, // row 1: 25 + A[c] - 5 | ||
| 446 | + 40, 50, 60, 70, // row 2 | ||
| 447 | + 50, 60, 70, 80, // row 3 | ||
| 448 | + ], | ||
| 449 | + ); | ||
| 450 | + } | ||
| 451 | + | ||
| 452 | + #[test] | ||
| 453 | + fn subblock_ve_smoothed_row() { | ||
| 454 | + // Row = avg3(A[c-1], A[c], A[c+1]) with A[-1] = P: | ||
| 455 | + // avg3(5,10,20)=11, avg3(10,20,30)=20, avg3(20,30,40)=30, | ||
| 456 | + // avg3(30,40,50)=40. | ||
| 457 | + let row = [11, 20, 30, 40]; | ||
| 458 | + let mut expected = [0u8; 16]; | ||
| 459 | + for r in 0..4 { | ||
| 460 | + expected[r * 4..r * 4 + 4].copy_from_slice(&row); | ||
| 461 | + } | ||
| 462 | + assert_pred4(2, expected); | ||
| 463 | + } | ||
| 464 | + | ||
| 465 | + #[test] | ||
| 466 | + fn subblock_he_smoothed_column() { | ||
| 467 | + // Rows: avg3(5,15,25)=15, avg3(15,25,35)=25, avg3(25,35,45)=35, | ||
| 468 | + // avg3(35,45,45)=43 (bottom-row exception, L[4] absent). | ||
| 469 | + assert_pred4( | ||
| 470 | + 3, | ||
| 471 | + [ | ||
| 472 | + 15, 15, 15, 15, 25, 25, 25, 25, 35, 35, 35, 35, 43, 43, 43, 43, | ||
| 473 | + ], | ||
| 474 | + ); | ||
| 475 | + } | ||
| 476 | + | ||
| 477 | + #[test] | ||
| 478 | + fn subblock_ld_downright_diagonal() { | ||
| 479 | + // B[3][3] = avg3(70,80,80) = (70 + 160 + 80 + 2) >> 2 = 78 (A[8] | ||
| 480 | + // does not exist). | ||
| 481 | + assert_pred4( | ||
| 482 | + 4, | ||
| 483 | + [ | ||
| 484 | + 20, 30, 40, 50, // avg3(10,20,30)=20, avg3(20,30,40)=30, ... | ||
| 485 | + 30, 40, 50, 60, // | ||
| 486 | + 40, 50, 60, 70, // | ||
| 487 | + 50, 60, 70, 78, // | ||
| 488 | + ], | ||
| 489 | + ); | ||
| 490 | + } | ||
| 491 | + | ||
| 492 | + #[test] | ||
| 493 | + fn subblock_rd_downright_diagonal() { | ||
| 494 | + // E = [45,35,25,15,5,10,20,30,40]. | ||
| 495 | + // B[3][0] = avg3(45,35,25) = 35; B[3][1]=B[2][0] = avg3(35,25,15) = 25; | ||
| 496 | + // B[3][2]=B[2][1]=B[1][0] = avg3(25,15,5) = 15; | ||
| 497 | + // main diagonal = avg3(15,5,10) = 9; B[2][3]=B[1][2]=B[0][1] = | ||
| 498 | + // avg3(5,10,20) = 11; B[1][3]=B[0][2] = avg3(10,20,30) = 20; | ||
| 499 | + // B[0][3] = avg3(20,30,40) = 30. | ||
| 500 | + assert_pred4( | ||
| 501 | + 5, | ||
| 502 | + [ | ||
| 503 | + 9, 11, 20, 30, // | ||
| 504 | + 15, 9, 11, 20, // | ||
| 505 | + 25, 15, 9, 11, // | ||
| 506 | + 35, 25, 15, 9, // | ||
| 507 | + ], | ||
| 508 | + ); | ||
| 509 | + } | ||
| 510 | + | ||
| 511 | + #[test] | ||
| 512 | + fn subblock_vr_mixed_diagonal() { | ||
| 513 | + // E = [45,35,25,15,5,10,20,30,40]. | ||
| 514 | + // B[0][0] = avg2(E4,E5) = avg2(5,10) = 8; | ||
| 515 | + // B[0][1] = avg2(10,20) = 15; B[0][2] = avg2(20,30) = 25; | ||
| 516 | + // B[0][3] = avg2(30,40) = 35; B[1][0] = avg3(15,5,10) = 9; | ||
| 517 | + // B[1][1] = avg3(5,10,20) = 11; B[1][2] = avg3(10,20,30) = 20; | ||
| 518 | + // B[1][3] = avg3(20,30,40) = 30; B[2][0] = avg3(25,15,5) = 15; | ||
| 519 | + // B[2][1] = 8; B[2][2] = 15; B[2][3] = 25; | ||
| 520 | + // B[3][0] = avg3(35,25,15) = 25; B[3][1] = 9; B[3][2] = 11; B[3][3] = 20. | ||
| 521 | + assert_pred4( | ||
| 522 | + 6, | ||
| 523 | + [ | ||
| 524 | + 8, 15, 25, 35, // | ||
| 525 | + 9, 11, 20, 30, // | ||
| 526 | + 15, 8, 15, 25, // | ||
| 527 | + 25, 9, 11, 20, // | ||
| 528 | + ], | ||
| 529 | + ); | ||
| 530 | + } | ||
| 531 | + | ||
| 532 | + #[test] | ||
| 533 | + fn subblock_vl_downleft_diagonal() { | ||
| 534 | + // avg2/avg3 pairs along the above row: | ||
| 535 | + // cols: avg2(10,20)=15, avg2(20,30)=25, avg2(30,40)=35, avg2(40,50)=45; | ||
| 536 | + // rows shift by avg3: 20, 30, 40, 50; last column 45/50/60/70 with | ||
| 537 | + // B[2][3]=avg3(50,60,70)=60, B[3][3]=avg3(60,70,80)=70. | ||
| 538 | + assert_pred4( | ||
| 539 | + 7, | ||
| 540 | + [ | ||
| 541 | + 15, 25, 35, 45, // | ||
| 542 | + 20, 30, 40, 50, // | ||
| 543 | + 25, 35, 45, 60, // | ||
| 544 | + 30, 40, 50, 70, // | ||
| 545 | + ], | ||
| 546 | + ); | ||
| 547 | + } | ||
| 548 | + | ||
| 549 | + #[test] | ||
| 550 | + fn subblock_hd_uses_avg2p_for_svg2p_typo_line() { | ||
| 551 | + // E = [45,35,25,15,5,10,20,30,40]. | ||
| 552 | + // The RFC's `svg2p(E + 1)` line: B[2][0] = B[3][2] = avg2p(E+1) = | ||
| 553 | + // avg2(E[1], E[2]) = avg2(35,25) = 30. A mis-transcription (any | ||
| 554 | + // avg3-style or E-shifted variant) would not yield 30 here. | ||
| 555 | + // B[3][0] = avg2(45,35) = 40; B[3][1] = avg3(45,35,25) = 35; | ||
| 556 | + // B[2][1]=B[3][3] = avg3(35,25,15) = 25; B[2][2]=B[1][0] = | ||
| 557 | + // avg2(25,15) = 20; B[2][3]=B[1][1] = avg3(25,15,5) = 15; | ||
| 558 | + // B[1][2]=B[0][0] = avg2(15,5) = 10; B[1][3]=B[0][1] = | ||
| 559 | + // avg3(15,5,10) = 9; B[0][2] = avg3(5,10,20) = 11; | ||
| 560 | + // B[0][3] = avg3(10,20,30) = 20. | ||
| 561 | + assert_pred4( | ||
| 562 | + 8, | ||
| 563 | + [ | ||
| 564 | + 10, 9, 11, 20, // | ||
| 565 | + 20, 15, 10, 9, // | ||
| 566 | + 30, 25, 20, 15, // | ||
| 567 | + 40, 35, 30, 25, // | ||
| 568 | + ], | ||
| 569 | + ); | ||
| 570 | + // Directly pin the corrected-typo cells. | ||
| 571 | + let mut out = [0u8; 16]; | ||
| 572 | + predict4(8, &EDGE_A, &EDGE_L, EDGE_P, &mut out); | ||
| 573 | + assert_eq!( | ||
| 574 | + (out[8], out[14]), | ||
| 575 | + (30, 30), | ||
| 576 | + "B[2][0] and B[3][2] = avg2(E1,E2)" | ||
| 577 | + ); | ||
| 578 | + } | ||
| 579 | + | ||
| 580 | + #[test] | ||
| 581 | + fn subblock_hu_up_diagonal() { | ||
| 582 | + // B[0][0] = avg2(15,25) = 20; B[0][1] = avg3(15,25,35) = 25; | ||
| 583 | + // B[0][2]=B[1][0] = avg2(25,35) = 30; B[0][3]=B[1][1] = | ||
| 584 | + // avg3(25,35,45) = 35; B[1][2]=B[2][0] = avg2(35,45) = 40; | ||
| 585 | + // B[1][3]=B[2][1] = avg3(35,45,45) = 43; bottom rows = L[3] = 45. | ||
| 586 | + assert_pred4( | ||
| 587 | + 9, | ||
| 588 | + [ | ||
| 589 | + 20, 25, 30, 35, // | ||
| 590 | + 30, 35, 40, 43, // | ||
| 591 | + 40, 43, 45, 45, // | ||
| 592 | + 45, 45, 45, 45, // | ||
| 593 | + ], | ||
| 594 | + ); | ||
| 595 | + } | ||
| 596 | + | ||
| 597 | + #[test] | ||
| 598 | + fn dc16_all_availability_cases() { | ||
| 599 | + // above = [10; 16] (sum 160), left = [20; 16] (sum 320). | ||
| 600 | + let above = [10u8; 16]; | ||
| 601 | + let left = [20u8; 16]; | ||
| 602 | + let mut out = [0u8; 256]; | ||
| 603 | + | ||
| 604 | + // Both edges: (160 + 320 + 16) >> 5 = 15. | ||
| 605 | + predict16(0, true, true, &above, &left, 5, &mut out); | ||
| 606 | + assert_eq!(out, [15; 256]); | ||
| 607 | + | ||
| 608 | + // Neither edge (top-left macroblock): constant 128. The array | ||
| 609 | + // contents are irrelevant here; availability flags decide. | ||
| 610 | + predict16(0, false, false, &above, &left, 5, &mut out); | ||
| 611 | + assert_eq!(out, [128; 256]); | ||
| 612 | + | ||
| 613 | + // Above only (left frame column): (160 + 8) >> 4 = 10. | ||
| 614 | + predict16(0, true, false, &above, &left, 5, &mut out); | ||
| 615 | + assert_eq!(out, [10; 256]); | ||
| 616 | + | ||
| 617 | + // Left only (top frame row): (320 + 8) >> 4 = 20. | ||
| 618 | + predict16(0, false, true, &above, &left, 5, &mut out); | ||
| 619 | + assert_eq!(out, [20; 256]); | ||
| 620 | + } | ||
| 621 | + | ||
| 622 | + #[test] | ||
| 623 | + fn dc8_all_availability_cases() { | ||
| 624 | + // above = [10; 8] (sum 80), left = [20; 8] (sum 160). | ||
| 625 | + let above = [10u8; 8]; | ||
| 626 | + let left = [20u8; 8]; | ||
| 627 | + let mut out = [0u8; 64]; | ||
| 628 | + | ||
| 629 | + // Both: (80 + 160 + 8) >> 4 = 15. | ||
| 630 | + predict8(0, true, true, &above, &left, 5, &mut out); | ||
| 631 | + assert_eq!(out, [15; 64]); | ||
| 632 | + | ||
| 633 | + // Neither: 128. | ||
| 634 | + predict8(0, false, false, &above, &left, 5, &mut out); | ||
| 635 | + assert_eq!(out, [128; 64]); | ||
| 636 | + | ||
| 637 | + // Above only: (80 + 4) >> 3 = 10. | ||
| 638 | + predict8(0, true, false, &above, &left, 5, &mut out); | ||
| 639 | + assert_eq!(out, [10; 64]); | ||
| 640 | + | ||
| 641 | + // Left only: (160 + 4) >> 3 = 20. | ||
| 642 | + predict8(0, false, true, &above, &left, 5, &mut out); | ||
| 643 | + assert_eq!(out, [20; 64]); | ||
| 644 | + } | ||
| 645 | + | ||
| 646 | + #[test] | ||
| 647 | + fn tm16_clamps_both_directions() { | ||
| 648 | + let mut out = [0u8; 256]; | ||
| 649 | + | ||
| 650 | + // Negative difference clamps to 0: P high (250), L and A low (0) | ||
| 651 | + // gives L + A - P = -250 everywhere. | ||
| 652 | + predict16(3, true, true, &[0u8; 16], &[0u8; 16], 250, &mut out); | ||
| 653 | + assert_eq!(out, [0; 256]); | ||
| 654 | + | ||
| 655 | + // Overflow clamps to 255: P = 0, L = A = 255 gives 510 everywhere. | ||
| 656 | + predict16(3, true, true, &[255u8; 16], &[255u8; 16], 0, &mut out); | ||
| 657 | + assert_eq!(out, [255; 256]); | ||
| 658 | + | ||
| 659 | + // Exact in-range gradient: out[r][c] = 200 + c - 50 = 150 + c, | ||
| 660 | + // no clamping, verifies arithmetic (not just the clamps). | ||
| 661 | + let above: [u8; 16] = core::array::from_fn(|i| i as u8); | ||
| 662 | + predict16(3, true, true, &above, &[200u8; 16], 50, &mut out); | ||
| 663 | + for r in 0..16 { | ||
| 664 | + let row: [u8; 16] = core::array::from_fn(|c| (150 + c) as u8); | ||
| 665 | + assert_eq!(out[r * 16..r * 16 + 16], row, "TM16 row {r}"); | ||
| 666 | + } | ||
| 667 | + } | ||
| 668 | + | ||
| 669 | + #[test] | ||
| 670 | + fn tm4_clamps_via_predict4() { | ||
| 671 | + // Same clamp contract at 4x4 (RFC B_TM_PRED == clamp255(L + A - P)). | ||
| 672 | + let mut out = [0u8; 16]; | ||
| 673 | + predict4(1, &[0u8; 8], &[0u8; 4], 250, &mut out); | ||
| 674 | + assert_eq!(out, [0; 16]); | ||
| 675 | + predict4(1, &[255u8; 8], &[255u8; 4], 0, &mut out); | ||
| 676 | + assert_eq!(out, [255; 16]); | ||
| 677 | + } | ||
| 678 | + | ||
| 679 | + #[test] | ||
| 680 | + fn v_and_h_copy_edges() { | ||
| 681 | + // V_PRED: every 16x16 row equals the above row. | ||
| 682 | + let above: [u8; 16] = core::array::from_fn(|i| (i * 7 + 3) as u8); | ||
| 683 | + let mut out = [0u8; 256]; | ||
| 684 | + predict16(1, true, true, &above, &[0u8; 16], 0, &mut out); | ||
| 685 | + for row in out.chunks_exact(16) { | ||
| 686 | + assert_eq!(row, above); | ||
| 687 | + } | ||
| 688 | + | ||
| 689 | + // H_PRED: every 8x8 row is the constant left[r]. | ||
| 690 | + let left: [u8; 8] = core::array::from_fn(|i| (i * 11 + 1) as u8); | ||
| 691 | + let mut out8 = [0u8; 64]; | ||
| 692 | + predict8(2, true, true, &[0u8; 8], &left, 0, &mut out8); | ||
| 693 | + for (r, row) in out8.chunks_exact(8).enumerate() { | ||
| 694 | + assert_eq!(row, [left[r]; 8]); | ||
| 695 | + } | ||
| 696 | + } | ||
| 697 | + | ||
| 698 | + #[test] | ||
| 699 | + #[should_panic(expected = "invalid intra mode")] | ||
| 700 | + fn predict16_rejects_invalid_mode() { | ||
| 701 | + let mut out = [0u8; 256]; | ||
| 702 | + predict16(4, true, true, &[0u8; 16], &[0u8; 16], 0, &mut out); | ||
| 703 | + } | ||
| 704 | + | ||
| 705 | + #[test] | ||
| 706 | + #[should_panic(expected = "invalid intra 4x4 mode")] | ||
| 707 | + fn predict4_rejects_invalid_mode() { | ||
| 708 | + let mut out = [0u8; 16]; | ||
| 709 | + predict4(10, &[0u8; 8], &[0u8; 4], 0, &mut out); | ||
| 710 | + } | ||
| 711 | +} | ||
crates/ec-vp8/src/lib.rsmodified+6 -0
| @@ -15,9 +15,15 @@ | |||
| 15 | #![warn(missing_docs)] | 15 | #![warn(missing_docs)] |
| 16 | 16 | ||
| 17 | pub mod bool; | 17 | pub mod bool; |
| 18 | +pub mod decode; | ||
| 18 | pub mod frame; | 19 | pub mod frame; |
| 19 | pub mod header; | 20 | pub mod header; |
| 21 | +pub mod intra; | ||
| 22 | +pub mod loopfilter; | ||
| 23 | +pub mod modes; | ||
| 20 | pub mod tables; | 24 | pub mod tables; |
| 25 | +pub mod tokens; | ||
| 26 | +pub mod transform; | ||
| 21 | 27 | ||
| 22 | pub use ec_core::{Error, Result}; | 28 | pub use ec_core::{Error, Result}; |
| 23 | pub use header::PersistedState; | 29 | pub use header::PersistedState; |
crates/ec-vp8/src/loopfilter.rsadded+1064 -0
| @@ -0,0 +1,1064 @@ | |||
| 1 | +//! VP8 in-loop deblocking filter — RFC 6386 Section 15. | ||
| 2 | +//! | ||
| 3 | +//! Implements the *normal* filter (§15.3), the *simple* filter (§15.2), the | ||
| 4 | +//! per-frame macroblock-edge driver in the reference decoder's exact visit | ||
| 5 | +//! order, and the per-sharpness limit-table construction of §15.4. | ||
| 6 | +//! | ||
| 7 | +//! The arithmetic is transcribed line-for-line from the normative reference | ||
| 8 | +//! sources and is bit-identical between them (verified term-by-term): | ||
| 9 | +//! | ||
| 10 | +//! * `dixie_loopfilter.c` shipped with RFC 6386 (§20.6) — kernels | ||
| 11 | +//! (`filter_common`, `filter_mb_edge`, thresholds) and the | ||
| 12 | +//! `filter_row_normal` / `filter_row_simple` drivers, | ||
| 13 | +//! * libvpx `vp8/common/loopfilter_filters.c` — the same kernels as | ||
| 14 | +//! branch-free C, and `vp8/common/vp8_loopfilter.c` | ||
| 15 | +//! (`vp8_loop_filter_update_sharpness`, `lf_init_lut`) — the limit and | ||
| 16 | +//! high-edge-variance tables. | ||
| 17 | +//! | ||
| 18 | +//! C signed right-shifts are arithmetic (floor); Rust `i32 >>` has the same | ||
| 19 | +//! semantics, so every `>>` below reproduces the C rounding exactly. No | ||
| 20 | +//! allocation, no `unsafe`. | ||
| 21 | +//! | ||
| 22 | +//! Frame-type note: §15.4 (and libvpx `lf_init_lut`) makes `hev_threshold` | ||
| 23 | +//! depend on whether the current frame is a key frame. [`filter_frame`] | ||
| 24 | +//! keeps the crate-contract signature and applies the *inter-frame* table; | ||
| 25 | +//! call [`filter_frame_ex`] with the decoded `is_keyframe` flag for fully | ||
| 26 | +//! type-exact decoding (the two differ only for levels ≥ 15). | ||
| 27 | + | ||
| 28 | +/// Per-macroblock filter inputs the decoder derives from the frame header, | ||
| 29 | +/// segmentation map and per-MB prediction info. | ||
| 30 | +/// | ||
| 31 | +/// `level` is the *final* per-MB loop filter level (0..=63) after the | ||
| 32 | +/// segment and ref/mode delta adjustments of RFC 6386 §15.4 (implemented | ||
| 33 | +/// decoder-side in `decode.rs`, mirroring dixie `calculate_filter_parameters`). | ||
| 34 | +/// A level of 0 disables all filtering of that macroblock (dixie: | ||
| 35 | +/// `if (edge_limit) { ... }`). | ||
| 36 | +/// | ||
| 37 | +/// `inner_edges` controls whether the subblock (interior) edges of the MB | ||
| 38 | +/// are filtered: true iff the MB has any non-zero DCT coefficient or its | ||
| 39 | +/// mode is `B_PRED`/`SPLITMV` (RFC §15.1; dixie's `eob_mask` condition, | ||
| 40 | +/// `filter_row_normal` ~L9308 and `filter_row_simple` ~L9433). | ||
| 41 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 42 | +pub struct MbFilterInfo { | ||
| 43 | + /// Effective per-MB loop filter level after segment and ref/mode delta | ||
| 44 | + /// adjustments, clamped to 0..=63. | ||
| 45 | + pub level: u8, | ||
| 46 | + /// Filter interior (subblock) edges of this MB (any non-zero DCT | ||
| 47 | + /// coefficient, or `B_PRED`/`SPLITMV` mode). | ||
| 48 | + pub inner_edges: bool, | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// Per-sharpness limit tables for levels 0..=63, in the order | ||
| 52 | +/// `lim` / `blim` / `mblim` of libvpx `loop_filter_info_n`. | ||
| 53 | +/// | ||
| 54 | +/// These are the combined edge limits of RFC §15.4: | ||
| 55 | +/// `mblim[l] = (l + 2) * 2 + interior_limit(l)` (macroblock edges), | ||
| 56 | +/// `blim[l] = l * 2 + interior_limit(l)` (subblock edges), and | ||
| 57 | +/// `lim[l] = interior_limit(l)`. Both filter variants consume these exact | ||
| 58 | +/// combined values (the simple filter directly, as dixie | ||
| 59 | +/// `filter_v_edge_simple` does; the normal filter splits them back into | ||
| 60 | +/// center + interior tests). | ||
| 61 | +#[derive(Clone, Copy, Debug)] | ||
| 62 | +pub struct LoopFilterTables { | ||
| 63 | + /// Interior-difference limit per level (dixie `interior_limit`). | ||
| 64 | + pub lim: [u8; 64], | ||
| 65 | + /// Combined subblock-edge center limit per level (dixie `b_limit`). | ||
| 66 | + pub blim: [u8; 64], | ||
| 67 | + /// Combined macroblock-edge center limit per level (dixie `mb_limit`). | ||
| 68 | + pub mblim: [u8; 64], | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +impl LoopFilterTables { | ||
| 72 | + /// Build the three limit tables for one frame's sharpness level. | ||
| 73 | + /// | ||
| 74 | + /// Port of libvpx `vp8_loop_filter_update_sharpness` | ||
| 75 | + /// (vp8/common/vp8_loopfilter.c), which matches the RFC §15.4 | ||
| 76 | + /// pseudocode: | ||
| 77 | + /// | ||
| 78 | + /// ```text | ||
| 79 | + /// inside = level >> (sharpness > 0) >> (sharpness > 4) | ||
| 80 | + /// if sharpness > 0 and inside > 9 - sharpness: inside = 9 - sharpness | ||
| 81 | + /// inside = max(inside, 1) | ||
| 82 | + /// ``` | ||
| 83 | + pub fn update_sharpness(sharpness: u8) -> Self { | ||
| 84 | + let s = i32::from(sharpness); | ||
| 85 | + let mut t = LoopFilterTables { | ||
| 86 | + lim: [0; 64], | ||
| 87 | + blim: [0; 64], | ||
| 88 | + mblim: [0; 64], | ||
| 89 | + }; | ||
| 90 | + for (lvl, slot) in t.lim.iter_mut().enumerate() { | ||
| 91 | + let filt_lvl = lvl as i32; | ||
| 92 | + // libvpx L59-60: two conditional single-bit shifts. | ||
| 93 | + let mut inside = filt_lvl; | ||
| 94 | + if s > 0 { | ||
| 95 | + inside >>= 1; | ||
| 96 | + } | ||
| 97 | + if s > 4 { | ||
| 98 | + inside >>= 1; | ||
| 99 | + } | ||
| 100 | + // libvpx L62-66: cap only applies when sharpness > 0. | ||
| 101 | + if s > 0 && inside > 9 - s { | ||
| 102 | + inside = 9 - s; | ||
| 103 | + } | ||
| 104 | + if inside < 1 { | ||
| 105 | + inside = 1; | ||
| 106 | + } | ||
| 107 | + *slot = inside as u8; | ||
| 108 | + t.blim[lvl] = (2 * filt_lvl + inside) as u8; | ||
| 109 | + t.mblim[lvl] = (2 * (filt_lvl + 2) + inside) as u8; | ||
| 110 | + } | ||
| 111 | + t | ||
| 112 | + } | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +/// Interior-difference limit for one level/sharpness pair (RFC §15.4). | ||
| 116 | +/// | ||
| 117 | +/// Same derivation as [`LoopFilterTables::update_sharpness`] for a single | ||
| 118 | +/// level; provided for callers that need the value without the tables. | ||
| 119 | +pub fn interior_limit(level: u8, sharpness: u8) -> i32 { | ||
| 120 | + let s = i32::from(sharpness); | ||
| 121 | + let mut il = i32::from(level); | ||
| 122 | + if s > 0 { | ||
| 123 | + // dixie: interior_limit >>= sharpness > 4 ? 2 : 1 — the two | ||
| 124 | + // conditional single-bit shifts of update_sharpness folded. | ||
| 125 | + il >>= if s > 4 { 2 } else { 1 }; | ||
| 126 | + if il > 9 - s { | ||
| 127 | + il = 9 - s; | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + if il < 1 { | ||
| 131 | + il = 1; | ||
| 132 | + } | ||
| 133 | + il | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// High-edge-variance threshold for one level (RFC §15.4, last block; also | ||
| 137 | +/// libvpx `lf_init_lut`'s `hev_thr_lut[KEY_FRAME|INTER_FRAME]`). | ||
| 138 | +/// | ||
| 139 | +/// Key frames: 2 at level ≥ 40, 1 at level ≥ 15, else 0. Inter frames: 3 at | ||
| 140 | +/// level ≥ 40, 2 at level ≥ 20, 1 at level ≥ 15, else 0. | ||
| 141 | +pub fn hev_threshold(level: u8, is_keyframe: bool) -> i32 { | ||
| 142 | + let l = i32::from(level); | ||
| 143 | + if is_keyframe { | ||
| 144 | + if l >= 40 { | ||
| 145 | + 2 | ||
| 146 | + } else if l >= 15 { | ||
| 147 | + 1 | ||
| 148 | + } else { | ||
| 149 | + 0 | ||
| 150 | + } | ||
| 151 | + } else if l >= 40 { | ||
| 152 | + 3 | ||
| 153 | + } else if l >= 20 { | ||
| 154 | + 2 | ||
| 155 | + } else if l >= 15 { | ||
| 156 | + 1 | ||
| 157 | + } else { | ||
| 158 | + 0 | ||
| 159 | + } | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +/// Filter one frame's worth of macroblock edges, in the reference decoder's | ||
| 163 | +/// exact order (dixie `filter_row_normal` / `filter_row_simple`, applied | ||
| 164 | +/// row-major over MBs; each MB visits, when enabled: left MB V-edge, then | ||
| 165 | +/// subblock V-edges at +4/+8/+12, then top MB H-edge, then subblock | ||
| 166 | +/// H-edges at +4/+8/+12 rows). | ||
| 167 | +/// | ||
| 168 | +/// `y`/`u`/`v` are unbordered plane buffers starting at pixel (0,0), | ||
| 169 | +/// `stride`/`uv_stride` samples apart, sized `mb_cols*16 × mb_rows*16` | ||
| 170 | +/// (and halved for chroma). Frame-boundary edges (column 0, row 0) are not | ||
| 171 | +/// filtered. `mb_info` is indexed `row * mb_cols + col`; a level of 0 | ||
| 172 | +/// disables all filtering of that MB. The simple variant filters only the | ||
| 173 | +/// Y plane (dixie `filter_row_simple`). | ||
| 174 | +/// | ||
| 175 | +/// This applies the inter-frame `hev_threshold` table (see the module docs); | ||
| 176 | +/// use [`filter_frame_ex`] for frame-type-exact decoding. | ||
| 177 | +#[allow(clippy::too_many_arguments)] | ||
| 178 | +pub fn filter_frame( | ||
| 179 | + y: &mut [u8], | ||
| 180 | + u: &mut [u8], | ||
| 181 | + v: &mut [u8], | ||
| 182 | + stride: usize, | ||
| 183 | + uv_stride: usize, | ||
| 184 | + mb_cols: usize, | ||
| 185 | + mb_rows: usize, | ||
| 186 | + sharpness: u8, | ||
| 187 | + simple_filter_type: bool, | ||
| 188 | + mb_info: &[MbFilterInfo], | ||
| 189 | +) { | ||
| 190 | + filter_frame_ex( | ||
| 191 | + y, | ||
| 192 | + u, | ||
| 193 | + v, | ||
| 194 | + stride, | ||
| 195 | + uv_stride, | ||
| 196 | + mb_cols, | ||
| 197 | + mb_rows, | ||
| 198 | + sharpness, | ||
| 199 | + simple_filter_type, | ||
| 200 | + mb_info, | ||
| 201 | + false, | ||
| 202 | + ); | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +/// [`filter_frame`] with an explicit frame type: `is_keyframe` selects the | ||
| 206 | +/// §15.4 key-frame `hev_threshold` table instead of the inter-frame table | ||
| 207 | +/// (dixie `calculate_filter_parameters`: | ||
| 208 | +/// `if (filter_level >= 20 && !is_keyframe) hev_threshold++`). | ||
| 209 | +#[allow(clippy::too_many_arguments)] | ||
| 210 | +pub fn filter_frame_ex( | ||
| 211 | + y: &mut [u8], | ||
| 212 | + u: &mut [u8], | ||
| 213 | + v: &mut [u8], | ||
| 214 | + stride: usize, | ||
| 215 | + uv_stride: usize, | ||
| 216 | + mb_cols: usize, | ||
| 217 | + mb_rows: usize, | ||
| 218 | + sharpness: u8, | ||
| 219 | + simple_filter_type: bool, | ||
| 220 | + mb_info: &[MbFilterInfo], | ||
| 221 | + is_keyframe: bool, | ||
| 222 | +) { | ||
| 223 | + debug_assert_eq!(mb_info.len(), mb_cols * mb_rows); | ||
| 224 | + debug_assert!(y.len() >= stride * (mb_rows * 16 - 1) + mb_cols * 16); | ||
| 225 | + debug_assert!(u.len() >= uv_stride * (mb_rows * 8 - 1) + mb_cols * 8); | ||
| 226 | + debug_assert!(v.len() >= uv_stride * (mb_rows * 8 - 1) + mb_cols * 8); | ||
| 227 | + debug_assert!(stride >= mb_cols * 16); | ||
| 228 | + debug_assert!(uv_stride >= mb_cols * 8); | ||
| 229 | + | ||
| 230 | + let tables = LoopFilterTables::update_sharpness(sharpness); | ||
| 231 | + | ||
| 232 | + for row in 0..mb_rows { | ||
| 233 | + for col in 0..mb_cols { | ||
| 234 | + let info = &mb_info[row * mb_cols + col]; | ||
| 235 | + let level = info.level as usize; | ||
| 236 | + // dixie filter_row_normal L9280 / filter_row_simple L9425: | ||
| 237 | + // `if (edge_limit)` — level 0 filters nothing for this MB. | ||
| 238 | + if level == 0 { | ||
| 239 | + continue; | ||
| 240 | + } | ||
| 241 | + let hev = hev_threshold(info.level, is_keyframe); | ||
| 242 | + let mblim = i32::from(tables.mblim[level]); | ||
| 243 | + let blim = i32::from(tables.blim[level]); | ||
| 244 | + let lim = i32::from(tables.lim[level]); | ||
| 245 | + let ybase = row * 16 * stride + col * 16; | ||
| 246 | + let uvbase = row * 8 * uv_stride + col * 8; | ||
| 247 | + | ||
| 248 | + if simple_filter_type { | ||
| 249 | + // dixie filter_row_simple L9436-9460. Y plane only. | ||
| 250 | + if col > 0 { | ||
| 251 | + filter_v_edge_simple(y, stride, ybase, mblim); | ||
| 252 | + } | ||
| 253 | + if info.inner_edges { | ||
| 254 | + filter_v_edge_simple(y, stride, ybase + 4, blim); | ||
| 255 | + filter_v_edge_simple(y, stride, ybase + 8, blim); | ||
| 256 | + filter_v_edge_simple(y, stride, ybase + 12, blim); | ||
| 257 | + } | ||
| 258 | + if row > 0 { | ||
| 259 | + filter_h_edge_simple(y, stride, ybase, mblim); | ||
| 260 | + } | ||
| 261 | + if info.inner_edges { | ||
| 262 | + filter_h_edge_simple(y, stride, ybase + 4 * stride, blim); | ||
| 263 | + filter_h_edge_simple(y, stride, ybase + 8 * stride, blim); | ||
| 264 | + filter_h_edge_simple(y, stride, ybase + 12 * stride, blim); | ||
| 265 | + } | ||
| 266 | + continue; | ||
| 267 | + } | ||
| 268 | + | ||
| 269 | + // dixie filter_row_normal L9282-9378. | ||
| 270 | + if col > 0 { | ||
| 271 | + filter_mb_v_edge(y, stride, ybase, mblim, lim, hev, 2); | ||
| 272 | + filter_mb_v_edge(u, uv_stride, uvbase, mblim, lim, hev, 1); | ||
| 273 | + filter_mb_v_edge(v, uv_stride, uvbase, mblim, lim, hev, 1); | ||
| 274 | + } | ||
| 275 | + if info.inner_edges { | ||
| 276 | + filter_subblock_v_edge(y, stride, ybase + 4, blim, lim, hev, 2); | ||
| 277 | + filter_subblock_v_edge(y, stride, ybase + 8, blim, lim, hev, 2); | ||
| 278 | + filter_subblock_v_edge(y, stride, ybase + 12, blim, lim, hev, 2); | ||
| 279 | + filter_subblock_v_edge(u, uv_stride, uvbase + 4, blim, lim, hev, 1); | ||
| 280 | + filter_subblock_v_edge(v, uv_stride, uvbase + 4, blim, lim, hev, 1); | ||
| 281 | + } | ||
| 282 | + if row > 0 { | ||
| 283 | + filter_mb_h_edge(y, stride, ybase, mblim, lim, hev, 2); | ||
| 284 | + filter_mb_h_edge(u, uv_stride, uvbase, mblim, lim, hev, 1); | ||
| 285 | + filter_mb_h_edge(v, uv_stride, uvbase, mblim, lim, hev, 1); | ||
| 286 | + } | ||
| 287 | + if info.inner_edges { | ||
| 288 | + filter_subblock_h_edge(y, stride, ybase + 4 * stride, blim, lim, hev, 2); | ||
| 289 | + filter_subblock_h_edge(y, stride, ybase + 8 * stride, blim, lim, hev, 2); | ||
| 290 | + filter_subblock_h_edge(y, stride, ybase + 12 * stride, blim, lim, hev, 2); | ||
| 291 | + filter_subblock_h_edge(u, uv_stride, uvbase + 4 * uv_stride, blim, lim, hev, 1); | ||
| 292 | + filter_subblock_h_edge(v, uv_stride, uvbase + 4 * uv_stride, blim, lim, hev, 1); | ||
| 293 | + } | ||
| 294 | + } | ||
| 295 | + } | ||
| 296 | +} | ||
| 297 | + | ||
| 298 | +// --------------------------------------------------------------------------- | ||
| 299 | +// Kernels — transcriptions of dixie_loopfilter.c (RFC 6386 §20.6). | ||
| 300 | +// Pixels are handled as raw unsigned samples widened to `i32`; every clamp | ||
| 301 | +// is the exact dixie saturate_int8 / saturate_uint8. | ||
| 302 | +// --------------------------------------------------------------------------- | ||
| 303 | + | ||
| 304 | +/// dixie `saturate_int8`. | ||
| 305 | +#[inline] | ||
| 306 | +fn sat_i8(x: i32) -> i32 { | ||
| 307 | + x.clamp(-128, 127) | ||
| 308 | +} | ||
| 309 | + | ||
| 310 | +/// dixie `saturate_uint8` (result kept as `i32` in 0..=255). | ||
| 311 | +#[inline] | ||
| 312 | +fn sat_u8(x: i32) -> i32 { | ||
| 313 | + x.clamp(0, 255) | ||
| 314 | +} | ||
| 315 | + | ||
| 316 | +/// dixie `simple_threshold` (RFC §15.2/§15.3): the center test | ||
| 317 | +/// `|p0-q0|*2 + |p1-q1|/2 <= limit` with `limit` already the *combined* | ||
| 318 | +/// edge limit (`2*E + I`, or the tables' `blim`/`mblim`). | ||
| 319 | +#[inline] | ||
| 320 | +fn simple_threshold(p1: i32, p0: i32, q0: i32, q1: i32, limit: i32) -> bool { | ||
| 321 | + (p0 - q0).abs() * 2 + ((p1 - q1).abs() >> 1) <= limit | ||
| 322 | +} | ||
| 323 | + | ||
| 324 | +/// dixie `normal_threshold` (RFC §15.3 `filter_yes`): the combined center | ||
| 325 | +/// test plus all six interior-difference tests against `interior`. | ||
| 326 | +/// `px` is `[p3, p2, p1, p0, q0, q1, q2, q3]` across the edge. | ||
| 327 | +#[inline] | ||
| 328 | +fn normal_threshold(px: &[i32; 8], center_limit: i32, interior: i32) -> bool { | ||
| 329 | + let [_, p2, p1, p0, q0, q1, q2, _] = *px; | ||
| 330 | + simple_threshold(p1, p0, q0, q1, center_limit) | ||
| 331 | + && (px[0] - p2).abs() <= interior | ||
| 332 | + && (p2 - p1).abs() <= interior | ||
| 333 | + && (p1 - p0).abs() <= interior | ||
| 334 | + && (px[7] - q2).abs() <= interior | ||
| 335 | + && (q2 - q1).abs() <= interior | ||
| 336 | + && (q1 - q0).abs() <= interior | ||
| 337 | +} | ||
| 338 | + | ||
| 339 | +/// dixie `high_edge_variance` (RFC §15.3 `hev`). | ||
| 340 | +#[inline] | ||
| 341 | +fn high_edge_variance(p1: i32, p0: i32, q0: i32, q1: i32, hev_threshold: i32) -> bool { | ||
| 342 | + (p1 - p0).abs() > hev_threshold || (q1 - q0).abs() > hev_threshold | ||
| 343 | +} | ||
| 344 | + | ||
| 345 | +/// dixie `filter_common` (RFC §15.3 `common_adjust`). | ||
| 346 | +/// | ||
| 347 | +/// `use_outer_taps` is true for the simple filter and for high-variance | ||
| 348 | +/// edges. Returns `[p1, p0, q0, q1]`; the returned `p1`/`q1` equal the | ||
| 349 | +/// inputs unless `!use_outer_taps` (subblock filter adjusts the inner | ||
| 350 | +/// taps by half the edge adjustment). | ||
| 351 | +fn filter_common(p1: i32, p0: i32, q0: i32, q1: i32, use_outer_taps: bool) -> [i32; 4] { | ||
| 352 | + let mut a = 3 * (q0 - p0); | ||
| 353 | + if use_outer_taps { | ||
| 354 | + a += sat_i8(p1 - q1); | ||
| 355 | + } | ||
| 356 | + a = sat_i8(a); | ||
| 357 | + // dixie clamps only the top here; a ≥ -128 makes a bottom clamp dead | ||
| 358 | + // code, and the arithmetic `>> 3` reproduces the C rounding exactly. | ||
| 359 | + let f1 = (if a + 4 > 127 { 127 } else { a + 4 }) >> 3; | ||
| 360 | + let f2 = (if a + 3 > 127 { 127 } else { a + 3 }) >> 3; | ||
| 361 | + let p0 = sat_u8(p0 + f2); | ||
| 362 | + let q0 = sat_u8(q0 - f1); | ||
| 363 | + let (p1, q1) = if !use_outer_taps { | ||
| 364 | + let a = (f1 + 1) >> 1; | ||
| 365 | + (sat_u8(p1 + a), sat_u8(q1 - a)) | ||
| 366 | + } else { | ||
| 367 | + (p1, q1) | ||
| 368 | + }; | ||
| 369 | + [p1, p0, q0, q1] | ||
| 370 | +} | ||
| 371 | + | ||
| 372 | +/// dixie `filter_mb_edge` (RFC §15.3 `MBfilter`, non-hev branch): `w` is | ||
| 373 | +/// "twice the edge difference" and the 27/18/9 coefficients approximate | ||
| 374 | +/// 3/7, 2/7, 1/7 of it. Returns `[p2, p1, p0, q0, q1, q2]`. | ||
| 375 | +fn filter_mb_edge(p2: i32, p1: i32, p0: i32, q0: i32, q1: i32, q2: i32) -> [i32; 6] { | ||
| 376 | + let w = sat_i8(sat_i8(p1 - q1) + 3 * (q0 - p0)); | ||
| 377 | + let a = (27 * w + 63) >> 7; | ||
| 378 | + let (p0, q0) = (sat_u8(p0 + a), sat_u8(q0 - a)); | ||
| 379 | + let a = (18 * w + 63) >> 7; | ||
| 380 | + let (p1, q1) = (sat_u8(p1 + a), sat_u8(q1 - a)); | ||
| 381 | + let a = (9 * w + 63) >> 7; | ||
| 382 | + let (p2, q2) = (sat_u8(p2 + a), sat_u8(q2 - a)); | ||
| 383 | + [p2, p1, p0, q0, q1, q2] | ||
| 384 | +} | ||
| 385 | + | ||
| 386 | +// --------------------------------------------------------------------------- | ||
| 387 | +// Edge walkers. `anchor` is the flat index of the edge's q0 sample in the | ||
| 388 | +// first row (V edges) / column (H edges); `size` is the number of 8-pixel | ||
| 389 | +// segments (2 = 16-pixel Y MB edge, 1 = 8-pixel chroma / subblock edge). | ||
| 390 | +// Frame-boundary guarantees (anchor ≥ 4 samples from the plane edge) are | ||
| 391 | +// established by `filter_frame_ex`'s `col > 0` / `row > 0` guards. | ||
| 392 | +// --------------------------------------------------------------------------- | ||
| 393 | + | ||
| 394 | +/// dixie `filter_mb_v_edge`: vertical MB edge, normal filter. | ||
| 395 | +fn filter_mb_v_edge( | ||
| 396 | + plane: &mut [u8], | ||
| 397 | + stride: usize, | ||
| 398 | + anchor: usize, | ||
| 399 | + center_limit: i32, | ||
| 400 | + interior: i32, | ||
| 401 | + hev: i32, | ||
| 402 | + size: usize, | ||
| 403 | +) { | ||
| 404 | + for row in 0..8 * size { | ||
| 405 | + let a = anchor + row * stride; | ||
| 406 | + debug_assert!(a >= 4 && a + 3 < plane.len()); | ||
| 407 | + let px = [ | ||
| 408 | + i32::from(plane[a - 4]), | ||
| 409 | + i32::from(plane[a - 3]), | ||
| 410 | + i32::from(plane[a - 2]), | ||
| 411 | + i32::from(plane[a - 1]), | ||
| 412 | + i32::from(plane[a]), | ||
| 413 | + i32::from(plane[a + 1]), | ||
| 414 | + i32::from(plane[a + 2]), | ||
| 415 | + i32::from(plane[a + 3]), | ||
| 416 | + ]; | ||
| 417 | + if !normal_threshold(&px, center_limit, interior) { | ||
| 418 | + continue; | ||
| 419 | + } | ||
| 420 | + let [_, p2, p1, p0, q0, q1, q2, _] = px; | ||
| 421 | + if high_edge_variance(p1, p0, q0, q1, hev) { | ||
| 422 | + // dixie: filter_common with outer taps (p1/q1 unchanged). | ||
| 423 | + let f = filter_common(p1, p0, q0, q1, true); | ||
| 424 | + plane[a - 2] = f[0] as u8; | ||
| 425 | + plane[a - 1] = f[1] as u8; | ||
| 426 | + plane[a] = f[2] as u8; | ||
| 427 | + plane[a + 1] = f[3] as u8; | ||
| 428 | + } else { | ||
| 429 | + let m = filter_mb_edge(p2, p1, p0, q0, q1, q2); | ||
| 430 | + plane[a - 3] = m[0] as u8; | ||
| 431 | + plane[a - 2] = m[1] as u8; | ||
| 432 | + plane[a - 1] = m[2] as u8; | ||
| 433 | + plane[a] = m[3] as u8; | ||
| 434 | + plane[a + 1] = m[4] as u8; | ||
| 435 | + plane[a + 2] = m[5] as u8; | ||
| 436 | + } | ||
| 437 | + } | ||
| 438 | +} | ||
| 439 | + | ||
| 440 | +/// dixie `filter_subblock_v_edge`: vertical subblock edge, normal filter. | ||
| 441 | +fn filter_subblock_v_edge( | ||
| 442 | + plane: &mut [u8], | ||
| 443 | + stride: usize, | ||
| 444 | + anchor: usize, | ||
| 445 | + center_limit: i32, | ||
| 446 | + interior: i32, | ||
| 447 | + hev: i32, | ||
| 448 | + size: usize, | ||
| 449 | +) { | ||
| 450 | + for row in 0..8 * size { | ||
| 451 | + let a = anchor + row * stride; | ||
| 452 | + debug_assert!(a >= 4 && a + 3 < plane.len()); | ||
| 453 | + let px = [ | ||
| 454 | + i32::from(plane[a - 4]), | ||
| 455 | + i32::from(plane[a - 3]), | ||
| 456 | + i32::from(plane[a - 2]), | ||
| 457 | + i32::from(plane[a - 1]), | ||
| 458 | + i32::from(plane[a]), | ||
| 459 | + i32::from(plane[a + 1]), | ||
| 460 | + i32::from(plane[a + 2]), | ||
| 461 | + i32::from(plane[a + 3]), | ||
| 462 | + ]; | ||
| 463 | + if normal_threshold(&px, center_limit, interior) { | ||
| 464 | + let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev); | ||
| 465 | + let f = filter_common(px[2], px[3], px[4], px[5], outer); | ||
| 466 | + plane[a - 2] = f[0] as u8; | ||
| 467 | + plane[a - 1] = f[1] as u8; | ||
| 468 | + plane[a] = f[2] as u8; | ||
| 469 | + plane[a + 1] = f[3] as u8; | ||
| 470 | + } | ||
| 471 | + } | ||
| 472 | +} | ||
| 473 | + | ||
| 474 | +/// dixie `filter_mb_h_edge`: horizontal MB edge, normal filter. | ||
| 475 | +fn filter_mb_h_edge( | ||
| 476 | + plane: &mut [u8], | ||
| 477 | + stride: usize, | ||
| 478 | + anchor: usize, | ||
| 479 | + center_limit: i32, | ||
| 480 | + interior: i32, | ||
| 481 | + hev: i32, | ||
| 482 | + size: usize, | ||
| 483 | +) { | ||
| 484 | + for i in 0..8 * size { | ||
| 485 | + let a = anchor + i; | ||
| 486 | + debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len()); | ||
| 487 | + let px = [ | ||
| 488 | + i32::from(plane[a - 4 * stride]), | ||
| 489 | + i32::from(plane[a - 3 * stride]), | ||
| 490 | + i32::from(plane[a - 2 * stride]), | ||
| 491 | + i32::from(plane[a - stride]), | ||
| 492 | + i32::from(plane[a]), | ||
| 493 | + i32::from(plane[a + stride]), | ||
| 494 | + i32::from(plane[a + 2 * stride]), | ||
| 495 | + i32::from(plane[a + 3 * stride]), | ||
| 496 | + ]; | ||
| 497 | + if !normal_threshold(&px, center_limit, interior) { | ||
| 498 | + continue; | ||
| 499 | + } | ||
| 500 | + let [_, p2, p1, p0, q0, q1, q2, _] = px; | ||
| 501 | + if high_edge_variance(p1, p0, q0, q1, hev) { | ||
| 502 | + let f = filter_common(p1, p0, q0, q1, true); | ||
| 503 | + plane[a - 2 * stride] = f[0] as u8; | ||
| 504 | + plane[a - stride] = f[1] as u8; | ||
| 505 | + plane[a] = f[2] as u8; | ||
| 506 | + plane[a + stride] = f[3] as u8; | ||
| 507 | + } else { | ||
| 508 | + let m = filter_mb_edge(p2, p1, p0, q0, q1, q2); | ||
| 509 | + plane[a - 3 * stride] = m[0] as u8; | ||
| 510 | + plane[a - 2 * stride] = m[1] as u8; | ||
| 511 | + plane[a - stride] = m[2] as u8; | ||
| 512 | + plane[a] = m[3] as u8; | ||
| 513 | + plane[a + stride] = m[4] as u8; | ||
| 514 | + plane[a + 2 * stride] = m[5] as u8; | ||
| 515 | + } | ||
| 516 | + } | ||
| 517 | +} | ||
| 518 | + | ||
| 519 | +/// dixie `filter_subblock_h_edge`: horizontal subblock edge, normal filter. | ||
| 520 | +fn filter_subblock_h_edge( | ||
| 521 | + plane: &mut [u8], | ||
| 522 | + stride: usize, | ||
| 523 | + anchor: usize, | ||
| 524 | + center_limit: i32, | ||
| 525 | + interior: i32, | ||
| 526 | + hev: i32, | ||
| 527 | + size: usize, | ||
| 528 | +) { | ||
| 529 | + for i in 0..8 * size { | ||
| 530 | + let a = anchor + i; | ||
| 531 | + debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len()); | ||
| 532 | + let px = [ | ||
| 533 | + i32::from(plane[a - 4 * stride]), | ||
| 534 | + i32::from(plane[a - 3 * stride]), | ||
| 535 | + i32::from(plane[a - 2 * stride]), | ||
| 536 | + i32::from(plane[a - stride]), | ||
| 537 | + i32::from(plane[a]), | ||
| 538 | + i32::from(plane[a + stride]), | ||
| 539 | + i32::from(plane[a + 2 * stride]), | ||
| 540 | + i32::from(plane[a + 3 * stride]), | ||
| 541 | + ]; | ||
| 542 | + if normal_threshold(&px, center_limit, interior) { | ||
| 543 | + let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev); | ||
| 544 | + let f = filter_common(px[2], px[3], px[4], px[5], outer); | ||
| 545 | + plane[a - 2 * stride] = f[0] as u8; | ||
| 546 | + plane[a - stride] = f[1] as u8; | ||
| 547 | + plane[a] = f[2] as u8; | ||
| 548 | + plane[a + stride] = f[3] as u8; | ||
| 549 | + } | ||
| 550 | + } | ||
| 551 | +} | ||
| 552 | + | ||
| 553 | +/// dixie `filter_v_edge_simple`: vertical edge, simple filter (2-tap; | ||
| 554 | +/// consumes the combined limit directly, touches only p0/q0). | ||
| 555 | +fn filter_v_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i32) { | ||
| 556 | + for row in 0..16 { | ||
| 557 | + let a = anchor + row * stride; | ||
| 558 | + debug_assert!(a >= 2 && a + 1 < plane.len()); | ||
| 559 | + let p1 = i32::from(plane[a - 2]); | ||
| 560 | + let p0 = i32::from(plane[a - 1]); | ||
| 561 | + let q0 = i32::from(plane[a]); | ||
| 562 | + let q1 = i32::from(plane[a + 1]); | ||
| 563 | + if simple_threshold(p1, p0, q0, q1, limit) { | ||
| 564 | + let f = filter_common(p1, p0, q0, q1, true); | ||
| 565 | + plane[a - 1] = f[1] as u8; | ||
| 566 | + plane[a] = f[2] as u8; | ||
| 567 | + } | ||
| 568 | + } | ||
| 569 | +} | ||
| 570 | + | ||
| 571 | +/// dixie `filter_h_edge_simple`: horizontal edge, simple filter. | ||
| 572 | +fn filter_h_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i32) { | ||
| 573 | + for i in 0..16 { | ||
| 574 | + let a = anchor + i; | ||
| 575 | + debug_assert!(a >= 2 * stride && a + stride < plane.len()); | ||
| 576 | + let p1 = i32::from(plane[a - 2 * stride]); | ||
| 577 | + let p0 = i32::from(plane[a - stride]); | ||
| 578 | + let q0 = i32::from(plane[a]); | ||
| 579 | + let q1 = i32::from(plane[a + stride]); | ||
| 580 | + if simple_threshold(p1, p0, q0, q1, limit) { | ||
| 581 | + let f = filter_common(p1, p0, q0, q1, true); | ||
| 582 | + plane[a - stride] = f[1] as u8; | ||
| 583 | + plane[a] = f[2] as u8; | ||
| 584 | + } | ||
| 585 | + } | ||
| 586 | +} | ||
| 587 | + | ||
| 588 | +#[cfg(test)] | ||
| 589 | +mod tests { | ||
| 590 | + use super::*; | ||
| 591 | + | ||
| 592 | + // ----------------------------------------------------------------------- | ||
| 593 | + // Python reference model — the SAME integer math used to derive every | ||
| 594 | + // expected vector below (transcribed from dixie_loopfilter.c, RFC 6386 | ||
| 595 | + // §20.6; control params from §15.4 / libvpx vp8_loopfilter.c). Run to | ||
| 596 | + // regenerate the constants in these tests. | ||
| 597 | + // | ||
| 598 | + // def sat_i8(x): return -128 if x < -128 else (127 if x > 127 else x) | ||
| 599 | + // def sat_u8(x): return 0 if x < 0 else (255 if x > 255 else x) | ||
| 600 | + // | ||
| 601 | + // def simple_threshold(p1, p0, q0, q1, limit): | ||
| 602 | + // return (abs(p0 - q0) * 2 + (abs(p1 - q1) >> 1)) <= limit | ||
| 603 | + // | ||
| 604 | + // def normal_threshold(p3, p2, p1, p0, q0, q1, q2, q3, E, I): | ||
| 605 | + // return simple_threshold(p1, p0, q0, q1, 2 * E + I) and \ | ||
| 606 | + // abs(p3 - p2) <= I and abs(p2 - p1) <= I and abs(p1 - p0) <= I and \ | ||
| 607 | + // abs(q3 - q2) <= I and abs(q2 - q1) <= I and abs(q1 - q0) <= I | ||
| 608 | + // | ||
| 609 | + // def high_edge_variance(p1, p0, q0, q1, t): | ||
| 610 | + // return abs(p1 - p0) > t or abs(q1 - q0) > t | ||
| 611 | + // | ||
| 612 | + // def filter_common(p1, p0, q0, q1, outer): | ||
| 613 | + // a = 3 * (q0 - p0) | ||
| 614 | + // if outer: a += sat_i8(p1 - q1) | ||
| 615 | + // a = sat_i8(a) | ||
| 616 | + // f1 = (127 if a + 4 > 127 else a + 4) >> 3 | ||
| 617 | + // f2 = (127 if a + 3 > 127 else a + 3) >> 3 | ||
| 618 | + // p0 = sat_u8(p0 + f2); q0 = sat_u8(q0 - f1) | ||
| 619 | + // if not outer: | ||
| 620 | + // a = (f1 + 1) >> 1 | ||
| 621 | + // p1 = sat_u8(p1 + a); q1 = sat_u8(q1 - a) | ||
| 622 | + // return p1, p0, q0, q1 | ||
| 623 | + // | ||
| 624 | + // def filter_mb_edge(p2, p1, p0, q0, q1, q2): | ||
| 625 | + // w = sat_i8(sat_i8(p1 - q1) + 3 * (q0 - p0)) | ||
| 626 | + // a = (27 * w + 63) >> 7; p0 = sat_u8(p0 + a); q0 = sat_u8(q0 - a) | ||
| 627 | + // a = (18 * w + 63) >> 7; p1 = sat_u8(p1 + a); q1 = sat_u8(q1 - a) | ||
| 628 | + // a = (9 * w + 63) >> 7; p2 = sat_u8(p2 + a); q2 = sat_u8(q2 - a) | ||
| 629 | + // return p2, p1, p0, q0, q1, q2 | ||
| 630 | + // | ||
| 631 | + // def interior_limit(level, sharpness): | ||
| 632 | + // il = level | ||
| 633 | + // if sharpness: | ||
| 634 | + // il >>= (2 if sharpness > 4 else 1) | ||
| 635 | + // if il > 9 - sharpness: il = 9 - sharpness | ||
| 636 | + // return il if il >= 1 else 1 | ||
| 637 | + // | ||
| 638 | + // def hev_threshold(level, key): | ||
| 639 | + // if key: return 2 if level >= 40 else (1 if level >= 15 else 0) | ||
| 640 | + // return 3 if level >= 40 else (2 if level >= 20 else (1 if level >= 15 else 0)) | ||
| 641 | + // | ||
| 642 | + // # update_sharpness: inside = lvl >> (s>0) >> (s>4), capped at 9-s | ||
| 643 | + // # (only when s>0), min 1; lim=inside, blim=2*lvl+inside, | ||
| 644 | + // # mblim=2*(lvl+2)+inside. | ||
| 645 | + // # | ||
| 646 | + // # Edge walkers mirror the Rust walkers: per row (V) / column (H), | ||
| 647 | + // # threshold -> hev ? filter_common(outer=True) : filter_mb_edge for | ||
| 648 | + // # MB edges, threshold -> filter_common(hev) for subblock edges, | ||
| 649 | + // # threshold -> filter_common(True) touching p0/q0 only for simple. | ||
| 650 | + // # Driver: row-major MBs, per MB [V-mb, V+4, V+8, V+12, H-mb, | ||
| 651 | + // # H+4r, H+8r, H+12r] guarded by col>0 / inner / row>0 / inner | ||
| 652 | + // # (dixie filter_row_normal / filter_row_simple). | ||
| 653 | + // ----------------------------------------------------------------------- | ||
| 654 | + | ||
| 655 | + /// Decode a (possibly newline-wrapped) hex string into bytes. | ||
| 656 | + fn unhex(s: &str) -> Vec<u8> { | ||
| 657 | + let hexed: String = s.chars().filter(char::is_ascii_hexdigit).collect(); | ||
| 658 | + (0..hexed.len() / 2) | ||
| 659 | + .map(|i| u8::from_str_radix(&hexed[2 * i..2 * i + 2], 16).unwrap()) | ||
| 660 | + .collect() | ||
| 661 | + } | ||
| 662 | + | ||
| 663 | + /// The shared 2x2-MB driver scene: `y = (x*7) ^ (y*13 + 37)`, | ||
| 664 | + /// `u = x*3 + y*5 + 11`, `v = x*5 + y*3 + 77` (all mod 256). | ||
| 665 | + fn scene() -> (Vec<u8>, Vec<u8>, Vec<u8>) { | ||
| 666 | + let (stride, uv_stride) = (32usize, 16usize); | ||
| 667 | + let mut y = vec![0u8; stride * 32]; | ||
| 668 | + let mut u = vec![0u8; uv_stride * 16]; | ||
| 669 | + let mut v = vec![0u8; uv_stride * 16]; | ||
| 670 | + for ty in 0..32usize { | ||
| 671 | + for tx in 0..32usize { | ||
| 672 | + y[ty * stride + tx] = (((tx * 7) ^ (ty * 13 + 37)) & 0xFF) as u8; | ||
| 673 | + } | ||
| 674 | + } | ||
| 675 | + for ty in 0..16usize { | ||
| 676 | + for tx in 0..16usize { | ||
| 677 | + u[ty * uv_stride + tx] = ((tx * 3 + ty * 5 + 11) & 0xFF) as u8; | ||
| 678 | + v[ty * uv_stride + tx] = ((tx * 5 + ty * 3 + 77) & 0xFF) as u8; | ||
| 679 | + } | ||
| 680 | + } | ||
| 681 | + (y, u, v) | ||
| 682 | + } | ||
| 683 | + | ||
| 684 | + const NORMAL_Y: &str = "\ | ||
| 685 | +25222b3039060f141d1a6368717e474c55525ba0a9b6bf848d8a9398e1eef7fc32353c272e1118030a0d747f6669505b42454cb7bea1a8939a9d848ff6f9e0eb | ||
| 686 | +3f38312a231c150e070079726b645d564f4841bab3aca59e97908982fbf4ede64c4b4259506f667d74730a0118172e253c3b32c9c0dfd6ede4e3faf188879e95 | ||
| 687 | +595e574c457a736861661f140d023b30292e27dcd5cac3f8f1f6efe49d928b80666168737a454c575e59202b323d040f161118e3eaf5fcc7cec9d0dba2adb4bf | ||
| 688 | +73747d666f5059424b4c353e2728111a03040df6ffe0e9d2dbdcc5ceb7b8a1aa80878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b5259 | ||
| 689 | +8d8a839891aea7bcb5b2cbc0d9d6efe4fdfaf308011e172c25223b3049465f549a9d948f86b9b0aba2a5dcd7cec1f8f3eaede41f1609003b32352c275e514843 | ||
| 690 | +a7a0a9b2bb848d969f98e1eaf3fcc5ced7d0d9222b343d060f08111a636c757eb4b3baa1a8979e858c8bf2f9e0efd6ddc4c3ca3138272e151c1b0209707f666d | ||
| 691 | +c1c6cfd4dde2ebf0f9fe878c959aa3a8b1b6bf444d525b60696e777c050a1318cec9c0dbd2ede4fff6f188839a95aca7beb9b04b425d546f666178730a051c17 | ||
| 692 | +dbdcd5cec7f8f1eae3e49d968f80b9b2abaca55e5748417a73746d661f100902e8efe6fdf4cbc2d9d0d7aea5bcb38a81989f966d647b724940475e552c233a31 | ||
| 693 | +f5f2fbe0e9d6dfc4cdcab3b8a1ae979c85828b7079666f545d5a4348313e272c02050c171e2128333a3d444f5659606b72757c878e9198a3aaadb4bfc6c9d0db | ||
| 694 | +0f08011a132c253e373049425b546d667f78718a839c95aea7a0b9b2cbc4ddd61c1b1209003f362d24235a5148477e756c6b6299908f86bdb4b3aaa1d8d7cec5 | ||
| 695 | +292e273c350a031811166f647d724b40595e57aca5bab38881869f94ede2fbf0363138232a151c070e09707b626d545f464148b3baa5ac979e99808bf2fde4ef | ||
| 696 | +43444d565f6069727b7c050e1718212a33343dc6cfd0d9e2ebecf5fe8788919a50575e454c737a61686f161d040b323920272ed5dcc3caf1f8ffe6ed949b8289 | ||
| 697 | +5d5a5348417e776c65621b1009063f342d2a23d8d1cec7fcf5f2ebe099968f846a6d647f7649405b52552c273e3108031a1d14efe6f9f0cbc2c5dcd7aea1b8b3 | ||
| 698 | +777079626b545d464f48313a232c151e070009f2fbe4edd6dfd8c1cab3bca5ae84838a9198a7aeb5bcbbc2c9d0dfe6edf4f3fa0108171e252c2b3239404f565d | ||
| 699 | +91969f848db2bba0a9aed7dcc5caf3f8e1e6ef141d020b30393e272c555a43489e99908b82bdb4afa6a1d8d3cac5fcf7eee9e01b120d043f363128235a554c47 | ||
| 700 | +abaca5beb788819a9394ede6fff0c9c2dbdcd52e2738310a03041d166f607972b8bfb6ada49b92898087fef5ece3dad1c8cfc63d342b221910170e057c736a61"; | ||
| 701 | + | ||
| 702 | + const NORMAL_U: &str = "\ | ||
| 703 | +0b0e1114171a1d202326292c2f323538101316191c1f2225282b2e3134373a3d15181b1e2124272a2d303336393c3f421a1d202326292c2f3235383b3e414447 | ||
| 704 | +1f2225282b2e3134373a3d404346494c24272a2d303336393c3f4245484b4e51292c2f3235383b3e4144474a4d5053562e3134373a3d404346494c4f5255585b | ||
| 705 | +3336393c3f4245484b4e5154575a5d60383b3e4144474a4d505356595c5f62653d404346494c4f5255585b5e6164676a4245484b4e5154575a5d606366696c6f | ||
| 706 | +474a4d505356595c5f6265686b6e71744c4f5255585b5e6164676a6d707376795154575a5d606366696c6f7275787b7e56595c5f6265686b6e7174777a7d8083"; | ||
| 707 | + | ||
| 708 | + const NORMAL_V: &str = "\ | ||
| 709 | +4d52575c61666b70757a7f84898e939850555a5f64696e73787d82878c91969b53585d62676c71767b80858a8f94999e565b60656a6f74797e83888d92979ca1 | ||
| 710 | +595e63686d72777c81868b90959a9fa45c61666b70757a7f84898e93989da2a75f64696e73787d82878c91969ba0a5aa62676c71767b80858a8f94999ea3a8ad | ||
| 711 | +656a6f74797e83888d92979ca1a6abb0686d72777c81868b90959a9fa4a9aeb36b70757a7f84898e93989da2a7acb1b66e73787d82878c91969ba0a5aaafb4b9 | ||
| 712 | +71767b80858a8f94999ea3a8adb2b7bc74797e83888d92979ca1a6abb0b5babf777c81868b90959a9fa4a9aeb3b8bdc27a7f84898e93989da2a7acb1b6bbc0c5"; | ||
| 713 | + | ||
| 714 | + const SIMPLE_Y: &str = "\ | ||
| 715 | +25222b3831060f161b1a6368717e474e53525ba0a9b6bf8e838a9398e1eef7fc32353c2f26111807060d74776e6950534a454cafc6a1a897969d848ff6f9e0eb | ||
| 716 | +3f38312a231c150e070079726b645d564f4841bab3aca59e97908982fbf4ede64c4d4250596e647879730a0816172e343a3d33cbc0dfd6e4eae3edf188949e95 | ||
| 717 | +595c57454c7b756762661f1507023b27252c26dad5cac3f3f9f6fce49d858b806661687a73454c585d59202a333d0410151118e3eaf5fcd0c5c9d0dba2adb4bf | ||
| 718 | +73747d6f66505947464c35372e2811130a040df6ffe0e9d7d6dcc5c7beb8a1aa8083879096a39eb1adbfc6cdd4dbe2e9f0f7fe050c131a21282f363d4f4b5259 | ||
| 719 | +8d8e8a959faeb3b8c4b2cbc8d1d6efecf5faf308011e172829223b3836465f549a9d94878eb9b0a9a4a5dcd7cec1f8f1ecede41f160900313c352c275e514843 | ||
| 720 | +a7a0a9bab3848d989d98e1eaf3fcc5d0d5d0d9222b343d100508111a636c757eb4b5bfa8a1979e8a878bf2f0e9efd6d6cbc1cb333d272e1a171b0209707f666d | ||
| 721 | +c1c4cad5dce2ebf1f8fe878d949aa3a9b0b8be4248525b61686e777c050a1318cec9c0d2dbede4fafbf1888a9395acaeb7b9b04b425d546a6b6178730a051c17 | ||
| 722 | +dbdcd5c7cef8f1e9e4e49d978e80b9b1acaca55e574841717c746d661f100902e8efe6fdf4cbc2d3d6d7bbb7b7b68a87979f976c627b664a3e475e552c233a31 | ||
| 723 | +f5f2fbe8e1d6dfcac7caa6a6a6ab979686828a7973667b5b575a4340393e272c02050c171e2128333a3d444f5659606b72757c878e9198a3aaadb4bfc6c9d0db | ||
| 724 | +0f0801121b2c253a3b30494a53546d6e777871828b9c95aaaba0b9bac3c4ddd61c1d1200093f362c26235a5049477e746d6d6390988f86b4bdb3ada2d8d4cec5 | ||
| 725 | +292c273d340a031315166f6d74724b47525c56aca6bab38b7e869c93ede5fbf03631382a23151c0c090970726b6d54584d4148b3baa5ac9c9999808bf2fde4ef | ||
| 726 | +43444d575e6069737a7c050f1618212b32343dc6cfd0d9e3eaecf5fe8788919a5053573e487a7e6b696f130f07063a3c292b2fd1d5c2c6f2ffffebed91968284 | ||
| 727 | +5d5e5a474d77736660621e160e0b3731242622dcd8cfcbeff7f2e6e09c9b8f896a6d647f7649405558552c2f36310809141d14efe6f9f0cdc0c5dcd7aea1b8b3 | ||
| 728 | +7770796a63545d4c494831322b2c15180d0009f2fbe4eddcd9d8c1c2bbbca5ae84858f898fa7aeb6bbbbc2c8d1dfe6eef3f3fa0108171e262b2b3238414f565d | ||
| 729 | +91949a8c96b2bba5a4aed7d5cccaf3f1e8e6ef141d020b2d3c3e272c555a43489e9990828bbdb4aea7a1d8d2cbc5fcf6efe9e01b120d04363f3128235a554c47 | ||
| 730 | +abaca5bfb68881959894edeff6f0c9c9d4dcd52e2738310d00041d166f607972b8bfb6ada49b92878287fef5ece3dacfcacfc63d342b221712170e057c736a61"; | ||
| 731 | + | ||
| 732 | + /// Table sanity: lengths plus entries hand-derived from libvpx | ||
| 733 | + /// `vp8_loop_filter_update_sharpness` (vp8/common/vp8_loopfilter.c | ||
| 734 | + /// L49-75): inside = lvl >> (s>0) >> (s>4), capped at 9-s when s>0, | ||
| 735 | + /// min 1; lim=inside, blim=2*lvl+inside, mblim=2*(lvl+2)+inside. | ||
| 736 | + #[test] | ||
| 737 | + fn sharpness_tables_match_libvpx() { | ||
| 738 | + let t0 = LoopFilterTables::update_sharpness(0); | ||
| 739 | + assert_eq!(t0.lim.len(), 64); | ||
| 740 | + assert_eq!(t0.blim.len(), 64); | ||
| 741 | + assert_eq!(t0.mblim.len(), 64); | ||
| 742 | + // sharpness 0: lvl 0 -> (1, 1, 5), lvl 1 -> (1, 3, 7), | ||
| 743 | + // lvl 15 -> (15, 45, 49), lvl 63 -> (63, 189, 193). | ||
| 744 | + assert_eq!((t0.lim[0], t0.blim[0], t0.mblim[0]), (1, 1, 5)); | ||
| 745 | + assert_eq!((t0.lim[1], t0.blim[1], t0.mblim[1]), (1, 3, 7)); | ||
| 746 | + assert_eq!((t0.lim[15], t0.blim[15], t0.mblim[15]), (15, 45, 49)); | ||
| 747 | + assert_eq!((t0.lim[63], t0.blim[63], t0.mblim[63]), (63, 189, 193)); | ||
| 748 | + // sharpness 5: inside = lvl >> 2 capped at 4: | ||
| 749 | + // lvl 3 -> (1, 7, 11), lvl 20 -> (4, 44, 48), lvl 63 -> (4, 130, 134). | ||
| 750 | + let t5 = LoopFilterTables::update_sharpness(5); | ||
| 751 | + assert_eq!((t5.lim[3], t5.blim[3], t5.mblim[3]), (1, 7, 11)); | ||
| 752 | + assert_eq!((t5.lim[20], t5.blim[20], t5.mblim[20]), (4, 44, 48)); | ||
| 753 | + assert_eq!((t5.lim[63], t5.blim[63], t5.mblim[63]), (4, 130, 134)); | ||
| 754 | + // sharpness 7: inside capped at 2: | ||
| 755 | + // lvl 4 -> (1, 9, 13), lvl 20 -> (2, 42, 46). | ||
| 756 | + let t7 = LoopFilterTables::update_sharpness(7); | ||
| 757 | + assert_eq!((t7.lim[4], t7.blim[4], t7.mblim[4]), (1, 9, 13)); | ||
| 758 | + assert_eq!((t7.lim[20], t7.blim[20], t7.mblim[20]), (2, 42, 46)); | ||
| 759 | + // The standalone helper must agree with the table for every level. | ||
| 760 | + for sharpness in 0..=7u8 { | ||
| 761 | + let t = LoopFilterTables::update_sharpness(sharpness); | ||
| 762 | + for level in 0..=63u8 { | ||
| 763 | + assert_eq!( | ||
| 764 | + interior_limit(level, sharpness), | ||
| 765 | + i32::from(t.lim[level as usize]) | ||
| 766 | + ); | ||
| 767 | + } | ||
| 768 | + } | ||
| 769 | + } | ||
| 770 | + | ||
| 771 | + /// §15.4 hev table (libvpx `lf_init_lut`): key 0/1/1/2 and inter | ||
| 772 | + /// 0/1/2/3 at levels 0/15/20/40 respectively. | ||
| 773 | + #[test] | ||
| 774 | + fn hev_threshold_table() { | ||
| 775 | + for level in [0u8, 14, 15, 19, 20, 39, 40, 63] { | ||
| 776 | + let l = i32::from(level); | ||
| 777 | + let want_key = if l >= 40 { | ||
| 778 | + 2 | ||
| 779 | + } else if l >= 15 { | ||
| 780 | + 1 | ||
| 781 | + } else { | ||
| 782 | + 0 | ||
| 783 | + }; | ||
| 784 | + let want_inter = if l >= 40 { | ||
| 785 | + 3 | ||
| 786 | + } else if l >= 20 { | ||
| 787 | + 2 | ||
| 788 | + } else if l >= 15 { | ||
| 789 | + 1 | ||
| 790 | + } else { | ||
| 791 | + 0 | ||
| 792 | + }; | ||
| 793 | + assert_eq!(hev_threshold(level, true), want_key); | ||
| 794 | + assert_eq!(hev_threshold(level, false), want_inter); | ||
| 795 | + } | ||
| 796 | + assert_eq!(hev_threshold(39, true), 1); | ||
| 797 | + assert_eq!(hev_threshold(39, false), 2); | ||
| 798 | + } | ||
| 799 | + | ||
| 800 | + /// Level 0 disables all filtering: a noisy frame is byte-identical. | ||
| 801 | + #[test] | ||
| 802 | + fn level_zero_disables_filtering() { | ||
| 803 | + let (y0, u0, v0) = scene(); | ||
| 804 | + let mut y = y0.clone(); | ||
| 805 | + let mut u = u0.clone(); | ||
| 806 | + let mut v = v0.clone(); | ||
| 807 | + filter_frame( | ||
| 808 | + &mut y, | ||
| 809 | + &mut u, | ||
| 810 | + &mut v, | ||
| 811 | + 32, | ||
| 812 | + 16, | ||
| 813 | + 2, | ||
| 814 | + 2, | ||
| 815 | + 1, | ||
| 816 | + false, | ||
| 817 | + &[MbFilterInfo { | ||
| 818 | + level: 0, | ||
| 819 | + inner_edges: true, | ||
| 820 | + }; 4], | ||
| 821 | + ); | ||
| 822 | + assert_eq!(y, y0); | ||
| 823 | + assert_eq!(u, u0); | ||
| 824 | + assert_eq!(v, v0); | ||
| 825 | + } | ||
| 826 | + | ||
| 827 | + /// Kernel: normal filter, vertical MB edge, non-hev wide path. | ||
| 828 | + /// Level 30, sharpness 0 -> interior 30, mblim = 2*32+30 = 94, hev = 2. | ||
| 829 | + /// Patch: cols < 16 = 110, cols >= 16 = 130. Python model row: | ||
| 830 | + /// w = sat_i8(-20 + 3*20) = 40; a27 = (1080+63)>>7 = 8, a18 = 6, | ||
| 831 | + /// a9 = 3 -> [110, 113, 116, 118 | 122, 124, 127, 130] at cols 12..19. | ||
| 832 | + #[test] | ||
| 833 | + fn mb_v_edge_normal_filter_kernel() { | ||
| 834 | + let mut y = vec![0u8; 32 * 16]; | ||
| 835 | + for r in 0..16 { | ||
| 836 | + for c in 0..32 { | ||
| 837 | + y[r * 32 + c] = if c < 16 { 110 } else { 130 }; | ||
| 838 | + } | ||
| 839 | + } | ||
| 840 | + let mut u = vec![128u8; 16 * 8]; | ||
| 841 | + let mut v = vec![128u8; 16 * 8]; | ||
| 842 | + filter_frame( | ||
| 843 | + &mut y, | ||
| 844 | + &mut u, | ||
| 845 | + &mut v, | ||
| 846 | + 32, | ||
| 847 | + 16, | ||
| 848 | + 2, | ||
| 849 | + 1, | ||
| 850 | + 0, | ||
| 851 | + false, | ||
| 852 | + &[MbFilterInfo { | ||
| 853 | + level: 30, | ||
| 854 | + inner_edges: false, | ||
| 855 | + }; 2], | ||
| 856 | + ); | ||
| 857 | + for r in 0..16 { | ||
| 858 | + assert_eq!( | ||
| 859 | + &y[r * 32 + 12..r * 32 + 20], | ||
| 860 | + &[110, 113, 116, 118, 122, 124, 127, 130], | ||
| 861 | + "row {r}" | ||
| 862 | + ); | ||
| 863 | + } | ||
| 864 | + // Flat chroma planes are untouched (all filter deltas are 0). | ||
| 865 | + assert!(u.iter().all(|&b| b == 128)); | ||
| 866 | + assert!(v.iter().all(|&b| b == 128)); | ||
| 867 | + } | ||
| 868 | + | ||
| 869 | + /// Kernel: hev edge takes the simple ±f path (p1/q1 unchanged). | ||
| 870 | + /// Level 15, sharpness 0 -> interior 15, mblim = 2*17+15 = 49, hev = 1. | ||
| 871 | + /// |p1-p0| = 2 > 1 triggers hev; Python model: a = 3*16 - 10 = 38, | ||
| 872 | + /// f1 = 42>>3 = 5, f2 = 41>>3 = 5. | ||
| 873 | + #[test] | ||
| 874 | + fn hev_edge_takes_short_path() { | ||
| 875 | + let mut plane = vec![0u8; 8 * 8]; | ||
| 876 | + for r in 0..8 { | ||
| 877 | + plane[r * 8..r * 8 + 8].copy_from_slice(&[101, 101, 102, 100, 116, 112, 112, 113]); | ||
| 878 | + } | ||
| 879 | + // Anchor: q0 at (row 0, col 4); 8 rows, one segment. | ||
| 880 | + filter_mb_v_edge( | ||
| 881 | + &mut plane, | ||
| 882 | + 8, | ||
| 883 | + 4, | ||
| 884 | + 2 * (15 + 2) + 15, | ||
| 885 | + 15, | ||
| 886 | + hev_threshold(15, false), | ||
| 887 | + 1, | ||
| 888 | + ); | ||
| 889 | + assert_eq!(&plane[0..8], &[101, 101, 102, 105, 111, 112, 112, 113]); | ||
| 890 | + // Outer-tap path leaves the inner taps alone. | ||
| 891 | + assert_eq!(plane[8 + 2], 102); | ||
| 892 | + assert_eq!(plane[8 + 5], 112); | ||
| 893 | + } | ||
| 894 | + | ||
| 895 | + /// Kernel: non-hev subblock edge runs the full path incl. p1/q1. | ||
| 896 | + /// Level 15, sharpness 0 -> interior 15, blim = 2*15+15 = 45. | ||
| 897 | + /// Python model: a = 3*10 = 30, f1 = 34>>3 = 4, f2 = 33>>3 = 4, | ||
| 898 | + /// inner a = (4+1)>>1 = 2. | ||
| 899 | + #[test] | ||
| 900 | + fn subblock_edge_takes_full_three_tap_path() { | ||
| 901 | + let mut plane = vec![0u8; 8 * 8]; | ||
| 902 | + for r in 0..8 { | ||
| 903 | + plane[r * 8..r * 8 + 8].copy_from_slice(&[100, 100, 100, 100, 110, 111, 111, 111]); | ||
| 904 | + } | ||
| 905 | + filter_subblock_v_edge( | ||
| 906 | + &mut plane, | ||
| 907 | + 8, | ||
| 908 | + 4, | ||
| 909 | + 2 * 15 + 15, | ||
| 910 | + 15, | ||
| 911 | + hev_threshold(15, false), | ||
| 912 | + 1, | ||
| 913 | + ); | ||
| 914 | + assert_eq!(&plane[0..8], &[100, 100, 102, 104, 106, 109, 111, 111]); | ||
| 915 | + } | ||
| 916 | + | ||
| 917 | + /// Simple filter: MB edge gets f = 5 (mb_limit = 94), subblock edges | ||
| 918 | + /// are filtered too (no-op on flat interiors), chroma is untouched. | ||
| 919 | + #[test] | ||
| 920 | + fn simple_filter_leaves_chroma_untouched() { | ||
| 921 | + let mut y = vec![0u8; 32 * 16]; | ||
| 922 | + for r in 0..16 { | ||
| 923 | + for c in 0..32 { | ||
| 924 | + y[r * 32 + c] = if c < 16 { 110 } else { 130 }; | ||
| 925 | + } | ||
| 926 | + } | ||
| 927 | + let mut u = vec![0u8; 16 * 8]; | ||
| 928 | + let mut v = vec![0u8; 16 * 8]; | ||
| 929 | + for r in 0..8 { | ||
| 930 | + for c in 0..16 { | ||
| 931 | + u[r * 16 + c] = if c < 8 { 100 } else { 150 }; | ||
| 932 | + v[r * 16 + c] = if c < 8 { 90 } else { 170 }; | ||
| 933 | + } | ||
| 934 | + } | ||
| 935 | + let u_orig = u.clone(); | ||
| 936 | + let v_orig = v.clone(); | ||
| 937 | + filter_frame( | ||
| 938 | + &mut y, | ||
| 939 | + &mut u, | ||
| 940 | + &mut v, | ||
| 941 | + 32, | ||
| 942 | + 16, | ||
| 943 | + 2, | ||
| 944 | + 1, | ||
| 945 | + 0, | ||
| 946 | + true, | ||
| 947 | + &[MbFilterInfo { | ||
| 948 | + level: 30, | ||
| 949 | + inner_edges: true, | ||
| 950 | + }; 2], | ||
| 951 | + ); | ||
| 952 | + // a = 3*20 - 20 = 40 -> f1 = 44>>3 = 5, f2 = 43>>3 = 5. | ||
| 953 | + for r in 0..16 { | ||
| 954 | + assert_eq!( | ||
| 955 | + &y[r * 32 + 12..r * 32 + 20], | ||
| 956 | + &[110, 110, 110, 115, 125, 130, 130, 130], | ||
| 957 | + "row {r}" | ||
| 958 | + ); | ||
| 959 | + } | ||
| 960 | + assert_eq!(u, u_orig); | ||
| 961 | + assert_eq!(v, v_orig); | ||
| 962 | + } | ||
| 963 | + | ||
| 964 | + /// Full-frame driver, normal filter: 2x2 MBs, level 25, sharpness 1, | ||
| 965 | + /// inner edges on. The whole frame must equal the Python model output | ||
| 966 | + /// byte-for-byte. Sample (17,17) is q1 of MB(1,1)'s V edge and then q1 | ||
| 967 | + /// of its H edge — the match proves the dixie visit order | ||
| 968 | + /// (V-MB, subblock-V, H-MB, subblock-H) is reproduced. | ||
| 969 | + #[test] | ||
| 970 | + fn driver_normal_filter_frame_order() { | ||
| 971 | + let (y0, u0, v0) = scene(); | ||
| 972 | + let mut y = y0; | ||
| 973 | + let mut u = u0; | ||
| 974 | + let mut v = v0; | ||
| 975 | + filter_frame_ex( | ||
| 976 | + &mut y, | ||
| 977 | + &mut u, | ||
| 978 | + &mut v, | ||
| 979 | + 32, | ||
| 980 | + 16, | ||
| 981 | + 2, | ||
| 982 | + 2, | ||
| 983 | + 1, | ||
| 984 | + false, | ||
| 985 | + &[MbFilterInfo { | ||
| 986 | + level: 25, | ||
| 987 | + inner_edges: true, | ||
| 988 | + }; 4], | ||
| 989 | + false, | ||
| 990 | + ); | ||
| 991 | + assert_eq!(y, unhex(NORMAL_Y)); | ||
| 992 | + assert_eq!(u, unhex(NORMAL_U)); | ||
| 993 | + assert_eq!(v, unhex(NORMAL_V)); | ||
| 994 | + assert_eq!(y[17 * 32 + 17], 0x75, "order-probe pixel (17,17)"); | ||
| 995 | + } | ||
| 996 | + | ||
| 997 | + /// Full-frame driver, simple filter: same scene, Y-only output. | ||
| 998 | + #[test] | ||
| 999 | + fn driver_simple_filter_frame() { | ||
| 1000 | + let (_, u0, v0) = scene(); | ||
| 1001 | + let (mut y, _, _) = scene(); | ||
| 1002 | + let mut u = u0.clone(); | ||
| 1003 | + let mut v = v0.clone(); | ||
| 1004 | + filter_frame( | ||
| 1005 | + &mut y, | ||
| 1006 | + &mut u, | ||
| 1007 | + &mut v, | ||
| 1008 | + 32, | ||
| 1009 | + 16, | ||
| 1010 | + 2, | ||
| 1011 | + 2, | ||
| 1012 | + 1, | ||
| 1013 | + true, | ||
| 1014 | + &[MbFilterInfo { | ||
| 1015 | + level: 25, | ||
| 1016 | + inner_edges: true, | ||
| 1017 | + }; 4], | ||
| 1018 | + ); | ||
| 1019 | + assert_eq!(y, unhex(SIMPLE_Y)); | ||
| 1020 | + assert_eq!(u, u0); | ||
| 1021 | + assert_eq!(v, v0); | ||
| 1022 | + } | ||
| 1023 | + | ||
| 1024 | + /// Frame type matters at level 25 (hev 2 inter / 1 key): a near-tap | ||
| 1025 | + /// difference of exactly 2 takes the wide MBfilter path on inter | ||
| 1026 | + /// frames and the hev ±f path on key frames. Python model rows: | ||
| 1027 | + /// inter 6e6f71706f707071, key 6e6e706f70717171. | ||
| 1028 | + #[test] | ||
| 1029 | + fn frame_type_changes_hev_path() { | ||
| 1030 | + let build = || { | ||
| 1031 | + let mut y = vec![0u8; 32 * 16]; | ||
| 1032 | + for r in 0..16 { | ||
| 1033 | + for c in 0..32 { | ||
| 1034 | + y[r * 32 + c] = if c == 14 { | ||
| 1035 | + 112 | ||
| 1036 | + } else if c < 16 { | ||
| 1037 | + 110 | ||
| 1038 | + } else { | ||
| 1039 | + 113 | ||
| 1040 | + }; | ||
| 1041 | + } | ||
| 1042 | + } | ||
| 1043 | + y | ||
| 1044 | + }; | ||
| 1045 | + let mut uy = vec![128u8; 16 * 8]; | ||
| 1046 | + let mut vy = vec![128u8; 16 * 8]; | ||
| 1047 | + let mut ky = build(); | ||
| 1048 | + let mut uk = uy.clone(); | ||
| 1049 | + let mut vk = vy.clone(); | ||
| 1050 | + let info = [MbFilterInfo { | ||
| 1051 | + level: 25, | ||
| 1052 | + inner_edges: false, | ||
| 1053 | + }; 2]; | ||
| 1054 | + let mut inter = build(); | ||
| 1055 | + filter_frame_ex( | ||
| 1056 | + &mut inter, &mut uy, &mut vy, 32, 16, 2, 1, 1, false, &info, false, | ||
| 1057 | + ); | ||
| 1058 | + filter_frame_ex( | ||
| 1059 | + &mut ky, &mut uk, &mut vk, 32, 16, 2, 1, 1, false, &info, true, | ||
| 1060 | + ); | ||
| 1061 | + assert_eq!(&inter[12..20], &[110, 111, 113, 112, 111, 112, 112, 113]); | ||
| 1062 | + assert_eq!(&ky[12..20], &[110, 110, 112, 111, 112, 113, 113, 113]); | ||
| 1063 | + } | ||
| 1064 | +} | ||
crates/ec-vp8/src/modes.rsadded+311 -0
| @@ -0,0 +1,311 @@ | |||
| 1 | +//! Macroblock prediction modes and their coding trees | ||
| 2 | +//! (RFC 6386 §8.2, §11.2, §11.4, §16.1). | ||
| 3 | + | ||
| 4 | +use crate::bool::BoolDecoder; | ||
| 5 | + | ||
| 6 | +/// Intra macroblock luma modes (RFC 6386 §8.2 enum values are normative; | ||
| 7 | +/// chroma modes are the first four). | ||
| 8 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 9 | +#[repr(u8)] | ||
| 10 | +pub enum YMode { | ||
| 11 | + /// Predict DC from the row above and column to the left. | ||
| 12 | + DcPred = 0, | ||
| 13 | + /// Predict rows from the row above. | ||
| 14 | + VPred = 1, | ||
| 15 | + /// Predict columns from the column to the left. | ||
| 16 | + HPred = 2, | ||
| 17 | + /// True-motion (second-difference) prediction. | ||
| 18 | + TmPred = 3, | ||
| 19 | + /// Each 4x4 Y subblock is independently predicted. | ||
| 20 | + BPred = 4, | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +impl YMode { | ||
| 24 | + /// Value as coded in the trees (the RFC's enum integers). | ||
| 25 | + pub fn as_u8(self) -> u8 { | ||
| 26 | + self as u8 | ||
| 27 | + } | ||
| 28 | + | ||
| 29 | + /// The subblock mode a 16x16 mode masquerades as for B_PRED context | ||
| 30 | + /// purposes (RFC 6386 §11.3 item 4). | ||
| 31 | + pub fn as_bmode(self) -> BMode { | ||
| 32 | + match self { | ||
| 33 | + YMode::DcPred => BMode::BDCPred, | ||
| 34 | + YMode::VPred => BMode::BVEPred, | ||
| 35 | + YMode::HPred => BMode::BHEPred, | ||
| 36 | + YMode::TmPred => BMode::BTMPred, | ||
| 37 | + YMode::BPred => unreachable!("B_PRED has no single subblock mode"), | ||
| 38 | + } | ||
| 39 | + } | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +/// The ten 4x4 subblock prediction modes (RFC 6386 §11.2). | ||
| 43 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 44 | +#[repr(u8)] | ||
| 45 | +pub enum BMode { | ||
| 46 | + /// DC from above row and left column. | ||
| 47 | + BDCPred = 0, | ||
| 48 | + /// True-motion. | ||
| 49 | + BTMPred = 1, | ||
| 50 | + /// Vertical from smoothed above row. | ||
| 51 | + BVEPred = 2, | ||
| 52 | + /// Horizontal from smoothed left column. | ||
| 53 | + BHEPred = 3, | ||
| 54 | + /// Down-left diagonal. | ||
| 55 | + BLDPred = 4, | ||
| 56 | + /// Down-right diagonal. | ||
| 57 | + BRDPred = 5, | ||
| 58 | + /// Vertical-right diagonal. | ||
| 59 | + BVRPred = 6, | ||
| 60 | + /// Vertical-left diagonal. | ||
| 61 | + BVLPred = 7, | ||
| 62 | + /// Horizontal-down diagonal. | ||
| 63 | + BHDPred = 8, | ||
| 64 | + /// Horizontal-up diagonal. | ||
| 65 | + BHUPred = 9, | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +impl BMode { | ||
| 69 | + /// Value as coded in the bmode tree (the RFC's enum integers). | ||
| 70 | + pub fn as_u8(self) -> u8 { | ||
| 71 | + self as u8 | ||
| 72 | + } | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// Key-frame Y-mode coding tree (RFC 6386 §11.2): B_PRED, then the four | ||
| 76 | +/// full-block modes. Leaf values are the [`YMode`] enum integers. | ||
| 77 | +pub const KF_YMODE_TREE: [i8; 8] = [-4, 2, 4, 6, 0, -1, -2, -3]; | ||
| 78 | + | ||
| 79 | +/// Key-frame Y-mode probabilities (fixed; RFC 6386 §11.2 and the | ||
| 80 | +/// reference decoder's `kf_y_mode_probs`). | ||
| 81 | +pub const KF_YMODE_PROBS: [u8; 4] = [145, 156, 163, 128]; | ||
| 82 | + | ||
| 83 | +/// Interframe Y-mode coding tree (RFC 6386 §8.2). | ||
| 84 | +pub const YMODE_TREE: [i8; 8] = [0, 2, 4, 6, -1, -2, -3, -4]; | ||
| 85 | + | ||
| 86 | +/// Chroma-mode coding tree (RFC 6386 §8.2/§11.4): DC, V, H, TM. | ||
| 87 | +pub const UV_MODE_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3]; | ||
| 88 | + | ||
| 89 | +/// Key-frame chroma-mode probabilities (fixed; RFC 6386 §11.4). | ||
| 90 | +pub const KF_UV_MODE_PROBS: [u8; 3] = [142, 114, 183]; | ||
| 91 | + | ||
| 92 | +/// 4x4 subblock-mode coding tree (RFC 6386 §11.2). Leaf values are the | ||
| 93 | +/// [`BMode`] enum integers; note the leaf 0 (B_DC_PRED) relies on the | ||
| 94 | +/// tree reader's `i <= 0` leaf test. | ||
| 95 | +pub const BMODE_TREE: [i8; 18] = [ | ||
| 96 | + 0, 2, // B_DC_PRED = "0" | ||
| 97 | + -1, 4, // B_TM = "10" | ||
| 98 | + -2, 6, // B_VE = "110" | ||
| 99 | + 8, 12, // inner | ||
| 100 | + -3, 10, // B_HE = "11100" | ||
| 101 | + -5, -6, // B_RD = "111010", B_VR = "111011" | ||
| 102 | + -4, 14, // B_LD = "111110" | ||
| 103 | + -7, 16, // B_VL = "1111110" | ||
| 104 | + -8, -9, // B_HD = "11111110", B_HU = "11111111" | ||
| 105 | +]; | ||
| 106 | + | ||
| 107 | +/// Subblock modes in interframes decode with this constant probability | ||
| 108 | +/// array, no context (RFC 6386 §11.3 item 5 / §16). | ||
| 109 | +pub const INTER_BMODE_PROBS: [u8; 9] = [120, 90, 79, 133, 87, 85, 80, 111, 151]; | ||
| 110 | + | ||
| 111 | +/// Decode a key-frame Y mode (RFC 6386 §11.2). | ||
| 112 | +pub fn read_kf_ymode(d: &mut BoolDecoder<'_>) -> YMode { | ||
| 113 | + YMode::from_u8(d.read_tree(&KF_YMODE_TREE, &KF_YMODE_PROBS)) | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +/// Decode an interframe Y mode at the persisted probabilities | ||
| 117 | +/// (RFC 6386 §16.1; `probs` is the frame header's updated array). | ||
| 118 | +pub fn read_ymode(d: &mut BoolDecoder<'_>, probs: &[u8; 4]) -> YMode { | ||
| 119 | + YMode::from_u8(d.read_tree(&YMODE_TREE, probs)) | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// Decode a chroma mode at the given (key-frame fixed or persisted | ||
| 123 | +/// interframe) probabilities. | ||
| 124 | +pub fn read_uvmode(d: &mut BoolDecoder<'_>, probs: &[u8; 3]) -> YMode { | ||
| 125 | + YMode::from_u8(d.read_tree(&UV_MODE_TREE, probs)) | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +/// Decode a 4x4 subblock mode at `probs` (RFC 6386 §11.3: in key frames | ||
| 129 | +/// the probabilities come from the above/left context table). | ||
| 130 | +pub fn read_bmode(d: &mut BoolDecoder<'_>, probs: &[u8]) -> BMode { | ||
| 131 | + BMode::from_u8(d.read_tree(&BMODE_TREE, probs)) | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +impl YMode { | ||
| 135 | + fn from_u8(v: u8) -> YMode { | ||
| 136 | + match v { | ||
| 137 | + 0 => YMode::DcPred, | ||
| 138 | + 1 => YMode::VPred, | ||
| 139 | + 2 => YMode::HPred, | ||
| 140 | + 3 => YMode::TmPred, | ||
| 141 | + 4 => YMode::BPred, | ||
| 142 | + _ => unreachable!("tree cannot produce mode {v}"), | ||
| 143 | + } | ||
| 144 | + } | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +impl BMode { | ||
| 148 | + fn from_u8(v: u8) -> BMode { | ||
| 149 | + match v { | ||
| 150 | + 0 => BMode::BDCPred, | ||
| 151 | + 1 => BMode::BTMPred, | ||
| 152 | + 2 => BMode::BVEPred, | ||
| 153 | + 3 => BMode::BHEPred, | ||
| 154 | + 4 => BMode::BLDPred, | ||
| 155 | + 5 => BMode::BRDPred, | ||
| 156 | + 6 => BMode::BVRPred, | ||
| 157 | + 7 => BMode::BVLPred, | ||
| 158 | + 8 => BMode::BHDPred, | ||
| 159 | + 9 => BMode::BHUPred, | ||
| 160 | + _ => unreachable!("tree cannot produce bmode {v}"), | ||
| 161 | + } | ||
| 162 | + } | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +/// Inter-frame motion-vector reference modes (RFC 6386 §16.2), offset | ||
| 166 | +/// from the intra modes by `num_ymodes` in the reference enum; here they | ||
| 167 | +/// are their own small enum with the RFC's tree integers. | ||
| 168 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 169 | +#[repr(u8)] | ||
| 170 | +pub enum MvRef { | ||
| 171 | + /// Zero motion vector ("10" second branch; coded 0). | ||
| 172 | + Zero = 0, | ||
| 173 | + /// "Nearest" vector (coded 1). | ||
| 174 | + Nearest = 1, | ||
| 175 | + /// "Near" vector (coded 2). | ||
| 176 | + Near = 2, | ||
| 177 | + /// Explicit offset from best (coded 3). | ||
| 178 | + New = 3, | ||
| 179 | + /// Per-subblock vectors (coded 4). | ||
| 180 | + Split = 4, | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +/// mv_ref coding tree (RFC 6386 §16.2): leaves are [`MvRef`] integers. | ||
| 184 | +pub const MV_REF_TREE: [i8; 8] = [0, 2, -1, 4, -2, 6, -3, -4]; | ||
| 185 | + | ||
| 186 | +/// Motion-vector component: row then column, each with the 19-probability | ||
| 187 | +/// table (§17.1). | ||
| 188 | +pub const MVP_IS_SHORT: usize = 0; | ||
| 189 | +pub const MVP_SIGN: usize = 1; | ||
| 190 | +pub const MVP_SHORT: usize = 2; | ||
| 191 | +pub const MVP_BITS: usize = MVP_SHORT + 7; | ||
| 192 | +pub const MVP_COUNT: usize = MVP_BITS + 10; | ||
| 193 | + | ||
| 194 | +/// Small-value coding tree for MV components (§17.1 `small_mvtree`). | ||
| 195 | +pub const SMALL_MV_TREE: [i8; 14] = [ | ||
| 196 | + 2, 8, // "0" / "1" subtrees | ||
| 197 | + 4, 6, // "00" / "01" | ||
| 198 | + 0, -1, // 0 = "000", 1 = "001" | ||
| 199 | + -2, -3, // 2, 3 | ||
| 200 | + 10, 12, // "10" / "11" | ||
| 201 | + -4, -5, // 4, 5 | ||
| 202 | + -6, -7, // 6, 7 | ||
| 203 | +]; | ||
| 204 | + | ||
| 205 | +/// SPLITMV partition shapes tree + fixed probs (§16.4). Leaves are the | ||
| 206 | +/// RFC's `MVpartition` integers: 0 = top/bottom, 1 = left/right, | ||
| 207 | +/// 2 = quarters, 3 = MV_16. | ||
| 208 | +pub const MV_PARTITION_TREE: [i8; 6] = [-3, 2, -2, 4, 0, -1]; | ||
| 209 | +pub const MV_PARTITION_PROBS: [u8; 3] = [110, 111, 150]; | ||
| 210 | + | ||
| 211 | +/// The four SPLITMV partitionings as subblock groups (§16.4), indexed | ||
| 212 | +/// by the `MVpartition` integer: each group shares one motion vector, | ||
| 213 | +/// decoded in the listed (leader) order. | ||
| 214 | +pub const MV_PARTITIONS: [&[usize]; 4] = [ | ||
| 215 | + // mv_top_bottom: {0..7} then {8..15}. | ||
| 216 | + &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], | ||
| 217 | + // mv_left_right: {0,1,4,5,8,9,12,13} then {2,3,6,7,10,11,14,15}. | ||
| 218 | + &[0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15], | ||
| 219 | + // mv_quarters: {0,1,4,5} {2,3,6,7} {8,9,12,13} {10,11,14,15}. | ||
| 220 | + &[0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15], | ||
| 221 | + // MV_16: every subblock gets its own vector, raster order. | ||
| 222 | + &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], | ||
| 223 | +]; | ||
| 224 | + | ||
| 225 | +/// Number of distinct vectors per partition shape (§16.4). | ||
| 226 | +pub const MV_PARTITION_COUNT: [usize; 4] = [2, 2, 4, 16]; | ||
| 227 | + | ||
| 228 | +/// Inter subblock modes (§16.4): reuse the already-coded MV left/above, | ||
| 229 | +/// zero, or an explicit offset. | ||
| 230 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 231 | +#[repr(u8)] | ||
| 232 | +pub enum SubMvRef { | ||
| 233 | + /// Copy the left neighbour's MV (coded 0). | ||
| 234 | + Left4x4 = 0, | ||
| 235 | + /// Copy the above neighbour's MV (coded 1). | ||
| 236 | + Above4x4 = 1, | ||
| 237 | + /// Zero MV (coded 2). | ||
| 238 | + Zero4x4 = 2, | ||
| 239 | + /// Explicit offset from best (coded 3). | ||
| 240 | + New4x4 = 3, | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +pub const SUB_MV_REF_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3]; | ||
| 244 | + | ||
| 245 | +/// Context-conditioned sub-MV probabilities (§16.4 `sub_mv_ref_prob`). | ||
| 246 | +pub const SUB_MV_REF_PROBS: [[u8; 3]; 5] = [ | ||
| 247 | + [147, 136, 18], | ||
| 248 | + [106, 145, 1], | ||
| 249 | + [179, 121, 1], | ||
| 250 | + [223, 1, 34], | ||
| 251 | + [208, 1, 1], | ||
| 252 | +]; | ||
| 253 | + | ||
| 254 | +/// Sub-MV tree context (§16.4 `vp8_mvCont`): 4 = left==above==zero, | ||
| 255 | +/// 3 = left==above, 2 = above zero, 1 = left zero, 0 = normal. | ||
| 256 | +pub fn mv_cont(l: (i16, i16), a: (i16, i16)) -> usize { | ||
| 257 | + let lez = l == (0, 0); | ||
| 258 | + let aez = a == (0, 0); | ||
| 259 | + let lea = l == a; | ||
| 260 | + if lea && lez { | ||
| 261 | + 4 | ||
| 262 | + } else if lea { | ||
| 263 | + 3 | ||
| 264 | + } else if aez { | ||
| 265 | + 2 | ||
| 266 | + } else if lez { | ||
| 267 | + 1 | ||
| 268 | + } else { | ||
| 269 | + 0 | ||
| 270 | + } | ||
| 271 | +} | ||
| 272 | + | ||
| 273 | +/// Weighted-census probability table for the mv_ref tree | ||
| 274 | +/// (§16.3 `vp8_mode_contexts`, indexed by clamped count per slot). | ||
| 275 | +pub const MODE_CONTEXTS: [[u8; 4]; 6] = [ | ||
| 276 | + [7, 1, 1, 143], | ||
| 277 | + [14, 18, 14, 107], | ||
| 278 | + [135, 64, 57, 68], | ||
| 279 | + [60, 56, 128, 65], | ||
| 280 | + [159, 134, 128, 34], | ||
| 281 | + [234, 188, 128, 28], | ||
| 282 | +]; | ||
| 283 | + | ||
| 284 | +/// Decode an mv_ref at the census-derived probabilities (§16.2/§16.3). | ||
| 285 | +pub fn read_mv_ref(d: &mut BoolDecoder<'_>, probs: &[u8; 4]) -> MvRef { | ||
| 286 | + match d.read_tree(&MV_REF_TREE, probs) { | ||
| 287 | + 0 => MvRef::Zero, | ||
| 288 | + 1 => MvRef::Nearest, | ||
| 289 | + 2 => MvRef::Near, | ||
| 290 | + 3 => MvRef::New, | ||
| 291 | + 4 => MvRef::Split, | ||
| 292 | + v => unreachable!("mv_ref tree produced {v}"), | ||
| 293 | + } | ||
| 294 | +} | ||
| 295 | + | ||
| 296 | +/// Decode a SPLITMV partition shape (§16.4); returns the `MVpartition` | ||
| 297 | +/// integer indexing [`MV_PARTITIONS`]. | ||
| 298 | +pub fn read_mv_partition(d: &mut BoolDecoder<'_>) -> usize { | ||
| 299 | + usize::from(d.read_tree(&MV_PARTITION_TREE, &MV_PARTITION_PROBS)) | ||
| 300 | +} | ||
| 301 | + | ||
| 302 | +/// Decode a sub-MV reference (§16.4) at the context's probabilities. | ||
| 303 | +pub fn read_sub_mv_ref(d: &mut BoolDecoder<'_>, ctx: usize) -> SubMvRef { | ||
| 304 | + match d.read_tree(&SUB_MV_REF_TREE, &SUB_MV_REF_PROBS[ctx]) { | ||
| 305 | + 0 => SubMvRef::Left4x4, | ||
| 306 | + 1 => SubMvRef::Above4x4, | ||
| 307 | + 2 => SubMvRef::Zero4x4, | ||
| 308 | + 3 => SubMvRef::New4x4, | ||
| 309 | + v => unreachable!("sub_mv_ref tree produced {v}"), | ||
| 310 | + } | ||
| 311 | +} | ||
crates/ec-vp8/src/tokens.rsadded+282 -0
| @@ -0,0 +1,282 @@ | |||
| 1 | +//! DCT coefficient (token) decoding — RFC 6386 §13. | ||
| 2 | +//! | ||
| 3 | +//! Per 4x4 block: tokens are tree-decoded at | ||
| 4 | +//! `probs[type][band[position]][ctx]` where `ctx` (0..2) is the zero- | ||
| 5 | +//! neighbour count — sum of the above/left block contexts for the first | ||
| 6 | +//! coded coefficient, then derived from the magnitude of the previous | ||
| 7 | +//! coefficient within the block (§13.3). Coefficients are written in | ||
| 8 | +//! natural (de-zigzagged) order and dequantized on the fly (the first | ||
| 9 | +//! coded position takes the DC factor, all others the AC factor — the | ||
| 10 | +//! same arithmetic dixie applies inline and libvpx applies in | ||
| 11 | +//! `vp8_dequantize_b`). | ||
| 12 | +//! | ||
| 13 | +//! After an EOB the block ends; after a `DCT_0` token the tree decode of | ||
| 14 | +//! the next coefficient skips the EOB branch (§13.2). A block whose | ||
| 15 | +//! coefficients fill all 16 positions cannot take an EOB (the decoder | ||
| 16 | +//! stops at 16 exactly like the reference decoder, down to the sentinel | ||
| 17 | +//! band entry). | ||
| 18 | + | ||
| 19 | +use crate::bool::BoolDecoder; | ||
| 20 | +use crate::tables::{PCAT3, PCAT4, PCAT5, PCAT6}; | ||
| 21 | + | ||
| 22 | +/// De-zigzag: coefficient scan position -> natural order index | ||
| 23 | +/// (RFC 6386 §13, dixie/libvpx `zigzag`). | ||
| 24 | +const ZIGZAG: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; | ||
| 25 | + | ||
| 26 | +/// Band per coefficient position, with the reference decoder's sentinel | ||
| 27 | +/// entry at 16 (band 0 on the malformed no-EOB path — libvpx `kBands`). | ||
| 28 | +const BANDS: [u8; 17] = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0]; | ||
| 29 | + | ||
| 30 | +/// Extra-bit probability tables per category (cat3..cat6, RFC 6386 | ||
| 31 | +/// §13.2; the cat1/cat2 probabilities 159/165+145 are inlined in the | ||
| 32 | +/// tree decode exactly as the reference does). Trailing 0 is the | ||
| 33 | +/// DCTextra sentinel. | ||
| 34 | +const CAT_EXTRA: [&[u8]; 4] = [&PCAT3, &PCAT4, &PCAT5, &PCAT6]; | ||
| 35 | + | ||
| 36 | +/// Dequantization factors for one macroblock (already scaled: Y2 AC has | ||
| 37 | +/// the ×155/100 min-8 rule applied, Y2 DC ×2, UV DC capped at 132). | ||
| 38 | +#[derive(Debug, Clone, Copy)] | ||
| 39 | +pub(crate) struct Dq { | ||
| 40 | + pub y1_dc: i16, | ||
| 41 | + pub y1_ac: i16, | ||
| 42 | + pub uv_dc: i16, | ||
| 43 | + pub uv_ac: i16, | ||
| 44 | + pub y2_dc: i16, | ||
| 45 | + pub y2_ac: i16, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +/// The 25 blocks of one macroblock, dequantized, in natural coefficient | ||
| 49 | +/// order. `eobs[b]` is the number of significant coefficients (position | ||
| 50 | +/// of the last non-zero + 1); `eob_mask` mirrors dixie's: bit b set iff | ||
| 51 | +/// block b ended with more than one significant coefficient, bit 31 set | ||
| 52 | +/// iff ANY block had a non-zero coefficient. | ||
| 53 | +pub(crate) struct MbCoeffs { | ||
| 54 | + pub y: [[i16; 16]; 16], | ||
| 55 | + pub u: [[i16; 16]; 4], | ||
| 56 | + pub v: [[i16; 16]; 4], | ||
| 57 | + pub y2: [i16; 16], | ||
| 58 | + pub has_y2: bool, | ||
| 59 | + pub eobs: [u8; 25], | ||
| 60 | + pub eob_mask: u32, | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +impl MbCoeffs { | ||
| 64 | + pub(crate) fn empty(has_y2: bool) -> Self { | ||
| 65 | + Self { | ||
| 66 | + y: [[0; 16]; 16], | ||
| 67 | + u: [[0; 16]; 4], | ||
| 68 | + v: [[0; 16]; 4], | ||
| 69 | + y2: [0; 16], | ||
| 70 | + has_y2, | ||
| 71 | + eobs: [0; 25], | ||
| 72 | + eob_mask: 0, | ||
| 73 | + } | ||
| 74 | + } | ||
| 75 | + | ||
| 76 | + /// Whether any block carries a non-zero coefficient (the loop | ||
| 77 | + /// filter's interior-edge condition, §15.1). | ||
| 78 | + pub fn has_nonzero(&self) -> bool { | ||
| 79 | + self.eob_mask & (1 << 31) != 0 | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// Left/above context slot of each block (dixie `left_context_index` / | ||
| 84 | +/// `above_context_index`). | ||
| 85 | +const LEFT_INDEX: [usize; 25] = [ | ||
| 86 | + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, | ||
| 87 | +]; | ||
| 88 | +const ABOVE_INDEX: [usize; 25] = [ | ||
| 89 | + 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, | ||
| 90 | +]; | ||
| 91 | + | ||
| 92 | +/// Token entropy contexts (dixie/libvpx layout): indices 0-3 are the Y | ||
| 93 | +/// subblock columns, 4-5 U, 6-7 V, 8 the Y2 block. `left` is the running | ||
| 94 | +/// one-MB-wide column state; `above` is the per-MB-column state for the | ||
| 95 | +/// current row (9 slots per MB column). | ||
| 96 | +pub(crate) struct TokenContexts { | ||
| 97 | + pub above: Vec<u8>, | ||
| 98 | + pub left: [u8; 9], | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +impl TokenContexts { | ||
| 102 | + /// `mb_cols` entries of 9 slots for the above state. | ||
| 103 | + pub fn new(mb_cols: usize) -> Self { | ||
| 104 | + Self { | ||
| 105 | + above: vec![0u8; mb_cols * 9], | ||
| 106 | + left: [0; 9], | ||
| 107 | + } | ||
| 108 | + } | ||
| 109 | + | ||
| 110 | + /// Reset the above state at the start of a row (§13.3: non-existent | ||
| 111 | + /// neighbours are empty). | ||
| 112 | + pub fn reset_above_row(&mut self) { | ||
| 113 | + self.above.iter_mut().for_each(|s| *s = 0); | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + /// Reset the left state at the start of a row (the caller MUST call | ||
| 117 | + /// this once per MB row before decoding its tokens). | ||
| 118 | + pub fn reset_left(&mut self) { | ||
| 119 | + self.left = [0; 9]; | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + /// Skip-MB context reset (dixie `reset_mb_context`): everything to 0 | ||
| 123 | + /// except the Y2 slots, which survive iff this MB has no Y2 block. | ||
| 124 | + pub fn reset_mb(&mut self, mb_col: usize, has_y2: bool) { | ||
| 125 | + let a = &mut self.above[mb_col * 9..mb_col * 9 + 9]; | ||
| 126 | + a[..8].fill(0); | ||
| 127 | + self.left[..8].fill(0); | ||
| 128 | + if has_y2 { | ||
| 129 | + a[8] = 0; | ||
| 130 | + self.left[8] = 0; | ||
| 131 | + } | ||
| 132 | + } | ||
| 133 | + | ||
| 134 | + fn ctx_pair(&self, mb_col: usize, block: usize) -> (u8, u8) { | ||
| 135 | + let a = &self.above[mb_col * 9..mb_col * 9 + 9]; | ||
| 136 | + (self.left[LEFT_INDEX[block]], a[ABOVE_INDEX[block]]) | ||
| 137 | + } | ||
| 138 | + | ||
| 139 | + fn set_ctx(&mut self, mb_col: usize, block: usize, v: u8) { | ||
| 140 | + self.left[LEFT_INDEX[block]] = v; | ||
| 141 | + self.above[mb_col * 9 + ABOVE_INDEX[block]] = v; | ||
| 142 | + } | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +/// Decode one 4x4 block's tokens (libvpx `GetCoeffs` / RFC §13.2-13.3 | ||
| 146 | +/// verbatim). `probs_t` is `[band][ctx][node]` for the block's plane | ||
| 147 | +/// type; `n0` the first coded position (1 for Y blocks after a Y2). | ||
| 148 | +/// Returns the number of significant coefficients. Coefficients are | ||
| 149 | +/// written dequantized into `out` (natural order). | ||
| 150 | +fn get_coeffs( | ||
| 151 | + bc: &mut BoolDecoder<'_>, | ||
| 152 | + probs_t: &[[[u8; 11]; 3]; 8], | ||
| 153 | + ctx: usize, | ||
| 154 | + n0: usize, | ||
| 155 | + dc_factor: i16, | ||
| 156 | + ac_factor: i16, | ||
| 157 | + out: &mut [i16; 16], | ||
| 158 | +) -> usize { | ||
| 159 | + let mut n = n0; | ||
| 160 | + let mut p = &probs_t[BANDS[n0] as usize][ctx]; | ||
| 161 | + if !bc.read_bool(p[0]) { | ||
| 162 | + return 0; // immediate EOB | ||
| 163 | + } | ||
| 164 | + loop { | ||
| 165 | + n += 1; | ||
| 166 | + let mut v: i32; | ||
| 167 | + if !bc.read_bool(p[1]) { | ||
| 168 | + // DCT_0: next decision skips the EOB branch (§13.2). | ||
| 169 | + p = &probs_t[BANDS[n] as usize][0]; | ||
| 170 | + } else { | ||
| 171 | + if !bc.read_bool(p[2]) { | ||
| 172 | + p = &probs_t[BANDS[n] as usize][1]; | ||
| 173 | + v = 1; | ||
| 174 | + } else if !bc.read_bool(p[3]) { | ||
| 175 | + if !bc.read_bool(p[4]) { | ||
| 176 | + v = 2; | ||
| 177 | + } else { | ||
| 178 | + v = 3 + i32::from(bc.read_bool(p[5])); | ||
| 179 | + } | ||
| 180 | + } else if !bc.read_bool(p[6]) { | ||
| 181 | + if !bc.read_bool(p[7]) { | ||
| 182 | + v = 5 + i32::from(bc.read_bool(159)); | ||
| 183 | + } else { | ||
| 184 | + v = 7 + 2 * i32::from(bc.read_bool(165)); | ||
| 185 | + v += i32::from(bc.read_bool(145)); | ||
| 186 | + } | ||
| 187 | + } else { | ||
| 188 | + // Categories 3..6: two tree bits pick the category, then | ||
| 189 | + // DCTextra (§13.2). | ||
| 190 | + let bit1 = usize::from(bc.read_bool(p[8])); | ||
| 191 | + let bit0 = usize::from(bc.read_bool(p[9 + bit1])); | ||
| 192 | + let cat = 2 * bit1 + bit0; | ||
| 193 | + v = 0; | ||
| 194 | + for &prob in CAT_EXTRA[cat] { | ||
| 195 | + if prob == 0 { | ||
| 196 | + break; | ||
| 197 | + } | ||
| 198 | + v += v + i32::from(bc.read_bool(prob)); | ||
| 199 | + } | ||
| 200 | + v += 3 + (8 << cat); | ||
| 201 | + } | ||
| 202 | + | ||
| 203 | + // Sign flag, then dequantize (first coded position is DC). | ||
| 204 | + let mag = if bc.read_bool(128) { -v } else { v }; | ||
| 205 | + out[ZIGZAG[n - 1]] = if n - 1 == 0 { | ||
| 206 | + (mag * i32::from(dc_factor)) as i16 | ||
| 207 | + } else { | ||
| 208 | + (mag * i32::from(ac_factor)) as i16 | ||
| 209 | + }; | ||
| 210 | + if n < 16 { | ||
| 211 | + // Non-zero coefficients set the magnitude context for | ||
| 212 | + // the next coefficient (§13.3). | ||
| 213 | + p = &probs_t[BANDS[n] as usize][2]; | ||
| 214 | + } | ||
| 215 | + if n == 16 || !bc.read_bool(p[0]) { | ||
| 216 | + return n; | ||
| 217 | + } | ||
| 218 | + } | ||
| 219 | + if n == 16 { | ||
| 220 | + return 16; // malformed without EOB: stop like the reference | ||
| 221 | + } | ||
| 222 | + } | ||
| 223 | +} | ||
| 224 | + | ||
| 225 | +/// Decode all 25 blocks of one macroblock (dixie `decode_mb_tokens`): | ||
| 226 | +/// Y2 first when present, then the 16 Y, then U, then V. A skipped MB | ||
| 227 | +/// must not be run through here — call [`skip_mb_tokens`] instead. | ||
| 228 | +pub(crate) fn decode_mb_tokens( | ||
| 229 | + bc: &mut BoolDecoder<'_>, | ||
| 230 | + probs: &[[[[u8; 11]; 3]; 8]; 4], | ||
| 231 | + dq: &Dq, | ||
| 232 | + has_y2: bool, | ||
| 233 | + ctxs: &mut TokenContexts, | ||
| 234 | + mb_col: usize, | ||
| 235 | +) -> MbCoeffs { | ||
| 236 | + let mut out = MbCoeffs::empty(has_y2); | ||
| 237 | + let mut eob_mask = 0u32; | ||
| 238 | + | ||
| 239 | + // Decode one block and fold its contexts/mask in. | ||
| 240 | + macro_rules! block { | ||
| 241 | + ($idx:expr, $ptype:expr, $dc:expr, $ac:expr, $slot:expr) => {{ | ||
| 242 | + let n0 = usize::from($ptype == 0); | ||
| 243 | + let (l, a) = ctxs.ctx_pair(mb_col, $idx); | ||
| 244 | + let ctx = (usize::from(l) + usize::from(a)).min(2); | ||
| 245 | + let eob = get_coeffs(bc, &probs[$ptype], ctx, n0, $dc, $ac, $slot); | ||
| 246 | + out.eobs[$idx] = eob as u8; | ||
| 247 | + let t = u8::from(eob > 0); | ||
| 248 | + ctxs.set_ctx(mb_col, $idx, t); | ||
| 249 | + eob_mask |= (u32::from(eob > 1)) << $idx; | ||
| 250 | + eob_mask |= u32::from(t != 0) << 31; | ||
| 251 | + }}; | ||
| 252 | + } | ||
| 253 | + | ||
| 254 | + if has_y2 { | ||
| 255 | + block!(24, 1, dq.y2_dc, dq.y2_ac, &mut out.y2); | ||
| 256 | + for b in 0..16 { | ||
| 257 | + block!(b, 0, dq.y1_dc, dq.y1_ac, &mut out.y[b]); | ||
| 258 | + } | ||
| 259 | + } else { | ||
| 260 | + for b in 0..16 { | ||
| 261 | + block!(b, 3, dq.y1_dc, dq.y1_ac, &mut out.y[b]); | ||
| 262 | + } | ||
| 263 | + } | ||
| 264 | + for b in 0..4 { | ||
| 265 | + block!(16 + b, 2, dq.uv_dc, dq.uv_ac, &mut out.u[b]); | ||
| 266 | + } | ||
| 267 | + for b in 0..4 { | ||
| 268 | + block!(20 + b, 2, dq.uv_dc, dq.uv_ac, &mut out.v[b]); | ||
| 269 | + } | ||
| 270 | + | ||
| 271 | + out.eob_mask = eob_mask; | ||
| 272 | + out | ||
| 273 | +} | ||
| 274 | + | ||
| 275 | +/// The context reset a skipped MB applies (dixie `reset_mb_context`): | ||
| 276 | +/// the returned [`MbCoeffs`] is all-zero and the contexts look like a | ||
| 277 | +/// fully-empty MB — except the Y2 slots survive when the skipped MB has | ||
| 278 | +/// no Y2 block. | ||
| 279 | +pub(crate) fn skip_mb_tokens(ctxs: &mut TokenContexts, mb_col: usize, has_y2: bool) -> MbCoeffs { | ||
| 280 | + ctxs.reset_mb(mb_col, has_y2); | ||
| 281 | + MbCoeffs::empty(has_y2) | ||
| 282 | +} | ||
crates/ec-vp8/src/transform.rsadded+640 -0
| @@ -0,0 +1,640 @@ | |||
| 1 | +//! Inverse transforms (inverse DCT, inverse Walsh-Hadamard) and dequant | ||
| 2 | +//! factor computation for VP8 (RFC 6386 §14). | ||
| 3 | +//! | ||
| 4 | +//! Every function here is a bit-exact transcription of the normative | ||
| 5 | +//! reference implementation in libvpx (`vp8/common/idctllm.c` and | ||
| 6 | +//! `vp8/common/quant_common.c`), which is also what RFC 6386 §§14.3–14.5 | ||
| 7 | +//! print as pseudocode. Bit-level fidelity of the rounding is a hard | ||
| 8 | +//! requirement: arithmetic right shifts (`>>` on `i32` in Rust, as in C) | ||
| 9 | +//! round toward negative infinity, and both implementations rely on that | ||
| 10 | +//! floor behavior for negative operands. | ||
| 11 | +//! | ||
| 12 | +//! Fidelity details reproduced verbatim from the oracle: | ||
| 13 | +//! - The 16-bit fixed-point constants `cospi8sqrt2minus1 = 20091` and | ||
| 14 | +//! `sinpi8sqrt2 = 35468` (§14.4). The `>> 16` multiplies carry **no** | ||
| 15 | +//! rounding constant; the `+4` before the final `>> 3` appears only in | ||
| 16 | +//! the second DCT pass. | ||
| 17 | +//! - `short output[16]` intermediates: libvpx stores the first-pass | ||
| 18 | +//! results into a `short` array, truncating `i32` arithmetic to `i16` | ||
| 19 | +//! between passes. We reproduce those truncation points with `as i16` | ||
| 20 | +//! (wrapping two's-complement truncation, identical to the de facto C | ||
| 21 | +//! behavior) so results stay oracle-exact even for adversarial inputs. | ||
| 22 | +//! - The inverse WHT rounds with `(x + 3) >> 3` (§14.3); the DC-only | ||
| 23 | +//! shortcut uses the same constant on `input[0]` alone. | ||
| 24 | +//! | ||
| 25 | +//! All functions are pure, allocation-free, and free of `unsafe`. | ||
| 26 | + | ||
| 27 | +#![deny(unsafe_code)] | ||
| 28 | + | ||
| 29 | +/// 16-bit fixed-point `sqrt(2) * cos(pi/8) - 1` (RFC 6386 §14.4). The | ||
| 30 | +/// product `x * sqrt(2) * cos(pi/8)` is computed as `x + ((x * K) >> 16)` | ||
| 31 | +/// because the constant exceeds 1.0 and would otherwise lose precision. | ||
| 32 | +const COSPI8SQRT2MINUS1: i32 = 20091; | ||
| 33 | + | ||
| 34 | +/// 16-bit fixed-point `sqrt(2) * sin(pi/8)` (RFC 6386 §14.4). | ||
| 35 | +const SINPI8SQRT2: i32 = 35468; | ||
| 36 | + | ||
| 37 | +/// DC quantizer lookup, `dc_qlookup[QINDEX_RANGE]` (RFC 6386 §14.1), | ||
| 38 | +/// transcribed mechanically from libvpx `vp8/common/quant_common.c`. | ||
| 39 | +const DC_QLOOKUP: [i16; 128] = [ | ||
| 40 | + 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, | ||
| 41 | + 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, | ||
| 42 | + 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, | ||
| 43 | + 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, | ||
| 44 | + 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130, | ||
| 45 | + 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, | ||
| 46 | +]; | ||
| 47 | + | ||
| 48 | +/// AC quantizer lookup, `ac_qlookup[QINDEX_RANGE]` (RFC 6386 §14.1), | ||
| 49 | +/// transcribed mechanically from libvpx `vp8/common/quant_common.c`. | ||
| 50 | +const AC_QLOOKUP: [i16; 128] = [ | ||
| 51 | + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, | ||
| 52 | + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, | ||
| 53 | + 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, | ||
| 54 | + 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, | ||
| 55 | + 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205, | ||
| 56 | + 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, | ||
| 57 | +]; | ||
| 58 | + | ||
| 59 | +/// Clamps a (possibly delta-adjusted) quantizer index to the valid | ||
| 60 | +/// qindex range `[0, 127]` — dixie `clamp_q` / libvpx bounds in | ||
| 61 | +/// `quant_common.c` (RFC 6386 §14.1). | ||
| 62 | +#[inline] | ||
| 63 | +fn clamp_q(q: i32) -> i32 { | ||
| 64 | + q.clamp(0, 127) | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// `dc_qlookup[clamp(q + delta)]` — Y-after-second / per-plane DC factor | ||
| 68 | +/// lookup with delta adjustment (RFC 6386 §14.1 `dc_q`). | ||
| 69 | +#[inline] | ||
| 70 | +fn dc_factor(q: i32, delta: i32) -> i16 { | ||
| 71 | + DC_QLOOKUP[clamp_q(q + delta) as usize] | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// `ac_qlookup[clamp(q + delta)]` — AC factor lookup with delta | ||
| 75 | +/// adjustment (RFC 6386 §14.1 `ac_q`). | ||
| 76 | +#[inline] | ||
| 77 | +fn ac_factor(q: i32, delta: i32) -> i16 { | ||
| 78 | + AC_QLOOKUP[clamp_q(q + delta) as usize] | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +/// Inverse Walsh-Hadamard transform of the 16 dequantized Y2 DC | ||
| 82 | +/// coefficients into the 16 Y-subblock DC residuals | ||
| 83 | +/// (RFC 6386 §14.3 `vp8_short_inv_walsh4x4_c`, oracle | ||
| 84 | +/// `vp8_short_inv_walsh4x4_c` in `idctllm.c`). | ||
| 85 | +/// | ||
| 86 | +/// `input` is the row-major 4x4 block of dequantized Y2 DCs; the returned | ||
| 87 | +/// array holds the 16 Y-subblock DC values in the same row-major order | ||
| 88 | +/// (the reference scatters `output[i]` to `mb_dqcoeff[i * 16]`, i.e. the | ||
| 89 | +/// DC slot of the i-th Y subblock — the caller places them). Two passes | ||
| 90 | +/// of the exact 4-point Hadamard butterfly, with `short` truncation of | ||
| 91 | +/// the first-pass results and `(x + 3) >> 3` rounding in the second. | ||
| 92 | +#[inline] | ||
| 93 | +pub fn iwht4x4(input: &[i16; 16]) -> [i16; 16] { | ||
| 94 | + let mut tmp = [0i16; 16]; | ||
| 95 | + | ||
| 96 | + // First pass: transform columns; results are stored transposed into | ||
| 97 | + // rows of `tmp` (ip walks input[i], input[4+i], input[8+i], | ||
| 98 | + // input[12+i]). libvpx stores into `short`: truncate to i16. | ||
| 99 | + for i in 0..4 { | ||
| 100 | + let a1 = input[i] as i32 + input[12 + i] as i32; | ||
| 101 | + let b1 = input[4 + i] as i32 + input[8 + i] as i32; | ||
| 102 | + let c1 = input[4 + i] as i32 - input[8 + i] as i32; | ||
| 103 | + let d1 = input[i] as i32 - input[12 + i] as i32; | ||
| 104 | + | ||
| 105 | + tmp[i] = (a1 + b1) as i16; | ||
| 106 | + tmp[4 + i] = (c1 + d1) as i16; | ||
| 107 | + tmp[8 + i] = (a1 - b1) as i16; | ||
| 108 | + tmp[12 + i] = (d1 - c1) as i16; | ||
| 109 | + } | ||
| 110 | + | ||
| 111 | + let mut output = [0i16; 16]; | ||
| 112 | + | ||
| 113 | + // Second pass: transform rows in place, rounding with (x + 3) >> 3. | ||
| 114 | + for r in 0..4 { | ||
| 115 | + let i = 4 * r; | ||
| 116 | + let a1 = tmp[i] as i32 + tmp[i + 3] as i32; | ||
| 117 | + let b1 = tmp[i + 1] as i32 + tmp[i + 2] as i32; | ||
| 118 | + let c1 = tmp[i + 1] as i32 - tmp[i + 2] as i32; | ||
| 119 | + let d1 = tmp[i] as i32 - tmp[i + 3] as i32; | ||
| 120 | + | ||
| 121 | + let a2 = a1 + b1; | ||
| 122 | + let b2 = c1 + d1; | ||
| 123 | + let c2 = a1 - b1; | ||
| 124 | + let d2 = d1 - c1; | ||
| 125 | + | ||
| 126 | + output[i] = ((a2 + 3) >> 3) as i16; | ||
| 127 | + output[i + 1] = ((b2 + 3) >> 3) as i16; | ||
| 128 | + output[i + 2] = ((c2 + 3) >> 3) as i16; | ||
| 129 | + output[i + 3] = ((d2 + 3) >> 3) as i16; | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + output | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +/// One-nonzero-DC shortcut of the inverse WHT | ||
| 136 | +/// (RFC 6386 §14.3 `vp8_short_inv_walsh4x4_1_c`, oracle | ||
| 137 | +/// `vp8_short_inv_walsh4x4_1_c` in `idctllm.c`). | ||
| 138 | +/// | ||
| 139 | +/// When only `input[0]` is non-zero, every Y-subblock DC equals | ||
| 140 | +/// `(input[0] + 3) >> 3`. Bit-identical to `iwht4x4` for such inputs. | ||
| 141 | +#[inline] | ||
| 142 | +pub fn iwht4x4_dc(input: &[i16; 16]) -> [i16; 16] { | ||
| 143 | + let a1 = ((input[0] as i32 + 3) >> 3) as i16; | ||
| 144 | + [a1; 16] | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +/// Full inverse DCT of one dequantized 4x4 coefficient block | ||
| 148 | +/// (RFC 6386 §14.4; oracle `short_idct4x4llm_c` in `idctllm.c`). | ||
| 149 | +/// | ||
| 150 | +/// `coeffs` is a row-major 4x4 block of **already dequantized** | ||
| 151 | +/// coefficients (dequantization happens before the transform, RFC 6386 | ||
| 152 | +/// §14.5). Two passes of the 4-point inverse DCT with the §14.4 | ||
| 153 | +/// fixed-point constants; the `>> 16` multiplies carry no rounding | ||
| 154 | +/// constant and the `(x + 4) >> 3` rounding is applied only in the | ||
| 155 | +/// second pass. First-pass results are truncated to `i16` exactly where | ||
| 156 | +/// the oracle stores into its `short output[16]` scratch. | ||
| 157 | +/// | ||
| 158 | +/// Returns the row-major 4x4 residual. Not clamped, not added to the | ||
| 159 | +/// prediction — see [`idct4x4_add`] for the combined form. | ||
| 160 | +#[inline] | ||
| 161 | +pub fn idct4x4(coeffs: &[i16; 16]) -> [i16; 16] { | ||
| 162 | + let mut tmp = [0i16; 16]; | ||
| 163 | + | ||
| 164 | + // First pass: transform columns; results land transposed in rows of | ||
| 165 | + // `tmp` (ip walks coeffs[i], coeffs[4+i], coeffs[8+i], coeffs[12+i]). | ||
| 166 | + for i in 0..4 { | ||
| 167 | + let a1 = coeffs[i] as i32 + coeffs[8 + i] as i32; | ||
| 168 | + let b1 = coeffs[i] as i32 - coeffs[8 + i] as i32; | ||
| 169 | + | ||
| 170 | + let temp1 = (coeffs[4 + i] as i32 * SINPI8SQRT2) >> 16; | ||
| 171 | + let temp2 = coeffs[12 + i] as i32 + ((coeffs[12 + i] as i32 * COSPI8SQRT2MINUS1) >> 16); | ||
| 172 | + let c1 = temp1 - temp2; | ||
| 173 | + | ||
| 174 | + let temp1 = coeffs[4 + i] as i32 + ((coeffs[4 + i] as i32 * COSPI8SQRT2MINUS1) >> 16); | ||
| 175 | + let temp2 = (coeffs[12 + i] as i32 * SINPI8SQRT2) >> 16; | ||
| 176 | + let d1 = temp1 + temp2; | ||
| 177 | + | ||
| 178 | + // libvpx stores into `short`: truncate to i16. | ||
| 179 | + tmp[i] = (a1 + d1) as i16; | ||
| 180 | + tmp[12 + i] = (a1 - d1) as i16; | ||
| 181 | + tmp[4 + i] = (b1 + c1) as i16; | ||
| 182 | + tmp[8 + i] = (b1 - c1) as i16; | ||
| 183 | + } | ||
| 184 | + | ||
| 185 | + let mut output = [0i16; 16]; | ||
| 186 | + | ||
| 187 | + // Second pass: transform rows, rounding with (x + 4) >> 3. | ||
| 188 | + for r in 0..4 { | ||
| 189 | + let i = 4 * r; | ||
| 190 | + let ip0 = tmp[i] as i32; | ||
| 191 | + let ip1 = tmp[i + 1] as i32; | ||
| 192 | + let ip2 = tmp[i + 2] as i32; | ||
| 193 | + let ip3 = tmp[i + 3] as i32; | ||
| 194 | + | ||
| 195 | + let a1 = ip0 + ip2; | ||
| 196 | + let b1 = ip0 - ip2; | ||
| 197 | + | ||
| 198 | + let temp1 = (ip1 * SINPI8SQRT2) >> 16; | ||
| 199 | + let temp2 = ip3 + ((ip3 * COSPI8SQRT2MINUS1) >> 16); | ||
| 200 | + let c1 = temp1 - temp2; | ||
| 201 | + | ||
| 202 | + let temp1 = ip1 + ((ip1 * COSPI8SQRT2MINUS1) >> 16); | ||
| 203 | + let temp2 = (ip3 * SINPI8SQRT2) >> 16; | ||
| 204 | + let d1 = temp1 + temp2; | ||
| 205 | + | ||
| 206 | + output[i] = ((a1 + d1 + 4) >> 3) as i16; | ||
| 207 | + output[i + 3] = ((a1 - d1 + 4) >> 3) as i16; | ||
| 208 | + output[i + 1] = ((b1 + c1 + 4) >> 3) as i16; | ||
| 209 | + output[i + 2] = ((b1 - c1 + 4) >> 3) as i16; | ||
| 210 | + } | ||
| 211 | + | ||
| 212 | + output | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +/// DC-only inverse DCT shortcut (RFC 6386 §14.4 | ||
| 216 | +/// `vp8_dc_only_idct_add_c` math; oracle `idctllm.c`): when position 0 is | ||
| 217 | +/// the sole non-zero coefficient, every residual pixel is `(dc + 4) >> 3`. | ||
| 218 | +/// | ||
| 219 | +/// Bit-identical to `idct4x4` on such inputs. Not clamped; the caller | ||
| 220 | +/// adds and clamps (or uses [`idct4x4_add`]). | ||
| 221 | +#[inline] | ||
| 222 | +pub fn idct4x4_dc(dc: i16) -> [i16; 16] { | ||
| 223 | + let a1 = ((dc as i32 + 4) >> 3) as i16; | ||
| 224 | + [a1; 16] | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +/// Combined per-block reconstruction kernel (RFC 6386 §14.4/§14.5; oracle | ||
| 228 | +/// `short_idct4x4llm_c` final loop in `idctllm.c`): inverse-transforms | ||
| 229 | +/// `coeffs` and writes `clamp(predict + residual)` into `recon`. | ||
| 230 | +/// | ||
| 231 | +/// `coeffs` must already be dequantized (dequantization is applied before | ||
| 232 | +/// the transform; for intra Y macroblocks the DC positions already hold | ||
| 233 | +/// the [`iwht4x4`] output). `predict` and `recon` are row-major 4x4 | ||
| 234 | +/// blocks of exactly 16 bytes each. Residuals are fully computed before | ||
| 235 | +/// any output byte is written. | ||
| 236 | +#[inline] | ||
| 237 | +pub fn idct4x4_add(coeffs: &[i16; 16], predict: &[u8], recon: &mut [u8]) { | ||
| 238 | + let residual = idct4x4(coeffs); | ||
| 239 | + for i in 0..16 { | ||
| 240 | + let a = residual[i] as i32 + predict[i] as i32; | ||
| 241 | + recon[i] = a.clamp(0, 255) as u8; | ||
| 242 | + } | ||
| 243 | +} | ||
| 244 | + | ||
| 245 | +/// Dequantization factors for one macroblock, indexed by plane and | ||
| 246 | +/// coefficient type (RFC 6386 §14.1; dixie `struct dequant_factors`). | ||
| 247 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 248 | +pub struct Dequant { | ||
| 249 | + /// Y plane, DC coefficient (after inverse WHT for intra Y2 rows). | ||
| 250 | + pub y1_dc: i16, | ||
| 251 | + /// Y plane, AC coefficients. | ||
| 252 | + pub y1_ac: i16, | ||
| 253 | + /// Y2 plane (second-order) DC coefficient: `dc_qlookup[...] * 2`. | ||
| 254 | + pub y2_dc: i16, | ||
| 255 | + /// Y2 plane AC coefficient: `ac_qlookup[...] * 155 / 100`, floored at 8. | ||
| 256 | + pub y2_ac: i16, | ||
| 257 | + /// Chroma DC coefficient, capped at 132 after lookup. | ||
| 258 | + pub uv_dc: i16, | ||
| 259 | + /// Chroma AC coefficient. | ||
| 260 | + pub uv_ac: i16, | ||
| 261 | +} | ||
| 262 | + | ||
| 263 | +/// Computes the six dequantization factors for quantizer index `q` with | ||
| 264 | +/// the per-frame delta updates (RFC 6386 §9.6 header fields applied per | ||
| 265 | +/// §14.1; dixie `dequant_init`, oracle `vp8cx_init_quantizer` in | ||
| 266 | +/// libvpx `decodframe.c` / `quant_common.c`). | ||
| 267 | +/// | ||
| 268 | +/// `q` is the per-macroblock segment-adjusted base qindex (already | ||
| 269 | +/// absolute or offset by the segment level per the segment header); the | ||
| 270 | +/// delta arguments are the frame-header updates. Each lookup clamps its | ||
| 271 | +/// `q + delta` sum to `[0, 127]`. Semantics transcribed exactly: | ||
| 272 | +/// - `y1_dc = dc_qlookup[clamp(q + y1_dc_delta)]`, | ||
| 273 | +/// `y1_ac = ac_qlookup[clamp(q)]` (no delta exists for Y AC), | ||
| 274 | +/// - `y2_dc = dc_qlookup[clamp(q + y2_dc_delta)] * 2`, | ||
| 275 | +/// - `y2_ac = ac_qlookup[clamp(q + y2_ac_delta)] * 155 / 100` (integer | ||
| 276 | +/// division), floored at 8, | ||
| 277 | +/// - `uv_dc = min(dc_qlookup[clamp(q + uv_dc_delta)], 132)` (cap applied | ||
| 278 | +/// after the lookup), | ||
| 279 | +/// - `uv_ac = ac_qlookup[clamp(q + uv_ac_delta)]`. | ||
| 280 | +#[must_use] | ||
| 281 | +pub fn dequant( | ||
| 282 | + q: i32, | ||
| 283 | + y1_dc_delta: i32, | ||
| 284 | + y2_dc_delta: i32, | ||
| 285 | + y2_ac_delta: i32, | ||
| 286 | + uv_dc_delta: i32, | ||
| 287 | + uv_ac_delta: i32, | ||
| 288 | +) -> Dequant { | ||
| 289 | + Dequant { | ||
| 290 | + y1_dc: dc_factor(q, y1_dc_delta), | ||
| 291 | + y1_ac: ac_factor(q, 0), | ||
| 292 | + y2_dc: dc_factor(q, y2_dc_delta) * 2, | ||
| 293 | + y2_ac: { | ||
| 294 | + let v = (ac_factor(q, y2_ac_delta) as i32 * 155) / 100; | ||
| 295 | + (if v < 8 { 8 } else { v }) as i16 | ||
| 296 | + }, | ||
| 297 | + uv_dc: { | ||
| 298 | + let v = dc_factor(q, uv_dc_delta); | ||
| 299 | + if v > 132 { 132 } else { v } | ||
| 300 | + }, | ||
| 301 | + uv_ac: ac_factor(q, uv_ac_delta), | ||
| 302 | + } | ||
| 303 | +} | ||
| 304 | + | ||
| 305 | +#[cfg(test)] | ||
| 306 | +mod tests { | ||
| 307 | + use super::*; | ||
| 308 | + | ||
| 309 | + /// Hand-derived: impulse `input[0] = 8`, all else 0. First pass, the | ||
| 310 | + /// only touched column (0) reads (8,0,0,0): a1 = 8+0 = 8, b1 = 0, | ||
| 311 | + /// c1 = 0, d1 = 8, giving intermediate column 0 = [8,8,8,8]. Second | ||
| 312 | + /// pass, every row reads (8,0,0,0): a2 = b2 = c2 = d2 = 8, and | ||
| 313 | + /// (8 + 3) >> 3 = 1. Expected: all 16 outputs are 1. | ||
| 314 | + #[test] | ||
| 315 | + fn iwht_unit_impulse_yields_all_ones() { | ||
| 316 | + let mut input = [0i16; 16]; | ||
| 317 | + input[0] = 8; | ||
| 318 | + assert_eq!(iwht4x4(&input), [1i16; 16]); | ||
| 319 | + } | ||
| 320 | + | ||
| 321 | + /// Hand-derived: impulse `input[5] = 8` (row 1, col 1). First pass, | ||
| 322 | + /// column 1 reads (0,8,0,0): a1 = 0, b1 = 8, c1 = 8, d1 = 0, giving | ||
| 323 | + /// intermediate column 1 = [8, 8, -8, -8]. Second pass, rows 0-1 read | ||
| 324 | + /// (0,8,0,0) → outputs (1, 1, -1, -1); rows 2-3 read (0,-8,0,0) → | ||
| 325 | + /// (-1, -1, 1, 1) — the Hadamard basis pattern for position (1,1). | ||
| 326 | + #[test] | ||
| 327 | + fn iwht_impulse_at_row1_col1_yields_hadamard_pattern() { | ||
| 328 | + let mut input = [0i16; 16]; | ||
| 329 | + input[5] = 8; | ||
| 330 | + assert_eq!( | ||
| 331 | + iwht4x4(&input), | ||
| 332 | + [ | ||
| 333 | + 1, 1, -1, -1, // | ||
| 334 | + 1, 1, -1, -1, // | ||
| 335 | + -1, -1, 1, 1, // | ||
| 336 | + -1, -1, 1, 1, | ||
| 337 | + ] | ||
| 338 | + ); | ||
| 339 | + } | ||
| 340 | + | ||
| 341 | + /// Mixed-coefficient oracle: expected values computed with a Python | ||
| 342 | + /// model of the exact libvpx integer algorithm (see the model in | ||
| 343 | + /// `idct_mixed_block_matches_oracle` below — the WHT variant is the | ||
| 344 | + /// same structure with §14.3 butterflies and `(x + 3) >> 3`). | ||
| 345 | + #[test] | ||
| 346 | + fn iwht_mixed_block_matches_oracle() { | ||
| 347 | + let input = [ | ||
| 348 | + 40, -13, 0, 7, 222, 5, -40, 1, 0, 0, 17, -9, 300, -250, 88, 3, | ||
| 349 | + ]; | ||
| 350 | + assert_eq!( | ||
| 351 | + iwht4x4(&input), | ||
| 352 | + [ | ||
| 353 | + 46, 30, 95, 110, // | ||
| 354 | + 9, 42, -15, -55, // | ||
| 355 | + -3, -35, 37, 60, // | ||
| 356 | + -36, -27, -86, -92, | ||
| 357 | + ] | ||
| 358 | + ); | ||
| 359 | + } | ||
| 360 | + | ||
| 361 | + /// The `_dc` shortcut must agree with the full transform whenever | ||
| 362 | + /// only `input[0]` is non-zero — across the whole practical range, | ||
| 363 | + /// including negatives and both i16 extremes (arithmetic shifts are | ||
| 364 | + /// floor rounding for negatives in both C and Rust). | ||
| 365 | + #[test] | ||
| 366 | + fn iwht_dc_shortcut_matches_full_transform() { | ||
| 367 | + for v in [ | ||
| 368 | + 0, | ||
| 369 | + 1, | ||
| 370 | + -1, | ||
| 371 | + 3, | ||
| 372 | + -3, | ||
| 373 | + 8, | ||
| 374 | + -8, | ||
| 375 | + 100, | ||
| 376 | + -100, | ||
| 377 | + 1234, | ||
| 378 | + -4321, | ||
| 379 | + i16::MAX, | ||
| 380 | + i16::MIN, | ||
| 381 | + ] { | ||
| 382 | + let input = { | ||
| 383 | + let mut i = [0i16; 16]; | ||
| 384 | + i[0] = v; | ||
| 385 | + i | ||
| 386 | + }; | ||
| 387 | + assert_eq!(iwht4x4(&input), iwht4x4_dc(&input), "mismatch at dc={v}"); | ||
| 388 | + } | ||
| 389 | + } | ||
| 390 | + | ||
| 391 | + /// §14.4 DC-only math: input [40, 0, ...] gives every pixel | ||
| 392 | + /// (40 + 4) >> 3 = 5. | ||
| 393 | + #[test] | ||
| 394 | + fn idct_dc_only_40_yields_five() { | ||
| 395 | + let coeffs = { | ||
| 396 | + let mut c = [0i16; 16]; | ||
| 397 | + c[0] = 40; | ||
| 398 | + c | ||
| 399 | + }; | ||
| 400 | + assert_eq!(idct4x4(&coeffs), [5i16; 16]); | ||
| 401 | + assert_eq!(idct4x4_dc(40), [5i16; 16]); | ||
| 402 | + } | ||
| 403 | + | ||
| 404 | + /// Mixed-coefficient oracle. The Python model below is a line-for-line | ||
| 405 | + /// transcription of libvpx `short_idct4x4llm_c` (same integer math, | ||
| 406 | + /// `short` truncation between passes via `s16`); running it on | ||
| 407 | + /// `coeffs` prints the expected block embedded in the assertion. | ||
| 408 | + /// | ||
| 409 | + /// ```python | ||
| 410 | + /// COS, SIN = 20091, 35468 | ||
| 411 | + /// def s16(x): | ||
| 412 | + /// x &= 0xFFFF | ||
| 413 | + /// return x - 0x10000 if x >= 0x8000 else x | ||
| 414 | + /// def idct(inp): | ||
| 415 | + /// out = [0] * 16 | ||
| 416 | + /// for i in range(4): # pass 1: columns, transposed into rows | ||
| 417 | + /// a1 = inp[i] + inp[8+i]; b1 = inp[i] - inp[8+i] | ||
| 418 | + /// c1 = ((inp[4+i]*SIN) >> 16) - (inp[12+i] + ((inp[12+i]*COS) >> 16)) | ||
| 419 | + /// d1 = (inp[4+i] + ((inp[4+i]*COS) >> 16)) + ((inp[12+i]*SIN) >> 16) | ||
| 420 | + /// out[i] = s16(a1 + d1); out[12+i] = s16(a1 - d1) | ||
| 421 | + /// out[4+i] = s16(b1 + c1); out[8+i] = s16(b1 - c1) | ||
| 422 | + /// res = [0] * 16 | ||
| 423 | + /// for i in range(4): # pass 2: rows, rounding (x + 4) >> 3 | ||
| 424 | + /// ip = out[4*i:4*i+4] | ||
| 425 | + /// a1 = ip[0] + ip[2]; b1 = ip[0] - ip[2] | ||
| 426 | + /// c1 = ((ip[1]*SIN) >> 16) - (ip[3] + ((ip[3]*COS) >> 16)) | ||
| 427 | + /// d1 = (ip[1] + ((ip[1]*COS) >> 16)) + ((ip[3]*SIN) >> 16) | ||
| 428 | + /// res[4*i+0] = s16((a1 + d1 + 4) >> 3) | ||
| 429 | + /// res[4*i+3] = s16((a1 - d1 + 4) >> 3) | ||
| 430 | + /// res[4*i+1] = s16((b1 + c1 + 4) >> 3) | ||
| 431 | + /// res[4*i+2] = s16((b1 - c1 + 4) >> 3) | ||
| 432 | + /// return res | ||
| 433 | + /// ``` | ||
| 434 | + #[test] | ||
| 435 | + fn idct_mixed_block_matches_oracle() { | ||
| 436 | + let coeffs = [ | ||
| 437 | + 87, -43, 210, 5, -19, 0, 33, -77, 1234, -517, 9, 401, -88, 2100, -3, 55, | ||
| 438 | + ]; | ||
| 439 | + assert_eq!( | ||
| 440 | + idct4x4(&coeffs), | ||
| 441 | + [ | ||
| 442 | + 305, 108, 139, 72, // | ||
| 443 | + -508, -228, -88, 303, // | ||
| 444 | + 372, 85, -443, -640, // | ||
| 445 | + -48, -41, 345, 441, | ||
| 446 | + ] | ||
| 447 | + ); | ||
| 448 | + } | ||
| 449 | + | ||
| 450 | + /// The DC-only shortcut must equal the full transform for any value | ||
| 451 | + /// at coefficient position 0 (with the rest zero), including the i16 | ||
| 452 | + /// extremes where the intermediate still fits. | ||
| 453 | + #[test] | ||
| 454 | + fn idct_dc_shortcut_matches_full_transform() { | ||
| 455 | + for v in [ | ||
| 456 | + 0, | ||
| 457 | + 1, | ||
| 458 | + -1, | ||
| 459 | + 8, | ||
| 460 | + -8, | ||
| 461 | + 40, | ||
| 462 | + -40, | ||
| 463 | + 100, | ||
| 464 | + -100, | ||
| 465 | + 4088, | ||
| 466 | + i16::MAX, | ||
| 467 | + i16::MIN, | ||
| 468 | + ] { | ||
| 469 | + let coeffs = { | ||
| 470 | + let mut c = [0i16; 16]; | ||
| 471 | + c[0] = v; | ||
| 472 | + c | ||
| 473 | + }; | ||
| 474 | + assert_eq!(idct4x4(&coeffs), idct4x4_dc(v), "mismatch at dc={v}"); | ||
| 475 | + } | ||
| 476 | + } | ||
| 477 | + | ||
| 478 | + /// §14.5: `idct4x4_add` is `clamp255(predict + idct4x4(coeffs))` | ||
| 479 | + /// pixelwise. With a flat prediction of 100, every output byte must | ||
| 480 | + /// be the saturated sum; extreme residuals clamp to 0 and 255. | ||
| 481 | + #[test] | ||
| 482 | + fn idct_add_equals_clamped_predict_plus_residual() { | ||
| 483 | + let coeffs = [ | ||
| 484 | + 87, -43, 210, 5, -19, 0, 33, -77, 1234, -517, 9, 401, -88, 2100, -3, 55, | ||
| 485 | + ]; | ||
| 486 | + let residual = idct4x4(&coeffs); | ||
| 487 | + let predict = [100u8; 16]; | ||
| 488 | + let mut recon = [0u8; 16]; | ||
| 489 | + idct4x4_add(&coeffs, &predict, &mut recon); | ||
| 490 | + for i in 0..16 { | ||
| 491 | + let expected = (residual[i] as i32 + 100).clamp(0, 255) as u8; | ||
| 492 | + assert_eq!(recon[i], expected, "pixel {i}"); | ||
| 493 | + } | ||
| 494 | + | ||
| 495 | + // Saturation: DC 4088 → residual (4088 + 4) >> 3 = 511; 100 + 511 | ||
| 496 | + // clamps to 255. Negative DC -32768 → residual (-32764) >> 3 = | ||
| 497 | + // -4096; clamps to 0. | ||
| 498 | + let mut hi = [0i16; 16]; | ||
| 499 | + hi[0] = 4088; | ||
| 500 | + let mut lo = [0i16; 16]; | ||
| 501 | + lo[0] = i16::MIN; | ||
| 502 | + let mut recon = [0u8; 16]; | ||
| 503 | + idct4x4_add(&hi, &predict, &mut recon); | ||
| 504 | + assert_eq!(recon, [255u8; 16]); | ||
| 505 | + idct4x4_add(&lo, &predict, &mut recon); | ||
| 506 | + assert_eq!(recon, [0u8; 16]); | ||
| 507 | + } | ||
| 508 | + | ||
| 509 | + /// `idct4x4_add` over an existing recon block that already holds the | ||
| 510 | + /// prediction (the common libvpx dst/pred shape). The `&[u8]` / | ||
| 511 | + /// `&mut [u8]` signature statically excludes predict/recon aliasing. | ||
| 512 | + #[test] | ||
| 513 | + fn idct_add_updates_existing_recon_buffer() { | ||
| 514 | + let coeffs = { | ||
| 515 | + let mut c = [0i16; 16]; | ||
| 516 | + c[0] = 40; | ||
| 517 | + c | ||
| 518 | + }; | ||
| 519 | + let predict = [100u8; 16]; | ||
| 520 | + let mut recon = [100u8; 16]; | ||
| 521 | + idct4x4_add(&coeffs, &predict, &mut recon); | ||
| 522 | + assert_eq!(recon, [105u8; 16]); | ||
| 523 | + } | ||
| 524 | + | ||
| 525 | + /// §14.1 tables, transcribed from libvpx `quant_common.c`: exact | ||
| 526 | + /// length plus boundary and known-trap entries (the duplicated 10 at | ||
| 527 | + /// dc[6..7], the >89 acceleration at dc[95..96] and dc[111..112], and | ||
| 528 | + /// the ac[54..55] and ac[84..85] jumps). | ||
| 529 | + #[test] | ||
| 530 | + fn quant_lookup_tables_match_libvpx() { | ||
| 531 | + assert_eq!(DC_QLOOKUP.len(), 128); | ||
| 532 | + assert_eq!(AC_QLOOKUP.len(), 128); | ||
| 533 | + assert_eq!(&DC_QLOOKUP[..3], &[4, 5, 6]); | ||
| 534 | + assert_eq!(DC_QLOOKUP[127], 157); | ||
| 535 | + assert_eq!(AC_QLOOKUP[0], 4); | ||
| 536 | + assert_eq!(AC_QLOOKUP[127], 284); | ||
| 537 | + assert_eq!(&DC_QLOOKUP[6..=8], &[10, 10, 11]); | ||
| 538 | + assert_eq!(&DC_QLOOKUP[95..=97], &[89, 91, 93]); | ||
| 539 | + assert_eq!(&DC_QLOOKUP[111..=112], &[118, 122]); | ||
| 540 | + assert_eq!(&AC_QLOOKUP[53..=55], &[57, 58, 60]); | ||
| 541 | + assert_eq!(&AC_QLOOKUP[83..=85], &[116, 119, 122]); | ||
| 542 | + } | ||
| 543 | + | ||
| 544 | + /// §14.1 boundary qindices: q=0 gives the minimum factors (with the | ||
| 545 | + /// Y2 AC floor of 8 already active), q=127 gives the maxima including | ||
| 546 | + /// the chroma DC cap at 132. | ||
| 547 | + #[test] | ||
| 548 | + fn dequant_at_qindex_boundaries() { | ||
| 549 | + assert_eq!( | ||
| 550 | + dequant(0, 0, 0, 0, 0, 0), | ||
| 551 | + Dequant { | ||
| 552 | + y1_dc: 4, | ||
| 553 | + y1_ac: 4, | ||
| 554 | + y2_dc: 8, | ||
| 555 | + y2_ac: 8, | ||
| 556 | + uv_dc: 4, | ||
| 557 | + uv_ac: 4 | ||
| 558 | + } | ||
| 559 | + ); | ||
| 560 | + assert_eq!( | ||
| 561 | + dequant(127, 0, 0, 0, 0, 0), | ||
| 562 | + Dequant { | ||
| 563 | + y1_dc: 157, | ||
| 564 | + y1_ac: 284, | ||
| 565 | + y2_dc: 314, | ||
| 566 | + y2_ac: 440, // 284 * 155 / 100 | ||
| 567 | + uv_dc: 132, // 157 capped at 132 | ||
| 568 | + uv_ac: 284, | ||
| 569 | + } | ||
| 570 | + ); | ||
| 571 | + } | ||
| 572 | + | ||
| 573 | + /// Delta-adjusted qindices clamp to [0, 127] before each lookup, for | ||
| 574 | + /// every delta channel (RFC 6386 §14.1 dixie `clamp_q`). | ||
| 575 | + #[test] | ||
| 576 | + fn dequant_delta_indices_clamp_to_qindex_range() { | ||
| 577 | + let lo = dequant(0, -1000, -1000, -1000, -1000, -1000); | ||
| 578 | + assert_eq!(lo.y1_dc, 4); | ||
| 579 | + assert_eq!(lo.y2_dc, 8); // 4 * 2 | ||
| 580 | + assert_eq!(lo.y2_ac, 8); // floor | ||
| 581 | + assert_eq!(lo.uv_dc, 4); | ||
| 582 | + assert_eq!(lo.uv_ac, 4); | ||
| 583 | + | ||
| 584 | + let hi = dequant(127, 1000, 1000, 1000, 1000, 1000); | ||
| 585 | + assert_eq!(hi.y1_dc, 157); | ||
| 586 | + assert_eq!(hi.y2_dc, 314); | ||
| 587 | + assert_eq!(hi.y2_ac, 440); | ||
| 588 | + assert_eq!(hi.uv_dc, 132); | ||
| 589 | + assert_eq!(hi.uv_ac, 284); | ||
| 590 | + | ||
| 591 | + // A base q of 0 with positive deltas reaches mid-table: q=60 has | ||
| 592 | + // dc_qlookup[60] = 55, ac_qlookup[60] = 70. | ||
| 593 | + let mid = dequant(0, 60, 60, 60, 60, 60); | ||
| 594 | + assert_eq!(mid.y1_dc, 55); | ||
| 595 | + assert_eq!(mid.y1_ac, 4); // Y AC has no delta channel | ||
| 596 | + assert_eq!(mid.y2_dc, 110); | ||
| 597 | + assert_eq!(mid.y2_ac, 70 * 155 / 100); // 108 | ||
| 598 | + assert_eq!(mid.uv_dc, 55); | ||
| 599 | + assert_eq!(mid.uv_ac, 70); | ||
| 600 | + } | ||
| 601 | + | ||
| 602 | + /// The Y2 AC floor: `x * 155 / 100 < 8` becomes 8. At q=0..4 | ||
| 603 | + /// (ac = 4..8) the scaled values are 6, 7, 9, 10, 12 — only the first | ||
| 604 | + /// two floor up. | ||
| 605 | + #[test] | ||
| 606 | + fn dequant_y2_ac_floor_at_eight() { | ||
| 607 | + for q in 0..=4i32 { | ||
| 608 | + let ac = AC_QLOOKUP[q as usize] as i32; | ||
| 609 | + let scaled = ac * 155 / 100; | ||
| 610 | + assert_eq!( | ||
| 611 | + dequant(q, 0, 0, 0, 0, 0).y2_ac as i32, | ||
| 612 | + scaled.max(8), | ||
| 613 | + "q={q}" | ||
| 614 | + ); | ||
| 615 | + } | ||
| 616 | + assert_eq!(dequant(0, 0, 0, 0, 0, 0).y2_ac, 8); // 4*155/100 = 6 → 8 | ||
| 617 | + assert_eq!(dequant(1, 0, 0, 0, 0, 0).y2_ac, 8); // 5*155/100 = 7 → 8 | ||
| 618 | + assert_eq!(dequant(2, 0, 0, 0, 0, 0).y2_ac, 9); // 6*155/100 = 9 | ||
| 619 | + } | ||
| 620 | + | ||
| 621 | + /// libvpx computes the Y2 AC factor as `(x * 101581) >> 16` and its | ||
| 622 | + /// comment asserts bitwise equality with `x * 155 / 100` for all | ||
| 623 | + /// table entries; our transcription of dixie uses `* 155 / 100`, so | ||
| 624 | + /// sweep the whole qindex range and prove the two agree through the | ||
| 625 | + /// public API (with a matching delta for the Y2 AC channel). | ||
| 626 | + #[test] | ||
| 627 | + fn dequant_y2_ac_matches_libvpx_fixed_point_over_all_q() { | ||
| 628 | + for q in 0..=127i32 { | ||
| 629 | + for delta in [0, -q - 1, 127 - q] { | ||
| 630 | + let x = AC_QLOOKUP[clamp_q(q + delta) as usize] as i32; | ||
| 631 | + let expected = (((x * 101581) >> 16).max(8)) as i16; | ||
| 632 | + assert_eq!( | ||
| 633 | + dequant(q, 0, 0, delta, 0, 0).y2_ac, | ||
| 634 | + expected, | ||
| 635 | + "q={q}, delta={delta}" | ||
| 636 | + ); | ||
| 637 | + } | ||
| 638 | + } | ||
| 639 | + } | ||
| 640 | +} | ||
crates/ec-vp8/tests/keyframe_exact.rsadded+114 -0
| @@ -0,0 +1,114 @@ | |||
| 1 | +//! M2 witness: key-frame decode is sample-exact against ffmpeg/libvpx | ||
| 2 | +//! (`ffmpeg -v error -i in.ivf -f rawvideo -pix_fmt yuv420p -`). | ||
| 3 | + | ||
| 4 | +mod ivf; | ||
| 5 | + | ||
| 6 | +use ec_vp8::decode::{Decoder, Picture}; | ||
| 7 | + | ||
| 8 | +/// ffmpeg's decoded rawvideo byte stream for the same file. | ||
| 9 | +fn ffmpeg_raw_yuv(path: &std::path::Path) -> Vec<u8> { | ||
| 10 | + let out = std::process::Command::new("ffmpeg") | ||
| 11 | + .args(["-v", "error", "-i"]) | ||
| 12 | + .arg(path) | ||
| 13 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) | ||
| 14 | + .output() | ||
| 15 | + .expect("ffmpeg must be on PATH for the witnesses"); | ||
| 16 | + assert!(out.status.success(), "ffmpeg failed on {path:?}"); | ||
| 17 | + out.stdout | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +fn raw<'a>(pos: &mut usize, data: &'a [u8], len: usize) -> &'a [u8] { | ||
| 21 | + let s = &data[*pos..*pos + len]; | ||
| 22 | + *pos += len; | ||
| 23 | + s | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/// Decode every frame of an IVF with our decoder and compare each | ||
| 27 | +/// frame's planes against ffmpeg's byte stream. | ||
| 28 | +fn compare(name: &str, skip_if_missing: bool) { | ||
| 29 | + let Some(dir) = ivf::fixture_dir() else { | ||
| 30 | + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); | ||
| 31 | + }; | ||
| 32 | + let path = dir.join(name); | ||
| 33 | + if skip_if_missing && !path.exists() { | ||
| 34 | + panic!("{name} missing (regenerate fixtures)"); | ||
| 35 | + } | ||
| 36 | + let bytes = std::fs::read(&path).unwrap(); | ||
| 37 | + let (_, w, h, frames) = ivf::parse_ivf(&bytes); | ||
| 38 | + let all = ffmpeg_raw_yuv(&path); | ||
| 39 | + let frame_len = usize::from(w) * usize::from(h) * 3 / 2; | ||
| 40 | + assert_eq!( | ||
| 41 | + all.len() % frame_len, | ||
| 42 | + 0, | ||
| 43 | + "{name}: ffmpeg output {}/{} not whole frames", | ||
| 44 | + all.len(), | ||
| 45 | + frame_len | ||
| 46 | + ); | ||
| 47 | + let count = all.len() / frame_len; | ||
| 48 | + assert_eq!(frames.len(), count, "{name}: frame count vs ffmpeg"); | ||
| 49 | + | ||
| 50 | + let mut dec = Decoder::new(); | ||
| 51 | + let (cw, ch) = (usize::from(w + 1) / 2, usize::from(h + 1) / 2); | ||
| 52 | + for (i, f) in frames.iter().enumerate() { | ||
| 53 | + let pic: Picture = dec | ||
| 54 | + .decode(&f.data) | ||
| 55 | + .expect("decode succeeds") | ||
| 56 | + .expect("shown"); | ||
| 57 | + assert_eq!(pic.width, w); | ||
| 58 | + assert_eq!(pic.height, h); | ||
| 59 | + let mut pos = i * frame_len; | ||
| 60 | + let exp_y = raw(&mut pos, &all, usize::from(w) * usize::from(h)); | ||
| 61 | + let exp_u = raw(&mut pos, &all, cw * ch); | ||
| 62 | + let exp_v = raw(&mut pos, &all, cw * ch); | ||
| 63 | + assert_eq!(pic.y, exp_y, "{name} frame {i}: luma mismatch"); | ||
| 64 | + assert_eq!(pic.u, exp_u, "{name} frame {i}: U mismatch"); | ||
| 65 | + assert_eq!(pic.v, exp_v, "{name} frame {i}: V mismatch"); | ||
| 66 | + } | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +#[test] | ||
| 70 | +fn keyframes_match_ffmpeg() { | ||
| 71 | + for (name, _, _) in [ | ||
| 72 | + ("kf-160x96-q20.ivf", 160, 96), | ||
| 73 | + ("kf-160x96-q40.ivf", 160, 96), | ||
| 74 | + ("kf-76x52-q30.ivf", 76, 52), | ||
| 75 | + ("kf-32x16-q35.ivf", 32, 16), | ||
| 76 | + ("kf-172x144-q25.ivf", 172, 144), | ||
| 77 | + ("kf-96x80-q63.ivf", 96, 80), | ||
| 78 | + ] { | ||
| 79 | + compare(name, false); | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +#[test] | ||
| 84 | +fn multi_partition_keyframe_matches_ffmpeg() { | ||
| 85 | + compare("mparts-160x96.ivf", false); | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +#[test] | ||
| 89 | +fn vp8_in_webp_still_matches_ffmpeg() { | ||
| 90 | + let Some(dir) = ivf::fixture_dir() else { | ||
| 91 | + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); | ||
| 92 | + }; | ||
| 93 | + let bytes = std::fs::read(dir.join("still.webp")).unwrap(); | ||
| 94 | + let vp8 = ivf::webp_vp8_chunk(&bytes); | ||
| 95 | + let reference = std::process::Command::new("ffmpeg") | ||
| 96 | + .args(["-v", "error", "-i"]) | ||
| 97 | + .arg(dir.join("still.webp")) | ||
| 98 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) | ||
| 99 | + .output() | ||
| 100 | + .unwrap(); | ||
| 101 | + assert!(reference.status.success()); | ||
| 102 | + let mut dec = Decoder::new(); | ||
| 103 | + let pic = dec.decode(&vp8).expect("decode").expect("shown"); | ||
| 104 | + assert_eq!( | ||
| 105 | + pic.y.len() + pic.u.len() + pic.v.len(), | ||
| 106 | + reference.stdout.len() | ||
| 107 | + ); | ||
| 108 | + let mut exp = &reference.stdout[..]; | ||
| 109 | + assert_eq!(pic.y, &exp[..pic.y.len()]); | ||
| 110 | + exp = &exp[pic.y.len()..]; | ||
| 111 | + assert_eq!(pic.u, &exp[..pic.u.len()]); | ||
| 112 | + exp = &exp[pic.u.len()..]; | ||
| 113 | + assert_eq!(pic.v, exp); | ||
| 114 | +} | ||
scripts/raw_to_y4m.pyadded+15 -0
| @@ -0,0 +1,15 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""Wrap raw planar yuv420p frames into a minimal y4m (for vpxenc). | ||
| 3 | + | ||
| 4 | + ffmpeg ... -f rawvideo - | raw_to_y4m.py W H FPS out.y4m | ||
| 5 | +""" | ||
| 6 | +import sys | ||
| 7 | + | ||
| 8 | +w, h, fps, out = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] | ||
| 9 | +frame = int(w) * int(h) * 3 // 2 | ||
| 10 | +raw = sys.stdin.buffer.read() | ||
| 11 | +with open(out, "wb") as f: | ||
| 12 | + f.write(f"YUV4MPEG2 W{w} H{h} F{fps}:1 Ip A1:1 C420jpeg\n".encode()) | ||
| 13 | + for i in range(len(raw) // frame): | ||
| 14 | + f.write(b"FRAME\n") | ||
| 15 | + f.write(raw[i * frame : (i + 1) * frame]) | ||