edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·9b67700·Tahinli·3 days ago·4021 commits
| 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::mc; |
| 18 | use crate::intra; |
| 19 | use crate::loopfilter::{self, MbFilterInfo}; |
| 20 | use crate::modes; |
| 21 | use crate::tables::KF_BMODE_PROB; |
| 22 | use crate::tokens::{self, Dq, MbCoeffs, TokenContexts}; |
| 23 | use crate::transform; |
| 24 | use crate::transform::Dequant; |
| 25 | use crate::{Error, PersistedState, Result}; |
| 26 | /// Copy a visible MB-aligned image out of the 1-pixel-bordered working |
| 27 | /// plane into the top-left visible corner of a bordered reference |
| 28 | /// buffer. |
| 29 | fn copy_plane( |
| 30 | dst: &mut [u8], |
| 31 | dst_stride: usize, |
| 32 | src: &[u8], |
| 33 | src_stride: usize, |
| 34 | w: usize, |
| 35 | h: usize, |
| 36 | ) { |
| 37 | for r in 0..h { |
| 38 | let s = (1 + r) * src_stride + 1; |
| 39 | let d = (MC_BORDER + r) * dst_stride + MC_BORDER; |
| 40 | dst[d..d + w].copy_from_slice(&src[s..s + w]); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | /// Reconstructed-image plane: a padded buffer with a 1-pixel left/top |
| 45 | /// border (127 on top including the corner, 129 on the left — RFC 6386 |
| 46 | /// §12) so intra prediction reads neighbours without special cases. |
| 47 | struct Plane { |
| 48 | data: Vec<u8>, |
| 49 | /// Row pitch: `1 + mb_cols * mb_size`. |
| 50 | stride: usize, |
| 51 | } |
| 52 | |
| 53 | impl Plane { |
| 54 | fn new(mb_cols: usize, mb_rows: usize, mb_size: usize) -> Self { |
| 55 | let stride = 1 + mb_cols * mb_size; |
| 56 | let rows = 1 + mb_rows * mb_size; |
| 57 | let mut data = vec![0u8; stride * rows]; |
| 58 | for cell in data[..stride].iter_mut() { |
| 59 | *cell = 127; |
| 60 | } |
| 61 | for row in 1..rows { |
| 62 | data[row * stride] = 129; |
| 63 | } |
| 64 | Plane { data, stride } |
| 65 | } |
| 66 | |
| 67 | fn resize(&mut self, mb_cols: usize, mb_rows: usize, mb_size: usize) { |
| 68 | *self = Plane::new(mb_cols, mb_rows, mb_size); |
| 69 | } |
| 70 | |
| 71 | /// Offset of pixel (x, y); the border occupies x = -1 / y = -1. |
| 72 | fn at(&self, x: usize, y: usize) -> usize { |
| 73 | (1 + y) * self.stride + 1 + x |
| 74 | } |
| 75 | |
| 76 | /// Offset of the pixel row ABOVE pixel row `y` (the border row for |
| 77 | /// y = 0), at pixel column `x`. |
| 78 | fn at_above(&self, x: usize, y: usize) -> usize { |
| 79 | y * self.stride + 1 + x |
| 80 | } |
| 81 | |
| 82 | /// Offset of the pixel column LEFT of pixel column `x` (the border |
| 83 | /// column for x = 0), at pixel row `y`. |
| 84 | fn at_left(&self, x: usize, y: usize) -> usize { |
| 85 | (1 + y) * self.stride + x |
| 86 | } |
| 87 | |
| 88 | /// Offset of the above-left pixel (border corner for x = y = 0). |
| 89 | fn at_above_left(&self, x: usize, y: usize) -> usize { |
| 90 | y * self.stride + x |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// One macroblock's parsed prediction record. |
| 95 | #[derive(Clone, Default)] |
| 96 | struct MbInfo { |
| 97 | /// [`modes::YMode`] as its coded integer. |
| 98 | y_mode: u8, |
| 99 | uv_mode: u8, |
| 100 | b_modes: [u8; 16], |
| 101 | segment_id: u8, |
| 102 | skip: bool, |
| 103 | /// 0 = intra, 1 = last, 2 = golden, 3 = altref (§16.2). Key-frame |
| 104 | /// MBs and the border are intra. |
| 105 | ref_frame: u8, |
| 106 | /// Inter mv_ref leaf (§16.2): 0 = zero, 1 = nearest, 2 = near, |
| 107 | /// 3 = new, 4 = split. 0 when intra. |
| 108 | mv_ref: u8, |
| 109 | /// Whole-MB motion vector in eighth-pels; the bottom-right subblock's |
| 110 | /// vector for SPLITMV (what future neighbours' census sees). |
| 111 | mv: (i16, i16), |
| 112 | /// Per-subblock motion vectors (SPLITMV). |
| 113 | bmi: [(i16, i16); 16], |
| 114 | /// `need_to_clamp_mvs` (§16.2): the luma MC clamps this MV into the |
| 115 | /// extended-frame range. |
| 116 | mv_clamp: bool, |
| 117 | /// Any non-zero coefficient decoded for this MB (bit 31 of dixie's |
| 118 | /// eob_mask); decides the loop filter's interior edges (§15.1). |
| 119 | has_nz: bool, |
| 120 | } |
| 121 | |
| 122 | /// One reference-frame slot: bordered planes, 32-pixel edge-replicated |
| 123 | /// borders around the MB-aligned image (dixie `extend_frame`). |
| 124 | #[derive(Clone)] |
| 125 | struct RefFrame { |
| 126 | y: Vec<u8>, |
| 127 | u: Vec<u8>, |
| 128 | v: Vec<u8>, |
| 129 | stride: usize, |
| 130 | uv_stride: usize, |
| 131 | } |
| 132 | |
| 133 | /// MC border width in pixels (libvpx `VP8BORDERINPIXELS`). |
| 134 | const MC_BORDER: usize = 32; |
| 135 | |
| 136 | impl MbInfo { |
| 137 | fn has_y2(&self) -> bool { |
| 138 | self.y_mode != modes::YMode::BPred.as_u8() |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | /// The VP8 decoder. Feed complete frames (one full VP8 frame payload, |
| 143 | /// exactly what a container demuxer hands over for the `VP80`/`vp08` |
| 144 | /// codec). |
| 145 | pub struct Decoder { |
| 146 | state: PersistedState, |
| 147 | dims: KeyFrameDims, |
| 148 | mb_cols: usize, |
| 149 | mb_rows: usize, |
| 150 | y: Plane, |
| 151 | u: Plane, |
| 152 | v: Plane, |
| 153 | /// `(mb_rows + 1) * (mb_cols + 1)` records; row/column index 0 is the |
| 154 | /// DC_PRED border (dixie's `mb_info` border trick). |
| 155 | mb_info: Vec<MbInfo>, |
| 156 | token_ctxs: TokenContexts, |
| 157 | /// Reference frame slots: [unused, last, golden, altref] (§16.2 |
| 158 | /// indices). Empty until the first key frame. |
| 159 | refs: [Option<RefFrame>; 4], |
| 160 | /// Persisted per-MB segment ids, `mb_rows * mb_cols` (§9.3: when a |
| 161 | /// frame does not re-code the map, ids carry over). |
| 162 | segment_map: Vec<u8>, |
| 163 | frame_decoded: bool, |
| 164 | /// Per-frame MC filter selection (libvpx `vp8_setup_version`, |
| 165 | /// alloccommon.c:131-167: version 0 and the reserved 4-7 use the |
| 166 | /// six-tap filters, versions 1-3 the bilinear ones) and full-pel |
| 167 | /// flag (version 3: `fullpixel_mask = ~7`). The decoder never reads |
| 168 | /// `no_lpf` — dead there too. |
| 169 | mc_bilinear: bool, |
| 170 | mc_fullpel: bool, |
| 171 | } |
| 172 | |
| 173 | /// A decoded, displayable frame: cropped contiguous planes. |
| 174 | #[derive(Clone)] |
| 175 | pub struct Picture { |
| 176 | /// Luma plane, `stride`-spaced rows of `width` pixels. |
| 177 | pub y: Vec<u8>, |
| 178 | /// U (Cb) plane, half resolution. |
| 179 | pub u: Vec<u8>, |
| 180 | /// V (Cr) plane, half resolution. |
| 181 | pub v: Vec<u8>, |
| 182 | /// Frame width in pixels. |
| 183 | pub width: u16, |
| 184 | /// Frame height in pixels. |
| 185 | pub height: u16, |
| 186 | /// Luma row pitch of the returned planes. |
| 187 | pub stride: usize, |
| 188 | /// Chroma row pitch of the returned planes. |
| 189 | pub uv_stride: usize, |
| 190 | } |
| 191 | |
| 192 | impl Decoder { |
| 193 | /// Create an empty decoder; the first key frame sets the size. |
| 194 | pub fn new() -> Self { |
| 195 | Self { |
| 196 | state: PersistedState::default(), |
| 197 | dims: KeyFrameDims { |
| 198 | width: 0, |
| 199 | height: 0, |
| 200 | h_scale: 0, |
| 201 | v_scale: 0, |
| 202 | }, |
| 203 | mb_cols: 0, |
| 204 | mb_rows: 0, |
| 205 | y: Plane { |
| 206 | data: Vec::new(), |
| 207 | stride: 0, |
| 208 | }, |
| 209 | u: Plane { |
| 210 | data: Vec::new(), |
| 211 | stride: 0, |
| 212 | }, |
| 213 | v: Plane { |
| 214 | data: Vec::new(), |
| 215 | stride: 0, |
| 216 | }, |
| 217 | mb_info: Vec::new(), |
| 218 | token_ctxs: TokenContexts::new(0), |
| 219 | refs: [None, None, None, None], |
| 220 | segment_map: Vec::new(), |
| 221 | frame_decoded: false, |
| 222 | mc_bilinear: false, |
| 223 | mc_fullpel: false, |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /// Size of the frames this decoder produces, once known. |
| 228 | pub fn dimensions(&self) -> Option<(u16, u16)> { |
| 229 | self.frame_decoded |
| 230 | .then_some((self.dims.width, self.dims.height)) |
| 231 | } |
| 232 | |
| 233 | /// Decode one frame; returns the picture when it is for display |
| 234 | /// (`show_frame`). Hidden frames still update the decode state. |
| 235 | pub fn decode(&mut self, frame: &[u8]) -> Result<Option<Picture>> { |
| 236 | // Entropy revert (§9.7, libvpx decodeframe.c:1156/1245): when |
| 237 | // `refresh_entropy` is 0 the frame's probability updates are |
| 238 | // transient — libvpx copies `fc` into `lfc` at this point in |
| 239 | // the header and restores it after the frame. On a KEY frame |
| 240 | // `fc` has already been reset to defaults by then (init_frame |
| 241 | // runs before header parsing), so a key frame with |
| 242 | // refresh_entropy == 0 reverts to DEFAULTS, not to whatever the |
| 243 | // previous stream carried. Segmentation and loop-filter deltas |
| 244 | // live outside `fc` and never revert. |
| 245 | let key = frame.first().is_some_and(|b| b & 1 == 0); |
| 246 | // An inter frame needs a decoded key frame to predict from. Reject it |
| 247 | // before header parsing touches the persisted state. |
| 248 | if !key && !self.has_reference_frames() { |
| 249 | return Err(Error::corrupt("VP8 inter frame before the first key frame")); |
| 250 | } |
| 251 | let defaults = PersistedState::default(); |
| 252 | let (coeff_probs, mv_probs, ymode_probs, uv_mode_probs) = if key { |
| 253 | ( |
| 254 | defaults.coeff_probs, |
| 255 | defaults.mv_probs, |
| 256 | defaults.ymode_probs, |
| 257 | defaults.uv_mode_probs, |
| 258 | ) |
| 259 | } else { |
| 260 | ( |
| 261 | self.state.coeff_probs, |
| 262 | self.state.mv_probs, |
| 263 | self.state.ymode_probs, |
| 264 | self.state.uv_mode_probs, |
| 265 | ) |
| 266 | }; |
| 267 | let (header, hdr_dec) = FrameHeader::parse(frame, &mut self.state)?; |
| 268 | // vp8_setup_version (decodeframe.c:935): the tag's version bits |
| 269 | // pick the MC interpolation filter and full-pel mode for this |
| 270 | // frame (see the field docs on Decoder). |
| 271 | self.mc_bilinear = matches!(header.tag.version, 1..=3); |
| 272 | self.mc_fullpel = header.tag.version == 3; |
| 273 | let refresh_entropy = header.refresh.refresh_entropy; |
| 274 | let pic = match header.tag.frame_type { |
| 275 | FrameType::Key => self.decode_keyframe(frame, header, hdr_dec), |
| 276 | FrameType::Inter => self.decode_interframe(frame, header, hdr_dec), |
| 277 | }?; |
| 278 | if !refresh_entropy { |
| 279 | self.state.coeff_probs = coeff_probs; |
| 280 | self.state.mv_probs = mv_probs; |
| 281 | self.state.ymode_probs = ymode_probs; |
| 282 | self.state.uv_mode_probs = uv_mode_probs; |
| 283 | } |
| 284 | Ok(pic) |
| 285 | } |
| 286 | |
| 287 | /// True once a key frame has sized the buffers and filled every reference slot. |
| 288 | fn has_reference_frames(&self) -> bool { |
| 289 | self.mb_cols != 0 && self.refs[1..4].iter().all(|r| r.is_some()) |
| 290 | } |
| 291 | |
| 292 | fn ensure_buffers(&mut self, kf: KeyFrameDims) { |
| 293 | let (mb_cols, mb_rows) = mb_geometry(kf.width, kf.height); |
| 294 | if self.mb_cols != mb_cols || self.mb_rows != mb_rows { |
| 295 | self.y.resize(mb_cols, mb_rows, 16); |
| 296 | self.u.resize(mb_cols, mb_rows, 8); |
| 297 | self.v.resize(mb_cols, mb_rows, 8); |
| 298 | self.mb_info = vec![MbInfo::default(); (mb_cols + 1) * (mb_rows + 1)]; |
| 299 | self.token_ctxs = TokenContexts::new(mb_cols); |
| 300 | } |
| 301 | self.mb_cols = mb_cols; |
| 302 | self.mb_rows = mb_rows; |
| 303 | self.dims = kf; |
| 304 | // Reset the mode border (row 0 / column 0) so the top-left mode |
| 305 | // contexts read DC_PRED like a fresh decode. |
| 306 | for col in 0..=mb_cols { |
| 307 | self.mb_info[col] = MbInfo::default(); |
| 308 | } |
| 309 | for row in 0..=mb_rows { |
| 310 | self.mb_info[row * (mb_cols + 1)] = MbInfo::default(); |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | /// Mode-record index for MB (row, col); row/col 0 is the border. |
| 315 | fn mbi(&self, row: usize, col: usize) -> &MbInfo { |
| 316 | &self.mb_info[row * (self.mb_cols + 1) + col] |
| 317 | } |
| 318 | |
| 319 | fn mbi_mut(&mut self, row: usize, col: usize) -> &mut MbInfo { |
| 320 | let w = self.mb_cols + 1; |
| 321 | &mut self.mb_info[row * w + col] |
| 322 | } |
| 323 | |
| 324 | fn decode_keyframe( |
| 325 | &mut self, |
| 326 | frame: &[u8], |
| 327 | header: FrameHeader, |
| 328 | mut hdr_dec: BoolDecoder<'_>, |
| 329 | ) -> Result<Option<Picture>> { |
| 330 | let kf = header |
| 331 | .dims |
| 332 | .ok_or_else(|| Error::corrupt("VP8 key frame without dimensions"))?; |
| 333 | self.ensure_buffers(kf); |
| 334 | |
| 335 | // Token partition bool decoders (§9.5). |
| 336 | let mut partitions = Vec::with_capacity(header.partition_sizes.len()); |
| 337 | let mut off = header.token_data_offset + 3 * (header.partition_sizes.len() - 1); |
| 338 | for &sz in &header.partition_sizes { |
| 339 | let end = off + sz as usize; |
| 340 | let slice = frame |
| 341 | .get(off..end) |
| 342 | .ok_or_else(|| Error::corrupt("VP8 token partition extends past frame end"))?; |
| 343 | partitions.push(BoolDecoder::new(slice)?); |
| 344 | off = end; |
| 345 | } |
| 346 | |
| 347 | // Dequant factors per segment (dixie dequant_init, §10/§14.1). |
| 348 | let seg = &header.segmentation; |
| 349 | let mut dqf = [Dequant { |
| 350 | y1_dc: 0, |
| 351 | y1_ac: 0, |
| 352 | y2_dc: 0, |
| 353 | y2_ac: 0, |
| 354 | uv_dc: 0, |
| 355 | uv_ac: 0, |
| 356 | }; 4]; |
| 357 | for (i, dq) in dqf.iter_mut().enumerate() { |
| 358 | let q = if seg.enabled { |
| 359 | if seg.abs_delta { |
| 360 | seg.quant_idx[i] |
| 361 | } else { |
| 362 | i32::from(header.quant.yac_qi) + seg.quant_idx[i] |
| 363 | } |
| 364 | } else { |
| 365 | i32::from(header.quant.yac_qi) |
| 366 | }; |
| 367 | *dq = transform::dequant( |
| 368 | q, |
| 369 | header.quant.ydc_delta, |
| 370 | header.quant.y2dc_delta, |
| 371 | header.quant.y2ac_delta, |
| 372 | header.quant.uvdc_delta, |
| 373 | header.quant.uvac_delta, |
| 374 | ); |
| 375 | } |
| 376 | |
| 377 | self.token_ctxs.reset_above_row(); |
| 378 | |
| 379 | for row in 1..=self.mb_rows { |
| 380 | self.token_ctxs.reset_left(); |
| 381 | // Phase 1: parse every mode record of the row (partition 0). |
| 382 | for col in 1..=self.mb_cols { |
| 383 | let mut mb = MbInfo::default(); |
| 384 | if header.segmentation.enabled && header.segmentation.update_map { |
| 385 | mb.segment_id = |
| 386 | hdr_dec.read_tree(&SEGMENT_TREE, &header.segmentation.tree_probs); |
| 387 | } |
| 388 | if header.coeff_skip_enabled { |
| 389 | mb.skip = hdr_dec.read_bool(header.prob_skip_false); |
| 390 | } |
| 391 | self.decode_kf_modes(&mut hdr_dec, row, col, &mut mb); |
| 392 | *self.mbi_mut(row, col) = mb; |
| 393 | } |
| 394 | |
| 395 | // Phases 2+3 per MB: tokens then reconstruction. Token row |
| 396 | // `r` (0-based) reads partition `r % n` like the reference. |
| 397 | let part = (row - 1) % partitions.len(); |
| 398 | for col in 1..=self.mb_cols { |
| 399 | if crate::trace_enabled() { |
| 400 | eprintln!("M {} {}", row - 1, col - 1); |
| 401 | } |
| 402 | let mb = self.mbi(row, col).clone(); |
| 403 | let has_y2 = mb.has_y2(); |
| 404 | let seg_i = usize::from(header.segmentation.enabled) * usize::from(mb.segment_id); |
| 405 | let dq = &dqf[seg_i]; |
| 406 | let mb_dq = Dq { |
| 407 | y1_dc: dq.y1_dc, |
| 408 | y1_ac: dq.y1_ac, |
| 409 | uv_dc: dq.uv_dc, |
| 410 | uv_ac: dq.uv_ac, |
| 411 | y2_dc: dq.y2_dc, |
| 412 | y2_ac: dq.y2_ac, |
| 413 | }; |
| 414 | if crate::trace_enabled() { |
| 415 | eprintln!("T {} {} hy2={}", row - 1, col - 1, has_y2); |
| 416 | } |
| 417 | let probs = self.state.coeff_probs; |
| 418 | let coeffs = if mb.skip { |
| 419 | tokens::skip_mb_tokens(&mut self.token_ctxs, col - 1, has_y2) |
| 420 | } else { |
| 421 | tokens::decode_mb_tokens( |
| 422 | &mut partitions[part], |
| 423 | &probs, |
| 424 | &mb_dq, |
| 425 | has_y2, |
| 426 | &mut self.token_ctxs, |
| 427 | col - 1, |
| 428 | ) |
| 429 | }; |
| 430 | self.mb_info[row * (self.mb_cols + 1) + col].has_nz = coeffs.has_nonzero(); |
| 431 | self.reconstruct_intra_mb(row - 1, col - 1, &mb, &coeffs)?; |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | // Loop filter post-pass (see module docs for the ordering |
| 436 | // equivalence argument). |
| 437 | self.run_loopfilter(&header, true)?; |
| 438 | |
| 439 | // A key frame refreshes every reference slot and clears the |
| 440 | // persisted segment map (§9.3, §9.7). |
| 441 | self.segment_map = vec![0; self.mb_cols * self.mb_rows]; |
| 442 | let rf = self.make_ref(); |
| 443 | self.refs[1] = Some(rf.clone()); |
| 444 | self.refs[2] = Some(rf.clone()); |
| 445 | self.refs[3] = Some(rf); |
| 446 | |
| 447 | self.frame_decoded = true; |
| 448 | Ok(header.tag.show_frame.then(|| self.crop())) |
| 449 | } |
| 450 | |
| 451 | /// Loop-filter post-pass over the whole frame (dixie order-equivalent |
| 452 | /// driver; `inner_edges` follows libvpx's `skip_lf`: skipped MBs |
| 453 | /// filter only their boundary edges, except 4x4-coded modes). |
| 454 | fn run_loopfilter(&mut self, header: &FrameHeader, is_keyframe: bool) -> Result<()> { |
| 455 | if header.filter_level == 0 { |
| 456 | return Ok(()); |
| 457 | } |
| 458 | let infos: Vec<MbFilterInfo> = (0..self.mb_rows) |
| 459 | .flat_map(|r| (0..self.mb_cols).map(move |c| (r, c))) |
| 460 | .map(|(r, c)| { |
| 461 | let mb = self.mbi(r + 1, c + 1); |
| 462 | MbFilterInfo { |
| 463 | level: self.mb_filter_level(header, mb), |
| 464 | inner_edges: mb.has_nz || !mb.has_y2(), |
| 465 | } |
| 466 | }) |
| 467 | .collect(); |
| 468 | // The planes are bordered; the filter sees the unbordered |
| 469 | // image (same row pitch) starting at pixel (0, 0). |
| 470 | let (ystride, ustride, vstride) = (self.y.stride, self.u.stride, self.v.stride); |
| 471 | let (mcols, mrows) = (self.mb_cols, self.mb_rows); |
| 472 | let simple = header.filter_type == 1; |
| 473 | let sharpness = header.sharpness_level; |
| 474 | let yimg = &mut self.y.data[1 + ystride..]; |
| 475 | let uimg = &mut self.u.data[1 + ustride..]; |
| 476 | let vimg = &mut self.v.data[1 + vstride..]; |
| 477 | loopfilter::filter_frame_ex( |
| 478 | yimg, uimg, vimg, ystride, ustride, mcols, mrows, sharpness, simple, &infos, |
| 479 | is_keyframe, |
| 480 | ) |
| 481 | } |
| 482 | |
| 483 | /// Snapshot the reconstructed (post-LF) frame into a bordered |
| 484 | /// reference buffer with 32-pixel edge-replicated borders. |
| 485 | fn make_ref(&self) -> RefFrame { |
| 486 | let w = self.mb_cols * 16; |
| 487 | let h = self.mb_rows * 16; |
| 488 | let (cw, ch) = (self.mb_cols * 8, self.mb_rows * 8); |
| 489 | let mut rf = RefFrame { |
| 490 | y: vec![0; (w + 2 * MC_BORDER) * (h + 2 * MC_BORDER)], |
| 491 | u: vec![0; (cw + 2 * MC_BORDER) * (ch + 2 * MC_BORDER)], |
| 492 | v: vec![0; (cw + 2 * MC_BORDER) * (ch + 2 * MC_BORDER)], |
| 493 | stride: w + 2 * MC_BORDER, |
| 494 | uv_stride: cw + 2 * MC_BORDER, |
| 495 | }; |
| 496 | copy_plane(&mut rf.y, rf.stride, &self.y.data, self.y.stride, w, h); |
| 497 | copy_plane(&mut rf.u, rf.uv_stride, &self.u.data, self.u.stride, cw, ch); |
| 498 | copy_plane(&mut rf.v, rf.uv_stride, &self.v.data, self.v.stride, cw, ch); |
| 499 | mc::extend_plane(&mut rf.y, rf.stride, w, h, MC_BORDER); |
| 500 | mc::extend_plane(&mut rf.u, rf.uv_stride, cw, ch, MC_BORDER); |
| 501 | mc::extend_plane(&mut rf.v, rf.uv_stride, cw, ch, MC_BORDER); |
| 502 | rf |
| 503 | } |
| 504 | |
| 505 | |
| 506 | /// Per-MB loop filter level (libvpx `loop_filter_frame_init`): |
| 507 | /// segment level (clamped), then the reference delta, then the mode |
| 508 | /// delta, clamped again. Mode slots: intra B_PRED → 0, other intra |
| 509 | /// and ZEROMV → 1 (no delta for other intra), the moving modes → 2, |
| 510 | /// SPLITMV → 3. |
| 511 | fn mb_filter_level(&self, header: &FrameHeader, mb: &MbInfo) -> u8 { |
| 512 | let seg = &header.segmentation; |
| 513 | let mut level = i32::from(header.filter_level); |
| 514 | if seg.enabled { |
| 515 | let d = seg.lf_level[usize::from(mb.segment_id)]; |
| 516 | level = if seg.abs_delta { d } else { level + d }; |
| 517 | } |
| 518 | level = level.clamp(0, 63); |
| 519 | if header.lf_delta_enabled { |
| 520 | level += self.state.ref_lf_delta[usize::from(mb.ref_frame)]; |
| 521 | let mode_idx = if mb.ref_frame == 0 { |
| 522 | if mb.y_mode == modes::YMode::BPred.as_u8() { |
| 523 | Some(0) |
| 524 | } else { |
| 525 | None |
| 526 | } |
| 527 | } else { |
| 528 | match mb.mv_ref { |
| 529 | 0 => Some(1), // ZEROMV |
| 530 | 4 => Some(3), // SPLITMV |
| 531 | _ => Some(2), // NEAREST / NEAR / NEW |
| 532 | } |
| 533 | }; |
| 534 | if let Some(mode_idx) = mode_idx { |
| 535 | level += self.state.mode_lf_delta[mode_idx]; |
| 536 | } |
| 537 | level = level.clamp(0, 63); |
| 538 | } |
| 539 | level as u8 |
| 540 | } |
| 541 | /// Decode one inter frame (§16): all mode records off partition 0 |
| 542 | /// (row-major), then per-row tokens and reconstruction off the row's |
| 543 | /// token partition, loop filter, then the reference updates (§9.7). |
| 544 | fn decode_interframe( |
| 545 | &mut self, |
| 546 | frame: &[u8], |
| 547 | header: FrameHeader, |
| 548 | mut hdr_dec: BoolDecoder<'_>, |
| 549 | ) -> Result<Option<Picture>> { |
| 550 | if !self.has_reference_frames() { |
| 551 | return Err(Error::corrupt("VP8 inter frame before the first key frame")); |
| 552 | } |
| 553 | |
| 554 | // Token partition bool decoders (§9.5) — identical tiling to |
| 555 | // key frames. |
| 556 | let mut partitions = Vec::with_capacity(header.partition_sizes.len()); |
| 557 | let mut off = header.token_data_offset + 3 * (header.partition_sizes.len() - 1); |
| 558 | for &sz in &header.partition_sizes { |
| 559 | let end = off + sz as usize; |
| 560 | let slice = frame |
| 561 | .get(off..end) |
| 562 | .ok_or_else(|| Error::corrupt("VP8 token partition extends past frame end"))?; |
| 563 | partitions.push(BoolDecoder::new(slice)?); |
| 564 | off = end; |
| 565 | } |
| 566 | |
| 567 | // Dequant factors per segment (persisted segmentation state). |
| 568 | let seg = &header.segmentation; |
| 569 | let mut dqf = [Dequant { |
| 570 | y1_dc: 0, |
| 571 | y1_ac: 0, |
| 572 | y2_dc: 0, |
| 573 | y2_ac: 0, |
| 574 | uv_dc: 0, |
| 575 | uv_ac: 0, |
| 576 | }; 4]; |
| 577 | for (i, dq) in dqf.iter_mut().enumerate() { |
| 578 | let q = if seg.enabled { |
| 579 | if seg.abs_delta { |
| 580 | seg.quant_idx[i] |
| 581 | } else { |
| 582 | i32::from(header.quant.yac_qi) + seg.quant_idx[i] |
| 583 | } |
| 584 | } else { |
| 585 | i32::from(header.quant.yac_qi) |
| 586 | }; |
| 587 | *dq = transform::dequant( |
| 588 | q, |
| 589 | header.quant.ydc_delta, |
| 590 | header.quant.y2dc_delta, |
| 591 | header.quant.y2ac_delta, |
| 592 | header.quant.uvdc_delta, |
| 593 | header.quant.uvac_delta, |
| 594 | ); |
| 595 | } |
| 596 | let ymode_probs = self.state.ymode_probs; |
| 597 | let uv_mode_probs = self.state.uv_mode_probs; |
| 598 | let sign_bias = [ |
| 599 | false, |
| 600 | header.refresh.sign_bias_golden, |
| 601 | header.refresh.sign_bias_altref, |
| 602 | ]; |
| 603 | |
| 604 | // §13.3: non-existent neighbours are empty — the above context |
| 605 | // is cleared at every frame start, like the key-frame path. |
| 606 | self.token_ctxs.reset_above_row(); |
| 607 | |
| 608 | // Phase 1: every mode record of the frame, row-major (§16). |
| 609 | if crate::trace_enabled() { |
| 610 | eprintln!("STAGE modes"); |
| 611 | } |
| 612 | for row in 1..=self.mb_rows { |
| 613 | for col in 1..=self.mb_cols { |
| 614 | let mut mb = MbInfo::default(); |
| 615 | if header.segmentation.enabled { |
| 616 | if header.segmentation.update_map { |
| 617 | mb.segment_id = |
| 618 | hdr_dec.read_tree(&SEGMENT_TREE, &header.segmentation.tree_probs); |
| 619 | self.segment_map[(row - 1) * self.mb_cols + (col - 1)] = mb.segment_id; |
| 620 | } else { |
| 621 | mb.segment_id = self.segment_map[(row - 1) * self.mb_cols + (col - 1)]; |
| 622 | } |
| 623 | } |
| 624 | if header.coeff_skip_enabled { |
| 625 | mb.skip = hdr_dec.read_bool(header.prob_skip_false); |
| 626 | } |
| 627 | self.parse_inter_modes( |
| 628 | &mut hdr_dec, |
| 629 | row, |
| 630 | col, |
| 631 | &mut mb, |
| 632 | &header, |
| 633 | &ymode_probs, |
| 634 | &uv_mode_probs, |
| 635 | &sign_bias, |
| 636 | ); |
| 637 | *self.mbi_mut(row, col) = mb; |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | // Phases 2+3 per row: tokens, then reconstruction (MC or intra). |
| 642 | for row in 1..=self.mb_rows { |
| 643 | self.token_ctxs.reset_left(); |
| 644 | let part = (row - 1) % partitions.len(); |
| 645 | for col in 1..=self.mb_cols { |
| 646 | let mb = self.mbi(row, col).clone(); |
| 647 | let has_y2 = mb.has_y2(); |
| 648 | let seg_i = usize::from(header.segmentation.enabled) * usize::from(mb.segment_id); |
| 649 | let dq = &dqf[seg_i]; |
| 650 | let mb_dq = Dq { |
| 651 | y1_dc: dq.y1_dc, |
| 652 | y1_ac: dq.y1_ac, |
| 653 | uv_dc: dq.uv_dc, |
| 654 | uv_ac: dq.uv_ac, |
| 655 | y2_dc: dq.y2_dc, |
| 656 | y2_ac: dq.y2_ac, |
| 657 | }; |
| 658 | let probs = self.state.coeff_probs; |
| 659 | let coeffs = if mb.skip { |
| 660 | tokens::skip_mb_tokens(&mut self.token_ctxs, col - 1, has_y2) |
| 661 | } else { |
| 662 | tokens::decode_mb_tokens( |
| 663 | &mut partitions[part], |
| 664 | &probs, |
| 665 | &mb_dq, |
| 666 | has_y2, |
| 667 | &mut self.token_ctxs, |
| 668 | col - 1, |
| 669 | ) |
| 670 | }; |
| 671 | { |
| 672 | // "Special case: force the loop filter to skip when |
| 673 | // eobtotal is zero" (libvpx decodeframe.c): a decoded |
| 674 | // MB without non-zero coefficients filters like a |
| 675 | // skipped one. |
| 676 | let slot = &mut self.mb_info[row * (self.mb_cols + 1) + col]; |
| 677 | slot.has_nz = coeffs.has_nonzero(); |
| 678 | slot.skip = mb.skip || !coeffs.has_nonzero(); |
| 679 | } |
| 680 | self.reconstruct_inter_mb(row - 1, col - 1, &mb, &coeffs)?; |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | self.run_loopfilter(&header, false)?; |
| 685 | |
| 686 | // Reference buffer updates, libvpx `swap_frame_buffers` order: |
| 687 | // the copies run first (copy_gf = 2 must see a possibly |
| 688 | // just-updated altref), then the refreshes, then last. |
| 689 | let new = self.make_ref(); |
| 690 | match header.refresh.copy_arf { |
| 691 | 1 => self.refs[3] = self.refs[1].clone(), |
| 692 | 2 => self.refs[3] = self.refs[2].clone(), |
| 693 | _ => {} |
| 694 | } |
| 695 | match header.refresh.copy_gf { |
| 696 | 1 => self.refs[2] = self.refs[1].clone(), |
| 697 | 2 => self.refs[2] = self.refs[3].clone(), |
| 698 | _ => {} |
| 699 | } |
| 700 | if header.refresh.refresh_gf { |
| 701 | self.refs[2] = Some(new.clone()); |
| 702 | } |
| 703 | if header.refresh.refresh_arf { |
| 704 | self.refs[3] = Some(new.clone()); |
| 705 | } |
| 706 | if header.refresh.refresh_last { |
| 707 | self.refs[1] = Some(new); |
| 708 | } |
| 709 | |
| 710 | self.frame_decoded = true; |
| 711 | Ok(header.tag.show_frame.then(|| self.crop())) |
| 712 | } |
| 713 | |
| 714 | /// Inter-frame mode record (§16, libvpx `read_mb_modes_mv`): intra |
| 715 | /// at the persisted mode probabilities, or an inter mode with its |
| 716 | /// motion vectors off the neighborhood census. |
| 717 | #[allow(clippy::too_many_arguments)] |
| 718 | fn parse_inter_modes( |
| 719 | &mut self, |
| 720 | d: &mut BoolDecoder<'_>, |
| 721 | row: usize, |
| 722 | col: usize, |
| 723 | mb: &mut MbInfo, |
| 724 | header: &FrameHeader, |
| 725 | ymode_probs: &[u8; 4], |
| 726 | uv_mode_probs: &[u8; 3], |
| 727 | sign_bias: &[bool; 3], |
| 728 | ) { |
| 729 | if !d.read_bool(header.prob_intra) { |
| 730 | // Intra-coded MB inside an inter frame (§16.1). Subblock |
| 731 | // modes decode at one CONSTANT probability array with no |
| 732 | // above/left context (libvpx decodemv.c:467 reads |
| 733 | // `fc.bmode_prob` — the flat vp8_bmode_prob default; the |
| 734 | // context-dependent kf_bmode_prob table is key-frame-only). |
| 735 | mb.ref_frame = 0; |
| 736 | let ymode = modes::read_ymode(d, ymode_probs); |
| 737 | mb.y_mode = ymode.as_u8(); |
| 738 | if ymode == modes::YMode::BPred { |
| 739 | for j in 0..16usize { |
| 740 | mb.b_modes[j] = modes::read_bmode(d, &modes::INTER_BMODE_PROBS).as_u8(); |
| 741 | } |
| 742 | } |
| 743 | mb.uv_mode = modes::read_uvmode(d, uv_mode_probs).as_u8(); |
| 744 | return; |
| 745 | } |
| 746 | |
| 747 | mb.ref_frame = if !d.read_bool(header.prob_last) { |
| 748 | 1 |
| 749 | } else if !d.read_bool(header.prob_gf) { |
| 750 | 2 |
| 751 | } else { |
| 752 | 3 |
| 753 | }; |
| 754 | let to_bias = sign_bias[usize::from(mb.ref_frame) - 1]; |
| 755 | |
| 756 | let edges = modes::mb_edges(col - 1, row - 1, self.mb_cols, self.mb_rows); |
| 757 | let above = self.mv_neighbor(row - 1, col, sign_bias); |
| 758 | let left = self.mv_neighbor(row, col - 1, sign_bias); |
| 759 | let aboveleft = self.mv_neighbor(row - 1, col - 1, sign_bias); |
| 760 | let (mut near_mvs, cnt) = modes::find_near_mvs(above, left, aboveleft, to_bias); |
| 761 | if crate::trace_enabled() { |
| 762 | eprintln!("CNT r={} c={} cnt={:?} mvs={:?}", row - 1, col - 1, cnt, near_mvs); |
| 763 | } |
| 764 | |
| 765 | if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_INTRA] as usize][0]) { |
| 766 | mb.mv_ref = 0; // ZEROMV |
| 767 | return; |
| 768 | } |
| 769 | if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_NEAREST] as usize][1]) { |
| 770 | mb.mv_ref = 1; // NEARESTMV |
| 771 | mb.mv = near_mvs[modes::CNT_NEAREST]; |
| 772 | modes::clamp_mv2(&mut mb.mv, edges); |
| 773 | return; |
| 774 | } |
| 775 | if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_NEAR] as usize][2]) { |
| 776 | mb.mv_ref = 2; // NEARMV |
| 777 | mb.mv = near_mvs[modes::CNT_NEAR]; |
| 778 | modes::clamp_mv2(&mut mb.mv, edges); |
| 779 | return; |
| 780 | } |
| 781 | |
| 782 | // NEWMV or SPLITMV: both code vectors as deltas off the best |
| 783 | // candidate — the nearest one when it dominates the census — |
| 784 | // clamped into range first (§16.2-§16.4). |
| 785 | let near_index = usize::from(cnt[modes::CNT_NEAREST] >= cnt[modes::CNT_INTRA]); |
| 786 | modes::clamp_mv2(&mut near_mvs[near_index], edges); |
| 787 | let best = near_mvs[near_index]; |
| 788 | if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_SPLITMV] as usize][3]) { |
| 789 | mb.mv_ref = 3; // NEWMV |
| 790 | let mut mv = modes::read_mv(d, &self.state.mv_probs); |
| 791 | mv.0 = mv.0.wrapping_add(best.0); |
| 792 | mv.1 = mv.1.wrapping_add(best.1); |
| 793 | mb.mv_clamp = modes::mv_out_of_bounds(mv, edges); |
| 794 | mb.mv = mv; |
| 795 | } else { |
| 796 | self.parse_split_mv(d, row, col, mb, best, edges); |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | /// Census input from one neighbour slot (§16.3); border and intra |
| 801 | /// MBs contribute nothing, zero-vector inter MBs count like intra. |
| 802 | fn mv_neighbor(&self, row: usize, col: usize, sign_bias: &[bool; 3]) -> modes::MvNeighbor { |
| 803 | if row == 0 || col == 0 || self.mbi(row, col).ref_frame == 0 { |
| 804 | return modes::MvNeighbor { |
| 805 | intra: true, |
| 806 | zero: false, |
| 807 | mv: (0, 0), |
| 808 | is_split: false, |
| 809 | sign_bias: false, |
| 810 | }; |
| 811 | } |
| 812 | let mb = self.mbi(row, col); |
| 813 | modes::MvNeighbor { |
| 814 | intra: false, |
| 815 | zero: mb.mv == (0, 0), |
| 816 | mv: mb.mv, |
| 817 | is_split: mb.mv_ref == 4, |
| 818 | sign_bias: sign_bias[usize::from(mb.ref_frame) - 1], |
| 819 | } |
| 820 | } |
| 821 | |
| 822 | /// SPLITMV mode record (§16.4, libvpx `decode_split_mv`): partition |
| 823 | /// shape, then one vector per subset coded against its left/above |
| 824 | /// contexts, each filling a whole group of subblocks. |
| 825 | fn parse_split_mv( |
| 826 | &mut self, |
| 827 | d: &mut BoolDecoder<'_>, |
| 828 | row: usize, |
| 829 | col: usize, |
| 830 | mb: &mut MbInfo, |
| 831 | best: (i16, i16), |
| 832 | edges: (i32, i32, i32, i32), |
| 833 | ) { |
| 834 | let s = modes::read_mv_partition(d); |
| 835 | let num_p = modes::MV_PARTITION_COUNT[s]; |
| 836 | let mv_probs = self.state.mv_probs; |
| 837 | for j in 0..num_p { |
| 838 | let k = usize::from(modes::MBSPLIT_OFFSET[s][j]); |
| 839 | let leftmv = if k % 4 == 0 { |
| 840 | let lm = self.mbi(row, col - 1); |
| 841 | if lm.mv_ref == 4 { |
| 842 | lm.bmi[k + 3] |
| 843 | } else { |
| 844 | lm.mv |
| 845 | } |
| 846 | } else { |
| 847 | mb.bmi[k - 1] |
| 848 | }; |
| 849 | let abovemv = if k < 4 { |
| 850 | let am = self.mbi(row - 1, col); |
| 851 | if am.mv_ref == 4 { |
| 852 | am.bmi[k + 12] |
| 853 | } else { |
| 854 | am.mv |
| 855 | } |
| 856 | } else { |
| 857 | mb.bmi[k - 4] |
| 858 | }; |
| 859 | let ctx = modes::mv_cont(leftmv, abovemv); |
| 860 | let blockmv = match modes::read_sub_mv_ref(d, ctx) { |
| 861 | modes::SubMvRef::Left4x4 => leftmv, |
| 862 | modes::SubMvRef::Above4x4 => abovemv, |
| 863 | modes::SubMvRef::Zero4x4 => (0, 0), |
| 864 | modes::SubMvRef::New4x4 => { |
| 865 | let mut mv = modes::read_mv(d, &mv_probs); |
| 866 | mv.0 = mv.0.wrapping_add(best.0); |
| 867 | mv.1 = mv.1.wrapping_add(best.1); |
| 868 | mv |
| 869 | } |
| 870 | }; |
| 871 | if crate::trace_enabled() { |
| 872 | eprintln!( |
| 873 | "SP r={} c={} j={} k={} l=({},{}) a=({},{}) ctx={} mv=({},{}) best=({},{})", |
| 874 | row - 1, |
| 875 | col - 1, |
| 876 | j, |
| 877 | k, |
| 878 | leftmv.0, |
| 879 | leftmv.1, |
| 880 | abovemv.0, |
| 881 | abovemv.1, |
| 882 | ctx, |
| 883 | blockmv.0, |
| 884 | blockmv.1, |
| 885 | best.0, |
| 886 | best.1 |
| 887 | ); |
| 888 | } |
| 889 | mb.mv_clamp |= modes::mv_out_of_bounds(blockmv, edges); |
| 890 | let count = modes::MBSPLIT_FILL_COUNT[s]; |
| 891 | for &off in &modes::MBSPLIT_FILL_OFFSET[s][j * count..(j + 1) * count] { |
| 892 | mb.bmi[usize::from(off)] = blockmv; |
| 893 | } |
| 894 | } |
| 895 | mb.mv_ref = 4; |
| 896 | // 4x4 residual coding without a Y2 block (like B_PRED). |
| 897 | mb.y_mode = modes::YMode::BPred.as_u8(); |
| 898 | // Neighbours' census sees the bottom-right subblock's vector. |
| 899 | mb.mv = mb.bmi[15]; |
| 900 | } |
| 901 | |
| 902 | /// Reconstruct one inter-frame MB: motion compensation from the |
| 903 | /// reference (or intra prediction), then the residual (§16, §14). |
| 904 | fn reconstruct_inter_mb( |
| 905 | &mut self, |
| 906 | row: usize, |
| 907 | col: usize, |
| 908 | mb: &MbInfo, |
| 909 | coeffs: &MbCoeffs, |
| 910 | ) -> Result<()> { |
| 911 | if mb.ref_frame == 0 { |
| 912 | return self.reconstruct_intra_mb(row, col, mb, coeffs); |
| 913 | } |
| 914 | if crate::trace_enabled() { |
| 915 | eprintln!( |
| 916 | "IMB r={} c={} ref={} mvref={} mv=({},{}) clamp={} skip={}", |
| 917 | row, col, mb.ref_frame, mb.mv_ref, mb.mv.0, mb.mv.1, mb.mv_clamp, mb.skip |
| 918 | ); |
| 919 | } |
| 920 | let reff = self.refs[usize::from(mb.ref_frame)] |
| 921 | .as_ref() |
| 922 | .ok_or_else(|| Error::corrupt("VP8 inter MB refers to an empty reference slot"))?; |
| 923 | let x = col * 16; |
| 924 | let y = row * 16; |
| 925 | let w = self.mb_cols * 16; |
| 926 | let h = self.mb_rows * 16; |
| 927 | // A reference left over from a frame of another size (a key frame that failed after |
| 928 | // resizing the decoder) has the wrong border geometry; the predictors index by it. |
| 929 | let (cw, ch) = (w / 2, h / 2); |
| 930 | if reff.stride != w + 2 * MC_BORDER |
| 931 | || reff.y.len() != (w + 2 * MC_BORDER) * (h + 2 * MC_BORDER) |
| 932 | || reff.uv_stride != cw + 2 * MC_BORDER |
| 933 | || reff.u.len() != (cw + 2 * MC_BORDER) * (ch + 2 * MC_BORDER) |
| 934 | || reff.v.len() != (cw + 2 * MC_BORDER) * (ch + 2 * MC_BORDER) |
| 935 | { |
| 936 | return Err(Error::corrupt("VP8 inter MB refers to a reference of another frame size")); |
| 937 | } |
| 938 | // Luma: one 16x16 predict, or 16 independent 4x4 predicts for |
| 939 | // SPLITMV (identical output to libvpx's grouped predicts). Each |
| 940 | // predict lands at its own (bx, by) slot of one 16x16 patch. |
| 941 | let mut py = [0u8; 256]; |
| 942 | if mb.mv_ref == 4 { |
| 943 | for b in 0..16usize { |
| 944 | let (bx, by) = ((b % 4) * 4, (b / 4) * 4); |
| 945 | // reconinter.c:370-374: the four corner subblocks clamp |
| 946 | // their MVs under need_to_clamp_mvs; the rest don't. |
| 947 | let corner = matches!(b, 0 | 2 | 8 | 10); |
| 948 | mc::predict_luma( |
| 949 | &reff.y, reff.stride, MC_BORDER, w, h, x + bx, y + by, mb.bmi[b], |
| 950 | mb.mv_clamp && corner, |
| 951 | &mut py[by * 16 + bx..], 16, 4, 4, self.mc_bilinear, |
| 952 | ); |
| 953 | } |
| 954 | } else { |
| 955 | mc::predict_luma( |
| 956 | &reff.y, reff.stride, MC_BORDER, w, h, x, y, mb.mv, mb.mv_clamp, &mut py, 16, |
| 957 | 16, 16, self.mc_bilinear, |
| 958 | ); |
| 959 | } |
| 960 | |
| 961 | // Chroma: libvpx predicts each plane as ONE 8x8 block for |
| 962 | // whole-MB modes (vp8_build_inter16x16_predictors_mb) or four |
| 963 | // independent 4x4 blocks for SPLITMV (build_inter4x4_predictors_mb, |
| 964 | // each from its quadrant's build_4x4uvmvs vector). The whole-MB |
| 965 | // path re-clamps UNCONDITIONALLY (reconinter.c: rounding the |
| 966 | // derived chroma MV to full-pel can move it outside the tap |
| 967 | // window even when the luma MV was in range); the SPLITMV path |
| 968 | // clamps only under need_to_clamp_mvs. |
| 969 | let mut pu = [0u8; 256]; |
| 970 | let mut pv = [0u8; 256]; |
| 971 | if mb.mv_ref == 4 { |
| 972 | for q in 0..4usize { |
| 973 | // Quadrant q: 4x4 chroma pixels at (qx4, qy4) in the MB. |
| 974 | let (qx4, qy4) = ((q % 2) * 4, (q / 2) * 4); |
| 975 | let (cx, cy) = (x / 2 + qx4, y / 2 + qy4); |
| 976 | let (qx, qy) = ((q % 2) * 2, (q / 2) * 2); |
| 977 | let uvmv = modes::chroma_mv_split( |
| 978 | &[ |
| 979 | mb.bmi[qy * 4 + qx], |
| 980 | mb.bmi[qy * 4 + qx + 1], |
| 981 | mb.bmi[qy * 4 + qx + 4], |
| 982 | mb.bmi[qy * 4 + qx + 5], |
| 983 | ], |
| 984 | self.mc_fullpel, |
| 985 | ); |
| 986 | mc::predict_chroma( |
| 987 | &reff.u, reff.uv_stride, MC_BORDER, w, h, cx, cy, uvmv, |
| 988 | mb.mv_clamp, &mut pu[qy4 * 16 + qx4..], 16, 4, 4, |
| 989 | self.mc_bilinear, |
| 990 | ); |
| 991 | mc::predict_chroma( |
| 992 | &reff.v, reff.uv_stride, MC_BORDER, w, h, cx, cy, uvmv, |
| 993 | mb.mv_clamp, &mut pv[qy4 * 16 + qx4..], 16, 4, 4, |
| 994 | self.mc_bilinear, |
| 995 | ); |
| 996 | } |
| 997 | } else { |
| 998 | let uvmv = modes::chroma_mv_whole(mb.mv, self.mc_fullpel); |
| 999 | mc::predict_chroma( |
| 1000 | &reff.u, reff.uv_stride, MC_BORDER, w, h, x / 2, y / 2, uvmv, true, |
| 1001 | &mut pu, 16, 8, 8, self.mc_bilinear, |
| 1002 | ); |
| 1003 | mc::predict_chroma( |
| 1004 | &reff.v, reff.uv_stride, MC_BORDER, w, h, x / 2, y / 2, uvmv, true, |
| 1005 | &mut pv, 16, 8, 8, self.mc_bilinear, |
| 1006 | ); |
| 1007 | } |
| 1008 | if crate::trace_enabled() && row == 0 && col == 0 { |
| 1009 | eprintln!( |
| 1010 | "CHROMA pred_u[0..8]={:?} refu_vis[0..8]={:?} coeffs.u0dcsum={}", |
| 1011 | &pu[0..8], |
| 1012 | &reff.u[MC_BORDER * reff.uv_stride + MC_BORDER..MC_BORDER * reff.uv_stride + MC_BORDER + 8], |
| 1013 | coeffs.u[0].iter().sum::<i16>() |
| 1014 | ); |
| 1015 | } |
| 1016 | |
| 1017 | // Residual: every block adds onto its MC prediction. |
| 1018 | let y_dcs: [i16; 16] = if coeffs.has_y2 { |
| 1019 | transform::iwht4x4(&coeffs.y2) |
| 1020 | } else { |
| 1021 | [0; 16] |
| 1022 | }; |
| 1023 | // loop indexes several parallel arrays; the index is clearer than zip chains |
| 1024 | #[allow(clippy::needless_range_loop)] |
| 1025 | for b in 0..16usize { |
| 1026 | let (bx, by) = ((b % 4) * 4, (b / 4) * 4); |
| 1027 | let mut c = coeffs.y[b]; |
| 1028 | if coeffs.has_y2 { |
| 1029 | c[0] = y_dcs[b]; |
| 1030 | } |
| 1031 | let dst = self.y.at(x + bx, y + by); |
| 1032 | idct_add_into(&mut self.y.data, &c, &py, 16, by * 16 + bx, dst, self.y.stride); |
| 1033 | } |
| 1034 | for (plane_data, coeffs_uv, pred, stride) in [ |
| 1035 | (&mut self.u.data, &coeffs.u, &pu, self.u.stride), |
| 1036 | (&mut self.v.data, &coeffs.v, &pv, self.v.stride), |
| 1037 | ] { |
| 1038 | // loop indexes several parallel arrays; the index is clearer than zip chains |
| 1039 | #[allow(clippy::needless_range_loop)] |
| 1040 | for b in 0..4usize { |
| 1041 | let (bx, by) = ((b % 2) * 4, (b / 2) * 4); |
| 1042 | let dst = (1 + y / 2 + by) * stride + 1 + x / 2 + bx; |
| 1043 | idct_add_into(plane_data, &coeffs_uv[b], pred, 16, by * 16 + bx, dst, stride); |
| 1044 | } |
| 1045 | } |
| 1046 | Ok(()) |
| 1047 | } |
| 1048 | |
| 1049 | /// Key-frame mode record (§11): Y mode at fixed probabilities, then |
| 1050 | /// 16 context-conditioned subblock modes for B_PRED, then chroma. |
| 1051 | fn decode_kf_modes( |
| 1052 | &mut self, |
| 1053 | d: &mut BoolDecoder<'_>, |
| 1054 | row: usize, |
| 1055 | col: usize, |
| 1056 | mb: &mut MbInfo, |
| 1057 | ) { |
| 1058 | let ymode = modes::read_kf_ymode(d); |
| 1059 | mb.y_mode = ymode.as_u8(); |
| 1060 | if ymode == modes::YMode::BPred { |
| 1061 | for j in 0..16u8 { |
| 1062 | let a = self.above_block_mode(row, col, j, mb); |
| 1063 | let l = self.left_block_mode(row, col, j, mb); |
| 1064 | mb.b_modes[usize::from(j)] = |
| 1065 | modes::read_bmode(d, &KF_BMODE_PROB[usize::from(a)][usize::from(l)]).as_u8(); |
| 1066 | } |
| 1067 | } |
| 1068 | mb.uv_mode = modes::read_uvmode(d, &modes::KF_UV_MODE_PROBS).as_u8(); |
| 1069 | } |
| 1070 | |
| 1071 | /// Above subblock mode context (dixie `above_block_mode`): subblocks |
| 1072 | /// 0-3 take the above MB's derived mode, inner subblocks the mode |
| 1073 | /// `j-4` of this same MB (already decoded into `mb`). |
| 1074 | fn above_block_mode(&self, row: usize, col: usize, j: u8, mb: &MbInfo) -> u8 { |
| 1075 | if j < 4 { |
| 1076 | let above = self.mbi(row - 1, col); |
| 1077 | if above.y_mode == modes::YMode::BPred.as_u8() { |
| 1078 | above.b_modes[usize::from(j) + 12] |
| 1079 | } else { |
| 1080 | ymode_as_bmode(above.y_mode) |
| 1081 | } |
| 1082 | } else { |
| 1083 | mb.b_modes[usize::from(j) - 4] |
| 1084 | } |
| 1085 | } |
| 1086 | |
| 1087 | /// Left subblock mode context (dixie `left_block_mode`). |
| 1088 | fn left_block_mode(&self, row: usize, col: usize, j: u8, mb: &MbInfo) -> u8 { |
| 1089 | if j.is_multiple_of(4) { |
| 1090 | let left = self.mbi(row, col - 1); |
| 1091 | if left.y_mode == modes::YMode::BPred.as_u8() { |
| 1092 | left.b_modes[usize::from(j) + 3] |
| 1093 | } else { |
| 1094 | ymode_as_bmode(left.y_mode) |
| 1095 | } |
| 1096 | } else { |
| 1097 | mb.b_modes[usize::from(j) - 1] |
| 1098 | } |
| 1099 | } |
| 1100 | |
| 1101 | /// Predict and reconstruct one intra key-frame MB at pixel (x, y). |
| 1102 | /// |
| 1103 | /// Whole-MB modes predict once from the pre-MB edges and then fold |
| 1104 | /// the 24 residual blocks in; B_PRED interleaves: each 4x4 subblock |
| 1105 | /// predicts from the reconstructed image (which already carries the |
| 1106 | /// earlier subblocks' residuals, §12.3) and is written back before |
| 1107 | /// the next subblock is predicted. |
| 1108 | fn reconstruct_intra_mb( |
| 1109 | &mut self, |
| 1110 | row: usize, |
| 1111 | col: usize, |
| 1112 | mb: &MbInfo, |
| 1113 | coeffs: &MbCoeffs, |
| 1114 | ) -> Result<()> { |
| 1115 | let x = col * 16; |
| 1116 | let y = row * 16; |
| 1117 | let y_mode = mb.y_mode; |
| 1118 | let uv_mode = mb.uv_mode; |
| 1119 | let b_modes = mb.b_modes; |
| 1120 | let have_above = row > 0; |
| 1121 | let have_left = col > 0; |
| 1122 | |
| 1123 | // The Y2 inverse WHT feeds the 16 Y subblock DCs (§14.2). |
| 1124 | let y_dcs: [i16; 16] = if coeffs.has_y2 { |
| 1125 | transform::iwht4x4(&coeffs.y2) |
| 1126 | } else { |
| 1127 | [0; 16] |
| 1128 | }; |
| 1129 | if crate::debug_enabled() { |
| 1130 | eprintln!( |
| 1131 | "MB({row},{col}) ymode={} uv={} y2={:?} y2has={} y0[:4]={:?} eobs24={} dcs={:?}", |
| 1132 | y_mode, |
| 1133 | uv_mode, |
| 1134 | coeffs.y2, |
| 1135 | coeffs.has_y2, |
| 1136 | &coeffs.y[0][..4], |
| 1137 | coeffs.eobs[24], |
| 1138 | &y_dcs[..4] |
| 1139 | ); |
| 1140 | } |
| 1141 | |
| 1142 | if y_mode == modes::YMode::BPred.as_u8() { |
| 1143 | for b in 0..16usize { |
| 1144 | let bx = (b % 4) * 4; |
| 1145 | let by = (b / 4) * 4; |
| 1146 | // A row: 4 above pixels then 4 above-right (§12.3); the |
| 1147 | // above-right extras are shared by right-edge subblocks |
| 1148 | // 3, 7, 11 and 15. |
| 1149 | let mut a8 = [0u8; 8]; |
| 1150 | let arow = self.y.at_above(x + bx, y + by); |
| 1151 | a8[..4].copy_from_slice(&self.y.data[arow..arow + 4]); |
| 1152 | if bx + 4 == 16 { |
| 1153 | a8[4..].copy_from_slice(&self.above_right(x, y)); |
| 1154 | } else { |
| 1155 | let ar = self.y.at_above(x + bx + 4, y + by); |
| 1156 | a8[4..].copy_from_slice(&self.y.data[ar..ar + 4]); |
| 1157 | } |
| 1158 | let mut l4 = [0u8; 4]; |
| 1159 | for (i, cell) in l4.iter_mut().enumerate() { |
| 1160 | *cell = self.y.data[self.y.at_left(x + bx, y + by + i)]; |
| 1161 | } |
| 1162 | let p = self.y.data[self.y.at_above_left(x + bx, y + by)]; |
| 1163 | let mut block = [0u8; 16]; |
| 1164 | intra::predict4(b_modes[b], &a8, &l4, p, &mut block)?; |
| 1165 | for i in 0..4 { |
| 1166 | let d = self.y.at(x + bx, y + by + i); |
| 1167 | self.y.data[d..d + 4].copy_from_slice(&block[i * 4..i * 4 + 4]); |
| 1168 | } |
| 1169 | let mut c = coeffs.y[b]; |
| 1170 | if coeffs.has_y2 { |
| 1171 | c[0] = y_dcs[b]; |
| 1172 | } |
| 1173 | if c.iter().any(|&v| v != 0) { |
| 1174 | let dst = self.y.at(x + bx, y + by); |
| 1175 | let stride = self.y.stride; |
| 1176 | idct_add_into(&mut self.y.data, &c, &block, 4, 0, dst, stride); |
| 1177 | } |
| 1178 | } |
| 1179 | } else { |
| 1180 | // Gather luma edges (border cells carry the 127/129 fills). |
| 1181 | let (above, left, above_left) = { |
| 1182 | let ay = self.y.at_above(x, y); |
| 1183 | let mut a = [0u8; 16]; |
| 1184 | let mut l = [0u8; 16]; |
| 1185 | a.copy_from_slice(&self.y.data[ay..ay + 16]); |
| 1186 | for (i, cell) in l.iter_mut().enumerate() { |
| 1187 | *cell = self.y.data[self.y.at_left(x, y + i)]; |
| 1188 | } |
| 1189 | let al = self.y.data[self.y.at_above_left(x, y)]; |
| 1190 | (a, l, al) |
| 1191 | }; |
| 1192 | let mut pred = [0u8; 256]; |
| 1193 | intra::predict16( |
| 1194 | y_mode, have_above, have_left, &above, &left, above_left, &mut pred, |
| 1195 | )?; |
| 1196 | // loop indexes several parallel arrays; the index is clearer than zip chains |
| 1197 | #[allow(clippy::needless_range_loop)] |
| 1198 | for b in 0..16usize { |
| 1199 | let bx = (b % 4) * 4; |
| 1200 | let by = (b / 4) * 4; |
| 1201 | let mut c = coeffs.y[b]; |
| 1202 | if coeffs.has_y2 { |
| 1203 | c[0] = y_dcs[b]; |
| 1204 | } |
| 1205 | if c.iter().all(|&v| v == 0) { |
| 1206 | for i in 0..4 { |
| 1207 | let d = self.y.at(x + bx, y + by + i); |
| 1208 | let s = (by + i) * 16 + bx; |
| 1209 | self.y.data[d..d + 4].copy_from_slice(&pred[s..s + 4]); |
| 1210 | } |
| 1211 | } else { |
| 1212 | let dst = self.y.at(x + bx, y + by); |
| 1213 | let stride = self.y.stride; |
| 1214 | idct_add_into(&mut self.y.data, &c, &pred, 16, by * 16 + bx, dst, stride); |
| 1215 | } |
| 1216 | } |
| 1217 | } |
| 1218 | |
| 1219 | // Chroma: 8x8 prediction then four residual blocks per plane. |
| 1220 | let (above_u, left_u, al_u) = self.chroma_edges(col, row, 0); |
| 1221 | let (above_v, left_v, al_v) = self.chroma_edges(col, row, 1); |
| 1222 | let mut pred_u = [0u8; 64]; |
| 1223 | let mut pred_v = [0u8; 64]; |
| 1224 | intra::predict8( |
| 1225 | uv_mode, |
| 1226 | have_above, |
| 1227 | have_left, |
| 1228 | &above_u, |
| 1229 | &left_u, |
| 1230 | al_u, |
| 1231 | &mut pred_u, |
| 1232 | )?; |
| 1233 | intra::predict8( |
| 1234 | uv_mode, |
| 1235 | have_above, |
| 1236 | have_left, |
| 1237 | &above_v, |
| 1238 | &left_v, |
| 1239 | al_v, |
| 1240 | &mut pred_v, |
| 1241 | )?; |
| 1242 | let (cx, cy) = (x / 2, y / 2); |
| 1243 | for (plane_data, coeffs_uv, pred8, stride) in [ |
| 1244 | (&mut self.u.data, &coeffs.u, &pred_u, self.u.stride), |
| 1245 | (&mut self.v.data, &coeffs.v, &pred_v, self.v.stride), |
| 1246 | ] { |
| 1247 | // loop indexes several parallel arrays; the index is clearer than zip chains |
| 1248 | #[allow(clippy::needless_range_loop)] |
| 1249 | for b in 0..4usize { |
| 1250 | let bx = (b % 2) * 4; |
| 1251 | let by = (b / 2) * 4; |
| 1252 | let c = coeffs_uv[b]; |
| 1253 | let dst = (1 + cy + by) * stride + 1 + cx + bx; |
| 1254 | if c.iter().all(|&v| v == 0) { |
| 1255 | for i in 0..4 { |
| 1256 | let s = (by + i) * 8 + bx; |
| 1257 | let d = dst + i * stride; |
| 1258 | plane_data[d..d + 4].copy_from_slice(&pred8[s..s + 4]); |
| 1259 | } |
| 1260 | } else { |
| 1261 | idct_add_into(plane_data, &c, pred8, 8, by * 8 + bx, dst, stride); |
| 1262 | } |
| 1263 | } |
| 1264 | } |
| 1265 | Ok(()) |
| 1266 | } |
| 1267 | |
| 1268 | /// Above-right extras (§12.3): real pixels from the above row, |
| 1269 | /// replicated last pixel on the rightmost MB, 127 on the top row. |
| 1270 | fn above_right(&self, x: usize, y: usize) -> [u8; 4] { |
| 1271 | if y == 0 { |
| 1272 | [127; 4] |
| 1273 | } else if x + 16 >= self.mb_cols * 16 { |
| 1274 | [self.y.data[self.y.at_above(x + 15, y)]; 4] |
| 1275 | } else { |
| 1276 | let off = self.y.at_above(x + 16, y); |
| 1277 | [ |
| 1278 | self.y.data[off], |
| 1279 | self.y.data[off + 1], |
| 1280 | self.y.data[off + 2], |
| 1281 | self.y.data[off + 3], |
| 1282 | ] |
| 1283 | } |
| 1284 | } |
| 1285 | |
| 1286 | fn chroma_edges(&self, col: usize, row: usize, plane: usize) -> ([u8; 8], [u8; 8], u8) { |
| 1287 | let p = if plane == 0 { &self.u } else { &self.v }; |
| 1288 | let x = col * 8; |
| 1289 | let y = row * 8; |
| 1290 | let mut a = [0u8; 8]; |
| 1291 | let mut l = [0u8; 8]; |
| 1292 | let aoff = p.at_above(x, y); |
| 1293 | a.copy_from_slice(&p.data[aoff..aoff + 8]); |
| 1294 | for (i, cell) in l.iter_mut().enumerate() { |
| 1295 | *cell = p.data[p.at_left(x, y + i)]; |
| 1296 | } |
| 1297 | let al = p.data[p.at_above_left(x, y)]; |
| 1298 | (a, l, al) |
| 1299 | } |
| 1300 | |
| 1301 | /// Crop the padded planes to the real frame size. |
| 1302 | fn crop(&self) -> Picture { |
| 1303 | let w = usize::from(self.dims.width); |
| 1304 | let h = usize::from(self.dims.height); |
| 1305 | let mut y = Vec::with_capacity(w * h); |
| 1306 | for row in 0..h { |
| 1307 | let off = self.y.at(0, row); |
| 1308 | y.extend_from_slice(&self.y.data[off..off + w]); |
| 1309 | } |
| 1310 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 1311 | let mut u = Vec::with_capacity(cw * ch); |
| 1312 | let mut v = Vec::with_capacity(cw * ch); |
| 1313 | for row in 0..ch { |
| 1314 | let off = self.u.at(0, row); |
| 1315 | u.extend_from_slice(&self.u.data[off..off + cw]); |
| 1316 | let off = self.v.at(0, row); |
| 1317 | v.extend_from_slice(&self.v.data[off..off + cw]); |
| 1318 | } |
| 1319 | Picture { |
| 1320 | y, |
| 1321 | u, |
| 1322 | v, |
| 1323 | width: self.dims.width, |
| 1324 | height: self.dims.height, |
| 1325 | stride: w, |
| 1326 | uv_stride: cw, |
| 1327 | } |
| 1328 | } |
| 1329 | } |
| 1330 | |
| 1331 | impl Default for Decoder { |
| 1332 | fn default() -> Self { |
| 1333 | Self::new() |
| 1334 | } |
| 1335 | } |
| 1336 | |
| 1337 | /// Segment-map coding tree (RFC 6386 §10): plain two-level split of 0-3. |
| 1338 | const SEGMENT_TREE: [i8; 6] = [2, 4, 0, -1, -2, -3]; |
| 1339 | |
| 1340 | fn ymode_as_bmode(y: u8) -> u8 { |
| 1341 | match y { |
| 1342 | 0 => 0, // DC_PRED -> B_DC_PRED |
| 1343 | 1 => 2, // V_PRED -> B_VE_PRED |
| 1344 | 2 => 3, // H_PRED -> B_HE_PRED |
| 1345 | 3 => 1, // TM_PRED -> B_TM_PRED |
| 1346 | _ => unreachable!("non-B_PRED luma mode {y}"), |
| 1347 | } |
| 1348 | } |
| 1349 | |
| 1350 | /// Add one 4x4 block's dequantized-coefficient residual to its |
| 1351 | /// prediction: reads the prediction patch from `pred`, clamps, writes |
| 1352 | /// into the strided plane (§14.4/§14.5). |
| 1353 | fn idct_add_into( |
| 1354 | plane: &mut [u8], |
| 1355 | coeffs: &[i16; 16], |
| 1356 | pred: &[u8], |
| 1357 | pred_stride: usize, |
| 1358 | pred_off: usize, |
| 1359 | dst_off: usize, |
| 1360 | dst_stride: usize, |
| 1361 | ) { |
| 1362 | let mut p = [0u8; 16]; |
| 1363 | for i in 0..4 { |
| 1364 | let s = pred_off + i * pred_stride; |
| 1365 | p[i * 4..i * 4 + 4].copy_from_slice(&pred[s..s + 4]); |
| 1366 | } |
| 1367 | let mut out = [0u8; 16]; |
| 1368 | transform::idct4x4_add(coeffs, &p, &mut out); |
| 1369 | for i in 0..4 { |
| 1370 | let d = dst_off + i * dst_stride; |
| 1371 | plane[d..d + 4].copy_from_slice(&out[i * 4..i * 4 + 4]); |
| 1372 | } |
| 1373 | } |