forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB6828b15Tahinli3 months ago393 commits

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