forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiB35bdf35Tahinli2 months ago3757 commits

decode.rs2329 lines, 87.4 KiBHistoryRawDownload
1//! Frame decoding: superframe split, uncompressed header (via
2//! [`ec_vp9_syntax::Vp9Parser`]), compressed header, tile parsing,
3//! partition recursion, intra prediction, token decoding,
4//! reconstruction and the loop filter (spec 6, 7, 8; libvpx
5//! `vp9_decodeframe.c`).
6//!
7//! Capability: every VP9 profile (0-3), 8/10/12-bit and every coded
8//! subsampling (4:2:0, 4:2:2, 4:4:0, 4:4:4): keyframes, intra-only frames
9//! and inter frames (motion compensation, residual reconstruction, the loop
10//! filter and an 8-slot reference DPB). A reference whose coded size differs
11//! from the current frame is scaled during prediction;
12//! `show_existing_frame` returns the buffered reference picture instead of
13//! pretending to decode. Odd coded extents are supported: chroma stores and
14//! crops at `(w + ss_x) >> ss_x` (`uv_crop_width`), matching libvpx.
15
16use crate::header::{FrameContext, read_compressed_header};
17use crate::intra::build_intra_predictors;
18use crate::loopfilter::LfGrids;
19use crate::mc::{RefPlane, ScaleFactors, average_split_mvs, build_inter_predictors};
20use crate::modes::{MiInfo, MiState, read_intra_frame_mode_info};
21use crate::tables::*;
22use crate::tokens::{PlaneContexts, decode_coefs, scan_for};
23use crate::transform::inverse_transform_add;
24use crate::{Error, Result, Sample};
25use ec_vp9_syntax::{FrameHeader, FrameType, Vp9Parser, superframe};
26
27const SB_MI: usize = 8; // a 64x64 superblock in mi (8x8) units
28
29/// A decoded, displayable frame: cropped contiguous planes.
30#[derive(Clone, Debug)]
31pub struct Picture {
32 /// Luma plane, `stride`-spaced rows of `width` samples.
33 pub y: Vec<Sample>,
34 /// U (Cb) plane, chroma resolution (`(width + ss_x) >> ss_x` by
35 /// `(height + ss_y) >> ss_y`).
36 pub u: Vec<Sample>,
37 /// V (Cr) plane, chroma resolution.
38 pub v: Vec<Sample>,
39 /// Frame width in pixels.
40 pub width: u16,
41 /// Frame height in pixels.
42 pub height: u16,
43 /// Luma row pitch of the returned planes (== `width`; the crop packs rows).
44 pub stride: usize,
45 /// Chroma row pitch of the returned planes (`(width + ss_x) >> ss_x`;
46 /// chroma ceils an odd coded width).
47 pub uv_stride: usize,
48 /// Bits per sample (8 for profile 0, 10 for profile 2).
49 pub bit_depth: u8,
50 /// Chroma horizontal subsampling (`subsampling_x`): 0 for 4:4:4, 1 for
51 /// 4:2:0/4:2:2. Chroma width is `(width + subsampling_x) >> subsampling_x`.
52 pub subsampling_x: u8,
53 /// Chroma vertical subsampling (`subsampling_y`): 0 for 4:4:4/4:2:2, 1
54 /// for 4:2:0/4:4:0.
55 pub subsampling_y: u8,
56}
57
58struct Planes {
59 y: Vec<Sample>,
60 u: Vec<Sample>,
61 v: Vec<Sample>,
62 ys: usize,
63 uvs: usize,
64 aw: usize,
65 ah: usize,
66 /// Bits per sample this frame was decoded at.
67 bd: u8,
68 /// Chroma horizontal subsampling (`subsampling_x`): 0 for 4:4:4, 1 for
69 /// 4:2:0/4:2:2.
70 ss_x: usize,
71 /// Chroma vertical subsampling (`subsampling_y`): 0 for 4:4:4/4:2:2, 1
72 /// for 4:2:0/4:4:0.
73 ss_y: usize,
74}
75
76impl Planes {
77 /// A frame scratch at the 64-multiple ALIGNED extent, filled with the
78 /// neutral grey `1 << (bd - 1)` (`128` at 8-bit, `512` at 10-bit). The
79 /// aligned the decode writes real samples into it (blocks at the frame
80 /// edge decode at FULL size), so the fill only backs the never-written
81 /// padding past the MI extent. Chroma planes are `aw >> ss_x` by
82 /// `ah >> ss_y`; since `aw`/`ah` are 64-multiples the shift is exact.
83 fn new(aw: usize, ah: usize, bd: u8, ss_x: usize, ss_y: usize) -> Planes {
84 let fill = 1u16 << (bd - 1);
85 let (cw, ch) = (aw >> ss_x, ah >> ss_y);
86 Planes {
87 y: vec![fill; aw * ah],
88 u: vec![fill; cw * ch],
89 v: vec![fill; cw * ch],
90 ys: aw,
91 uvs: cw,
92 aw,
93 ah,
94 bd,
95 ss_x,
96 ss_y,
97 }
98 }
99
100 /// Immutable plane + stride (the predictor reads references).
101 fn plane_ref(&self, plane: usize) -> (&[Sample], usize) {
102 match plane {
103 0 => (&self.y, self.ys),
104 1 => (&self.u, self.uvs),
105 _ => (&self.v, self.uvs),
106 }
107 }
108 fn plane(&mut self, plane: usize) -> (&mut [Sample], usize) {
109 match plane {
110 0 => (&mut self.y, self.ys),
111 1 => (&mut self.u, self.uvs),
112 _ => (&mut self.v, self.uvs),
113 }
114 }
115 fn dims(&self, plane: usize) -> (usize, usize) {
116 if plane == 0 {
117 (self.aw, self.ah)
118 } else {
119 (self.aw >> self.ss_x, self.ah >> self.ss_y)
120 }
121 }
122}
123
124/// The VP9 decoder. Feed complete frames — one full VP9 frame payload
125/// or one superframe chunk, exactly what a container demuxer hands over
126/// for the `VP90` codec.
127pub struct Decoder {
128 parser: Vp9Parser,
129 /// The frame context in force for the frame being parsed.
130 ///
131 /// Boxed for the same reason as `frame_ctxs` below: a `FrameContext` is
132 /// 2039 bytes, and leaving this one inline put 73% of the whole `Decoder`
133 /// back on the stack. `Stack`: crate::stack_budget.
134 ctx: Box<FrameContext>,
135 refs: [Option<RefFrame>; 8],
136 /// Frame scratch, live only inside `decode_keyframe`.
137 planes: Option<Planes>,
138 /// The four stored frame contexts (spec 6.2 `frame_context_idx`).
139 ///
140 /// Boxed because a `FrameContext` is 2039 bytes and four of them inline
141 /// are 8156 of the 10944 a `Decoder` costs a caller that takes one BY
142 /// VALUE from `Decoder::new`. Indexing and whole-array assignment read
143 /// through the box. `Stack`: crate::stack_budget.
144 frame_ctxs: Box<[FrameContext; 4]>,
145 /// The previous frame's per-8x8 MV field and segment map
146 /// (`prev_frame->mvs` / `last_frame_seg_map`).
147 prev_mvs: Vec<crate::inter::MvRef>,
148 prev_seg: Vec<u8>,
149 last: LastFrameFacts,
150 /// Live only while an inter frame is being parsed.
151 iw: Option<InterWalk>,
152 /// Frames parsed by `decode_syntax` (the dump's frame index).
153 frames_seen: usize,
154 /// Frames decoded by `decode` (the dumps' `frame=` field for this path;
155 /// `decode_syntax` counts the same way in `frames_seen`).
156 decode_index: usize,
157 /// Mode-info blocks parsed in the most recent inter frame (0 otherwise).
158 syntax_blocks: usize,
159 /// `twd->extend_and_predict_buf`: the per-prediction bordered reference
160 /// window built when a block's read leaves the reference frame.
161 mc_scratch: Vec<Sample>,
162 /// The `vpx_convolve8` stride-64 intermediate plus the second scratch its
163 /// averaging variant needs.
164 mc_temp: Vec<Sample>,
165}
166
167/// One DPB slot: a decoded frame buffer at its ALIGNED (64-multiple) extent
168/// plus the coded size it was decoded at.
169///
170/// The aligned extent is load-bearing, not slack: libvpx writes a block at the
171/// frame edge at its FULL size (`decodeframe.c:1216`), so the rows past the
172/// coded height hold real reconstructed samples, and `dec_build_inter_predictors`
173/// reads them directly whenever a block's window is inside the frame with a
174/// whole-pixel MV (`build_mc_border` is only reached when the window leaves the
175/// frame or the coded size is not a multiple of 8). Cropping the reference to
176/// the visible size would drop exactly those samples.
177#[derive(Clone)]
178struct RefFrame {
179 planes: std::sync::Arc<Planes>,
180 /// Coded width — the predictor's `y_crop_width`.
181 width: u16,
182 /// Coded height — the predictor's `y_crop_height`.
183 height: u16,
184}
185
186/// What `use_prev_frame_mvs` (decodeframe.c:3023) tests about the last frame.
187#[derive(Clone, Copy, Default)]
188struct LastFrameFacts {
189 width: u32,
190 height: u32,
191 intra_only: bool,
192 show_frame: bool,
193 key: bool,
194}
195
196/// State of one inter-syntax frame walk.
197struct InterWalk {
198 ifs: crate::inter::InterFrameState,
199 sign_bias: [bool; 4],
200 use_prev: bool,
201 seg_map: Vec<u8>,
202 mvs: Vec<crate::inter::MvRef>,
203 prev_seg: Vec<u8>,
204 prev_mvs: Vec<crate::inter::MvRef>,
205 tile_col_end: usize,
206 frame_index: usize,
207 /// Mode-info blocks parsed in this frame (the harness's count gate).
208 blocks: usize,
209}
210
211impl Decoder {
212 /// Create an empty decoder; the first key frame sets the size.
213 pub fn new() -> Self {
214 Decoder {
215 parser: Vp9Parser::new(),
216 ctx: Box::new(FrameContext::new(true)),
217 refs: [const { None }; 8],
218 planes: None,
219 frame_ctxs: {
220 let d = FrameContext::new(false);
221 Box::new([d.clone(), d.clone(), d.clone(), d])
222 },
223 prev_mvs: Vec::new(),
224 prev_seg: Vec::new(),
225 last: LastFrameFacts::default(),
226 iw: None,
227 frames_seen: 0,
228 decode_index: 0,
229 syntax_blocks: 0,
230 mc_scratch: Vec::new(),
231 mc_temp: vec![0; 64 * 135 + 64 * 64],
232 }
233 }
234
235 /// Mode-info blocks the most recent inter frame parsed; `0` for a keyframe
236 /// or before any frame. The syntax harness pins this number.
237 pub fn last_frame_blocks(&self) -> usize {
238 self.syntax_blocks
239 }
240
241 /// Decode one frame (or one superframe chunk); returns the picture
242 /// when a frame is for display. Hidden frames still update state.
243 pub fn decode(&mut self, frame: &[u8]) -> Result<Option<Picture>> {
244 let mut out = None;
245 for sub in superframe::split(frame)? {
246 if let Some(pic) = self.decode_one(sub)? {
247 out = Some(pic);
248 }
249 }
250 Ok(out)
251 }
252
253 fn decode_one(&mut self, frame: &[u8]) -> Result<Option<Picture>> {
254 let hdr = self.parser.parse_frame(frame)?;
255 if hdr.show_existing_frame {
256 let slot = hdr.frame_to_show_map_idx as usize;
257 return match self.refs.get(slot).and_then(|p| p.as_ref()) {
258 Some(p) => Ok(Some(crop_picture(&p.planes, p.width, p.height))),
259 None => Err(corrupt("show_existing_frame names an empty slot")),
260 };
261 }
262 if hdr.bit_depth != 8 && hdr.bit_depth != 10 && hdr.bit_depth != 12 {
263 return Err(Error::unsupported(
264 format!("vp9 bit depth {}", hdr.bit_depth),
265 "this lane decodes 8-, 10- and 12-bit only",
266 ));
267 }
268 // One index per decoded frame (the dumps' `frame=` field), so this
269 // path and `decode_syntax` label the same frame the same way.
270 let index = self.decode_index;
271 self.decode_index += 1;
272 if hdr.frame_type == FrameType::Key {
273 return self.decode_key_frame(&hdr, frame);
274 }
275 if hdr.intra_only {
276 return self.decode_intra_only_frame(&hdr, frame);
277 }
278 self.decode_inter_frame(&hdr, frame, index, true)
279 }
280
281 /// Decode one key frame through to pixels and refresh every slot.
282 fn decode_key_frame(&mut self, hdr: &FrameHeader, frame: &[u8]) -> Result<Option<Picture>> {
283 let hdr = hdr.clone();
284 // setup_past_independence (spec 7.2): a key frame resets the frame
285 // context, so every STORED context goes back to the inter defaults.
286 // The keyframe's own mode info reads the const `vp9_kf_partition_probs`
287 // (libvpx `get_partition_probs`), which our `new(true)` models on the
288 // active copy only.
289 let d = FrameContext::new(false);
290 self.frame_ctxs = Box::new([d.clone(), d.clone(), d.clone(), d]);
291 self.ctx = Box::new(FrameContext::new(true));
292 self.prev_mvs.clear();
293 self.prev_seg.clear();
294 self.last = LastFrameFacts {
295 width: hdr.width,
296 height: hdr.height,
297 intra_only: hdr.intra_only,
298 show_frame: hdr.show_frame,
299 key: true,
300 };
301 // [scratch probe] EC_VP9_FORCE_UH / EC_VP9_FORCE_HSZ: override the
302 // uncompressed-header size / header_size_in_bytes split for diagnosis.
303 let hdr = {
304 let mut h = hdr;
305 if let Ok(v) = std::env::var("EC_VP9_FORCE_UH") {
306 h.uncompressed_header_size = v.parse().unwrap_or(h.uncompressed_header_size);
307 }
308 if let Ok(v) = std::env::var("EC_VP9_FORCE_HSZ") {
309 h.header_size_in_bytes = v.parse().unwrap_or(h.header_size_in_bytes);
310 }
311 h
312 };
313 let hdr_start = hdr.uncompressed_header_size as usize;
314 let ch = read_compressed_header(
315 &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize],
316 &mut self.ctx,
317 &hdr,
318 )?;
319
320 let pic = self.decode_keyframe(&hdr, frame, ch.tx_mode)?;
321 if hdr.refresh_frame_context {
322 self.ctx.reset_inter_partition();
323 self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.as_ref().clone();
324 }
325 // Reference refresh (spec 8.10): a keyframe updates all slots.
326 let frame = RefFrame {
327 planes: std::sync::Arc::new(self.planes.take().expect("frame scratch")),
328 width: hdr.width as u16,
329 height: hdr.height as u16,
330 };
331 for slot in self.refs.iter_mut() {
332 *slot = Some(frame.clone());
333 }
334 Ok(if hdr.show_frame { Some(pic) } else { None })
335 }
336
337 /// Decode an intra-only frame through to pixels. `libvpx
338 /// vp9_decodeframe.c:2708-2745` makes it an INTER frame that never shows
339 /// and refreshes only the slots its `refresh_frame_flags` names, but its
340 /// body is a keyframe's: intra-only mode info, intra prediction, the intra
341 /// coefficient axis and the intra loop-filter levels. Two header decisions
342 /// differ from a keyframe (`vp9_setup_past_independence`,
343 /// `vp9/common/vp9_entropymode.c:424`):
344 ///
345 /// - the ACTIVE frame context comes from storage
346 /// (`*cm->fc = cm->frame_contexts[frame_context_idx]`,
347 /// `vp9_decodeframe.c:3008`) — reset to the defaults only for
348 /// `reset_frame_context` 2 (selected) or 3 (all), or under
349 /// error-resilient mode, never unconditionally like a keyframe (whose
350 /// `cm->frame_type == KEY_FRAME` clause resets every stored context);
351 /// - partitions read the const `vp9_kf_partition_probs`
352 /// (`set_partition_probs`), so the stored context's own `partition`
353 /// field survives the frame untouched.
354 fn decode_intra_only_frame(
355 &mut self,
356 hdr: &FrameHeader,
357 frame: &[u8],
358 ) -> Result<Option<Picture>> {
359 let hdr = hdr.clone();
360 if hdr.error_resilient_mode || hdr.reset_frame_context == 3 {
361 let d = FrameContext::new(false);
362 self.frame_ctxs = Box::new([d.clone(), d.clone(), d.clone(), d]);
363 } else if hdr.reset_frame_context == 2 {
364 self.frame_ctxs[0] = FrameContext::new(false);
365 }
366 // The parser forces frame_context_idx to 0 for an intra frame.
367 let mut ctx = self.frame_ctxs[0].clone();
368 let stored_partition = ctx.partition;
369 ctx.use_key_partition();
370 self.ctx = Box::new(ctx);
371 self.prev_seg.clear();
372 self.prev_mvs.clear();
373 self.last = LastFrameFacts {
374 width: hdr.width,
375 height: hdr.height,
376 intra_only: true,
377 show_frame: hdr.show_frame,
378 key: false,
379 };
380 let hdr_start = hdr.uncompressed_header_size as usize;
381 let ch = read_compressed_header(
382 &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize],
383 &mut self.ctx,
384 &hdr,
385 )?;
386 let pic = self.decode_keyframe(&hdr, frame, ch.tx_mode)?;
387 if hdr.refresh_frame_context {
388 // Store back with the partition probs the context arrived with:
389 // the const key table is not a `FRAME_CONTEXT` field.
390 self.ctx.partition = stored_partition;
391 self.frame_ctxs[0] = self.ctx.as_ref().clone();
392 }
393 // Reference refresh (spec 8.10): only `refresh_frame_flags` slots.
394 let frame = RefFrame {
395 planes: std::sync::Arc::new(self.planes.take().expect("frame scratch")),
396 width: hdr.width as u16,
397 height: hdr.height as u16,
398 };
399 for slot in 0..8 {
400 if hdr.refresh_frame_flags & (1 << slot) != 0 {
401 self.refs[slot] = Some(frame.clone());
402 }
403 }
404 Ok(if hdr.show_frame { Some(pic) } else { None })
405 }
406
407 /// Parse one frame's syntax: keyframes decode through to pixels, inter
408 /// frames are parsed (headers, mode info, MVs) with no reconstruction and
409 /// no picture. `decode` still refuses inter frames.
410 pub fn decode_syntax(&mut self, frame: &[u8]) -> Result<()> {
411 for sub in superframe::split(frame)? {
412 let index = self.frames_seen;
413 self.frames_seen += 1;
414 let hdr = self.parser.parse_frame(sub)?;
415 if hdr.show_existing_frame {
416 continue;
417 }
418 if hdr.bit_depth != 8 && hdr.bit_depth != 10 && hdr.bit_depth != 12 {
419 return Err(Error::unsupported(
420 format!("vp9 bit depth {}", hdr.bit_depth),
421 "this lane decodes 8-, 10- and 12-bit only",
422 ));
423 }
424 if hdr.frame_type == FrameType::Key {
425 // Propagate: a corrupt keyframe leaves a half-updated frame
426 // context, prev-frame MV field and reference slots behind, so
427 // any inter-frame dump after it would be meaningless evidence.
428 self.decode_key_frame(&hdr, sub)?;
429 } else if hdr.intra_only {
430 // Same body as a keyframe, but an inter frame that refreshes
431 // only the slots it names.
432 self.decode_intra_only_frame(&hdr, sub)?;
433 } else {
434 self.decode_inter_frame(&hdr, sub, index, false)?;
435 }
436 }
437 Ok(())
438 }
439
440 /// Inter-frame decode: compressed header, the tile walk (mode info, MVs
441 /// and tokens always; prediction, residual and the loop filter when
442 /// `pixels`), then the reference refresh.
443 ///
444 /// `pixels == false` is the syntax-only walk the instrumented harnesses
445 /// drive: tokens keep the entropy stream aligned, no pixel is touched and
446 /// the reference slots are left alone.
447 fn decode_inter_frame(
448 &mut self,
449 hdr: &FrameHeader,
450 frame: &[u8],
451 index: usize,
452 pixels: bool,
453 ) -> Result<Option<Picture>> {
454 let ss_x = hdr.subsampling_x as usize;
455 let ss_y = hdr.subsampling_y as usize;
456 // Frame-context bookkeeping (spec 6.2 / libvpx `vp9_decode_frame`):
457 // 3 resets every stored context, 2 resets the selected one; 1 means
458 // "reset after this frame" and takes no action at frame start.
459 if hdr.reset_frame_context == 3 {
460 let d = FrameContext::new(false);
461 self.frame_ctxs = Box::new([d.clone(), d.clone(), d.clone(), d]);
462 } else if hdr.reset_frame_context == 2 {
463 self.frame_ctxs[hdr.frame_context_idx as usize] = FrameContext::new(false);
464 }
465 self.ctx = Box::new(self.frame_ctxs[hdr.frame_context_idx as usize].clone());
466
467 // Reference slots (spec 7.2): `ref_frame_idx[i]` names the slot LAST,
468 // GOLDEN and ALTREF use. libvpx validates every named reference's
469 // format here (`vp9_decodeframe.c:1620-1627`); a reference whose coded
470 // size differs from this frame's is SCALED during prediction
471 // (`vp9_setup_scale_factors_for_frame` per reference), not refused.
472 if pixels {
473 for (i, name) in ["last", "golden", "altref"].iter().enumerate() {
474 let slot = hdr.ref_frame_idx[i] as usize;
475 if slot >= self.refs.len() || hdr.ref_frame_idx[i] >= 8 {
476 return Err(corrupt("vp9 inter names a reference slot past the DPB"));
477 }
478 if self.refs[slot].is_none() {
479 return Err(Error::corrupt(format!(
480 "vp9 inter reference `{name}` names empty slot {slot}"
481 )));
482 }
483 }
484 let width = hdr.width as usize;
485 let height = hdr.height as usize;
486 let aw = width.div_ceil(64) * 64;
487 let ah = height.div_ceil(64) * 64;
488 self.planes = Some(Planes::new(aw, ah, hdr.bit_depth, ss_x, ss_y));
489 }
490
491 let hdr_start = hdr.uncompressed_header_size as usize;
492 if crate::trace_enabled() {
493 eprintln!("CHSTART frame={index}");
494 }
495 let ch = read_compressed_header(
496 &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize],
497 &mut self.ctx,
498 hdr,
499 )?;
500
501 if crate::interdump_enabled() {
502 let mut line = format!("PPFLAT frame={index}");
503 for row in self.ctx.partition.iter() {
504 for v in row.iter() {
505 line.push_str(&format!(" {v}"));
506 }
507 }
508 eprintln!("{line}");
509 }
510
511 // INTRA_FRAME's sign bias is 0 by definition; the coded three land at
512 // LAST/GOLDEN/ALTREF.
513 let sign_bias = [
514 false,
515 hdr.ref_frame_sign_bias[0],
516 hdr.ref_frame_sign_bias[1],
517 hdr.ref_frame_sign_bias[2],
518 ];
519 let mut ifs = crate::inter::InterFrameState {
520 reference_mode: ch.reference_mode,
521 ..Default::default()
522 };
523 if ch.reference_mode != crate::inter::SINGLE_REFERENCE {
524 crate::inter::setup_compound_reference_mode(&mut ifs, sign_bias);
525 }
526 let use_prev = !hdr.error_resilient_mode
527 && hdr.width == self.last.width
528 && hdr.height == self.last.height
529 && !self.last.intra_only
530 && self.last.show_frame
531 && !self.last.key;
532
533 let mi_cols = hdr.mi_cols() as usize;
534 let mi_rows = hdr.mi_rows() as usize;
535 let sb64_cols = mi_cols.div_ceil(SB_MI);
536 let sb64_rows = mi_rows.div_ceil(SB_MI);
537 let tile_cols = 1usize << hdr.tile_info.cols_log2;
538 let tile_rows = 1usize << hdr.tile_info.rows_log2;
539
540 self.iw = Some(InterWalk {
541 ifs,
542 sign_bias,
543 use_prev,
544 seg_map: vec![0; mi_cols * mi_rows],
545 mvs: vec![crate::inter::MvRef::default(); mi_cols * mi_rows],
546 prev_seg: std::mem::take(&mut self.prev_seg),
547 prev_mvs: std::mem::take(&mut self.prev_mvs),
548 tile_col_end: mi_cols,
549 frame_index: index,
550 blocks: 0,
551 });
552
553 let mut data: &[u8] = &frame[hdr_start + hdr.header_size_in_bytes as usize..];
554 let mut tiles: Vec<&[u8]> = Vec::with_capacity(tile_cols * tile_rows);
555 for tr in 0..tile_rows {
556 for tc in 0..tile_cols {
557 let last = tr == tile_rows - 1 && tc == tile_cols - 1;
558 if last {
559 tiles.push(data);
560 } else {
561 ensure(data.len() >= 4, "truncated tile size")?;
562 let sz = u32::from_be_bytes(data[..4].try_into().unwrap()) as usize;
563 data = &data[4..];
564 ensure(data.len() >= sz, "truncated tile data")?;
565 tiles.push(&data[..sz]);
566 data = &data[sz..];
567 }
568 }
569 }
570
571 // The loop-filter grids are only written when pixels are built, but
572 // the walk's signature carries them.
573 let mut grids = LfGrids {
574 level8: vec![0; mi_cols * mi_rows],
575 blk: vec![(0u8, 0u32, 0u32); mi_cols * mi_rows],
576 otx: vec![0; mi_cols * mi_rows],
577 skip_inter: vec![false; mi_cols * mi_rows],
578 mi_cols,
579 mi_rows,
580 };
581 // `above_context` / `above_seg_context` and the mi grid are
582 // FRAME-scoped in libvpx (memset once per frame before the tile loop,
583 // `vp9_decodeframe.c:2079-2083`; indexed by absolute mi_row/mi_col by
584 // `set_skip_context`). Tile rows are disjoint in COLUMN only, so a
585 // tile row k > 0 reads above state written by tile row k - 1 — the
586 // same invariant the keyframe path documents. `above_context` is
587 // sized by `mi_cols_aligned_to_sb`: a TX_32X32 block indexes up to 8
588 // 4x4 units past the last mi col.
589 let aligned_cols = mi_cols.div_ceil(SB_MI) * SB_MI;
590 let mut ectx = [
591 PlaneContexts::new(aligned_cols * 2),
592 PlaneContexts::new(aligned_cols * 2),
593 PlaneContexts::new(aligned_cols * 2),
594 ];
595 ectx.iter_mut().for_each(|p| p.above.fill(0));
596 let mut mi = MiState::new(mi_cols, mi_rows);
597 mi.above_seg.fill(0);
598 let mut ti = 0usize;
599 for tr in 0..tile_rows {
600 let row_lo = ((sb64_rows * tr) >> hdr.tile_info.rows_log2) * SB_MI;
601 let row_hi = (((sb64_rows * (tr + 1)) >> hdr.tile_info.rows_log2) * SB_MI).min(mi_rows);
602 for tc in 0..tile_cols {
603 let col_lo = ((sb64_cols * tc) >> hdr.tile_info.cols_log2) * SB_MI;
604 let col_hi =
605 (((sb64_cols * (tc + 1)) >> hdr.tile_info.cols_log2) * SB_MI).min(mi_cols);
606 if let Some(w) = self.iw.as_mut() {
607 w.tile_col_end = col_hi;
608 }
609 if crate::trace_enabled() {
610 eprintln!("TILE {} bytes frame={index}", tiles[ti].len());
611 }
612 let mut r = crate::bool::BoolDecoder::new(tiles[ti])?;
613 ti += 1;
614 for sb_row in (row_lo..row_hi).step_by(SB_MI) {
615 // Left entropy/partition contexts are zeroed at the start
616 // of every superblock row (the SB row's left edge has no
617 // neighbours); the above contexts stay frame-scoped.
618 ectx.iter_mut().for_each(|p| p.left = [0; 32]);
619 mi.left_seg = [0; 32];
620 for sb_col in (col_lo..col_hi).step_by(SB_MI) {
621 self.decode_partition(
622 &mut r,
623 &mut mi,
624 &mut ectx,
625 &mut grids,
626 &[[0u8; 2]; 8],
627 hdr,
628 sb_row,
629 sb_col,
630 4,
631 col_lo,
632 ch.tx_mode,
633 pixels,
634 )?;
635 }
636 }
637 ensure(r.overreads() == 0, "tile bool decoder desync")?;
638 }
639 }
640
641 // The walk state is consumed below, so the block count the harness pins
642 // has to be captured first.
643 self.syntax_blocks = self.iw.as_ref().map_or(0, |w| w.blocks);
644 let w = self.iw.take().expect("inter walk state");
645 self.prev_mvs = w.mvs;
646 self.prev_seg = w.seg_map;
647 self.last = LastFrameFacts {
648 width: hdr.width,
649 height: hdr.height,
650 intra_only: hdr.intra_only,
651 show_frame: hdr.show_frame,
652 key: false,
653 };
654 if hdr.refresh_frame_context {
655 self.frame_ctxs[hdr.frame_context_idx as usize] = self.ctx.as_ref().clone();
656 }
657 if crate::interdump_enabled() {
658 eprintln!(
659 "CHSUM frame={index} tx_mode={} ref_mode={} allow_hp={} interp={} tile_rows={} tile_cols={} pp12={:?} pp0={:?} pp13={:?}",
660 ch.tx_mode,
661 ch.reference_mode,
662 hdr.allow_high_precision_mv,
663 hdr.interpolation_filter as u8,
664 hdr.tile_info.rows_log2,
665 hdr.tile_info.cols_log2,
666 self.ctx.partition[12],
667 self.ctx.partition[0],
668 self.ctx.partition[13]
669 );
670 }
671
672 if !pixels {
673 return Ok(None);
674 }
675
676 // Loop filter post-pass: same extents as the keyframe path, but the
677 // per-cell level comes from the block's own reference and mode class
678 // (`get_filter_level`, vp9_loopfilter.c:249).
679 if hdr.loop_filter.level > 0 && std::env::var_os("EC_VP9_SKIP_LF").is_none() {
680 let p = self.planes.as_mut().expect("frame scratch");
681 let (vw, vh) = (mi_cols * 8, mi_rows * 8);
682 grids.filter_frame(
683 &mut p.y,
684 p.ys,
685 &mut p.u,
686 &mut p.v,
687 p.uvs,
688 vw,
689 vh,
690 vw >> ss_x,
691 vh >> ss_y,
692 ss_x,
693 ss_y,
694 hdr.loop_filter.sharpness,
695 hdr.bit_depth,
696 );
697 }
698
699 let pic = self.take_picture(hdr);
700 let frame = RefFrame {
701 planes: std::sync::Arc::new(self.planes.take().expect("frame scratch")),
702 width: hdr.width as u16,
703 height: hdr.height as u16,
704 };
705
706 // Reference refresh (spec 8.10 / `swap_frame_buffers`): bit i of
707 // `refresh_frame_flags` replaces slot i with the frame just decoded —
708 // the LOOP-FILTERED frame, which is what a later frame's prediction
709 // reads.
710 for slot in 0..8 {
711 if hdr.refresh_frame_flags & (1 << slot) != 0 {
712 self.refs[slot] = Some(frame.clone());
713 }
714 }
715 Ok(if hdr.show_frame { Some(pic) } else { None })
716 }
717
718 /// Crop the frame scratch to a [`Picture`].
719 fn take_picture(&self, hdr: &FrameHeader) -> Picture {
720 crop_picture(
721 self.planes.as_ref().expect("frame scratch"),
722 hdr.width as u16,
723 hdr.height as u16,
724 )
725 }
726
727 /// One inter block's syntax (`read_inter_frame_mode_info` + the MV field
728 /// `vp9_read_mode_info` stores for the next frame).
729 #[allow(clippy::too_many_arguments)]
730 fn read_inter_block_info(
731 &mut self,
732 r: &mut crate::bool::BoolDecoder,
733 mi: &MiState,
734 hdr: &FrameHeader,
735 row: usize,
736 col: usize,
737 sb_type: usize,
738 x_mis: usize,
739 y_mis: usize,
740 tile_col_start: usize,
741 tx_mode: u8,
742 ) -> Result<MiInfo> {
743 // BLOCK_4X4/4X8/8X4 are the SPLIT/VERT/HORZ partitions of an 8x8.
744 let partition = match sb_type {
745 0 => 3u8,
746 1 => 2u8,
747 2 => 1u8,
748 _ => 0u8,
749 };
750 let w = self.iw.as_mut().expect("inter walk state");
751 let prev_seg = std::mem::take(&mut w.prev_seg);
752 let prev_mvs = std::mem::take(&mut w.prev_mvs);
753 let ctx = crate::inter::InterBlockCtx {
754 seg: &hdr.segmentation,
755 ifs: w.ifs,
756 sign_bias: w.sign_bias,
757 allow_hp: hdr.allow_high_precision_mv,
758 frame_interp: interp_filter_of(hdr),
759 tx_mode,
760 mi_rows: mi.mi_rows,
761 mi_cols: mi.mi_cols,
762 tile_col_start,
763 tile_col_end: w.tile_col_end,
764 last_seg: (!prev_seg.is_empty()).then_some(&prev_seg[..]),
765 prev_mvs: (w.use_prev && !prev_mvs.is_empty()).then_some(&prev_mvs[..]),
766 };
767 let info = crate::inter::read_inter_frame_mode_info(
768 r,
769 mi,
770 &ctx,
771 &self.ctx,
772 row,
773 col,
774 sb_type,
775 x_mis,
776 y_mis,
777 partition,
778 &mut w.seg_map,
779 );
780 if let Ok(info) = &info {
781 w.blocks += 1;
782 for dy in 0..y_mis {
783 for dx in 0..x_mis {
784 let i = (row + dy) * mi.mi_cols + col + dx;
785 w.mvs[i] = crate::inter::MvRef {
786 ref_frame: info.ref_frame,
787 mv: info.mv,
788 };
789 }
790 }
791 if crate::interdump_enabled() {
792 eprintln!(
793 "MODE {} {} {} {} {} {} {} {} {} tpos=0 ref0={} ref1={} mvrow={} mvcol={} if={}",
794 w.frame_index,
795 row,
796 col,
797 sb_type,
798 info.tx_size,
799 info.mode,
800 info.uv_mode,
801 u8::from(info.skip),
802 info.segment,
803 info.ref_frame[0],
804 info.ref_frame[1],
805 info.mv[0].0,
806 info.mv[0].1,
807 info.interp_filter
808 );
809 }
810 }
811 w.prev_seg = prev_seg;
812 w.prev_mvs = prev_mvs;
813 info
814 }
815
816 /// Tokens for one inter block: same entropy walk as the keyframe path,
817 /// but no prediction and no residual add. `is_inter` selects the
818 /// coefficient-probability ref axis.
819 #[allow(clippy::too_many_arguments)]
820 fn decode_inter_block_tokens(
821 &mut self,
822 r: &mut crate::bool::BoolDecoder,
823 mi: &MiState,
824 ectx: &mut [PlaneContexts; 3],
825 hdr: &FrameHeader,
826 info: &MiInfo,
827 row: usize,
828 col: usize,
829 sb_type: usize,
830 bw: usize,
831 bh: usize,
832 ) -> Result<()> {
833 let (ss_x, ss_y) = plane_ss(hdr, 1);
834 let n4w = [
835 plane_n4_w(bw, 0),
836 plane_n4_w(bw, ss_x),
837 plane_n4_w(bw, ss_x),
838 ];
839 let n4h = [
840 plane_n4_h(bh, 0),
841 plane_n4_h(bh, ss_y),
842 plane_n4_h(bh, ss_y),
843 ];
844 if info.skip {
845 // dec_reset_skip_context
846 reset_skip_context(ectx, row, col, sb_type, n4w, n4h, ss_x, ss_y);
847 return Ok(());
848 }
849 let mb_to_right = ((mi.mi_cols as isize - bw as isize - col as isize) * 64) as i32;
850 let mb_to_bottom = ((mi.mi_rows as isize - bh as isize - row as isize) * 64) as i32;
851 for plane in 0..3usize {
852 let (ss_x, ss_y) = plane_ss(hdr, plane);
853 let tx_size = if plane == 0 {
854 info.tx_size
855 } else {
856 get_uv_tx_size(info.tx_size, sb_type, ss_x, ss_y)
857 };
858 let step = 1usize << tx_size;
859 let max_blocks_wide =
860 (n4w[plane] as i32 + (mb_to_right.min(0) >> (5 + ss_x))).max(0) as usize;
861 let max_blocks_high =
862 (n4h[plane] as i32 + (mb_to_bottom.min(0) >> (5 + ss_y))).max(0) as usize;
863 for brow in (0..max_blocks_high).step_by(step) {
864 for bcol in (0..max_blocks_wide).step_by(step) {
865 let _ = decode_inter_tx_tokens(
866 r,
867 ectx,
868 hdr,
869 info,
870 &self.ctx,
871 plane,
872 row,
873 col,
874 brow,
875 bcol,
876 tx_size,
877 sb_type,
878 bw,
879 bh,
880 mb_to_right,
881 mb_to_bottom,
882 );
883 }
884 }
885 }
886 Ok(())
887 }
888
889 /// `decode_block`'s inter arm with pixels (`vp9_decodeframe.c:990-1044`):
890 /// `dec_build_inter_predictors_sb` for the whole block, then
891 /// `reconstruct_inter_block` per transform block. Intra blocks inside an
892 /// inter frame take the intra path (`:964-989`).
893 #[allow(clippy::too_many_arguments)]
894 fn reconstruct_inter_pixels(
895 &mut self,
896 r: &mut crate::bool::BoolDecoder,
897 ectx: &mut [PlaneContexts; 3],
898 grids: &mut LfGrids,
899 hdr: &FrameHeader,
900 info: &MiInfo,
901 row: usize,
902 col: usize,
903 sb_type: usize,
904 bw: usize,
905 bh: usize,
906 mi: &mut MiState,
907 tile_col_start: usize,
908 ) -> Result<()> {
909 let (ss_x, ss_y) = plane_ss(hdr, 1);
910 let x_mis = bw.min(mi.mi_cols - col);
911 let y_mis = bh.min(mi.mi_rows - row);
912 let n4w = [
913 plane_n4_w(bw, 0),
914 plane_n4_w(bw, ss_x),
915 plane_n4_w(bw, ss_x),
916 ];
917 let n4h = [
918 plane_n4_h(bh, 0),
919 plane_n4_h(bh, ss_y),
920 plane_n4_h(bh, ss_y),
921 ];
922 let mb_to_right = ((mi.mi_cols as isize - bw as isize - col as isize) * 64) as i32;
923 let mb_to_bottom = ((mi.mi_rows as isize - bh as isize - row as isize) * 64) as i32;
924
925 // `get_filter_level` (vp9_loopfilter.c:249):
926 // `lvl[segment_id][mi->ref_frame[0]][mode_lf_lut[mi->mode]]`, with
927 // `lvl` built by `vp9_loop_filter_frame_init` from the frame level,
928 // the per-reference deltas and the per-mode-class deltas.
929 let levels = hdr.loop_filter_levels(info.segment as usize);
930 let ref0 = if info.is_inter {
931 info.ref_frame[0].clamp(0, 3) as usize
932 } else {
933 // An intra block inside an inter frame: `mi->ref_frame[0]` is
934 // INTRA_FRAME and its mode is an intra mode, so the mode class is
935 // 0 and the reference slot is intra's.
936 0
937 };
938 let level = levels[ref0][mode_lf_lut(info.mode)];
939 for dy in 0..y_mis {
940 for dx in 0..x_mis {
941 let cell = (row + dy) * mi.mi_cols + col + dx;
942 grids.level8[cell] = level;
943 grids.blk[cell] = (sb_type as u8, row as u32, col as u32);
944 grids.otx[cell] = if sb_type < 3 {
945 TX_4X4 as u8
946 } else {
947 info.tx_size as u8
948 };
949 // `build_masks`'s early return is gated on
950 // `mi->skip && is_inter_block(mi)` — a skipped inter block
951 // keeps ONLY the above/left prediction masks.
952 grids.skip_inter[cell] = info.is_inter && info.skip;
953 }
954 }
955
956 // `if (mi->skip) dec_reset_skip_context(xd);` — libvpx does this at the
957 // top of `decode_block` (decodeframe.c:960), BEFORE the intra/inter
958 // split, so skipped intra blocks inside an inter frame reset too.
959 if info.skip {
960 reset_skip_context(ectx, row, col, sb_type, n4w, n4h, ss_x, ss_y);
961 }
962
963 if !info.is_inter {
964 // `predict_and_reconstruct_intra_block` per transform block.
965 for plane in 0..3usize {
966 let (ss_x, ss_y) = plane_ss(hdr, plane);
967 let tx_size = if plane == 0 {
968 info.tx_size
969 } else {
970 get_uv_tx_size(info.tx_size, sb_type, ss_x, ss_y)
971 };
972 let step = 1usize << tx_size;
973 let max_blocks_wide =
974 (n4w[plane] as i32 + (mb_to_right.min(0) >> (5 + ss_x))).max(0) as usize;
975 let max_blocks_high =
976 (n4h[plane] as i32 + (mb_to_bottom.min(0) >> (5 + ss_y))).max(0) as usize;
977 for brow in (0..max_blocks_high).step_by(step) {
978 for bcol in (0..max_blocks_wide).step_by(step) {
979 self.predict_and_reconstruct(
980 r,
981 ectx,
982 hdr,
983 info,
984 plane,
985 row,
986 col,
987 brow,
988 bcol,
989 tx_size,
990 sb_type,
991 bw,
992 bh,
993 mb_to_right,
994 mb_to_bottom,
995 // Intra prediction's left availability is
996 // tile-scoped (`tile->mi_col_start`), which the
997 // inter walk passes as the tile's first mi col.
998 tile_col_start,
999 )?;
1000 }
1001 }
1002 }
1003 return Ok(());
1004 }
1005
1006 // Prediction: `dec_build_inter_predictors_sb`, every reference, every
1007 // plane, before any token is read.
1008 {
1009 let planes = self.planes.as_mut().expect("frame scratch");
1010 let refs = &self.refs;
1011 let scratch = &mut self.mc_scratch;
1012 let temp = &mut self.mc_temp;
1013 for plane in 0..3usize {
1014 inter_predict_plane(
1015 planes,
1016 refs,
1017 scratch,
1018 temp,
1019 hdr,
1020 info,
1021 plane,
1022 row,
1023 col,
1024 &n4w,
1025 &n4h,
1026 mb_to_right,
1027 mb_to_bottom,
1028 sb_type,
1029 )?;
1030 }
1031 }
1032
1033 if info.skip {
1034 return Ok(());
1035 }
1036
1037 // Reconstruction: `reconstruct_inter_block` per transform block.
1038 let mut eobtotal = 0usize;
1039 for plane in 0..3usize {
1040 let (ss_x, ss_y) = plane_ss(hdr, plane);
1041 let tx_size = if plane == 0 {
1042 info.tx_size
1043 } else {
1044 get_uv_tx_size(info.tx_size, sb_type, ss_x, ss_y)
1045 };
1046 let step = 1usize << tx_size;
1047 let max_blocks_wide =
1048 (n4w[plane] as i32 + (mb_to_right.min(0) >> (5 + ss_x))).max(0) as usize;
1049 let max_blocks_high =
1050 (n4h[plane] as i32 + (mb_to_bottom.min(0) >> (5 + ss_y))).max(0) as usize;
1051 for brow in (0..max_blocks_high).step_by(step) {
1052 for bcol in (0..max_blocks_wide).step_by(step) {
1053 let coef = decode_inter_tx_tokens(
1054 r,
1055 ectx,
1056 hdr,
1057 info,
1058 &self.ctx,
1059 plane,
1060 row,
1061 col,
1062 brow,
1063 bcol,
1064 tx_size,
1065 sb_type,
1066 bw,
1067 bh,
1068 mb_to_right,
1069 mb_to_bottom,
1070 );
1071 eobtotal += coef.eob;
1072 if coef.eob == 0 {
1073 continue;
1074 }
1075 // `inverse_transform_block_inter`: inter blocks always use
1076 // the DEFAULT scan and DCT_DCT (`reconstruct_inter_block`,
1077 // decodeframe.c:413).
1078 let planes = self.planes.as_mut().expect("frame scratch");
1079 let stride = planes.dims(plane).0;
1080 let bd = planes.bd;
1081 let x0 = ((col * 8) >> ss_x) + bcol * 4;
1082 let y0 = ((row * 8) >> ss_y) + brow * 4;
1083 let dst_off = y0 * stride + x0;
1084 let (data, _) = planes.plane(plane);
1085 inverse_transform_add(
1086 tx_size,
1087 DCT_DCT,
1088 &coef.coeffs,
1089 data,
1090 dst_off,
1091 stride,
1092 hdr.quantization.lossless(),
1093 bd,
1094 );
1095 }
1096 }
1097 }
1098
1099 // `if (!less8x8 && eobtotal == 0) mi->skip = 1; // skip loopfilter`
1100 // (decodeframe.c:1043).
1101 if sb_type >= 3 && eobtotal == 0 {
1102 for dy in 0..y_mis {
1103 for dx in 0..x_mis {
1104 grids.skip_inter[(row + dy) * mi.mi_cols + col + dx] = true;
1105 }
1106 }
1107 }
1108 Ok(())
1109 }
1110
1111 fn decode_keyframe(&mut self, hdr: &FrameHeader, frame: &[u8], tx_mode: u8) -> Result<Picture> {
1112 let ss_x = hdr.subsampling_x as usize;
1113 let ss_y = hdr.subsampling_y as usize;
1114 let width = hdr.width as usize;
1115 let height = hdr.height as usize;
1116 // The decode buffer is padded to whole superblocks: libvpx decodes a
1117 // block at the frame edge at its FULL size (decodeframe.c:1216,
1118 // `PARTITION_NONE` needs only `mi_row < mi_rows`) and writes the
1119 // overhang into the frame buffer's border. Clipping to 8 pixels
1120 // instead panicked on real 1080p content (a 32x32 block starting at
1121 // mi_row 132 writes 8 rows past a 1080-row buffer).
1122 let aw = width.div_ceil(64) * 64;
1123 let ah = height.div_ceil(64) * 64;
1124 self.planes = Some(Planes::new(aw, ah, hdr.bit_depth, ss_x, ss_y));
1125 let tail_start = std::env::var("EC_VP9_FORCE_TAIL")
1126 .ok()
1127 .and_then(|s| s.parse().ok())
1128 .unwrap_or_else(|| {
1129 hdr.uncompressed_header_size as usize + hdr.header_size_in_bytes as usize
1130 });
1131 let tail: Vec<u8> = frame[tail_start..].to_vec();
1132 self.decode_keyframe_inner(hdr, tx_mode, &tail)
1133 }
1134
1135 fn decode_keyframe_inner(
1136 &mut self,
1137 hdr: &FrameHeader,
1138 tx_mode: u8,
1139 tail: &[u8],
1140 ) -> Result<Picture> {
1141 let ss_x = hdr.subsampling_x as usize;
1142 let ss_y = hdr.subsampling_y as usize;
1143 let mi_cols = hdr.mi_cols() as usize;
1144 let mi_rows = hdr.mi_rows() as usize;
1145 let sb64_cols = mi_cols.div_ceil(SB_MI);
1146 let sb64_rows = mi_rows.div_ceil(SB_MI);
1147 let tile_cols = 1usize << hdr.tile_info.cols_log2;
1148 let tile_rows = 1usize << hdr.tile_info.rows_log2;
1149
1150 // Tile data: every tile except the overall last carries a
1151 // 32-bit BIG-endian size prefix (spec 6.4; libvpx `get_tile_buffer`
1152 // reads it with `mem_get_be32`, vp9_decodeframe.c:1688/1690).
1153 let mut data: &[u8] = tail;
1154 let mut tiles: Vec<&[u8]> = Vec::with_capacity(tile_cols * tile_rows);
1155 for tr in 0..tile_rows {
1156 for tc in 0..tile_cols {
1157 let last = tr == tile_rows - 1 && tc == tile_cols - 1;
1158 if last {
1159 tiles.push(data);
1160 } else {
1161 ensure(data.len() >= 4, "truncated tile size")?;
1162 let sz = u32::from_be_bytes(data[..4].try_into().unwrap()) as usize;
1163 data = &data[4..];
1164 ensure(data.len() >= sz, "truncated tile data")?;
1165 tiles.push(&data[..sz]);
1166 data = &data[sz..];
1167 }
1168 }
1169 }
1170
1171 // Keyframe loop filter levels: intra ref, no mode class, per
1172 // segment (spec 8.8.1).
1173 let mut level_of_seg = [[0u8; 2]; 8];
1174 for (seg, slot) in level_of_seg.iter_mut().enumerate() {
1175 *slot = hdr.loop_filter_levels(seg)[0];
1176 }
1177
1178 let mut grids = LfGrids {
1179 level8: vec![0; mi_cols * mi_rows],
1180 blk: vec![(0u8, 0u32, 0u32); mi_cols * mi_rows],
1181 otx: vec![0; mi_cols * mi_rows],
1182 skip_inter: vec![false; mi_cols * mi_rows],
1183 mi_cols,
1184 mi_rows,
1185 };
1186 let mut ti = 0usize;
1187 // `above_context` / `above_seg_context` and the mi grid are
1188 // FRAME-scoped in libvpx: `cm->above_context` is memset once per
1189 // frame BEFORE the tile loop (vp9_decodeframe.c:2079-2080 / :2082-2083,
1190 // inside the :2077-2083 block), the
1191 // shared `cm->mi_grid_visible` accumulates every tile's records, and
1192 // the buffers are indexed by ABSOLUTE mi_row/mi_col
1193 // (`set_skip_context`, vp9_onyxc_int.h:405-413). A tile row k > 0
1194 // therefore reads above state written by tile row k - 1 — tiles are
1195 // disjoint in COLUMN only. Allocating these per tile would discard
1196 // that above state and mis-gate `xd->above_mi`, so they live here and
1197 // are zeroed exactly once per frame.
1198 // libvpx sizes `cm->above_context` by `mi_cols_aligned_to_sb` and the
1199 // mi grid stride by `mi_cols`; the above arrays are written/indexed up
1200 // to a whole TX_32X32 (8 4x4 units) past the last mi col, so a
1201 // non-multiple-of-8 width would otherwise index out of bounds.
1202 let aligned_cols = mi_cols.div_ceil(SB_MI) * SB_MI;
1203 let mut ectx = [
1204 PlaneContexts::new(aligned_cols * 2),
1205 PlaneContexts::new(aligned_cols * 2),
1206 PlaneContexts::new(aligned_cols * 2),
1207 ];
1208 ectx.iter_mut().for_each(|p| p.above.fill(0));
1209 let mut mi = MiState::new(mi_cols, mi_rows);
1210 mi.above_seg.fill(0);
1211 for tr in 0..tile_rows {
1212 let row_lo = ((sb64_rows * tr) >> hdr.tile_info.rows_log2) * SB_MI;
1213 let row_hi = (((sb64_rows * (tr + 1)) >> hdr.tile_info.rows_log2) * SB_MI).min(mi_rows);
1214 for tc in 0..tile_cols {
1215 let col_lo = ((sb64_cols * tc) >> hdr.tile_info.cols_log2) * SB_MI;
1216 let col_hi =
1217 (((sb64_cols * (tc + 1)) >> hdr.tile_info.cols_log2) * SB_MI).min(mi_cols);
1218 if crate::trace_enabled() {
1219 eprintln!(
1220 "TILE {} bytes first={:02x?}",
1221 tiles[ti].len(),
1222 &tiles[ti][..8.min(tiles[ti].len())]
1223 );
1224 }
1225 let mut r = crate::bool::BoolDecoder::new(tiles[ti])?;
1226 ti += 1;
1227 for sb_row in (row_lo..row_hi).step_by(SB_MI) {
1228 // libvpx zeroes the left ENTROPY and PARTITION contexts at
1229 // the start of EVERY superblock row, not just the tile's
1230 // first one (vp9_decodeframe.c:2260-2261 plain
1231 // `decode_tiles`; the row-mt twin is :2117-2118 and the
1232 // per-tile-row twins :1828-1829 / :1901-1902): the left
1233 // edge of an SB row has no pixels to its left. Our luma
1234 // left index wraps at mi_row 16, so a stale value from two
1235 // SB rows earlier would otherwise be read here.
1236 // `above_context`/`above_seg_context` are frame-scoped
1237 // (memset once per frame at :2079-2083, before the tile
1238 // loop) and indexed by ABSOLUTE mi_col, so they persist
1239 // across tile rows and are NOT reset here.
1240 ectx.iter_mut().for_each(|p| p.left = [0; 32]);
1241 mi.left_seg = [0; 32];
1242 for sb_col in (col_lo..col_hi).step_by(SB_MI) {
1243 self.decode_partition(
1244 &mut r,
1245 &mut mi,
1246 &mut ectx,
1247 &mut grids,
1248 &level_of_seg,
1249 hdr,
1250 sb_row,
1251 sb_col,
1252 4,
1253 col_lo,
1254 tx_mode,
1255 true,
1256 )?;
1257 }
1258 }
1259 if r.overreads() != 0 {
1260 return Err(corrupt(format!(
1261 "tile bool decoder desync (tile tr={tr} tc={tc} overreads={})",
1262 r.overreads()
1263 )));
1264 }
1265 }
1266 }
1267
1268 // Loop filter post-pass (level 0 disables it for the frame).
1269 // The extents are the MI-aligned VISIBLE plane (libvpx's masks clear
1270 // everything past `mi_cols`/`mi_rows`), not the padded buffer size.
1271 if hdr.loop_filter.level > 0 && std::env::var_os("EC_VP9_SKIP_LF").is_none() {
1272 let p = self.planes.as_mut().expect("frame scratch");
1273 let (vw, vh) = (mi_cols * 8, mi_rows * 8);
1274 grids.filter_frame(
1275 &mut p.y,
1276 p.ys,
1277 &mut p.u,
1278 &mut p.v,
1279 p.uvs,
1280 vw,
1281 vh,
1282 vw >> ss_x,
1283 vh >> ss_y,
1284 ss_x,
1285 ss_y,
1286 hdr.loop_filter.sharpness,
1287 hdr.bit_depth,
1288 );
1289 }
1290
1291 Ok(self.take_picture(hdr))
1292 }
1293
1294 /// `decode_partition` (decodeframe.c:1173).
1295 #[allow(clippy::too_many_arguments)]
1296 fn decode_partition(
1297 &mut self,
1298 r: &mut crate::bool::BoolDecoder,
1299 mi: &mut MiState,
1300 ectx: &mut [PlaneContexts; 3],
1301 grids: &mut LfGrids,
1302 level_of_seg: &[[u8; 2]; 8],
1303 hdr: &FrameHeader,
1304 row: usize,
1305 col: usize,
1306 n4: usize,
1307 tile_col_start: usize,
1308 tx_mode: u8,
1309 // Whether this walk reconstructs pixels. Consulted by the inter
1310 // branch only: a keyframe always reconstructs its intra blocks, and
1311 // the syntax-only inter walk parses tokens without predicting.
1312 pixels: bool,
1313 ) -> Result<()> {
1314 if row >= mi.mi_rows || col >= mi.mi_cols {
1315 return Ok(());
1316 }
1317 let n8 = n4 - 1;
1318 let hbs = (1usize << n8) >> 1;
1319 let has_rows = row + hbs < mi.mi_rows;
1320 let has_cols = col + hbs < mi.mi_cols;
1321 // libvpx reads the partition symbol at EVERY level INCLUDING 8x8
1322 // (decodeframe.c:1188 runs before the `!hbs` branch): the 8x8
1323 // symbol picks 8x8 / 8x4 / 4x8 / 4x4-split — the sub-8x8 shapes.
1324 // Only the 4x4 level has no symbol, and SPLIT recursion never
1325 // reaches it (it stops at n4 == 1).
1326 let partition = {
1327 let ctx = mi.partition_ctx(row, col, n8 as u32);
1328 let probs = &self.ctx.partition[ctx];
1329 if has_rows && has_cols {
1330 r.read_tree(&PARTITION_TREE, probs)
1331 } else if !has_rows && has_cols {
1332 if r.read_bool(probs[1]) { 3 } else { 1 }
1333 } else if has_rows && !has_cols {
1334 if r.read_bool(probs[2]) { 3 } else { 2 }
1335 } else {
1336 3
1337 }
1338 };
1339 let bsize = bsize_of_n4(n4);
1340 let subsize = SUBSIZE_LOOKUP[partition as usize * 13 + bsize] as usize;
1341 if hbs == 0 {
1342 self.decode_block(
1343 r,
1344 mi,
1345 ectx,
1346 grids,
1347 level_of_seg,
1348 hdr,
1349 row,
1350 col,
1351 subsize,
1352 1,
1353 1,
1354 tile_col_start,
1355 tx_mode,
1356 pixels,
1357 )?;
1358 } else {
1359 match partition {
1360 0 => self.decode_block(
1361 r,
1362 mi,
1363 ectx,
1364 grids,
1365 level_of_seg,
1366 hdr,
1367 row,
1368 col,
1369 subsize,
1370 n4,
1371 n4,
1372 tile_col_start,
1373 tx_mode,
1374 pixels,
1375 )?,
1376 1 => {
1377 self.decode_block(
1378 r,
1379 mi,
1380 ectx,
1381 grids,
1382 level_of_seg,
1383 hdr,
1384 row,
1385 col,
1386 subsize,
1387 n4,
1388 n8,
1389 tile_col_start,
1390 tx_mode,
1391 pixels,
1392 )?;
1393 if has_rows {
1394 self.decode_block(
1395 r,
1396 mi,
1397 ectx,
1398 grids,
1399 level_of_seg,
1400 hdr,
1401 row + hbs,
1402 col,
1403 subsize,
1404 n4,
1405 n8,
1406 tile_col_start,
1407 tx_mode,
1408 pixels,
1409 )?;
1410 }
1411 }
1412 2 => {
1413 self.decode_block(
1414 r,
1415 mi,
1416 ectx,
1417 grids,
1418 level_of_seg,
1419 hdr,
1420 row,
1421 col,
1422 subsize,
1423 n8,
1424 n4,
1425 tile_col_start,
1426 tx_mode,
1427 pixels,
1428 )?;
1429 if has_cols {
1430 self.decode_block(
1431 r,
1432 mi,
1433 ectx,
1434 grids,
1435 level_of_seg,
1436 hdr,
1437 row,
1438 col + hbs,
1439 subsize,
1440 n8,
1441 n4,
1442 tile_col_start,
1443 tx_mode,
1444 pixels,
1445 )?;
1446 }
1447 }
1448 _ => {
1449 for (rr, cc) in [
1450 (row, col),
1451 (row, col + hbs),
1452 (row + hbs, col),
1453 (row + hbs, col + hbs),
1454 ] {
1455 self.decode_partition(
1456 r,
1457 mi,
1458 ectx,
1459 grids,
1460 level_of_seg,
1461 hdr,
1462 rr,
1463 cc,
1464 n8,
1465 tile_col_start,
1466 tx_mode,
1467 pixels,
1468 )?;
1469 }
1470 }
1471 }
1472 }
1473 if bsize >= 3 && (bsize == 3 || partition != 3) {
1474 mi.update_partition_ctx(row, col, subsize, 1 << n8);
1475 }
1476 Ok(())
1477 }
1478
1479 /// `decode_block` intra path (decodeframe.c:913).
1480 #[allow(clippy::too_many_arguments)]
1481 fn decode_block(
1482 &mut self,
1483 r: &mut crate::bool::BoolDecoder,
1484 mi: &mut MiState,
1485 ectx: &mut [PlaneContexts; 3],
1486 grids: &mut LfGrids,
1487 level_of_seg: &[[u8; 2]; 8],
1488 hdr: &FrameHeader,
1489 row: usize,
1490 col: usize,
1491 sb_type: usize,
1492 bwl: usize,
1493 bhl: usize,
1494 tile_col_start: usize,
1495 tx_mode: u8,
1496 pixels: bool,
1497 ) -> Result<()> {
1498 let bw = 1 << (bwl - 1);
1499 let bh = 1 << (bhl - 1);
1500 let x_mis = bw.min(mi.mi_cols - col);
1501 let y_mis = bh.min(mi.mi_rows - row);
1502
1503 // `decode_block` (decodeframe.c:942): a block size that does not
1504 // exist once subsampled (`BLOCK_8X4` under 4:4:0, `BLOCK_4X8` under
1505 // 4:2:2) is a corrupt frame. Sub-8x8 sizes have no `ss_size_lookup`
1506 // row to check and are exempt.
1507 if sb_type >= 3 && (hdr.subsampling_x != 0 || hdr.subsampling_y != 0) {
1508 ensure(
1509 ss_size(
1510 sb_type,
1511 hdr.subsampling_x as usize,
1512 hdr.subsampling_y as usize,
1513 ) != BLOCK_INVALID,
1514 "invalid block size for the chroma subsampling",
1515 )?;
1516 }
1517
1518 // `frame_is_intra_only` (onyxc_int.h:363): a keyframe OR an
1519 // intra-only frame walks the intra mode-info path.
1520 let intra_frame = hdr.frame_type == FrameType::Key || hdr.intra_only;
1521 let info = if intra_frame {
1522 read_intra_frame_mode_info(
1523 r,
1524 mi,
1525 &hdr.segmentation,
1526 &self.ctx.partition,
1527 row,
1528 col,
1529 sb_type,
1530 x_mis,
1531 y_mis,
1532 tile_col_start,
1533 tx_mode,
1534 &self.ctx,
1535 )?
1536 } else {
1537 self.read_inter_block_info(
1538 r,
1539 mi,
1540 hdr,
1541 row,
1542 col,
1543 sb_type,
1544 x_mis,
1545 y_mis,
1546 tile_col_start,
1547 tx_mode,
1548 )?
1549 };
1550 if !intra_frame {
1551 if pixels {
1552 // Full inter decode: prediction, tokens, residual. The
1553 // per-cell loop-filter level is the block's own reference and
1554 // mode class (`get_filter_level`), so the grids are written
1555 // inside the reconstruction rather than from `level_of_seg`.
1556 self.reconstruct_inter_pixels(
1557 r,
1558 ectx,
1559 grids,
1560 hdr,
1561 &info,
1562 row,
1563 col,
1564 sb_type,
1565 bw,
1566 bh,
1567 mi,
1568 tile_col_start,
1569 )?;
1570 } else {
1571 // Inter syntax only: tokens keep the entropy stream aligned,
1572 // the block lands in the mode grid, and no pixel is touched.
1573 self.decode_inter_block_tokens(r, mi, ectx, hdr, &info, row, col, sb_type, bw, bh)?;
1574 }
1575 for dy in 0..y_mis {
1576 for dx in 0..x_mis {
1577 if crate::mvdbg2_enabled() && row + dy == 7 && col + dx >= 30 && col + dx <= 40
1578 {
1579 eprintln!(
1580 "GWR cell=({} {}) idx={} from=({row} {col}) dy={dy} dx={dx} sb={sb_type} bw={bw} bh={bh} x_mis={x_mis} y_mis={y_mis} mv={:?} ref0={} mi_cols={}",
1581 row + dy,
1582 col + dx,
1583 (row + dy) * mi.mi_cols + col + dx,
1584 info.mv,
1585 info.ref_frame[0],
1586 mi.mi_cols
1587 );
1588 }
1589 mi.grid[(row + dy) * mi.mi_cols + col + dx] = Some(info.clone());
1590 }
1591 }
1592 return Ok(());
1593 }
1594
1595 // Per-plane 4x4 counts. Sub-8x8 shapes still occupy the WHOLE 8x8
1596 // mi area (libvpx set_plane_n4 with bw=bh=1): luma walks 2x2 4x4
1597 // TUs, chroma is one 4x4 (n4 >> subsampling), coded once per 8x8.
1598 let (ss_x, ss_y) = plane_ss(hdr, 1);
1599 let n4w = [
1600 plane_n4_w(bw, 0),
1601 plane_n4_w(bw, ss_x),
1602 plane_n4_w(bw, ss_x),
1603 ];
1604 let n4h = [
1605 plane_n4_h(bh, 0),
1606 plane_n4_h(bh, ss_y),
1607 plane_n4_h(bh, ss_y),
1608 ];
1609 let mb_to_right = ((mi.mi_cols as isize - bw as isize - col as isize) * 64) as i32;
1610 let mb_to_bottom = ((mi.mi_rows as isize - bh as isize - row as isize) * 64) as i32;
1611
1612 let level = level_of_seg[info.segment as usize][0];
1613 for dy in 0..y_mis {
1614 for dx in 0..x_mis {
1615 let cell = (row + dy) * mi.mi_cols + col + dx;
1616 grids.level8[cell] = level;
1617 grids.blk[cell] = (sb_type as u8, row as u32, col as u32);
1618 grids.otx[cell] = if sb_type < 3 {
1619 TX_4X4 as u8
1620 } else {
1621 info.tx_size as u8
1622 };
1623 }
1624 }
1625
1626 if info.skip {
1627 for plane in 0..3usize {
1628 let (sx, sy) = if plane == 0 { (0, 0) } else { (ss_x, ss_y) };
1629 let offx = (col << 1) >> sx;
1630 let offy = (row << 1) >> sy;
1631 for i in 0..n4w[plane] {
1632 ectx[plane].above[offx + i] = 0;
1633 }
1634 let lrows = 32usize >> sy;
1635 for i in 0..n4h[plane].min(lrows) {
1636 ectx[plane].left[(offy + i) % lrows] = 0;
1637 }
1638 }
1639 }
1640
1641 for plane in 0..3usize {
1642 let (ss_x, ss_y) = plane_ss(hdr, plane);
1643 let tx_size = if plane == 0 {
1644 info.tx_size
1645 } else {
1646 get_uv_tx_size(info.tx_size, sb_type, ss_x, ss_y)
1647 };
1648 let step = 1usize << tx_size;
1649 let max_blocks_wide =
1650 (n4w[plane] as i32 + (mb_to_right.min(0) >> (5 + ss_x))).max(0) as usize;
1651 let max_blocks_high =
1652 (n4h[plane] as i32 + (mb_to_bottom.min(0) >> (5 + ss_y))).max(0) as usize;
1653 for brow in (0..max_blocks_high).step_by(step) {
1654 for bcol in (0..max_blocks_wide).step_by(step) {
1655 self.predict_and_reconstruct(
1656 r,
1657 ectx,
1658 hdr,
1659 &info,
1660 plane,
1661 row,
1662 col,
1663 brow,
1664 bcol,
1665 tx_size,
1666 sb_type,
1667 bw,
1668 bh,
1669 mb_to_right,
1670 mb_to_bottom,
1671 tile_col_start,
1672 )?;
1673 }
1674 }
1675 }
1676
1677 for dy in 0..y_mis {
1678 for dx in 0..x_mis {
1679 mi.grid[(row + dy) * mi.mi_cols + col + dx] = Some(info.clone());
1680 }
1681 }
1682 Ok(())
1683 }
1684
1685 /// `predict_and_reconstruct_intra_block` (decodeframe.c:309):
1686 /// predict, then tokens, then residual add; plus
1687 /// `vp9_decode_block_tokens` context bookkeeping (the v1.15 edge
1688 /// shifts included).
1689 #[allow(clippy::too_many_arguments)]
1690 fn predict_and_reconstruct(
1691 &mut self,
1692 r: &mut crate::bool::BoolDecoder,
1693 ectx: &mut [PlaneContexts; 3],
1694 hdr: &FrameHeader,
1695 info: &MiInfo,
1696 plane: usize,
1697 mi_row: usize,
1698 mi_col: usize,
1699 tx_row: usize,
1700 tx_col: usize,
1701 tx_size: usize,
1702 sb_type: usize,
1703 bw: usize,
1704 bh: usize,
1705 mb_to_right: i32,
1706 mb_to_bottom: i32,
1707 tile_col_start: usize,
1708 ) -> Result<()> {
1709 let (ss_x, ss_y) = plane_ss(hdr, plane);
1710 let mode = if plane == 0 {
1711 if sb_type < 3 {
1712 info.bmi[(tx_row << 1) + tx_col]
1713 } else {
1714 info.mode
1715 }
1716 } else {
1717 info.uv_mode
1718 };
1719 let planes = self.planes.as_mut().expect("frame scratch");
1720 let stride = planes.dims(plane).0;
1721 let bd = planes.bd;
1722 let bs = 4 << tx_size;
1723 let x0 = ((mi_col * 8) >> ss_x) + tx_col * 4;
1724 let y0 = ((mi_row * 8) >> ss_y) + tx_row * 4;
1725 // vp9_predict_intra_block `have_top = loff || (xd->above_mi != NULL)`
1726 // (vp9_reconintra.c:411); `above_mi` is FRAME-gated
1727 // (`set_mi_row_col`, vp9_onyxc_int.h:430: `mi_row != 0`), NOT
1728 // tile-row-gated. The above row of a tile row k > 0 is decoded by
1729 // tile row k - 1 and is available.
1730 let up = tx_row != 0 || mi_row > 0;
1731 let lft = tx_col != 0 || mi_col > tile_col_start;
1732 // vp9_predict_intra_block `have_right`: the tx block is not in the
1733 // last tx column of ITS OWN block (pd->n4_w units) — above-right
1734 // past the block's right edge belongs to a not-yet-decoded
1735 // neighbour, so it must stage as unavailable.
1736 let rgt = tx_col + (1usize << tx_size) < bw * 2 >> ss_x;
1737
1738 // `xd->cur_buf->y_width/y_height` (vp9_reconintra.c:288-292) are the
1739 // MI-ALIGNED (8-multiple) buffer extent, not the visible coded size:
1740 // confirmed by instrumenting the oracle's staging for a 320x242 frame
1741 // (`fh=248`, not 242). The extend-vs-direct DECISION is `mb_to_*_edge`
1742 // (`:302/326/354`, passed in as `bot_ext`/`right_ext`).
1743 let vw = (hdr.mi_cols() as usize * 8) >> ss_x;
1744 let vh = (hdr.mi_rows() as usize * 8) >> ss_y;
1745
1746 // 1. Intra prediction (reads reconstructed neighbours).
1747 {
1748 let (data, _) = planes.plane(plane);
1749 build_intra_predictors(
1750 data,
1751 stride,
1752 vw,
1753 vh,
1754 x0,
1755 y0,
1756 mode,
1757 bs,
1758 up,
1759 lft,
1760 rgt,
1761 mb_to_bottom < 0,
1762 mb_to_right < 0,
1763 bd,
1764 );
1765 }
1766
1767 if info.skip {
1768 return Ok(());
1769 }
1770
1771 // 2. Tokens.
1772 let lossless = hdr.quantization.lossless();
1773 let tx_type = if plane != 0 || lossless {
1774 DCT_DCT
1775 } else {
1776 MODE_TO_TXTYPE_LOOKUP[mode as usize] as usize
1777 };
1778 let (scan, nb) = scan_for(tx_size, tx_type);
1779 let q = hdr.segment_dequant(info.segment as usize);
1780 let dequant: [i16; 2] = if plane == 0 {
1781 [q.luma_dc, q.luma_ac]
1782 } else {
1783 [q.chroma_dc, q.chroma_ac]
1784 };
1785 let ptype = usize::from(plane != 0);
1786 let ax = ((mi_col << 1) >> ss_x) + tx_col;
1787 let lrows = 32usize >> ss_y;
1788 let ay = (((mi_row << 1) >> ss_y) + tx_row) % lrows;
1789 // libvpx reads the context as !!*(uintN_t *)a / l over the WHOLE
1790 // tx-block span (uint16 for 8x8, uint32 for 16x16, uint64 for
1791 // 32x32), not just the first entry.
1792 let nblocks = 1usize << tx_size;
1793 let ctx_in = usize::from(ectx[plane].above[ax..ax + nblocks].iter().any(|&v| v != 0))
1794 + usize::from(ectx[plane].left[ay..ay + nblocks].iter().any(|&v| v != 0));
1795 if crate::trace_enabled() {
1796 eprintln!(
1797 "CTX p={} prob={:?} ax={} ay={} a={} l={} ctx={}",
1798 plane,
1799 self.ctx.coef[tx_size][ptype][0][0][ctx_in],
1800 ax,
1801 ay,
1802 ectx[plane].above[ax],
1803 ectx[plane].left[ay],
1804 ctx_in
1805 );
1806 }
1807 if crate::trace_enabled() {
1808 eprintln!(
1809 "TXB p={} x={} y={} tx={} a={} l={} deq={},{}",
1810 plane,
1811 x0,
1812 y0,
1813 tx_size,
1814 ectx[plane].above[ax],
1815 ectx[plane].left[ay],
1816 dequant[0],
1817 dequant[1]
1818 );
1819 }
1820 let coef = decode_coefs(
1821 r,
1822 ptype,
1823 tx_size,
1824 &dequant,
1825 ctx_in,
1826 scan,
1827 nb,
1828 &self.ctx.coef[tx_size],
1829 false,
1830 bd,
1831 (x0, y0),
1832 plane,
1833 );
1834
1835 // 3. Context write-back (vp9_decode_block_tokens, v1.15 shifts).
1836 let n4w = bw * 2 >> ss_x;
1837 let n4h = bh * 2 >> ss_y;
1838 let maxw = (n4w as i32 + (mb_to_right.min(0) >> (5 + ss_x))).max(0) as usize;
1839 let maxh = (n4h as i32 + (mb_to_bottom.min(0) >> (5 + ss_y))).max(0) as usize;
1840 let nblocks = 1usize << tx_size;
1841 let shift_a = if maxw > 0 && nblocks + tx_col > maxw {
1842 (nblocks - (maxw - tx_col)) * 8
1843 } else {
1844 0
1845 };
1846 let shift_l = if maxh > 0 && nblocks + tx_row > maxh {
1847 (nblocks - (maxh - tx_row)) * 8
1848 } else {
1849 0
1850 };
1851 write_tx_context(ectx, plane, tx_size, ax, ay, coef.eob > 0, shift_a, shift_l);
1852 if crate::tokdbg_enabled() {
1853 eprintln!(
1854 "TDW row={mi_row} col={mi_col} plane={plane} brow={tx_row} bcol={tx_col} tx={tx_size} eob={} sa={} sl={} aw={:?} lw={:?} intra=1",
1855 coef.eob,
1856 shift_a,
1857 shift_l,
1858 &ectx[plane].above[ax..ax + nblocks],
1859 &ectx[plane].left[ay..ay + nblocks],
1860 );
1861 }
1862
1863 // 4. Residual add.
1864 if coef.eob > 0 {
1865 let dst_off = y0 * stride + x0;
1866 let (data, _) = planes.plane(plane);
1867 let probe = crate::trace_enabled()
1868 && plane == 0
1869 && std::env::var("EC_VP9_PROBE_TU")
1870 .ok()
1871 .and_then(|s| {
1872 let mut it = s.split(',');
1873 Some((it.next()?.parse::<usize>().ok()?, it.next()?.parse().ok()?))
1874 })
1875 .is_some_and(|(px, py)| x0 == px && y0 == py);
1876 let t: Option<Vec<Vec<Sample>>> = if probe {
1877 Some(
1878 (0..4usize)
1879 .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec())
1880 .collect(),
1881 )
1882 } else {
1883 None
1884 };
1885 inverse_transform_add(
1886 tx_size,
1887 tx_type,
1888 &coef.coeffs,
1889 data,
1890 dst_off,
1891 stride,
1892 lossless,
1893 bd,
1894 );
1895 if let Some(before) = t {
1896 let after: Vec<Vec<Sample>> = (0..4usize)
1897 .map(|rr| data[dst_off + rr * stride..dst_off + rr * stride + 4].to_vec())
1898 .collect();
1899 eprintln!("RC x0={x0} y0={y0} tx={tx_size} mode={mode}");
1900 for rr in 0..4 {
1901 eprintln!(" pred{rr}={:?} after{rr}={:?}", before[rr], after[rr]);
1902 }
1903 }
1904 }
1905 Ok(())
1906 }
1907}
1908
1909impl Default for Decoder {
1910 fn default() -> Self {
1911 Self::new()
1912 }
1913}
1914
1915/// `BLOCK_SIZE` from `log2(4x4s per side)`.
1916fn bsize_of_n4(n4: usize) -> usize {
1917 match n4 {
1918 4 => 12, // BLOCK_64X64
1919 3 => 9, // BLOCK_32X32
1920 2 => 6, // BLOCK_16X16
1921 1 => 3, // BLOCK_8X8
1922 _ => 0, // BLOCK_4X4 (recursion never reaches n4 == 0)
1923 }
1924}
1925
1926/// Crop an aligned plane set to a displayable [`Picture`]: rows are packed to
1927/// the visible width, so `stride` describes the RETURNED buffers, not the
1928/// aligned decode buffer.
1929fn crop_picture(planes: &Planes, width: u16, height: u16) -> Picture {
1930 let (w, h) = (width as usize, height as usize);
1931 let crop = |src: &[Sample], stride: usize, cw: usize, ch: usize| -> Vec<Sample> {
1932 let mut out = Vec::with_capacity(cw * ch);
1933 for row in 0..ch {
1934 out.extend_from_slice(&src[row * stride..row * stride + cw]);
1935 }
1936 out
1937 };
1938 // Chroma CEILS: a subsampled plane of an odd extent carries one extra
1939 // half-sample column/row (`uv_crop_width = (w + ss_x) >> ss_x`). Under
1940 // 4:4:4 the chroma plane is the full luma extent.
1941 let (sx, sy) = (planes.ss_x, planes.ss_y);
1942 let (cw, chh) = ((w + sx) >> sx, (h + sy) >> sy);
1943 Picture {
1944 y: crop(&planes.y, planes.ys, w, h),
1945 u: crop(&planes.u, planes.uvs, cw, chh),
1946 v: crop(&planes.v, planes.uvs, cw, chh),
1947 width,
1948 height,
1949 stride: w,
1950 uv_stride: cw,
1951 bit_depth: planes.bd,
1952 subsampling_x: sx as u8,
1953 subsampling_y: sy as u8,
1954 }
1955}
1956
1957/// `(ss_x, ss_y)` of a plane: luma is always full-resolution.
1958#[inline]
1959fn plane_ss(hdr: &FrameHeader, plane: usize) -> (usize, usize) {
1960 if plane == 0 {
1961 (0, 0)
1962 } else {
1963 (hdr.subsampling_x as usize, hdr.subsampling_y as usize)
1964 }
1965}
1966
1967/// `pd->n4_w` (`set_plane_n4`, decodeframe.c:809): the plane block's width in
1968/// its own 4x4 units, `(bw << 1) >> ss_x`. Sub-8x8 shapes occupy a whole 8x8
1969/// mi cell (`set_plane_n4(xd, bw=1, bh=1)`), so luma walks 2x2 and chroma
1970/// `(2 >> ss_x)` wide.
1971fn plane_n4_w(bw: usize, ss_x: usize) -> usize {
1972 (bw << 1) >> ss_x
1973}
1974
1975/// `pd->n4_h`, the height twin of [`plane_n4_w`].
1976fn plane_n4_h(bh: usize, ss_y: usize) -> usize {
1977 (bh << 1) >> ss_y
1978}
1979
1980/// `dec_reset_skip_context` (`vp9_decodeframe.c:800`).
1981#[allow(clippy::too_many_arguments)]
1982fn reset_skip_context(
1983 ectx: &mut [PlaneContexts; 3],
1984 row: usize,
1985 col: usize,
1986 sb_type: usize,
1987 n4w: [usize; 3],
1988 n4h: [usize; 3],
1989 ss_x: usize,
1990 ss_y: usize,
1991) {
1992 let _ = sb_type;
1993 for plane in 0..3usize {
1994 let (sx, sy) = if plane == 0 { (0, 0) } else { (ss_x, ss_y) };
1995 let offx = (col << 1) >> sx;
1996 let offy = (row << 1) >> sy;
1997 for i in 0..n4w[plane] {
1998 ectx[plane].above[offx + i] = 0;
1999 }
2000 let lrows = 32usize >> sy;
2001 for i in 0..n4h[plane].min(lrows) {
2002 ectx[plane].left[(offy + i) % lrows] = 0;
2003 }
2004 }
2005 if crate::tokdbg_enabled() {
2006 // Mirror the oracle's `SKIPCTX` print: the CLEARED window, indexed from
2007 // the reset offset (libvpx's `left_context` is already offset to the
2008 // block), not the whole rolling buffer from base index 0.
2009 let mut line = format!("TDK row={row} col={col} n4w={n4w:?} n4h={n4h:?}");
2010 for plane in 0..3usize {
2011 let (sx, sy) = if plane == 0 { (0, 0) } else { (ss_x, ss_y) };
2012 let offx = (col << 1) >> sx;
2013 let offy = (row << 1) >> sy;
2014 let lrows = 32usize >> sy;
2015 let a: Vec<u8> = (0..n4w[plane])
2016 .map(|i| ectx[plane].above[offx + i])
2017 .collect();
2018 let l: Vec<u8> = (0..n4h[plane].min(lrows))
2019 .map(|i| ectx[plane].left[(offy + i) % lrows])
2020 .collect();
2021 line.push_str(&format!(" p{plane} a={a:?} l={l:?}"));
2022 }
2023 eprintln!("{line}");
2024 }
2025}
2026
2027/// The entropy-context write-back of one transform block
2028/// (`vp9_decode_block_tokens`, `vp9_detokenize.c:273-323`): the block's
2029/// `eob` spreads over its `1 << tx_size` 4x4 slots, and `shift_a`/`shift_l`
2030/// (the `get_ctx_shift` frame-edge rule) zero the slots past the frame edge.
2031///
2032/// libvpx applies the shift to a value whose WIDTH IS THE WINDOW'S — a
2033/// `(uint16_t)` for `TX_8X8`, `(uint32_t)` for `TX_16X16`, `(uint64_t)` for
2034/// `TX_32X32` — so the shift zeroes the window's TAIL. Shifting a 64-bit
2035/// spread instead only zeroes bytes past the window and leaves the in-window
2036/// tail set: the last-SB-row chroma blocks then hand a stale 1 to the next
2037/// row's context read (the frame-72 desync).
2038fn write_tx_context(
2039 ectx: &mut [PlaneContexts; 3],
2040 plane: usize,
2041 tx_size: usize,
2042 ax: usize,
2043 ay: usize,
2044 eob: bool,
2045 shift_a: usize,
2046 shift_l: usize,
2047) {
2048 const ONES: u64 = 0x0101_0101_0101_0101;
2049 let nblocks = 1usize << tx_size;
2050 let eob_pos = u64::from(eob);
2051 // Narrow to the window first (libvpx's cast), then apply the edge shift;
2052 // the clamp keeps a fully-outside window (libvpx: undefined shift) total.
2053 let narrow = 64 - 8 * nblocks;
2054 let spread_a = ((eob_pos * ONES) >> narrow) >> shift_a.min(8 * nblocks);
2055 let spread_l = ((eob_pos * ONES) >> narrow) >> shift_l.min(8 * nblocks);
2056 for k in 0..nblocks {
2057 ectx[plane].above[ax + k] = (spread_a >> (8 * k)) as u8;
2058 ectx[plane].left[ay + k] = (spread_l >> (8 * k)) as u8;
2059 }
2060}
2061
2062/// `mode_lf_lut` (`vp9/common/vp9_loopfilter.c:223`):
2063/// `{0 × INTRA_MODES, 1, 1, 0, 1}` — NEARESTMV, NEARMV and NEWMV take the
2064/// inter mode delta, ZEROMV does not, and intra modes never do.
2065fn mode_lf_lut(mode: u8) -> usize {
2066 match mode {
2067 10 | 11 | 13 => 1,
2068 _ => 0,
2069 }
2070}
2071
2072/// One inter transform block's tokens plus the context write-back
2073/// (`vp9_decode_block_tokens`, `decodeframe.c:414`). Inter blocks always use
2074/// the DEFAULT scan and `DCT_DCT`.
2075#[allow(clippy::too_many_arguments)]
2076fn decode_inter_tx_tokens(
2077 r: &mut crate::bool::BoolDecoder,
2078 ectx: &mut [PlaneContexts; 3],
2079 hdr: &FrameHeader,
2080 info: &MiInfo,
2081 fc: &FrameContext,
2082 plane: usize,
2083 row: usize,
2084 col: usize,
2085 brow: usize,
2086 bcol: usize,
2087 tx_size: usize,
2088 sb_type: usize,
2089 bw: usize,
2090 bh: usize,
2091 mb_to_right: i32,
2092 mb_to_bottom: i32,
2093) -> crate::tokens::CoeffBlock {
2094 let (ss_x, ss_y) = plane_ss(hdr, plane);
2095 // `predict_and_reconstruct_intra_block` (decodeframe.c:320-345): the luma
2096 // mode of a sub-8x8 block is the SUB-BLOCK's, and an intra block inside an
2097 // inter frame picks its tx type from that mode — `reconstruct_inter_block`
2098 // hard-codes DCT_DCT instead, which is why the inter guard is here.
2099 let tx_type = if plane != 0 || hdr.quantization.lossless() || info.is_inter {
2100 DCT_DCT
2101 } else {
2102 let mode = if sb_type < 3 {
2103 info.bmi[(brow << 1) + bcol]
2104 } else {
2105 info.mode
2106 };
2107 MODE_TO_TXTYPE_LOOKUP[mode as usize] as usize
2108 };
2109 let (scan, nb) = scan_for(tx_size, tx_type);
2110 let q = hdr.segment_dequant(info.segment as usize);
2111 let dequant: [i16; 2] = if plane == 0 {
2112 [q.luma_dc, q.luma_ac]
2113 } else {
2114 [q.chroma_dc, q.chroma_ac]
2115 };
2116 let ptype = usize::from(plane != 0);
2117 let ax = ((col << 1) >> ss_x) + bcol;
2118 let lrows = 32usize >> ss_y;
2119 let ay = (((row << 1) >> ss_y) + brow) % lrows;
2120 let nblocks = 1usize << tx_size;
2121 let ctx_in = usize::from(ectx[plane].above[ax..ax + nblocks].iter().any(|&v| v != 0))
2122 + usize::from(ectx[plane].left[ay..ay + nblocks].iter().any(|&v| v != 0));
2123 if crate::tokdbg_enabled() {
2124 eprintln!(
2125 "TDB row={row} col={col} plane={plane} brow={brow} bcol={bcol} tx={tx_size} sbt={sb_type} ptype={ptype} inter={} mode={} tt={tx_type} ax={ax} ay={ay} cin={ctx_in} a={:?} l={:?}",
2126 u8::from(info.is_inter),
2127 info.mode,
2128 &ectx[plane].above[ax..ax + nblocks],
2129 &ectx[plane].left[ay..ay + nblocks],
2130 );
2131 }
2132 let coef = decode_coefs(
2133 r,
2134 ptype,
2135 tx_size,
2136 &dequant,
2137 ctx_in,
2138 scan,
2139 nb,
2140 &fc.coef[tx_size],
2141 info.is_inter,
2142 hdr.bit_depth,
2143 (0, 0),
2144 plane,
2145 );
2146 // vp9_decode_block_tokens context write-back (v1.15 edge shifts).
2147 let n4w_s = bw * 2 >> ss_x;
2148 let n4h_s = bh * 2 >> ss_y;
2149 let maxw = (n4w_s as i32 + (mb_to_right.min(0) >> (5 + ss_x))).max(0) as usize;
2150 let maxh = (n4h_s as i32 + (mb_to_bottom.min(0) >> (5 + ss_y))).max(0) as usize;
2151 let shift_a = if maxw > 0 && nblocks + bcol > maxw {
2152 (nblocks - (maxw - bcol)) * 8
2153 } else {
2154 0
2155 };
2156 let shift_l = if maxh > 0 && nblocks + brow > maxh {
2157 (nblocks - (maxh - brow)) * 8
2158 } else {
2159 0
2160 };
2161 write_tx_context(ectx, plane, tx_size, ax, ay, coef.eob > 0, shift_a, shift_l);
2162 if crate::tokdbg_enabled() {
2163 eprintln!(
2164 "TDW row={row} col={col} plane={plane} brow={brow} bcol={bcol} tx={tx_size} eob={} sa={} sl={} aw={:?} lw={:?}",
2165 coef.eob,
2166 shift_a,
2167 shift_l,
2168 &ectx[plane].above[ax..ax + nblocks],
2169 &ectx[plane].left[ay..ay + nblocks],
2170 );
2171 }
2172 coef
2173}
2174
2175/// `dec_build_inter_predictors_sb` (`vp9_decodeframe.c:731`) for one plane:
2176/// every reference's prediction for one block, in reference order (compound
2177/// blocks average the second into the first).
2178#[allow(clippy::too_many_arguments)]
2179fn inter_predict_plane(
2180 planes: &mut Planes,
2181 refs: &[Option<RefFrame>; 8],
2182 scratch: &mut Vec<Sample>,
2183 temp: &mut Vec<Sample>,
2184 hdr: &FrameHeader,
2185 info: &MiInfo,
2186 plane: usize,
2187 row: usize,
2188 col: usize,
2189 n4w: &[usize; 3],
2190 n4h: &[usize; 3],
2191 mb_to_right: i32,
2192 mb_to_bottom: i32,
2193 sb_type: usize,
2194) -> Result<()> {
2195 let (ss_x, ss_y) = plane_ss(hdr, plane);
2196 let pw = n4w[plane] * 4;
2197 let ph = n4h[plane] * 4;
2198 let mb_left = -((col as i32) * 64);
2199 let mb_top = -((row as i32) * 64);
2200 let is_compound = info.ref_frame[1] > crate::inter::INTRA_FRAME;
2201 let refs_used = 1 + usize::from(is_compound);
2202 let kernel = usize::from(info.interp_filter);
2203 let dst_stride = planes.dims(plane).0;
2204 for rf in 0..refs_used {
2205 let ref_name = info.ref_frame[rf];
2206 let slot = hdr.ref_frame_idx[(ref_name - 1) as usize] as usize;
2207 let Some(ref_frame) = refs[slot].as_ref() else {
2208 return Err(corrupt("vp9 inter prediction read an empty reference slot"));
2209 };
2210 let (ref_data, ref_stride) = ref_frame.planes.plane_ref(plane);
2211 // `vp9_setup_scale_factors_for_frame` (`vp9_decodeframe.c:2758`): the
2212 // scale from the REFERENCE's coded luma size to this frame's, shared
2213 // by every plane. `vp9_is_valid_scale` is enforced where libvpx
2214 // enforces it — at prediction time, for the references actually used.
2215 let sf = ScaleFactors::setup(
2216 ref_frame.width as usize,
2217 ref_frame.height as usize,
2218 hdr.width as usize,
2219 hdr.height as usize,
2220 );
2221 if !sf.is_valid() {
2222 return Err(Error::unsupported(
2223 "vp9 reference scale",
2224 format!(
2225 "reference `{ref_name}` in slot {slot} is {}x{} against a {}x{} frame; \
2226 `valid_ref_frame_size` rejects that ratio",
2227 ref_frame.width, ref_frame.height, hdr.width, hdr.height
2228 ),
2229 ));
2230 }
2231 let refp = RefPlane {
2232 data: ref_data,
2233 stride: ref_stride,
2234 // `y_crop_width` / `uv_crop_width`: luma is the coded size, chroma
2235 // CEILS (`(w + 1) / 2`). libvpx stores `uv_crop_width` as
2236 // `(y_crop_width + 1) >> 1` (`vpx_scale/yv12config.c`), so a
2237 // plain `>> 1` is one short whenever the coded extent is odd and
2238 // the predictor's border/inside test then clips the last chroma
2239 // column (or row).
2240 width: (ref_frame.width as usize + ss_x) >> ss_x,
2241 height: (ref_frame.height as usize + ss_y) >> ss_y,
2242 bd: ref_frame.planes.bd,
2243 };
2244 if sb_type < 3 {
2245 // libvpx builds one 4x4 prediction per sub-block, with the MV from
2246 // `average_split_mvs` selected by subsampling: luma and 4:4:4
2247 // chroma take the sub-block's own MV, 4:4:0 averages the vertical
2248 // pair, 4:2:2 the horizontal pair, 4:2:0 all four (q4).
2249 let n4x = n4w[plane];
2250 let n4y = n4h[plane];
2251 for y in 0..n4y {
2252 for xx in 0..n4x {
2253 let i = y * n4x + xx;
2254 let mv = average_split_mvs(&info.bmi_mv, rf, i, ss_x, ss_y);
2255 let (data, _) = planes.plane(plane);
2256 let dst_off =
2257 (((row * 8) >> ss_y) + y * 4) * dst_stride + ((col * 8) >> ss_x) + xx * 4;
2258 build_inter_predictors(
2259 &mut data[dst_off..],
2260 dst_stride,
2261 &refp,
2262 col,
2263 row,
2264 xx * 4,
2265 y * 4,
2266 4,
2267 4,
2268 mv,
2269 mb_left,
2270 mb_to_right,
2271 mb_top,
2272 mb_to_bottom,
2273 ss_x,
2274 ss_y,
2275 kernel,
2276 rf == 1,
2277 &sf,
2278 scratch,
2279 temp,
2280 );
2281 }
2282 }
2283 } else {
2284 let (data, _) = planes.plane(plane);
2285 let dst_off = ((row * 8) >> ss_y) * dst_stride + ((col * 8) >> ss_x);
2286 build_inter_predictors(
2287 &mut data[dst_off..],
2288 dst_stride,
2289 &refp,
2290 col,
2291 row,
2292 0,
2293 0,
2294 pw,
2295 ph,
2296 info.mv[rf],
2297 mb_left,
2298 mb_to_right,
2299 mb_top,
2300 mb_to_bottom,
2301 ss_x,
2302 ss_y,
2303 kernel,
2304 rf == 1,
2305 &sf,
2306 scratch,
2307 temp,
2308 );
2309 }
2310 }
2311 Ok(())
2312}
2313
2314/// `read_interp_filter` (`vp9_decodeframe.c:1482`): the header's filter is a
2315/// literal index through `literal_to_filter[] = {EIGHTTAP_SMOOTH, EIGHTTAP,
2316/// EIGHTTAP_SHARP, BILINEAR}` — the spec's literal order is NOT libvpx's
2317/// filter numbering (`#define EIGHTTAP 0`, `EIGHTTAP_SMOOTH 1`,
2318/// `EIGHTTAP_SHARP 2`, `BILINEAR 3`), and `vp9_filter_kernels` (the kernel
2319/// table) is indexed by the latter. A switchable frame stores SWITCHABLE (4)
2320/// and picks per block, where the tree's leaves already use libvpx numbering.
2321fn interp_filter_of(hdr: &FrameHeader) -> u8 {
2322 const LITERAL_TO_FILTER: [u8; 4] = [1, 0, 2, 3];
2323 let v = hdr.interpolation_filter as u8;
2324 if v == crate::inter::SWITCHABLE {
2325 v
2326 } else {
2327 LITERAL_TO_FILTER[v as usize]
2328 }
2329}