forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcd996f4Tahinli3 months ago51 commits

decoder.rs2281 lines, 81.2 KiBHistoryRawDownload
1//! Decoder core: parameter-set store, decoded picture buffer, macroblock
2//! decode loop, reconstruction and the in-loop filter driver.
3//!
4//! Layout choices (perf-first):
5//! - Planes are padded (`PAD_Y`/`PAD_C` samples each side) and their borders
6//! replicated once per picture, so neighbour gathers and inter-prediction
7//! overreach never bounds-check per sample and edge availability is data,
8//! not arithmetic.
9//! - All per-macroblock and per-4x4-block state lives in flat struct-of-arrays
10//! keyed by macroblock address or block coordinate: coefficient counts, intra
11//! modes, QP, flags, owning slice, motion vectors, reference identities. No
12//! per-macroblock heap objects anywhere.
13//! - Pictures are pooled by the [`Dpb`], so a steady-state decode loop reuses
14//! every buffer and performs zero allocations.
15//!
16//! Output is in display order: pictures leave the decoded picture buffer by the
17//! bumping process, smallest picture order count first, which is the order a
18//! player presents them in. [`OutputOrder::Decode`] switches that off for a
19//! caller that wants pictures as they are decoded.
20
21use std::collections::VecDeque;
22
23use ec_core::BitReader;
24use ec_core::error::{Error, Result};
25use ec_core::frame::{PixelFormat, Plane, VideoFrame};
26use ec_core::timebase::Timestamp;
27use ec_h264_syntax::{
28 AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, PredWeightTable, SliceHeader,
29 SliceType, Sps, WeightEntry, unescape_rbsp,
30};
31
32use crate::deblock::{
33 chroma_qp, edge_params, filter_chroma_line, filter_luma_h_edge16, filter_luma_line,
34};
35use crate::dpb::{
36 BLK_DIRECT, BLK_INTRA, BLK_SKIP, Dpb, Mark, NO_SLICE, PicInfo, Picture, Plane8, RefList,
37 SliceParams,
38};
39use crate::entropy::{
40 BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM,
41 FLAG_SKIP, MbCtx, MbInfo,
42};
43use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma};
44use crate::mv::{
45 B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive,
46 neighbour_mvd, predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd,
47};
48use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8};
49use crate::tables::{BLK4_POS, CHROMA_QP};
50use crate::transform::{
51 LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, luma_dc_transform,
52 unzigzag, unzigzag_ac15,
53};
54
55/// Where a 4x4 block's top-right neighbour samples come from, per
56/// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule).
57#[derive(Clone, Copy, PartialEq)]
58enum TrKind {
59 /// Bottom row of an earlier block in this macroblock: always available.
60 InMb,
61 /// The macroblock above.
62 B,
63 /// The macroblock above-right.
64 C,
65 /// Never available (right column, or blkIdx 3/11).
66 None,
67}
68
69const TR_KIND: [TrKind; 16] = [
70 TrKind::B,
71 TrKind::B,
72 TrKind::InMb,
73 TrKind::None,
74 TrKind::B,
75 TrKind::C,
76 TrKind::InMb,
77 TrKind::None,
78 TrKind::InMb,
79 TrKind::InMb,
80 TrKind::InMb,
81 TrKind::None,
82 TrKind::InMb,
83 TrKind::None,
84 TrKind::InMb,
85 TrKind::None,
86];
87
88/// The order [`Decoder`] hands decoded pictures back in.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
90pub enum OutputOrder {
91 /// Display order: pictures leave the decoded picture buffer by the bumping
92 /// process of clause C.4.5.3. This is what a player needs, and the only
93 /// order that is correct for a stream with B pictures.
94 #[default]
95 Display,
96 /// Decode order: each picture is emitted the moment it is complete. Lower
97 /// latency, wrong presentation order whenever the stream reorders.
98 Decode,
99}
100
101/// Streaming H.264 decoder (frame-coded 4:2:0 8-bit; unsupported features come
102/// back as named [`Error::Unsupported`] values, never wrong pixels).
103pub struct Decoder {
104 sps_map: Vec<Option<Sps>>,
105 pps_map: Vec<Option<Pps>>,
106 rbsp: Vec<u8>,
107 /// The picture being decoded, held out of the buffer pool.
108 cur: Picture,
109 dpb: Dpb,
110 has_picture: bool,
111 /// Scaling factors of the active PPS/SPS, `[intra, inter][Y, Cb, Cr]`.
112 ls: [[LevelScale4x4; 3]; 2],
113 active_pps: Option<u32>,
114 /// `seq_parameter_set_id` of the most recently stored SPS, so a container
115 /// entry path can publish the picture size before the first slice.
116 last_sps: Option<u8>,
117 /// Clause 8.2 view of the open picture, from its first slice header.
118 cur_info: PicInfo,
119 /// `dec_ref_pic_marking( )` of the open picture, kept in place so a
120 /// steady-state loop does not reallocate its MMCO list.
121 cur_marking: DecRefPicMarking,
122 has_marking: bool,
123 /// Identity of the picture `end_picture` completed most recently.
124 last_decoded: i32,
125 output_order: OutputOrder,
126 out: VecDeque<VideoFrame>,
127 /// Presentation timestamp to attach to the next picture started.
128 pending_pts: Option<Timestamp>,
129}
130
131/// What [`Decoder::push_nal`] did with a NAL unit.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub enum NalOutcome {
134 /// SPS or PPS stored.
135 ParameterSet,
136 /// Non-VCL NAL skipped (SEI, AUD, filler, ...).
137 Skipped,
138 /// A slice was decoded into the open picture.
139 SliceDecoded,
140 /// The NAL starts a new picture while one is open; it was not consumed.
141 /// Call [`Decoder::end_picture`], then push it again.
142 PictureBoundary,
143}
144
145impl Default for Decoder {
146 fn default() -> Self {
147 Decoder::new()
148 }
149}
150
151fn flat_scaling() -> [[LevelScale4x4; 3]; 2] {
152 [
153 [
154 LevelScale4x4::new(&[16; 16]),
155 LevelScale4x4::new(&[16; 16]),
156 LevelScale4x4::new(&[16; 16]),
157 ],
158 [
159 LevelScale4x4::new(&[16; 16]),
160 LevelScale4x4::new(&[16; 16]),
161 LevelScale4x4::new(&[16; 16]),
162 ],
163 ]
164}
165
166impl Decoder {
167 /// A fresh decoder with no parameter sets.
168 pub fn new() -> Decoder {
169 Decoder {
170 sps_map: vec![None; 32],
171 pps_map: vec![None; 256],
172 rbsp: Vec::new(),
173 cur: Picture::default(),
174 dpb: Dpb::default(),
175 has_picture: false,
176 ls: flat_scaling(),
177 active_pps: None,
178 last_sps: None,
179 cur_info: PicInfo {
180 is_idr: false,
181 is_reference: false,
182 frame_num: 0,
183 pic_order_cnt_lsb: 0,
184 delta_pic_order_cnt_bottom: 0,
185 delta_pic_order_cnt: [0; 2],
186 },
187 cur_marking: DecRefPicMarking::default(),
188 has_marking: false,
189 last_decoded: -1,
190 output_order: OutputOrder::default(),
191 out: VecDeque::new(),
192 pending_pts: None,
193 }
194 }
195
196 /// Choose between display order (the default) and decode order.
197 pub fn set_output_order(&mut self, order: OutputOrder) {
198 self.output_order = order;
199 }
200
201 /// The order pictures are handed back in.
202 pub fn output_order(&self) -> OutputOrder {
203 self.output_order
204 }
205
206 /// Attach `pts` to the next picture started, so a presentation timestamp
207 /// follows its picture through reordering instead of staying with the
208 /// packet that carried it.
209 pub fn set_next_pts(&mut self, pts: Option<Timestamp>) {
210 self.pending_pts = pts;
211 }
212
213 /// Cropped picture size of the most recently stored SPS, `None` until one
214 /// arrives. Lets a container entry path fill in stream parameters from an
215 /// `avcC` record without decoding a picture first.
216 pub fn picture_size(&self) -> Option<(u32, u32)> {
217 let sps = self.sps_map[self.last_sps? as usize].as_ref()?;
218 Some((sps.width, sps.height))
219 }
220
221 /// Decode the first IDR picture of an Annex B stream and return it.
222 pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> {
223 let mut got_slice = false;
224 for nal in AnnexBIter::new(annexb) {
225 match self.push_nal(nal)? {
226 NalOutcome::PictureBoundary => break,
227 NalOutcome::SliceDecoded => got_slice = true,
228 _ => {}
229 }
230 }
231 if !got_slice {
232 return Err(Error::NeedMore);
233 }
234 self.end_picture()?;
235 self.frame()
236 }
237
238 /// Feed one NAL unit (header byte first, no start code).
239 pub fn push_nal(&mut self, nal: &[u8]) -> Result<NalOutcome> {
240 let Some((&header_byte, payload)) = nal.split_first() else {
241 return Err(Error::NeedMore);
242 };
243 let header = NalHeader::parse(header_byte)?;
244 match header.unit_type {
245 NalUnitType::Sps => {
246 let mut rbsp = core::mem::take(&mut self.rbsp);
247 unescape_rbsp(payload, &mut rbsp);
248 let sps = Sps::parse(&rbsp);
249 self.rbsp = rbsp;
250 let sps = sps?;
251 let id = sps.id;
252 self.dpb.configure(&sps);
253 self.sps_map[id as usize] = Some(sps);
254 self.last_sps = Some(id);
255 Ok(NalOutcome::ParameterSet)
256 }
257 NalUnitType::Pps => {
258 let mut rbsp = core::mem::take(&mut self.rbsp);
259 unescape_rbsp(payload, &mut rbsp);
260 let pps = Pps::parse(&rbsp, |id| self.sps_map[id as usize].as_ref());
261 self.rbsp = rbsp;
262 let pps = pps?;
263 let id = pps.id as usize;
264 self.pps_map[id] = Some(pps);
265 Ok(NalOutcome::ParameterSet)
266 }
267 NalUnitType::Slice | NalUnitType::SliceIdr => {
268 let mut rbsp = core::mem::take(&mut self.rbsp);
269 unescape_rbsp(payload, &mut rbsp);
270 let r = self.decode_slice_rbsp(header, &rbsp);
271 self.rbsp = rbsp;
272 r
273 }
274 NalUnitType::SliceDataA | NalUnitType::SliceDataB | NalUnitType::SliceDataC => {
275 Err(Error::unsupported(
276 "slice data partitioning",
277 "nal_unit_type 2 to 4 carry a slice in three NAL units that \
278 clause 7.4.1 reassembles by slice_id; not implemented",
279 ))
280 }
281 _ => Ok(NalOutcome::Skipped),
282 }
283 }
284
285 /// Run the deblocking filter over the open picture, store it in the decoded
286 /// picture buffer and queue whatever pictures that makes ready for output.
287 pub fn end_picture(&mut self) -> Result<()> {
288 if !self.has_picture || self.cur.complete {
289 return Err(Error::corrupt("end_picture without an open picture"));
290 }
291 deblock_picture(&mut self.cur);
292 self.cur.extend_borders();
293 self.cur.complete = true;
294 self.last_decoded = self.cur.id;
295 let sps = self.sps_map[self.cur.sps_id as usize]
296 .as_ref()
297 .ok_or_else(|| Error::corrupt("active SPS vanished"))?
298 .clone();
299 let pic = core::mem::take(&mut self.cur);
300 let marking = self.has_marking.then_some(&self.cur_marking);
301 self.dpb.store(pic, &sps, &self.cur_info, marking)?;
302 self.has_picture = false;
303 self.pump_output(false)
304 }
305
306 /// Emit every remaining picture (end of stream).
307 pub fn flush(&mut self) -> Result<()> {
308 if self.has_picture && !self.cur.complete {
309 self.end_picture()?;
310 }
311 self.pump_output(true)
312 }
313
314 /// The next frame ready for output, in the configured order.
315 pub fn next_frame(&mut self) -> Option<VideoFrame> {
316 self.out.pop_front()
317 }
318
319 /// The picture `end_picture` completed most recently, in decode order.
320 ///
321 /// Kept for a caller that drives one picture at a time; a player wants
322 /// [`Decoder::next_frame`], which respects the reordering the stream asks
323 /// for.
324 pub fn frame(&self) -> Result<VideoFrame> {
325 let id = self.last_decoded;
326 let pic = self
327 .dpb
328 .frames
329 .iter()
330 .find(|p| p.id == id)
331 .ok_or_else(|| Error::corrupt("frame() before end_picture()"))?;
332 self.picture_to_frame(pic)
333 }
334
335 /// True while a picture is open (started, not completed).
336 pub fn picture_open(&self) -> bool {
337 self.has_picture && !self.cur.complete
338 }
339
340 /// Drop picture state after a seek. Parameter sets survive, because the
341 /// container does not resend them at every seek point.
342 pub fn reset_pictures(&mut self) {
343 self.has_picture = false;
344 self.cur.complete = false;
345 self.dpb.clear();
346 self.out.clear();
347 self.last_decoded = -1;
348 self.pending_pts = None;
349 }
350
351 /// Move pictures out of the decoded picture buffer into the output queue.
352 fn pump_output(&mut self, flush: bool) -> Result<()> {
353 if self.output_order == OutputOrder::Decode && !flush {
354 let id = self.last_decoded;
355 if let Some(i) = self.dpb.frames.iter().position(|p| p.id == id && p.output) {
356 let frame = self.picture_to_frame(&self.dpb.frames[i])?;
357 self.out.push_back(frame);
358 self.dpb.released(i);
359 }
360 return Ok(());
361 }
362 while let Some(i) = self.dpb.next_output(flush) {
363 let frame = self.picture_to_frame(&self.dpb.frames[i])?;
364 self.out.push_back(frame);
365 self.dpb.released(i);
366 }
367 Ok(())
368 }
369
370 /// Copy a stored picture out as a cropped I420 frame.
371 fn picture_to_frame(&self, pic: &Picture) -> Result<VideoFrame> {
372 let sps = self.sps_map[pic.sps_id as usize]
373 .as_ref()
374 .ok_or_else(|| Error::corrupt("active SPS vanished"))?;
375 let (w, h) = (sps.width as usize, sps.height as usize);
376 let (cx, cy) = (sps.crop.0 as usize, sps.crop.2 as usize);
377 let copy = |p: &Plane8, x0: usize, y0: usize, w: usize, h: usize| -> Plane {
378 let mut out = vec![0u8; w * h];
379 for row in 0..h {
380 let src = p.at(x0, y0 + row);
381 out[row * w..(row + 1) * w].copy_from_slice(&p.data[src..src + w]);
382 }
383 Plane::new(out, w)
384 };
385 let planes = vec![
386 copy(&pic.y, cx, cy, w, h),
387 copy(&pic.cb, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)),
388 copy(&pic.cr, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)),
389 ];
390 let mut frame = VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)?;
391 if let Some(vui) = &sps.vui {
392 frame.color.full_range = vui.video_full_range;
393 if let Some((p, t, m)) = vui.colour_description {
394 frame.color.primaries = p;
395 frame.color.transfer = t;
396 frame.color.matrix = m;
397 }
398 }
399 frame.pts = pic.pts;
400 Ok(frame)
401 }
402
403 fn decode_slice_rbsp(&mut self, header: NalHeader, rbsp: &[u8]) -> Result<NalOutcome> {
404 // Peek first_mb / slice_type / pps_id to select parameter sets.
405 let mut peek = BitReader::new(rbsp);
406 let first_mb = peek.read_ue()?;
407 let slice_type_code = peek.read_ue()?;
408 let pps_id = peek.read_ue()?;
409 if pps_id > 255 {
410 return Err(Error::corrupt("pic_parameter_set_id > 255"));
411 }
412 if self.has_picture && !self.cur.complete && first_mb == 0 && self.cur.decoded_mbs > 0 {
413 return Ok(NalOutcome::PictureBoundary);
414 }
415 let pps = self.pps_map[pps_id as usize]
416 .as_ref()
417 .ok_or_else(|| Error::corrupt("slice refers to an unknown PPS"))?;
418 let sps = self.sps_map[pps.sps_id as usize]
419 .as_ref()
420 .ok_or_else(|| Error::corrupt("PPS refers to an unknown SPS"))?;
421
422 check_supported(sps, pps, slice_type_code)?;
423 let sh = SliceHeader::parse(rbsp, header, sps, pps)?;
424 let sps = sps.clone();
425 let pps = pps.clone();
426
427 if !self.has_picture || self.cur.complete {
428 self.start_picture(&sps, &pps, &sh, header)?;
429 }
430 if self.cur.sps_id != sps.id {
431 return Err(Error::corrupt("SPS changed mid-picture"));
432 }
433 if self.cur.slices.len() >= usize::from(u16::MAX) {
434 return Err(Error::corrupt("more than 65534 slices in a picture"));
435 }
436 let slice_id = self.cur.slices.len() as u16;
437 self.cur.slices.push(SliceParams {
438 disable_deblock_idc: sh.deblock.disable_idc,
439 alpha_offset: sh.deblock.alpha_c0_offset,
440 beta_offset: sh.deblock.beta_offset,
441 cb_qp_offset: pps.chroma_qp_index_offset,
442 cr_qp_offset: pps.second_chroma_qp_index_offset,
443 });
444
445 // Reference picture lists (clause 8.2.4), rebuilt per slice because
446 // num_ref_idx_active and the modification list are slice header state.
447 let max_pic_num = 1i32 << sps.log2_max_frame_num;
448 let lists = if sh.slice_type.is_intra() {
449 [RefList::default(), RefList::default()]
450 } else {
451 self.dpb.number_short_term(sh.frame_num, &sps);
452 self.dpb.build_ref_lists(
453 sh.slice_type,
454 self.cur.poc,
455 sh.frame_num as i32,
456 max_pic_num,
457 sh.num_ref_idx_l0_active as usize,
458 sh.num_ref_idx_l1_active as usize,
459 (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1),
460 )?
461 };
462
463 let mut r = if pps.entropy_coding_mode {
464 let column = if sh.slice_type.is_intra() {
465 0
466 } else {
467 sh.cabac_init_idc as usize + 1
468 };
469 Entropy::cabac(rbsp, sh.header_bits, sh.slice_qp, column)?
470 } else {
471 Entropy::cavlc(rbsp, sh.header_bits)
472 };
473
474 let mut ctx = SliceCtx {
475 slice_id,
476 slice_type: sh.slice_type,
477 qp: sh.slice_qp,
478 cb_qp_offset: pps.chroma_qp_index_offset,
479 cr_qp_offset: pps.second_chroma_qp_index_offset,
480 transform_8x8_mode: pps.transform_8x8_mode,
481 constrained_intra_pred: pps.constrained_intra_pred,
482 qp_delta_inc: 0,
483 lists,
484 num_ref_idx: [
485 sh.num_ref_idx_l0_active as usize,
486 sh.num_ref_idx_l1_active as usize,
487 ],
488 direct_spatial: sh.direct_spatial_mv_pred,
489 direct_8x8_inference: sps.direct_8x8_inference,
490 weighted_pred: pps.weighted_pred,
491 weighted_bipred_idc: pps.weighted_bipred_idc,
492 weights: sh.pred_weight_table.clone(),
493 poc: self.cur.poc,
494 };
495 let intra_slice = sh.slice_type.is_intra();
496 let b_slice = sh.slice_type == SliceType::B;
497 if !intra_slice && ctx.lists[0].len() == 0 {
498 return Err(Error::corrupt("inter slice with no reference pictures"));
499 }
500
501 let mbs = self.cur.mb_w * self.cur.mb_h;
502 let mut mb_addr = first_mb as usize;
503 let mut more = true;
504 while more {
505 if mb_addr >= mbs {
506 return Err(Error::corrupt("macroblock address beyond the picture"));
507 }
508 let mut decode_mb = true;
509 if !intra_slice {
510 if r.is_cabac() {
511 self.begin_mb(&mut r, &ctx, mb_addr);
512 let inc = self.skip_inc(&ctx, mb_addr);
513 if r.mb_skip_flag(b_slice, inc)? {
514 decode_macroblock(
515 &mut self.cur,
516 &self.dpb.frames,
517 &self.ls,
518 &mut r,
519 &mut ctx,
520 mb_addr,
521 true,
522 )?;
523 decode_mb = false;
524 }
525 } else {
526 let run = r.mb_skip_run()?;
527 for _ in 0..run {
528 if mb_addr >= mbs {
529 return Err(Error::corrupt("mb_skip_run past the picture"));
530 }
531 decode_macroblock(
532 &mut self.cur,
533 &self.dpb.frames,
534 &self.ls,
535 &mut r,
536 &mut ctx,
537 mb_addr,
538 true,
539 )?;
540 mb_addr += 1;
541 }
542 if run > 0 {
543 more = r.more_macroblocks()?;
544 if !more {
545 break;
546 }
547 if mb_addr >= mbs {
548 return Err(Error::corrupt("macroblock address beyond the picture"));
549 }
550 }
551 }
552 }
553 if decode_mb {
554 decode_macroblock(
555 &mut self.cur,
556 &self.dpb.frames,
557 &self.ls,
558 &mut r,
559 &mut ctx,
560 mb_addr,
561 false,
562 )?;
563 }
564 more = r.more_macroblocks()?;
565 mb_addr += 1;
566 }
567 Ok(NalOutcome::SliceDecoded)
568 }
569
570 /// Publish the neighbourhood of `mb_addr` to a CABAC reader ahead of
571 /// mb_skip_flag, which is decoded before the macroblock layer.
572 fn begin_mb(&self, r: &mut Entropy<'_>, ctx: &SliceCtx, mb_addr: usize) {
573 let pic = &self.cur;
574 let mb_x = mb_addr % pic.mb_w;
575 let mb_y = mb_addr / pic.mb_w;
576 let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id);
577 let info = |addr: usize| MbInfo {
578 flags: pic.mb_flags[addr],
579 cbp: pic.mb_cbp[addr],
580 dc_cbf: pic.mb_dc_cbf[addr],
581 };
582 r.begin_mb(&MbCtx {
583 a: nbr.a.then(|| info(mb_addr - 1)),
584 b: nbr.b.then(|| info(mb_addr - pic.mb_w)),
585 qp_delta_inc: ctx.qp_delta_inc,
586 });
587 }
588
589 /// ctxIdxInc for mb_skip_flag (9.3.3.1.1.1): a neighbour counts unless it
590 /// is unavailable or was itself skipped.
591 fn skip_inc(&self, ctx: &SliceCtx, mb_addr: usize) -> usize {
592 let pic = &self.cur;
593 let mb_x = mb_addr % pic.mb_w;
594 let mb_y = mb_addr / pic.mb_w;
595 let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id);
596 let cond = |avail: bool, addr: usize| {
597 usize::from(avail && pic.mb_flags[addr] & FLAG_SKIP == 0)
598 };
599 cond(nbr.a, mb_addr.wrapping_sub(1)) + cond(nbr.b, mb_addr.wrapping_sub(pic.mb_w))
600 }
601
602 /// Open a new picture: clause 8.2 bookkeeping, then the geometry reset.
603 fn start_picture(
604 &mut self,
605 sps: &Sps,
606 pps: &Pps,
607 sh: &SliceHeader,
608 header: NalHeader,
609 ) -> Result<()> {
610 let info = PicInfo {
611 is_idr: header.is_idr(),
612 is_reference: header.ref_idc != 0,
613 frame_num: sh.frame_num,
614 pic_order_cnt_lsb: sh.pic_order_cnt_lsb,
615 delta_pic_order_cnt_bottom: sh.delta_pic_order_cnt_bottom,
616 delta_pic_order_cnt: sh.delta_pic_order_cnt,
617 };
618 // A frame_num gap is what a seek or a dropped packet looks like: the
619 // pictures it names never arrive, so clause 8.2.5.2 infers them and
620 // decoding continues rather than stalling until the next IDR.
621 if !info.is_idr && self.dpb.frame_num_gap(sps, sh.frame_num) {
622 if !sps.gaps_in_frame_num_allowed {
623 // Not a conformant gap: pictures were lost. Same repair.
624 self.dpb.fill_frame_num_gap(sps, sh.frame_num)?;
625 } else {
626 self.dpb.fill_frame_num_gap(sps, sh.frame_num)?;
627 }
628 self.pump_output(false)?;
629 }
630 let poc = self.dpb.picture_order_count(sps, &info)?;
631 let mut pic = self.dpb.take_picture();
632 pic.start(sps);
633 pic.poc = poc.value;
634 pic.poc_msb = poc.msb;
635 pic.poc_lsb = poc.lsb;
636 pic.frame_num_offset = poc.frame_num_offset;
637 pic.frame_num = sh.frame_num;
638 pic.pts = self.pending_pts.take();
639 self.cur = pic;
640 self.cur_info = info;
641 self.has_marking = sh.dec_ref_pic_marking.is_some();
642 if let Some(m) = &sh.dec_ref_pic_marking {
643 self.cur_marking.no_output_of_prior_pics = m.no_output_of_prior_pics;
644 self.cur_marking.long_term_reference = m.long_term_reference;
645 self.cur_marking.adaptive = m.adaptive;
646 self.cur_marking.mmcos.clear();
647 self.cur_marking.mmcos.extend_from_slice(&m.mmcos);
648 }
649 self.has_picture = true;
650 if self.active_pps != Some(pps.id) {
651 let lists = pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref());
652 let weights = match lists {
653 Some(l) => [
654 [&l.list_4x4[0], &l.list_4x4[1], &l.list_4x4[2]],
655 [&l.list_4x4[3], &l.list_4x4[4], &l.list_4x4[5]],
656 ],
657 None => [[&[16u8; 16]; 3]; 2],
658 };
659 self.ls = [
660 [
661 LevelScale4x4::new(weights[0][0]),
662 LevelScale4x4::new(weights[0][1]),
663 LevelScale4x4::new(weights[0][2]),
664 ],
665 [
666 LevelScale4x4::new(weights[1][0]),
667 LevelScale4x4::new(weights[1][1]),
668 LevelScale4x4::new(weights[1][2]),
669 ],
670 ];
671 self.active_pps = Some(pps.id);
672 }
673 Ok(())
674 }
675}
676
677/// Reject unsupported streams with named reasons before touching pixels.
678///
679/// Every `why` here names the syntax element that fired and the machinery it
680/// would need: a refusal is a capability statement about this binary, and the
681/// conformance suite proves each one against a stream that really uses the
682/// feature.
683fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> {
684 if pps.num_slice_groups > 1 {
685 return Err(Error::unsupported(
686 "FMO slice groups",
687 "num_slice_groups_minus1 > 0 needs the macroblock-to-slice-group \
688 map of clause 8.2.2; only one slice group per picture is decoded",
689 ));
690 }
691 if sps.chroma_format_idc != 1 {
692 return Err(Error::unsupported(
693 "chroma format",
694 format!(
695 "chroma_format_idc {} needs its own chroma prediction, scan and \
696 DC transform; only 4:2:0 (ChromaArrayType 1) is decoded",
697 sps.chroma_format_idc
698 ),
699 ));
700 }
701 if sps.bit_depth_luma != 8 || sps.bit_depth_chroma != 8 {
702 return Err(Error::unsupported(
703 "bit depth",
704 format!(
705 "{}-bit luma / {}-bit chroma needs 16-bit sample planes and the \
706 widened transform clip of clause 8.5; only 8-bit is decoded",
707 sps.bit_depth_luma, sps.bit_depth_chroma
708 ),
709 ));
710 }
711 if !sps.frame_mbs_only {
712 return Err(Error::unsupported(
713 "interlaced coding",
714 "frame_mbs_only_flag 0 admits field pictures and MBAFF, whose \
715 neighbour derivation (6.4.9) and field deblocking are not implemented",
716 ));
717 }
718 if sps.separate_colour_plane {
719 return Err(Error::unsupported(
720 "separate colour planes",
721 "separate_colour_plane_flag 1 codes 4:4:4 as three monochrome \
722 planes with their own slice headers; not implemented",
723 ));
724 }
725 if sps.transform_bypass {
726 return Err(Error::unsupported(
727 "transform bypass",
728 "qpprime_y_zero_transform_bypass_flag 1 makes QP'Y 0 lossless, \
729 bypassing the transform and scaling of 8.5 entirely; not implemented",
730 ));
731 }
732 if slice_type_code > 9 {
733 return Err(Error::corrupt("slice_type > 9"));
734 }
735 if matches!(slice_type_code % 5, 3 | 4) {
736 return Err(Error::unsupported(
737 "SP and SI slices",
738 "switching slices need the transform-domain reconstruction of \
739 clause 8.5.14 and their own deblocking strengths; not implemented",
740 ));
741 }
742 Ok(())
743}
744
745/// Mutable per-slice decode state.
746struct SliceCtx {
747 slice_id: u16,
748 slice_type: SliceType,
749 qp: i32,
750 cb_qp_offset: i32,
751 cr_qp_offset: i32,
752 transform_8x8_mode: bool,
753 constrained_intra_pred: bool,
754 /// ctxIdxInc for the next macroblock's first mb_qp_delta bin: set when the
755 /// macroblock just decoded coded a non-zero mb_qp_delta (9.3.3.1.1.5).
756 qp_delta_inc: u8,
757 /// `RefPicList0` and `RefPicList1` as decoded picture buffer indices.
758 lists: [RefList; 2],
759 num_ref_idx: [usize; 2],
760 direct_spatial: bool,
761 direct_8x8_inference: bool,
762 weighted_pred: bool,
763 weighted_bipred_idc: u8,
764 weights: Option<PredWeightTable>,
765 /// `PicOrderCnt( CurrPic )`.
766 poc: i32,
767}
768
769impl SliceCtx {
770 fn is_b(&self) -> bool {
771 self.slice_type == SliceType::B
772 }
773
774 /// The reference picture `RefPicListX[idx]` points at.
775 fn reference<'a>(&self, refs: &'a [Picture], list: usize, idx: i8) -> Option<&'a Picture> {
776 if idx < 0 {
777 return None;
778 }
779 refs.get(self.lists[list].get(idx as usize)?)
780 }
781
782 /// Prediction weights of one component (clause 8.4.3).
783 fn weights_for(
784 &self,
785 refs: &[Picture],
786 comp: usize,
787 r0: i8,
788 r1: i8,
789 use0: bool,
790 use1: bool,
791 ) -> Weights {
792 let implicit = self.weighted_bipred_idc == 2 && self.is_b() && use0 && use1;
793 let explicit = (self.weighted_bipred_idc == 1 && self.is_b())
794 || (self.weighted_pred && !self.is_b());
795 if implicit {
796 let (Some(p0), Some(p1)) = (
797 self.reference(refs, 0, r0),
798 self.reference(refs, 1, r1),
799 ) else {
800 return Weights::DEFAULT;
801 };
802 let td = (p1.poc - p0.poc).clamp(-128, 127);
803 let long_term = p0.mark == Mark::Long || p1.mark == Mark::Long;
804 if td == 0 || long_term {
805 return Weights {
806 log_wd: 5,
807 w: [32, 32],
808 o: [0, 0],
809 };
810 }
811 let tb = (self.poc - p0.poc).clamp(-128, 127);
812 let tx = (16384 + (td / 2).abs()) / td;
813 let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023);
814 let w1 = dist >> 2;
815 if !(-64..=128).contains(&w1) {
816 return Weights {
817 log_wd: 5,
818 w: [32, 32],
819 o: [0, 0],
820 };
821 }
822 return Weights {
823 log_wd: 5,
824 w: [64 - w1, w1],
825 o: [0, 0],
826 };
827 }
828 if !explicit {
829 return Weights::DEFAULT;
830 }
831 let Some(t) = &self.weights else {
832 return Weights::DEFAULT;
833 };
834 let denom = if comp == 0 {
835 t.luma_log2_weight_denom
836 } else {
837 t.chroma_log2_weight_denom
838 } as i32;
839 let pick = |list: &[WeightEntry], idx: i8| -> (i32, i32) {
840 let default = (1 << denom, 0);
841 if idx < 0 {
842 return default;
843 }
844 match list.get(idx as usize) {
845 None => default,
846 Some(e) if comp == 0 => e.luma.unwrap_or(default),
847 Some(e) => e.chroma.map(|c| c[comp - 1]).unwrap_or(default),
848 }
849 };
850 let (w0, o0) = pick(&t.l0, r0);
851 let (w1, o1) = pick(&t.l1, r1);
852 Weights {
853 log_wd: denom,
854 w: [w0, w1],
855 o: [o0, o1],
856 }
857 }
858}
859
860/// Neighbour-availability snapshot for one macroblock (left, top, top-right).
861#[derive(Clone, Copy)]
862struct MbNeighbors {
863 a: bool,
864 b: bool,
865 c: bool,
866}
867
868fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNeighbors {
869 let w = pic.mb_w;
870 let addr = mb_y * w + mb_x;
871 let same = |a: usize| pic.mb_slice[a] == slice_id;
872 MbNeighbors {
873 a: mb_x > 0 && same(addr - 1),
874 b: mb_y > 0 && same(addr - w),
875 c: mb_y > 0 && mb_x + 1 < w && same(addr - w + 1),
876 }
877}
878
879/// The same, with the constrained intra prediction rule of 7.4.2.2 applied:
880/// an inter-coded neighbour is not available as an intra prediction source.
881fn intra_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, n: MbNeighbors) -> MbNeighbors {
882 let w = pic.mb_w;
883 let addr = mb_y * w + mb_x;
884 let intra = |a: usize| pic.mb_flags[a] & FLAG_INTER == 0;
885 MbNeighbors {
886 a: n.a && intra(addr - 1),
887 b: n.b && intra(addr - w),
888 c: n.c && intra(addr - w + 1),
889 }
890}
891
892/// Non-zero counts of the left and above neighbours of the luma 4x4 block at
893/// global block coords `(bx, by)`, `None` when that neighbour is unavailable
894/// (clause 6.4.11.4 plus the availability rules of 6.4.8).
895#[inline]
896fn luma_nz_pair(pic: &Picture, n: &MbNeighbors, bx: usize, by: usize) -> (Option<u8>, Option<u8>) {
897 let w4 = pic.mb_w * 4;
898 let left_avail = if bx.is_multiple_of(4) { n.a } else { true };
899 let top_avail = if by.is_multiple_of(4) { n.b } else { true };
900 (
901 (left_avail && bx > 0).then(|| pic.nz_y[by * w4 + bx - 1]),
902 (top_avail && by > 0).then(|| pic.nz_y[(by - 1) * w4 + bx]),
903 )
904}
905
906/// The same for a chroma AC 4x4 block at global chroma block coords.
907#[inline]
908fn chroma_nz_pair(
909 pic: &Picture,
910 n: &MbNeighbors,
911 comp: usize,
912 cx: usize,
913 cy: usize,
914) -> (Option<u8>, Option<u8>) {
915 let w2 = pic.mb_w * 2;
916 let grid = &pic.nz_c[comp];
917 let left_avail = if cx.is_multiple_of(2) { n.a } else { true };
918 let top_avail = if cy.is_multiple_of(2) { n.b } else { true };
919 (
920 (left_avail && cx > 0).then(|| grid[cy * w2 + cx - 1]),
921 (top_avail && cy > 0).then(|| grid[(cy - 1) * w2 + cx]),
922 )
923}
924
925/// Motion data parsed for one macroblock, before prediction derivation.
926#[derive(Clone, Copy)]
927struct MbMotion {
928 /// Sub-macroblock types of a P_8x8 / B_8x8 macroblock.
929 sub: [SubShape; 4],
930 /// `ref_idx_lX[ mbPartIdx ]`, -1 when the partition does not use the list.
931 ref_idx: [[i8; 4]; 2],
932 /// `mvd_lX[ mbPartIdx ][ subMbPartIdx ]`, indexed by 4x4 raster position.
933 mvd: [[[i16; 2]; 16]; 2],
934}
935
936/// Decode one macroblock (spec 7.3.5, 7.4.5) and reconstruct it. `ctx.qp`
937/// carries the QPY prediction chain.
938// Block loops are indexed: `blk` is simultaneously a bitstream position, a
939// geometry key (BLK4_POS) and a grid coordinate; iterators obscure that.
940#[allow(clippy::needless_range_loop, clippy::too_many_arguments)]
941fn decode_macroblock(
942 pic: &mut Picture,
943 refs: &[Picture],
944 ls: &[[LevelScale4x4; 3]; 2],
945 r: &mut Entropy<'_>,
946 ctx: &mut SliceCtx,
947 mb_addr: usize,
948 skipped: bool,
949) -> Result<()> {
950 let mb_x = mb_addr % pic.mb_w;
951 let mb_y = mb_addr / pic.mb_w;
952 if pic.mb_slice[mb_addr] != NO_SLICE {
953 return Err(Error::corrupt("macroblock decoded twice"));
954 }
955 let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id);
956 if !skipped || !r.is_cabac() {
957 let info = |addr: usize| MbInfo {
958 flags: pic.mb_flags[addr],
959 cbp: pic.mb_cbp[addr],
960 dc_cbf: pic.mb_dc_cbf[addr],
961 };
962 r.begin_mb(&MbCtx {
963 a: nbr.a.then(|| info(mb_addr - 1)),
964 b: nbr.b.then(|| info(mb_addr - pic.mb_w)),
965 qp_delta_inc: ctx.qp_delta_inc,
966 });
967 }
968 let w4 = pic.mb_w * 4;
969 let w2 = pic.mb_w * 2;
970 let (bx0, by0) = (mb_x * 4, mb_y * 4);
971 let (cx0, cy0) = (mb_x * 2, mb_y * 2);
972
973 // Every 4x4 block of this macroblock starts from a known state: the arrays
974 // survive from the previous picture, and both the CABAC contexts and the
975 // neighbour derivations read them for blocks of the macroblock in progress.
976 for py in 0..4 {
977 let base = (by0 + py) * w4 + bx0;
978 for idx in base..base + 4 {
979 pic.mv[idx] = [[0; 2]; 2];
980 pic.ref_idx[idx] = [-1; 2];
981 pic.ref_id[idx] = [-1; 2];
982 pic.mvd_abs[idx] = [0; 4];
983 pic.blk[idx] = 0;
984 }
985 }
986
987 let mb_type = if skipped {
988 u32::MAX
989 } else if ctx.slice_type == SliceType::P {
990 r.mb_type_p()?
991 } else if ctx.is_b() {
992 r.mb_type_b()?
993 } else {
994 r.mb_type_i()?
995 };
996
997 // Split the P/B numbering into an inter shape or an intra mb_type.
998 let (shape, intra_type) = if skipped {
999 let s = if ctx.is_b() { B_SHAPES[0] } else { P_SHAPES[0] };
1000 (Some(s), None)
1001 } else if ctx.slice_type == SliceType::P {
1002 if mb_type < 5 {
1003 (Some(P_SHAPES[mb_type as usize]), None)
1004 } else {
1005 (None, Some(mb_type - 5))
1006 }
1007 } else if ctx.is_b() {
1008 if mb_type < 23 {
1009 (Some(B_SHAPES[mb_type as usize]), None)
1010 } else {
1011 (None, Some(mb_type - 23))
1012 }
1013 } else {
1014 (None, Some(mb_type))
1015 };
1016 r.set_intra(intra_type.is_some());
1017
1018 if let Some(shape) = shape {
1019 return decode_inter_mb(
1020 pic, refs, ls, r, ctx, mb_addr, shape, skipped, mb_type, nbr,
1021 );
1022 }
1023 let mb_type = intra_type.expect("an intra macroblock type");
1024 write_intra_mb(pic, mb_x, mb_y);
1025 let intra_nbr = if ctx.constrained_intra_pred {
1026 intra_neighbors(pic, mb_x, mb_y, nbr)
1027 } else {
1028 nbr
1029 };
1030
1031 if mb_type == 25 {
1032 // I_PCM (7.3.5, 8.3.5): raw samples, byte aligned.
1033 let pcm = r.pcm_block()?;
1034 for y in 0..16 {
1035 let dst = pic.y.at(mb_x * 16, mb_y * 16 + y);
1036 pic.y.data[dst..dst + 16].copy_from_slice(&pcm[y * 16..y * 16 + 16]);
1037 }
1038 for (c, plane) in [&mut pic.cb, &mut pic.cr].into_iter().enumerate() {
1039 let base = 256 + c * 64;
1040 for y in 0..8 {
1041 let dst = plane.at(mb_x * 8, mb_y * 8 + y);
1042 plane.data[dst..dst + 8].copy_from_slice(&pcm[base + y * 8..base + y * 8 + 8]);
1043 }
1044 }
1045 for dy in 0..4 {
1046 let base = (by0 + dy) * w4 + bx0;
1047 pic.nz_y[base..base + 4].fill(16);
1048 pic.i4_modes[base..base + 4].fill(2);
1049 }
1050 for comp in 0..2 {
1051 for dy in 0..2 {
1052 let base = (cy0 + dy) * w2 + cx0;
1053 pic.nz_c[comp][base..base + 2].fill(16);
1054 }
1055 }
1056 // QPY prediction chain continues unchanged (mb_qp_delta inferred 0);
1057 // the deblocker substitutes 0 via FLAG_PCM (spec 8.7.2).
1058 pic.mb_qp[mb_addr] = ctx.qp as u8;
1059 pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_PCM;
1060 pic.mb_cbp[mb_addr] = 0x3F;
1061 pic.mb_dc_cbf[mb_addr] = 0b111;
1062 ctx.qp_delta_inc = 0;
1063 pic.mb_slice[mb_addr] = ctx.slice_id;
1064 pic.decoded_mbs += 1;
1065 return Ok(());
1066 }
1067
1068 let is_i16 = mb_type >= 1;
1069 let (cbp_luma, cbp_chroma, i16_mode) = if is_i16 {
1070 let m = mb_type - 1;
1071 (
1072 if m >= 12 { 15u8 } else { 0 },
1073 ((m / 4) % 3) as u8,
1074 (m % 4) as u8,
1075 )
1076 } else {
1077 (0, 0, 0) // read below via me(v)
1078 };
1079
1080 // I_NxN transform size flag (High profile only).
1081 if !is_i16 && ctx.transform_8x8_mode && r.transform_size_8x8_flag()? {
1082 return Err(Error::unsupported(
1083 "8x8 transform",
1084 "transform_size_8x8_flag 1 selects the 8x8 intra prediction of \
1085 clause 8.3.2 and the 8x8 transform of 8.5.13; not implemented",
1086 ));
1087 }
1088
1089 // mb_pred (7.3.5.1): intra 4x4 modes, then chroma mode.
1090 let mut modes = [2u8; 16];
1091 if !is_i16 {
1092 for blk in 0..16 {
1093 let (dx, dy) = BLK4_POS[blk];
1094 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
1095 // Predicted mode = min of neighbours, DC when either unavailable
1096 // (8.3.1.1; non-I4x4 neighbours were written as 2).
1097 let left_avail = if bx % 4 == 0 { intra_nbr.a } else { true };
1098 let top_avail = if by % 4 == 0 { intra_nbr.b } else { true };
1099 let pred = if left_avail && top_avail {
1100 let ma = pic.i4_modes[by * w4 + bx - 1];
1101 let mb = pic.i4_modes[(by - 1) * w4 + bx];
1102 ma.min(mb)
1103 } else {
1104 2
1105 };
1106 let mode = match r.intra4x4_pred_mode()? {
1107 None => pred,
1108 Some(rem) if rem < pred => rem,
1109 Some(rem) => rem + 1,
1110 };
1111 pic.i4_modes[by * w4 + bx] = mode;
1112 modes[blk] = mode;
1113 }
1114 } else {
1115 for dy in 0..4 {
1116 let base = (by0 + dy) * w4 + bx0;
1117 pic.i4_modes[base..base + 4].fill(2);
1118 }
1119 }
1120 let chroma_mode = r.intra_chroma_pred_mode()?;
1121
1122 // coded_block_pattern for I_NxN; Intra_16x16 derives it from mb_type.
1123 let (cbp_luma, cbp_chroma) = if is_i16 {
1124 (cbp_luma, cbp_chroma)
1125 } else {
1126 r.coded_block_pattern_intra()?
1127 };
1128
1129 finish_macroblock(
1130 pic,
1131 &ls[0],
1132 r,
1133 ctx,
1134 mb_addr,
1135 &intra_nbr,
1136 MbFinish {
1137 is_i16,
1138 i16_mode,
1139 cbp_luma,
1140 cbp_chroma,
1141 modes,
1142 chroma_mode,
1143 intra: true,
1144 flags: if is_i16 { FLAG_I16 } else { 0 },
1145 },
1146 )
1147}
1148
1149/// Everything the shared residual path needs after prediction is decided.
1150struct MbFinish {
1151 is_i16: bool,
1152 i16_mode: u8,
1153 cbp_luma: u8,
1154 cbp_chroma: u8,
1155 modes: [u8; 16],
1156 chroma_mode: u8,
1157 intra: bool,
1158 flags: u8,
1159}
1160
1161/// The residual half of a macroblock (7.3.5.3 + 8.5), shared by the intra and
1162/// inter paths.
1163///
1164/// Bitstream order (luma blocks in Z-order, then chroma DC, then chroma AC)
1165/// equals reconstruction dependency order, so each block reconstructs the
1166/// moment its levels are parsed: no per-macroblock coefficient arrays, and
1167/// empty blocks cost one coeff_token read plus a prediction write. For an inter
1168/// macroblock the prediction is already in the plane, so the intra branches
1169/// below are simply skipped.
1170#[allow(clippy::needless_range_loop, clippy::too_many_arguments)]
1171fn finish_macroblock(
1172 pic: &mut Picture,
1173 ls: &[LevelScale4x4; 3],
1174 r: &mut Entropy<'_>,
1175 ctx: &mut SliceCtx,
1176 mb_addr: usize,
1177 nbr: &MbNeighbors,
1178 m: MbFinish,
1179) -> Result<()> {
1180 let mb_x = mb_addr % pic.mb_w;
1181 let mb_y = mb_addr / pic.mb_w;
1182 let w4 = pic.mb_w * 4;
1183 let w2 = pic.mb_w * 2;
1184 let (bx0, by0) = (mb_x * 4, mb_y * 4);
1185 let (cx0, cy0) = (mb_x * 2, mb_y * 2);
1186 let (cbp_luma, cbp_chroma) = (m.cbp_luma, m.cbp_chroma);
1187
1188 // mb_qp_delta (7.4.5).
1189 let mut qp_delta = 0;
1190 if cbp_luma != 0 || cbp_chroma != 0 || m.is_i16 {
1191 qp_delta = r.mb_qp_delta()?;
1192 ctx.qp = (ctx.qp + qp_delta + 52) % 52;
1193 }
1194 ctx.qp_delta_inc = u8::from(qp_delta != 0);
1195 pic.mb_qp[mb_addr] = ctx.qp as u8;
1196 pic.mb_flags[mb_addr] = FLAG_DECODED
1197 | m.flags
1198 | if !m.intra { FLAG_INTER } else { 0 }
1199 | if m.intra && m.chroma_mode != 0 {
1200 FLAG_CHROMA_PRED
1201 } else {
1202 0
1203 };
1204 pic.mb_cbp[mb_addr] = cbp_luma | (cbp_chroma << 4);
1205 pic.mb_slice[mb_addr] = ctx.slice_id;
1206 pic.decoded_mbs += 1;
1207 let qp_y = ctx.qp;
1208 let qp_cb = i32::from(CHROMA_QP[(qp_y + ctx.cb_qp_offset).clamp(0, 51) as usize]);
1209 let qp_cr = i32::from(CHROMA_QP[(qp_y + ctx.cr_qp_offset).clamp(0, 51) as usize]);
1210
1211 let mut dc_cbf = 0u8;
1212 let mut scan = [0i32; 16];
1213 let mut raster = [0i32; 16];
1214 let mut resid = [0i32; 16];
1215 if m.is_i16 {
1216 let mut w = PlaneWindow {
1217 data: &mut pic.y.data,
1218 stride: pic.y.stride,
1219 origin: pic.y.origin + (mb_y * 16) * pic.y.stride + mb_x * 16,
1220 };
1221 pred_16x16(m.i16_mode, &mut w, nbr.b, nbr.a);
1222 // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale.
1223 let (na, nb) = luma_nz_pair(pic, nbr, bx0, by0);
1224 let dc_tc = r.residual_block(&mut scan, BlockCat::LumaDc, na, nb)?;
1225 dc_cbf |= u8::from(dc_tc != 0);
1226 unzigzag(&scan, &mut raster);
1227 luma_dc_transform(&mut raster, &ls[0], qp_y);
1228 let dc = raster;
1229 for blk in 0..16 {
1230 let (dx, dy) = BLK4_POS[blk];
1231 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
1232 let tc = if cbp_luma != 0 {
1233 let (na, nb) = luma_nz_pair(pic, nbr, bx, by);
1234 r.residual_block(&mut scan, BlockCat::LumaAc, na, nb)?
1235 } else {
1236 0
1237 };
1238 pic.nz_y[by * w4 + bx] = tc;
1239 let dc_blk = dc[dy as usize * 4 + dx as usize];
1240 if tc == 0 && dc_blk == 0 {
1241 continue; // prediction already in place
1242 }
1243 if tc > 0 {
1244 unzigzag_ac15(&scan, &mut raster);
1245 dequant_4x4(&mut raster, &ls[0], qp_y, true);
1246 } else {
1247 raster = [0; 16]; // DC-only block
1248 }
1249 raster[0] = dc_blk;
1250 inverse_transform_4x4(&raster, &mut resid);
1251 let origin = pic
1252 .y
1253 .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1254 add_residual_4x4(&mut pic.y.data, pic.y.stride, origin, &resid);
1255 }
1256 } else {
1257 for blk in 0..16 {
1258 let (dx, dy) = BLK4_POS[blk];
1259 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
1260 let tc = if cbp_luma & (1 << (blk >> 2)) != 0 {
1261 let (na, nb) = luma_nz_pair(pic, nbr, bx, by);
1262 r.residual_block(&mut scan, BlockCat::Luma4x4, na, nb)?
1263 } else {
1264 0
1265 };
1266 pic.nz_y[by * w4 + bx] = tc;
1267 let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
1268 let origin = pic.y.at(x, y);
1269 let stride = pic.y.stride;
1270 if m.intra {
1271 let n = gather_nbr4(pic, nbr, blk, x, y);
1272 let mut p = [0u8; 16];
1273 pred_4x4(m.modes[blk], &n, &mut p);
1274 if tc == 0 {
1275 // Pure prediction: copy the 16 samples in.
1276 for ry in 0..4 {
1277 let row = origin + ry * stride;
1278 pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
1279 }
1280 continue;
1281 }
1282 unzigzag(&scan, &mut raster);
1283 dequant_4x4(&mut raster, &ls[0], qp_y, false);
1284 inverse_transform_4x4(&raster, &mut resid);
1285 for ry in 0..4 {
1286 let row = origin + ry * stride;
1287 for rx in 0..4 {
1288 let v = i32::from(p[ry * 4 + rx]) + resid[ry * 4 + rx];
1289 pic.y.data[row + rx] = v.clamp(0, 255) as u8;
1290 }
1291 }
1292 } else {
1293 if tc == 0 {
1294 continue; // motion-compensated prediction already in place
1295 }
1296 unzigzag(&scan, &mut raster);
1297 dequant_4x4(&mut raster, &ls[0], qp_y, false);
1298 inverse_transform_4x4(&raster, &mut resid);
1299 add_residual_4x4(&mut pic.y.data, stride, origin, &resid);
1300 }
1301 }
1302 }
1303
1304 // Chroma: predict both components (intra only), then DC (Cb, Cr), then AC
1305 // in bitstream order, reconstructing as levels arrive.
1306 if m.intra {
1307 for comp in 0..2 {
1308 let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
1309 let mut w = PlaneWindow {
1310 data: &mut plane.data,
1311 stride: plane.stride,
1312 origin: plane.origin + (mb_y * 8) * plane.stride + mb_x * 8,
1313 };
1314 pred_chroma_8x8(m.chroma_mode, &mut w, nbr.b, nbr.a);
1315 }
1316 }
1317 let mut chroma_dc = [[0i32; 4]; 2];
1318 if cbp_chroma != 0 {
1319 for (comp, c) in chroma_dc.iter_mut().enumerate() {
1320 let tc = r.residual_block(&mut scan, BlockCat::ChromaDc(comp as u8), None, None)?;
1321 dc_cbf |= u8::from(tc != 0) << (1 + comp);
1322 c.copy_from_slice(&scan[..4]);
1323 let (ls_c, qp_c) = if comp == 0 {
1324 (&ls[1], qp_cb)
1325 } else {
1326 (&ls[2], qp_cr)
1327 };
1328 chroma_dc_transform_420(c, ls_c, qp_c);
1329 }
1330 }
1331 for comp in 0..2 {
1332 for blk in 0..4 {
1333 let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
1334 let tc = if cbp_chroma == 2 {
1335 let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy);
1336 r.residual_block(&mut scan, BlockCat::ChromaAc, na, nb)?
1337 } else {
1338 0
1339 };
1340 pic.nz_c[comp][cy * w2 + cx] = tc;
1341 if cbp_chroma == 0 {
1342 continue;
1343 }
1344 let dc_blk = chroma_dc[comp][blk];
1345 if tc == 0 && dc_blk == 0 {
1346 continue;
1347 }
1348 let (plane, ls_c, qp_c) = if comp == 0 {
1349 (&mut pic.cb, &ls[1], qp_cb)
1350 } else {
1351 (&mut pic.cr, &ls[2], qp_cr)
1352 };
1353 if tc > 0 {
1354 unzigzag_ac15(&scan, &mut raster);
1355 dequant_4x4(&mut raster, ls_c, qp_c, true);
1356 } else {
1357 raster = [0; 16]; // DC-only block
1358 }
1359 raster[0] = dc_blk;
1360 inverse_transform_4x4(&raster, &mut resid);
1361 let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
1362 add_residual_4x4(&mut plane.data, plane.stride, origin, &resid);
1363 }
1364 }
1365 pic.mb_dc_cbf[mb_addr] = dc_cbf;
1366 Ok(())
1367}
1368
1369/// Decode an inter macroblock: sub-macroblock types, reference indices and
1370/// motion vector differences (7.3.5.1, 7.3.5.2), then motion compensation
1371/// (8.4.2) and the shared residual path.
1372#[allow(clippy::too_many_arguments)]
1373fn decode_inter_mb(
1374 pic: &mut Picture,
1375 refs: &[Picture],
1376 ls: &[[LevelScale4x4; 3]; 2],
1377 r: &mut Entropy<'_>,
1378 ctx: &mut SliceCtx,
1379 mb_addr: usize,
1380 shape: MbShape,
1381 skipped: bool,
1382 mb_type: u32,
1383 nbr: MbNeighbors,
1384) -> Result<()> {
1385 let mb_x = mb_addr % pic.mb_w;
1386 let mb_y = mb_addr / pic.mb_w;
1387 let b = ctx.is_b();
1388 let mut mvc = MvCtx {
1389 mb_x,
1390 mb_y,
1391 slice_id: ctx.slice_id,
1392 written: 0,
1393 };
1394 let mut motion = MbMotion {
1395 sub: [P_SUB[0]; 4],
1396 ref_idx: [[-1; 4]; 2],
1397 mvd: [[[0; 2]; 16]; 2],
1398 };
1399 // A direct or skipped block contributes nothing to the ref_idx and mvd
1400 // contexts of its neighbours (9.3.3.1.1.6, 9.3.3.1.1.7), so the flag has to
1401 // be in place before any of this macroblock's syntax is parsed.
1402 let direct_mb = skipped || (b && mb_type == 0);
1403 if direct_mb {
1404 let f = BLK_DIRECT | if skipped { BLK_SKIP } else { 0 };
1405 for py in 0..4 {
1406 let base = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4;
1407 for idx in base..base + 4 {
1408 pic.blk[idx] = f;
1409 }
1410 }
1411 }
1412
1413 if shape.sub && !skipped {
1414 for part in 0..4 {
1415 let t = r.sub_mb_type(b)? as usize;
1416 motion.sub[part] = if b { B_SUB[t] } else { P_SUB[t] };
1417 if motion.sub[part].pred == Pred::Direct {
1418 for k in 0..4 {
1419 let (px, py) = (part % 2 * 2 + k % 2, part / 2 * 2 + k / 2);
1420 let idx = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4 + px;
1421 pic.blk[idx] = BLK_DIRECT;
1422 }
1423 }
1424 }
1425 }
1426
1427 // ---- ref_idx_lX (7.3.5.1, 7.3.5.2) ----
1428 // P_8x8ref0 infers reference index 0 for every partition.
1429 let infer_ref0 = ctx.slice_type == SliceType::P && mb_type == 4;
1430 if !skipped {
1431 for list in 0..2 {
1432 for part in 0..shape.parts {
1433 let uses = if shape.sub {
1434 motion.sub[part].pred.uses(list)
1435 } else {
1436 shape.pred[part.min(1)].uses(list)
1437 };
1438 if !uses {
1439 continue;
1440 }
1441 let idx = if infer_ref0 || ctx.num_ref_idx[list] <= 1 {
1442 0
1443 } else {
1444 let (px, py) = part_origin(&shape, part, (0, 0));
1445 let bx = (mb_x * 4 + px) as i32;
1446 let by = (mb_y * 4 + py) as i32;
1447 let inc = ref_idx_cond(pic, &mvc, bx - 1, by, list)
1448 + 2 * ref_idx_cond(pic, &mvc, bx, by - 1, list);
1449 r.ref_idx(ctx.num_ref_idx[list] as u32 - 1, inc)? as i8
1450 };
1451 motion.ref_idx[list][part] = idx;
1452 // Publish it so the next partition's context can see it.
1453 let (px, py) = part_origin(&shape, part, (0, 0));
1454 let (pw, ph) = part_size(&shape, &motion, part);
1455 for dy in 0..ph {
1456 for dx in 0..pw {
1457 let bi = (mb_y * 4 + py + dy) * pic.mb_w * 4 + mb_x * 4 + px + dx;
1458 pic.ref_idx[bi][list] = idx;
1459 mvc.written |= 1 << ((py + dy) * 4 + px + dx);
1460 }
1461 }
1462 }
1463 }
1464 if infer_ref0 {
1465 for part in 0..4 {
1466 motion.ref_idx[0][part] = 0;
1467 }
1468 }
1469
1470 // ---- mvd_lX ----
1471 mvc.written = 0;
1472 for list in 0..2 {
1473 for part in 0..shape.parts {
1474 let uses = if shape.sub {
1475 motion.sub[part].pred.uses(list)
1476 } else {
1477 shape.pred[part.min(1)].uses(list)
1478 };
1479 if !uses {
1480 continue;
1481 }
1482 let subparts = if shape.sub { motion.sub[part].parts } else { 1 };
1483 for sp in 0..subparts {
1484 let (px, py) = part_origin(&shape, part, sp_offset(&shape, &motion, part, sp));
1485 let (pw, ph) = part_size(&shape, &motion, part);
1486 let bx = (mb_x * 4 + px) as i32;
1487 let by = (mb_y * 4 + py) as i32;
1488 let mut mvd = [0i16; 2];
1489 for comp in 0..2 {
1490 let a = neighbour_mvd(pic, &mvc, bx - 1, by, list)[comp];
1491 let bb = neighbour_mvd(pic, &mvc, bx, by - 1, list)[comp];
1492 let sum = a + bb;
1493 let inc = if sum > 32 {
1494 2
1495 } else if sum > 2 {
1496 1
1497 } else {
1498 0
1499 };
1500 let v = r.mvd(comp, inc)?;
1501 mvd[comp] = i16::try_from(v)
1502 .map_err(|_| Error::corrupt("mvd outside the level limits"))?;
1503 }
1504 for dy in 0..ph {
1505 for dx in 0..pw {
1506 motion.mvd[list][(py + dy) * 4 + px + dx] = mvd;
1507 write_mvd(pic, mb_x, mb_y, px + dx, py + dy, list, mvd);
1508 mvc.written |= 1 << ((py + dy) * 4 + px + dx);
1509 }
1510 }
1511 }
1512 }
1513 }
1514 }
1515
1516 // ---- motion vector derivation and compensation (8.4.1, 8.4.2) ----
1517 mvc.written = 0;
1518 if direct_mb && !b {
1519 predict_p_skip(pic, refs, ctx, &mut mvc)?;
1520 } else if direct_mb {
1521 predict_direct(pic, refs, ctx, &mut mvc, true)?;
1522 } else {
1523 for part in 0..shape.parts {
1524 if shape.sub && motion.sub[part].pred == Pred::Direct {
1525 predict_direct_8x8(pic, refs, ctx, &mut mvc, part)?;
1526 continue;
1527 }
1528 let subparts = if shape.sub { motion.sub[part].parts } else { 1 };
1529 let pred = if shape.sub {
1530 motion.sub[part].pred
1531 } else {
1532 shape.pred[part.min(1)]
1533 };
1534 for sp in 0..subparts {
1535 let (px, py) = part_origin(&shape, part, sp_offset(&shape, &motion, part, sp));
1536 let (pw, ph) = part_size(&shape, &motion, part);
1537 let mut mv = [[0i16; 2]; 2];
1538 let mut ref_idx = [-1i8; 2];
1539 let mut ref_id = [-1i32; 2];
1540 for list in 0..2 {
1541 if !pred.uses(list) {
1542 continue;
1543 }
1544 let idx = motion.ref_idx[list][part];
1545 // predPartWidth of 6.4.11.7: the macroblock partition width
1546 // for a whole-macroblock partition, the sub-macroblock
1547 // partition width inside an 8x8.
1548 let n = mvc.neighbours(pic, px, py, pw, list);
1549 let mvp = predict_mv(&n, idx, shape.w, shape.h, part);
1550 let d = motion.mvd[list][py * 4 + px];
1551 mv[list] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])];
1552 ref_idx[list] = idx;
1553 ref_id[list] = ctx
1554 .reference(refs, list, idx)
1555 .map(|p| p.id)
1556 .unwrap_or(-1);
1557 }
1558 for dy in 0..ph {
1559 for dx in 0..pw {
1560 write_block(pic, &mut mvc, px + dx, py + dy, mv, ref_idx, ref_id, 0);
1561 }
1562 }
1563 compensate(pic, refs, ctx, mb_x, mb_y, px, py, pw, ph, mv, ref_idx)?;
1564 }
1565 }
1566 }
1567
1568 if skipped {
1569 // 7.4.5: a skipped macroblock has no residual and does not change QPY.
1570 let w4 = pic.mb_w * 4;
1571 let w2 = pic.mb_w * 2;
1572 for dy in 0..4 {
1573 let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
1574 pic.nz_y[base..base + 4].fill(0);
1575 pic.i4_modes[base..base + 4].fill(2);
1576 }
1577 for comp in 0..2 {
1578 for dy in 0..2 {
1579 let base = (mb_y * 2 + dy) * w2 + mb_x * 2;
1580 pic.nz_c[comp][base..base + 2].fill(0);
1581 }
1582 }
1583 pic.mb_qp[mb_addr] = ctx.qp as u8;
1584 pic.mb_flags[mb_addr] =
1585 FLAG_DECODED | FLAG_INTER | FLAG_SKIP | if b { FLAG_DIRECT } else { 0 };
1586 pic.mb_cbp[mb_addr] = 0;
1587 pic.mb_dc_cbf[mb_addr] = 0;
1588 pic.mb_slice[mb_addr] = ctx.slice_id;
1589 pic.decoded_mbs += 1;
1590 ctx.qp_delta_inc = 0;
1591 return Ok(());
1592 }
1593
1594 let w4 = pic.mb_w * 4;
1595 for dy in 0..4 {
1596 let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
1597 pic.i4_modes[base..base + 4].fill(2);
1598 }
1599 let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?;
1600 // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual.
1601 finish_macroblock(
1602 pic,
1603 &ls[1],
1604 r,
1605 ctx,
1606 mb_addr,
1607 &nbr,
1608 MbFinish {
1609 is_i16: false,
1610 i16_mode: 0,
1611 cbp_luma,
1612 cbp_chroma,
1613 modes: [2; 16],
1614 chroma_mode: 0,
1615 intra: false,
1616 flags: if b && mb_type == 0 { FLAG_DIRECT } else { 0 },
1617 },
1618 )
1619}
1620
1621/// Top-left 4x4 block of macroblock partition `part`, offset by `sp` blocks in
1622/// raster order within the 8x8.
1623fn part_origin(shape: &MbShape, part: usize, sp: (usize, usize)) -> (usize, usize) {
1624 let (px, py) = if shape.sub {
1625 (part % 2 * 2, part / 2 * 2)
1626 } else if shape.parts == 1 {
1627 (0, 0)
1628 } else if shape.w == 4 {
1629 (0, part * 2) // 16x8
1630 } else {
1631 (part * 2, 0) // 8x16
1632 };
1633 (px + sp.0, py + sp.1)
1634}
1635
1636/// Block offset of sub-macroblock partition `sp` inside its 8x8.
1637fn sp_offset(shape: &MbShape, m: &MbMotion, part: usize, sp: usize) -> (usize, usize) {
1638 if !shape.sub {
1639 return (0, 0);
1640 }
1641 let s = m.sub[part];
1642 match (s.w, s.h) {
1643 (2, 2) => (0, 0),
1644 (2, 1) => (0, sp),
1645 (1, 2) => (sp, 0),
1646 _ => (sp % 2, sp / 2),
1647 }
1648}
1649
1650/// Size of one (sub-)macroblock partition in 4x4 blocks.
1651fn part_size(shape: &MbShape, m: &MbMotion, part: usize) -> (usize, usize) {
1652 if shape.sub {
1653 let s = m.sub[part];
1654 (s.w, s.h)
1655 } else {
1656 (shape.w, shape.h)
1657 }
1658}
1659
1660/// P_Skip (clause 8.4.1.1).
1661fn predict_p_skip(
1662 pic: &mut Picture,
1663 refs: &[Picture],
1664 ctx: &SliceCtx,
1665 mvc: &mut MvCtx,
1666) -> Result<()> {
1667 let n = mvc.neighbours(pic, 0, 0, 4, 0);
1668 let zero = !n[0].avail
1669 || !n[1].avail
1670 || (n[0].ref_idx == 0 && n[0].mv == [0, 0])
1671 || (n[1].ref_idx == 0 && n[1].mv == [0, 0]);
1672 let mv = if zero {
1673 [0i16; 2]
1674 } else {
1675 predict_mv(&n, 0, 4, 4, 0)
1676 };
1677 let ref_id = ctx.reference(refs, 0, 0).map(|p| p.id).unwrap_or(-1);
1678 for py in 0..4 {
1679 for px in 0..4 {
1680 write_block(
1681 pic,
1682 mvc,
1683 px,
1684 py,
1685 [mv, [0; 2]],
1686 [0, -1],
1687 [ref_id, -1],
1688 BLK_SKIP | BLK_DIRECT,
1689 );
1690 }
1691 }
1692 compensate(
1693 pic,
1694 refs,
1695 ctx,
1696 mvc.mb_x,
1697 mvc.mb_y,
1698 0,
1699 0,
1700 4,
1701 4,
1702 [mv, [0; 2]],
1703 [0, -1],
1704 )
1705}
1706
1707/// B_Skip / B_Direct_16x16 (clause 8.4.1.2) over the whole macroblock.
1708fn predict_direct(
1709 pic: &mut Picture,
1710 refs: &[Picture],
1711 ctx: &SliceCtx,
1712 mvc: &mut MvCtx,
1713 skip: bool,
1714) -> Result<()> {
1715 for quad in 0..4 {
1716 direct_quadrant(pic, refs, ctx, mvc, quad, skip)?;
1717 }
1718 Ok(())
1719}
1720
1721/// B_Direct_8x8 for one 8x8 sub-macroblock.
1722fn predict_direct_8x8(
1723 pic: &mut Picture,
1724 refs: &[Picture],
1725 ctx: &SliceCtx,
1726 mvc: &mut MvCtx,
1727 part: usize,
1728) -> Result<()> {
1729 direct_quadrant(pic, refs, ctx, mvc, part, false)
1730}
1731
1732/// One 8x8 quadrant of a direct-mode macroblock. With
1733/// `direct_8x8_inference_flag` the whole quadrant shares the motion of its
1734/// outer corner 4x4 block; without it each 4x4 block is derived on its own.
1735fn direct_quadrant(
1736 pic: &mut Picture,
1737 refs: &[Picture],
1738 ctx: &SliceCtx,
1739 mvc: &mut MvCtx,
1740 quad: usize,
1741 skip: bool,
1742) -> Result<()> {
1743 let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y);
1744 let (qx, qy) = (quad % 2 * 2, quad / 2 * 2);
1745 let flags = BLK_DIRECT | if skip { BLK_SKIP } else { 0 };
1746 if ctx.direct_8x8_inference {
1747 // 8.4.1.2.1: luma4x4BlkIdx = 5 * mbPartIdx, i.e. the quadrant's own
1748 // outer corner of the macroblock.
1749 let corner = (quad % 2 * 3, quad / 2 * 3);
1750 let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, corner)?;
1751 for dy in 0..2 {
1752 for dx in 0..2 {
1753 write_block(pic, mvc, qx + dx, qy + dy, mv, ref_idx, ref_id, flags);
1754 }
1755 }
1756 compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx)
1757 } else {
1758 for dy in 0..2 {
1759 for dx in 0..2 {
1760 let (px, py) = (qx + dx, qy + dy);
1761 let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, (px, py))?;
1762 write_block(pic, mvc, px, py, mv, ref_idx, ref_id, flags);
1763 compensate(pic, refs, ctx, mb_x, mb_y, px, py, 1, 1, mv, ref_idx)?;
1764 }
1765 }
1766 Ok(())
1767 }
1768}
1769
1770/// Motion of one direct-mode 4x4 block: spatial (8.4.1.2.2) or temporal
1771/// (8.4.1.2.3).
1772fn direct_block(
1773 pic: &Picture,
1774 refs: &[Picture],
1775 ctx: &SliceCtx,
1776 mvc: &MvCtx,
1777 at: (usize, usize),
1778) -> Result<([[i16; 2]; 2], [i8; 2], [i32; 2])> {
1779 // The co-located block, in both modes.
1780 let col = ctx.lists[1].get(0).and_then(|i| refs.get(i));
1781 let (col_ref_id, col_mv, col_list) = match col {
1782 Some(c) => {
1783 let bx = mvc.mb_x * 4 + at.0;
1784 let by = mvc.mb_y * 4 + at.1;
1785 let idx = by * c.mb_w.max(1) * 4 + bx;
1786 if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 {
1787 let list = usize::from(c.ref_id[idx][0] < 0);
1788 (c.ref_id[idx][list], c.mv[idx][list], list)
1789 } else {
1790 (-1, [0i16; 2], 0)
1791 }
1792 }
1793 None => (-1, [0i16; 2], 0),
1794 };
1795 let _ = col_list;
1796
1797 if ctx.direct_spatial {
1798 // Reference indices from the macroblock's own neighbours, once.
1799 let mut ref_idx = [-1i8; 2];
1800 let mut mvp = [[0i16; 2]; 2];
1801 for list in 0..2 {
1802 let n = mvc.neighbours(pic, 0, 0, 4, list);
1803 ref_idx[list] = min_positive(n[0].ref_idx, min_positive(n[1].ref_idx, n[2].ref_idx));
1804 mvp[list] = predict_mv(&n, ref_idx[list], 4, 4, 0);
1805 }
1806 let zero_prediction = ref_idx[0] < 0 && ref_idx[1] < 0;
1807 if zero_prediction {
1808 ref_idx = [0, 0];
1809 }
1810 // colZeroFlag: the co-located block sits still on a short-term picture.
1811 let col_short = col.is_some_and(|c| c.mark == Mark::Short);
1812 let col_zero = col_short
1813 && col_ref_id >= 0
1814 && col.is_some_and(|c| {
1815 let bx = mvc.mb_x * 4 + at.0;
1816 let by = mvc.mb_y * 4 + at.1;
1817 let idx = by * c.mb_w.max(1) * 4 + bx;
1818 idx < c.ref_idx.len() && (c.ref_idx[idx][0] == 0 || c.ref_idx[idx][1] == 0)
1819 })
1820 && (-1..=1).contains(&col_mv[0])
1821 && (-1..=1).contains(&col_mv[1]);
1822 let mut mv = [[0i16; 2]; 2];
1823 let mut ref_id = [-1i32; 2];
1824 for list in 0..2 {
1825 if ref_idx[list] < 0 {
1826 continue;
1827 }
1828 ref_id[list] = ctx
1829 .reference(refs, list, ref_idx[list])
1830 .map(|p| p.id)
1831 .unwrap_or(-1);
1832 if zero_prediction || (ref_idx[list] == 0 && col_zero) {
1833 mv[list] = [0; 2];
1834 } else {
1835 mv[list] = mvp[list];
1836 }
1837 }
1838 return Ok((mv, ref_idx, ref_id));
1839 }
1840
1841 // Temporal direct (8.4.1.2.3).
1842 let ref_idx0 = if col_ref_id < 0 {
1843 0
1844 } else {
1845 map_col_to_list0(ctx, refs, col_ref_id)
1846 };
1847 let pic0 = ctx.reference(refs, 0, ref_idx0);
1848 let pic1 = ctx.reference(refs, 1, 0);
1849 let ref_id = [
1850 pic0.map(|p| p.id).unwrap_or(-1),
1851 pic1.map(|p| p.id).unwrap_or(-1),
1852 ];
1853 let (Some(p0), Some(p1)) = (pic0, pic1) else {
1854 return Ok(([[0; 2]; 2], [ref_idx0, 0], ref_id));
1855 };
1856 let td = (p1.poc - p0.poc).clamp(-128, 127);
1857 if p0.mark == Mark::Long || td == 0 {
1858 return Ok(([col_mv, [0; 2]], [ref_idx0, 0], ref_id));
1859 }
1860 let tb = (ctx.poc - p0.poc).clamp(-128, 127);
1861 let tx = (16384 + (td / 2).abs()) / td;
1862 let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023);
1863 let mv0 = [
1864 ((dist * i32::from(col_mv[0]) + 128) >> 8) as i16,
1865 ((dist * i32::from(col_mv[1]) + 128) >> 8) as i16,
1866 ];
1867 let mv1 = [mv0[0] - col_mv[0], mv0[1] - col_mv[1]];
1868 Ok(([mv0, mv1], [ref_idx0, 0], ref_id))
1869}
1870
1871/// `MapColToList0` (8.4.1.2.3): the lowest RefPicList0 index that names the
1872/// picture the co-located block referenced.
1873fn map_col_to_list0(ctx: &SliceCtx, refs: &[Picture], col_ref_id: i32) -> i8 {
1874 for i in 0..ctx.lists[0].len() {
1875 if ctx
1876 .lists[0]
1877 .get(i)
1878 .and_then(|k| refs.get(k))
1879 .is_some_and(|p| p.id == col_ref_id)
1880 {
1881 return i as i8;
1882 }
1883 }
1884 0
1885}
1886
1887/// Motion compensation of one partition (clause 8.4.2): interpolate each list's
1888/// prediction, then combine them by the weighting of 8.4.2.3 and write the
1889/// result straight into the picture, where the residual is added on top.
1890///
1891/// `(px, py)` and `(pw, ph)` are in 4x4 blocks within the macroblock.
1892#[allow(clippy::too_many_arguments)]
1893fn compensate(
1894 pic: &mut Picture,
1895 refs: &[Picture],
1896 ctx: &SliceCtx,
1897 mb_x: usize,
1898 mb_y: usize,
1899 px: usize,
1900 py: usize,
1901 pw: usize,
1902 ph: usize,
1903 mv: [[i16; 2]; 2],
1904 ref_idx: [i8; 2],
1905) -> Result<()> {
1906 let use0 = ref_idx[0] >= 0;
1907 let use1 = ref_idx[1] >= 0;
1908 if !use0 && !use1 {
1909 return Ok(());
1910 }
1911 let x0 = (mb_x * 16 + px * 4) as i32;
1912 let y0 = (mb_y * 16 + py * 4) as i32;
1913 let (w, h) = (pw * 4, ph * 4);
1914
1915 let mut part = [[0u8; 256]; 2];
1916 for list in 0..2 {
1917 if ref_idx[list] < 0 {
1918 continue;
1919 }
1920 let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| {
1921 Error::corrupt("reference index names a picture the buffer does not hold")
1922 })?;
1923 let plane = RefPlane {
1924 data: &rp.y.data,
1925 stride: rp.y.stride,
1926 origin: rp.y.origin,
1927 width: rp.y.width,
1928 height: rp.y.height,
1929 pad: rp.y.pad,
1930 };
1931 mc_luma(&plane, x0, y0, mv[list], w, h, &mut part[list]);
1932 }
1933 let wt = ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1);
1934 let mut out = [0u8; 256];
1935 let (p0, p1) = part.split_at(1);
1936 combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h);
1937 let stride = pic.y.stride;
1938 let origin = pic.y.at(x0 as usize, y0 as usize);
1939 for row in 0..h {
1940 let dst = origin + row * stride;
1941 pic.y.data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]);
1942 }
1943
1944 // Chroma (8.4.1.4): for 4:2:0 frame coding the chroma vector is the luma
1945 // vector, read as eighth-sample units over the half-resolution plane.
1946 let (cw, ch) = (w / 2, h / 2);
1947 let (cx0, cy0) = (x0 / 2, y0 / 2);
1948 for comp in 0..2 {
1949 let mut cpart = [[0u8; 64]; 2];
1950 for list in 0..2 {
1951 if ref_idx[list] < 0 {
1952 continue;
1953 }
1954 let rp = ctx
1955 .reference(refs, list, ref_idx[list])
1956 .expect("checked above");
1957 let src = if comp == 0 { &rp.cb } else { &rp.cr };
1958 let plane = RefPlane {
1959 data: &src.data,
1960 stride: src.stride,
1961 origin: src.origin,
1962 width: src.width,
1963 height: src.height,
1964 pad: src.pad,
1965 };
1966 mc_chroma(&plane, cx0, cy0, mv[list], cw, ch, &mut cpart[list]);
1967 }
1968 let wt = ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1);
1969 let mut cout = [0u8; 64];
1970 let (c0, c1) = cpart.split_at(1);
1971 combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch);
1972 let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
1973 let stride = plane.stride;
1974 let origin = plane.at(cx0 as usize, cy0 as usize);
1975 for row in 0..ch {
1976 let dst = origin + row * stride;
1977 plane.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]);
1978 }
1979 }
1980 Ok(())
1981}
1982
1983/// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2),
1984/// including the top-right substitution rule.
1985fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) -> Nbr4 {
1986 let (dx, dy) = BLK4_POS[blk];
1987 let stride = pic.y.stride;
1988 let o = pic.y.at(x, y);
1989 let have_left = if dx == 0 { nbr.a } else { true };
1990 let have_top = if dy == 0 { nbr.b } else { true };
1991 let have_tr = match TR_KIND[blk] {
1992 TrKind::InMb => true,
1993 TrKind::B => nbr.b,
1994 TrKind::C => nbr.c,
1995 TrKind::None => false,
1996 };
1997 let mut top = [0u8; 8];
1998 let data = &pic.y.data;
1999 top[..4].copy_from_slice(&data[o - stride..o - stride + 4]);
2000 if have_tr {
2001 top[4..].copy_from_slice(&data[o - stride + 4..o - stride + 8]);
2002 } else if have_top {
2003 let t3 = top[3];
2004 top[4..].fill(t3);
2005 }
2006 let mut left = [0u8; 4];
2007 for (i, l) in left.iter_mut().enumerate() {
2008 *l = data[o + i * stride - 1];
2009 }
2010 Nbr4 {
2011 top,
2012 left,
2013 top_left: data[o - stride - 1],
2014 have_top,
2015 have_left,
2016 }
2017}
2018
2019/// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all
2020/// vertical edges then all horizontal edges per macroblock, then chroma.
2021fn deblock_picture(pic: &mut Picture) {
2022 let mb_w = pic.mb_w;
2023 for mb_y in 0..pic.mb_h {
2024 for mb_x in 0..mb_w {
2025 let addr = mb_y * mb_w + mb_x;
2026 if pic.mb_flags[addr] & FLAG_DECODED == 0 {
2027 continue;
2028 }
2029 let sid = pic.mb_slice[addr];
2030 let sp = pic.slices[sid as usize];
2031 if sp.disable_deblock_idc == 1 {
2032 continue;
2033 }
2034 let decoded = |a: usize| pic.mb_flags[a] & FLAG_DECODED != 0;
2035 let cross_ok = |a: usize| sp.disable_deblock_idc != 2 || pic.mb_slice[a] == sid;
2036 let filter_left = mb_x > 0 && decoded(addr - 1) && cross_ok(addr - 1);
2037 let filter_top = mb_y > 0 && decoded(addr - mb_w) && cross_ok(addr - mb_w);
2038 // Deblocking QP: 0 for I_PCM macroblocks (8.7.2).
2039 let qp_of = |a: usize| -> i32 {
2040 if pic.mb_flags[a] & FLAG_PCM != 0 {
2041 0
2042 } else {
2043 i32::from(pic.mb_qp[a])
2044 }
2045 };
2046 let qp_q = qp_of(addr);
2047
2048 // Boundary strengths, per 4-sample segment of each edge (8.7.2.1).
2049 let mut bs_v = [[0u8; 4]; 4];
2050 let mut bs_h = [[0u8; 4]; 4];
2051 for e in 0..4 {
2052 for k in 0..4 {
2053 if e > 0 || filter_left {
2054 bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true);
2055 }
2056 if e > 0 || filter_top {
2057 bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false);
2058 }
2059 }
2060 }
2061
2062 // ---- luma ----
2063 {
2064 let stride = pic.y.stride;
2065 let base = pic.y.at(mb_x * 16, mb_y * 16);
2066 // Vertical edges (filter across columns), left to right.
2067 for e in 0..4 {
2068 if e == 0 && !filter_left {
2069 continue;
2070 }
2071 let qp_p = if e == 0 { qp_of(addr - 1) } else { qp_q };
2072 let qp_avg = (qp_p + qp_q + 1) >> 1;
2073 // Vertical edges stay scalar: a gather/scatter SIMD
2074 // variant measured slower than this loop (strided
2075 // per-lane loads dominate).
2076 for j in 0..4 {
2077 let bs = bs_v[e][j];
2078 if bs == 0 {
2079 continue;
2080 }
2081 let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs);
2082 if params.alpha == 0 || params.beta == 0 {
2083 continue;
2084 }
2085 for k in 0..4 {
2086 let row = j * 4 + k;
2087 filter_luma_line(
2088 &mut pic.y.data,
2089 base + row * stride + e * 4,
2090 1,
2091 &params,
2092 );
2093 }
2094 }
2095 }
2096 // Horizontal edges, top to bottom.
2097 for e in 0..4 {
2098 if e == 0 && !filter_top {
2099 continue;
2100 }
2101 let qp_p = if e == 0 { qp_of(addr - mb_w) } else { qp_q };
2102 let qp_avg = (qp_p + qp_q + 1) >> 1;
2103 let bs = bs_h[e];
2104 let uniform = bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3];
2105 if uniform {
2106 if bs[0] == 0 {
2107 continue;
2108 }
2109 let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0]);
2110 if params.alpha == 0 || params.beta == 0 {
2111 continue;
2112 }
2113 // Eight rows around the edge are contiguous, so the
2114 // whole 16-sample edge filters in one pass.
2115 filter_luma_h_edge16(&mut pic.y.data, base + e * 4 * stride, stride, &params);
2116 continue;
2117 }
2118 for j in 0..4 {
2119 if bs[j] == 0 {
2120 continue;
2121 }
2122 let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[j]);
2123 if params.alpha == 0 || params.beta == 0 {
2124 continue;
2125 }
2126 for k in 0..4 {
2127 filter_luma_line(
2128 &mut pic.y.data,
2129 base + e * 4 * stride + j * 4 + k,
2130 stride,
2131 &params,
2132 );
2133 }
2134 }
2135 }
2136 }
2137
2138 // ---- chroma (Cb, Cr) ----
2139 for comp in 0..2 {
2140 let (plane, off_sel): (&mut Plane8, fn(&SliceParams) -> i32) = if comp == 0 {
2141 (&mut pic.cb, |s| s.cb_qp_offset)
2142 } else {
2143 (&mut pic.cr, |s| s.cr_qp_offset)
2144 };
2145 let stride = plane.stride;
2146 let base = plane.origin + (mb_y * 8) * stride + mb_x * 8;
2147 // Chroma QP per side: each macroblock's luma QP mapped with
2148 // the offset of ITS OWN slice's PPS (8.7.2).
2149 let cqp = |a: usize| -> i32 {
2150 let s = pic.slices[pic.mb_slice[a] as usize];
2151 if pic.mb_flags[a] & FLAG_PCM != 0 {
2152 chroma_qp(0, off_sel(&s))
2153 } else {
2154 chroma_qp(i32::from(pic.mb_qp[a]), off_sel(&s))
2155 }
2156 };
2157 let cq_q = cqp(addr);
2158 // A chroma edge inherits the boundary strength of the luma edge
2159 // it sits on: chroma sample k maps to luma sample 2k, so a
2160 // chroma 4-sample run spans two luma 4x4 block rows.
2161 for e in 0..2 {
2162 if e == 0 && !filter_left {
2163 continue;
2164 }
2165 let cq_p = if e == 0 { cqp(addr - 1) } else { cq_q };
2166 let qp_avg = (cq_p + cq_q + 1) >> 1;
2167 for k in 0..8 {
2168 let bs = bs_v[e * 2][k / 2];
2169 if bs == 0 {
2170 continue;
2171 }
2172 let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs);
2173 if params.alpha == 0 || params.beta == 0 {
2174 continue;
2175 }
2176 filter_chroma_line(&mut plane.data, base + k * stride + e * 4, 1, &params);
2177 }
2178 }
2179 for e in 0..2 {
2180 if e == 0 && !filter_top {
2181 continue;
2182 }
2183 let cq_p = if e == 0 { cqp(addr - mb_w) } else { cq_q };
2184 let qp_avg = (cq_p + cq_q + 1) >> 1;
2185 for k in 0..8 {
2186 let bs = bs_h[e * 2][k / 2];
2187 if bs == 0 {
2188 continue;
2189 }
2190 let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs);
2191 if params.alpha == 0 || params.beta == 0 {
2192 continue;
2193 }
2194 filter_chroma_line(
2195 &mut plane.data,
2196 base + e * 4 * stride + k,
2197 stride,
2198 &params,
2199 );
2200 }
2201 }
2202 }
2203 }
2204 }
2205}
2206
2207/// Boundary strength of one 4-sample luma edge segment (clause 8.7.2.1).
2208///
2209/// `edge` 0..4 selects the vertical (`vertical`) or horizontal edge inside the
2210/// macroblock, `seg` the 4-sample run along it. Edge 0 is the macroblock edge.
2211fn boundary_strength(
2212 pic: &Picture,
2213 mb_x: usize,
2214 mb_y: usize,
2215 edge: usize,
2216 seg: usize,
2217 vertical: bool,
2218) -> u8 {
2219 let w4 = pic.mb_w * 4;
2220 let (qbx, qby) = if vertical {
2221 (mb_x * 4 + edge, mb_y * 4 + seg)
2222 } else {
2223 (mb_x * 4 + seg, mb_y * 4 + edge)
2224 };
2225 let (pbx, pby) = if vertical {
2226 (qbx - 1, qby)
2227 } else {
2228 (qbx, qby - 1)
2229 };
2230 let q = qby * w4 + qbx;
2231 let p = pby * w4 + pbx;
2232 let mb_edge = edge == 0;
2233 let q_mb = (qby / 4) * pic.mb_w + qbx / 4;
2234 let p_mb = (pby / 4) * pic.mb_w + pbx / 4;
2235 let intra = pic.mb_flags[q_mb] & FLAG_INTER == 0 || pic.mb_flags[p_mb] & FLAG_INTER == 0;
2236 if intra {
2237 return if mb_edge { 4 } else { 3 };
2238 }
2239 if pic.nz_y[p] != 0 || pic.nz_y[q] != 0 {
2240 return 2;
2241 }
2242 let (pr, qr) = (pic.ref_id[p], pic.ref_id[q]);
2243 let pn = u8::from(pr[0] >= 0) + u8::from(pr[1] >= 0);
2244 let qn = u8::from(qr[0] >= 0) + u8::from(qr[1] >= 0);
2245 if pn != qn {
2246 return 1;
2247 }
2248 let (pm, qm) = (pic.mv[p], pic.mv[q]);
2249 let differs = |a: [i16; 2], b: [i16; 2]| {
2250 (i32::from(a[0]) - i32::from(b[0])).abs() >= 4
2251 || (i32::from(a[1]) - i32::from(b[1])).abs() >= 4
2252 };
2253 if pn == 1 {
2254 let pl = usize::from(pr[0] < 0);
2255 let ql = usize::from(qr[0] < 0);
2256 if pr[pl] != qr[ql] {
2257 return 1;
2258 }
2259 return u8::from(differs(pm[pl], qm[ql]));
2260 }
2261 if pn == 0 {
2262 return 0;
2263 }
2264 // Two motion vectors each: compare the two partitions by which pictures
2265 // they reference, not by list position (NOTE 1 of 8.7.2.1).
2266 let same_set = (pr[0] == qr[0] && pr[1] == qr[1]) || (pr[0] == qr[1] && pr[1] == qr[0]);
2267 if !same_set {
2268 return 1;
2269 }
2270 if pr[0] != pr[1] {
2271 return if pr[0] == qr[0] {
2272 u8::from(differs(pm[0], qm[0]) || differs(pm[1], qm[1]))
2273 } else {
2274 u8::from(differs(pm[0], qm[1]) || differs(pm[1], qm[0]))
2275 };
2276 }
2277 // Both lists name the same picture: either pairing agreeing is enough.
2278 let straight = !differs(pm[0], qm[0]) && !differs(pm[1], qm[1]);
2279 let crossed = !differs(pm[0], qm[1]) && !differs(pm[1], qm[0]);
2280 u8::from(!(straight || crossed))
2281}