forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB98eeb6cTahinli3 months ago90 commits

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