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