forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe63caffTahinli3 months ago103 commits

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