forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB30d372eTahinli3 months ago42 commits

decoder.rs1056 lines, 38.5 KiBHistoryRawDownload
1//! Decoder core: parameter-set store, flat per-picture context, 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), so neighbour
6//! gathers and future inter-prediction overreach never bounds-check per
7//! sample and edge availability is data, not arithmetic.
8//! - All per-macroblock state lives in flat struct-of-arrays keyed by
9//! macroblock address or 4x4-block coordinate: non-zero coefficient counts
10//! (`nz_y`, `nz_c`), intra 4x4 modes, QP, flags, owning slice. No per-MB
11//! heap objects anywhere.
12//! - Buffers are reused across pictures; a picture start is O(macroblocks)
13//! fills, and the slice decode loop performs zero allocations.
14
15use ec_core::BitReader;
16use ec_core::error::{Error, Result};
17use ec_core::frame::{PixelFormat, Plane, VideoFrame};
18use ec_h264_syntax::{
19 AnnexBIter, NalHeader, NalUnitType, Pps, SliceHeader, SliceType, Sps, unescape_rbsp,
20};
21
22use crate::deblock::{
23 chroma_qp, edge_params, filter_chroma_line, filter_luma_h_edge16, filter_luma_line,
24};
25use crate::entropy::{
26 BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_PCM, MbCtx, MbInfo,
27};
28use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8};
29use crate::tables::{BLK4_POS, CHROMA_QP};
30use crate::transform::{
31 LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, luma_dc_transform,
32 unzigzag, unzigzag_ac15,
33};
34
35/// Luma plane padding on every side, sized for future inter-prediction
36/// filter overreach (16 MB + margin).
37const PAD_Y: usize = 32;
38/// Chroma plane padding on every side.
39const PAD_C: usize = 16;
40/// `mb_slice` value for a not-yet-decoded macroblock.
41const NO_SLICE: u16 = u16::MAX;
42
43/// Where a 4x4 block's top-right neighbour samples come from, per
44/// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule).
45#[derive(Clone, Copy, PartialEq)]
46enum TrKind {
47 /// Bottom row of an earlier block in this macroblock: always available.
48 InMb,
49 /// The macroblock above.
50 B,
51 /// The macroblock above-right.
52 C,
53 /// Never available (right column, or blkIdx 3/11).
54 None,
55}
56
57const TR_KIND: [TrKind; 16] = [
58 TrKind::B,
59 TrKind::B,
60 TrKind::InMb,
61 TrKind::None,
62 TrKind::B,
63 TrKind::C,
64 TrKind::InMb,
65 TrKind::None,
66 TrKind::InMb,
67 TrKind::InMb,
68 TrKind::InMb,
69 TrKind::None,
70 TrKind::InMb,
71 TrKind::None,
72 TrKind::InMb,
73 TrKind::None,
74];
75
76/// A padded 8-bit plane.
77#[derive(Debug, Default)]
78struct Plane8 {
79 data: Vec<u8>,
80 stride: usize,
81 /// Index of sample (0, 0) of the picture.
82 origin: usize,
83}
84
85impl Plane8 {
86 fn resize(&mut self, width: usize, height: usize, pad: usize) {
87 self.stride = width + 2 * pad;
88 self.origin = pad * self.stride + pad;
89 self.data.clear();
90 self.data.resize(self.stride * (height + 2 * pad), 0);
91 }
92
93 #[inline]
94 fn at(&self, x: usize, y: usize) -> usize {
95 self.origin + y * self.stride + x
96 }
97}
98
99/// Per-slice values the deblocking filter needs after slice decode ends.
100#[derive(Debug, Clone, Copy)]
101struct SliceParams {
102 disable_deblock_idc: u8,
103 alpha_offset: i32,
104 beta_offset: i32,
105 cb_qp_offset: i32,
106 cr_qp_offset: i32,
107}
108
109/// Flat per-picture decode context (see module docs for the layout story).
110#[derive(Debug, Default)]
111struct Picture {
112 sps_id: u8,
113 mb_w: usize,
114 mb_h: usize,
115 y: Plane8,
116 cb: Plane8,
117 cr: Plane8,
118 /// TotalCoeff per luma 4x4 block, `(mb_w * 4) x (mb_h * 4)`.
119 nz_y: Vec<u8>,
120 /// TotalCoeff per chroma 4x4 block, `(mb_w * 2) x (mb_h * 2)`, Cb and Cr.
121 nz_c: [Vec<u8>; 2],
122 /// Intra4x4PredMode per luma 4x4 block (2 = DC for non-I4x4 MBs).
123 i4_modes: Vec<u8>,
124 /// QPY per macroblock (the prediction-chain value; PCM keeps the chain).
125 mb_qp: Vec<u8>,
126 /// `FLAG_*` bits per macroblock.
127 mb_flags: Vec<u8>,
128 /// `CodedBlockPatternLuma | CodedBlockPatternChroma << 4` per macroblock,
129 /// read by CABAC context selection (9.3.3.1.1.4).
130 mb_cbp: Vec<u8>,
131 /// coded_block_flag of the DC blocks per macroblock: bit 0 luma, 1 Cb,
132 /// 2 Cr (9.3.3.1.1.9 with ctxBlockCat 0 and 3).
133 mb_dc_cbf: Vec<u8>,
134 /// Owning slice index per macroblock, `NO_SLICE` when undecoded.
135 mb_slice: Vec<u16>,
136 slices: Vec<SliceParams>,
137 decoded_mbs: usize,
138 complete: bool,
139}
140
141impl Picture {
142 fn start(&mut self, sps: &Sps) {
143 let mb_w = sps.mb_width as usize;
144 let mb_h = sps.mb_height as usize;
145 if self.mb_w != mb_w || self.mb_h != mb_h || self.sps_id != sps.id {
146 self.mb_w = mb_w;
147 self.mb_h = mb_h;
148 self.sps_id = sps.id;
149 self.y.resize(mb_w * 16, mb_h * 16, PAD_Y);
150 self.cb.resize(mb_w * 8, mb_h * 8, PAD_C);
151 self.cr.resize(mb_w * 8, mb_h * 8, PAD_C);
152 self.nz_y.resize(mb_w * mb_h * 16, 0);
153 for c in &mut self.nz_c {
154 c.resize(mb_w * mb_h * 4, 0);
155 }
156 self.i4_modes.resize(mb_w * mb_h * 16, 2);
157 self.mb_qp.resize(mb_w * mb_h, 0);
158 self.mb_flags.resize(mb_w * mb_h, 0);
159 self.mb_cbp.resize(mb_w * mb_h, 0);
160 self.mb_dc_cbf.resize(mb_w * mb_h, 0);
161 self.mb_slice.resize(mb_w * mb_h, NO_SLICE);
162 }
163 // Per-MB metadata is rewritten by each decoded macroblock; only the
164 // "who is decoded" state must be wiped between pictures.
165 self.mb_slice.fill(NO_SLICE);
166 self.mb_flags.fill(0);
167 self.slices.clear();
168 self.decoded_mbs = 0;
169 self.complete = false;
170 }
171}
172
173/// Streaming H.264 decoder (CAVLC intra scope; unsupported features come back
174/// as named [`Error::Unsupported`] values, never wrong pixels).
175pub struct Decoder {
176 sps_map: Vec<Option<Sps>>,
177 pps_map: Vec<Option<Pps>>,
178 rbsp: Vec<u8>,
179 pic: Picture,
180 has_picture: bool,
181 /// Scaling factors for intra Y/Cb/Cr 4x4 lists of the active PPS/SPS.
182 ls: [LevelScale4x4; 3],
183 active_pps: Option<u32>,
184 /// `seq_parameter_set_id` of the most recently stored SPS, so a container
185 /// entry path can publish the picture size before the first slice.
186 last_sps: Option<u8>,
187}
188
189/// What [`Decoder::push_nal`] did with a NAL unit.
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191pub enum NalOutcome {
192 /// SPS or PPS stored.
193 ParameterSet,
194 /// Non-VCL NAL skipped (SEI, AUD, filler, ...).
195 Skipped,
196 /// A slice was decoded into the open picture.
197 SliceDecoded,
198 /// The NAL starts a new picture while one is open; it was not consumed.
199 /// Call [`Decoder::end_picture`] + [`Decoder::frame`], then push it again.
200 PictureBoundary,
201}
202
203impl Default for Decoder {
204 fn default() -> Self {
205 Decoder::new()
206 }
207}
208
209impl Decoder {
210 /// A fresh decoder with no parameter sets.
211 pub fn new() -> Decoder {
212 Decoder {
213 sps_map: vec![None; 32],
214 pps_map: vec![None; 256],
215 rbsp: Vec::new(),
216 pic: Picture::default(),
217 has_picture: false,
218 ls: [
219 LevelScale4x4::new(&[16; 16]),
220 LevelScale4x4::new(&[16; 16]),
221 LevelScale4x4::new(&[16; 16]),
222 ],
223 active_pps: None,
224 last_sps: None,
225 }
226 }
227
228 /// Cropped picture size of the most recently stored SPS, `None` until one
229 /// arrives. Lets a container entry path fill in stream parameters from an
230 /// `avcC` record without decoding a picture first.
231 pub fn picture_size(&self) -> Option<(u32, u32)> {
232 let sps = self.sps_map[self.last_sps? as usize].as_ref()?;
233 Some((sps.width, sps.height))
234 }
235
236 /// Decode the first IDR picture of an Annex B stream and return it.
237 pub fn decode_first_idr(&mut self, annexb: &[u8]) -> Result<VideoFrame> {
238 let mut got_slice = false;
239 for nal in AnnexBIter::new(annexb) {
240 match self.push_nal(nal)? {
241 NalOutcome::PictureBoundary => break,
242 NalOutcome::SliceDecoded => got_slice = true,
243 _ => {}
244 }
245 }
246 if !got_slice {
247 return Err(Error::NeedMore);
248 }
249 self.end_picture()?;
250 self.frame()
251 }
252
253 /// Feed one NAL unit (header byte first, no start code).
254 pub fn push_nal(&mut self, nal: &[u8]) -> Result<NalOutcome> {
255 let Some((&header_byte, payload)) = nal.split_first() else {
256 return Err(Error::NeedMore);
257 };
258 let header = NalHeader::parse(header_byte)?;
259 match header.unit_type {
260 NalUnitType::Sps => {
261 let mut rbsp = core::mem::take(&mut self.rbsp);
262 unescape_rbsp(payload, &mut rbsp);
263 let sps = Sps::parse(&rbsp);
264 self.rbsp = rbsp;
265 let sps = sps?;
266 let id = sps.id;
267 self.sps_map[id as usize] = Some(sps);
268 self.last_sps = Some(id);
269 Ok(NalOutcome::ParameterSet)
270 }
271 NalUnitType::Pps => {
272 let mut rbsp = core::mem::take(&mut self.rbsp);
273 unescape_rbsp(payload, &mut rbsp);
274 let pps = Pps::parse(&rbsp, |id| self.sps_map[id as usize].as_ref());
275 self.rbsp = rbsp;
276 let pps = pps?;
277 let id = pps.id as usize;
278 self.pps_map[id] = Some(pps);
279 Ok(NalOutcome::ParameterSet)
280 }
281 NalUnitType::Slice | NalUnitType::SliceIdr => {
282 let mut rbsp = core::mem::take(&mut self.rbsp);
283 unescape_rbsp(payload, &mut rbsp);
284 let r = self.decode_slice_rbsp(header, &rbsp);
285 self.rbsp = rbsp;
286 r
287 }
288 NalUnitType::SliceDataA | NalUnitType::SliceDataB | NalUnitType::SliceDataC => {
289 Err(Error::unsupported(
290 "slice data partitioning",
291 "nal_unit_type 2 to 4 carry a slice in three NAL units that \
292 clause 7.4.1 reassembles by slice_id; not implemented",
293 ))
294 }
295 _ => Ok(NalOutcome::Skipped),
296 }
297 }
298
299 /// Run the deblocking filter over the open picture and mark it complete.
300 pub fn end_picture(&mut self) -> Result<()> {
301 if !self.has_picture || self.pic.complete {
302 return Err(Error::corrupt("end_picture without an open picture"));
303 }
304 deblock_picture(&mut self.pic);
305 self.pic.complete = true;
306 Ok(())
307 }
308
309 /// Copy the completed picture out as a cropped I420 frame.
310 pub fn frame(&self) -> Result<VideoFrame> {
311 if !self.pic.complete {
312 return Err(Error::corrupt("frame() before end_picture()"));
313 }
314 let sps = self.sps_map[self.pic.sps_id as usize]
315 .as_ref()
316 .ok_or_else(|| Error::corrupt("active SPS vanished"))?;
317 let (w, h) = (sps.width as usize, sps.height as usize);
318 let (cx, cy) = (sps.crop.0 as usize, sps.crop.2 as usize);
319 let copy = |p: &Plane8, x0: usize, y0: usize, w: usize, h: usize| -> Plane {
320 let mut out = vec![0u8; w * h];
321 for row in 0..h {
322 let src = p.at(x0, y0 + row);
323 out[row * w..(row + 1) * w].copy_from_slice(&p.data[src..src + w]);
324 }
325 Plane::new(out, w)
326 };
327 let planes = vec![
328 copy(&self.pic.y, cx, cy, w, h),
329 copy(&self.pic.cb, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)),
330 copy(&self.pic.cr, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)),
331 ];
332 let mut frame = VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)?;
333 if let Some(vui) = &sps.vui {
334 frame.color.full_range = vui.video_full_range;
335 if let Some((p, t, m)) = vui.colour_description {
336 frame.color.primaries = p;
337 frame.color.transfer = t;
338 frame.color.matrix = m;
339 }
340 }
341 Ok(frame)
342 }
343
344 /// True while a picture is open (started, not completed).
345 pub fn picture_open(&self) -> bool {
346 self.has_picture && !self.pic.complete
347 }
348
349 /// Drop picture state after a seek. Parameter sets survive, because the
350 /// container does not resend them at every seek point.
351 pub fn reset_pictures(&mut self) {
352 self.has_picture = false;
353 self.pic.complete = false;
354 }
355
356 fn decode_slice_rbsp(&mut self, header: NalHeader, rbsp: &[u8]) -> Result<NalOutcome> {
357 // Peek first_mb / slice_type / pps_id to select parameter sets.
358 let mut peek = BitReader::new(rbsp);
359 let first_mb = peek.read_ue()?;
360 let slice_type_code = peek.read_ue()?;
361 let pps_id = peek.read_ue()?;
362 if pps_id > 255 {
363 return Err(Error::corrupt("pic_parameter_set_id > 255"));
364 }
365 if self.has_picture && !self.pic.complete && first_mb == 0 && self.pic.decoded_mbs > 0 {
366 return Ok(NalOutcome::PictureBoundary);
367 }
368 let pps = self.pps_map[pps_id as usize]
369 .as_ref()
370 .ok_or_else(|| Error::corrupt("slice refers to an unknown PPS"))?;
371 let sps = self.sps_map[pps.sps_id as usize]
372 .as_ref()
373 .ok_or_else(|| Error::corrupt("PPS refers to an unknown SPS"))?;
374
375 check_supported(sps, pps, slice_type_code)?;
376 let sh = SliceHeader::parse(rbsp, header, sps, pps)?;
377 if sh.slice_type != SliceType::I {
378 return Err(Error::unsupported(
379 "non-I slice",
380 "P/B/SP/SI slices need inter prediction and a decoded picture \
381 buffer (clause 8.4); only intra slices are decoded",
382 ));
383 }
384
385 if !self.has_picture || self.pic.complete {
386 self.pic.start(sps);
387 self.has_picture = true;
388 if self.active_pps != Some(pps.id) {
389 let lists = pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref());
390 let weights = match lists {
391 Some(l) => [&l.list_4x4[0], &l.list_4x4[1], &l.list_4x4[2]],
392 None => [&[16u8; 16]; 3],
393 };
394 self.ls = [
395 LevelScale4x4::new(weights[0]),
396 LevelScale4x4::new(weights[1]),
397 LevelScale4x4::new(weights[2]),
398 ];
399 self.active_pps = Some(pps.id);
400 }
401 }
402 if self.pic.sps_id != sps.id {
403 return Err(Error::corrupt("SPS changed mid-picture"));
404 }
405 if self.pic.slices.len() >= usize::from(u16::MAX) {
406 return Err(Error::corrupt("more than 65534 slices in a picture"));
407 }
408 let slice_id = self.pic.slices.len() as u16;
409 self.pic.slices.push(SliceParams {
410 disable_deblock_idc: sh.deblock.disable_idc,
411 alpha_offset: sh.deblock.alpha_c0_offset,
412 beta_offset: sh.deblock.beta_offset,
413 cb_qp_offset: pps.chroma_qp_index_offset,
414 cr_qp_offset: pps.second_chroma_qp_index_offset,
415 });
416
417 let mut r = if pps.entropy_coding_mode {
418 Entropy::cabac(rbsp, sh.header_bits, sh.slice_qp)?
419 } else {
420 Entropy::cavlc(rbsp, sh.header_bits)
421 };
422
423 let mut ctx = SliceCtx {
424 slice_id,
425 qp: sh.slice_qp,
426 cb_qp_offset: pps.chroma_qp_index_offset,
427 cr_qp_offset: pps.second_chroma_qp_index_offset,
428 transform_8x8_mode: pps.transform_8x8_mode,
429 qp_delta_inc: 0,
430 };
431 let mbs = self.pic.mb_w * self.pic.mb_h;
432 let mut mb_addr = first_mb as usize;
433 loop {
434 if mb_addr >= mbs {
435 return Err(Error::corrupt("macroblock address beyond the picture"));
436 }
437 decode_macroblock(&mut self.pic, &self.ls, &mut r, &mut ctx, mb_addr)?;
438 if !r.more_macroblocks()? {
439 break;
440 }
441 mb_addr += 1;
442 }
443 Ok(NalOutcome::SliceDecoded)
444 }
445}
446
447/// Reject unsupported streams with named reasons before touching pixels.
448///
449/// Every `why` here names the syntax element that fired and the machinery it
450/// would need: a refusal is a capability statement about this binary, and the
451/// conformance suite proves each one against a stream that really uses the
452/// feature.
453fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> {
454 if pps.num_slice_groups > 1 {
455 return Err(Error::unsupported(
456 "FMO slice groups",
457 "num_slice_groups_minus1 > 0 needs the macroblock-to-slice-group \
458 map of clause 8.2.2; only one slice group per picture is decoded",
459 ));
460 }
461 if sps.chroma_format_idc != 1 {
462 return Err(Error::unsupported(
463 "chroma format",
464 format!(
465 "chroma_format_idc {} needs its own chroma prediction, scan and \
466 DC transform; only 4:2:0 (ChromaArrayType 1) is decoded",
467 sps.chroma_format_idc
468 ),
469 ));
470 }
471 if sps.bit_depth_luma != 8 || sps.bit_depth_chroma != 8 {
472 return Err(Error::unsupported(
473 "bit depth",
474 format!(
475 "{}-bit luma / {}-bit chroma needs 16-bit sample planes and the \
476 widened transform clip of clause 8.5; only 8-bit is decoded",
477 sps.bit_depth_luma, sps.bit_depth_chroma
478 ),
479 ));
480 }
481 if !sps.frame_mbs_only {
482 return Err(Error::unsupported(
483 "interlaced coding",
484 "frame_mbs_only_flag 0 admits field pictures and MBAFF, whose \
485 neighbour derivation (6.4.9) and field deblocking are not implemented",
486 ));
487 }
488 if sps.separate_colour_plane {
489 return Err(Error::unsupported(
490 "separate colour planes",
491 "separate_colour_plane_flag 1 codes 4:4:4 as three monochrome \
492 planes with their own slice headers; not implemented",
493 ));
494 }
495 if sps.transform_bypass {
496 return Err(Error::unsupported(
497 "transform bypass",
498 "qpprime_y_zero_transform_bypass_flag 1 makes QP'Y 0 lossless, \
499 bypassing the transform and scaling of 8.5 entirely; not implemented",
500 ));
501 }
502 if slice_type_code > 9 {
503 return Err(Error::corrupt("slice_type > 9"));
504 }
505 Ok(())
506}
507
508/// Mutable per-slice decode state.
509struct SliceCtx {
510 slice_id: u16,
511 qp: i32,
512 cb_qp_offset: i32,
513 cr_qp_offset: i32,
514 transform_8x8_mode: bool,
515 /// ctxIdxInc for the next macroblock's first mb_qp_delta bin: set when the
516 /// macroblock just decoded coded a non-zero mb_qp_delta (9.3.3.1.1.5).
517 qp_delta_inc: u8,
518}
519
520/// Neighbour-availability snapshot for one macroblock (left, top,
521/// top-right). Top-left availability follows from the modes that read it
522/// being conformance-restricted; inter prediction will add it back.
523#[derive(Clone, Copy)]
524struct MbNeighbors {
525 a: bool,
526 b: bool,
527 c: bool,
528}
529
530fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNeighbors {
531 let w = pic.mb_w;
532 let addr = mb_y * w + mb_x;
533 let same = |a: usize| pic.mb_slice[a] == slice_id;
534 MbNeighbors {
535 a: mb_x > 0 && same(addr - 1),
536 b: mb_y > 0 && same(addr - w),
537 c: mb_y > 0 && mb_x + 1 < w && same(addr - w + 1),
538 }
539}
540
541/// Non-zero counts of the left and above neighbours of the luma 4x4 block at
542/// global block coords `(bx, by)`, `None` when that neighbour is unavailable
543/// (clause 6.4.11.4 plus the availability rules of 6.4.8).
544#[inline]
545fn luma_nz_pair(pic: &Picture, n: &MbNeighbors, bx: usize, by: usize) -> (Option<u8>, Option<u8>) {
546 let w4 = pic.mb_w * 4;
547 let left_avail = if bx.is_multiple_of(4) { n.a } else { true };
548 let top_avail = if by.is_multiple_of(4) { n.b } else { true };
549 (
550 (left_avail && bx > 0).then(|| pic.nz_y[by * w4 + bx - 1]),
551 (top_avail && by > 0).then(|| pic.nz_y[(by - 1) * w4 + bx]),
552 )
553}
554
555/// The same for a chroma AC 4x4 block at global chroma block coords.
556#[inline]
557fn chroma_nz_pair(
558 pic: &Picture,
559 n: &MbNeighbors,
560 comp: usize,
561 cx: usize,
562 cy: usize,
563) -> (Option<u8>, Option<u8>) {
564 let w2 = pic.mb_w * 2;
565 let grid = &pic.nz_c[comp];
566 let left_avail = if cx.is_multiple_of(2) { n.a } else { true };
567 let top_avail = if cy.is_multiple_of(2) { n.b } else { true };
568 (
569 (left_avail && cx > 0).then(|| grid[cy * w2 + cx - 1]),
570 (top_avail && cy > 0).then(|| grid[(cy - 1) * w2 + cx]),
571 )
572}
573
574/// Decode one macroblock of an I slice (spec 7.3.5, 7.4.5) and reconstruct
575/// it. `ctx.qp` carries the QPY prediction chain.
576// Block loops are indexed: `blk` is simultaneously a bitstream position, a
577// geometry key (BLK4_POS) and a grid coordinate; iterators obscure that.
578#[allow(clippy::needless_range_loop)]
579fn decode_macroblock(
580 pic: &mut Picture,
581 ls: &[LevelScale4x4; 3],
582 r: &mut Entropy<'_>,
583 ctx: &mut SliceCtx,
584 mb_addr: usize,
585) -> Result<()> {
586 let mb_x = mb_addr % pic.mb_w;
587 let mb_y = mb_addr / pic.mb_w;
588 if pic.mb_slice[mb_addr] != NO_SLICE {
589 return Err(Error::corrupt("macroblock decoded twice"));
590 }
591 let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id);
592 let info = |addr: usize| MbInfo {
593 flags: pic.mb_flags[addr],
594 cbp: pic.mb_cbp[addr],
595 dc_cbf: pic.mb_dc_cbf[addr],
596 };
597 r.begin_mb(&MbCtx {
598 a: nbr.a.then(|| info(mb_addr - 1)),
599 b: nbr.b.then(|| info(mb_addr - pic.mb_w)),
600 qp_delta_inc: ctx.qp_delta_inc,
601 });
602 let w4 = pic.mb_w * 4;
603 let w2 = pic.mb_w * 2;
604 let (bx0, by0) = (mb_x * 4, mb_y * 4);
605 let (cx0, cy0) = (mb_x * 2, mb_y * 2);
606
607 let mb_type = r.mb_type_i()?;
608
609 if mb_type == 25 {
610 // I_PCM (7.3.5, 8.3.5): raw samples, byte aligned.
611 let pcm = r.pcm_block()?;
612 for y in 0..16 {
613 let dst = pic.y.at(mb_x * 16, mb_y * 16 + y);
614 pic.y.data[dst..dst + 16].copy_from_slice(&pcm[y * 16..y * 16 + 16]);
615 }
616 for (c, plane) in [&mut pic.cb, &mut pic.cr].into_iter().enumerate() {
617 let base = 256 + c * 64;
618 for y in 0..8 {
619 let dst = plane.at(mb_x * 8, mb_y * 8 + y);
620 plane.data[dst..dst + 8].copy_from_slice(&pcm[base + y * 8..base + y * 8 + 8]);
621 }
622 }
623 for dy in 0..4 {
624 let base = (by0 + dy) * w4 + bx0;
625 pic.nz_y[base..base + 4].fill(16);
626 pic.i4_modes[base..base + 4].fill(2);
627 }
628 for comp in 0..2 {
629 for dy in 0..2 {
630 let base = (cy0 + dy) * w2 + cx0;
631 pic.nz_c[comp][base..base + 2].fill(16);
632 }
633 }
634 // QPY prediction chain continues unchanged (mb_qp_delta inferred 0);
635 // the deblocker substitutes 0 via FLAG_PCM (spec 8.7.2).
636 pic.mb_qp[mb_addr] = ctx.qp as u8;
637 pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_PCM;
638 pic.mb_cbp[mb_addr] = 0x3F;
639 pic.mb_dc_cbf[mb_addr] = 0b111;
640 ctx.qp_delta_inc = 0;
641 pic.mb_slice[mb_addr] = ctx.slice_id;
642 pic.decoded_mbs += 1;
643 return Ok(());
644 }
645
646 let is_i16 = mb_type >= 1;
647 let (cbp_luma, cbp_chroma, i16_mode) = if is_i16 {
648 let m = mb_type - 1;
649 (
650 if m >= 12 { 15u8 } else { 0 },
651 ((m / 4) % 3) as u8,
652 (m % 4) as u8,
653 )
654 } else {
655 (0, 0, 0) // read below via me(v)
656 };
657
658 // I_NxN transform size flag (High profile only).
659 if !is_i16 && ctx.transform_8x8_mode && r.transform_size_8x8_flag()? {
660 return Err(Error::unsupported(
661 "8x8 transform",
662 "transform_size_8x8_flag 1 selects the 8x8 intra prediction of \
663 clause 8.3.2 and the 8x8 transform of 8.5.13; not implemented",
664 ));
665 }
666
667 // mb_pred (7.3.5.1): intra 4x4 modes, then chroma mode.
668 let mut modes = [2u8; 16];
669 if !is_i16 {
670 for blk in 0..16 {
671 let (dx, dy) = BLK4_POS[blk];
672 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
673 // Predicted mode = min of neighbours, DC when either unavailable
674 // (8.3.1.1; non-I4x4 neighbours were written as 2).
675 let left_avail = if bx % 4 == 0 { nbr.a } else { true };
676 let top_avail = if by % 4 == 0 { nbr.b } else { true };
677 let pred = if left_avail && top_avail {
678 let ma = pic.i4_modes[by * w4 + bx - 1];
679 let mb = pic.i4_modes[(by - 1) * w4 + bx];
680 ma.min(mb)
681 } else {
682 2
683 };
684 let mode = match r.intra4x4_pred_mode()? {
685 None => pred,
686 Some(rem) if rem < pred => rem,
687 Some(rem) => rem + 1,
688 };
689 pic.i4_modes[by * w4 + bx] = mode;
690 modes[blk] = mode;
691 }
692 } else {
693 for dy in 0..4 {
694 let base = (by0 + dy) * w4 + bx0;
695 pic.i4_modes[base..base + 4].fill(2);
696 }
697 }
698 let chroma_mode = r.intra_chroma_pred_mode()?;
699
700 // coded_block_pattern for I_NxN; Intra_16x16 derives it from mb_type.
701 let (cbp_luma, cbp_chroma) = if is_i16 {
702 (cbp_luma, cbp_chroma)
703 } else {
704 r.coded_block_pattern_intra()?
705 };
706
707 // mb_qp_delta (7.4.5).
708 let mut qp_delta = 0;
709 if cbp_luma != 0 || cbp_chroma != 0 || is_i16 {
710 qp_delta = r.mb_qp_delta()?;
711 ctx.qp = (ctx.qp + qp_delta + 52) % 52;
712 }
713 ctx.qp_delta_inc = u8::from(qp_delta != 0);
714 pic.mb_qp[mb_addr] = ctx.qp as u8;
715 pic.mb_flags[mb_addr] = FLAG_DECODED
716 | if is_i16 { FLAG_I16 } else { 0 }
717 | if chroma_mode != 0 {
718 FLAG_CHROMA_PRED
719 } else {
720 0
721 };
722 pic.mb_cbp[mb_addr] = cbp_luma | (cbp_chroma << 4);
723 pic.mb_slice[mb_addr] = ctx.slice_id;
724 pic.decoded_mbs += 1;
725 let qp_y = ctx.qp;
726 let qp_cb = i32::from(CHROMA_QP[(qp_y + ctx.cb_qp_offset).clamp(0, 51) as usize]);
727 let qp_cr = i32::from(CHROMA_QP[(qp_y + ctx.cr_qp_offset).clamp(0, 51) as usize]);
728
729 // ---- residual parse fused with reconstruction (7.3.5.3 + 8.5) ----
730 //
731 // Bitstream order (luma blocks in Z-order, then chroma DC, then chroma
732 // AC) equals reconstruction dependency order, so each block reconstructs
733 // the moment its levels are parsed: no per-MB coefficient arrays, and
734 // empty blocks cost one coeff_token read plus a prediction write.
735 let mut dc_cbf = 0u8;
736 let mut scan = [0i32; 16];
737 let mut raster = [0i32; 16];
738 let mut resid = [0i32; 16];
739 if is_i16 {
740 let mut w = PlaneWindow {
741 data: &mut pic.y.data,
742 stride: pic.y.stride,
743 origin: pic.y.origin + (mb_y * 16) * pic.y.stride + mb_x * 16,
744 };
745 pred_16x16(i16_mode, &mut w, nbr.b, nbr.a);
746 // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale.
747 let (na, nb) = luma_nz_pair(pic, &nbr, bx0, by0);
748 let dc_tc = r.residual_block(&mut scan, BlockCat::LumaDc, na, nb)?;
749 dc_cbf |= u8::from(dc_tc != 0);
750 unzigzag(&scan, &mut raster);
751 luma_dc_transform(&mut raster, &ls[0], qp_y);
752 let dc = raster;
753 for blk in 0..16 {
754 let (dx, dy) = BLK4_POS[blk];
755 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
756 let tc = if cbp_luma != 0 {
757 let (na, nb) = luma_nz_pair(pic, &nbr, bx, by);
758 r.residual_block(&mut scan, BlockCat::LumaAc, na, nb)?
759 } else {
760 0
761 };
762 pic.nz_y[by * w4 + bx] = tc;
763 let dc_blk = dc[dy as usize * 4 + dx as usize];
764 if tc == 0 && dc_blk == 0 {
765 continue; // prediction already in place
766 }
767 if tc > 0 {
768 unzigzag_ac15(&scan, &mut raster);
769 dequant_4x4(&mut raster, &ls[0], qp_y, true);
770 } else {
771 raster = [0; 16]; // DC-only block
772 }
773 raster[0] = dc_blk;
774 inverse_transform_4x4(&raster, &mut resid);
775 let origin = pic
776 .y
777 .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
778 add_residual_4x4(&mut pic.y.data, pic.y.stride, origin, &resid);
779 }
780 } else {
781 for blk in 0..16 {
782 let (dx, dy) = BLK4_POS[blk];
783 let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
784 let tc = if cbp_luma & (1 << (blk >> 2)) != 0 {
785 let (na, nb) = luma_nz_pair(pic, &nbr, bx, by);
786 r.residual_block(&mut scan, BlockCat::Luma4x4, na, nb)?
787 } else {
788 0
789 };
790 pic.nz_y[by * w4 + bx] = tc;
791 let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4);
792 let n = gather_nbr4(pic, &nbr, blk, x, y);
793 let mut p = [0u8; 16];
794 pred_4x4(modes[blk], &n, &mut p);
795 let origin = pic.y.at(x, y);
796 let stride = pic.y.stride;
797 if tc == 0 {
798 // Pure prediction: copy the 16 samples in.
799 for ry in 0..4 {
800 let row = origin + ry * stride;
801 pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]);
802 }
803 continue;
804 }
805 unzigzag(&scan, &mut raster);
806 dequant_4x4(&mut raster, &ls[0], qp_y, false);
807 inverse_transform_4x4(&raster, &mut resid);
808 for ry in 0..4 {
809 let row = origin + ry * stride;
810 for rx in 0..4 {
811 let v = i32::from(p[ry * 4 + rx]) + resid[ry * 4 + rx];
812 pic.y.data[row + rx] = v.clamp(0, 255) as u8;
813 }
814 }
815 }
816 }
817
818 // Chroma: predict both components, then DC (Cb, Cr), then AC in
819 // bitstream order (all Cb blocks, all Cr blocks), reconstructing as
820 // levels arrive.
821 for comp in 0..2 {
822 let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr };
823 let mut w = PlaneWindow {
824 data: &mut plane.data,
825 stride: plane.stride,
826 origin: plane.origin + (mb_y * 8) * plane.stride + mb_x * 8,
827 };
828 pred_chroma_8x8(chroma_mode, &mut w, nbr.b, nbr.a);
829 }
830 let mut chroma_dc = [[0i32; 4]; 2];
831 if cbp_chroma != 0 {
832 for (comp, c) in chroma_dc.iter_mut().enumerate() {
833 let tc = r.residual_block(&mut scan, BlockCat::ChromaDc(comp as u8), None, None)?;
834 dc_cbf |= u8::from(tc != 0) << (1 + comp);
835 c.copy_from_slice(&scan[..4]);
836 let (ls_c, qp_c) = if comp == 0 {
837 (&ls[1], qp_cb)
838 } else {
839 (&ls[2], qp_cr)
840 };
841 chroma_dc_transform_420(c, ls_c, qp_c);
842 }
843 }
844 for comp in 0..2 {
845 for blk in 0..4 {
846 let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
847 let tc = if cbp_chroma == 2 {
848 let (na, nb) = chroma_nz_pair(pic, &nbr, comp, cx, cy);
849 r.residual_block(&mut scan, BlockCat::ChromaAc, na, nb)?
850 } else {
851 0
852 };
853 pic.nz_c[comp][cy * w2 + cx] = tc;
854 if cbp_chroma == 0 {
855 continue;
856 }
857 let dc_blk = chroma_dc[comp][blk];
858 if tc == 0 && dc_blk == 0 {
859 continue;
860 }
861 let (plane, ls_c, qp_c) = if comp == 0 {
862 (&mut pic.cb, &ls[1], qp_cb)
863 } else {
864 (&mut pic.cr, &ls[2], qp_cr)
865 };
866 if tc > 0 {
867 unzigzag_ac15(&scan, &mut raster);
868 dequant_4x4(&mut raster, ls_c, qp_c, true);
869 } else {
870 raster = [0; 16]; // DC-only block
871 }
872 raster[0] = dc_blk;
873 inverse_transform_4x4(&raster, &mut resid);
874 let origin = plane.at(mb_x * 8 + (blk & 1) * 4, mb_y * 8 + (blk >> 1) * 4);
875 add_residual_4x4(&mut plane.data, plane.stride, origin, &resid);
876 }
877 }
878 pic.mb_dc_cbf[mb_addr] = dc_cbf;
879 Ok(())
880}
881
882/// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2),
883/// including the top-right substitution rule.
884fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) -> Nbr4 {
885 let (dx, dy) = BLK4_POS[blk];
886 let stride = pic.y.stride;
887 let o = pic.y.at(x, y);
888 let have_left = if dx == 0 { nbr.a } else { true };
889 let have_top = if dy == 0 { nbr.b } else { true };
890 let have_tr = match TR_KIND[blk] {
891 TrKind::InMb => true,
892 TrKind::B => nbr.b,
893 TrKind::C => nbr.c,
894 TrKind::None => false,
895 };
896 let mut top = [0u8; 8];
897 let data = &pic.y.data;
898 top[..4].copy_from_slice(&data[o - stride..o - stride + 4]);
899 if have_tr {
900 top[4..].copy_from_slice(&data[o - stride + 4..o - stride + 8]);
901 } else if have_top {
902 let t3 = top[3];
903 top[4..].fill(t3);
904 }
905 let mut left = [0u8; 4];
906 for (i, l) in left.iter_mut().enumerate() {
907 *l = data[o + i * stride - 1];
908 }
909 Nbr4 {
910 top,
911 left,
912 top_left: data[o - stride - 1],
913 have_top,
914 have_left,
915 }
916}
917
918/// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all
919/// vertical edges then all horizontal edges per macroblock, then chroma.
920fn deblock_picture(pic: &mut Picture) {
921 let mb_w = pic.mb_w;
922 for mb_y in 0..pic.mb_h {
923 for mb_x in 0..mb_w {
924 let addr = mb_y * mb_w + mb_x;
925 if pic.mb_flags[addr] & FLAG_DECODED == 0 {
926 continue;
927 }
928 let sid = pic.mb_slice[addr];
929 let sp = pic.slices[sid as usize];
930 if sp.disable_deblock_idc == 1 {
931 continue;
932 }
933 let decoded = |a: usize| pic.mb_flags[a] & FLAG_DECODED != 0;
934 let cross_ok = |a: usize| sp.disable_deblock_idc != 2 || pic.mb_slice[a] == sid;
935 let filter_left = mb_x > 0 && decoded(addr - 1) && cross_ok(addr - 1);
936 let filter_top = mb_y > 0 && decoded(addr - mb_w) && cross_ok(addr - mb_w);
937 // Deblocking QP: 0 for I_PCM macroblocks (8.7.2).
938 let qp_of = |a: usize| -> i32 {
939 if pic.mb_flags[a] & FLAG_PCM != 0 {
940 0
941 } else {
942 i32::from(pic.mb_qp[a])
943 }
944 };
945 let qp_q = qp_of(addr);
946
947 // ---- luma ----
948 {
949 let stride = pic.y.stride;
950 let base = pic.y.at(mb_x * 16, mb_y * 16);
951 // Vertical edges (filter across columns), left to right.
952 for e in 0..4 {
953 if e == 0 && !filter_left {
954 continue;
955 }
956 let (bs, qp_p) = if e == 0 {
957 (4, qp_of(addr - 1))
958 } else {
959 (3, qp_q)
960 };
961 let params =
962 edge_params((qp_p + qp_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs);
963 if params.alpha == 0 || params.beta == 0 {
964 continue;
965 }
966 // Vertical edges stay scalar: a gather/scatter SIMD
967 // variant measured slower than this loop (strided
968 // per-lane loads dominate).
969 for k in 0..16 {
970 filter_luma_line(&mut pic.y.data, base + k * stride + e * 4, 1, &params);
971 }
972 }
973 // Horizontal edges, top to bottom.
974 for e in 0..4 {
975 if e == 0 && !filter_top {
976 continue;
977 }
978 let (bs, qp_p) = if e == 0 {
979 (4, qp_of(addr - mb_w))
980 } else {
981 (3, qp_q)
982 };
983 let params =
984 edge_params((qp_p + qp_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs);
985 if params.alpha == 0 || params.beta == 0 {
986 continue;
987 }
988 filter_luma_h_edge16(&mut pic.y.data, base + e * 4 * stride, stride, &params);
989 }
990 }
991
992 // ---- chroma (Cb, Cr) ----
993 for comp in 0..2 {
994 let (plane, off_sel): (&mut Plane8, fn(&SliceParams) -> i32) = if comp == 0 {
995 (&mut pic.cb, |s| s.cb_qp_offset)
996 } else {
997 (&mut pic.cr, |s| s.cr_qp_offset)
998 };
999 let stride = plane.stride;
1000 let base = plane.origin + (mb_y * 8) * stride + mb_x * 8;
1001 // Chroma QP per side: each macroblock's luma QP mapped with
1002 // the offset of ITS OWN slice's PPS (8.7.2).
1003 let cqp = |a: usize| -> i32 {
1004 let s = pic.slices[pic.mb_slice[a] as usize];
1005 if pic.mb_flags[a] & FLAG_PCM != 0 {
1006 chroma_qp(0, off_sel(&s))
1007 } else {
1008 chroma_qp(i32::from(pic.mb_qp[a]), off_sel(&s))
1009 }
1010 };
1011 let cq_q = cqp(addr);
1012 for e in 0..2 {
1013 if e == 0 && !filter_left {
1014 continue;
1015 }
1016 let (bs, cq_p) = if e == 0 {
1017 (4, cqp(addr - 1))
1018 } else {
1019 (3, cq_q)
1020 };
1021 let params =
1022 edge_params((cq_p + cq_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs);
1023 if params.alpha == 0 || params.beta == 0 {
1024 continue;
1025 }
1026 for k in 0..8 {
1027 filter_chroma_line(&mut plane.data, base + k * stride + e * 4, 1, &params);
1028 }
1029 }
1030 for e in 0..2 {
1031 if e == 0 && !filter_top {
1032 continue;
1033 }
1034 let (bs, cq_p) = if e == 0 {
1035 (4, cqp(addr - mb_w))
1036 } else {
1037 (3, cq_q)
1038 };
1039 let params =
1040 edge_params((cq_p + cq_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs);
1041 if params.alpha == 0 || params.beta == 0 {
1042 continue;
1043 }
1044 for k in 0..8 {
1045 filter_chroma_line(
1046 &mut plane.data,
1047 base + e * 4 * stride + k,
1048 stride,
1049 &params,
1050 );
1051 }
1052 }
1053 }
1054 }
1055 }
1056}