forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBcdccbc2Tahinli10 hours ago4263 commits

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