forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

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