forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB70849e0Tahinli2 months ago3122 commits

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