forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB58b009bTahinli2 months ago2045 commits

decode.rs748 lines, 28.0 KiBHistoryRawDownload
1//! Intra-only HEVC decode: the mirror of [`crate::ctu`], minus the
2//! rate-distortion search.
3//!
4//! # Module map
5//!
6//! - [`cabac::CabacDecoder`](crate::cabac::CabacDecoder) mirrors
7//! [`CabacEncoder`](crate::cabac::CabacEncoder) bin for bin, sharing its
8//! context tables (`RANGE_TAB_LPS`, `TRANS_IDX_LPS`/`MPS`, [`Contexts`]).
9//! - [`residual::decode_residual`](crate::residual::decode_residual) mirrors
10//! `encode_residual` bin for bin.
11//! - [`crate::intra`] and [`crate::transform`] are reused as-is: prediction,
12//! the inverse transform and dequantisation do not care which direction the
13//! bits came from.
14//! - This module supplies what the encoder's [`crate::ctu::CtuEncoder`] does
15//! *not* have a decode-shaped twin for: the coding-tree and transform-tree
16//! walk, which the encoder interleaves with a mode search but a decoder
17//! just reads.
18//!
19//! # What is genuinely a search heuristic vs. genuine syntax
20//!
21//! `code_quadtree`'s special-cased branches for `min_cu_size` and `cu64`, and
22//! `code_cu`'s `intra_nxn` gate, all still write a real `split_cu_flag` /
23//! `part_mode` bit — they only fix *which* value the search settles for
24//! without trying the alternative. A decoder does not need to know any of
25//! those encoder config knobs: it reads the bit that is there. Only
26//! `EncoderConfig::rqt`, `sign_hiding` and `transform_skip` change whether a
27//! bit is *present* at all (mirroring `max_transform_hierarchy_depth_intra`,
28//! `sign_data_hiding_enabled_flag`, `transform_skip_enabled_flag`), so those
29//! three travel from the parsed SPS/PPS into [`CtuDecoder`].
30
31use crate::cabac::{CabacDecoder, Contexts, ctx};
32use crate::ctu::MIN_CB_LOG2;
33use crate::deblock::{TuMap, deblock};
34use crate::intra::{self, Availability, Refs};
35use crate::residual::decode_residual;
36use crate::transform::{
37 chroma_qp, dequantize, inverse_transform, inverse_transform_skip, uses_dst,
38};
39use ec_core::error::{Error, Result};
40use ec_h265_syntax::nal::split_annex_b;
41use ec_h265_syntax::slice::{SliceHeader, SliceType};
42use ec_h265_syntax::{Pps, Sps};
43
44/// A decoded picture: three planes at the SPS's *coded* size (before the
45/// conformance window crops it), 8-bit, one byte per sample.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct DecodedPicture {
48 /// Coded width.
49 pub width: usize,
50 /// Coded height.
51 pub height: usize,
52 /// Luma, `width * height`.
53 pub y: Vec<u8>,
54 /// Cb, `width/2 * height/2`.
55 pub cb: Vec<u8>,
56 /// Cr, `width/2 * height/2`.
57 pub cr: Vec<u8>,
58}
59
60/// Decode one IDR access unit: VPS/SPS/PPS/slice NALs in Annex-B framing, one
61/// I slice covering the whole picture. Anything but an intra slice is refused
62/// with a named reason rather than silently mis-decoded — inter prediction is
63/// not implemented yet (see the module doc for what is).
64pub fn decode_idr_au(data: &[u8]) -> Result<DecodedPicture> {
65 let mut sps: Option<Sps> = None;
66 let mut pps: Option<Pps> = None;
67 for nal in split_annex_b(data) {
68 match nal.header.nal_type {
69 ec_h265_syntax::nal::NalUnitType::Sps => sps = Some(Sps::parse(&nal.rbsp())?),
70 ec_h265_syntax::nal::NalUnitType::Pps => pps = Some(Pps::parse(&nal.rbsp())?),
71 ec_h265_syntax::nal::NalUnitType::IdrWRadl
72 | ec_h265_syntax::nal::NalUnitType::IdrNLp => {
73 let sps = sps.as_ref().ok_or_else(|| {
74 Error::corrupt("HEVC decode: slice before an SPS".to_string())
75 })?;
76 let pps = pps
77 .as_ref()
78 .ok_or_else(|| Error::corrupt("HEVC decode: slice before a PPS".to_string()))?;
79 let rbsp = nal.rbsp();
80 let (header, pos) = SliceHeader::parse(&rbsp, sps, pps, nal.header.nal_type)?;
81 if header.slice_type != SliceType::I {
82 return Err(Error::unsupported(
83 "HEVC decode: inter slice",
84 "no inter prediction implemented yet; only IDR I-slice streams decode",
85 ));
86 }
87 let byte_off = (pos.header_bits / 8) as usize;
88 return decode_i_slice(sps, pps, &header, &rbsp[byte_off..]);
89 }
90 _ => {}
91 }
92 }
93 Err(Error::corrupt(
94 "HEVC decode: no IDR slice found in the access unit".to_string(),
95 ))
96}
97
98fn decode_i_slice(
99 sps: &Sps,
100 pps: &Pps,
101 header: &SliceHeader,
102 slice_data: &[u8],
103) -> Result<DecodedPicture> {
104 // The coded picture, not the CTB-grid-rounded size: HEVC's last CTU in a
105 // row/column is legally partial (7.3.8.4's boundary-forced split exists
106 // precisely for this), and the encoder's own boundary checks are against
107 // `pic_width_in_luma_samples`/`pic_height_in_luma_samples`, not the next
108 // multiple of the CTB size. Rounding up here desynchronised the decoder's
109 // split_cu_flag inference from the encoder's whenever the two bases
110 // differed — every size that is not itself an exact CTB-size multiple.
111 let width = sps.pic_width_in_luma_samples as usize;
112 let height = sps.pic_height_in_luma_samples as usize;
113 let ctb = sps.ctb_size() as usize;
114 let cols = width.div_ceil(ctb);
115 let rows = height.div_ceil(ctb);
116 let qp = 26 + pps.init_qp_minus26 + header.qp_delta;
117 let rqt = sps.max_transform_hierarchy_depth_intra > 0;
118
119 let mut decoder = CtuDecoder::new(
120 width,
121 height,
122 ctb,
123 qp,
124 rqt,
125 pps.sign_data_hiding_enabled,
126 pps.transform_skip_enabled,
127 sps.strong_intra_smoothing,
128 );
129
130 let mut wpp_contexts: Vec<Option<Contexts>> = vec![None; rows];
131 let mut byte_pos = 0usize;
132 'rows: for row in 0..rows {
133 let contexts = if row == 0 || cols < 2 {
134 Contexts::new(qp)
135 } else {
136 wpp_contexts[row - 1]
137 .clone()
138 .unwrap_or_else(|| Contexts::new(qp))
139 };
140 if byte_pos > slice_data.len() {
141 return Err(Error::corrupt(
142 "HEVC decode: slice data ran out before the last CTB row".to_string(),
143 ));
144 }
145 let mut dec = CabacDecoder::new(&slice_data[byte_pos..], contexts);
146 for col in 0..cols {
147 decoder.decode_ctu(col * ctb, row * ctb, &mut dec);
148 if col == 1 {
149 wpp_contexts[row] = Some(Contexts::clone(&dec.contexts));
150 }
151 let last_in_picture = row + 1 == rows && col + 1 == cols;
152 let term = dec.decode_terminate();
153 if term != u32::from(last_in_picture) {
154 return Err(Error::corrupt(format!(
155 "HEVC decode: end_of_slice_segment_flag {term} at CTB ({col},{row}), expected {}",
156 u32::from(last_in_picture)
157 )));
158 }
159 if last_in_picture {
160 break 'rows;
161 }
162 if col + 1 == cols {
163 let subset_end = dec.decode_terminate();
164 if subset_end != 1 {
165 return Err(Error::corrupt(
166 "HEVC decode: end_of_subset_one_bit was not set at a WPP row boundary"
167 .to_string(),
168 ));
169 }
170 }
171 }
172 byte_pos += dec.byte_position_aligned();
173 }
174
175 if !header.deblocking_filter_disabled {
176 let mut tus = TuMap::new(width, height);
177 tus.absorb_band(0, height / 4, &decoder.tu_log2);
178 deblock(
179 &mut decoder.y_buf,
180 &mut decoder.cb_buf,
181 &mut decoder.cr_buf,
182 width,
183 height,
184 qp,
185 &tus,
186 );
187 }
188
189 Ok(DecodedPicture {
190 width,
191 height,
192 y: decoder.y_buf,
193 cb: decoder.cb_buf,
194 cr: decoder.cr_buf,
195 })
196}
197
198/// Decoder state for one picture: the reconstruction, and the per-4x4-unit
199/// bookkeeping [`crate::ctu::CtuEncoder`] keeps per row-band, kept here for
200/// the whole picture instead since a decoder has no wavefront to shard by.
201struct CtuDecoder {
202 width: usize,
203 height: usize,
204 ctb_size: usize,
205 qp: i32,
206 qp_c: i32,
207 rqt: bool,
208 sign_hiding: bool,
209 transform_skip_enabled: bool,
210 strong_smoothing: bool,
211 y_buf: Vec<u8>,
212 cb_buf: Vec<u8>,
213 cr_buf: Vec<u8>,
214 /// Whether each 4x4 luma unit has been reconstructed yet, in the same
215 /// raster-CTB-then-z-scan order the encoder's `available()` assumes. One
216 /// picture-wide flag serves every purpose the encoder split across a
217 /// row-boundary struct and a per-CTB reset: a single-threaded decoder
218 /// visits positions in exactly the order that made those two exist.
219 decoded: Vec<bool>,
220 modes: Vec<u8>,
221 depths: Vec<u8>,
222 tu_log2: Vec<u8>,
223}
224
225impl CtuDecoder {
226 #[allow(clippy::too_many_arguments)]
227 fn new(
228 width: usize,
229 height: usize,
230 ctb_size: usize,
231 qp: i32,
232 rqt: bool,
233 sign_hiding: bool,
234 transform_skip_enabled: bool,
235 strong_smoothing: bool,
236 ) -> CtuDecoder {
237 let units = (width / 4) * (height / 4);
238 CtuDecoder {
239 width,
240 height,
241 ctb_size,
242 qp,
243 qp_c: chroma_qp(qp, 0),
244 rqt,
245 sign_hiding,
246 transform_skip_enabled,
247 strong_smoothing,
248 y_buf: vec![0; width * height],
249 cb_buf: vec![0; width / 2 * height / 2],
250 cr_buf: vec![0; width / 2 * height / 2],
251 decoded: vec![false; units],
252 modes: vec![255; units],
253 depths: vec![0; units],
254 tu_log2: vec![2; units],
255 }
256 }
257
258 fn available(&self, x: isize, y: isize) -> bool {
259 if x < 0 || y < 0 || x >= self.width as isize || y >= self.height as isize {
260 return false;
261 }
262 self.decoded[(y as usize / 4) * (self.width / 4) + x as usize / 4]
263 }
264
265 fn depth_at(&self, x: usize, y: usize) -> u8 {
266 self.depths[(y / 4) * (self.width / 4) + x / 4]
267 }
268
269 /// Record a reconstructed region: mode, coding depth and availability for
270 /// every 4x4 unit it covers.
271 fn mark_coded(&mut self, x: usize, y: usize, n: usize, mode: u8, depth: u8) {
272 let stride = self.width / 4;
273 for by in (y..y + n).step_by(4) {
274 for bx in (x..x + n).step_by(4) {
275 let idx = (by / 4) * stride + bx / 4;
276 self.modes[idx] = mode;
277 self.depths[idx] = depth;
278 self.decoded[idx] = true;
279 }
280 }
281 }
282
283 fn mark_tu(&mut self, x: usize, y: usize, n: usize) {
284 let stride = self.width / 4;
285 let log2 = n.trailing_zeros() as u8;
286 for by in (y..y + n).step_by(4) {
287 for bx in (x..x + n).step_by(4) {
288 self.tu_log2[(by / 4) * stride + bx / 4] = log2;
289 }
290 }
291 }
292
293 /// The mode at a position if one has been assigned, independent of
294 /// whether its *pixels* have been reconstructed yet: an NxN coding unit's
295 /// `prev_intra_luma_pred_flag`s (and then every remainder) are all
296 /// signalled before any of its four partitions is reconstructed
297 /// (7.3.8.5), so by the time partition 2's mode is decoded, partition 1's
298 /// mode is already known even though its transform tree has not run —
299 /// MPM only needs the syntax-level mode (8.4.2), not the reconstructed
300 /// sample `available()` gates for prediction reference construction
301 /// (8.4.4.2.1). Using the `modes` sentinel directly (unset stays 255)
302 /// keeps those two notions of "available" from being conflated: pixel
303 /// availability still comes from `decoded`, set only once a position is
304 /// actually reconstructed.
305 fn mode_if_known(&self, x: isize, y: isize) -> Option<u8> {
306 if x < 0 || y < 0 || x >= self.width as isize || y >= self.height as isize {
307 return None;
308 }
309 let m = self.modes[(y as usize / 4) * (self.width / 4) + x as usize / 4];
310 if m == 255 { None } else { Some(m) }
311 }
312
313 fn mpm_at(&self, x: usize, y: usize) -> [u8; 3] {
314 let left = self.mode_if_known(x as isize - 1, y as isize);
315 let band_y0 = (y / self.ctb_size) * self.ctb_size;
316 let above = if y > band_y0 {
317 self.mode_if_known(x as isize, y as isize - 1)
318 } else {
319 None
320 };
321 intra::mpm_list(left, above)
322 }
323
324 fn luma_refs(&self, x: usize, y: usize, n: usize) -> Refs {
325 let mut refs = Refs::default();
326 let mut avail = Availability::default();
327 let span = 2 * n;
328 avail.corner = self.available(x as isize - 1, y as isize - 1);
329 if avail.corner {
330 refs.corner = self.y_buf[(y - 1) * self.width + x - 1];
331 }
332 for i in 0..span {
333 if self.available((x + i) as isize, y as isize - 1) {
334 avail.top |= 1 << i;
335 refs.top[i] = self.y_buf[(y - 1) * self.width + x + i];
336 }
337 if self.available(x as isize - 1, (y + i) as isize) {
338 avail.left |= 1 << i;
339 refs.left[i] = self.y_buf[(y + i) * self.width + x - 1];
340 }
341 }
342 intra::substitute(&mut refs, &avail, n, 8);
343 refs
344 }
345
346 fn chroma_refs(&self, cx: usize, cy: usize, cn: usize, plane: &[u8]) -> Refs {
347 let mut refs = Refs::default();
348 let mut avail = Availability::default();
349 let cw = self.width / 2;
350 let span = 2 * cn;
351 avail.corner = self.available(cx as isize * 2 - 1, cy as isize * 2 - 1);
352 if avail.corner {
353 refs.corner = plane[(cy - 1) * cw + cx - 1];
354 }
355 for i in 0..span {
356 if self.available(((cx + i) * 2) as isize, cy as isize * 2 - 1) {
357 avail.top |= 1 << i;
358 refs.top[i] = plane[(cy - 1) * cw + cx + i];
359 }
360 if self.available(cx as isize * 2 - 1, ((cy + i) * 2) as isize) {
361 avail.left |= 1 << i;
362 refs.left[i] = plane[(cy + i) * cw + cx - 1];
363 }
364 }
365 intra::substitute(&mut refs, &avail, cn, 8);
366 refs
367 }
368
369 // ---- one coding tree unit ---------------------------------------------
370
371 fn decode_ctu(&mut self, x0: usize, y0: usize, dec: &mut CabacDecoder) {
372 let log2_ctb = self.ctb_size.trailing_zeros();
373 self.decode_quadtree(x0, y0, log2_ctb, 0, dec);
374 }
375
376 fn decode_quadtree(
377 &mut self,
378 x: usize,
379 y: usize,
380 log2: u32,
381 depth: u8,
382 dec: &mut CabacDecoder,
383 ) {
384 let size = 1usize << log2;
385 let half = size / 2;
386 if x + size > self.width || y + size > self.height {
387 for (dx, dy) in [(0, 0), (half, 0), (0, half), (half, half)] {
388 if x + dx < self.width && y + dy < self.height {
389 self.decode_quadtree(x + dx, y + dy, log2 - 1, depth + 1, dec);
390 }
391 }
392 return;
393 }
394 if log2 == MIN_CB_LOG2 {
395 self.decode_cu(x, y, log2, depth, dec);
396 return;
397 }
398 let split_ctx = ctx::SPLIT_CU
399 + usize::from(
400 self.available(x as isize - 1, y as isize) && self.depth_at(x - 1, y) > depth,
401 )
402 + usize::from(
403 self.available(x as isize, y as isize - 1) && self.depth_at(x, y - 1) > depth,
404 );
405 if dec.decode_bin(split_ctx) != 0 {
406 for (dx, dy) in [(0, 0), (half, 0), (0, half), (half, half)] {
407 self.decode_quadtree(x + dx, y + dy, log2 - 1, depth + 1, dec);
408 }
409 } else {
410 self.decode_cu(x, y, log2, depth, dec);
411 }
412 }
413
414 fn decode_cu(&mut self, x: usize, y: usize, log2: u32, depth: u8, dec: &mut CabacDecoder) {
415 if log2 == MIN_CB_LOG2 {
416 if dec.decode_bin(ctx::PART_MODE) != 0 {
417 self.decode_cu_2nx2n(x, y, log2, depth, dec);
418 } else {
419 self.decode_cu_nxn(x, y, depth, dec);
420 }
421 } else {
422 self.decode_cu_2nx2n(x, y, log2, depth, dec);
423 }
424 }
425
426 fn decode_intra_mode(&self, dec: &mut CabacDecoder, mpm: &[u8; 3]) -> u8 {
427 let is_mpm = dec.decode_bin(ctx::PREV_INTRA_LUMA_PRED) != 0;
428 if is_mpm {
429 let idx = if dec.decode_bypass() == 0 {
430 0
431 } else {
432 1 + dec.decode_bypass()
433 };
434 mpm[idx as usize]
435 } else {
436 let rem = dec.decode_bypass_bits(5) as u8;
437 let mut sorted = *mpm;
438 sorted.sort_unstable();
439 let mut mode = rem;
440 for m in sorted {
441 if mode >= m {
442 mode += 1;
443 }
444 }
445 mode
446 }
447 }
448
449 fn decode_chroma_mode(&self, dec: &mut CabacDecoder, luma_mode: u8) -> u8 {
450 if dec.decode_bin(ctx::INTRA_CHROMA_PRED_MODE) == 0 {
451 return luma_mode;
452 }
453 let idx = dec.decode_bypass_bits(2) as usize;
454 let mut explicit = [0u8, 26, 10, 1];
455 for m in explicit.iter_mut() {
456 if *m == luma_mode {
457 *m = 34;
458 }
459 }
460 explicit[idx]
461 }
462
463 fn decode_cu_2nx2n(
464 &mut self,
465 x: usize,
466 y: usize,
467 log2: u32,
468 depth: u8,
469 dec: &mut CabacDecoder,
470 ) {
471 let n = 1usize << log2;
472 let mpm = self.mpm_at(x, y);
473 let mode = self.decode_intra_mode(dec, &mpm);
474 let chroma_mode = self.decode_chroma_mode(dec, mode);
475 if log2 > 5 {
476 self.decode_split_tu(x, y, n, log2, mode, chroma_mode, depth, dec);
477 } else if self.rqt && log2 > 2 {
478 let split_ctx = ctx::SPLIT_TRANSFORM + (5 - log2) as usize;
479 if dec.decode_bin(split_ctx) != 0 {
480 self.decode_split_tu(x, y, n, log2, mode, chroma_mode, depth, dec);
481 } else {
482 self.decode_single_tu(x, y, n, log2, mode, chroma_mode, dec);
483 }
484 } else {
485 self.decode_single_tu(x, y, n, log2, mode, chroma_mode, dec);
486 }
487 self.mark_coded(x, y, n, mode, depth);
488 }
489
490 /// The four-4x4-partition form of the smallest coding unit.
491 fn decode_cu_nxn(&mut self, x: usize, y: usize, depth: u8, dec: &mut CabacDecoder) {
492 let offsets = [(0usize, 0usize), (4, 0), (0, 4), (4, 4)];
493 // prev_intra_luma_pred_flag for all four, then every remainder — the
494 // batching the encoder's two separate loops produce; only the second
495 // loop's decode needs `mpm`, and by the time it reaches partition i
496 // partitions 0..i already have a resolved mode in `self.modes` (this
497 // loop resolves both flag and remainder together per partition, so
498 // that still holds).
499 let is_mpm: [bool; 4] =
500 std::array::from_fn(|_| dec.decode_bin(ctx::PREV_INTRA_LUMA_PRED) != 0);
501 let mut modes = [0u8; 4];
502 for (part, &(dx, dy)) in offsets.iter().enumerate() {
503 let (px, py) = (x + dx, y + dy);
504 let mpm = self.mpm_at(px, py);
505 let mode = if is_mpm[part] {
506 let idx = if dec.decode_bypass() == 0 {
507 0
508 } else {
509 1 + dec.decode_bypass()
510 };
511 mpm[idx as usize]
512 } else {
513 let rem = dec.decode_bypass_bits(5) as u8;
514 let mut sorted = mpm;
515 sorted.sort_unstable();
516 let mut mode = rem;
517 for m in sorted {
518 if mode >= m {
519 mode += 1;
520 }
521 }
522 mode
523 };
524 modes[part] = mode;
525 // Mode only, so the next partition's `mpm_at` (via
526 // `mode_if_known`) sees this one's mode without its pixels being
527 // reconstructed yet — 8.4.2's candIntraPredMode only needs the
528 // neighbour's syntax-level mode, which an NxN CU's own earlier
529 // partition already has despite its transform tree not having
530 // run (7.3.8.5 signals all four modes before any residual).
531 // Marking `self.decoded` here too (as an earlier version of this
532 // loop did) went further than that: it made partition 2 and 3's
533 // *pixels* look available to partition 1's own reference-sample
534 // construction (8.4.4.2.1) before the second loop below had
535 // reconstructed them, reading zero-initialised `y_buf` instead of
536 // the correctly-substituted "not yet available" edge case — a
537 // one-CU-late reconstruction that stayed invisible until a
538 // picture edge forced this exact NxN+RQT combination.
539 let stride = self.width / 4;
540 let idx = (py / 4) * stride + px / 4;
541 self.modes[idx] = mode;
542 }
543
544 let chroma_mode = self.decode_chroma_mode(dec, modes[0]);
545 let cb_cbf = dec.decode_bin(ctx::CBF_CHROMA) != 0;
546 let cr_cbf = dec.decode_bin(ctx::CBF_CHROMA) != 0;
547
548 for (part, &(dx, dy)) in offsets.iter().enumerate() {
549 let (px, py) = (x + dx, y + dy);
550 let luma_cbf = dec.decode_bin(ctx::CBF_LUMA) != 0;
551 self.reconstruct_luma(px, py, 4, modes[part], 2, luma_cbf, dec);
552 self.mark_coded(px, py, 4, modes[part], depth);
553 self.mark_tu(px, py, 4);
554 if part == 3 {
555 // `reconstruct_chroma`'s `log2_luma` is the covering luma
556 // block's log2 (it derives `clog2 = log2_luma - 1` for the
557 // transform-split convention); an NxN CU's covering block is
558 // the whole 8x8 CU (`MIN_CB_LOG2`), not a 4x4 partition —
559 // passing `2` here derived `clog2 = 1` and underflowed
560 // `decode_residual`'s `log2_size - 2`.
561 self.reconstruct_chroma(x, y, 8, chroma_mode, MIN_CB_LOG2, cb_cbf, cr_cbf, dec);
562 }
563 }
564 }
565
566 /// Predict, decode residual if `cbf`, reconstruct one luma transform
567 /// block of side `n` at `(x, y)` and write it into `y_buf`.
568 fn reconstruct_luma(
569 &mut self,
570 x: usize,
571 y: usize,
572 n: usize,
573 mode: u8,
574 log2: u32,
575 cbf: bool,
576 dec: &mut CabacDecoder,
577 ) {
578 let refs = self.luma_refs(x, y, n);
579 let mut pred = vec![0u8; n * n];
580 intra::predict(&refs, mode, n, true, self.strong_smoothing, &mut pred);
581 let mut residual = vec![0i32; n * n];
582 if cbf {
583 let scan = intra::scan_index(mode, log2, true);
584 let mut levels = vec![0i32; n * n];
585 let skip = decode_residual(
586 dec,
587 &mut levels,
588 log2,
589 0,
590 scan,
591 self.sign_hiding,
592 self.transform_skip_enabled,
593 );
594 let mut scaled = vec![0i32; n * n];
595 dequantize(&levels, &mut scaled, n, self.qp);
596 if skip {
597 inverse_transform_skip(&scaled, &mut residual, n);
598 } else {
599 inverse_transform(&scaled, &mut residual, n, uses_dst(n, true));
600 }
601 }
602 for row in 0..n {
603 for col in 0..n {
604 let i = row * n + col;
605 let v = (i32::from(pred[i]) + residual[i]).clamp(0, 255) as u8;
606 self.y_buf[(y + row) * self.width + x + col] = v;
607 }
608 }
609 }
610
611 /// The chroma pair (Cb then Cr) of one transform block of side `n`
612 /// (luma-equivalent side; the chroma block is `n/2`).
613 fn reconstruct_chroma(
614 &mut self,
615 x: usize,
616 y: usize,
617 n: usize,
618 mode: u8,
619 log2_luma: u32,
620 cb_cbf: bool,
621 cr_cbf: bool,
622 dec: &mut CabacDecoder,
623 ) {
624 let cn = n / 2;
625 let (cx, cy) = (x / 2, y / 2);
626 let clog2 = log2_luma - 1;
627 let scan = intra::scan_index(mode, clog2, false);
628 for (plane_idx, cbf) in [(1usize, cb_cbf), (2usize, cr_cbf)] {
629 let cw = self.width / 2;
630 let refs = {
631 let plane = if plane_idx == 1 {
632 &self.cb_buf
633 } else {
634 &self.cr_buf
635 };
636 self.chroma_refs(cx, cy, cn, plane)
637 };
638 let mut pred = vec![0u8; cn * cn];
639 intra::predict(&refs, mode, cn, false, self.strong_smoothing, &mut pred);
640 let mut residual = vec![0i32; cn * cn];
641 if cbf {
642 let mut levels = vec![0i32; cn * cn];
643 let skip = decode_residual(
644 dec,
645 &mut levels,
646 clog2,
647 plane_idx,
648 scan,
649 self.sign_hiding,
650 self.transform_skip_enabled,
651 );
652 let mut scaled = vec![0i32; cn * cn];
653 dequantize(&levels, &mut scaled, cn, self.qp_c);
654 if skip {
655 inverse_transform_skip(&scaled, &mut residual, cn);
656 } else {
657 inverse_transform(&scaled, &mut residual, cn, false);
658 }
659 }
660 let plane = if plane_idx == 1 {
661 &mut self.cb_buf
662 } else {
663 &mut self.cr_buf
664 };
665 for row in 0..cn {
666 for col in 0..cn {
667 let i = row * cn + col;
668 let v = (i32::from(pred[i]) + residual[i]).clamp(0, 255) as u8;
669 plane[(cy + row) * cw + cx + col] = v;
670 }
671 }
672 }
673 }
674
675 /// One unsplit transform tree: `cbf_cb`, `cbf_cr`, `cbf_luma` (context 1,
676 /// `trafoDepth == 0`), then the residuals.
677 fn decode_single_tu(
678 &mut self,
679 x: usize,
680 y: usize,
681 n: usize,
682 log2: u32,
683 mode: u8,
684 chroma_mode: u8,
685 dec: &mut CabacDecoder,
686 ) {
687 let cb_cbf = dec.decode_bin(ctx::CBF_CHROMA) != 0;
688 let cr_cbf = dec.decode_bin(ctx::CBF_CHROMA) != 0;
689 let luma_cbf = dec.decode_bin(ctx::CBF_LUMA + 1) != 0;
690 self.reconstruct_luma(x, y, n, mode, log2, luma_cbf, dec);
691 self.reconstruct_chroma(x, y, n, chroma_mode, log2, cb_cbf, cr_cbf, dec);
692 self.mark_tu(x, y, n);
693 }
694
695 /// A split transform tree: the parent's chroma flags, then four
696 /// half-size children (`cbf_luma` context 0, `trafoDepth >= 1`). A child
697 /// carries its own chroma when the chroma blocks stay 4x4 or larger;
698 /// below that the parent's chroma rides on the last child.
699 #[allow(clippy::too_many_arguments)]
700 fn decode_split_tu(
701 &mut self,
702 x: usize,
703 y: usize,
704 n: usize,
705 log2: u32,
706 mode: u8,
707 chroma_mode: u8,
708 depth: u8,
709 dec: &mut CabacDecoder,
710 ) {
711 let half = n / 2;
712 let cb_cbf = dec.decode_bin(ctx::CBF_CHROMA) != 0;
713 let cr_cbf = dec.decode_bin(ctx::CBF_CHROMA) != 0;
714 let chroma_split = log2 > 3;
715 let offsets = [(0usize, 0usize), (half, 0), (0, half), (half, half)];
716 for (part, &(dx, dy)) in offsets.iter().enumerate() {
717 let (cx, cy) = (x + dx, y + dy);
718 let (child_cb, child_cr) = if chroma_split {
719 (
720 cb_cbf && dec.decode_bin(ctx::CBF_CHROMA + 1) != 0,
721 cr_cbf && dec.decode_bin(ctx::CBF_CHROMA + 1) != 0,
722 )
723 } else {
724 (false, false)
725 };
726 let child_luma_cbf = dec.decode_bin(ctx::CBF_LUMA) != 0;
727 self.reconstruct_luma(cx, cy, half, mode, log2 - 1, child_luma_cbf, dec);
728 // The next child predicts from this one, and (below the 8x8
729 // luma-tree case) so does its own chroma.
730 self.mark_coded(cx, cy, half, mode, depth);
731 self.mark_tu(cx, cy, half);
732 if chroma_split {
733 self.reconstruct_chroma(
734 cx,
735 cy,
736 half,
737 chroma_mode,
738 log2 - 1,
739 child_cb,
740 child_cr,
741 dec,
742 );
743 } else if part == 3 {
744 self.reconstruct_chroma(x, y, n, chroma_mode, log2, cb_cbf, cr_cbf, dec);
745 }
746 }
747 }
748}