forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust378.6 MiBabd41b6Tahinli3 months ago75 commits

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