forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

decoder.rs5051 lines, 180.6 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::{Interlace, 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::{chroma_qp, edge_params, filter_chroma_line, filter_luma_line};
34use crate::dpb::{
35 BLK_DIRECT, BLK_INTRA, BLK_SKIP, BOTTOM, CODED_AFRM, CODED_FLD, Dpb, FRAME, Mark, NO_SLICE,
36 PicInfo, PicPlane, Picture, RefList, SliceParams, TOP,
37};
38use crate::entropy::{
39 BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM,
40 FLAG_SKIP, FLAG_TRANS8X8, MbCtx, MbInfo, MbaffA,
41};
42use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma};
43use crate::mbaff::{self, MbPos};
44use crate::mv::{
45 B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, neighbour_mvd,
46 predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd,
47};
48use crate::pred::{
49 Nbr4, Nbr8, PlaneWindow, add_residual_4x4, add_residual_8x8, add_residual_dpcm, filter_nbr8,
50 pred_4x4, pred_8x8, pred_16x16, pred_chroma_8x8_halves, pred_chroma_8x16,
51};
52use crate::sample::Sample;
53use crate::tables::BLK4_POS;
54use crate::transform::{
55 CHROMA_DC_422_RASTER, LevelScale4x4, LevelScale8x8, chroma_dc_transform_420,
56 chroma_dc_transform_422, dequant_4x4, dequant_8x8, inverse_transform_4x4,
57 inverse_transform_8x8, luma_dc_transform, unfield, unfield_8x8, unfield_ac15, unzigzag,
58 unzigzag_8x8, 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/// The decode core, generic over the sample type of the pictures it holds.
108pub(crate) struct Core<S: Sample> {
109 sps_map: Vec<Option<Sps>>,
110 pps_map: Vec<Option<Pps>>,
111 rbsp: Vec<u8>,
112 /// The picture being decoded, held out of the buffer pool.
113 cur: Picture<S>,
114 dpb: Dpb<S>,
115 has_picture: bool,
116 /// Identity of the open picture, from its first slice's header.
117 cur_key: Option<PicKey>,
118 /// `first_mb_in_slice` of the most recent slice of the open picture.
119 /// Scaling factors of the active PPS/SPS, `[intra, inter][Y, Cb, Cr]`.
120 ls: [[LevelScale4x4; 3]; 2],
121 /// The same for the 8x8 transform, `[intra, inter][Y, Cb, Cr]` (only 4:4:4
122 /// has an 8x8 chroma transform).
123 ls8: [[LevelScale8x8; 3]; 2],
124 /// Which colour plane this core decodes when the stream codes the three
125 /// planes separately (`separate_colour_plane_flag`): 0 Y, 1 Cb, 2 Cr. The
126 /// scaling lists of that plane stand in for the luma ones (8.5.9).
127 plane_id: u8,
128 /// Accept sample depths up to 14 bits ([`Decoder::set_wide_samples`]).
129 wide: bool,
130 active_pps: Option<u32>,
131 /// `seq_parameter_set_id` of the most recently stored SPS, so a container
132 /// entry path can publish the picture size before the first slice.
133 last_sps: Option<u8>,
134 /// Clause 8.2 view of the open picture, from its first slice header.
135 cur_info: PicInfo,
136 /// `dec_ref_pic_marking( )` of the open picture, kept in place so a
137 /// steady-state loop does not reallocate its MMCO list.
138 cur_marking: DecRefPicMarking,
139 has_marking: bool,
140 /// Identity of the picture `end_picture` completed most recently.
141 last_decoded: i32,
142 output_order: OutputOrder,
143 out: VecDeque<VideoFrame>,
144 /// Bits parsed so far, by syntax class (CABAC slices only).
145 account: BitAccount,
146 shapes: MbShapes,
147 /// Presentation timestamp to attach to the next picture started.
148 pending_pts: Option<Timestamp>,
149 /// `PicOrderCnt` of the random-access point most recently established by
150 /// [`Decoder::reset_pictures`] — the first picture decoded after it,
151 /// i.e. the I picture a seek landed on. `None` before that picture
152 /// completes. Absent a recovery_point SEI (not parsed here), D.2.8's
153 /// recovery point defaults to this picture itself: anything with a
154 /// smaller POC that had to guess a reference (see `cur_ref_padded`)
155 /// predicts from something never decoded since the seek and must not
156 /// reach the caller.
157 recovery_poc: Option<i32>,
158 /// Set while decoding the open picture if `build_ref_lists` had to pad a
159 /// reference list, i.e. this picture asked for a reference the DPB does
160 /// not have. Reset per picture in `start_picture`.
161 cur_ref_padded: bool,
162}
163
164/// Streaming H.264 decoder (monochrome, 4:2:0, 4:2:2 and 4:4:4, 8 to 10
165/// bits, with lossless transform bypass; unsupported features come back as
166/// named [`Error::Unsupported`] values, never wrong pixels).
167///
168/// 8-bit streams decode into 8-bit planes and come out as `I420` (`I422` for
169/// 4:2:2, `I444` for 4:4:4); 9- and 10-bit streams decode into 16-bit planes
170/// and come out as `I010` (`I210`, `I410`): 16-bit little-endian samples, the
171/// formats the HEVC Main 10 decoder produces. Monochrome leaves as 4:2:0 with
172/// neutral chroma, and a stream with `separate_colour_plane_flag` as 4:4:4,
173/// its three colour planes decoded as independent monochrome sequences. The
174/// choice of sample width is made per slice from the bit depth of the active
175/// SPS.
176pub struct Decoder {
177 c8: Core<u8>,
178 c16: Core<u16>,
179 /// Cores for colour planes 1 and 2 of a `separate_colour_plane_flag`
180 /// stream: each colour plane is an independent monochrome picture
181 /// sequence, merged into one 4:4:4 frame on output.
182 x8: [Core<u8>; 2],
183 x16: [Core<u16>; 2],
184 /// The core the open picture belongs to.
185 hbd: bool,
186}
187
188impl Default for Decoder {
189 fn default() -> Self {
190 Decoder::new()
191 }
192}
193
194impl Decoder {
195 /// A fresh decoder with no parameter sets.
196 pub fn new() -> Decoder {
197 let mut d = Decoder {
198 c8: Core::new(),
199 c16: Core::new(),
200 x8: [Core::new(), Core::new()],
201 x16: [Core::new(), Core::new()],
202 hbd: false,
203 };
204 for i in 0..2 {
205 d.x8[i].plane_id = i as u8 + 1;
206 d.x16[i].plane_id = i as u8 + 1;
207 }
208 d
209 }
210
211 /// Accept High 4:4:4 Predictive streams of up to 14 bits per sample (the
212 /// JVT conformance streams use 14). Frames then carry the samples at their
213 /// native depth in 16-bit little-endian words inside `I410`/`I010`
214 /// containers, which only describe 10 bits, so this is for conformance
215 /// tooling and off by default: without it deeper streams are refused.
216 pub fn set_wide_samples(&mut self, wide: bool) {
217 self.c8.wide = wide;
218 self.c16.wide = wide;
219 for i in 0..2 {
220 self.x8[i].wide = wide;
221 self.x16[i].wide = wide;
222 }
223 }
224
225 /// Choose between display order (the default) and decode order.
226 pub fn set_output_order(&mut self, order: OutputOrder) {
227 self.c8.set_output_order(order);
228 self.c16.set_output_order(order);
229 for i in 0..2 {
230 self.x8[i].set_output_order(order);
231 self.x16[i].set_output_order(order);
232 }
233 }
234
235 /// The order pictures are handed back in.
236 pub fn output_order(&self) -> OutputOrder {
237 self.c8.output_order()
238 }
239
240 /// Attach `pts` to the next picture started, so a presentation timestamp
241 /// follows its picture through reordering instead of staying with the
242 /// packet that carried it.
243 pub fn set_next_pts(&mut self, pts: Option<Timestamp>) {
244 self.c8.set_next_pts(pts);
245 self.c16.set_next_pts(pts);
246 for i in 0..2 {
247 self.x8[i].set_next_pts(pts);
248 self.x16[i].set_next_pts(pts);
249 }
250 }
251
252 /// Cropped picture size of the most recently stored SPS, `None` until one
253 /// arrives. Lets a container entry path fill in stream parameters from an
254 /// `avcC` record without decoding a picture first.
255 pub fn picture_size(&self) -> Option<(u32, u32)> {
256 self.c8.picture_size()
257 }
258
259 /// Pixel format of the frames the most recently stored SPS produces: `I420`
260 /// at 8 bits, `I010` above.
261 pub fn picture_format(&self) -> Option<PixelFormat> {
262 let sps = self.c8.sps_map[self.c8.last_sps? as usize].as_ref()?;
263 let high = sps.bit_depth_luma > 8 || sps.bit_depth_chroma > 8;
264 // Monochrome leaves as 4:2:0 with neutral chroma; separate colour
265 // planes are merged into 4:4:4.
266 let wide = if sps.separate_colour_plane {
267 3
268 } else {
269 sps.chroma_format_idc
270 };
271 Some(match (wide, high) {
272 (3, false) => PixelFormat::I444,
273 (3, true) => PixelFormat::I410,
274 (2, false) => PixelFormat::I422,
275 (2, true) => PixelFormat::I210,
276 (_, false) => PixelFormat::I420,
277 (_, true) => PixelFormat::I010,
278 })
279 }
280
281 /// Where the bits of every CABAC slice parsed so far went, by syntax
282 /// class, in 1/256ths of a bit.
283 pub fn bit_account(&self) -> BitAccount {
284 if self.hbd {
285 self.c16.bit_account()
286 } else {
287 self.c8.bit_account()
288 }
289 }
290
291 /// How many macroblocks of each shape this decoder has read.
292 pub fn mb_shapes(&self) -> MbShapes {
293 if self.hbd {
294 self.c16.mb_shapes()
295 } else {
296 self.c8.mb_shapes()
297 }
298 }
299
300 /// Decode the first IDR picture of an Annex B stream and return it.
301 pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> {
302 let mut got_slice = false;
303 // An IDR picture that is a field is only half a frame: the second
304 // field of the pair is decoded too.
305 let mut fields_done = false;
306 for nal in AnnexBIter::new(annexb) {
307 match self.push_nal(nal)? {
308 NalOutcome::PictureBoundary => {
309 if fields_done || !got_slice {
310 break;
311 }
312 self.end_picture()?;
313 if !self.awaiting_second_field() {
314 // The IDR picture was a whole frame.
315 return self.frame();
316 }
317 fields_done = true;
318 got_slice = false;
319 if let NalOutcome::SliceDecoded = self.push_nal(nal)? {
320 got_slice = true;
321 }
322 }
323 NalOutcome::SliceDecoded => got_slice = true,
324 _ => {}
325 }
326 }
327 if !got_slice {
328 if fields_done {
329 // The stream ended after the first field.
330 return self.frame();
331 }
332 return Err(Error::NeedMore);
333 }
334 self.end_picture()?;
335 self.frame()
336 }
337
338 /// Feed one NAL unit (header byte first, no start code).
339 pub fn push_nal(&mut self, nal: &[u8]) -> Result<NalOutcome> {
340 let is_slice = nal.first().is_some_and(|b| matches!(b & 0x1f, 1 | 5));
341 if !is_slice {
342 // Parameter sets are kept by both cores: which one a slice runs
343 // on depends on the SPS it names, known only at the slice.
344 let mut r = self.c8.push_nal(nal).and(self.c16.push_nal(nal));
345 for i in 0..2 {
346 r = r
347 .and(self.x8[i].push_nal(nal))
348 .and(self.x16[i].push_nal(nal));
349 }
350 return r;
351 }
352 let mut plane = 0usize;
353 if let Some((depth, cp)) = self.c8.slice_route(nal) {
354 plane = usize::from(cp);
355 let hbd = depth > 8;
356 if hbd != self.hbd {
357 // The bit depth changed: finish whatever the old core had open
358 // so its pictures are queued, then switch.
359 self.flush()?;
360 self.hbd = hbd;
361 }
362 }
363 match (self.hbd, plane) {
364 (true, 0) => self.c16.push_nal(nal),
365 (true, p) => self.x16[p - 1].push_nal(nal),
366 (false, 0) => self.c8.push_nal(nal),
367 (false, p) => self.x8[p - 1].push_nal(nal),
368 }
369 }
370
371 /// Run the deblocking filter over the open picture, store it in the decoded
372 /// picture buffer and queue whatever pictures that makes ready for output.
373 pub fn end_picture(&mut self) -> Result<()> {
374 // Every colour plane's picture ends together; planes that never
375 // opened one (the usual case) are skipped.
376 if self.hbd {
377 if self.x16.iter().all(|c| !c.picture_open()) {
378 return self.c16.end_picture();
379 }
380 let mut r = Ok(());
381 if self.c16.picture_open() {
382 r = self.c16.end_picture();
383 }
384 for c in self.x16.iter_mut().filter(|c| c.picture_open()) {
385 r = r.and(c.end_picture());
386 }
387 r
388 } else {
389 if self.x8.iter().all(|c| !c.picture_open()) {
390 return self.c8.end_picture();
391 }
392 let mut r = Ok(());
393 if self.c8.picture_open() {
394 r = self.c8.end_picture();
395 }
396 for c in self.x8.iter_mut().filter(|c| c.picture_open()) {
397 r = r.and(c.end_picture());
398 }
399 r
400 }
401 }
402
403 /// Emit every remaining picture (end of stream).
404 pub fn flush(&mut self) -> Result<()> {
405 self.c8.flush()?;
406 self.c16.flush()?;
407 for i in 0..2 {
408 self.x8[i].flush()?;
409 self.x16[i].flush()?;
410 }
411 Ok(())
412 }
413
414 /// The next frame ready for output, in the configured order.
415 pub fn next_frame(&mut self) -> Option<VideoFrame> {
416 // The core that is not running holds the older pictures.
417 if self.hbd {
418 if let Some(f) = self.c8.next_frame() {
419 return Some(f);
420 }
421 let f = self.c16.next_frame()?;
422 Some(merge_planes(
423 f,
424 self.x16[0].next_frame(),
425 self.x16[1].next_frame(),
426 ))
427 } else {
428 if let Some(f) = self.c16.next_frame() {
429 return Some(f);
430 }
431 let f = self.c8.next_frame()?;
432 Some(merge_planes(
433 f,
434 self.x8[0].next_frame(),
435 self.x8[1].next_frame(),
436 ))
437 }
438 }
439
440 /// The picture `end_picture` completed most recently, in decode order.
441 pub fn frame(&self) -> Result<VideoFrame> {
442 if self.hbd {
443 let f = self.c16.frame()?;
444 Ok(merge_planes(
445 f,
446 self.x16[0].frame().ok(),
447 self.x16[1].frame().ok(),
448 ))
449 } else {
450 let f = self.c8.frame()?;
451 Ok(merge_planes(
452 f,
453 self.x8[0].frame().ok(),
454 self.x8[1].frame().ok(),
455 ))
456 }
457 }
458
459 /// True when the picture just completed is a first field whose second
460 /// field has not arrived.
461 fn awaiting_second_field(&self) -> bool {
462 if self.hbd {
463 self.c16.awaiting_second_field()
464 } else {
465 self.c8.awaiting_second_field()
466 }
467 }
468
469 /// True while a picture is open (started, not completed).
470 pub fn picture_open(&self) -> bool {
471 if self.hbd {
472 self.c16.picture_open() || self.x16.iter().any(|c| c.picture_open())
473 } else {
474 self.c8.picture_open() || self.x8.iter().any(|c| c.picture_open())
475 }
476 }
477
478 /// Drop picture state after a seek. Parameter sets survive.
479 pub fn reset_pictures(&mut self) {
480 self.c8.reset_pictures();
481 self.c16.reset_pictures();
482 for i in 0..2 {
483 self.x8[i].reset_pictures();
484 self.x16[i].reset_pictures();
485 }
486 }
487}
488
489/// Join the monochrome frames of colour planes 1 and 2 to the one of plane 0
490/// as a 4:4:4 frame. A frame that is not part of a separate-plane stream (the
491/// other planes returned nothing) leaves as it is.
492fn merge_planes(f0: VideoFrame, f1: Option<VideoFrame>, f2: Option<VideoFrame>) -> VideoFrame {
493 let (Some(f1), Some(f2)) = (f1, f2) else {
494 return f0;
495 };
496 let format = match f0.format {
497 PixelFormat::I420 => PixelFormat::I444,
498 PixelFormat::I010 => PixelFormat::I410,
499 _ => return f0,
500 };
501 let planes = vec![
502 f0.planes[0].clone(),
503 f1.planes[0].clone(),
504 f2.planes[0].clone(),
505 ];
506 match VideoFrame::try_new(format, f0.width, f0.height, planes) {
507 Ok(mut f) => {
508 f.color = f0.color;
509 f.pts = f0.pts;
510 f.interlace = f0.interlace;
511 f
512 }
513 Err(_) => f0,
514 }
515}
516
517impl<S: Sample> Core<S> {
518 /// Bit depth named by the SPS of the slice in `nal`, `None` when the slice
519 /// or its parameter sets cannot be read (the core then reports the error).
520 pub(crate) fn slice_route(&mut self, nal: &[u8]) -> Option<(u8, u8)> {
521 let (_, payload) = nal.split_first()?;
522 let n = payload.len().min(16);
523 // The scratch buffer the slice path uses anyway, so a steady-state
524 // loop allocates nothing here.
525 let mut rbsp = core::mem::take(&mut self.rbsp);
526 unescape_rbsp(&payload[..n], &mut rbsp);
527 let mut peek = BitReader::new(&rbsp);
528 let ids = (|| {
529 Some((
530 peek.read_ue().ok()?,
531 peek.read_ue().ok()?,
532 peek.read_ue().ok()?,
533 ))
534 })();
535 let (_, _, pps_id) = ids?;
536 let pps = self.pps_map.get(pps_id as usize)?.as_ref()?;
537 let sps = self.sps_map.get(pps.sps_id as usize)?.as_ref()?;
538 let plane = if sps.separate_colour_plane {
539 // colour_plane_id u(2) follows pic_parameter_set_id.
540 peek.read_bits(2).ok().map_or(0, |v| (v as u8).min(2))
541 } else {
542 0
543 };
544 let depth = if sps.chroma_array_type() == 0 {
545 sps.bit_depth_luma
546 } else {
547 sps.bit_depth_luma.max(sps.bit_depth_chroma)
548 };
549 self.rbsp = rbsp;
550 Some((depth, plane))
551 }
552}
553
554/// What [`Decoder::push_nal`] did with a NAL unit.
555#[derive(Debug, Clone, Copy, PartialEq, Eq)]
556pub enum NalOutcome {
557 /// SPS or PPS stored.
558 ParameterSet,
559 /// Non-VCL NAL skipped (SEI, AUD, filler, ...).
560 Skipped,
561 /// A slice was decoded into the open picture.
562 SliceDecoded,
563 /// The NAL starts a new picture while one is open; it was not consumed.
564 /// Call [`Decoder::end_picture`], then push it again.
565 PictureBoundary,
566}
567
568fn flat_scaling() -> [[LevelScale4x4; 3]; 2] {
569 [
570 [
571 LevelScale4x4::new(&[16; 16]),
572 LevelScale4x4::new(&[16; 16]),
573 LevelScale4x4::new(&[16; 16]),
574 ],
575 [
576 LevelScale4x4::new(&[16; 16]),
577 LevelScale4x4::new(&[16; 16]),
578 LevelScale4x4::new(&[16; 16]),
579 ],
580 ]
581}
582
583impl<S: Sample> Core<S> {
584 /// A fresh decoder with no parameter sets.
585 pub(crate) fn new() -> Core<S> {
586 Core {
587 sps_map: vec![None; 32],
588 pps_map: vec![None; 256],
589 rbsp: Vec::new(),
590 cur: Picture::default(),
591 dpb: Dpb::default(),
592 has_picture: false,
593 cur_key: None,
594 ls: flat_scaling(),
595 ls8: std::array::from_fn(|_| std::array::from_fn(|_| LevelScale8x8::new(&[16; 64]))),
596 plane_id: 0,
597 wide: false,
598 active_pps: None,
599 last_sps: None,
600 cur_info: PicInfo {
601 structure: FRAME,
602 second_of: None,
603 is_idr: false,
604 is_reference: false,
605 frame_num: 0,
606 pic_order_cnt_lsb: 0,
607 delta_pic_order_cnt_bottom: 0,
608 delta_pic_order_cnt: [0; 2],
609 },
610 cur_marking: DecRefPicMarking::default(),
611 has_marking: false,
612 last_decoded: -1,
613 output_order: OutputOrder::default(),
614 out: VecDeque::new(),
615 account: BitAccount::default(),
616 shapes: MbShapes::default(),
617 pending_pts: None,
618 recovery_poc: None,
619 cur_ref_padded: false,
620 }
621 }
622
623 /// Choose between display order (the default) and decode order.
624 pub(crate) fn set_output_order(&mut self, order: OutputOrder) {
625 self.output_order = order;
626 }
627
628 /// The order pictures are handed back in.
629 pub(crate) fn output_order(&self) -> OutputOrder {
630 self.output_order
631 }
632
633 /// Attach `pts` to the next picture started, so a presentation timestamp
634 /// follows its picture through reordering instead of staying with the
635 /// packet that carried it.
636 pub(crate) fn set_next_pts(&mut self, pts: Option<Timestamp>) {
637 self.pending_pts = pts;
638 }
639
640 /// Cropped picture size of the most recently stored SPS, `None` until one
641 /// arrives. Lets a container entry path fill in stream parameters from an
642 /// `avcC` record without decoding a picture first.
643 pub(crate) fn picture_size(&self) -> Option<(u32, u32)> {
644 let sps = self.sps_map[self.last_sps? as usize].as_ref()?;
645 Some((sps.width, sps.height))
646 }
647
648 /// Where the bits of every CABAC slice parsed so far went, by syntax
649 /// class, in 1/256ths of a bit. Any conforming stream can be measured
650 /// this way, so an encoder's spending can be compared with another's
651 /// through one account.
652 pub(crate) fn bit_account(&self) -> BitAccount {
653 self.account
654 }
655
656 /// How many macroblocks of each shape this decoder has read, which is what
657 /// a stream's partitioning looks like from the outside.
658 pub(crate) fn mb_shapes(&self) -> MbShapes {
659 self.shapes
660 }
661
662 /// Feed one NAL unit (header byte first, no start code).
663 pub(crate) fn push_nal(&mut self, nal: &[u8]) -> Result<NalOutcome> {
664 let Some((&header_byte, payload)) = nal.split_first() else {
665 return Err(Error::NeedMore);
666 };
667 let header = NalHeader::parse(header_byte)?;
668 match header.unit_type {
669 NalUnitType::Sps => {
670 let mut rbsp = core::mem::take(&mut self.rbsp);
671 unescape_rbsp(payload, &mut rbsp);
672 let sps = Sps::parse(&rbsp);
673 self.rbsp = rbsp;
674 let sps = sps?;
675 let id = sps.id;
676 self.dpb.configure(&sps);
677 self.sps_map[id as usize] = Some(sps);
678 self.active_pps = None;
679 self.last_sps = Some(id);
680 Ok(NalOutcome::ParameterSet)
681 }
682 NalUnitType::Pps => {
683 let mut rbsp = core::mem::take(&mut self.rbsp);
684 unescape_rbsp(payload, &mut rbsp);
685 let pps = Pps::parse(&rbsp, |id| self.sps_map[id as usize].as_ref());
686 self.rbsp = rbsp;
687 let pps = pps?;
688 let id = pps.id as usize;
689 self.pps_map[id] = Some(pps);
690 // A re-sent PPS may carry other scaling lists: rebuild the level scales.
691 self.active_pps = None;
692 Ok(NalOutcome::ParameterSet)
693 }
694 NalUnitType::Slice | NalUnitType::SliceIdr => {
695 let mut rbsp = core::mem::take(&mut self.rbsp);
696 unescape_rbsp(payload, &mut rbsp);
697 let r = self.decode_slice_rbsp(header, &rbsp);
698 self.rbsp = rbsp;
699 r
700 }
701 NalUnitType::SliceDataA | NalUnitType::SliceDataB | NalUnitType::SliceDataC => {
702 Err(Error::unsupported(
703 "slice data partitioning",
704 "nal_unit_type 2 to 4 carry a slice in three NAL units that \
705 clause 7.4.1 reassembles by slice_id; not implemented",
706 ))
707 }
708 _ => Ok(NalOutcome::Skipped),
709 }
710 }
711
712 /// Run the deblocking filter over the open picture, store it in the decoded
713 /// picture buffer and queue whatever pictures that makes ready for output.
714 pub(crate) fn end_picture(&mut self) -> Result<()> {
715 if !self.has_picture || self.cur.complete {
716 return Err(Error::corrupt("end_picture without an open picture"));
717 }
718 if self.cur.mbaff {
719 crate::deblock_mbaff::deblock_mbaff(&mut self.cur);
720 } else {
721 deblock_picture(&mut self.cur);
722 }
723 self.cur.extend_borders();
724 self.cur.complete = true;
725 self.last_decoded = self.cur.id;
726 // The first picture completed after a reset is the random-access
727 // point the seek landed on; its own POC becomes the recovery
728 // threshold (see `recovery_poc`'s doc comment).
729 let recovery_poc = *self.recovery_poc.get_or_insert(self.cur.poc);
730 let output_ok = !(self.cur_ref_padded && self.cur.poc < recovery_poc);
731 let sps_id = self.cur.sps_id as usize;
732 let sps = self.sps_map[sps_id]
733 .take()
734 .ok_or_else(|| Error::corrupt("active SPS vanished"))?;
735 let pic = core::mem::take(&mut self.cur);
736 let marking = self.has_marking.then_some(&self.cur_marking);
737 let stored = if self.dpb.interlaced {
738 self.dpb
739 .store_i(pic, &sps, &self.cur_info, marking, output_ok)
740 } else {
741 self.dpb
742 .store(pic, &sps, &self.cur_info, marking, output_ok)
743 };
744 self.sps_map[sps_id] = Some(sps);
745 stored?;
746 if self.dpb.interlaced {
747 // The picture a caller asks for is the frame store, which a field
748 // joined or created.
749 self.last_decoded = self.dpb.last_stored_id();
750 }
751 self.has_picture = false;
752 self.pump_output(false)
753 }
754
755 /// Emit every remaining picture (end of stream).
756 pub(crate) fn flush(&mut self) -> Result<()> {
757 if self.has_picture && !self.cur.complete {
758 self.end_picture()?;
759 }
760 self.pump_output(true)
761 }
762
763 /// The next frame ready for output, in the configured order.
764 pub(crate) fn next_frame(&mut self) -> Option<VideoFrame> {
765 self.out.pop_front()
766 }
767
768 /// The picture `end_picture` completed most recently, in decode order.
769 ///
770 /// Kept for a caller that drives one picture at a time; a player wants
771 /// [`Decoder::next_frame`], which respects the reordering the stream asks
772 /// for.
773 pub(crate) fn frame(&self) -> Result<VideoFrame> {
774 let id = self.last_decoded;
775 let pic = self
776 .dpb
777 .frames
778 .iter()
779 .find(|p| p.id == id)
780 .ok_or_else(|| Error::corrupt("frame() before end_picture()"))?;
781 self.picture_to_frame(pic)
782 }
783
784 /// True when the most recently completed picture is a first field.
785 pub(crate) fn awaiting_second_field(&self) -> bool {
786 self.dpb.awaiting_second_field()
787 }
788
789 /// True while a picture is open (started, not completed).
790 pub(crate) fn picture_open(&self) -> bool {
791 self.has_picture && !self.cur.complete
792 }
793
794 /// Drop picture state after a seek. Parameter sets survive, because the
795 /// container does not resend them at every seek point.
796 pub(crate) fn reset_pictures(&mut self) {
797 self.has_picture = false;
798 self.cur.complete = false;
799 self.dpb.clear();
800 self.out.clear();
801 self.last_decoded = -1;
802 self.pending_pts = None;
803 self.recovery_poc = None;
804 }
805
806 /// Move pictures out of the decoded picture buffer into the output queue.
807 fn pump_output(&mut self, flush: bool) -> Result<()> {
808 if self.output_order == OutputOrder::Decode && !flush {
809 let id = self.last_decoded;
810 if let Some(i) = self
811 .dpb
812 .frames
813 .iter()
814 .position(|p| p.id == id && p.output && !p.awaiting_second)
815 {
816 let frame = self.picture_to_frame(&self.dpb.frames[i])?;
817 self.out.push_back(frame);
818 self.dpb.released(i);
819 }
820 return Ok(());
821 }
822 while let Some(i) = self.dpb.next_output(flush) {
823 let frame = self.picture_to_frame(&self.dpb.frames[i])?;
824 self.out.push_back(frame);
825 self.dpb.released(i);
826 }
827 Ok(())
828 }
829
830 /// Copy a stored picture out as a cropped I420 frame.
831 fn picture_to_frame(&self, pic: &Picture<S>) -> Result<VideoFrame> {
832 let (w, h) = (pic.out_size.0 as usize, pic.out_size.1 as usize);
833 let (cx, cy) = (pic.crop.0 as usize, pic.crop.1 as usize);
834 // Above 8 bits the samples leave as 16-bit little-endian words in I010,
835 // left-aligned to 10 bits when the stream is 9-bit.
836 let shift = 10u32.saturating_sub(pic.bd);
837 let copy = |p: &PicPlane<S>, x0: usize, y0: usize, w: usize, h: usize| -> Plane {
838 // Grown row by row rather than allocated zeroed: every byte is
839 // about to be overwritten, and at 1080p the fill it avoids is
840 // three megabytes per frame.
841 let mut out = Vec::with_capacity(w * h * S::BYTES);
842 for row in 0..h {
843 let src = p.at(x0, y0 + row);
844 S::extend_bytes(&mut out, &p.data[src..src + w], shift);
845 }
846 Plane::new(out, w * S::BYTES)
847 };
848 let c422 = pic.cat == 2;
849 let c444 = pic.cat == 3;
850 // 4:2:2 chroma is full height: no vertical halving of the crop origin
851 // or of the plane height; 4:4:4 chroma is full size.
852 let (cy_c, ch_c) = if c422 || c444 {
853 (cy, h)
854 } else {
855 (cy / 2, h.div_ceil(2))
856 };
857 let (cx_c, cw_c) = if c444 {
858 (cx, w)
859 } else {
860 (cx / 2, w.div_ceil(2))
861 };
862 let planes = vec![
863 copy(&pic.y, cx, cy, w, h),
864 copy(&pic.cb, cx_c, cy_c, cw_c, ch_c),
865 copy(&pic.cr, cx_c, cy_c, cw_c, ch_c),
866 ];
867 let mut frame = VideoFrame::try_new(
868 match (pic.cat, S::IS_8) {
869 (3, true) => PixelFormat::I444,
870 (3, false) => PixelFormat::I410,
871 (2, true) => PixelFormat::I422,
872 (2, false) => PixelFormat::I210,
873 (_, true) => PixelFormat::I420,
874 (_, false) => PixelFormat::I010,
875 },
876 w as u32,
877 h as u32,
878 planes,
879 )?;
880 frame.color = pic.color;
881 frame.pts = pic.pts;
882 frame.interlace = if pic.fields.is_empty() {
883 Interlace::Progressive
884 } else {
885 // The field that displays first is the one with the lower order
886 // count (a lone field leaves the other one's count meaningless).
887 let first_is_bottom = match pic.have {
888 [true, false] => false,
889 [false, true] => true,
890 _ => pic.fpoc[1] < pic.fpoc[0],
891 };
892 if first_is_bottom {
893 Interlace::BottomFieldFirst
894 } else {
895 Interlace::TopFieldFirst
896 }
897 };
898 Ok(frame)
899 }
900
901 fn decode_slice_rbsp(&mut self, header: NalHeader, rbsp: &[u8]) -> Result<NalOutcome> {
902 // Peek first_mb / slice_type / pps_id to select parameter sets.
903 let mut peek = BitReader::new(rbsp);
904 let first_mb = peek.read_ue()?;
905 let slice_type_code = peek.read_ue()?;
906 let pps_id = peek.read_ue()?;
907 if pps_id > 255 {
908 return Err(Error::corrupt("pic_parameter_set_id > 255"));
909 }
910 let pps = self.pps_map[pps_id as usize]
911 .as_ref()
912 .ok_or_else(|| Error::corrupt("slice refers to an unknown PPS"))?;
913 let sps = self.sps_map[pps.sps_id as usize]
914 .as_ref()
915 .ok_or_else(|| Error::corrupt("PPS refers to an unknown SPS"))?;
916
917 check_supported::<S>(sps, pps, slice_type_code, self.wide)?;
918 let sh = SliceHeader::parse(rbsp, header, sps, pps)?;
919 if self.has_picture && !self.cur.complete {
920 let same_picture = self.cur_key == Some(PicKey::of(&sh, header));
921 // A picture starts again at macroblock 0 once macroblock 0 is
922 // already decoded; with ASO (clause 7.4.3) the slice holding
923 // macroblock 0 may also arrive after the others.
924 if self.cur.decoded_mbs > 0
925 && (!same_picture || (first_mb == 0 && self.cur.mb_slice[0] != NO_SLICE))
926 {
927 return Ok(NalOutcome::PictureBoundary);
928 }
929 }
930 if sh.redundant_pic_cnt > 0 {
931 // Redundant coded slices (7.4.3) repeat primary data: ignored.
932 return Ok(NalOutcome::Skipped);
933 }
934 // Borrow the parameter sets out of their slots for the duration of the
935 // slice: cloning them per slice would allocate, and a decode loop that
936 // allocates per slice is the thing the whole layout is built to avoid.
937 let sps_slot = pps.sps_id as usize;
938 let sps = self.sps_map[sps_slot].take().expect("checked above");
939 let pps = self.pps_map[pps_id as usize].take().expect("checked above");
940 let outcome = self.decode_slice_data(&sps, &pps, &sh, header, rbsp, first_mb);
941 self.sps_map[sps_slot] = Some(sps);
942 self.pps_map[pps_id as usize] = Some(pps);
943 outcome
944 }
945
946 #[allow(clippy::too_many_arguments)]
947 fn decode_slice_data(
948 &mut self,
949 sps: &Sps,
950 pps: &Pps,
951 sh: &SliceHeader,
952 header: NalHeader,
953 rbsp: &[u8],
954 first_mb: u32,
955 ) -> Result<NalOutcome> {
956 if !self.has_picture || self.cur.complete {
957 self.start_picture(sps, pps, sh, header)?;
958 self.cur_key = Some(PicKey::of(sh, header));
959 }
960 if self.cur.sps_id != sps.id {
961 return Err(Error::corrupt("SPS changed mid-picture"));
962 }
963 if self.cur.slices.len() >= usize::from(u16::MAX) {
964 return Err(Error::corrupt("more than 65534 slices in a picture"));
965 }
966 let slice_id = self.cur.slices.len() as u16;
967 self.cur.slices.push(SliceParams {
968 disable_deblock_idc: sh.deblock.disable_idc,
969 alpha_offset: sh.deblock.alpha_c0_offset,
970 beta_offset: sh.deblock.beta_offset,
971 cb_qp_offset: pps.chroma_qp_index_offset,
972 cr_qp_offset: pps.second_chroma_qp_index_offset,
973 });
974
975 // Reference picture lists (clause 8.2.4), rebuilt per slice because
976 // num_ref_idx_active and the modification list are slice header state.
977 let lists = if sh.slice_type.is_intra() {
978 [RefList::default(), RefList::default()]
979 } else {
980 let (lists, padded) = if self.dpb.interlaced {
981 // 8.2.4.1: a field counts picture numbers per field.
982 let (curr_pic_num, max_pic_num) = if sh.field_pic {
983 (2 * sh.frame_num as i32 + 1, 2i32 << sps.log2_max_frame_num)
984 } else {
985 (sh.frame_num as i32, 1i32 << sps.log2_max_frame_num)
986 };
987 self.dpb.number_short_term_i(sh.frame_num, sps);
988 self.dpb.build_ref_lists_i(
989 sh.slice_type,
990 self.cur.structure,
991 self.cur.poc,
992 curr_pic_num,
993 max_pic_num,
994 sh.num_ref_idx_l0_active as usize,
995 sh.num_ref_idx_l1_active as usize,
996 (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1),
997 )?
998 } else {
999 let max_pic_num = 1i32 << sps.log2_max_frame_num;
1000 self.dpb.number_short_term(sh.frame_num, sps);
1001 self.dpb.build_ref_lists(
1002 sh.slice_type,
1003 self.cur.poc,
1004 sh.frame_num as i32,
1005 max_pic_num,
1006 sh.num_ref_idx_l0_active as usize,
1007 sh.num_ref_idx_l1_active as usize,
1008 (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1),
1009 )?
1010 };
1011 // A ref list shorter than requested was padded by repeating an
1012 // available entry (8.2.4.2's unspecified tail) rather than the
1013 // reference this slice actually asked for. Right after a seek's
1014 // reset, that means the picture predicts from something never
1015 // decoded since the random-access start; recorded here so
1016 // `end_picture` can hold its output back (see `recovery_poc`).
1017 self.cur_ref_padded |= padded;
1018 lists
1019 };
1020
1021 let mut r = if pps.entropy_coding_mode {
1022 let column = if sh.slice_type.is_intra() {
1023 0
1024 } else {
1025 sh.cabac_init_idc as usize + 1
1026 };
1027 Entropy::cabac(rbsp, sh.header_bits, sh.slice_qp, column)?
1028 } else {
1029 Entropy::cavlc(rbsp, sh.header_bits)
1030 };
1031
1032 let mut ctx = SliceCtx {
1033 shapes: MbShapes::default(),
1034 slice_id,
1035 slice_type: sh.slice_type,
1036 qp: sh.slice_qp,
1037 cb_qp_offset: pps.chroma_qp_index_offset,
1038 cr_qp_offset: pps.second_chroma_qp_index_offset,
1039 cmb_h: self.cur.cmb_h,
1040 cat: self.cur.cat,
1041 transform_8x8_mode: pps.transform_8x8_mode,
1042 constrained_intra_pred: pps.constrained_intra_pred,
1043 qp_delta_inc: 0,
1044 lists,
1045 num_ref_idx: [
1046 sh.num_ref_idx_l0_active as usize,
1047 sh.num_ref_idx_l1_active as usize,
1048 ],
1049 direct_spatial: sh.direct_spatial_mv_pred,
1050 direct_8x8_inference: sps.direct_8x8_inference,
1051 weighted_pred: pps.weighted_pred,
1052 weighted_bipred_idc: pps.weighted_bipred_idc,
1053 weights: sh.pred_weight_table.clone(),
1054 poc: self.cur.poc,
1055 fpoc: self.cur.fpoc,
1056 structure: self.cur.structure,
1057 mb_parity: self.cur.structure,
1058 pos: MbPos::default(),
1059 };
1060 let intra_slice = sh.slice_type.is_intra();
1061 let b_slice = sh.slice_type == SliceType::B;
1062 if !intra_slice && ctx.lists[0].len() == 0 {
1063 return Err(Error::corrupt("inter slice with no reference pictures"));
1064 }
1065
1066 let mbs = self.cur.mb_w * self.cur.mb_h;
1067 if self.cur.mbaff {
1068 self.decode_mbaff_slice(
1069 &mut r,
1070 &mut ctx,
1071 first_mb as usize * 2,
1072 pps.entropy_coding_mode,
1073 )?;
1074 self.shapes.add(&ctx.shapes);
1075 if let Entropy::Cabac(c) = &r {
1076 self.account.add(&c.account());
1077 }
1078 return Ok(NalOutcome::SliceDecoded);
1079 }
1080 let groups = if pps.num_slice_groups > 1 {
1081 crate::fmo::mb_to_slice_group(sps, pps, sh.slice_group_change_cycle)
1082 } else {
1083 None
1084 };
1085 let step = |a: usize| match &groups {
1086 Some(g) => crate::fmo::next_in_group(g, a),
1087 None => a + 1,
1088 };
1089 let mut mb_addr = first_mb as usize;
1090 let mut more = true;
1091 while more {
1092 if mb_addr >= mbs {
1093 return Err(Error::corrupt("macroblock address beyond the picture"));
1094 }
1095 let mut decode_mb = true;
1096 if !intra_slice {
1097 if r.is_cabac() {
1098 self.begin_mb(&mut r, &ctx, mb_addr);
1099 let inc = self.skip_inc(&ctx, mb_addr);
1100 if r.mb_skip_flag(b_slice, inc)? {
1101 decode_macroblock(
1102 &mut self.cur,
1103 &self.dpb.frames,
1104 &self.ls,
1105 &self.ls8,
1106 &mut r,
1107 &mut ctx,
1108 mb_addr,
1109 true,
1110 )?;
1111 decode_mb = false;
1112 }
1113 } else {
1114 let run = r.mb_skip_run()?;
1115 for _ in 0..run {
1116 if mb_addr >= mbs {
1117 return Err(Error::corrupt("mb_skip_run past the picture"));
1118 }
1119 decode_macroblock(
1120 &mut self.cur,
1121 &self.dpb.frames,
1122 &self.ls,
1123 &self.ls8,
1124 &mut r,
1125 &mut ctx,
1126 mb_addr,
1127 true,
1128 )?;
1129 mb_addr = step(mb_addr);
1130 }
1131 if run > 0 {
1132 more = r.more_macroblocks()?;
1133 if !more {
1134 break;
1135 }
1136 if mb_addr >= mbs {
1137 return Err(Error::corrupt("macroblock address beyond the picture"));
1138 }
1139 }
1140 }
1141 }
1142 if decode_mb {
1143 decode_macroblock(
1144 &mut self.cur,
1145 &self.dpb.frames,
1146 &self.ls,
1147 &self.ls8,
1148 &mut r,
1149 &mut ctx,
1150 mb_addr,
1151 false,
1152 )?;
1153 }
1154 more = r.more_macroblocks()?;
1155 mb_addr = step(mb_addr);
1156 }
1157 self.shapes.add(&ctx.shapes);
1158 if let Entropy::Cabac(c) = &r {
1159 self.account.add(&c.account());
1160 }
1161 Ok(NalOutcome::SliceDecoded)
1162 }
1163
1164 /// Point `ctx` at macroblock `mb_addr` (syntax order, `2 * pair + b`) of an
1165 /// MBAFF frame in the given frame/field mode; returns its slot.
1166 fn mbaff_enter(&self, ctx: &mut SliceCtx, mb_addr: usize, field: bool) -> usize {
1167 let w = self.cur.mb_w;
1168 let pair = mb_addr >> 1;
1169 let (px, pr) = (pair % w, pair / w);
1170 let b = mb_addr & 1;
1171 ctx.pos = MbPos {
1172 active: true,
1173 px,
1174 slot_y: 2 * pr + b,
1175 field,
1176 slice_id: ctx.slice_id,
1177 };
1178 ctx.mb_parity = if !field {
1179 FRAME
1180 } else if b == 1 {
1181 BOTTOM
1182 } else {
1183 TOP
1184 };
1185 (2 * pr + b) * w + px
1186 }
1187
1188 /// ctxIdxInc of mb_field_decoding_flag (9.3.3.1.1.2): the left and above
1189 /// macroblock pairs of the same slice that are field pairs.
1190 fn field_flag_inc(&self, ctx: &SliceCtx, mb_addr: usize) -> usize {
1191 let pic = &self.cur;
1192 let w = pic.mb_w;
1193 let pair = mb_addr >> 1;
1194 let (px, pr) = (pair % w, pair / w);
1195 let is_field = |x: usize, y: usize| {
1196 let t = (2 * y) * w + x;
1197 usize::from(pic.mb_slice[t] == ctx.slice_id && pic.mb_field[t] != 0)
1198 };
1199 (if px > 0 { is_field(px - 1, pr) } else { 0 })
1200 + (if pr > 0 { is_field(px, pr - 1) } else { 0 })
1201 }
1202
1203 /// The slice data loop of an MBAFF frame (7.3.4): macroblock pairs, the
1204 /// per-pair `mb_field_decoding_flag`, and the skipped-top-macroblock
1205 /// cases in which the flag arrives with the bottom macroblock.
1206 fn decode_mbaff_slice(
1207 &mut self,
1208 r: &mut Entropy<'_>,
1209 ctx: &mut SliceCtx,
1210 first_addr: usize,
1211 cabac: bool,
1212 ) -> Result<()> {
1213 let intra_slice = ctx.slice_type.is_intra();
1214 let b_slice = ctx.is_b();
1215 let mbs = self.cur.mb_w * self.cur.mb_h;
1216 let w = self.cur.mb_w;
1217 let mut mb_addr = first_addr;
1218 let mut more = true;
1219 macro_rules! decode {
1220 ($slot:expr, $skipped:expr) => {
1221 decode_macroblock(
1222 &mut self.cur,
1223 &self.dpb.frames,
1224 &self.ls,
1225 &self.ls8,
1226 r,
1227 ctx,
1228 $slot,
1229 $skipped,
1230 )?
1231 };
1232 }
1233 // The frame/field mode of the pair being decoded, once known.
1234 let mut pair_field = false;
1235 if cabac {
1236 // CABAC codes pairs: at most two macroblocks between end_of_slice
1237 // flags, with the top-skipped case reordered.
1238 if !mb_addr.is_multiple_of(2) {
1239 return Err(Error::corrupt("MBAFF slice starts at a bottom macroblock"));
1240 }
1241 while more {
1242 if mb_addr + 1 >= mbs {
1243 return Err(Error::corrupt("macroblock address beyond the picture"));
1244 }
1245 let pair = mb_addr >> 1;
1246 let (px, pr) = (pair % w, pair / w);
1247 let inferred = mbaff::infer_field(&self.cur, px, pr, ctx.slice_id);
1248 let top_slot = self.mbaff_enter(ctx, mb_addr, inferred);
1249 let bot_slot = top_slot + w;
1250 let mut top_skipped = false;
1251 if !intra_slice {
1252 self.begin_mb(r, ctx, top_slot);
1253 let inc = self.skip_inc(ctx, top_slot);
1254 top_skipped = r.mb_skip_flag(b_slice, inc)?;
1255 }
1256 if !top_skipped {
1257 let inc = self.field_flag_inc(ctx, mb_addr);
1258 pair_field = r.mb_field_flag(inc)?;
1259 self.mbaff_enter(ctx, mb_addr, pair_field);
1260 decode!(top_slot, false);
1261 self.mbaff_enter(ctx, mb_addr + 1, pair_field);
1262 let mut bot_skipped = false;
1263 if !intra_slice {
1264 self.begin_mb(r, ctx, bot_slot);
1265 let inc = self.skip_inc(ctx, bot_slot);
1266 bot_skipped = r.mb_skip_flag(b_slice, inc)?;
1267 }
1268 decode!(bot_slot, bot_skipped);
1269 } else {
1270 // The top macroblock is skipped; whether the pair is a
1271 // field pair is only known after the bottom macroblock's
1272 // skip flag (and, when that is clear, its field flag).
1273 // Until then the top stands in as a decoded skipped
1274 // macroblock for the bottom's context derivation.
1275 self.cur.mb_slice[top_slot] = ctx.slice_id;
1276 self.cur.mb_flags[top_slot] = FLAG_DECODED
1277 | FLAG_INTER
1278 | FLAG_SKIP
1279 | if b_slice { FLAG_DIRECT } else { 0 };
1280 self.cur.mb_field[top_slot] = u8::from(inferred);
1281 self.mbaff_enter(ctx, mb_addr + 1, inferred);
1282 self.begin_mb(r, ctx, bot_slot);
1283 let inc = self.skip_inc(ctx, bot_slot);
1284 let bot_skipped = r.mb_skip_flag(b_slice, inc)?;
1285 pair_field = if bot_skipped {
1286 inferred
1287 } else {
1288 let inc = self.field_flag_inc(ctx, mb_addr);
1289 r.mb_field_flag(inc)?
1290 };
1291 self.cur.mb_slice[top_slot] = NO_SLICE;
1292 self.cur.mb_flags[top_slot] = 0;
1293 self.mbaff_enter(ctx, mb_addr, pair_field);
1294 decode!(top_slot, true);
1295 self.mbaff_enter(ctx, mb_addr + 1, pair_field);
1296 decode!(bot_slot, bot_skipped);
1297 }
1298 more = r.more_macroblocks()?;
1299 mb_addr += 2;
1300 }
1301 return Ok(());
1302 }
1303 // CAVLC.
1304 while more {
1305 let mut run = 0u32;
1306 if !intra_slice {
1307 run = r.mb_skip_run()?;
1308 for left in (1..=run).rev() {
1309 if mb_addr >= mbs {
1310 return Err(Error::corrupt("mb_skip_run past the picture"));
1311 }
1312 let pair = mb_addr >> 1;
1313 let (px, pr) = (pair % w, pair / w);
1314 let top = mb_addr.is_multiple_of(2);
1315 // A skipped top macroblock whose bottom macroblock is
1316 // coded takes the bottom's field flag, which is the next
1317 // bit of the stream; two skipped macroblocks infer it.
1318 if top {
1319 pair_field = if left > 1 {
1320 mbaff::infer_field(&self.cur, px, pr, ctx.slice_id)
1321 } else {
1322 r.peek_bit()
1323 };
1324 }
1325 let slot = self.mbaff_enter(ctx, mb_addr, pair_field);
1326 decode!(slot, true);
1327 mb_addr += 1;
1328 }
1329 if run > 0 {
1330 more = r.more_macroblocks()?;
1331 if !more {
1332 break;
1333 }
1334 if mb_addr >= mbs {
1335 return Err(Error::corrupt("macroblock address beyond the picture"));
1336 }
1337 }
1338 }
1339 let top = mb_addr.is_multiple_of(2);
1340 if top || run > 0 {
1341 pair_field = r.mb_field_flag(0)?;
1342 }
1343 let slot = self.mbaff_enter(ctx, mb_addr, pair_field);
1344 decode!(slot, false);
1345 more = r.more_macroblocks()?;
1346 mb_addr += 1;
1347 }
1348 Ok(())
1349 }
1350
1351 /// Publish the neighbourhood of `mb_addr` to a CABAC reader ahead of
1352 /// mb_skip_flag, which is decoded before the macroblock layer.
1353 fn begin_mb(&self, r: &mut Entropy<'_>, ctx: &SliceCtx, mb_addr: usize) {
1354 let pic = &self.cur;
1355 let nbr = ctx_neighbors(pic, ctx, mb_addr % pic.mb_w, mb_addr / pic.mb_w);
1356 r.begin_mb(&build_mb_ctx(pic, ctx, &nbr, mb_addr));
1357 }
1358
1359 /// ctxIdxInc for mb_skip_flag (9.3.3.1.1.1): a neighbour counts unless it
1360 /// is unavailable or was itself skipped.
1361 fn skip_inc(&self, ctx: &SliceCtx, mb_addr: usize) -> usize {
1362 let pic = &self.cur;
1363 let mb_x = mb_addr % pic.mb_w;
1364 let mb_y = mb_addr / pic.mb_w;
1365 if ctx.pos.active {
1366 let cond =
1367 |s: Option<usize>| usize::from(s.is_some_and(|s| pic.mb_flags[s] & FLAG_SKIP == 0));
1368 return cond(mbaff::mb_a(pic, &ctx.pos)) + cond(mbaff::mb_b(pic, &ctx.pos));
1369 }
1370 let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id);
1371 let cond =
1372 |avail: bool, addr: usize| usize::from(avail && pic.mb_flags[addr] & FLAG_SKIP == 0);
1373 cond(nbr.a, mb_addr.wrapping_sub(1)) + cond(nbr.b, mb_addr.wrapping_sub(pic.mb_w))
1374 }
1375
1376 /// Open a new picture: clause 8.2 bookkeeping, then the geometry reset.
1377 fn start_picture(
1378 &mut self,
1379 sps: &Sps,
1380 pps: &Pps,
1381 sh: &SliceHeader,
1382 header: NalHeader,
1383 ) -> Result<()> {
1384 self.cur_ref_padded = false;
1385 let structure = if !sh.field_pic {
1386 FRAME
1387 } else if sh.bottom_field {
1388 BOTTOM
1389 } else {
1390 TOP
1391 };
1392 let mut info = PicInfo {
1393 structure,
1394 second_of: None,
1395 is_idr: header.is_idr(),
1396 is_reference: header.ref_idc != 0,
1397 frame_num: sh.frame_num,
1398 pic_order_cnt_lsb: sh.pic_order_cnt_lsb,
1399 delta_pic_order_cnt_bottom: sh.delta_pic_order_cnt_bottom,
1400 delta_pic_order_cnt: sh.delta_pic_order_cnt,
1401 };
1402 // A frame_num gap is what a seek or a dropped packet looks like: the
1403 // pictures it names never arrive, so clause 8.2.5.2 infers them and
1404 // decoding continues rather than stalling until the next IDR.
1405 let interlaced = self.dpb.interlaced;
1406 if interlaced
1407 && self
1408 .dpb
1409 .pending_first_field(sh.frame_num, structure, info.is_idr)
1410 .is_none()
1411 {
1412 // A picture that does not complete the waiting first field leaves
1413 // that field a non-paired one.
1414 self.dpb.finalize_unpaired();
1415 self.pump_output(false)?;
1416 }
1417 let second = if interlaced {
1418 self.dpb
1419 .pending_first_field(sh.frame_num, structure, info.is_idr)
1420 } else {
1421 None
1422 };
1423 if second.is_none() && !info.is_idr && self.dpb.frame_num_gap(sps, sh.frame_num) {
1424 // Pictures were lost (or a seek landed here): infer them either way.
1425 if interlaced {
1426 self.dpb.fill_frame_num_gap_i(sps, sh.frame_num)?;
1427 } else {
1428 self.dpb.fill_frame_num_gap(sps, sh.frame_num)?;
1429 }
1430 self.pump_output(false)?;
1431 }
1432 info.second_of = second;
1433 let poc = self.dpb.picture_order_count(sps, &info)?;
1434 let mut pic = if structure == FRAME {
1435 self.dpb.take_picture()
1436 } else {
1437 self.dpb.take_field_picture()
1438 };
1439 pic.start_as(sps, structure);
1440 if sps.mb_adaptive_frame_field && structure == FRAME {
1441 pic.coding = CODED_AFRM;
1442 pic.mbaff = true;
1443 }
1444 pic.poc = poc.value;
1445 pic.fpoc = [poc.top, poc.bottom];
1446 pic.poc_msb = poc.msb;
1447 pic.poc_lsb = poc.lsb;
1448 pic.frame_num_offset = poc.frame_num_offset;
1449 pic.frame_num = sh.frame_num;
1450 if second.is_none() {
1451 pic.pts = self.pending_pts.take();
1452 }
1453 self.cur = pic;
1454 self.cur_info = info;
1455 self.has_marking = sh.dec_ref_pic_marking.is_some();
1456 if let Some(m) = &sh.dec_ref_pic_marking {
1457 self.cur_marking.no_output_of_prior_pics = m.no_output_of_prior_pics;
1458 self.cur_marking.long_term_reference = m.long_term_reference;
1459 self.cur_marking.adaptive = m.adaptive;
1460 self.cur_marking.mmcos.clear();
1461 self.cur_marking.mmcos.extend_from_slice(&m.mmcos);
1462 }
1463 self.has_picture = true;
1464 if self.active_pps != Some(pps.id) {
1465 let lists = pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref());
1466 let weights = match lists {
1467 Some(l) => [
1468 [&l.list_4x4[0], &l.list_4x4[1], &l.list_4x4[2]],
1469 [&l.list_4x4[3], &l.list_4x4[4], &l.list_4x4[5]],
1470 ],
1471 None => [[&[16u8; 16]; 3]; 2],
1472 };
1473 // Separately coded colour planes are monochrome pictures that
1474 // take the lists of their own colour (iYCbCr = colour_plane_id).
1475 let weights = if sps.separate_colour_plane {
1476 let k = usize::from(self.plane_id);
1477 [[weights[0][k]; 3], [weights[1][k]; 3]]
1478 } else {
1479 weights
1480 };
1481 self.ls = [
1482 [
1483 LevelScale4x4::new(weights[0][0]),
1484 LevelScale4x4::new(weights[0][1]),
1485 LevelScale4x4::new(weights[0][2]),
1486 ],
1487 [
1488 LevelScale4x4::new(weights[1][0]),
1489 LevelScale4x4::new(weights[1][1]),
1490 LevelScale4x4::new(weights[1][2]),
1491 ],
1492 ];
1493 // list_8x8 is [Intra Y, Inter Y, Intra Cb, Inter Cb, Intra Cr, Inter Cr].
1494 let w8 = |intra: usize, comp: usize| -> &[u8; 64] {
1495 let k = if sps.separate_colour_plane {
1496 usize::from(self.plane_id)
1497 } else {
1498 comp
1499 };
1500 match lists {
1501 Some(l) => &l.list_8x8[2 * k + intra],
1502 None => &[16u8; 64],
1503 }
1504 };
1505 self.ls8 = std::array::from_fn(|intra| {
1506 std::array::from_fn(|comp| LevelScale8x8::new(w8(intra, comp)))
1507 });
1508 self.active_pps = Some(pps.id);
1509 }
1510 Ok(())
1511 }
1512}
1513
1514/// What tells two slices of one picture apart from the first slice of the
1515/// next one: the first-slice fields of clause 7.4.1.2.4.
1516#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1517struct PicKey {
1518 field_pic: bool,
1519 bottom_field: bool,
1520 idr: bool,
1521 reference: bool,
1522 idr_pic_id: Option<u32>,
1523 frame_num: u32,
1524 pps_id: u32,
1525 poc_lsb: u32,
1526 delta_poc_bottom: i32,
1527 delta_poc: [i32; 2],
1528}
1529
1530impl PicKey {
1531 fn of(sh: &SliceHeader, header: NalHeader) -> PicKey {
1532 PicKey {
1533 field_pic: sh.field_pic,
1534 bottom_field: sh.bottom_field,
1535 idr: header.is_idr(),
1536 reference: header.ref_idc != 0,
1537 idr_pic_id: sh.idr_pic_id,
1538 frame_num: sh.frame_num,
1539 pps_id: sh.pps_id,
1540 poc_lsb: sh.pic_order_cnt_lsb,
1541 delta_poc_bottom: sh.delta_pic_order_cnt_bottom,
1542 delta_poc: sh.delta_pic_order_cnt,
1543 }
1544 }
1545}
1546
1547/// Reject unsupported streams with named reasons before touching pixels.
1548///
1549/// Every `why` here names the syntax element that fired and the machinery it
1550/// would need: a refusal is a capability statement about this binary, and the
1551/// conformance suite proves each one against a stream that really uses the
1552/// feature.
1553fn check_supported<S: Sample>(
1554 sps: &Sps,
1555 pps: &Pps,
1556 slice_type_code: u32,
1557 wide: bool,
1558) -> Result<()> {
1559 if pps.num_slice_groups > 1 && !sps.frame_mbs_only {
1560 return Err(Error::unsupported(
1561 "FMO slice groups with interlaced coding",
1562 "slice groups over field or MBAFF map units (clause 8.2.2.8) are \
1563 not implemented; FMO is decoded for frame_mbs_only streams",
1564 ));
1565 }
1566 // With ChromaArrayType 0 (monochrome, or three separately coded planes)
1567 // the chroma depth is not used by the decoding process (7.4.2.1.1).
1568 if sps.chroma_array_type() != 0 && sps.bit_depth_luma != sps.bit_depth_chroma {
1569 return Err(Error::unsupported(
1570 "different luma and chroma bit depths",
1571 format!(
1572 "{}-bit luma with {}-bit chroma; planes and output frames carry \
1573 one sample depth",
1574 sps.bit_depth_luma, sps.bit_depth_chroma
1575 ),
1576 ));
1577 }
1578 if sps.bit_depth_luma > if wide { 14 } else { 10 } {
1579 return Err(Error::unsupported(
1580 "bit depth above 10",
1581 format!(
1582 "{}-bit samples are beyond what this decoder carries; it handles \
1583 8, 9 and 10 bits",
1584 sps.bit_depth_luma
1585 ),
1586 ));
1587 }
1588 if (sps.bit_depth_luma == 8) != S::IS_8 {
1589 // slice_bit_depth routes slices to the matching core; this is the
1590 // guard for a caller that bypasses it.
1591 return Err(Error::unsupported(
1592 "bit depth change inside a picture buffer",
1593 "the sample type of the decoder does not match the SPS bit depth",
1594 ));
1595 }
1596 if slice_type_code > 9 {
1597 return Err(Error::corrupt("slice_type > 9"));
1598 }
1599 if matches!(slice_type_code % 5, 3 | 4) {
1600 return Err(Error::unsupported(
1601 "SP and SI slices",
1602 "switching slices need the transform-domain reconstruction of \
1603 clause 8.5.14 and their own deblocking strengths; not implemented",
1604 ));
1605 }
1606 Ok(())
1607}
1608
1609/// Mutable per-slice decode state.
1610/// How many macroblocks of each shape a stream codes: the partitioning the
1611/// encoder chose, counted from the outside.
1612///
1613/// P macroblocks only; a B macroblock's own shapes are not split out.
1614#[derive(Debug, Default, Clone, Copy)]
1615pub struct MbShapes {
1616 pub skip: u64,
1617 pub p16x16: u64,
1618 pub p16x8: u64,
1619 pub p8x16: u64,
1620 /// P_8x8 and P_8x8ref0, whatever the sub_mb_types inside are.
1621 pub p8x8: u64,
1622 pub bidir: u64,
1623 pub intra: u64,
1624}
1625
1626impl MbShapes {
1627 /// Add another count into this one.
1628 pub fn add_public(&mut self, o: &MbShapes) {
1629 self.add(o);
1630 }
1631
1632 pub(crate) fn add(&mut self, o: &MbShapes) {
1633 self.skip += o.skip;
1634 self.p16x16 += o.p16x16;
1635 self.p16x8 += o.p16x8;
1636 self.p8x16 += o.p8x16;
1637 self.p8x8 += o.p8x8;
1638 self.bidir += o.bidir;
1639 self.intra += o.intra;
1640 }
1641}
1642
1643/// See [`SliceCtx::geo`]. Chroma rows are half of each luma row value.
1644#[derive(Clone, Copy)]
1645struct Geo {
1646 src_y: usize,
1647 dst_y: usize,
1648 dst_cy: usize,
1649 mul: usize,
1650}
1651
1652impl Geo {
1653 /// Picture row of luma row `r` of the macroblock.
1654 #[inline]
1655 fn y(&self, r: usize) -> usize {
1656 self.dst_y + r * self.mul
1657 }
1658
1659 /// Picture row of chroma row `r` of the macroblock.
1660 #[inline]
1661 fn cy(&self, r: usize) -> usize {
1662 self.dst_cy + r * self.mul
1663 }
1664}
1665
1666pub(crate) struct SliceCtx {
1667 slice_id: u16,
1668 slice_type: SliceType,
1669 qp: i32,
1670 cb_qp_offset: i32,
1671 cr_qp_offset: i32,
1672 /// Chroma rows per macroblock: 8 (4:2:0) or 16 (4:2:2).
1673 cmb_h: usize,
1674 /// ChromaArrayType of the picture being decoded.
1675 cat: u8,
1676 transform_8x8_mode: bool,
1677 constrained_intra_pred: bool,
1678 /// ctxIdxInc for the next macroblock's first mb_qp_delta bin: set when the
1679 /// macroblock just decoded coded a non-zero mb_qp_delta (9.3.3.1.1.5).
1680 qp_delta_inc: u8,
1681 /// `RefPicList0` and `RefPicList1` as decoded picture buffer indices.
1682 lists: [RefList; 2],
1683 num_ref_idx: [usize; 2],
1684 direct_spatial: bool,
1685 direct_8x8_inference: bool,
1686 weighted_pred: bool,
1687 weighted_bipred_idc: u8,
1688 weights: Option<PredWeightTable>,
1689 /// `PicOrderCnt( CurrPic )`.
1690 poc: i32,
1691 /// `TopFieldOrderCnt` and `BottomFieldOrderCnt` of the current picture.
1692 fpoc: [i32; 2],
1693 /// Structure of the picture being decoded: [`FRAME`], [`TOP`] or [`BOTTOM`].
1694 structure: u8,
1695 /// Parity of the macroblock being decoded when it is a field macroblock
1696 /// ([`TOP`] or [`BOTTOM`]), [`FRAME`] for a frame macroblock. In a field
1697 /// picture this is the picture's own parity.
1698 mb_parity: u8,
1699 /// Where the macroblock being decoded sits when the picture is an MBAFF
1700 /// frame (`pos.active`); inert otherwise.
1701 pos: MbPos,
1702 /// How many macroblocks of each shape this slice decoded.
1703 shapes: MbShapes,
1704}
1705
1706impl SliceCtx {
1707 /// `PicOrderCnt` of the current picture, or of the field of the current
1708 /// macroblock's parity for a field macroblock of an MBAFF frame (8.4.1.2.3, 8.4.2.3.1).
1709 #[inline]
1710 fn cur_poc(&self) -> i32 {
1711 if self.pos.active && self.pos.field {
1712 self.fpoc[usize::from(self.mb_parity == BOTTOM)]
1713 } else {
1714 self.poc
1715 }
1716 }
1717
1718 fn is_b(&self) -> bool {
1719 self.slice_type == SliceType::B
1720 }
1721
1722 /// The reference picture `RefPicListX[idx]` points at: a frame, or one
1723 /// field of a stored frame.
1724 #[inline(always)]
1725 fn reference<'a, S: Sample>(
1726 &self,
1727 refs: &'a [Picture<S>],
1728 list: usize,
1729 idx: i8,
1730 ) -> Option<&'a Picture<S>> {
1731 if idx < 0 {
1732 return None;
1733 }
1734 if self.pos.active && self.pos.field {
1735 return self.field_mb_reference(refs, list, idx);
1736 }
1737 let (k, s) = self.lists[list].get_ref(idx as usize)?;
1738 let p = refs.get(k)?;
1739 if s == FRAME {
1740 Some(p)
1741 } else {
1742 p.fields
1743 .get(usize::from(s) - 1)
1744 .filter(|f| !f.y.data.is_empty())
1745 }
1746 }
1747
1748 /// [`SliceCtx::reference`] for a field macroblock of an MBAFF frame.
1749 #[inline(never)]
1750 fn field_mb_reference<'a, S: Sample>(
1751 &self,
1752 refs: &'a [Picture<S>],
1753 list: usize,
1754 idx: i8,
1755 ) -> Option<&'a Picture<S>> {
1756 // 8.4.2.1: a field macroblock of an MBAFF frame indexes the fields of
1757 // the frame list: entry `idx >> 1`, the field of the macroblock's own
1758 // parity for an even index, the other for odd.
1759 let (k, _) = self.lists[list].get_ref((idx >> 1) as usize)?;
1760 let par = usize::from(self.mb_parity == BOTTOM) ^ (idx as usize & 1);
1761 refs.get(k)?
1762 .fields
1763 .get(par)
1764 .filter(|f| !f.y.data.is_empty())
1765 }
1766
1767 /// True while decoding a field picture or a field macroblock.
1768 #[inline]
1769 fn is_field(&self) -> bool {
1770 self.mb_parity != FRAME
1771 }
1772
1773 /// Sample geometry of the macroblock in slot row `mb_y`: the reference
1774 /// row of its first luma row (motion compensation reads fields at field
1775 /// row positions), the picture row it is written at, and the row step.
1776 #[inline]
1777 fn geo(&self, mb_y: usize) -> Geo {
1778 if self.pos.active && self.pos.field {
1779 Geo {
1780 src_y: (mb_y / 2) * 16,
1781 dst_y: (mb_y / 2) * 32 + (mb_y & 1),
1782 dst_cy: (mb_y / 2) * 2 * self.cmb_h + (mb_y & 1),
1783 mul: 2,
1784 }
1785 } else {
1786 Geo {
1787 src_y: mb_y * 16,
1788 dst_y: mb_y * 16,
1789 dst_cy: mb_y * self.cmb_h,
1790 mul: 1,
1791 }
1792 }
1793 }
1794
1795 /// The vertical chroma vector offset of 8.4.1.4 (Tables 8-9 and 8-10) for
1796 /// a prediction from `rp`: fields of opposite parity sit half a field line
1797 /// apart, which is a quarter of a chroma sample.
1798 #[inline]
1799 fn chroma_dy<S: Sample>(&self, rp: &Picture<S>) -> i16 {
1800 if self.cat != 1 {
1801 // Tables 8-9 and 8-10 apply to ChromaArrayType 1 only.
1802 return 0;
1803 }
1804 match (self.mb_parity, rp.structure) {
1805 (TOP, BOTTOM) => -2,
1806 (BOTTOM, TOP) => 2,
1807 _ => 0,
1808 }
1809 }
1810
1811 /// True when no slice-level weighting can apply at all, so every
1812 /// component of every partition resolves to [`Weights::DEFAULT`] without
1813 /// the per-component lookup: neither weighted prediction (P) nor
1814 /// weighted/bi-prediction (B) is signalled.
1815 fn no_weights(&self) -> bool {
1816 self.weighted_bipred_idc == 0 && !self.weighted_pred
1817 }
1818
1819 /// Prediction weights of one component (clause 8.4.3).
1820 fn weights_for<S: Sample>(
1821 &self,
1822 refs: &[Picture<S>],
1823 comp: usize,
1824 r0: i8,
1825 r1: i8,
1826 use0: bool,
1827 use1: bool,
1828 ) -> Weights {
1829 let implicit = self.weighted_bipred_idc == 2 && self.is_b() && use0 && use1;
1830 let explicit =
1831 (self.weighted_bipred_idc == 1 && self.is_b()) || (self.weighted_pred && !self.is_b());
1832 if implicit {
1833 let (Some(p0), Some(p1)) = (self.reference(refs, 0, r0), self.reference(refs, 1, r1))
1834 else {
1835 return Weights::DEFAULT;
1836 };
1837 let td = (p1.poc - p0.poc).clamp(-128, 127);
1838 let long_term = p0.mark == Mark::Long || p1.mark == Mark::Long;
1839 if td == 0 || long_term {
1840 return Weights {
1841 log_wd: 5,
1842 w: [32, 32],
1843 o: [0, 0],
1844 };
1845 }
1846 let tb = (self.cur_poc() - p0.poc).clamp(-128, 127);
1847 let tx = (16384 + (td / 2).abs()) / td;
1848 let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023);
1849 let w1 = dist >> 2;
1850 if !(-64..=128).contains(&w1) {
1851 return Weights {
1852 log_wd: 5,
1853 w: [32, 32],
1854 o: [0, 0],
1855 };
1856 }
1857 return Weights {
1858 log_wd: 5,
1859 w: [64 - w1, w1],
1860 o: [0, 0],
1861 };
1862 }
1863 if !explicit {
1864 return Weights::DEFAULT;
1865 }
1866 let Some(t) = &self.weights else {
1867 return Weights::DEFAULT;
1868 };
1869 let denom = if comp == 0 {
1870 t.luma_log2_weight_denom
1871 } else {
1872 t.chroma_log2_weight_denom
1873 } as i32;
1874 let field_mb = self.pos.active && self.pos.field;
1875 let pick = |list: &[WeightEntry], idx: i8| -> (i32, i32) {
1876 let default = (1 << denom, 0);
1877 if idx < 0 {
1878 return default;
1879 }
1880 // refIdxL0WP of 8.4.2.3: field macroblocks of an MBAFF frame use
1881 // the frame entry of the weight table.
1882 let idx = if field_mb { idx >> 1 } else { idx };
1883 match list.get(idx as usize) {
1884 None => default,
1885 Some(e) if comp == 0 => e.luma.unwrap_or(default),
1886 Some(e) => e.chroma.map(|c| c[comp - 1]).unwrap_or(default),
1887 }
1888 };
1889 let (w0, o0) = pick(&t.l0, r0);
1890 let (w1, o1) = pick(&t.l1, r1);
1891 Weights {
1892 log_wd: denom,
1893 w: [w0, w1],
1894 o: [o0, o1],
1895 }
1896 }
1897}
1898
1899/// Neighbour-availability snapshot for one macroblock (left, top, top-right,
1900/// top-left). The top-left neighbour is only read by the Intra_8x8 reference
1901/// filter of 8.3.2.2.1, which changes its end taps when the corner sample is
1902/// missing.
1903#[derive(Clone, Copy)]
1904pub(crate) struct MbNeighbors {
1905 pub a: bool,
1906 /// Availability of the left samples of each group of four rows. All equal
1907 /// to `a` except under constrained intra prediction in an MBAFF frame,
1908 /// where the rows of a macroblock can come from different neighbours.
1909 pub a4: [bool; 4],
1910 pub b: bool,
1911 pub c: bool,
1912 pub d: bool,
1913 /// The macroblock's place in an MBAFF frame; inert (`active` false) in
1914 /// every other picture, where the readers below take the raster path.
1915 pub pos: MbPos,
1916}
1917
1918pub(crate) fn mb_neighbors<S: Sample>(
1919 pic: &Picture<S>,
1920 mb_x: usize,
1921 mb_y: usize,
1922 slice_id: u16,
1923) -> MbNeighbors {
1924 let w = pic.mb_w;
1925 let addr = mb_y * w + mb_x;
1926 let same = |a: usize| pic.mb_slice[a] == slice_id;
1927 let a = mb_x > 0 && same(addr - 1);
1928 MbNeighbors {
1929 a,
1930 a4: [a; 4],
1931 b: mb_y > 0 && same(addr - w),
1932 c: mb_y > 0 && mb_x + 1 < w && same(addr - w + 1),
1933 d: mb_y > 0 && mb_x > 0 && same(addr - w - 1),
1934 pos: MbPos::default(),
1935 }
1936}
1937
1938/// [`mb_neighbors`] for the macroblock the slice context currently points at,
1939/// MBAFF-aware: neighbours A..D are the macroblocks Table 6-4 gives for the
1940/// locations (-1, 0), (0, -1), (16, -1) and (-1, -1).
1941fn ctx_neighbors<S: Sample>(
1942 pic: &Picture<S>,
1943 ctx: &SliceCtx,
1944 mb_x: usize,
1945 mb_y: usize,
1946) -> MbNeighbors {
1947 if !ctx.pos.active {
1948 return mb_neighbors(pic, mb_x, mb_y, ctx.slice_id);
1949 }
1950 let pos = ctx.pos;
1951 let at = |x, y| mbaff::locate(pic, &pos, x, y, 16, 16).is_some();
1952 let a = at(-1, 0);
1953 MbNeighbors {
1954 a,
1955 a4: [a; 4],
1956 b: at(0, -1),
1957 c: at(16, -1),
1958 d: at(-1, -1),
1959 pos,
1960 }
1961}
1962
1963/// The same, with the constrained intra prediction rule of 7.4.2.2 applied:
1964/// an inter-coded neighbour is not available as an intra prediction source.
1965fn intra_neighbors<S: Sample>(
1966 pic: &Picture<S>,
1967 mb_x: usize,
1968 mb_y: usize,
1969 n: MbNeighbors,
1970) -> MbNeighbors {
1971 let w = pic.mb_w;
1972 let addr = mb_y * w + mb_x;
1973 if n.pos.active {
1974 let intra_at = |x, y| {
1975 mbaff::locate(pic, &n.pos, x, y, 16, 16)
1976 .is_some_and(|l| pic.mb_flags[l.slot] & FLAG_INTER == 0)
1977 };
1978 let a4: [bool; 4] =
1979 std::array::from_fn(|k| n.a && (4 * k..4 * k + 4).all(|y| intra_at(-1, y as i32)));
1980 return MbNeighbors {
1981 a: a4.iter().all(|&v| v),
1982 a4,
1983 b: n.b && intra_at(0, -1),
1984 c: n.c && intra_at(16, -1),
1985 d: n.d && intra_at(-1, -1),
1986 pos: n.pos,
1987 };
1988 }
1989 let intra = |a: usize| pic.mb_flags[a] & FLAG_INTER == 0;
1990 let a = n.a && intra(addr - 1);
1991 MbNeighbors {
1992 a,
1993 a4: [a; 4],
1994 b: n.b && intra(addr - w),
1995 c: n.c && intra(addr - w + 1),
1996 d: n.d && intra(addr - w - 1),
1997 pos: n.pos,
1998 }
1999}
2000
2001/// Non-zero counts of the left and above neighbours of the luma 4x4 block at
2002/// global block coords `(bx, by)`, `None` when that neighbour is unavailable
2003/// (clause 6.4.11.4 plus the availability rules of 6.4.8).
2004#[inline]
2005pub(crate) fn luma_nz_pair<S: Sample>(
2006 pic: &Picture<S>,
2007 n: &MbNeighbors,
2008 bx: usize,
2009 by: usize,
2010) -> (Option<u8>, Option<u8>) {
2011 nz_pair_in(pic, &pic.nz_y, n, bx, by)
2012}
2013
2014/// The count grid of colour component `comp` laid out like the luma one: `nz_y`,
2015/// or for 4:4:4 the Cb / Cr grids, which are coded like luma.
2016#[inline]
2017fn nz_grid<S: Sample>(pic: &Picture<S>, comp: usize) -> &[u8] {
2018 if comp == 0 {
2019 &pic.nz_y
2020 } else {
2021 &pic.nz_c[comp - 1]
2022 }
2023}
2024
2025#[inline]
2026fn nz_grid_mut<S: Sample>(pic: &mut Picture<S>, comp: usize) -> &mut [u8] {
2027 if comp == 0 {
2028 &mut pic.nz_y
2029 } else {
2030 &mut pic.nz_c[comp - 1]
2031 }
2032}
2033
2034/// [`luma_nz_pair`] over an explicit count grid (`mb_w * 4` wide).
2035#[inline]
2036fn nz_pair_in<S: Sample>(
2037 pic: &Picture<S>,
2038 grid: &[u8],
2039 n: &MbNeighbors,
2040 bx: usize,
2041 by: usize,
2042) -> (Option<u8>, Option<u8>) {
2043 let w4 = pic.mb_w * 4;
2044 if n.pos.active {
2045 let get =
2046 |left| mbaff::nb_blk4(pic, &n.pos, bx, by, left).map(|(x, y, _)| grid[y * w4 + x]);
2047 return (get(true), get(false));
2048 }
2049 let left_avail = if bx.is_multiple_of(4) { n.a } else { true };
2050 let top_avail = if by.is_multiple_of(4) { n.b } else { true };
2051 (
2052 (left_avail && bx > 0).then(|| grid[by * w4 + bx - 1]),
2053 (top_avail && by > 0).then(|| grid[(by - 1) * w4 + bx]),
2054 )
2055}
2056
2057/// The neighbours of an 8x8 block for the coded_block_flag of ChromaArrayType 3
2058/// (9.3.3.1.1.9, ctxBlockCat 5, 9, 13): a neighbouring macroblock that did not
2059/// use the 8x8 transform has no 8x8 block there, which counts as "not coded"
2060/// (I_PCM counts as coded).
2061fn nz_pair_8x8<S: Sample>(
2062 pic: &Picture<S>,
2063 comp: usize,
2064 n: &MbNeighbors,
2065 bx: usize,
2066 by: usize,
2067) -> (Option<u8>, Option<u8>) {
2068 let grid = nz_grid(pic, comp);
2069 let w4 = pic.mb_w * 4;
2070 let masked = |loc: Option<(usize, usize)>| {
2071 loc.map(|(x, y)| {
2072 let slot = (y / 4) * pic.mb_w + x / 4;
2073 if pic.mb_flags[slot] & (FLAG_TRANS8X8 | FLAG_PCM) != 0 {
2074 grid[y * w4 + x]
2075 } else {
2076 0
2077 }
2078 })
2079 };
2080 if n.pos.active {
2081 let get = |left| masked(mbaff::nb_blk4(pic, &n.pos, bx, by, left).map(|(x, y, _)| (x, y)));
2082 return (get(true), get(false));
2083 }
2084 let left_avail = if bx.is_multiple_of(4) { n.a } else { true };
2085 let top_avail = if by.is_multiple_of(4) { n.b } else { true };
2086 (
2087 masked((left_avail && bx > 0).then(|| (bx - 1, by))),
2088 masked((top_avail && by > 0).then(|| (bx, by - 1))),
2089 )
2090}
2091
2092/// The same for a chroma AC 4x4 block at global chroma block coords.
2093#[inline]
2094pub(crate) fn chroma_nz_pair<S: Sample>(
2095 pic: &Picture<S>,
2096 n: &MbNeighbors,
2097 comp: usize,
2098 cx: usize,
2099 cy: usize,
2100) -> (Option<u8>, Option<u8>) {
2101 let w2 = pic.mb_w * 2;
2102 let grid = &pic.nz_c[comp];
2103 if n.pos.active {
2104 let get = |left| mbaff::nb_blk_c(pic, &n.pos, cx, cy, left).map(|(x, y)| grid[y * w2 + x]);
2105 return (get(true), get(false));
2106 }
2107 let cbh = pic.cmb_h / 4;
2108 let left_avail = if cx.is_multiple_of(2) { n.a } else { true };
2109 let top_avail = if cy.is_multiple_of(cbh) { n.b } else { true };
2110 (
2111 (left_avail && cx > 0).then(|| grid[cy * w2 + cx - 1]),
2112 (top_avail && cy > 0).then(|| grid[(cy - 1) * w2 + cx]),
2113 )
2114}
2115
2116/// Predicted Intra4x4PredMode / Intra8x8PredMode (8.3.1.1, 8.3.2.1) of the
2117/// block at global block coordinates `(bx, by)` of an MBAFF macroblock: the
2118/// smaller of the modes of the blocks Table 6-4 gives on the left and above,
2119/// DC (2) when either is unavailable or, under constrained intra prediction,
2120/// inter coded.
2121fn pred_mode_mbaff<S: Sample>(
2122 pic: &Picture<S>,
2123 nbr: &MbNeighbors,
2124 constrained: bool,
2125 bx: usize,
2126 by: usize,
2127) -> u8 {
2128 let w4 = pic.mb_w * 4;
2129 let get = |left: bool| -> Option<u8> {
2130 let (gx, gy, _) = mbaff::nb_blk4(pic, &nbr.pos, bx, by, left)?;
2131 let slot = (gy / 4) * pic.mb_w + gx / 4;
2132 if constrained && pic.mb_flags[slot] & FLAG_INTER != 0 {
2133 return None;
2134 }
2135 Some(pic.i4_modes[gy * w4 + gx])
2136 };
2137 match (get(true), get(false)) {
2138 (Some(a), Some(b)) => a.min(b),
2139 _ => 2,
2140 }
2141}
2142
2143/// The CABAC neighbourhood of the macroblock at slot `mb_addr`.
2144fn build_mb_ctx<S: Sample>(
2145 pic: &Picture<S>,
2146 ctx: &SliceCtx,
2147 nbr: &MbNeighbors,
2148 mb_addr: usize,
2149) -> MbCtx {
2150 let info = |addr: usize| MbInfo {
2151 flags: pic.mb_flags[addr],
2152 cbp: pic.mb_cbp[addr],
2153 dc_cbf: pic.mb_dc_cbf[addr],
2154 };
2155 if nbr.pos.active {
2156 let la = mbaff::locate(pic, &nbr.pos, -1, 0, 16, 16);
2157 let lo = mbaff::locate(pic, &nbr.pos, -1, 8, 16, 16);
2158 let blk = |l: Option<mbaff::Loc>| l.map_or(1, |l| ((l.yw >> 3) * 2 + 1) as u8);
2159 return MbCtx {
2160 a: la.map(|l| info(l.slot)),
2161 b: mbaff::mb_b(pic, &nbr.pos).map(info),
2162 qp_delta_inc: ctx.qp_delta_inc,
2163 field: ctx.is_field(),
2164 mbaff_a: Some(MbaffA {
2165 lower: lo.map(|l| info(l.slot)),
2166 blk: [blk(la), blk(lo)],
2167 }),
2168 };
2169 }
2170 MbCtx {
2171 a: nbr.a.then(|| info(mb_addr - 1)),
2172 b: nbr.b.then(|| info(mb_addr - pic.mb_w)),
2173 qp_delta_inc: ctx.qp_delta_inc,
2174 field: ctx.is_field(),
2175 mbaff_a: None,
2176 }
2177}
2178
2179/// Motion data parsed for one macroblock, before prediction derivation.
2180#[derive(Clone, Copy)]
2181struct MbMotion {
2182 /// Sub-macroblock types of a P_8x8 / B_8x8 macroblock.
2183 sub: [SubShape; 4],
2184 /// `ref_idx_lX[ mbPartIdx ]`, -1 when the partition does not use the list.
2185 ref_idx: [[i8; 4]; 2],
2186 /// `mvd_lX[ mbPartIdx ][ subMbPartIdx ]`, indexed by 4x4 raster position.
2187 mvd: [[[i16; 2]; 16]; 2],
2188}
2189
2190/// Decode one macroblock (spec 7.3.5, 7.4.5) and reconstruct it. `ctx.qp`
2191/// carries the QPY prediction chain.
2192// Block loops are indexed: `blk` is simultaneously a bitstream position, a
2193// geometry key (BLK4_POS) and a grid coordinate; iterators obscure that.
2194#[allow(clippy::needless_range_loop, clippy::too_many_arguments)]
2195fn decode_macroblock<S: Sample>(
2196 pic: &mut Picture<S>,
2197 refs: &[Picture<S>],
2198 ls: &[[LevelScale4x4; 3]; 2],
2199 ls8: &[[LevelScale8x8; 3]; 2],
2200 r: &mut Entropy<'_>,
2201 ctx: &mut SliceCtx,
2202 mb_addr: usize,
2203 skipped: bool,
2204) -> Result<()> {
2205 let mb_x = mb_addr % pic.mb_w;
2206 let mb_y = mb_addr / pic.mb_w;
2207 if pic.mb_slice[mb_addr] != NO_SLICE {
2208 return Err(Error::corrupt("macroblock decoded twice"));
2209 }
2210 let nbr = ctx_neighbors(pic, ctx, mb_x, mb_y);
2211 if ctx.pos.active {
2212 pic.mb_field[mb_addr] = u8::from(ctx.pos.field);
2213 }
2214 if !skipped || !r.is_cabac() {
2215 r.begin_mb(&build_mb_ctx(pic, ctx, &nbr, mb_addr));
2216 }
2217 let w4 = pic.mb_w * 4;
2218 let (bx0, by0) = (mb_x * 4, mb_y * 4);
2219
2220 // Every 4x4 block of this macroblock starts from a known state: the arrays
2221 // survive from the previous picture, and both the CABAC contexts and the
2222 // neighbour derivations read them for blocks of the macroblock in progress.
2223 for py in 0..4 {
2224 let base = (by0 + py) * w4 + bx0;
2225 for idx in base..base + 4 {
2226 pic.mv[idx] = [[0; 2]; 2];
2227 pic.ref_idx[idx] = [-1; 2];
2228 pic.ref_id[idx] = [-1; 2];
2229 pic.mvd_abs[idx] = [0; 4];
2230 pic.blk[idx] = 0;
2231 }
2232 }
2233
2234 let mb_type = if skipped {
2235 u32::MAX
2236 } else if ctx.slice_type == SliceType::P {
2237 r.mb_type_p()?
2238 } else if ctx.is_b() {
2239 r.mb_type_b()?
2240 } else {
2241 r.mb_type_i()?
2242 };
2243
2244 if skipped {
2245 ctx.shapes.skip += 1;
2246 } else if ctx.slice_type == SliceType::P {
2247 match mb_type {
2248 0 => ctx.shapes.p16x16 += 1,
2249 1 => ctx.shapes.p16x8 += 1,
2250 2 => ctx.shapes.p8x16 += 1,
2251 3 | 4 => ctx.shapes.p8x8 += 1,
2252 _ => ctx.shapes.intra += 1,
2253 }
2254 } else if ctx.is_b() {
2255 ctx.shapes.bidir += 1;
2256 } else {
2257 ctx.shapes.intra += 1;
2258 }
2259
2260 // Split the P/B numbering into an inter shape or an intra mb_type.
2261 let (shape, intra_type) = if skipped {
2262 let s = if ctx.is_b() { B_SHAPES[0] } else { P_SHAPES[0] };
2263 (Some(s), None)
2264 } else if ctx.slice_type == SliceType::P {
2265 if mb_type < 5 {
2266 (Some(P_SHAPES[mb_type as usize]), None)
2267 } else {
2268 (None, Some(mb_type - 5))
2269 }
2270 } else if ctx.is_b() {
2271 if mb_type < 23 {
2272 (Some(B_SHAPES[mb_type as usize]), None)
2273 } else {
2274 (None, Some(mb_type - 23))
2275 }
2276 } else {
2277 (None, Some(mb_type))
2278 };
2279 r.set_intra(intra_type.is_some());
2280 if let Some(shape) = shape {
2281 return decode_inter_mb(
2282 pic, refs, ls, ls8, r, ctx, mb_addr, shape, skipped, mb_type, nbr,
2283 );
2284 }
2285 let mb_type = intra_type.expect("an intra macroblock type");
2286 write_intra_mb(pic, mb_x, mb_y);
2287 let intra_nbr = if ctx.constrained_intra_pred {
2288 intra_neighbors(pic, mb_x, mb_y, nbr)
2289 } else {
2290 nbr
2291 };
2292
2293 if mb_type == 25 {
2294 // I_PCM (7.3.5, 8.3.5): raw samples, byte aligned.
2295 let bd = pic.bd;
2296 let samples = match pic.cat {
2297 0 => 256,
2298 1 => 384,
2299 2 => 512,
2300 _ => 768,
2301 };
2302 let pcm = r.pcm_block(bd, samples)?;
2303 // pcm_sample_luma / chroma are `bd`-bit words, most significant bit
2304 // first; at 8 bits they are the bytes themselves.
2305 let sample = |i: usize| -> S {
2306 if bd == 8 {
2307 S::from_i32(i32::from(pcm[i]))
2308 } else {
2309 let mut v = 0i32;
2310 for b in 0..bd as usize {
2311 let bit = i * bd as usize + b;
2312 v = (v << 1) | i32::from((pcm[bit >> 3] >> (7 - (bit & 7))) & 1);
2313 }
2314 S::from_i32(v)
2315 }
2316 };
2317 let geo = ctx.geo(mb_y);
2318 for y in 0..16 {
2319 let dst = pic.y.at(mb_x * 16, geo.y(y));
2320 for x in 0..16 {
2321 pic.y.data[dst + x] = sample(y * 16 + x);
2322 }
2323 }
2324 let (cmb_h, cw) = (pic.cmb_h, pic.cw);
2325 if pic.cat != 0 {
2326 for (c, plane) in [&mut pic.cb, &mut pic.cr].into_iter().enumerate() {
2327 let base = 256 + c * cw * cmb_h;
2328 for y in 0..cmb_h {
2329 let dst = plane.at(mb_x * cw, geo.cy(y));
2330 for x in 0..cw {
2331 plane.data[dst + x] = sample(base + y * cw + x);
2332 }
2333 }
2334 }
2335 }
2336 for dy in 0..4 {
2337 let base = (by0 + dy) * w4 + bx0;
2338 pic.nz_y[base..base + 4].fill(16);
2339 pic.i4_modes[base..base + 4].fill(2);
2340 }
2341 fill_chroma_nz(pic, mb_x, mb_y, 16);
2342 // QPY prediction chain continues unchanged (mb_qp_delta inferred 0);
2343 // the deblocker substitutes 0 via FLAG_PCM (spec 8.7.2).
2344 pic.mb_qp[mb_addr] = ctx.qp as i8;
2345 pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_PCM;
2346 pic.mb_cbp[mb_addr] = 0x3F;
2347 pic.mb_dc_cbf[mb_addr] = 0b111;
2348 ctx.qp_delta_inc = 0;
2349 pic.mb_slice[mb_addr] = ctx.slice_id;
2350 pic.decoded_mbs += 1;
2351 return Ok(());
2352 }
2353
2354 let is_i16 = mb_type >= 1;
2355 let (cbp_luma, cbp_chroma, i16_mode) = if is_i16 {
2356 let m = mb_type - 1;
2357 (
2358 if m >= 12 { 15u8 } else { 0 },
2359 ((m / 4) % 3) as u8,
2360 (m % 4) as u8,
2361 )
2362 } else {
2363 (0, 0, 0) // read below via me(v)
2364 };
2365 // ChromaArrayType 1 and 2 have the chroma prediction mode and the chroma
2366 // part of the pattern; 0 and 3 code none of it (7.3.5, 7.4.5).
2367 let has_chroma = matches!(pic.cat, 1 | 2);
2368 if is_i16 && !has_chroma && cbp_chroma != 0 {
2369 return Err(Error::corrupt(
2370 "Intra_16x16 mb_type with a chroma pattern in a stream without subsampled chroma",
2371 ));
2372 }
2373
2374 // I_NxN transform size flag (7.3.5, High profile only): it selects
2375 // Intra_8x8 prediction and the 8x8 transform for this macroblock.
2376 let trans8x8 = !is_i16 && ctx.transform_8x8_mode && r.transform_size_8x8_flag()?;
2377
2378 // mb_pred (7.3.5.1): intra 4x4 or 8x8 modes, then chroma mode.
2379 let mut modes = [2u8; 16];
2380 let mut modes8 = [2u8; 4];
2381 if trans8x8 {
2382 // Intra_8x8: four modes, predicted by 8.3.2.1 from the neighbouring
2383 // block modes. Every 4x4 slot of an 8x8 block carries its mode, which
2384 // is exactly what 8.3.1.1 and 8.3.2.1 read back from a neighbour
2385 // whichever size that neighbour used.
2386 for blk8 in 0..4 {
2387 let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
2388 let left_avail = if blk8.is_multiple_of(2) {
2389 intra_nbr.a
2390 } else {
2391 true
2392 };
2393 let top_avail = if blk8 < 2 { intra_nbr.b } else { true };
2394 let pred = if nbr.pos.active {
2395 pred_mode_mbaff(pic, &nbr, ctx.constrained_intra_pred, bx, by)
2396 } else if left_avail && top_avail {
2397 let ma = pic.i4_modes[by * w4 + bx - 1];
2398 let mb = pic.i4_modes[(by - 1) * w4 + bx];
2399 ma.min(mb)
2400 } else {
2401 2
2402 };
2403 let mode = match r.intra4x4_pred_mode()? {
2404 None => pred,
2405 Some(rem) if rem < pred => rem,
2406 Some(rem) => rem + 1,
2407 };
2408 modes8[blk8] = mode;
2409 for dy in 0..2 {
2410 let base = (by + dy) * w4 + bx;
2411 pic.i4_modes[base..base + 2].fill(mode);
2412 }
2413 }
2414 } else if !is_i16 {
2415 for blk in 0..16 {
2416 let (dx, dy) = BLK4_POS[blk];
2417 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
2418 // Predicted mode = min of neighbours, DC when either unavailable
2419 // (8.3.1.1; non-I4x4 neighbours were written as 2).
2420 let left_avail = if bx % 4 == 0 { intra_nbr.a } else { true };
2421 let top_avail = if by % 4 == 0 { intra_nbr.b } else { true };
2422 let pred = if nbr.pos.active {
2423 pred_mode_mbaff(pic, &nbr, ctx.constrained_intra_pred, bx, by)
2424 } else if left_avail && top_avail {
2425 let ma = pic.i4_modes[by * w4 + bx - 1];
2426 let mb = pic.i4_modes[(by - 1) * w4 + bx];
2427 ma.min(mb)
2428 } else {
2429 2
2430 };
2431 let mode = match r.intra4x4_pred_mode()? {
2432 None => pred,
2433 Some(rem) if rem < pred => rem,
2434 Some(rem) => rem + 1,
2435 };
2436 pic.i4_modes[by * w4 + bx] = mode;
2437 modes[blk] = mode;
2438 }
2439 } else {
2440 for dy in 0..4 {
2441 let base = (by0 + dy) * w4 + bx0;
2442 pic.i4_modes[base..base + 4].fill(2);
2443 }
2444 }
2445 let chroma_mode = if has_chroma {
2446 r.intra_chroma_pred_mode()?
2447 } else {
2448 0
2449 };
2450
2451 // coded_block_pattern for I_NxN; Intra_16x16 derives it from mb_type.
2452 let (cbp_luma, cbp_chroma) = if is_i16 {
2453 (cbp_luma, cbp_chroma)
2454 } else {
2455 r.coded_block_pattern_intra(has_chroma)?
2456 };
2457
2458 finish_macroblock(
2459 pic,
2460 &ls[0],
2461 &ls8[0],
2462 r,
2463 ctx,
2464 mb_addr,
2465 &nbr,
2466 MbFinish {
2467 pred_nbr: intra_nbr,
2468 is_i16,
2469 i16_mode,
2470 cbp_luma,
2471 cbp_chroma,
2472 modes,
2473 modes8,
2474 trans8x8,
2475 chroma_mode,
2476 intra: true,
2477 flags: if is_i16 { FLAG_I16 } else { 0 } | if trans8x8 { FLAG_TRANS8X8 } else { 0 },
2478 },
2479 )
2480}
2481
2482/// Set the chroma coefficient counts of a macroblock without a residual to
2483/// `value` (16 for I_PCM, 0 for a skipped macroblock). Monochrome has none.
2484fn fill_chroma_nz<S: Sample>(pic: &mut Picture<S>, mb_x: usize, mb_y: usize, value: u8) {
2485 match pic.cat {
2486 0 => {}
2487 3 => {
2488 let w4 = pic.mb_w * 4;
2489 for comp in 0..2 {
2490 for dy in 0..4 {
2491 let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
2492 pic.nz_c[comp][base..base + 4].fill(value);
2493 }
2494 }
2495 }
2496 _ => {
2497 let w2 = pic.mb_w * 2;
2498 let cbh = pic.cmb_h / 4;
2499 for comp in 0..2 {
2500 for dy in 0..cbh {
2501 let base = (mb_y * cbh + dy) * w2 + mb_x * 2;
2502 pic.nz_c[comp][base..base + 2].fill(value);
2503 }
2504 }
2505 }
2506 }
2507}
2508
2509/// Everything the shared residual path needs after prediction is decided.
2510struct MbFinish {
2511 /// Neighbour availability for *prediction*, which honours
2512 /// constrained_intra_pred_flag. The residual contexts use the plain
2513 /// availability instead — clause 9.2.1 and 9.3.3.1.1.9 only exclude an
2514 /// inter neighbour there when slice data partitioning is in use, and this
2515 /// decoder refuses partitioned slices outright.
2516 pred_nbr: MbNeighbors,
2517 is_i16: bool,
2518 i16_mode: u8,
2519 cbp_luma: u8,
2520 cbp_chroma: u8,
2521 modes: [u8; 16],
2522 /// Intra8x8PredMode per 8x8 block, when `trans8x8` and `intra`.
2523 modes8: [u8; 4],
2524 /// transform_size_8x8_flag: the luma residual is four 8x8 transform blocks.
2525 trans8x8: bool,
2526 chroma_mode: u8,
2527 intra: bool,
2528 flags: u8,
2529}
2530
2531/// The plane of colour component `comp` (0 Y, 1 Cb, 2 Cr).
2532#[inline]
2533fn plane_mut<S: Sample>(pic: &mut Picture<S>, comp: usize) -> &mut PicPlane<S> {
2534 match comp {
2535 0 => &mut pic.y,
2536 1 => &mut pic.cb,
2537 _ => &mut pic.cr,
2538 }
2539}
2540
2541#[inline]
2542fn plane_ref<S: Sample>(pic: &Picture<S>, comp: usize) -> &PicPlane<S> {
2543 match comp {
2544 0 => &pic.y,
2545 1 => &pic.cb,
2546 _ => &pic.cr,
2547 }
2548}
2549
2550/// `residual_luma( )` (7.3.5.3.1) of one colour component plus its
2551/// reconstruction (8.5): the luma residual, and for ChromaArrayType 3 the Cb
2552/// and Cr residual too, which is coded and reconstructed exactly like luma
2553/// (against the plane of `comp`, with `qp` its QP', and `ls` / `ls8` its
2554/// scaling lists).
2555///
2556/// Bitstream order equals reconstruction dependency order, so each block
2557/// reconstructs the moment its levels are parsed. `bypass` is
2558/// TransformBypassModeFlag: the levels are the residual (8.5.15).
2559#[allow(clippy::needless_range_loop, clippy::too_many_arguments)]
2560fn residual_luma_style<S: Sample>(
2561 pic: &mut Picture<S>,
2562 r: &mut Entropy<'_>,
2563 nbr: &MbNeighbors,
2564 m: &MbFinish,
2565 mb_x: usize,
2566 mb_y: usize,
2567 comp: usize,
2568 ls: &LevelScale4x4,
2569 ls8: &LevelScale8x8,
2570 qp: i32,
2571 bypass: bool,
2572 fld: bool,
2573 geo: Geo,
2574 dc_cbf: &mut u8,
2575) -> Result<()> {
2576 let bd = pic.bd;
2577 let max = (1i32 << bd) - 1;
2578 let w4 = pic.mb_w * 4;
2579 let (bx0, by0) = (mb_x * 4, mb_y * 4);
2580 let mul = geo.mul;
2581 let cbp_luma = m.cbp_luma;
2582 let c = comp as u8;
2583 let cat3 = pic.cat == 3;
2584 let mut scan = [0i32; 16];
2585 let mut raster = [0i32; 16];
2586 let mut resid = [0i32; 16];
2587 if m.is_i16 {
2588 {
2589 let pl = plane_mut(pic, comp);
2590 let mut w = PlaneWindow {
2591 origin: pl.at(mb_x * 16, geo.y(0)),
2592 stride: pl.stride * mul,
2593 data: &mut pl.data,
2594 };
2595 pred_16x16(m.i16_mode, bd, &mut w, m.pred_nbr.b, m.pred_nbr.a);
2596 }
2597 // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale.
2598 let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx0, by0);
2599 let dc_tc = r.residual_block_c(&mut scan, BlockCat::LumaDc, c, na, nb)?;
2600 *dc_cbf |= u8::from(dc_tc != 0) << comp;
2601 if fld {
2602 unfield(&scan, &mut raster);
2603 } else {
2604 unzigzag(&scan, &mut raster);
2605 }
2606 if !bypass {
2607 luma_dc_transform(&mut raster, ls, qp);
2608 }
2609 let dc = raster;
2610 // Lossless horizontal / vertical prediction accumulates the residual
2611 // over the whole macroblock, so every block takes part.
2612 let dpcm = bypass && m.i16_mode < 2;
2613 let horizontal = m.i16_mode == 1;
2614 for blk in 0..16 {
2615 let (dx, dy) = BLK4_POS[blk];
2616 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
2617 let tc = if cbp_luma != 0 {
2618 let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx, by);
2619 r.residual_block_c(&mut scan, BlockCat::LumaAc, c, na, nb)?
2620 } else {
2621 0
2622 };
2623 nz_grid_mut(pic, comp)[by * w4 + bx] = tc;
2624 let dc_blk = dc[dy as usize * 4 + dx as usize];
2625 if tc == 0 && dc_blk == 0 && !dpcm {
2626 continue; // prediction already in place
2627 }
2628 if tc > 0 {
2629 if fld {
2630 unfield_ac15(&scan, &mut raster);
2631 } else {
2632 unzigzag_ac15(&scan, &mut raster);
2633 }
2634 if !bypass {
2635 dequant_4x4(&mut raster, ls, qp, true);
2636 }
2637 } else {
2638 raster = [0; 16]; // DC-only block
2639 }
2640 raster[0] = dc_blk;
2641 let pl = plane_mut(pic, comp);
2642 let origin = pl.at(mb_x * 16 + dx as usize * 4, geo.y(dy as usize * 4));
2643 let stride = pl.stride * mul;
2644 if bypass {
2645 if dpcm {
2646 let first = if horizontal { dx == 0 } else { dy == 0 };
2647 add_residual_dpcm(
2648 &mut pl.data,
2649 bd,
2650 stride,
2651 origin,
2652 4,
2653 4,
2654 &raster,
2655 horizontal,
2656 first,
2657 );
2658 } else {
2659 add_residual_4x4(&mut pl.data, bd, stride, origin, &raster);
2660 }
2661 } else {
2662 inverse_transform_4x4(&raster, &mut resid);
2663 add_residual_4x4(&mut pl.data, bd, stride, origin, &resid);
2664 }
2665 }
2666 } else if m.trans8x8 {
2667 // 8x8 transform (8.5.13): predict, parse and reconstruct one 8x8 block
2668 // at a time, because an Intra_8x8 block predicts from the reconstructed
2669 // samples of the blocks before it.
2670 let mut scan8 = [0i32; 64];
2671 let mut raster8 = [0i32; 64];
2672 let mut resid8 = [0i32; 64];
2673 for blk8 in 0..4 {
2674 let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, geo.y((blk8 / 2) * 8));
2675 let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
2676 let origin = plane_ref(pic, comp).at(x, y);
2677 let stride = plane_ref(pic, comp).stride * mul;
2678 if m.intra {
2679 let n = filter_nbr8(&gather_nbr8_in(
2680 &plane_ref(pic, comp).data,
2681 &m.pred_nbr,
2682 blk8,
2683 origin,
2684 stride,
2685 ));
2686 let mut p = [S::default(); 64];
2687 pred_8x8(m.modes8[blk8], bd, &n, &mut p);
2688 let pl = plane_mut(pic, comp);
2689 for ry in 0..8 {
2690 let row = origin + ry * stride;
2691 pl.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]);
2692 }
2693 }
2694 if cbp_luma & (1 << blk8) == 0 {
2695 let grid = nz_grid_mut(pic, comp);
2696 for dy in 0..2 {
2697 let base = (by + dy) * w4 + bx;
2698 grid[base..base + 2].fill(0);
2699 }
2700 continue;
2701 }
2702 let tc = if r.is_cabac() {
2703 // ctxBlockCat 5: one 64-coefficient block, and every 4x4 slot
2704 // of it reports the block's own count to the neighbours
2705 // (9.3.3.1.1.9 resolves them to the 8x8 transform block). Only
2706 // ChromaArrayType 3 sends a coded_block_flag for it.
2707 let cbf = cat3.then(|| nz_pair_8x8(pic, comp, nbr, bx, by));
2708 let tc = r.residual_block_8x8(&mut scan8, c, cbf)?;
2709 let grid = nz_grid_mut(pic, comp);
2710 for dy in 0..2 {
2711 let base = (by + dy) * w4 + bx;
2712 grid[base..base + 2].fill(tc.min(16));
2713 }
2714 tc
2715 } else {
2716 // CAVLC codes the same 64 coefficients as four interleaved 4x4
2717 // blocks (7.3.5.3.1), each with its own nC neighbourhood.
2718 let mut tc = 0u8;
2719 for i4 in 0..4 {
2720 let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
2721 let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
2722 let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, sx, sy);
2723 let n = r.residual_block_c(&mut scan, BlockCat::Luma4x4, c, na, nb)?;
2724 nz_grid_mut(pic, comp)[sy * w4 + sx] = n;
2725 tc += n;
2726 for i in 0..16 {
2727 scan8[4 * i + i4] = scan[i];
2728 }
2729 }
2730 tc
2731 };
2732 if tc == 0 {
2733 continue;
2734 }
2735 if fld {
2736 unfield_8x8(&scan8, &mut raster8);
2737 } else {
2738 unzigzag_8x8(&scan8, &mut raster8);
2739 }
2740 let pl = plane_mut(pic, comp);
2741 if bypass {
2742 if m.intra && m.modes8[blk8] < 2 {
2743 add_residual_dpcm(
2744 &mut pl.data,
2745 bd,
2746 stride,
2747 origin,
2748 8,
2749 8,
2750 &raster8,
2751 m.modes8[blk8] == 1,
2752 true,
2753 );
2754 } else {
2755 add_residual_8x8(&mut pl.data, bd, stride, origin, &raster8);
2756 }
2757 } else {
2758 dequant_8x8(&mut raster8, ls8, qp);
2759 inverse_transform_8x8(&raster8, &mut resid8);
2760 add_residual_8x8(&mut pl.data, bd, stride, origin, &resid8);
2761 }
2762 }
2763 } else {
2764 for blk in 0..16 {
2765 let (dx, dy) = BLK4_POS[blk];
2766 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
2767 let tc = if cbp_luma & (1 << (blk >> 2)) != 0 {
2768 let (na, nb) = nz_pair_in(pic, nz_grid(pic, comp), nbr, bx, by);
2769 r.residual_block_c(&mut scan, BlockCat::Luma4x4, c, na, nb)?
2770 } else {
2771 0
2772 };
2773 nz_grid_mut(pic, comp)[by * w4 + bx] = tc;
2774 let (x, y) = (mb_x * 16 + dx as usize * 4, geo.y(dy as usize * 4));
2775 let origin = plane_ref(pic, comp).at(x, y);
2776 let stride = plane_ref(pic, comp).stride * mul;
2777 if m.intra {
2778 let n =
2779 gather_nbr4_in(&plane_ref(pic, comp).data, &m.pred_nbr, blk, origin, stride);
2780 let mut p = [S::default(); 16];
2781 pred_4x4(m.modes[blk], bd, &n, &mut p);
2782 let pl = plane_mut(pic, comp);
2783 if tc == 0 {
2784 // Pure prediction: copy the 16 samples in.
2785 for ry in 0..4 {
2786 let row = origin + ry * stride;
2787 pl.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
2788 }
2789 continue;
2790 }
2791 if fld {
2792 unfield(&scan, &mut raster);
2793 } else {
2794 unzigzag(&scan, &mut raster);
2795 }
2796 if bypass {
2797 for ry in 0..4 {
2798 let row = origin + ry * stride;
2799 pl.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
2800 }
2801 if m.modes[blk] < 2 {
2802 add_residual_dpcm(
2803 &mut pl.data,
2804 bd,
2805 stride,
2806 origin,
2807 4,
2808 4,
2809 &raster,
2810 m.modes[blk] == 1,
2811 true,
2812 );
2813 } else {
2814 add_residual_4x4(&mut pl.data, bd, stride, origin, &raster);
2815 }
2816 continue;
2817 }
2818 dequant_4x4(&mut raster, ls, qp, false);
2819 inverse_transform_4x4(&raster, &mut resid);
2820 for ry in 0..4 {
2821 let row = origin + ry * stride;
2822 for rx in 0..4 {
2823 let v = p[ry * 4 + rx].to_i32() + resid[ry * 4 + rx];
2824 pl.data[row + rx] = S::clip(v, max);
2825 }
2826 }
2827 } else {
2828 if tc == 0 {
2829 continue; // motion-compensated prediction already in place
2830 }
2831 if fld {
2832 unfield(&scan, &mut raster);
2833 } else {
2834 unzigzag(&scan, &mut raster);
2835 }
2836 let pl = plane_mut(pic, comp);
2837 if bypass {
2838 add_residual_4x4(&mut pl.data, bd, stride, origin, &raster);
2839 } else {
2840 dequant_4x4(&mut raster, ls, qp, false);
2841 inverse_transform_4x4(&raster, &mut resid);
2842 add_residual_4x4(&mut pl.data, bd, stride, origin, &resid);
2843 }
2844 }
2845 }
2846 }
2847 Ok(())
2848}
2849
2850/// The residual half of a macroblock (7.3.5.3 + 8.5), shared by the intra and
2851/// inter paths.
2852///
2853/// Bitstream order (luma blocks in Z-order, then chroma DC, then chroma AC)
2854/// equals reconstruction dependency order, so each block reconstructs the
2855/// moment its levels are parsed: no per-macroblock coefficient arrays, and
2856/// empty blocks cost one coeff_token read plus a prediction write. For an inter
2857/// macroblock the prediction is already in the plane, so the intra branches
2858/// below are simply skipped.
2859#[allow(clippy::needless_range_loop, clippy::too_many_arguments)]
2860fn finish_macroblock<S: Sample>(
2861 pic: &mut Picture<S>,
2862 ls: &[LevelScale4x4; 3],
2863 ls8: &[LevelScale8x8; 3],
2864 r: &mut Entropy<'_>,
2865 ctx: &mut SliceCtx,
2866 mb_addr: usize,
2867 nbr: &MbNeighbors,
2868 m: MbFinish,
2869) -> Result<()> {
2870 let mb_x = mb_addr % pic.mb_w;
2871 let mb_y = mb_addr / pic.mb_w;
2872 let bd = pic.bd;
2873 let qp_bd = 6 * (bd as i32 - 8);
2874 let w2 = pic.mb_w * 2;
2875 let c422 = pic.cat == 2;
2876 let c_sub = matches!(pic.cat, 1 | 2);
2877 let cbh = pic.cmb_h / 4;
2878 let (cx0, cy0) = (mb_x * 2, mb_y * cbh);
2879 let (cbp_luma, cbp_chroma) = (m.cbp_luma, m.cbp_chroma);
2880 let fld = ctx.is_field();
2881 let geo = ctx.geo(mb_y);
2882 let mul = geo.mul;
2883
2884 // mb_qp_delta (7.4.5).
2885 let mut qp_delta = 0;
2886 if cbp_luma != 0 || cbp_chroma != 0 || m.is_i16 {
2887 qp_delta = r.mb_qp_delta()?;
2888 // 7.4.5: the delta spans the extended QP range, and QPY wraps modulo
2889 // 52 + QpBdOffsetY back into [-QpBdOffsetY, 51].
2890 if qp_delta < -(26 + qp_bd / 2) || qp_delta > 25 + qp_bd / 2 {
2891 return Err(Error::corrupt("mb_qp_delta outside [-26, 25]"));
2892 }
2893 ctx.qp = (ctx.qp + qp_delta + 52 + 2 * qp_bd) % (52 + qp_bd) - qp_bd;
2894 }
2895 ctx.qp_delta_inc = u8::from(qp_delta != 0);
2896 pic.mb_qp[mb_addr] = ctx.qp as i8;
2897 pic.mb_flags[mb_addr] = FLAG_DECODED
2898 | m.flags
2899 | if !m.intra { FLAG_INTER } else { 0 }
2900 | if m.intra && m.chroma_mode != 0 {
2901 FLAG_CHROMA_PRED
2902 } else {
2903 0
2904 };
2905 pic.mb_cbp[mb_addr] = cbp_luma | (cbp_chroma << 4);
2906 pic.mb_slice[mb_addr] = ctx.slice_id;
2907 pic.decoded_mbs += 1;
2908 // The scaling process takes QP'Y = QPY + QpBdOffsetY and QP'C = QPC +
2909 // QpBdOffsetC (8.5.8); QPC maps qPI = Clip3(-QpBdOffsetC, 51, QPY + off).
2910 let qp_y = ctx.qp + qp_bd;
2911 let qp_cb = chroma_qp(ctx.qp, ctx.cb_qp_offset, qp_bd) + qp_bd;
2912 let qp_cr = chroma_qp(ctx.qp, ctx.cr_qp_offset, qp_bd) + qp_bd;
2913
2914 let mut dc_cbf = 0u8;
2915 let bypass = pic.bypass_enabled && qp_y == 0;
2916 let ncomp = if pic.cat == 3 { 3 } else { 1 };
2917 let qps = [qp_y, qp_cb, qp_cr];
2918 for comp in 0..ncomp {
2919 residual_luma_style(
2920 pic,
2921 r,
2922 nbr,
2923 &m,
2924 mb_x,
2925 mb_y,
2926 comp,
2927 &ls[comp],
2928 &ls8[comp],
2929 qps[comp],
2930 bypass,
2931 fld,
2932 geo,
2933 &mut dc_cbf,
2934 )?;
2935 }
2936 let mut scan = [0i32; 16];
2937 let mut raster = [0i32; 16];
2938 let mut resid = [0i32; 16];
2939
2940 // Chroma of 4:2:0 and 4:2:2: predict both components (intra only), then DC
2941 // (Cb, Cr), then AC in bitstream order, reconstructing as levels arrive.
2942 // (ChromaArrayType 3 coded its chroma like luma above; 0 has none.)
2943 if c_sub {
2944 if m.intra {
2945 for comp in 0..2 {
2946 let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
2947 let mut w = PlaneWindow {
2948 origin: plane.at(mb_x * 8, geo.cy(0)),
2949 stride: plane.stride * mul,
2950 data: &mut plane.data,
2951 };
2952 if c422 {
2953 pred_chroma_8x16(m.chroma_mode, bd, &mut w, m.pred_nbr.b, m.pred_nbr.a4);
2954 } else {
2955 pred_chroma_8x8_halves(
2956 m.chroma_mode,
2957 bd,
2958 &mut w,
2959 m.pred_nbr.b,
2960 [
2961 m.pred_nbr.a4[0] && m.pred_nbr.a4[1],
2962 m.pred_nbr.a4[2] && m.pred_nbr.a4[3],
2963 ],
2964 );
2965 }
2966 }
2967 }
2968 // Lossless horizontal / vertical chroma prediction accumulates the
2969 // residual over the whole chroma block (8.5.15), so every block of it
2970 // takes part.
2971 let dpcm = bypass && m.intra && matches!(m.chroma_mode, 1 | 2);
2972 let horizontal = m.chroma_mode == 1;
2973 let mut chroma_dc = [[0i32; 8]; 2];
2974 if cbp_chroma != 0 {
2975 for (comp, c) in chroma_dc.iter_mut().enumerate() {
2976 let (ls_c, qp_c) = if comp == 0 {
2977 (&ls[1], qp_cb)
2978 } else {
2979 (&ls[2], qp_cr)
2980 };
2981 if c422 {
2982 let tc =
2983 r.residual_block(&mut scan, BlockCat::ChromaDc422(comp as u8), None, None)?;
2984 dc_cbf |= u8::from(tc != 0) << (1 + comp);
2985 c.copy_from_slice(&scan[..8]);
2986 if bypass {
2987 // The levels are the DC values, in raster order.
2988 for (rr, &sc) in CHROMA_DC_422_RASTER.iter().enumerate() {
2989 c[rr] = scan[sc];
2990 }
2991 } else {
2992 chroma_dc_transform_422(c, ls_c, qp_c);
2993 }
2994 } else {
2995 let tc =
2996 r.residual_block(&mut scan, BlockCat::ChromaDc(comp as u8), None, None)?;
2997 dc_cbf |= u8::from(tc != 0) << (1 + comp);
2998 let mut c4 = [0i32; 4];
2999 c4.copy_from_slice(&scan[..4]);
3000 if !bypass {
3001 chroma_dc_transform_420(&mut c4, ls_c, qp_c);
3002 }
3003 c[..4].copy_from_slice(&c4);
3004 }
3005 }
3006 }
3007 for comp in 0..2 {
3008 for blk in 0..cbh * 2 {
3009 let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
3010 let tc = if cbp_chroma == 2 {
3011 let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy);
3012 r.residual_block(&mut scan, BlockCat::ChromaAc, na, nb)?
3013 } else {
3014 0
3015 };
3016 pic.nz_c[comp][cy * w2 + cx] = tc;
3017 if cbp_chroma == 0 {
3018 continue;
3019 }
3020 let dc_blk = chroma_dc[comp][blk];
3021 if tc == 0 && dc_blk == 0 && !dpcm {
3022 continue;
3023 }
3024 let (plane, ls_c, qp_c) = if comp == 0 {
3025 (&mut pic.cb, &ls[1], qp_cb)
3026 } else {
3027 (&mut pic.cr, &ls[2], qp_cr)
3028 };
3029 if tc > 0 {
3030 if fld {
3031 unfield_ac15(&scan, &mut raster);
3032 } else {
3033 unzigzag_ac15(&scan, &mut raster);
3034 }
3035 if !bypass {
3036 dequant_4x4(&mut raster, ls_c, qp_c, true);
3037 }
3038 } else {
3039 raster = [0; 16]; // DC-only block
3040 }
3041 raster[0] = dc_blk;
3042 let origin = plane.at(mb_x * 8 + (blk & 1) * 4, geo.cy((blk >> 1) * 4));
3043 let stride = plane.stride * mul;
3044 if bypass {
3045 if dpcm {
3046 let first = if horizontal {
3047 blk & 1 == 0
3048 } else {
3049 blk >> 1 == 0
3050 };
3051 add_residual_dpcm(
3052 &mut plane.data,
3053 bd,
3054 stride,
3055 origin,
3056 4,
3057 4,
3058 &raster,
3059 horizontal,
3060 first,
3061 );
3062 } else {
3063 add_residual_4x4(&mut plane.data, bd, stride, origin, &raster);
3064 }
3065 } else {
3066 inverse_transform_4x4(&raster, &mut resid);
3067 add_residual_4x4(&mut plane.data, bd, stride, origin, &resid);
3068 }
3069 }
3070 }
3071 }
3072 pic.mb_dc_cbf[mb_addr] = dc_cbf;
3073 Ok(())
3074}
3075
3076/// Decode an inter macroblock: sub-macroblock types, reference indices and
3077/// motion vector differences (7.3.5.1, 7.3.5.2), then motion compensation
3078/// (8.4.2) and the shared residual path.
3079// `comp` indexes a motion vector component and selects its context offset at
3080// the same time, which an iterator would obscure.
3081#[allow(clippy::too_many_arguments, clippy::needless_range_loop)]
3082fn decode_inter_mb<S: Sample>(
3083 pic: &mut Picture<S>,
3084 refs: &[Picture<S>],
3085 ls: &[[LevelScale4x4; 3]; 2],
3086 ls8: &[[LevelScale8x8; 3]; 2],
3087 r: &mut Entropy<'_>,
3088 ctx: &mut SliceCtx,
3089 mb_addr: usize,
3090 shape: MbShape,
3091 skipped: bool,
3092 mb_type: u32,
3093 nbr: MbNeighbors,
3094) -> Result<()> {
3095 let mb_x = mb_addr % pic.mb_w;
3096 let mb_y = mb_addr / pic.mb_w;
3097 let b = ctx.is_b();
3098 let mut mvc = MvCtx {
3099 mb_x,
3100 mb_y,
3101 slice_id: ctx.slice_id,
3102 written: 0,
3103 pos: ctx.pos,
3104 };
3105 let mut motion = MbMotion {
3106 sub: [P_SUB[0]; 4],
3107 ref_idx: [[-1; 4]; 2],
3108 mvd: [[[0; 2]; 16]; 2],
3109 };
3110 // A direct or skipped block contributes nothing to the ref_idx and mvd
3111 // contexts of its neighbours (9.3.3.1.1.6, 9.3.3.1.1.7), so the flag has to
3112 // be in place before any of this macroblock's syntax is parsed.
3113 let direct_mb = skipped || (b && mb_type == 0);
3114 if direct_mb {
3115 let f = BLK_DIRECT | if skipped { BLK_SKIP } else { 0 };
3116 for py in 0..4 {
3117 let base = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4;
3118 for idx in base..base + 4 {
3119 pic.blk[idx] = f;
3120 }
3121 }
3122 }
3123
3124 if shape.sub && !skipped {
3125 for part in 0..4 {
3126 let t = r.sub_mb_type(b)? as usize;
3127 motion.sub[part] = if b { B_SUB[t] } else { P_SUB[t] };
3128 if motion.sub[part].pred == Pred::Direct {
3129 for k in 0..4 {
3130 let (px, py) = (part % 2 * 2 + k % 2, part / 2 * 2 + k / 2);
3131 let idx = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4 + px;
3132 pic.blk[idx] = BLK_DIRECT;
3133 }
3134 }
3135 }
3136 }
3137
3138 // ---- ref_idx_lX (7.3.5.1, 7.3.5.2) ----
3139 // P_8x8ref0 infers reference index 0 for every partition.
3140 let infer_ref0 = ctx.slice_type == SliceType::P && mb_type == 4;
3141 if !skipped {
3142 for list in 0..2 {
3143 for part in 0..shape.parts {
3144 let uses = if shape.sub {
3145 motion.sub[part].pred.uses(list)
3146 } else {
3147 shape.pred[part.min(1)].uses(list)
3148 };
3149 if !uses {
3150 continue;
3151 }
3152 let nref = if ctx.pos.active && ctx.pos.field {
3153 2 * ctx.num_ref_idx[list]
3154 } else {
3155 ctx.num_ref_idx[list]
3156 };
3157 let idx = if infer_ref0 || nref <= 1 {
3158 0
3159 } else {
3160 let (px, py) = part_origin(&shape, part, (0, 0));
3161 let bx = (mb_x * 4 + px) as i32;
3162 let by = (mb_y * 4 + py) as i32;
3163 let inc = ref_idx_cond(pic, &mvc, bx - 1, by, list)
3164 + 2 * ref_idx_cond(pic, &mvc, bx, by - 1, list);
3165 r.ref_idx(nref as u32 - 1, inc)? as i8
3166 };
3167 motion.ref_idx[list][part] = idx;
3168 // Publish it over the whole macroblock partition — one
3169 // reference index covers an entire 8x8, however it is further
3170 // split — so the next partition's context (9.3.3.1.1.6) and
3171 // the mvd contexts of 9.3.3.1.1.7 see it everywhere.
3172 let (px, py) = part_origin(&shape, part, (0, 0));
3173 let (pw, ph) = mb_part_size(&shape);
3174 for dy in 0..ph {
3175 for dx in 0..pw {
3176 let bi = (mb_y * 4 + py + dy) * pic.mb_w * 4 + mb_x * 4 + px + dx;
3177 pic.ref_idx[bi][list] = idx;
3178 mvc.written |= 1 << ((py + dy) * 4 + px + dx);
3179 }
3180 }
3181 }
3182 }
3183 if infer_ref0 {
3184 for part in 0..4 {
3185 motion.ref_idx[0][part] = 0;
3186 }
3187 }
3188
3189 // ---- mvd_lX ----
3190 mvc.written = 0;
3191 for list in 0..2 {
3192 for part in 0..shape.parts {
3193 let uses = if shape.sub {
3194 motion.sub[part].pred.uses(list)
3195 } else {
3196 shape.pred[part.min(1)].uses(list)
3197 };
3198 if !uses {
3199 continue;
3200 }
3201 let subparts = if shape.sub { motion.sub[part].parts } else { 1 };
3202 for sp in 0..subparts {
3203 let (px, py) = part_origin(&shape, part, sp_offset(&shape, &motion, part, sp));
3204 let (pw, ph) = part_size(&shape, &motion, part);
3205 let bx = (mb_x * 4 + px) as i32;
3206 let by = (mb_y * 4 + py) as i32;
3207 let mut mvd = [0i16; 2];
3208 for comp in 0..2 {
3209 let a = neighbour_mvd(pic, &mvc, bx - 1, by, list)[comp];
3210 let bb = neighbour_mvd(pic, &mvc, bx, by - 1, list)[comp];
3211 let sum = a + bb;
3212 let inc = if sum > 32 {
3213 2
3214 } else if sum > 2 {
3215 1
3216 } else {
3217 0
3218 };
3219 let v = r.mvd(comp, inc)?;
3220 mvd[comp] = i16::try_from(v)
3221 .map_err(|_| Error::corrupt("mvd outside the level limits"))?;
3222 }
3223 for dy in 0..ph {
3224 for dx in 0..pw {
3225 motion.mvd[list][(py + dy) * 4 + px + dx] = mvd;
3226 write_mvd(pic, mb_x, mb_y, px + dx, py + dy, list, mvd);
3227 mvc.written |= 1 << ((py + dy) * 4 + px + dx);
3228 }
3229 }
3230 }
3231 }
3232 }
3233 }
3234
3235 // ---- motion vector derivation and compensation (8.4.1, 8.4.2) ----
3236 mvc.written = 0;
3237 if direct_mb && !b {
3238 predict_p_skip(pic, refs, ctx, &mut mvc)?;
3239 } else if direct_mb {
3240 predict_direct(pic, refs, ctx, &mut mvc, true)?;
3241 } else {
3242 for part in 0..shape.parts {
3243 if shape.sub && motion.sub[part].pred == Pred::Direct {
3244 predict_direct_8x8(pic, refs, ctx, &mut mvc, part)?;
3245 continue;
3246 }
3247 let subparts = if shape.sub { motion.sub[part].parts } else { 1 };
3248 let pred = if shape.sub {
3249 motion.sub[part].pred
3250 } else {
3251 shape.pred[part.min(1)]
3252 };
3253 for sp in 0..subparts {
3254 let (px, py) = part_origin(&shape, part, sp_offset(&shape, &motion, part, sp));
3255 let (pw, ph) = part_size(&shape, &motion, part);
3256 let mut mv = [[0i16; 2]; 2];
3257 let mut ref_idx = [-1i8; 2];
3258 let mut ref_id = [-1i32; 2];
3259 for list in 0..2 {
3260 if !pred.uses(list) {
3261 continue;
3262 }
3263 let idx = motion.ref_idx[list][part];
3264 // predPartWidth of 6.4.11.7: the macroblock partition width
3265 // for a whole-macroblock partition, the sub-macroblock
3266 // partition width inside an 8x8.
3267 let n = mvc.neighbours(pic, px, py, pw, list);
3268 let mvp = predict_mv(&n, idx, shape.w, shape.h, part);
3269 let d = motion.mvd[list][py * 4 + px];
3270 mv[list] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])];
3271 ref_idx[list] = idx;
3272 ref_id[list] = ctx.reference(refs, list, idx).map(|p| p.id).unwrap_or(-1);
3273 }
3274 for dy in 0..ph {
3275 for dx in 0..pw {
3276 write_block(pic, &mut mvc, px + dx, py + dy, mv, ref_idx, ref_id, 0);
3277 }
3278 }
3279 S::compensate(pic, refs, ctx, mb_x, mb_y, px, py, pw, ph, mv, ref_idx)?;
3280 }
3281 }
3282 }
3283
3284 if skipped {
3285 // 7.4.5: a skipped macroblock has no residual and does not change QPY.
3286 let w4 = pic.mb_w * 4;
3287 for dy in 0..4 {
3288 let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
3289 pic.nz_y[base..base + 4].fill(0);
3290 pic.i4_modes[base..base + 4].fill(2);
3291 }
3292 fill_chroma_nz(pic, mb_x, mb_y, 0);
3293 pic.mb_qp[mb_addr] = ctx.qp as i8;
3294 pic.mb_flags[mb_addr] =
3295 FLAG_DECODED | FLAG_INTER | FLAG_SKIP | if b { FLAG_DIRECT } else { 0 };
3296 pic.mb_cbp[mb_addr] = 0;
3297 pic.mb_dc_cbf[mb_addr] = 0;
3298 pic.mb_slice[mb_addr] = ctx.slice_id;
3299 pic.decoded_mbs += 1;
3300 ctx.qp_delta_inc = 0;
3301 return Ok(());
3302 }
3303
3304 let w4 = pic.mb_w * 4;
3305 for dy in 0..4 {
3306 let base = (mb_y * 4 + dy) * w4 + mb_x * 4;
3307 pic.i4_modes[base..base + 4].fill(2);
3308 }
3309 let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter(matches!(pic.cat, 1 | 2))?;
3310 // transform_size_8x8_flag (7.3.5): only when every 8x8 of this macroblock
3311 // is predicted as a whole, because an 8x8 transform block may not straddle
3312 // two motion partitions.
3313 let no_sub_lt_8x8 = !shape.sub
3314 || (0..4).all(|p| {
3315 let s = motion.sub[p];
3316 if s.pred == Pred::Direct {
3317 ctx.direct_8x8_inference
3318 } else {
3319 s.parts == 1
3320 }
3321 });
3322 let trans8x8 = cbp_luma != 0
3323 && ctx.transform_8x8_mode
3324 && no_sub_lt_8x8
3325 && (!direct_mb || ctx.direct_8x8_inference)
3326 && r.transform_size_8x8_flag()?;
3327 // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual.
3328 finish_macroblock(
3329 pic,
3330 &ls[1],
3331 &ls8[1],
3332 r,
3333 ctx,
3334 mb_addr,
3335 &nbr,
3336 MbFinish {
3337 pred_nbr: nbr,
3338 is_i16: false,
3339 i16_mode: 0,
3340 cbp_luma,
3341 cbp_chroma,
3342 modes: [2; 16],
3343 modes8: [2; 4],
3344 trans8x8,
3345 chroma_mode: 0,
3346 intra: false,
3347 flags: if b && mb_type == 0 { FLAG_DIRECT } else { 0 }
3348 | if trans8x8 { FLAG_TRANS8X8 } else { 0 },
3349 },
3350 )
3351}
3352
3353/// Top-left 4x4 block of macroblock partition `part`, offset by `sp` blocks in
3354/// raster order within the 8x8.
3355fn part_origin(shape: &MbShape, part: usize, sp: (usize, usize)) -> (usize, usize) {
3356 let (px, py) = if shape.sub {
3357 (part % 2 * 2, part / 2 * 2)
3358 } else if shape.parts == 1 {
3359 (0, 0)
3360 } else if shape.w == 4 {
3361 (0, part * 2) // 16x8
3362 } else {
3363 (part * 2, 0) // 8x16
3364 };
3365 (px + sp.0, py + sp.1)
3366}
3367
3368/// Block offset of sub-macroblock partition `sp` inside its 8x8.
3369fn sp_offset(shape: &MbShape, m: &MbMotion, part: usize, sp: usize) -> (usize, usize) {
3370 if !shape.sub {
3371 return (0, 0);
3372 }
3373 let s = m.sub[part];
3374 match (s.w, s.h) {
3375 (2, 2) => (0, 0),
3376 (2, 1) => (0, sp),
3377 (1, 2) => (sp, 0),
3378 _ => (sp % 2, sp / 2),
3379 }
3380}
3381
3382/// Size of one *macroblock* partition in 4x4 blocks: always 8x8 for a
3383/// macroblock that carries sub-macroblock types, however those split it.
3384fn mb_part_size(shape: &MbShape) -> (usize, usize) {
3385 if shape.sub {
3386 (2, 2)
3387 } else {
3388 (shape.w, shape.h)
3389 }
3390}
3391
3392/// Size of one (sub-)macroblock partition in 4x4 blocks.
3393fn part_size(shape: &MbShape, m: &MbMotion, part: usize) -> (usize, usize) {
3394 if shape.sub {
3395 let s = m.sub[part];
3396 (s.w, s.h)
3397 } else {
3398 (shape.w, shape.h)
3399 }
3400}
3401
3402/// P_Skip (clause 8.4.1.1).
3403fn predict_p_skip<S: Sample>(
3404 pic: &mut Picture<S>,
3405 refs: &[Picture<S>],
3406 ctx: &SliceCtx,
3407 mvc: &mut MvCtx,
3408) -> Result<()> {
3409 let n = mvc.neighbours(pic, 0, 0, 4, 0);
3410 let zero = !n[0].avail
3411 || !n[1].avail
3412 || (n[0].ref_idx == 0 && n[0].mv == [0, 0])
3413 || (n[1].ref_idx == 0 && n[1].mv == [0, 0]);
3414 let mv = if zero {
3415 [0i16; 2]
3416 } else {
3417 predict_mv(&n, 0, 4, 4, 0)
3418 };
3419 let ref_id = ctx.reference(refs, 0, 0).map(|p| p.id).unwrap_or(-1);
3420 for py in 0..4 {
3421 for px in 0..4 {
3422 write_block(
3423 pic,
3424 mvc,
3425 px,
3426 py,
3427 [mv, [0; 2]],
3428 [0, -1],
3429 [ref_id, -1],
3430 BLK_SKIP | BLK_DIRECT,
3431 );
3432 }
3433 }
3434 S::compensate(
3435 pic,
3436 refs,
3437 ctx,
3438 mvc.mb_x,
3439 mvc.mb_y,
3440 0,
3441 0,
3442 4,
3443 4,
3444 [mv, [0; 2]],
3445 [0, -1],
3446 )
3447}
3448
3449/// B_Skip / B_Direct_16x16 (clause 8.4.1.2) over the whole macroblock.
3450fn predict_direct<S: Sample>(
3451 pic: &mut Picture<S>,
3452 refs: &[Picture<S>],
3453 ctx: &SliceCtx,
3454 mvc: &mut MvCtx,
3455 skip: bool,
3456) -> Result<()> {
3457 for quad in 0..4 {
3458 direct_quadrant(pic, refs, ctx, mvc, quad, skip)?;
3459 }
3460 Ok(())
3461}
3462
3463/// B_Direct_8x8 for one 8x8 sub-macroblock.
3464fn predict_direct_8x8<S: Sample>(
3465 pic: &mut Picture<S>,
3466 refs: &[Picture<S>],
3467 ctx: &SliceCtx,
3468 mvc: &mut MvCtx,
3469 part: usize,
3470) -> Result<()> {
3471 direct_quadrant(pic, refs, ctx, mvc, part, false)
3472}
3473
3474/// One 8x8 quadrant of a direct-mode macroblock. With
3475/// `direct_8x8_inference_flag` the whole quadrant shares the motion of its
3476/// outer corner 4x4 block; without it each 4x4 block is derived on its own.
3477fn direct_quadrant<S: Sample>(
3478 pic: &mut Picture<S>,
3479 refs: &[Picture<S>],
3480 ctx: &SliceCtx,
3481 mvc: &mut MvCtx,
3482 quad: usize,
3483 skip: bool,
3484) -> Result<()> {
3485 let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y);
3486 let (qx, qy) = (quad % 2 * 2, quad / 2 * 2);
3487 let flags = BLK_DIRECT | if skip { BLK_SKIP } else { 0 };
3488 if ctx.direct_8x8_inference {
3489 // 8.4.1.2.1: luma4x4BlkIdx = 5 * mbPartIdx, i.e. the quadrant's own
3490 // outer corner of the macroblock.
3491 let corner = (quad % 2 * 3, quad / 2 * 3);
3492 let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, corner)?;
3493 for dy in 0..2 {
3494 for dx in 0..2 {
3495 write_block(pic, mvc, qx + dx, qy + dy, mv, ref_idx, ref_id, flags);
3496 }
3497 }
3498 S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx)
3499 } else {
3500 // Each 4x4 block derives its own motion, but they usually come out
3501 // equal: interpolation is position-invariant, so one 8x8 compensation
3502 // of the shared vector produces the same samples as four 4x4 ones and
3503 // pays the per-partition setup once instead of four times.
3504 let mut motion = [([[0i16; 2]; 2], [0i8; 2]); 4];
3505 for dy in 0..2 {
3506 for dx in 0..2 {
3507 let (px, py) = (qx + dx, qy + dy);
3508 let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, (px, py))?;
3509 write_block(pic, mvc, px, py, mv, ref_idx, ref_id, flags);
3510 motion[dy * 2 + dx] = (mv, ref_idx);
3511 }
3512 }
3513 if motion.iter().all(|m| *m == motion[0]) {
3514 let (mv, ref_idx) = motion[0];
3515 return S::compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx);
3516 }
3517 for dy in 0..2 {
3518 for dx in 0..2 {
3519 let (mv, ref_idx) = motion[dy * 2 + dx];
3520 S::compensate(
3521 pic,
3522 refs,
3523 ctx,
3524 mb_x,
3525 mb_y,
3526 qx + dx,
3527 qy + dy,
3528 1,
3529 1,
3530 mv,
3531 ref_idx,
3532 )?;
3533 }
3534 }
3535 Ok(())
3536 }
3537}
3538
3539/// Motion of one direct-mode 4x4 block: `(mvLX, refIdxLX, reference picture
3540/// identity)`, spatial (8.4.1.2.2) or temporal (8.4.1.2.3).
3541#[allow(clippy::type_complexity)]
3542fn direct_block<S: Sample>(
3543 pic: &Picture<S>,
3544 refs: &[Picture<S>],
3545 ctx: &SliceCtx,
3546 mvc: &MvCtx,
3547 at: (usize, usize),
3548) -> Result<([[i16; 2]; 2], [i8; 2], [i32; 2])> {
3549 // The co-located block, in both modes (8.4.1.2.1): its list 0 motion, or
3550 // its list 1 motion when list 0 is unused. `col_ref_idx` is refIdxCol —
3551 // an index into the co-located picture's own reference list, not ours.
3552 let (col_ref_id, col_mv, col_ref_idx, vscale) = colocated(ctx, refs, mvc, at);
3553 let col = ctx.reference(refs, 1, 0);
3554
3555 if ctx.direct_spatial {
3556 // Reference indices from the macroblock's own neighbours, once.
3557 let mut ref_idx = [-1i8; 2];
3558 let mut mvp = [[0i16; 2]; 2];
3559 for list in 0..2 {
3560 let n = mvc.neighbours(pic, 0, 0, 4, list);
3561 ref_idx[list] = min_positive(n[0].ref_idx, min_positive(n[1].ref_idx, n[2].ref_idx));
3562 mvp[list] = predict_mv(&n, ref_idx[list], 4, 4, 0);
3563 }
3564 let zero_prediction = ref_idx[0] < 0 && ref_idx[1] < 0;
3565 if zero_prediction {
3566 ref_idx = [0, 0];
3567 }
3568 // colZeroFlag (8.4.1.2.2): the co-located block sits still on a
3569 // short-term picture, referencing that picture's own list entry 0. The
3570 // index is the one belonging to the list 8.4.1.2.1 picked — reading
3571 // "either list is 0" instead lets a bi-predicted co-located block whose
3572 // list 1 index happens to be 0 zero a motion vector it must not, which
3573 // only shows on a B picture used as the co-located one.
3574 let col_short = col.is_some_and(|c| c.mark == Mark::Short);
3575 let col_zero = col_short
3576 && col_ref_id >= 0
3577 && col_ref_idx == 0
3578 && (-1..=1).contains(&col_mv[0])
3579 && (-1..=1).contains(&col_mv[1]);
3580 let mut mv = [[0i16; 2]; 2];
3581 let mut ref_id = [-1i32; 2];
3582 for list in 0..2 {
3583 if ref_idx[list] < 0 {
3584 continue;
3585 }
3586 ref_id[list] = ctx
3587 .reference(refs, list, ref_idx[list])
3588 .map(|p| p.id)
3589 .unwrap_or(-1);
3590 if zero_prediction || (ref_idx[list] == 0 && col_zero) {
3591 mv[list] = [0; 2];
3592 } else {
3593 mv[list] = mvp[list];
3594 }
3595 }
3596 return Ok((mv, ref_idx, ref_id));
3597 }
3598
3599 // Temporal direct (8.4.1.2.3).
3600 let ref_idx0 = if col_ref_id < 0 {
3601 0
3602 } else {
3603 map_col_to_list0(ctx, refs, col_ref_id, vscale)
3604 };
3605 let col_mv = match vscale {
3606 // 8-195 and 8-196: "/" truncates toward zero.
3607 COL_FRM_TO_FLD => [col_mv[0], col_mv[1] / 2],
3608 COL_FLD_TO_FRM => [col_mv[0], col_mv[1].wrapping_mul(2)],
3609 _ => col_mv,
3610 };
3611 let pic0 = ctx.reference(refs, 0, ref_idx0);
3612 let pic1 = ctx.reference(refs, 1, 0);
3613 let ref_id = [
3614 pic0.map(|p| p.id).unwrap_or(-1),
3615 pic1.map(|p| p.id).unwrap_or(-1),
3616 ];
3617 let (Some(p0), Some(p1)) = (pic0, pic1) else {
3618 return Ok(([[0; 2]; 2], [ref_idx0, 0], ref_id));
3619 };
3620 let td = (p1.poc - p0.poc).clamp(-128, 127);
3621 if p0.mark == Mark::Long || td == 0 {
3622 return Ok(([col_mv, [0; 2]], [ref_idx0, 0], ref_id));
3623 }
3624 let tb = (ctx.cur_poc() - p0.poc).clamp(-128, 127);
3625 let tx = (16384 + (td / 2).abs()) / td;
3626 let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023);
3627 let mv0 = [
3628 ((dist * i32::from(col_mv[0]) + 128) >> 8) as i16,
3629 ((dist * i32::from(col_mv[1]) + 128) >> 8) as i16,
3630 ];
3631 let mv1 = [mv0[0] - col_mv[0], mv0[1] - col_mv[1]];
3632 Ok(([mv0, mv1], [ref_idx0, 0], ref_id))
3633}
3634
3635/// `MapColToList0` (8.4.1.2.3): the lowest RefPicList0 index that names the
3636/// picture the co-located block referenced.
3637fn map_col_to_list0<S: Sample>(
3638 ctx: &SliceCtx,
3639 refs: &[Picture<S>],
3640 col_ref_id: i32,
3641 vscale: u8,
3642) -> i8 {
3643 // Picture ids step by 4: a field id is its frame's id + 1 + parity.
3644 let field_mb = ctx.pos.active && ctx.pos.field;
3645 let want = match vscale {
3646 // The field of the referenced frame with the current picture's (or
3647 // macroblock's) parity.
3648 COL_FRM_TO_FLD => col_ref_id + i32::from(ctx.mb_parity),
3649 // A field macroblock of an MBAFF frame names the field of the frame
3650 // the co-located field macroblock referenced that has its own parity.
3651 _ if field_mb && MBAFF_ONE_TO_ONE_SAME_PARITY => {
3652 (col_ref_id & !3) + i32::from(ctx.mb_parity)
3653 }
3654 _ => col_ref_id,
3655 };
3656 let n = if field_mb {
3657 2 * ctx.lists[0].len()
3658 } else {
3659 ctx.lists[0].len()
3660 };
3661 for i in 0..n {
3662 let hit = ctx.reference(refs, 0, i as i8).is_some_and(|p| {
3663 if vscale == COL_FLD_TO_FRM {
3664 p.id == col_ref_id & !3
3665 } else {
3666 p.id == want
3667 }
3668 });
3669 if hit {
3670 return i as i8;
3671 }
3672 }
3673 0
3674}
3675
3676/// Whether a field macroblock of an MBAFF frame whose co-located block is a
3677/// field macroblock maps the referenced field to the field of the same parity
3678/// as itself (true) or to that very field (false).
3679const MBAFF_ONE_TO_ONE_SAME_PARITY: bool = false;
3680
3681/// `vertMvScale` of 8.4.1.2.1.
3682const COL_ONE_TO_ONE: u8 = 0;
3683const COL_FRM_TO_FLD: u8 = 1;
3684const COL_FLD_TO_FRM: u8 = 2;
3685
3686/// [`colocated`] for a frame macroblock or field macroblock of an MBAFF frame.
3687#[inline(never)]
3688fn colocated_mbaff<S: Sample>(
3689 ctx: &SliceCtx,
3690 refs: &[Picture<S>],
3691 mvc: &MvCtx,
3692 at: (usize, usize),
3693) -> (i32, [i16; 2], i8, u8) {
3694 const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE);
3695 let Some((k, _)) = ctx.lists[1].get_ref(0) else {
3696 return NONE;
3697 };
3698 let Some(store) = refs.get(k) else {
3699 return NONE;
3700 };
3701 let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y);
3702 let w = store.mb_w.max(1);
3703 let (c, bx, by, vs) = {
3704 let field_mb = ctx.pos.field;
3705 let bot = mb_y & 1;
3706 let top = mb_y & !1;
3707 // The field of a complementary pair, or of an MBAFF frame's field
3708 // macroblock pair, a frame macroblock takes its co-located block from.
3709 let by_poc =
3710 usize::from((store.fpoc[0] - ctx.poc).abs() >= (store.fpoc[1] - ctx.poc).abs());
3711 if store.coding == CODED_FLD {
3712 let p = if field_mb { bot } else { by_poc };
3713 let Some(f) = store.fields.get(p) else {
3714 return NONE;
3715 };
3716 if field_mb {
3717 (f, mb_x * 4 + at.0, (mb_y / 2) * 4 + at.1, COL_ONE_TO_ONE)
3718 } else {
3719 // mbAddrCol5 and yM = 8 * (CurrMbAddr % 2) + 4 * (yCol / 8).
3720 let by = (mb_y / 2) * 4 + 2 * bot + at.1 / 2;
3721 (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM)
3722 }
3723 } else {
3724 let col_field = store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) != 0;
3725 match (field_mb, col_field) {
3726 (false, false) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE),
3727 (false, true) => {
3728 let slot = top + by_poc;
3729 let by = slot * 4 + 2 * bot + at.1 / 2;
3730 (store, mb_x * 4 + at.0, by, COL_FLD_TO_FRM)
3731 }
3732 (true, false) => {
3733 let slot = top + at.1 / 2;
3734 let by = slot * 4 + (2 * at.1) % 4;
3735 (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD)
3736 }
3737 (true, true) => (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE),
3738 }
3739 }
3740 };
3741 let idx = by * c.mb_w.max(1) * 4 + bx;
3742 if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 {
3743 let list = usize::from(c.ref_id[idx][0] < 0);
3744 (
3745 c.ref_id[idx][list],
3746 c.mv[idx][list],
3747 c.ref_idx[idx][list],
3748 vs,
3749 )
3750 } else {
3751 (-1, [0; 2], -1, vs)
3752 }
3753}
3754
3755/// The co-located block of 8.4.1.2.1 for the 4x4 block `at` of the current
3756/// macroblock: `(refPicCol identity, mvCol, refIdxCol, vertMvScale)`; the
3757/// identity is -1 for an intra block.
3758fn colocated<S: Sample>(
3759 ctx: &SliceCtx,
3760 refs: &[Picture<S>],
3761 mvc: &MvCtx,
3762 at: (usize, usize),
3763) -> (i32, [i16; 2], i8, u8) {
3764 const NONE: (i32, [i16; 2], i8, u8) = (-1, [0; 2], -1, COL_ONE_TO_ONE);
3765 let Some((k, _)) = ctx.lists[1].get_ref(0) else {
3766 return NONE;
3767 };
3768 let Some(store) = refs.get(k) else {
3769 return NONE;
3770 };
3771 if ctx.pos.active {
3772 return colocated_mbaff(ctx, refs, mvc, at);
3773 }
3774 let Some(cur) = ctx.reference(refs, 1, 0) else {
3775 return NONE;
3776 };
3777 let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y);
3778 let w = store.mb_w.max(1);
3779 // Table 8-6 and Table 8-8. `mb_y` is a slot row for an MBAFF frame (the
3780 // pair is `mb_y / 2`, the macroblock of the pair `mb_y % 2`).
3781 let (c, bx, by, vs) = if ctx.structure != FRAME {
3782 if store.coding == CODED_FLD {
3783 (cur, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE)
3784 } else if store.coding == CODED_AFRM {
3785 let top = 2 * mb_y;
3786 if store.mb_field.get(top * w + mb_x).copied().unwrap_or(0) == 0 {
3787 // mbAddrCol6 = 2 * CurrMbAddr + (yCol / 8), yM = (2 * yCol) % 16.
3788 let by = (top + at.1 / 2) * 4 + (2 * at.1) % 4;
3789 (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD)
3790 } else {
3791 // mbAddrCol7 = 2 * CurrMbAddr + bottom_field_flag.
3792 let slot = top + usize::from(ctx.structure == BOTTOM);
3793 (store, mb_x * 4 + at.0, slot * 4 + at.1, COL_ONE_TO_ONE)
3794 }
3795 } else {
3796 // mbAddrCol1 and yM = (2 * yCol) % 16.
3797 let by = (2 * mb_y + at.1 / 2) * 4 + (2 * at.1) % 4;
3798 (store, mb_x * 4 + at.0, by, COL_FRM_TO_FLD)
3799 }
3800 } else if store.coding == CODED_FLD {
3801 let top = (store.fpoc[0] - ctx.poc).abs();
3802 let bottom = (store.fpoc[1] - ctx.poc).abs();
3803 let p = usize::from(top >= bottom);
3804 let Some(f) = store.fields.get(p) else {
3805 return NONE;
3806 };
3807 // mbAddrCol4 and yM = 8 * ((CurrMbAddr / PicWidthInMbs) % 2) + 4 * (yCol / 8).
3808 let by = (mb_y / 2) * 4 + 2 * (mb_y % 2) + at.1 / 2;
3809 (f, mb_x * 4 + at.0, by, COL_FLD_TO_FRM)
3810 } else {
3811 (store, mb_x * 4 + at.0, mb_y * 4 + at.1, COL_ONE_TO_ONE)
3812 };
3813 let idx = by * c.mb_w.max(1) * 4 + bx;
3814 if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 {
3815 let list = usize::from(c.ref_id[idx][0] < 0);
3816 (
3817 c.ref_id[idx][list],
3818 c.mv[idx][list],
3819 c.ref_idx[idx][list],
3820 vs,
3821 )
3822 } else {
3823 (-1, [0; 2], -1, vs)
3824 }
3825}
3826
3827/// The motion vectors chroma prediction uses: the luma vectors, with the
3828/// vertical offset of 8.4.1.4 added when a field predicts from a field of the
3829/// opposite parity.
3830#[inline]
3831fn chroma_mvs<S: Sample>(
3832 ctx: &SliceCtx,
3833 refs: &[Picture<S>],
3834 ref_idx: [i8; 2],
3835 mv: [[i16; 2]; 2],
3836) -> [[i16; 2]; 2] {
3837 let mut out = mv;
3838 if ctx.cat == 2 {
3839 // 4:2:2 chroma is full height: the vertical vector stays in quarter
3840 // samples of the chroma plane, which the eighth-sample interpolator
3841 // reads as twice the value.
3842 for l in out.iter_mut() {
3843 l[1] = l[1].wrapping_mul(2);
3844 }
3845 } else if ctx.is_field() {
3846 for l in 0..2 {
3847 if let Some(rp) = ctx.reference(refs, l, ref_idx[l]) {
3848 out[l][1] = out[l][1].wrapping_add(ctx.chroma_dy(rp));
3849 }
3850 }
3851 }
3852 out
3853}
3854
3855/// The reference plane (`0` luma, `1` Cb, `2` Cr) list `list` predicts from.
3856#[inline(always)]
3857fn ref_plane<'a>(
3858 ctx: &SliceCtx,
3859 refs: &'a [Picture<u8>],
3860 ref_idx: [i8; 2],
3861 list: usize,
3862 comp: usize,
3863) -> Result<RefPlane<'a>> {
3864 let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| {
3865 Error::corrupt("reference index names a picture the buffer does not hold")
3866 })?;
3867 let src = match comp {
3868 0 => &rp.y,
3869 1 => &rp.cb,
3870 _ => &rp.cr,
3871 };
3872 Ok(RefPlane {
3873 data: &src.data,
3874 stride: src.stride,
3875 origin: src.origin,
3876 width: src.width,
3877 height: src.height,
3878 pad: src.pad,
3879 })
3880}
3881
3882/// Motion compensation of one partition (clause 8.4.2): interpolate each list's
3883/// prediction, then combine them by the weighting of 8.4.2.3 and write the
3884/// result straight into the picture, where the residual is added on top.
3885///
3886/// `(px, py)` and `(pw, ph)` are in 4x4 blocks within the macroblock.
3887#[allow(clippy::too_many_arguments)]
3888pub(crate) fn compensate8(
3889 pic: &mut Picture<u8>,
3890 refs: &[Picture<u8>],
3891 ctx: &SliceCtx,
3892 mb_x: usize,
3893 mb_y: usize,
3894 px: usize,
3895 py: usize,
3896 pw: usize,
3897 ph: usize,
3898 mv: [[i16; 2]; 2],
3899 ref_idx: [i8; 2],
3900) -> Result<()> {
3901 let use0 = ref_idx[0] >= 0;
3902 let use1 = ref_idx[1] >= 0;
3903 if !use0 && !use1 {
3904 return Ok(());
3905 }
3906 let geo = ctx.geo(mb_y);
3907 let x0 = (mb_x * 16 + px * 4) as i32;
3908 let y0 = (geo.src_y + py * 4) as i32;
3909 let (w, h) = (pw * 4, ph * 4);
3910 // A stream carrying no weighted prediction at all resolves every
3911 // component to the identity weighting without the per-component lookup.
3912 let plain = ctx.no_weights();
3913 // ChromaArrayType 3 predicts Cb and Cr with the luma interpolation, on
3914 // their own planes and weights.
3915 let ncomp = if ctx.cat == 3 { 3 } else { 1 };
3916 for comp in 0..ncomp {
3917 let wt = if plain {
3918 Weights::DEFAULT
3919 } else {
3920 ctx.weights_for(refs, comp, ref_idx[0], ref_idx[1], use0, use1)
3921 };
3922 // 8.4.2.3.1 over one list is the identity, so the interpolation of that
3923 // one list IS the prediction: it is written straight into the picture at
3924 // the picture's own pitch. Over both lists the combined prediction is the
3925 // rounded byte average of the two clipped ones, so list 0 interpolates
3926 // into the picture and list 1 averages on top of it (Put::Avg) — no
3927 // temporaries, no combining pass, no copy back.
3928 let direct = wt.is_default();
3929 let stride = plane_ref(pic, comp).stride * geo.mul;
3930 let origin = plane_ref(pic, comp).at(x0 as usize, geo.y(py * 4));
3931 // Weighted bi-prediction fuses the same way: the combining formula is
3932 // per-sample, so list 0 lands in the picture and list 1 combines on top
3933 // of it (Put::AvgW) with 8.4.2.3.2's exact integers.
3934 let weighted_put = if !direct && use0 && use1 {
3935 Some(crate::inter::Put::AvgW {
3936 w0: wt.w[0],
3937 w1: wt.w[1],
3938 shift: (wt.log_wd + 1) as u32,
3939 round: 1 << wt.log_wd,
3940 off: (wt.o[0] + wt.o[1] + 1) >> 1,
3941 })
3942 } else {
3943 None
3944 };
3945 if direct && use0 && use1 {
3946 let plane = ref_plane(ctx, refs, ref_idx, 0, comp)?;
3947 mc_luma(
3948 &plane,
3949 x0,
3950 y0,
3951 mv[0],
3952 w,
3953 h,
3954 stride,
3955 &mut plane_mut(pic, comp).data[origin..],
3956 crate::inter::Put::Set,
3957 );
3958 let plane = ref_plane(ctx, refs, ref_idx, 1, comp)?;
3959 mc_luma(
3960 &plane,
3961 x0,
3962 y0,
3963 mv[1],
3964 w,
3965 h,
3966 stride,
3967 &mut plane_mut(pic, comp).data[origin..],
3968 crate::inter::Put::Avg,
3969 );
3970 } else if direct {
3971 // No scratch buffer is declared on this path at all: the scratch is
3972 // zeroed on entry, and most partitions of a P slice come through here.
3973 let list = usize::from(!use0);
3974 let plane = ref_plane(ctx, refs, ref_idx, list, comp)?;
3975 mc_luma(
3976 &plane,
3977 x0,
3978 y0,
3979 mv[list],
3980 w,
3981 h,
3982 stride,
3983 &mut plane_mut(pic, comp).data[origin..],
3984 crate::inter::Put::Set,
3985 );
3986 } else if let Some(put) = weighted_put {
3987 let plane = ref_plane(ctx, refs, ref_idx, 0, comp)?;
3988 mc_luma(
3989 &plane,
3990 x0,
3991 y0,
3992 mv[0],
3993 w,
3994 h,
3995 stride,
3996 &mut plane_mut(pic, comp).data[origin..],
3997 crate::inter::Put::Set,
3998 );
3999 let plane = ref_plane(ctx, refs, ref_idx, 1, comp)?;
4000 mc_luma(
4001 &plane,
4002 x0,
4003 y0,
4004 mv[1],
4005 w,
4006 h,
4007 stride,
4008 &mut plane_mut(pic, comp).data[origin..],
4009 put,
4010 );
4011 } else {
4012 let mut part = [[0u8; 256]; 2];
4013 for list in 0..2 {
4014 if ref_idx[list] < 0 {
4015 continue;
4016 }
4017 let plane = ref_plane(ctx, refs, ref_idx, list, comp)?;
4018 mc_luma(
4019 &plane,
4020 x0,
4021 y0,
4022 mv[list],
4023 w,
4024 h,
4025 w,
4026 &mut part[list],
4027 crate::inter::Put::Set,
4028 );
4029 }
4030 let mut out = [0u8; 256];
4031 let (p0, p1) = part.split_at(1);
4032 combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h);
4033 for row in 0..h {
4034 let dst = origin + row * stride;
4035 plane_mut(pic, comp).data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]);
4036 }
4037 }
4038 }
4039
4040 // Chroma (8.4.1.4): for 4:2:0 frame coding the chroma vector is the luma
4041 // vector, read as eighth-sample units over the half-resolution plane.
4042 if ctx.cat == 0 || ctx.cat == 3 {
4043 return Ok(());
4044 }
4045 let cmv = chroma_mvs(ctx, refs, ref_idx, mv);
4046 let c422 = ctx.cat == 2;
4047 let (cw, ch) = (w / 2, if c422 { h } else { h / 2 });
4048 let (cx0, cy0) = (x0 / 2, if c422 { y0 } else { y0 / 2 });
4049 let crow = if c422 { py * 4 } else { py * 2 };
4050 for comp in 0..2 {
4051 let wt = if plain {
4052 Weights::DEFAULT
4053 } else {
4054 ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1)
4055 };
4056 let direct = wt.is_default();
4057 // The combining weights are per-component syntax (luma and chroma
4058 // carry their own denoms, weights and offsets), so this component's
4059 // fused mode is built from ITS OWN lookup — never the luma one.
4060 let weighted_put = if !direct && use0 && use1 {
4061 Some(crate::inter::Put::AvgW {
4062 w0: wt.w[0],
4063 w1: wt.w[1],
4064 shift: (wt.log_wd + 1) as u32,
4065 round: 1 << wt.log_wd,
4066 off: (wt.o[0] + wt.o[1] + 1) >> 1,
4067 })
4068 } else {
4069 None
4070 };
4071 let plane_out = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
4072 let stride = plane_out.stride * geo.mul;
4073 let origin = plane_out.at(cx0 as usize, geo.cy(crow));
4074 if direct && use0 && use1 {
4075 let plane = ref_plane(ctx, refs, ref_idx, 0, 1 + comp)?;
4076 mc_chroma(
4077 &plane,
4078 cx0,
4079 cy0,
4080 cmv[0],
4081 cw,
4082 ch,
4083 stride,
4084 &mut plane_out.data[origin..],
4085 crate::inter::Put::Set,
4086 );
4087 let plane = ref_plane(ctx, refs, ref_idx, 1, 1 + comp)?;
4088 mc_chroma(
4089 &plane,
4090 cx0,
4091 cy0,
4092 cmv[1],
4093 cw,
4094 ch,
4095 stride,
4096 &mut plane_out.data[origin..],
4097 crate::inter::Put::Avg,
4098 );
4099 } else if let Some(put) = weighted_put {
4100 let plane = ref_plane(ctx, refs, ref_idx, 0, 1 + comp)?;
4101 mc_chroma(
4102 &plane,
4103 cx0,
4104 cy0,
4105 cmv[0],
4106 cw,
4107 ch,
4108 stride,
4109 &mut plane_out.data[origin..],
4110 crate::inter::Put::Set,
4111 );
4112 let plane = ref_plane(ctx, refs, ref_idx, 1, 1 + comp)?;
4113 mc_chroma(
4114 &plane,
4115 cx0,
4116 cy0,
4117 cmv[1],
4118 cw,
4119 ch,
4120 stride,
4121 &mut plane_out.data[origin..],
4122 put,
4123 );
4124 } else if direct {
4125 let list = usize::from(!use0);
4126 let plane = ref_plane(ctx, refs, ref_idx, list, 1 + comp)?;
4127 mc_chroma(
4128 &plane,
4129 cx0,
4130 cy0,
4131 cmv[list],
4132 cw,
4133 ch,
4134 stride,
4135 &mut plane_out.data[origin..],
4136 crate::inter::Put::Set,
4137 );
4138 } else {
4139 let mut cpart = [[0u8; 128]; 2];
4140 for list in 0..2 {
4141 if ref_idx[list] < 0 {
4142 continue;
4143 }
4144 let plane = ref_plane(ctx, refs, ref_idx, list, 1 + comp)?;
4145 mc_chroma(
4146 &plane,
4147 cx0,
4148 cy0,
4149 cmv[list],
4150 cw,
4151 ch,
4152 cw,
4153 &mut cpart[list],
4154 crate::inter::Put::Set,
4155 );
4156 }
4157 let mut cout = [0u8; 128];
4158 let (c0, c1) = cpart.split_at(1);
4159 combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch);
4160 for row in 0..ch {
4161 let dst = origin + row * stride;
4162 plane_out.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]);
4163 }
4164 }
4165 }
4166 Ok(())
4167}
4168
4169/// Motion compensation of one partition over `u16` planes: the same clause
4170/// 8.4.2 process as [`compensate8`], computed per sample from the equations.
4171/// Weighted prediction offsets scale by `1 << (BitDepth - 8)` (8-298, 8-299).
4172#[allow(clippy::too_many_arguments)]
4173pub(crate) fn compensate16(
4174 pic: &mut Picture<u16>,
4175 refs: &[Picture<u16>],
4176 ctx: &SliceCtx,
4177 mb_x: usize,
4178 mb_y: usize,
4179 px: usize,
4180 py: usize,
4181 pw: usize,
4182 ph: usize,
4183 mv: [[i16; 2]; 2],
4184 ref_idx: [i8; 2],
4185) -> Result<()> {
4186 let use0 = ref_idx[0] >= 0;
4187 let use1 = ref_idx[1] >= 0;
4188 if !use0 && !use1 {
4189 return Ok(());
4190 }
4191 let bd = pic.bd;
4192 let max = (1i32 << bd) - 1;
4193 let geo = ctx.geo(mb_y);
4194 let x0 = (mb_x * 16 + px * 4) as i32;
4195 let y0 = (geo.src_y + py * 4) as i32;
4196 let plain = ctx.no_weights();
4197 let cmv = chroma_mvs(ctx, refs, ref_idx, mv);
4198 let cat = pic.cat;
4199 let ncomp = if cat == 0 { 1 } else { 3 };
4200 for comp in 0..ncomp {
4201 let c422 = cat == 2;
4202 let (w, h, cx, cy) = if comp == 0 || cat == 3 {
4203 (pw * 4, ph * 4, x0, y0)
4204 } else if c422 {
4205 (pw * 2, ph * 4, x0 / 2, y0)
4206 } else {
4207 (pw * 2, ph * 2, x0 / 2, y0 / 2)
4208 };
4209 let mut wt = if plain {
4210 Weights::DEFAULT
4211 } else {
4212 ctx.weights_for(refs, comp, ref_idx[0], ref_idx[1], use0, use1)
4213 };
4214 wt.o[0] <<= bd - 8;
4215 wt.o[1] <<= bd - 8;
4216 let mut pred = [[0i32; 256]; 2];
4217 for list in 0..2 {
4218 if ref_idx[list] < 0 {
4219 continue;
4220 }
4221 let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| {
4222 Error::corrupt("reference index names a picture the buffer does not hold")
4223 })?;
4224 match comp {
4225 0 => crate::inter16::luma_pred(&rp.y, cx, cy, mv[list], w, h, max, &mut pred[list]),
4226 1 if cat == 3 => {
4227 crate::inter16::luma_pred(&rp.cb, cx, cy, mv[list], w, h, max, &mut pred[list])
4228 }
4229 _ if cat == 3 => {
4230 crate::inter16::luma_pred(&rp.cr, cx, cy, mv[list], w, h, max, &mut pred[list])
4231 }
4232 1 => crate::inter16::chroma_pred(&rp.cb, cx, cy, cmv[list], w, h, &mut pred[list]),
4233 _ => crate::inter16::chroma_pred(&rp.cr, cx, cy, cmv[list], w, h, &mut pred[list]),
4234 }
4235 }
4236 let plane = match comp {
4237 0 => &mut pic.y,
4238 1 => &mut pic.cb,
4239 _ => &mut pic.cr,
4240 };
4241 let stride = plane.stride * geo.mul;
4242 let origin = if comp == 0 || cat == 3 {
4243 plane.at(cx as usize, geo.y(py * 4))
4244 } else {
4245 plane.at(cx as usize, geo.cy(if c422 { py * 4 } else { py * 2 }))
4246 };
4247 let round1 = if wt.log_wd >= 1 {
4248 1 << (wt.log_wd - 1)
4249 } else {
4250 0
4251 };
4252 for row in 0..h {
4253 for col in 0..w {
4254 let i = row * w + col;
4255 let v = if use0 && use1 {
4256 // 8-301 / 8-300 (default weights reduce to the rounded mean).
4257 ((pred[0][i] * wt.w[0] + pred[1][i] * wt.w[1] + (1 << wt.log_wd))
4258 >> (wt.log_wd + 1))
4259 + ((wt.o[0] + wt.o[1] + 1) >> 1)
4260 } else {
4261 let k = usize::from(!use0);
4262 if wt.log_wd >= 1 {
4263 ((pred[k][i] * wt.w[k] + round1) >> wt.log_wd) + wt.o[k]
4264 } else {
4265 pred[k][i] * wt.w[k] + wt.o[k]
4266 }
4267 };
4268 plane.data[origin + row * stride + col] = v.clamp(0, max) as u16;
4269 }
4270 }
4271 }
4272 Ok(())
4273}
4274
4275/// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2),
4276/// including the top-right substitution rule.
4277pub(crate) fn gather_nbr4<S: Sample>(
4278 pic: &Picture<S>,
4279 nbr: &MbNeighbors,
4280 blk: usize,
4281 x: usize,
4282 y: usize,
4283) -> Nbr4<S> {
4284 gather_nbr4_at(pic, nbr, blk, pic.y.at(x, y), pic.y.stride)
4285}
4286
4287/// [`gather_nbr4`] for a block at plane index `o` in a plane read at row
4288/// pitch `stride` (twice the plane's own for a field macroblock of an MBAFF
4289/// frame, whose neighbouring rows are the same-parity ones).
4290pub(crate) fn gather_nbr4_at<S: Sample>(
4291 pic: &Picture<S>,
4292 nbr: &MbNeighbors,
4293 blk: usize,
4294 o: usize,
4295 stride: usize,
4296) -> Nbr4<S> {
4297 gather_nbr4_in(&pic.y.data, nbr, blk, o, stride)
4298}
4299
4300/// [`gather_nbr4_at`] over any plane's samples (the Cb and Cr planes of 4:4:4
4301/// are predicted like luma).
4302pub(crate) fn gather_nbr4_in<S: Sample>(
4303 data: &[S],
4304 nbr: &MbNeighbors,
4305 blk: usize,
4306 o: usize,
4307 stride: usize,
4308) -> Nbr4<S> {
4309 let (dx, dy) = BLK4_POS[blk];
4310 let have_left = if dx == 0 { nbr.a4[dy as usize] } else { true };
4311 let have_top = if dy == 0 { nbr.b } else { true };
4312 let have_tr = match TR_KIND[blk] {
4313 TrKind::InMb => true,
4314 TrKind::B => nbr.b,
4315 TrKind::C => nbr.c,
4316 TrKind::None => false,
4317 };
4318 let mut top = [S::default(); 8];
4319 top[..4].copy_from_slice(&data[o - stride..o - stride + 4]);
4320 if have_tr {
4321 top[4..].copy_from_slice(&data[o - stride + 4..o - stride + 8]);
4322 } else if have_top {
4323 let t3 = top[3];
4324 top[4..].fill(t3);
4325 }
4326 let mut left = [S::default(); 4];
4327 for (i, l) in left.iter_mut().enumerate() {
4328 *l = data[o + i * stride - 1];
4329 }
4330 Nbr4 {
4331 top,
4332 left,
4333 top_left: data[o - stride - 1],
4334 have_top,
4335 have_left,
4336 }
4337}
4338
4339/// Gather the 25 neighbour samples of an Intra_8x8 luma block (spec 8.3.2.2),
4340/// including the top-right substitution rule, unfiltered.
4341///
4342/// `blk8` is luma8x8BlkIdx: block 1 reaches the above-right macroblock for its
4343/// top-right run, block 2 finds it inside this macroblock, and block 3 has none
4344/// (the samples right of it are not decoded yet).
4345pub(crate) fn gather_nbr8<S: Sample>(
4346 pic: &Picture<S>,
4347 nbr: &MbNeighbors,
4348 blk8: usize,
4349 x: usize,
4350 y: usize,
4351) -> Nbr8<S> {
4352 gather_nbr8_at(pic, nbr, blk8, pic.y.at(x, y), pic.y.stride)
4353}
4354
4355/// [`gather_nbr8`] at plane index `o` with row pitch `stride`.
4356pub(crate) fn gather_nbr8_at<S: Sample>(
4357 pic: &Picture<S>,
4358 nbr: &MbNeighbors,
4359 blk8: usize,
4360 o: usize,
4361 stride: usize,
4362) -> Nbr8<S> {
4363 gather_nbr8_in(&pic.y.data, nbr, blk8, o, stride)
4364}
4365
4366/// [`gather_nbr8_at`] over any plane's samples.
4367pub(crate) fn gather_nbr8_in<S: Sample>(
4368 data: &[S],
4369 nbr: &MbNeighbors,
4370 blk8: usize,
4371 o: usize,
4372 stride: usize,
4373) -> Nbr8<S> {
4374 let have_top = if blk8 < 2 { nbr.b } else { true };
4375 let have_left = if blk8.is_multiple_of(2) {
4376 nbr.a4[blk8] && nbr.a4[blk8 + 1]
4377 } else {
4378 true
4379 };
4380 let have_tr = match blk8 {
4381 0 => nbr.b,
4382 1 => nbr.c,
4383 2 => true,
4384 _ => false,
4385 };
4386 let have_tl = match blk8 {
4387 0 => nbr.d,
4388 1 => nbr.b,
4389 2 => nbr.a4[1],
4390 _ => true,
4391 };
4392 let mut top = [S::default(); 16];
4393 top[..8].copy_from_slice(&data[o - stride..o - stride + 8]);
4394 if have_tr {
4395 top[8..].copy_from_slice(&data[o - stride + 8..o - stride + 16]);
4396 } else {
4397 let t7 = top[7];
4398 top[8..].fill(t7);
4399 }
4400 let mut left = [S::default(); 8];
4401 for (i, l) in left.iter_mut().enumerate() {
4402 *l = data[o + i * stride - 1];
4403 }
4404 Nbr8 {
4405 top,
4406 left,
4407 top_left: data[o - stride - 1],
4408 have_top,
4409 have_left,
4410 have_tl,
4411 }
4412}
4413
4414/// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all
4415/// vertical edges then all horizontal edges per macroblock, then chroma.
4416// `e` and `j` are edge and segment positions inside the macroblock, used to
4417// index the plane as well as the strength arrays; iterating the arrays would
4418// hide which geometry each one names.
4419#[allow(clippy::needless_range_loop)]
4420pub(crate) fn deblock_picture<S: Sample>(pic: &mut Picture<S>) {
4421 let mb_w = pic.mb_w;
4422 let bd = pic.bd;
4423 let max = (1i32 << bd) - 1;
4424 let qp_bd = 6 * (bd as i32 - 8);
4425 let cmb_h = pic.cmb_h;
4426 let cat = pic.cat;
4427 let lcomps = if cat == 3 { 3 } else { 1 };
4428 for mb_y in 0..pic.mb_h {
4429 for mb_x in 0..mb_w {
4430 let addr = mb_y * mb_w + mb_x;
4431 if pic.mb_flags[addr] & FLAG_DECODED == 0 {
4432 continue;
4433 }
4434 let sid = pic.mb_slice[addr];
4435 let sp = pic.slices[sid as usize];
4436 if sp.disable_deblock_idc == 1 {
4437 continue;
4438 }
4439 let decoded = |a: usize| pic.mb_flags[a] & FLAG_DECODED != 0;
4440 let cross_ok = |a: usize| sp.disable_deblock_idc != 2 || pic.mb_slice[a] == sid;
4441 let filter_left = mb_x > 0 && decoded(addr - 1) && cross_ok(addr - 1);
4442 let filter_top = mb_y > 0 && decoded(addr - mb_w) && cross_ok(addr - mb_w);
4443 // Deblocking QP: 0 for I_PCM macroblocks (8.7.2).
4444 let qp_of = |a: usize| -> i32 {
4445 if pic.mb_flags[a] & FLAG_PCM != 0 {
4446 0
4447 } else {
4448 i32::from(pic.mb_qp[a])
4449 }
4450 };
4451 // 8.7: an 8x8-transform macroblock has no transform edge at luma
4452 // 4 or 12, so those internal edges are not filtered. Chroma is
4453 // unaffected for 4:2:0 (its internal edge sits on luma edge 8).
4454 let internal =
4455 |e: usize| e.is_multiple_of(2) || pic.mb_flags[addr] & FLAG_TRANS8X8 == 0;
4456
4457 // Boundary strengths, per 4-sample segment of each edge (8.7.2.1).
4458 //
4459 // Both sides of an internal edge live in this macroblock, so the
4460 // whole 8.7.2.1 ladder is decided once for all 24 of them: an intra
4461 // macroblock gives 3 everywhere, and an inter macroblock with no
4462 // luma coefficients and one motion vector over the whole 16x16
4463 // gives 0 everywhere. Only the two macroblock edges then need the
4464 // per-segment derivation.
4465 let mut bs_v = [[0u8; 4]; 4];
4466 let mut bs_h = [[0u8; 4]; 4];
4467 let cur_intra = pic.mb_flags[addr] & FLAG_INTER == 0;
4468 let internal_uniform = if cur_intra {
4469 Some(3)
4470 } else if pic.mb_cbp[addr] == 0 && uniform_motion(pic, mb_x, mb_y) {
4471 Some(0)
4472 } else {
4473 None
4474 };
4475 for k in 0..4 {
4476 if filter_left {
4477 bs_v[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, true);
4478 }
4479 if filter_top {
4480 bs_h[0][k] = boundary_strength(pic, mb_x, mb_y, 0, k, false);
4481 }
4482 }
4483 for e in 1..4 {
4484 match internal_uniform {
4485 Some(bs) => {
4486 bs_v[e] = [bs; 4];
4487 bs_h[e] = [bs; 4];
4488 }
4489 None => {
4490 for k in 0..4 {
4491 bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true);
4492 bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false);
4493 }
4494 }
4495 }
4496 }
4497
4498 // ---- luma (and Cb/Cr, coded like luma, for ChromaArrayType 3) ----
4499 for comp in 0..lcomps {
4500 let pl: &mut PicPlane<S> = match comp {
4501 0 => &mut pic.y,
4502 1 => &mut pic.cb,
4503 _ => &mut pic.cr,
4504 };
4505 let stride = pl.stride;
4506 let base = pl.at(mb_x * 16, mb_y * 16);
4507 let qpf = |a: usize| -> i32 {
4508 if comp == 0 {
4509 qp_of(a)
4510 } else {
4511 let s = pic.slices[pic.mb_slice[a] as usize];
4512 let off = if comp == 1 {
4513 s.cb_qp_offset
4514 } else {
4515 s.cr_qp_offset
4516 };
4517 let q = if pic.mb_flags[a] & FLAG_PCM != 0 {
4518 0
4519 } else {
4520 i32::from(pic.mb_qp[a])
4521 };
4522 chroma_qp(q, off, qp_bd)
4523 }
4524 };
4525 let qp_q = qpf(addr);
4526 // Lossless macroblocks keep their samples (8.7.2.2).
4527 let lossless = |a: usize| {
4528 pic.bypass_enabled
4529 && pic.mb_flags[a] & FLAG_PCM == 0
4530 && i32::from(pic.mb_qp[a]) + qp_bd == 0
4531 };
4532 let (p_ll_v, q_ll) = (filter_left && lossless(addr - 1), lossless(addr));
4533 let snap_v = (p_ll_v || (filter_left && q_ll))
4534 .then(|| snap_edge(&pl.data, base, stride, true));
4535 // Vertical edges (filter across columns), left to right.
4536 for e in 0..4 {
4537 if e == 0 && !filter_left {
4538 continue;
4539 }
4540 if !internal(e) {
4541 continue;
4542 }
4543 let qp_p = if e == 0 { qpf(addr - 1) } else { qp_q };
4544 let qp_avg = (qp_p + qp_q + 1) >> 1;
4545 // Vertical edges stay scalar: a gather/scatter SIMD
4546 // variant measured slower than this loop (strided
4547 // per-lane loads dominate).
4548 for j in 0..4 {
4549 let bs = bs_v[e][j];
4550 if bs == 0 {
4551 continue;
4552 }
4553 let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd);
4554 if params.alpha == 0 || params.beta == 0 {
4555 continue;
4556 }
4557 for k in 0..4 {
4558 let row = j * 4 + k;
4559 filter_luma_line(
4560 &mut pl.data,
4561 max,
4562 base + row * stride + e * 4,
4563 1,
4564 &params,
4565 );
4566 }
4567 }
4568 }
4569 if let Some(sv) = &snap_v {
4570 restore_edge(&mut pl.data, sv, base, stride, true, p_ll_v, q_ll);
4571 }
4572 let p_ll_h = filter_top && lossless(addr - mb_w);
4573 let snap_h = (p_ll_h || (filter_top && q_ll))
4574 .then(|| snap_edge(&pl.data, base, stride, false));
4575 // Horizontal edges, top to bottom.
4576 for e in 0..4 {
4577 if e == 0 && !filter_top {
4578 continue;
4579 }
4580 if !internal(e) {
4581 continue;
4582 }
4583 let qp_p = if e == 0 { qpf(addr - mb_w) } else { qp_q };
4584 let qp_avg = (qp_p + qp_q + 1) >> 1;
4585 let bs = bs_h[e];
4586 let uniform = bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3];
4587 if uniform {
4588 if bs[0] == 0 {
4589 continue;
4590 }
4591 let params =
4592 edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0], bd);
4593 if params.alpha == 0 || params.beta == 0 {
4594 continue;
4595 }
4596 // Eight rows around the edge are contiguous, so the
4597 // whole 16-sample edge filters in one pass.
4598 S::filter_luma_h_edge16(
4599 &mut pl.data,
4600 max,
4601 base + e * 4 * stride,
4602 stride,
4603 &params,
4604 );
4605 continue;
4606 }
4607 for j in 0..4 {
4608 if bs[j] == 0 {
4609 continue;
4610 }
4611 let params =
4612 edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[j], bd);
4613 if params.alpha == 0 || params.beta == 0 {
4614 continue;
4615 }
4616 for k in 0..4 {
4617 filter_luma_line(
4618 &mut pl.data,
4619 max,
4620 base + e * 4 * stride + j * 4 + k,
4621 stride,
4622 &params,
4623 );
4624 }
4625 }
4626 }
4627 if let Some(sh) = &snap_h {
4628 restore_edge(&mut pl.data, sh, base, stride, false, p_ll_h, q_ll);
4629 }
4630 }
4631
4632 // ---- chroma (Cb, Cr) ----
4633 for comp in 0..if matches!(cat, 1 | 2) { 2 } else { 0 } {
4634 let (plane, off_sel): (&mut PicPlane<S>, fn(&SliceParams) -> i32) = if comp == 0 {
4635 (&mut pic.cb, |s| s.cb_qp_offset)
4636 } else {
4637 (&mut pic.cr, |s| s.cr_qp_offset)
4638 };
4639 let stride = plane.stride;
4640 let c422 = cat == 2;
4641 let base = plane.origin + (mb_y * cmb_h) * stride + mb_x * 8;
4642 // Chroma QP per side: each macroblock's luma QP mapped with
4643 // the offset of ITS OWN slice's PPS (8.7.2).
4644 let cqp = |a: usize| -> i32 {
4645 let s = pic.slices[pic.mb_slice[a] as usize];
4646 if pic.mb_flags[a] & FLAG_PCM != 0 {
4647 chroma_qp(0, off_sel(&s), qp_bd)
4648 } else {
4649 chroma_qp(i32::from(pic.mb_qp[a]), off_sel(&s), qp_bd)
4650 }
4651 };
4652 let cq_q = cqp(addr);
4653 // A chroma edge inherits the boundary strength of the luma edge
4654 // it sits on: chroma sample k maps to luma sample 2k, so a
4655 // chroma 4-sample run spans two luma 4x4 block rows.
4656 for e in 0..2 {
4657 if e == 0 && !filter_left {
4658 continue;
4659 }
4660 let cq_p = if e == 0 { cqp(addr - 1) } else { cq_q };
4661 let qp_avg = (cq_p + cq_q + 1) >> 1;
4662 for k in 0..cmb_h {
4663 let bs = bs_v[e * 2][k >> if c422 { 2 } else { 1 }];
4664 if bs == 0 {
4665 continue;
4666 }
4667 let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd);
4668 if params.alpha == 0 || params.beta == 0 {
4669 continue;
4670 }
4671 filter_chroma_line(
4672 &mut plane.data,
4673 max,
4674 base + k * stride + e * 4,
4675 1,
4676 &params,
4677 );
4678 }
4679 }
4680 // 4:2:2 chroma is as tall as luma: its horizontal 4x4 transform
4681 // edges sit at rows 0, 4, 8 and 12, each on the boundary
4682 // strength of the luma edge on the same row.
4683 for e in 0..if c422 { 4 } else { 2 } {
4684 if e == 0 && !filter_top {
4685 continue;
4686 }
4687 let cq_p = if e == 0 { cqp(addr - mb_w) } else { cq_q };
4688 let qp_avg = (cq_p + cq_q + 1) >> 1;
4689 let bs = bs_h[if c422 { e } else { e * 2 }];
4690 if bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3] {
4691 if bs[0] == 0 {
4692 continue;
4693 }
4694 let params =
4695 edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0], bd);
4696 if params.alpha == 0 || params.beta == 0 {
4697 continue;
4698 }
4699 // The four rows around the edge are contiguous, so the
4700 // whole eight-sample edge filters in one pass.
4701 S::filter_chroma_h_edge8(
4702 &mut plane.data,
4703 max,
4704 base + e * 4 * stride,
4705 stride,
4706 &params,
4707 );
4708 continue;
4709 }
4710 for k in 0..8 {
4711 let bs = bs[k / 2];
4712 if bs == 0 {
4713 continue;
4714 }
4715 let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs, bd);
4716 if params.alpha == 0 || params.beta == 0 {
4717 continue;
4718 }
4719 filter_chroma_line(
4720 &mut plane.data,
4721 max,
4722 base + e * 4 * stride + k,
4723 stride,
4724 &params,
4725 );
4726 }
4727 }
4728 }
4729 }
4730 }
4731}
4732
4733/// Copy the 8 samples across a macroblock edge (4 each side) along its 16
4734/// samples, so a lossless side can be put back after the filter ran.
4735fn snap_edge<S: Sample>(data: &[S], base: usize, stride: usize, vertical: bool) -> Vec<S> {
4736 let mut v = Vec::with_capacity(128);
4737 for i in 0..16 {
4738 for d in 0..8 {
4739 v.push(if vertical {
4740 data[base + i * stride + d - 4]
4741 } else {
4742 data[base + d * stride + i - 4 * stride]
4743 });
4744 }
4745 }
4746 v
4747}
4748
4749fn restore_edge<S: Sample>(
4750 data: &mut [S],
4751 snap: &[S],
4752 base: usize,
4753 stride: usize,
4754 vertical: bool,
4755 p: bool,
4756 q: bool,
4757) {
4758 for i in 0..16 {
4759 for d in 0..8 {
4760 if (d < 4 && !p) || (d >= 4 && !q) {
4761 continue;
4762 }
4763 let idx = if vertical {
4764 base + i * stride + d - 4
4765 } else {
4766 base + d * stride + i - 4 * stride
4767 };
4768 data[idx] = snap[i * 8 + d];
4769 }
4770 }
4771}
4772
4773/// True when every 4x4 block of this macroblock predicts from the same
4774/// pictures with the same motion, so no internal edge can reach the motion
4775/// clauses of 8.7.2.1.
4776fn uniform_motion<S: Sample>(pic: &Picture<S>, mb_x: usize, mb_y: usize) -> bool {
4777 let w4 = pic.mb_w * 4;
4778 let first = mb_y * 4 * w4 + mb_x * 4;
4779 let (mv, id) = (pic.mv[first], pic.ref_id[first]);
4780 (0..4).all(|by| {
4781 let row = first + by * w4;
4782 (0..4).all(|bx| pic.mv[row + bx] == mv && pic.ref_id[row + bx] == id)
4783 })
4784}
4785
4786/// What clause 8.7.2.1 needs from the 4x4 block on one side of a luma edge.
4787#[derive(Clone, Copy)]
4788pub(crate) struct BsSide {
4789 /// The containing macroblock is intra: strength 4 on macroblock edges and
4790 /// 3 on internal ones, regardless of motion or levels.
4791 pub(crate) intra: bool,
4792 /// The transform block containing this sample has non-zero levels.
4793 pub(crate) coded: bool,
4794 /// MvLX of the block, `[list][component]`.
4795 pub(crate) mv: [[i16; 2]; 2],
4796 /// RefIdxLX of the block as list identities (`Picture::id`), -1 unused.
4797 pub(crate) refs: [i32; 2],
4798}
4799
4800/// Boundary strength between the 4x4 blocks on the two sides of a luma edge
4801/// (clause 8.7.2.1). `mb_edge` selects the macroblock-edge strengths 4/3.
4802pub(crate) fn bs_between(p: &BsSide, q: &BsSide, mb_edge: bool, field: bool, vertical: bool) -> u8 {
4803 if p.intra || q.intra {
4804 // A horizontal edge of a field picture is never strength 4 (8.7.2.1).
4805 return if mb_edge && (vertical || !field) {
4806 4
4807 } else {
4808 3
4809 };
4810 }
4811 if p.coded || q.coded {
4812 return 2;
4813 }
4814 let (pr, qr) = (p.refs, q.refs);
4815 let pn = u8::from(pr[0] >= 0) + u8::from(pr[1] >= 0);
4816 let qn = u8::from(qr[0] >= 0) + u8::from(qr[1] >= 0);
4817 if pn != qn {
4818 return 1;
4819 }
4820 let (pm, qm) = (p.mv, q.mv);
4821 // The vertical limit is 4 quarter frame samples: 2 in field units.
4822 let ylim = if field { 2 } else { 4 };
4823 let differs = |a: [i16; 2], b: [i16; 2]| {
4824 (i32::from(a[0]) - i32::from(b[0])).abs() >= 4
4825 || (i32::from(a[1]) - i32::from(b[1])).abs() >= ylim
4826 };
4827 if pn == 1 {
4828 let pl = usize::from(pr[0] < 0);
4829 let ql = usize::from(qr[0] < 0);
4830 if pr[pl] != qr[ql] {
4831 return 1;
4832 }
4833 return u8::from(differs(pm[pl], qm[ql]));
4834 }
4835 if pn == 0 {
4836 return 0;
4837 }
4838 // Two motion vectors each: compare the two partitions by which pictures
4839 // they reference, not by list position (NOTE 1 of 8.7.2.1).
4840 let same_set = (pr[0] == qr[0] && pr[1] == qr[1]) || (pr[0] == qr[1] && pr[1] == qr[0]);
4841 if !same_set {
4842 return 1;
4843 }
4844 if pr[0] != pr[1] {
4845 return if pr[0] == qr[0] {
4846 u8::from(differs(pm[0], qm[0]) || differs(pm[1], qm[1]))
4847 } else {
4848 u8::from(differs(pm[0], qm[1]) || differs(pm[1], qm[0]))
4849 };
4850 }
4851 // Both lists name the same picture: either pairing agreeing is enough.
4852 let straight = !differs(pm[0], qm[0]) && !differs(pm[1], qm[1]);
4853 let crossed = !differs(pm[0], qm[1]) && !differs(pm[1], qm[0]);
4854 u8::from(!(straight || crossed))
4855}
4856
4857/// One side of a luma edge from picture state: the decoder path, both sides
4858/// final macroblocks. The encoder's inter trial uses this for the
4859/// already-coded neighbour and builds its candidate side itself.
4860pub(crate) fn bs_side<S: Sample>(pic: &Picture<S>, bx: usize, by: usize) -> BsSide {
4861 let w4 = pic.mb_w * 4;
4862 let mb = (by / 4) * pic.mb_w + bx / 4;
4863 BsSide {
4864 intra: pic.mb_flags[mb] & FLAG_INTER == 0,
4865 coded: bs_coded(pic, mb, bx, by),
4866 mv: pic.mv[by * w4 + bx],
4867 refs: pic.ref_id[by * w4 + bx],
4868 }
4869}
4870
4871/// "The transform block containing the sample has non-zero levels": for an
4872/// 8x8-transform macroblock that is the whole 8x8, whose four 4x4 slots
4873/// carry per-slot counts under CAVLC (7.3.5.3.1 splits it into four blocks).
4874fn bs_coded<S: Sample>(pic: &Picture<S>, mb: usize, bx: usize, by: usize) -> bool {
4875 let w4 = pic.mb_w * 4;
4876 if pic.mb_flags[mb] & FLAG_TRANS8X8 == 0 {
4877 return pic.nz_y[by * w4 + bx] != 0;
4878 }
4879 let (ox, oy) = (bx & !1, by & !1);
4880 pic.nz_y[oy * w4 + ox] != 0
4881 || pic.nz_y[oy * w4 + ox + 1] != 0
4882 || pic.nz_y[(oy + 1) * w4 + ox] != 0
4883 || pic.nz_y[(oy + 1) * w4 + ox + 1] != 0
4884}
4885
4886/// Boundary strength of one 4-sample luma edge segment (clause 8.7.2.1).
4887///
4888/// `edge` 0..4 selects the vertical (`vertical`) or horizontal edge inside the
4889/// macroblock, `seg` the 4-sample run along it. Edge 0 is the macroblock edge.
4890fn boundary_strength<S: Sample>(
4891 pic: &Picture<S>,
4892 mb_x: usize,
4893 mb_y: usize,
4894 edge: usize,
4895 seg: usize,
4896 vertical: bool,
4897) -> u8 {
4898 let (qbx, qby) = if vertical {
4899 (mb_x * 4 + edge, mb_y * 4 + seg)
4900 } else {
4901 (mb_x * 4 + seg, mb_y * 4 + edge)
4902 };
4903 let (pbx, pby) = if vertical {
4904 (qbx - 1, qby)
4905 } else {
4906 (qbx, qby - 1)
4907 };
4908 bs_between(
4909 &bs_side(pic, pbx, pby),
4910 &bs_side(pic, qbx, qby),
4911 edge == 0,
4912 pic.structure != FRAME,
4913 vertical,
4914 )
4915}
4916
4917#[cfg(test)]
4918mod tests {
4919 use super::*;
4920 use crate::dpb::RefList;
4921 use ec_h264_syntax::{PredWeightTable, WeightEntry};
4922
4923 /// A picture whose visible samples are a fixed ramp, borders replicated.
4924 fn ramp_picture(value: impl Fn(usize, usize) -> u8) -> Picture {
4925 let mut pic = Picture {
4926 mb_w: 1,
4927 mb_h: 1,
4928 ..Default::default()
4929 };
4930 for (plane, size) in [(0usize, 16usize), (1, 8), (2, 8)] {
4931 let p = match plane {
4932 0 => &mut pic.y,
4933 1 => &mut pic.cb,
4934 _ => &mut pic.cr,
4935 };
4936 let pad = 8;
4937 let stride = size + 2 * pad;
4938 let mut data = vec![0u8; stride * (size + 2 * pad)];
4939 for y in 0..size {
4940 for x in 0..size {
4941 data[(pad + y) * stride + pad + x] = value(x, y);
4942 }
4943 }
4944 *p = PicPlane {
4945 data,
4946 stride,
4947 origin: pad * stride + pad,
4948 width: size,
4949 height: size,
4950 pad,
4951 };
4952 p.extend_borders();
4953 }
4954 pic
4955 }
4956
4957 fn plane_byte(p: &PicPlane, x: usize, y: usize) -> u8 {
4958 p.data[p.origin + y * p.stride + x]
4959 }
4960
4961 /// Explicit-weight bipred combines each component with ITS OWN weights:
4962 /// luma and chroma signal independent denoms/weights/offsets, so chroma
4963 /// must never ride the luma lookup (regression guard for the fused
4964 /// weighted path in [`compensate`]).
4965 #[test]
4966 fn weighted_bipred_combines_per_component() {
4967 let refs = vec![
4968 ramp_picture(|x, y| (40 + x * 3 + y) as u8),
4969 ramp_picture(|x, y| (220 - x - y * 2) as u8),
4970 ];
4971 let mut l0 = RefList::default();
4972 l0.push(0);
4973 let mut l1 = RefList::default();
4974 l1.push(1);
4975 let ctx = SliceCtx {
4976 structure: FRAME,
4977 mb_parity: FRAME,
4978 pos: MbPos::default(),
4979 slice_id: 0,
4980 slice_type: SliceType::B,
4981 qp: 30,
4982 cb_qp_offset: 0,
4983 cr_qp_offset: 0,
4984 cmb_h: 8,
4985 cat: 1,
4986 transform_8x8_mode: false,
4987 constrained_intra_pred: false,
4988 qp_delta_inc: 0,
4989 lists: [l0, l1],
4990 num_ref_idx: [1, 1],
4991 direct_spatial: true,
4992 direct_8x8_inference: true,
4993 weighted_pred: false,
4994 weighted_bipred_idc: 1,
4995 weights: Some(PredWeightTable {
4996 luma_log2_weight_denom: 1,
4997 chroma_log2_weight_denom: 2,
4998 l0: vec![WeightEntry {
4999 luma: Some((2, 1)),
5000 chroma: Some([(5, 2), (7, 3)]),
5001 }],
5002 l1: vec![WeightEntry {
5003 luma: Some((2, 1)),
5004 chroma: Some([(5, 2), (7, 3)]),
5005 }],
5006 }),
5007 poc: 4,
5008 fpoc: [4, 4],
5009 shapes: MbShapes::default(),
5010 };
5011 let mut pic = ramp_picture(|_, _| 0);
5012
5013 compensate8(&mut pic, &refs, &ctx, 0, 0, 0, 0, 4, 4, [[0, 0]; 2], [0, 0])
5014 .expect("compensate");
5015
5016 let expected = |p0: u8, p1: u8, w: i32, log_wd: u32, o: i32| -> u8 {
5017 let v = (((i32::from(p0) * w + i32::from(p1) * w + (1 << log_wd)) >> (log_wd + 1)) + o)
5018 .clamp(0, 255);
5019 v as u8
5020 };
5021 // Luma: weights (2, 1) — whatever luma does is the luma reference
5022 // behaviour; the point is chroma below.
5023 for y in 0..16 {
5024 for x in 0..16 {
5025 let (p0, p1) = (plane_byte(&refs[0].y, x, y), plane_byte(&refs[1].y, x, y));
5026 assert_eq!(
5027 plane_byte(&pic.y, x, y),
5028 expected(p0, p1, 2, 1, 1),
5029 "luma ({x},{y})"
5030 );
5031 }
5032 }
5033 // Chroma Cb: weights (5, 2) with denom 2 — NOT the luma weights.
5034 for y in 0..8 {
5035 for x in 0..8 {
5036 let (p0, p1) = (plane_byte(&refs[0].cb, x, y), plane_byte(&refs[1].cb, x, y));
5037 assert_eq!(
5038 plane_byte(&pic.cb, x, y),
5039 expected(p0, p1, 5, 2, 2),
5040 "cb ({x},{y})"
5041 );
5042 let (p0, p1) = (plane_byte(&refs[0].cr, x, y), plane_byte(&refs[1].cr, x, y));
5043 assert_eq!(
5044 plane_byte(&pic.cr, x, y),
5045 expected(p0, p1, 7, 2, 3),
5046 "cr ({x},{y})"
5047 );
5048 }
5049 }
5050 }
5051}