forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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