forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

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