forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB4c07cbcTahinli2 months ago3583 commits

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