forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

cu_syntax.rs1777 lines, 64.4 KiBHistoryRawDownload
1//! CABAC syntax of slice data for P and B slices (and for I slices when the
2//! syntax check runs): coding quadtree, coding units, prediction units, the
3//! transform tree, SAO parameters and the slice-segment loop (H.265 7.3.8.1 to
4//! 7.3.8.12, bin binarisations of 9.3.3 and context selection of 9.3.4.2).
5//!
6//! The parser reads every bin, keeps the syntax of each coding unit, and turns
7//! each transform block's coefficients into residual samples through the same
8//! dequantisation and inverse transform the intra path uses. It does not
9//! predict. Motion for each prediction unit comes from a [`MotionSource`]; the
10//! merge and AMVP lane implements that trait, and [`ZeroMotion`] stands in until
11//! then.
12//!
13//! Slices, slice segments, tiles and wavefront substreams are followed: CTBs
14//! are visited in tile scan order, contexts are initialised, synced or restored
15//! at each segment, tile and wavefront row start (9.3.1), and the arithmetic
16//! decoder restarts at each substream (7.3.8.1).
17
18use super::inter::{self, InterRefs};
19use super::mc::{Block, McScratch};
20use super::motion_field::MotionField;
21use super::pic::{BlockInfo, CtbInfo, EDGE_PU, EDGE_TU, PicState, SaoParams, SliceFilter};
22use super::rext;
23use super::tiles::TileScan;
24use crate::cabac::{CabacDecoder, Contexts, ctx};
25use crate::decode::chroma_shifts;
26use crate::intra;
27use crate::residual::{ResidualCfg, decode_residual_ext};
28use crate::transform::{
29 chroma_qp_for, dequantize_weighted, inverse_transform_bd, inverse_transform_skip_bd, uses_dst,
30};
31use ec_core::error::{Error, Result};
32use ec_h265_syntax::slice::{SliceHeader, SliceType};
33use ec_h265_syntax::{Pps, ScalingFactors, Sps};
34
35/// Wavefront parallel parsing of slice segments (9.3.2.2), in its own module.
36pub mod wpp;
37
38/// The partitioning of a coding unit (Table 7-10).
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum PartMode {
41 /// One prediction unit, the whole coding unit.
42 Part2Nx2N,
43 /// Two halves, stacked.
44 Part2NxN,
45 /// Two halves, side by side.
46 PartNx2N,
47 /// Four quarters (intra: the smallest coding unit; inter: only at the minimum size).
48 PartNxN,
49 /// Asymmetric: a quarter on top, three quarters below.
50 Part2NxnU,
51 /// Asymmetric: three quarters on top, a quarter below.
52 Part2NxnD,
53 /// Asymmetric: a quarter on the left, three quarters right.
54 PartnLx2N,
55 /// Asymmetric: three quarters on the left, a quarter right.
56 PartnRx2N,
57}
58
59/// `inter_pred_idc` (Table 7-? value meaning of 7.4.9.6).
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub enum InterPredIdc {
62 /// `PRED_L0`: list 0 only.
63 #[default]
64 PredL0,
65 /// `PRED_L1`: list 1 only.
66 PredL1,
67 /// `PRED_BI`: both lists.
68 PredBi,
69}
70
71/// The syntax of one prediction unit.
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
73pub struct PredictionUnit {
74 /// Luma position of the unit, in samples of the picture.
75 pub x: usize,
76 /// Luma position of the unit, in samples of the picture.
77 pub y: usize,
78 /// Luma width.
79 pub width: usize,
80 /// Luma height.
81 pub height: usize,
82 /// `merge_flag` (true for every unit of a skipped coding unit).
83 pub merge_flag: bool,
84 /// `merge_idx`, 0 when not present.
85 pub merge_idx: u8,
86 /// `inter_pred_idc`, `PredL0` unless a B slice says otherwise.
87 pub inter_pred_idc: InterPredIdc,
88 /// `ref_idx_l0` and `ref_idx_l1`, 0 when not present.
89 pub ref_idx: [u8; 2],
90 /// `mvp_l0_flag` and `mvp_l1_flag`.
91 pub mvp_flag: [u8; 2],
92 /// `MvdLX[0]` and `MvdLX[1]` (horizontal, vertical), per list.
93 pub mvd: [[i32; 2]; 2],
94}
95
96/// Motion of one prediction unit, as a [`MotionSource`] returns it.
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
98pub struct Motion {
99 /// `predFlagLX` for list 0 and list 1.
100 pub pred_flags: [bool; 2],
101 /// `refIdxLX`, -1 where the list is not used.
102 pub ref_idx: [i8; 2],
103 /// `mvLX` (horizontal, vertical), per list.
104 pub mv: [[i32; 2]; 2],
105}
106
107/// The geometry of a coding unit, as a [`MotionSource`] needs it.
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub struct CuGeometry {
110 /// Luma position of the coding unit.
111 pub x: usize,
112 /// Luma position of the coding unit.
113 pub y: usize,
114 /// Luma size of the coding unit.
115 pub size: usize,
116 /// The partitioning.
117 pub part_mode: PartMode,
118 /// Whether the coding unit is skipped.
119 pub skip: bool,
120}
121
122/// Derives the motion of each prediction unit. Called once per unit, in decoding
123/// order, after the unit's syntax has been parsed (so merge candidates from
124/// earlier units are available to the implementation). Merge and AMVP derivation
125/// (8.5.3) is the job of the implementation; the parser does not look inside.
126pub trait MotionSource {
127 /// The motion of unit `pu_index` of the coding unit `cu`.
128 fn derive_motion(&mut self, cu: &CuGeometry, pu_index: usize, pu: &PredictionUnit) -> Motion;
129
130 /// Called once the CTB row that ends at luma row `row_end` is fully parsed. Only
131 /// pictures with one tile get the call (their CTBs come in raster order).
132 fn row_done(&mut self, _pic: &mut PicState, _row_end: usize) {}
133
134 /// The motion field this source writes, when it is a wavefront band (see [`wpp`]).
135 fn band_cells(&mut self) -> Option<&mut MotionField> {
136 None
137 }
138}
139
140/// The placeholder [`MotionSource`]: zero motion vectors and reference index 0 for
141/// every list the unit uses. Replace it with the merge/AMVP derivation.
142#[derive(Clone, Copy, Debug, Default)]
143pub struct ZeroMotion;
144
145impl MotionSource for ZeroMotion {
146 fn derive_motion(&mut self, _cu: &CuGeometry, _pu_index: usize, pu: &PredictionUnit) -> Motion {
147 let pred_flags = if pu.merge_flag {
148 [true, false]
149 } else {
150 match pu.inter_pred_idc {
151 InterPredIdc::PredL0 => [true, false],
152 InterPredIdc::PredL1 => [false, true],
153 InterPredIdc::PredBi => [true, true],
154 }
155 };
156 let ref_idx = [
157 if pred_flags[0] {
158 i8::try_from(pu.ref_idx[0]).unwrap_or(0)
159 } else {
160 -1
161 },
162 if pred_flags[1] {
163 i8::try_from(pu.ref_idx[1]).unwrap_or(0)
164 } else {
165 -1
166 },
167 ];
168 Motion {
169 pred_flags,
170 ref_idx,
171 mv: [[0, 0], [0, 0]],
172 }
173 }
174}
175
176/// The residual samples of one transform block, after dequantisation and the
177/// inverse transform. Samples are row-major, `size * size`.
178#[derive(Clone, Debug, PartialEq, Eq)]
179pub struct ResidualBlock {
180 /// 0 luma, 1 Cb, 2 Cr.
181 pub component: usize,
182 /// Position in samples of that component.
183 pub x: usize,
184 /// Position in samples of that component.
185 pub y: usize,
186 /// Side length in samples of that component.
187 pub size: usize,
188 /// The residual, `size * size` values.
189 pub samples: Vec<i32>,
190}
191
192/// One coding unit, as parsed.
193#[derive(Clone, Debug, PartialEq, Eq)]
194pub struct CodingUnit {
195 /// Luma position.
196 pub x: usize,
197 /// Luma position.
198 pub y: usize,
199 /// `log2CbSize`.
200 pub log2_size: u32,
201 /// `cqtDepth` (CtDepth).
202 pub depth: u32,
203 /// `CuPredMode` is MODE_INTRA.
204 pub intra: bool,
205 /// `cu_skip_flag`.
206 pub skip: bool,
207 /// `PartMode`.
208 pub part_mode: PartMode,
209 /// `IntraPredModeY` of each partition (only the first one for 2Nx2N).
210 pub luma_modes: [u8; 4],
211 /// `IntraPredModeC` (intra only).
212 pub chroma_mode: u8,
213 /// The prediction units, in order.
214 pub pus: Vec<PredictionUnit>,
215 /// The motion of each prediction unit, from the [`MotionSource`].
216 pub motion: Vec<Motion>,
217 /// `rqt_root_cbf` (inferred 1 for intra).
218 pub rqt_root_cbf: bool,
219 /// `QpY` of the coding unit.
220 pub qp_y: i32,
221 /// The residual blocks, in decoding order.
222 pub residuals: Vec<ResidualBlock>,
223}
224
225/// What a slice's parse produced, for the test tables and for sanity checks.
226#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
227pub struct SliceStats {
228 /// Coding tree units parsed.
229 pub ctus: usize,
230 /// Coding units parsed.
231 pub cus: usize,
232 /// Intra coding units.
233 pub intra_cus: usize,
234 /// Skipped coding units.
235 pub skip_cus: usize,
236 /// Prediction units parsed.
237 pub pus: usize,
238 /// Residual blocks parsed.
239 pub residual_blocks: usize,
240 /// Coding tree units that carried SAO parameters.
241 pub sao_ctus: usize,
242 /// Whether the bytes after the end of the slice are the trailing bits
243 /// (a stop bit, then zeros) that 7.3.2.9 requires.
244 pub trailing_bits_ok: bool,
245}
246
247/// Parse one slice segment's data, from the byte after its header, to
248/// `end_of_slice_segment_flag`. `sink` sees every coding unit in decoding order.
249/// `motion` derives the motion of each prediction unit.
250///
251/// A desync shows up as an `end_of_slice_segment_flag` at the wrong CTB, or as a
252/// trailing-bit pattern that is not the stop bit; both are errors. This form
253/// keeps only the syntax: no samples are produced.
254pub fn parse_slice(
255 sps: &Sps,
256 pps: &Pps,
257 header: &SliceHeader,
258 data: &[u8],
259 motion: &mut dyn MotionSource,
260 sink: &mut dyn FnMut(&CodingUnit),
261) -> Result<SliceStats> {
262 let mut pic = PicState::for_sps_pps(sps, pps, false);
263 parse_slice_into(
264 sps,
265 pps,
266 header,
267 data,
268 motion,
269 &mut pic,
270 None,
271 sink,
272 &mut |_, _| {},
273 )
274}
275
276/// Parse one slice segment's data into `pic`. The block maps are always
277/// filled. When `pic` has sample planes (pixel decode), intra coding units are
278/// reconstructed in decoding order, and inter coding units are predicted from
279/// `refs` (8.5.3.3) per prediction unit, then get their residual added.
280#[allow(clippy::too_many_arguments)] // the slice, the picture it decodes into, and its references
281pub fn parse_slice_into(
282 sps: &Sps,
283 pps: &Pps,
284 header: &SliceHeader,
285 data: &[u8],
286 motion: &mut dyn MotionSource,
287 pic: &mut PicState,
288 refs: Option<&InterRefs>,
289 sink: &mut dyn FnMut(&CodingUnit),
290 rows: &mut dyn FnMut(&mut PicState, usize),
291) -> Result<SliceStats> {
292 let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3;
293 let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size;
294 let slice_qp = 26 + pps.init_qp_minus26 + header.qp_delta;
295 // 7.4.3.3.1: Log2ParMrgLevel = log2_parallel_merge_level_minus2 + 2 is at most CtbLog2SizeY.
296 // Merge derivation shifts coordinates by it, so a larger value is a shift overflow.
297 if pps.log2_parallel_merge_level_minus2.saturating_add(2) > ctb_log2 {
298 return Err(Error::corrupt(
299 "HEVC PPS: Log2ParMrgLevel exceeds CtbLog2SizeY",
300 ));
301 }
302 // 7.4.3.3.1: diff_cu_qp_delta_depth is at most log2_diff_max_min_luma_coding_block_size.
303 if pps.cu_qp_delta_enabled && pps.diff_cu_qp_delta_depth > sps.log2_diff_max_min_cb_size {
304 return Err(Error::corrupt(
305 "HEVC PPS: diff_cu_qp_delta_depth exceeds the CTB depth",
306 ));
307 }
308 // 7-56 / 7.4.7.1: SliceQpY lies in -QpBdOffsetY..=51.
309 if !(-6 * sps.bit_depth_luma_minus8 as i32..=51).contains(&slice_qp) {
310 return Err(Error::corrupt(
311 "HEVC slice: SliceQpY is outside -QpBdOffsetY..=51",
312 ));
313 }
314 let init_type = match header.slice_type {
315 SliceType::I => 0,
316 SliceType::P => 1 + u8::from(header.cabac_init),
317 SliceType::B => 2 - u8::from(header.cabac_init),
318 };
319 let cols = pic.ctb_cols;
320 let total = cols * pic.ctb_rows;
321 // 6.5.1: the tile scan of this picture (the same for every segment of it).
322 pic.tiles = TileScan::from_pps(pps, cols, pic.ctb_rows)?;
323 let start_ts = pic
324 .tiles
325 .rs_to_ts
326 .get(header.segment_address as usize)
327 .copied()
328 .ok_or_else(|| {
329 Error::corrupt("HEVC slice: slice_segment_address is outside the picture")
330 })?;
331 // SliceAddrRs: a dependent segment belongs to the slice of the segment before it.
332 if !header.dependent_slice_segment {
333 pic.carry.slice_addr = header.segment_address as usize;
334 }
335 let slice_addr = pic.carry.slice_addr;
336 let dependent = header.dependent_slice_segment;
337 let slice_index = u16::try_from(pic.slices.len()).map_err(|_| {
338 Error::unsupported("HEVC slice syntax: slice count", "more than 65535 slices")
339 })?;
340 pic.slices.push(SliceFilter {
341 deblock_disabled: header.deblocking_filter_disabled,
342 beta_offset_div2: header.beta_offset_div2,
343 tc_offset_div2: header.tc_offset_div2,
344 loop_filter_across_slices: header.loop_filter_across_slices_enabled,
345 sao_luma: header.sao_luma,
346 sao_chroma: header.sao_chroma,
347 });
348 // qPY_PREV carries over a dependent segment (the first QG of a slice, not of a segment).
349 let last_qp = if dependent {
350 pic.carry.last_qp
351 } else {
352 slice_qp
353 };
354 let mut p = new_parser(sps, pps, header, pic, refs, motion, last_qp);
355 let fresh = Contexts::for_init_type(slice_qp, init_type);
356 let mut dec = CabacDecoder::new(data, fresh.clone());
357 let wpp = pps.entropy_coding_sync_enabled;
358 let raster = !pps.tiles_enabled;
359 let ctb_size = 1usize << ctb_log2;
360 // A slice segment ends at the first end_of_slice_segment_flag equal to 1,
361 // which may come before the picture's last CTB (several slices per picture).
362 let mut ended = false;
363 let mut ts = start_ts;
364 let mut first = true;
365 while ts < total {
366 let rs = p
367 .pic
368 .tiles
369 .ts_to_rs
370 .get(ts)
371 .copied()
372 .ok_or_else(|| Error::corrupt("HEVC slice: CTB address past the picture"))?;
373 let (rx, ry) = (rs % cols, rs / cols);
374 let (x0, y0) = (rx << ctb_log2, ry << ctb_log2);
375 let tile_start = p.pic.tiles.is_tile_start(ts);
376 let row_start = wpp && p.pic.tiles.is_row_start(rs, cols);
377 let tile = p.pic.tiles.tile_of_rs.get(rs).copied().unwrap_or(0);
378 let ctb = p
379 .pic
380 .ctb
381 .get_mut(rs)
382 .ok_or_else(|| Error::corrupt("HEVC slice: CTB address past the picture"))?;
383 *ctb = CtbInfo {
384 slice: slice_index,
385 slice_addr: slice_addr as u32,
386 tile,
387 sao: ctb.sao,
388 };
389 p.stats.ctus += 1;
390 // 9.3.1: the contexts at the start of a CTB. A tile starts fresh; a wavefront
391 // row syncs from the CTB above and to the right (when it is available), and
392 // a dependent segment restores the contexts the segment before it left.
393 if tile_start {
394 dec.contexts = fresh.clone();
395 } else if row_start {
396 let top_right = p.pic.available(
397 x0,
398 y0,
399 (x0 + ctb_size) as isize,
400 y0 as isize - ctb_size as isize,
401 );
402 dec.contexts = match (top_right, p.pic.carry.wpp.clone()) {
403 (true, Some(saved)) => saved,
404 _ => fresh.clone(),
405 };
406 } else if first && dependent {
407 dec.contexts = p.pic.carry.ds.clone().unwrap_or_else(|| fresh.clone());
408 }
409 if tile_start || row_start || (first && !dependent) {
410 p.last_qp = slice_qp;
411 }
412 if header.sao_luma || header.sao_chroma {
413 p.sao(&mut dec, rs, rx, ry)?;
414 }
415 p.coding_quadtree(&mut dec, x0, y0, ctb_log2, 0, sink)?;
416 // The row is complete with its last CTB. Single-tile pictures are in raster order.
417 if raster && rx + 1 == cols {
418 p.motion.row_done(p.pic, y0 + ctb_size);
419 rows(p.pic, ry);
420 }
421 // 9.3.2.2: the wavefront storage after the second CTB of a row in a tile.
422 if wpp
423 && (rs % cols == 1
424 || (rs > 1 && p.pic.tiles.tile_of_rs.get(rs) != p.pic.tiles.tile_of_rs.get(rs - 2)))
425 {
426 p.pic.carry.wpp = Some(dec.contexts.clone());
427 }
428 if dec.decode_terminate() != 0 {
429 ended = true;
430 break;
431 }
432 ts += 1;
433 first = false;
434 // 7.3.8.1: a new tile or a new wavefront row starts a substream. The next
435 // CTB begins with end_of_subset_one_bit and byte alignment, then a fresh
436 // arithmetic decoder (9.3.2.5). Entry point offsets are not needed for this.
437 if ts < total {
438 let next_rs = p.pic.tiles.ts_to_rs.get(ts).copied().unwrap_or(0);
439 let next_row = wpp && p.pic.tiles.is_row_start(next_rs, cols);
440 if p.pic.tiles.is_tile_start(ts) || next_row {
441 if dec.decode_terminate() != 1 {
442 return Err(Error::corrupt(
443 "HEVC slice syntax: end_of_subset_one_bit was not set at a substream boundary",
444 ));
445 }
446 dec.restart_at_byte(dec.byte_position_aligned());
447 }
448 }
449 }
450 if !ended {
451 return Err(Error::corrupt(
452 "HEVC slice syntax: end_of_slice_segment_flag 0 after the last CTB of the picture",
453 ));
454 }
455 // The state the next segment may restore (9.3.1 storage at the end of a segment).
456 p.pic.carry.ds = Some(dec.contexts.clone());
457 p.pic.carry.last_qp = p.last_qp;
458 // rbsp_slice_segment_trailing_bits (7.3.2.10): the stop bit, zeros to the
459 // byte boundary, then optional cabac_zero_words (zero bytes). Where the stop
460 // bit sits relative to the decoder's read position is checked both ways.
461 let read = dec.bits_read();
462 p.stats.trailing_bits_ok = trailing_bits_ok(data, read);
463 if !p.stats.trailing_bits_ok {
464 return Err(Error::corrupt(format!(
465 "HEVC slice syntax: no stop bit at the end of the slice data (CABAC read {read} bits)"
466 )));
467 }
468 Ok(p.stats)
469}
470
471/// Whether the slice data ends with the stop bit of `rbsp_slice_segment_trailing_bits`
472/// (7.3.2.10) at the bit the decoder reached (`read` bits in), or one bit before it, and
473/// zeros (cabac_zero_words) follow to the end of `data`.
474pub(super) fn trailing_bits_ok(data: &[u8], read: usize) -> bool {
475 let stop_at = |bit: usize| -> bool {
476 let Some(&byte) = data.get(bit / 8) else {
477 return false;
478 };
479 let shift = 7 - (bit % 8);
480 byte & (1 << shift) != 0
481 && byte & ((1u16 << shift) - 1) as u8 == 0
482 && data[bit / 8 + 1..].iter().all(|&b| b == 0)
483 };
484 read > 0 && (stop_at(read - 1) || stop_at(read))
485}
486
487/// The coding-tree walk of one slice segment, starting with `last_qp` as qPY_PREV.
488fn new_parser<'a>(
489 sps: &'a Sps,
490 pps: &'a Pps,
491 header: &'a SliceHeader,
492 pic: &'a mut PicState,
493 refs: Option<&'a InterRefs>,
494 motion: &'a mut dyn MotionSource,
495 last_qp: i32,
496) -> Parser<'a> {
497 let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3;
498 let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size;
499 let min_tb_log2 = sps.log2_min_tb_size_minus2 + 2;
500 let slice_qp = 26 + pps.init_qp_minus26 + header.qp_delta;
501 Parser {
502 sps,
503 pps,
504 header,
505 scaling: ScalingFactors::for_picture(sps, pps),
506 pic,
507 refs,
508 mc_scratch: McScratch::new(),
509 min_cb_log2,
510 ctb_log2,
511 min_tb_log2,
512 max_tb_log2: min_tb_log2 + sps.log2_diff_max_min_tb_size,
513 max_depth_inter: sps.max_transform_hierarchy_depth_inter,
514 max_depth_intra: sps.max_transform_hierarchy_depth_intra,
515 max_merge: 5 - header.five_minus_max_num_merge_cand.min(4),
516 qg_log2: ctb_log2
517 - if pps.cu_qp_delta_enabled {
518 pps.diff_cu_qp_delta_depth
519 } else {
520 0
521 },
522 qp_bd_y: 6 * sps.bit_depth_luma_minus8 as i32,
523 qp_bd_c: 6 * sps.bit_depth_chroma_minus8 as i32,
524 last_qp,
525 qg_pred: slice_qp,
526 qp_delta: 0,
527 qp_delta_coded: false,
528 cu_chroma_qp_offset_enabled: header.cu_chroma_qp_offset_enabled,
529 chroma_qg_coded: false,
530 chroma_qg_log2: ctb_log2 - pps.range.diff_cu_chroma_qp_offset_depth,
531 cu_qp_offset: [0, 0],
532 cu_bypass: false,
533 chroma_modes: ([1; 4], [false; 4]),
534 motion,
535 stats: SliceStats::default(),
536 }
537}
538
539/// Per-transform-tree facts that do not change down the tree.
540#[derive(Clone, Copy)]
541struct TxInfo {
542 intra: bool,
543 intra_split: bool,
544 inter_split: bool,
545 max_depth: u32,
546 /// `IntraPredModeC` of each partition (all four the same unless 4:4:4 NxN).
547 chroma_modes: [u8; 4],
548 /// `intra_chroma_pred_mode == 4` (the derived mode) of each partition.
549 chroma_dm: [bool; 4],
550 /// The coding unit's position and size, to find the partition of a transform block.
551 cu_x: usize,
552 cu_y: usize,
553 cu_log2: u32,
554}
555
556/// One node of the transform tree (7.3.8.8).
557#[derive(Clone, Copy)]
558struct TxNode {
559 x0: usize,
560 y0: usize,
561 x_base: usize,
562 y_base: usize,
563 log2: u32,
564 depth: u32,
565 blk_idx: usize,
566}
567
568/// The coded block flags of a transform unit.
569/// Table 8-3: the 4:2:2 chroma intra mode for each intra mode (the mode of the 4:2:0 table
570/// that the 4:2:2 chroma grid maps it to). Horizontal-ish modes (2..17) double their
571/// angle for the half-width chroma grid, so 11 (-2) goes to 12 (-5) and 14 (-13) to 17 (-26).
572const MODE_422: [u8; 35] = [
573 0, 1, 2, 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, 18, 19, 20, 21, 22, 23, 23, 24, 24, 25, 25,
574 26, 27, 27, 28, 28, 29, 29, 30, 31,
575];
576
577#[derive(Clone, Copy)]
578struct Cbf {
579 luma: bool,
580 /// `cbf_cb`: one flag, or two for 4:2:2 (the upper and lower square blocks).
581 cb: [bool; 2],
582 /// `cbf_cr`, as `cb`.
583 cr: [bool; 2],
584}
585
586/// The coding-tree walk state for one slice segment.
587struct Parser<'a> {
588 sps: &'a Sps,
589 pps: &'a Pps,
590 header: &'a SliceHeader,
591 /// The picture being decoded: maps, samples, CTB state.
592 pic: &'a mut PicState,
593 /// The reference samples and weights of the slice (`None` for an I slice).
594 refs: Option<&'a InterRefs>,
595 /// Scratch buffers of motion compensation, reused across prediction units.
596 mc_scratch: McScratch,
597 min_cb_log2: u32,
598 ctb_log2: u32,
599 min_tb_log2: u32,
600 max_tb_log2: u32,
601 max_depth_inter: u32,
602 max_depth_intra: u32,
603 max_merge: u32,
604 /// `Log2MinCuQpDeltaSize`.
605 qg_log2: u32,
606 /// The scaling factors of the picture (`None`: flat 16, 7.4.3.3).
607 scaling: Option<ScalingFactors>,
608 /// `QpBdOffsetY` and `QpBdOffsetC`.
609 qp_bd_y: i32,
610 qp_bd_c: i32,
611 /// `qPY_PREV`: the QpY of the last coding unit parsed.
612 last_qp: i32,
613 /// `qPY_PRED` of the current quantization group.
614 qg_pred: i32,
615 /// `CuQpDeltaVal`.
616 qp_delta: i32,
617 /// `IsCuQpDeltaCoded`.
618 qp_delta_coded: bool,
619 /// `cu_chroma_qp_offset_enabled_flag` of the slice.
620 cu_chroma_qp_offset_enabled: bool,
621 /// `IsCuChromaQpOffsetCoded`.
622 chroma_qg_coded: bool,
623 /// `Log2MinCuChromaQpOffsetSize`.
624 chroma_qg_log2: u32,
625 /// `CuQpOffsetCb` and `CuQpOffsetCr`.
626 cu_qp_offset: [i32; 2],
627 /// `cu_transquant_bypass_flag` of the coding unit being parsed.
628 cu_bypass: bool,
629 /// The chroma modes of the intra coding unit being parsed, with their DM flags.
630 chroma_modes: ([u8; 4], [bool; 4]),
631 motion: &'a mut dyn MotionSource,
632 stats: SliceStats,
633}
634
635impl Parser<'_> {
636 fn info_at(&self, x: usize, y: usize) -> BlockInfo {
637 self.pic.info[self.pic.unit(x, y)]
638 }
639
640 /// `QpY` of the current coding unit (8-283): the prediction plus
641 /// CuQpDeltaVal, wrapped into the range `-QpBdOffsetY..=51`.
642 fn cu_qp(&self) -> i32 {
643 let off = self.qp_bd_y;
644 // rem_euclid keeps the result in range even for a CuQpDeltaVal outside its
645 // legal span (checked in the parser) or an overflowing sum.
646 let sum = self
647 .qg_pred
648 .saturating_add(self.qp_delta)
649 .saturating_add(52 + 2 * off);
650 sum.rem_euclid(52 + off) - off
651 }
652
653 /// `qPY_PRED` for the quantization group at `(x, y)` (8.6.1).
654 fn start_quantization_group(&mut self, x: usize, y: usize) {
655 self.qp_delta_coded = false;
656 self.qp_delta = 0;
657 let prev = self.last_qp;
658 let ctb_mask = (1usize << self.ctb_log2) - 1;
659 let qa = if x & ctb_mask != 0 {
660 i32::from(self.info_at(x - 1, y).qp)
661 } else {
662 prev
663 };
664 let qb = if y & ctb_mask != 0 {
665 i32::from(self.info_at(x, y - 1).qp)
666 } else {
667 prev
668 };
669 self.qg_pred = (qa + qb + 1) >> 1;
670 }
671
672 fn coding_quadtree(
673 &mut self,
674 dec: &mut CabacDecoder,
675 x0: usize,
676 y0: usize,
677 log2: u32,
678 depth: u32,
679 sink: &mut dyn FnMut(&CodingUnit),
680 ) -> Result<()> {
681 let n = 1usize << log2;
682 let fits = x0 + n <= self.pic.width && y0 + n <= self.pic.height;
683 let split = if fits && log2 > self.min_cb_log2 {
684 let mut inc = 0;
685 if self.pic.available(x0, y0, x0 as isize - 1, y0 as isize)
686 && u32::from(self.info_at(x0 - 1, y0).depth) > depth
687 {
688 inc += 1;
689 }
690 if self.pic.available(x0, y0, x0 as isize, y0 as isize - 1)
691 && u32::from(self.info_at(x0, y0 - 1).depth) > depth
692 {
693 inc += 1;
694 }
695 dec.decode_bin(ctx::SPLIT_CU + inc) != 0
696 } else {
697 log2 > self.min_cb_log2
698 };
699 if log2 >= self.qg_log2 {
700 self.start_quantization_group(x0, y0);
701 }
702 if self.cu_chroma_qp_offset_enabled && log2 >= self.chroma_qg_log2 {
703 self.chroma_qg_coded = false;
704 }
705 if split {
706 let half = n / 2;
707 for (dx, dy) in [(0, 0), (half, 0), (0, half), (half, half)] {
708 if x0 + dx < self.pic.width && y0 + dy < self.pic.height {
709 self.coding_quadtree(dec, x0 + dx, y0 + dy, log2 - 1, depth + 1, sink)?;
710 }
711 }
712 Ok(())
713 } else {
714 self.coding_unit(dec, x0, y0, log2, depth, sink)
715 }
716 }
717
718 /// `pcm_flag` may be read for a coding unit of this size (7.3.8.5).
719 fn pcm_size_ok(&self, log2: u32) -> bool {
720 match self.sps.pcm {
721 Some((_, _, min_m3, diff, _)) if self.sps.pcm_enabled => {
722 let min = min_m3 + 3;
723 (min..=min + diff).contains(&log2)
724 }
725 _ => false,
726 }
727 }
728
729 fn coding_unit(
730 &mut self,
731 dec: &mut CabacDecoder,
732 x0: usize,
733 y0: usize,
734 log2: u32,
735 depth: u32,
736 sink: &mut dyn FnMut(&CodingUnit),
737 ) -> Result<()> {
738 let n = 1usize << log2;
739 self.stats.cus += 1;
740 let is_i = self.header.slice_type == SliceType::I;
741 let bypass =
742 self.pps.transquant_bypass_enabled && dec.decode_bin(ctx::CU_TRANSQUANT_BYPASS) != 0;
743 self.cu_bypass = bypass;
744 let skip = !is_i && {
745 let mut inc = 0;
746 if self.pic.available(x0, y0, x0 as isize - 1, y0 as isize)
747 && self.info_at(x0 - 1, y0).skip
748 {
749 inc += 1;
750 }
751 if self.pic.available(x0, y0, x0 as isize, y0 as isize - 1)
752 && self.info_at(x0, y0 - 1).skip
753 {
754 inc += 1;
755 }
756 dec.decode_bin(ctx::CU_SKIP + inc) != 0
757 };
758 let intra = if skip {
759 false
760 } else if is_i {
761 true
762 } else {
763 dec.decode_bin(ctx::PRED_MODE) != 0
764 };
765 let mut cu = CodingUnit {
766 x: x0,
767 y: y0,
768 log2_size: log2,
769 depth,
770 intra,
771 skip,
772 part_mode: PartMode::Part2Nx2N,
773 luma_modes: [1; 4],
774 chroma_mode: 1,
775 pus: Vec::new(),
776 motion: Vec::new(),
777 rqt_root_cbf: false,
778 qp_y: 0,
779 residuals: Vec::new(),
780 };
781 self.pic.update_info(x0, y0, n, n, |b| {
782 b.depth = depth as u8;
783 b.skip = skip;
784 b.intra = intra;
785 b.bypass = bypass;
786 b.pcm = false;
787 b.intra_mode = 1;
788 b.nz_luma = false;
789 b.edge_v = 0;
790 b.edge_h = 0;
791 });
792 // The coding unit's own boundary is a transform (and prediction) edge.
793 self.pic.mark_edges(x0, y0, n, n, EDGE_TU | EDGE_PU);
794
795 if skip {
796 self.stats.skip_cus += 1;
797 let geom = CuGeometry {
798 x: x0,
799 y: y0,
800 size: n,
801 part_mode: PartMode::Part2Nx2N,
802 skip: true,
803 };
804 let pu = self.prediction_unit(dec, x0, y0, n, n, depth, true)?;
805 let m = self.motion.derive_motion(&geom, 0, &pu);
806 self.predict_pu(x0, y0, n, n, &m)?;
807 cu.motion.push(m);
808 cu.pus.push(pu);
809 } else if intra {
810 self.stats.intra_cus += 1;
811 cu.part_mode = if log2 == self.min_cb_log2 && dec.decode_bin(ctx::PART_MODE) == 0 {
812 PartMode::PartNxN
813 } else {
814 PartMode::Part2Nx2N
815 };
816 let nparts = if cu.part_mode == PartMode::PartNxN {
817 4
818 } else {
819 1
820 };
821 let pu_size = if nparts == 4 { n / 2 } else { n };
822 if cu.part_mode == PartMode::Part2Nx2N
823 && self.pcm_size_ok(log2)
824 && dec.decode_terminate() != 0
825 {
826 self.pcm_cu(dec, x0, y0, log2)?;
827 } else {
828 cu.luma_modes = self.intra_luma_modes(dec, x0, y0, pu_size, nparts);
829 // 4:4:4 codes one chroma mode per partition, other formats one in all.
830 let nchroma = match self.sps.chroma_format_idc {
831 0 => 0,
832 3 => nparts,
833 _ => 1,
834 };
835 let mut chroma_modes = [1u8; 4];
836 let mut chroma_dm = [false; 4];
837 for i in 0..nchroma {
838 (chroma_modes[i], chroma_dm[i]) = self.chroma_mode(dec, cu.luma_modes[i]);
839 }
840 if nchroma == 1 {
841 chroma_modes = [chroma_modes[0]; 4];
842 chroma_dm = [chroma_dm[0]; 4];
843 }
844 cu.chroma_mode = chroma_modes[0];
845 cu.rqt_root_cbf = true;
846 self.chroma_modes = (chroma_modes, chroma_dm);
847 self.transform_tree_root(dec, &mut cu, log2, true)?;
848 }
849 } else {
850 cu.part_mode = if dec.decode_bin(ctx::PART_MODE) == 0 {
851 self.inter_part_mode(dec, log2)
852 } else {
853 PartMode::Part2Nx2N
854 };
855 let geom = CuGeometry {
856 x: x0,
857 y: y0,
858 size: n,
859 part_mode: cu.part_mode,
860 skip: false,
861 };
862 for (i, (px, py, pw, ph)) in pu_rects(cu.part_mode, x0, y0, n).into_iter().enumerate() {
863 let pu = self.prediction_unit(dec, px, py, pw, ph, depth, false)?;
864 let m = self.motion.derive_motion(&geom, i, &pu);
865 self.predict_pu(px, py, pw, ph, &m)?;
866 self.pic.mark_edges(px, py, pw, ph, EDGE_PU);
867 cu.motion.push(m);
868 cu.pus.push(pu);
869 }
870 cu.rqt_root_cbf = if !(cu.part_mode == PartMode::Part2Nx2N && cu.pus[0].merge_flag) {
871 dec.decode_bin(ctx::RQT_ROOT_CBF) != 0
872 } else {
873 true
874 };
875 if cu.rqt_root_cbf {
876 self.transform_tree_root(dec, &mut cu, log2, false)?;
877 }
878 }
879 if !intra {
880 inter::add_residuals(self.pic, &cu.residuals);
881 }
882 cu.qp_y = self.cu_qp();
883 self.last_qp = cu.qp_y;
884 let qp = cu.qp_y as i8;
885 self.pic.update_info(x0, y0, n, n, |b| b.qp = qp);
886 self.stats.pus += cu.pus.len();
887 self.stats.residual_blocks += cu.residuals.len();
888 sink(&cu);
889 Ok(())
890 }
891
892 /// Motion-compensated prediction of one prediction unit (8.5.3.3) into the
893 /// picture's samples. Nothing happens without pixel decode.
894 fn predict_pu(&mut self, x: usize, y: usize, w: usize, h: usize, m: &Motion) -> Result<()> {
895 if !self.pic.has_pixels() {
896 return Ok(());
897 }
898 let Some(refs) = self.refs else {
899 return Err(Error::corrupt(
900 "HEVC decode: an inter prediction unit in a slice with no reference lists",
901 ));
902 };
903 let mut out = self.pic.planes_mut();
904 refs.predict(
905 m,
906 Block {
907 x,
908 y,
909 width: w,
910 height: h,
911 },
912 &mut out,
913 &mut self.mc_scratch,
914 )
915 }
916
917 /// The transform tree of a coding unit, from its root.
918 fn transform_tree_root(
919 &mut self,
920 dec: &mut CabacDecoder,
921 cu: &mut CodingUnit,
922 log2: u32,
923 intra: bool,
924 ) -> Result<()> {
925 let intra_split = intra && cu.part_mode == PartMode::PartNxN;
926 let tx = TxInfo {
927 intra,
928 intra_split,
929 inter_split: !intra && cu.part_mode != PartMode::Part2Nx2N && self.max_depth_inter == 0,
930 max_depth: if intra {
931 self.max_depth_intra + u32::from(intra_split)
932 } else {
933 self.max_depth_inter
934 },
935 chroma_modes: self.chroma_modes.0,
936 chroma_dm: self.chroma_modes.1,
937 cu_x: cu.x,
938 cu_y: cu.y,
939 cu_log2: log2,
940 };
941 let node = TxNode {
942 x0: cu.x,
943 y0: cu.y,
944 x_base: cu.x,
945 y_base: cu.y,
946 log2,
947 depth: 0,
948 blk_idx: 0,
949 };
950 self.transform_tree(dec, &tx, node, [[false; 2]; 2], &mut cu.residuals)
951 }
952
953 /// `intra_luma_prev_intra_pred_flag`, `mpm_idx` or `rem_intra_luma_pred_mode`
954 /// for each partition, with the modes written to the map as they are derived.
955 fn intra_luma_modes(
956 &mut self,
957 dec: &mut CabacDecoder,
958 x0: usize,
959 y0: usize,
960 pu_size: usize,
961 nparts: usize,
962 ) -> [u8; 4] {
963 let mut prev = [false; 4];
964 for flag in prev.iter_mut().take(nparts) {
965 *flag = dec.decode_bin(ctx::PREV_INTRA_LUMA_PRED) != 0;
966 }
967 let mut modes = [1u8; 4];
968 for (i, mode_out) in modes.iter_mut().enumerate().take(nparts) {
969 let px = x0 + (i & 1) * pu_size;
970 let py = y0 + (i >> 1) * pu_size;
971 let mpm = self.mpm(px, py);
972 let mode = if prev[i] {
973 let idx = if dec.decode_bypass() == 0 {
974 0
975 } else {
976 1 + dec.decode_bypass() as usize
977 };
978 mpm[idx]
979 } else {
980 let rem = dec.decode_bypass_bits(5) as u8;
981 let mut sorted = mpm;
982 sorted.sort_unstable();
983 let mut mode = rem;
984 for m in sorted {
985 if mode >= m {
986 mode += 1;
987 }
988 }
989 mode
990 };
991 *mode_out = mode;
992 self.pic
993 .update_info(px, py, pu_size, pu_size, |b| b.intra_mode = mode);
994 }
995 modes
996 }
997
998 /// `candModeList` of 8.4.2 for the partition at `(x, y)`. A neighbour that is
999 /// unavailable, not intra, PCM, or above the current CTB row reads as DC.
1000 fn mpm(&self, x: usize, y: usize) -> [u8; 3] {
1001 let left = if self.pic.available(x, y, x as isize - 1, y as isize) {
1002 self.info_at(x - 1, y).intra_mode
1003 } else {
1004 1
1005 };
1006 let ctb_mask = (1usize << self.ctb_log2) - 1;
1007 let above = if y & ctb_mask != 0 {
1008 self.info_at(x, y - 1).intra_mode
1009 } else {
1010 1
1011 };
1012 intra::mpm_list(Some(left), Some(above))
1013 }
1014
1015 /// `intra_chroma_pred_mode` and the mode it names (8.4.3, Table 8-2).
1016 fn chroma_mode(&self, dec: &mut CabacDecoder, luma: u8) -> (u8, bool) {
1017 let dm = dec.decode_bin(ctx::INTRA_CHROMA_PRED_MODE) == 0;
1018 let mode = if dm {
1019 luma
1020 } else {
1021 let candidate = [0u8, 26, 10, 1][dec.decode_bypass_bits(2) as usize];
1022 if candidate == luma { 34 } else { candidate }
1023 };
1024 // 8.4.3, Table 8-3: the 4:2:2 chroma mode is the angle that the 4:2:2 chroma
1025 // grid gives the mode's angle in 4:2:0 terms.
1026 let mode = if self.sps.chroma_format_idc == 2 {
1027 MODE_422[usize::from(mode)]
1028 } else {
1029 mode
1030 };
1031 (mode, dm)
1032 }
1033
1034 /// `part_mode` of an inter coding unit (9.3.3.7, Table 9-43). The first bin
1035 /// is read by the caller.
1036 fn inter_part_mode(&mut self, dec: &mut CabacDecoder, log2: u32) -> PartMode {
1037 if log2 == self.min_cb_log2 {
1038 if dec.decode_bin(ctx::PART_MODE + 1) != 0 {
1039 return PartMode::Part2NxN;
1040 }
1041 if log2 == 3 {
1042 return PartMode::PartNx2N;
1043 }
1044 return if dec.decode_bin(ctx::PART_MODE + 2) != 0 {
1045 PartMode::PartNx2N
1046 } else {
1047 PartMode::PartNxN
1048 };
1049 }
1050 if !self.sps.amp_enabled {
1051 return if dec.decode_bin(ctx::PART_MODE + 1) != 0 {
1052 PartMode::Part2NxN
1053 } else {
1054 PartMode::PartNx2N
1055 };
1056 }
1057 let horizontal = dec.decode_bin(ctx::PART_MODE + 1) != 0;
1058 if dec.decode_bin(ctx::PART_MODE + 3) != 0 {
1059 return if horizontal {
1060 PartMode::Part2NxN
1061 } else {
1062 PartMode::PartNx2N
1063 };
1064 }
1065 let second = dec.decode_bypass() != 0;
1066 match (horizontal, second) {
1067 (true, false) => PartMode::Part2NxnU,
1068 (true, true) => PartMode::Part2NxnD,
1069 (false, false) => PartMode::PartnLx2N,
1070 (false, true) => PartMode::PartnRx2N,
1071 }
1072 }
1073
1074 /// One prediction unit (7.3.8.6). `skip` is the coding unit's `cu_skip_flag`.
1075 #[allow(clippy::too_many_arguments)] // the unit's position, size and the CU facts it reads
1076 fn prediction_unit(
1077 &mut self,
1078 dec: &mut CabacDecoder,
1079 x: usize,
1080 y: usize,
1081 width: usize,
1082 height: usize,
1083 depth: u32,
1084 skip: bool,
1085 ) -> Result<PredictionUnit> {
1086 let mut pu = PredictionUnit {
1087 x,
1088 y,
1089 width,
1090 height,
1091 ..PredictionUnit::default()
1092 };
1093 pu.merge_flag = skip || dec.decode_bin(ctx::MERGE_FLAG) != 0;
1094 if pu.merge_flag {
1095 if self.max_merge > 1 {
1096 pu.merge_idx = truncated_unary(dec, self.max_merge - 1, ctx::MERGE_IDX) as u8;
1097 }
1098 return Ok(pu);
1099 }
1100 pu.inter_pred_idc = if self.header.slice_type == SliceType::B {
1101 inter_pred_idc(dec, width, height, depth)
1102 } else {
1103 InterPredIdc::PredL0
1104 };
1105 let uses_l0 = pu.inter_pred_idc != InterPredIdc::PredL1;
1106 let uses_l1 = pu.inter_pred_idc != InterPredIdc::PredL0;
1107 if uses_l0 {
1108 if self.header.num_ref_idx_l0_active_minus1 > 0 {
1109 pu.ref_idx[0] = self.ref_idx(dec, self.header.num_ref_idx_l0_active_minus1) as u8;
1110 }
1111 pu.mvd[0] = self.mvd_coding(dec)?;
1112 pu.mvp_flag[0] = dec.decode_bin(ctx::MVP_FLAG) as u8;
1113 }
1114 if uses_l1 {
1115 if self.header.num_ref_idx_l1_active_minus1 > 0 {
1116 pu.ref_idx[1] = self.ref_idx(dec, self.header.num_ref_idx_l1_active_minus1) as u8;
1117 }
1118 pu.mvd[1] = if self.header.mvd_l1_zero && pu.inter_pred_idc == InterPredIdc::PredBi {
1119 [0, 0]
1120 } else {
1121 self.mvd_coding(dec)?
1122 };
1123 pu.mvp_flag[1] = dec.decode_bin(ctx::MVP_FLAG) as u8;
1124 }
1125 Ok(pu)
1126 }
1127
1128 /// `ref_idx_lX`: truncated rice, bins 0 and 1 in contexts, the rest bypass.
1129 fn ref_idx(&self, dec: &mut CabacDecoder, cmax: u32) -> u32 {
1130 let mut v = 0;
1131 while v < cmax {
1132 let bin = if v < 2 {
1133 dec.decode_bin(ctx::REF_IDX + v as usize)
1134 } else {
1135 dec.decode_bypass()
1136 };
1137 if bin == 0 {
1138 break;
1139 }
1140 v += 1;
1141 }
1142 v
1143 }
1144
1145 /// `mvd_coding` (7.3.8.9): the two greater-than flags of each component,
1146 /// then for each component `abs_mvd_minus2` (EG1, bypass) and the sign.
1147 fn mvd_coding(&self, dec: &mut CabacDecoder) -> Result<[i32; 2]> {
1148 let gt0 = [
1149 dec.decode_bin(ctx::ABS_MVD_GT0) != 0,
1150 dec.decode_bin(ctx::ABS_MVD_GT0) != 0,
1151 ];
1152 let gt1 = [
1153 gt0[0] && dec.decode_bin(ctx::ABS_MVD_GT1) != 0,
1154 gt0[1] && dec.decode_bin(ctx::ABS_MVD_GT1) != 0,
1155 ];
1156 let mut mvd = [0i32; 2];
1157 for (c, mvd_c) in mvd.iter_mut().enumerate() {
1158 if !gt0[c] {
1159 continue;
1160 }
1161 let abs = if gt1[c] {
1162 2 + i64::from(decode_exp_golomb(dec, 1)?)
1163 } else {
1164 1
1165 };
1166 let negative = dec.decode_bypass() != 0;
1167 let value = if negative { -abs } else { abs };
1168 *mvd_c = i32::try_from(value)
1169 .map_err(|_| Error::corrupt("HEVC slice syntax: motion vector difference"))?;
1170 }
1171 Ok(mvd)
1172 }
1173
1174 /// The transform tree (7.3.8.8).
1175 fn transform_tree(
1176 &mut self,
1177 dec: &mut CabacDecoder,
1178 tx: &TxInfo,
1179 node: TxNode,
1180 parent_cbf: [[bool; 2]; 2],
1181 out: &mut Vec<ResidualBlock>,
1182 ) -> Result<()> {
1183 let TxNode {
1184 x0,
1185 y0,
1186 log2,
1187 depth,
1188 ..
1189 } = node;
1190 let split = if log2 <= self.max_tb_log2
1191 && log2 > self.min_tb_log2
1192 && depth < tx.max_depth
1193 && !(tx.intra_split && depth == 0)
1194 {
1195 dec.decode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize) != 0
1196 } else {
1197 log2 > self.max_tb_log2
1198 || (tx.intra_split && depth == 0)
1199 || (tx.inter_split && depth == 0)
1200 };
1201 // ChromaArrayType 2 (4:2:2) codes a second cbf per chroma plane when the node
1202 // is not split, or is 8x8 (7.3.8.8).
1203 let second = self.sps.chroma_format_idc == 2 && (!split || log2 == 3);
1204 // 4:2:0 chroma. Below an 8x8 luma node the chroma flags are the parent's
1205 // (7.3.8.10 reads them at trafoDepth - 1); the chroma blocks ride on the
1206 // last 4x4 luma block.
1207 let idc = self.sps.chroma_format_idc;
1208 let (cb, cr) = if idc == 0 {
1209 ([false; 2], [false; 2])
1210 } else if log2 > 2 || idc == 3 {
1211 let mut planes = [[false; 2]; 2];
1212 for (c, flags) in planes.iter_mut().enumerate() {
1213 if depth == 0 || parent_cbf[c][0] {
1214 flags[0] = dec.decode_bin(ctx::CBF_CHROMA + depth as usize) != 0;
1215 if second {
1216 flags[1] = dec.decode_bin(ctx::CBF_CHROMA + depth as usize) != 0;
1217 }
1218 }
1219 }
1220 (planes[0], planes[1])
1221 } else {
1222 (parent_cbf[0], parent_cbf[1])
1223 };
1224 if split {
1225 let half = 1usize << (log2 - 1);
1226 for (i, (dx, dy)) in [(0, 0), (half, 0), (0, half), (half, half)]
1227 .into_iter()
1228 .enumerate()
1229 {
1230 let child = TxNode {
1231 x0: x0 + dx,
1232 y0: y0 + dy,
1233 x_base: x0,
1234 y_base: y0,
1235 log2: log2 - 1,
1236 depth: depth + 1,
1237 blk_idx: i,
1238 };
1239 self.transform_tree(dec, tx, child, [cb, cr], out)?;
1240 }
1241 return Ok(());
1242 }
1243 let luma = if tx.intra || depth != 0 || cb.iter().chain(cr.iter()).any(|&f| f) {
1244 dec.decode_bin(ctx::CBF_LUMA + usize::from(depth == 0)) != 0
1245 } else {
1246 true
1247 };
1248 self.transform_unit(dec, tx, node, Cbf { luma, cb, cr }, out)
1249 }
1250
1251 /// The transform unit (7.3.8.10): the QP delta, then each coded block's
1252 /// residual. With pixel decode on, an intra block is predicted and
1253 /// reconstructed here, in the order luma, Cb, Cr that its neighbours need.
1254 fn transform_unit(
1255 &mut self,
1256 dec: &mut CabacDecoder,
1257 tx: &TxInfo,
1258 node: TxNode,
1259 cbf: Cbf,
1260 out: &mut Vec<ResidualBlock>,
1261 ) -> Result<()> {
1262 let TxNode {
1263 x0,
1264 y0,
1265 x_base,
1266 y_base,
1267 log2,
1268 blk_idx,
1269 ..
1270 } = node;
1271 let n = 1usize << log2;
1272 self.pic.mark_edges(x0, y0, n, n, EDGE_TU);
1273 if (cbf.luma || cbf.cb.iter().chain(cbf.cr.iter()).any(|&f| f))
1274 && self.pps.cu_qp_delta_enabled
1275 && !self.qp_delta_coded
1276 {
1277 self.cu_qp_delta(dec)?;
1278 }
1279 let chroma_coded = cbf.cb.iter().chain(cbf.cr.iter()).any(|&f| f);
1280 if self.cu_chroma_qp_offset_enabled
1281 && chroma_coded
1282 && !self.cu_bypass
1283 && !self.chroma_qg_coded
1284 {
1285 self.cu_chroma_qp_offset(dec);
1286 }
1287 let recon = tx.intra && self.pic.has_pixels();
1288 let luma_mode = tx
1289 .intra
1290 .then(|| self.pic.info[self.pic.unit(x0, y0)].intra_mode);
1291 // disableIntraBoundaryFilter (8.4.4.2.6): implicit RDPCM on a transquant-bypass unit.
1292 let no_boundary = self.sps.range.implicit_rdpcm_enabled && self.cu_bypass;
1293 if let (true, Some(mode)) = (recon, luma_mode) {
1294 self.pic
1295 .predict_intra_ext(0, x0, y0, log2, mode, no_boundary);
1296 }
1297 let cross = self.pps.range.cross_component_prediction_enabled;
1298 let mut luma_residual: Option<Vec<i32>> = None;
1299 if cbf.luma {
1300 self.pic.update_info(x0, y0, n, n, |b| b.nz_luma = true);
1301 let block = self.residual_block(dec, 0, x0, y0, log2, luma_mode);
1302 if recon {
1303 self.pic.add_residual(0, x0, y0, n, &block.samples);
1304 }
1305 if cross {
1306 luma_residual = Some(block.samples.clone());
1307 }
1308 out.push(block);
1309 }
1310 // 4:2:0 and 4:2:2 chroma: a luma TU of 8x8 or more carries its own chroma blocks;
1311 // a 4x4 luma TU carries the chroma of its 8x8 parent with the fourth block. 4:4:4
1312 // chroma blocks are the size of the luma block, 4x4 included.
1313 let idc = self.sps.chroma_format_idc;
1314 let (sx, sy) = chroma_shifts(idc);
1315 let chroma = if idc == 0 {
1316 None
1317 } else if idc == 3 {
1318 Some(((x0, y0), log2))
1319 } else if log2 > 2 {
1320 Some(((x0 >> sx, y0 >> sy), log2 - 1))
1321 } else if blk_idx == 3 {
1322 Some(((x_base >> sx, y_base >> sy), 2))
1323 } else {
1324 None
1325 };
1326 if let Some(((cx, cy), clog2)) = chroma {
1327 let part = if tx.intra_split && idc == 3 {
1328 let half = 1usize << (tx.cu_log2 - 1);
1329 usize::from(y0 >= tx.cu_y + half) * 2 + usize::from(x0 >= tx.cu_x + half)
1330 } else {
1331 0
1332 };
1333 let mode = tx.intra.then_some(tx.chroma_modes[part]);
1334 let dm = !tx.intra || tx.chroma_dm[part];
1335 // 4:2:2 splits the chroma block into two square blocks, the upper then the
1336 // lower, each with its own cbf and its own intra prediction (8.4.4.1).
1337 let parts = if idc == 2 { 2 } else { 1 };
1338 for c in 1..=2usize {
1339 let flags = if c == 1 { cbf.cb } else { cbf.cr };
1340 let mut res_scale = 0i32;
1341 if cross && cbf.luma && dm {
1342 res_scale = self.cross_comp_pred(dec, c - 1);
1343 }
1344 for (k, &coded) in flags.iter().enumerate().take(parts) {
1345 let by = cy + (k << clog2);
1346 if let (true, Some(m)) = (recon, mode) {
1347 self.pic.predict_intra_ext(c, cx, by, clog2, m, no_boundary);
1348 }
1349 let mut block = if coded {
1350 Some(self.residual_block(dec, c, cx, by, clog2, mode))
1351 } else if res_scale != 0 {
1352 let size = 1usize << clog2;
1353 Some(ResidualBlock {
1354 component: c,
1355 x: cx,
1356 y: by,
1357 size,
1358 samples: vec![0; size * size],
1359 })
1360 } else {
1361 None
1362 };
1363 if let Some(block) = block.as_mut() {
1364 if let (true, Some(luma)) = (res_scale != 0, luma_residual.as_ref()) {
1365 rext::cross_component(
1366 &mut block.samples,
1367 luma,
1368 res_scale,
1369 self.pic.bit_depth_y,
1370 self.pic.bit_depth_c,
1371 );
1372 }
1373 if recon {
1374 self.pic.add_residual(c, cx, by, 1 << clog2, &block.samples);
1375 }
1376 }
1377 if let Some(block) = block {
1378 out.push(block);
1379 }
1380 }
1381 }
1382 }
1383 Ok(())
1384 }
1385
1386 /// `cross_comp_pred(x0, y0, c)` (7.3.8.12): `ResScaleVal` of chroma component `c`
1387 /// (0 Cb, 1 Cr), 0 when `log2_res_scale_abs_plus1` is 0.
1388 fn cross_comp_pred(&mut self, dec: &mut CabacDecoder, c: usize) -> i32 {
1389 // TR, cMax 4, context 4 * c + binIdx.
1390 let mut abs_plus1 = 0usize;
1391 while abs_plus1 < 4 && dec.decode_bin(ctx::LOG2_RES_SCALE_ABS + 4 * c + abs_plus1) != 0 {
1392 abs_plus1 += 1;
1393 }
1394 if abs_plus1 == 0 {
1395 return 0;
1396 }
1397 let negative = dec.decode_bin(ctx::RES_SCALE_SIGN + c) != 0;
1398 let magnitude = 1i32 << (abs_plus1 - 1);
1399 if negative { -magnitude } else { magnitude }
1400 }
1401
1402 /// `cu_chroma_qp_offset_flag` and `cu_chroma_qp_offset_idx` (7.3.8.10, 7.4.9.14):
1403 /// sets `CuQpOffsetCb` and `CuQpOffsetCr` from the PPS lists. The index is a truncated
1404 /// unary code with one context (Table 9-41).
1405 fn cu_chroma_qp_offset(&mut self, dec: &mut CabacDecoder) {
1406 let flag = dec.decode_bin(ctx::CU_CHROMA_QP_OFFSET_FLAG) != 0;
1407 let len = self.pps.range.cb_qp_offset_list.len();
1408 let mut idx = 0usize;
1409 if flag {
1410 while idx + 1 < len && dec.decode_bin(ctx::CU_CHROMA_QP_OFFSET_IDX) != 0 {
1411 idx += 1;
1412 }
1413 self.cu_qp_offset = [
1414 self.pps.range.cb_qp_offset_list[idx],
1415 self.pps.range.cr_qp_offset_list[idx],
1416 ];
1417 } else {
1418 self.cu_qp_offset = [0, 0];
1419 }
1420 self.chroma_qg_coded = true;
1421 }
1422
1423 /// `cu_qp_delta_abs` and its sign (9.3.3.10: TU prefix up to 5, EG0 suffix).
1424 fn cu_qp_delta(&mut self, dec: &mut CabacDecoder) -> Result<()> {
1425 let mut prefix = 0u32;
1426 while prefix < 5 {
1427 let inc = if prefix == 0 { 0 } else { 1 };
1428 if dec.decode_bin(ctx::CU_QP_DELTA_ABS + inc) == 0 {
1429 break;
1430 }
1431 prefix += 1;
1432 }
1433 let mut abs = i64::from(prefix);
1434 if prefix == 5 {
1435 abs += i64::from(decode_exp_golomb(dec, 0)?);
1436 }
1437 let value = if abs > 0 && dec.decode_bypass() != 0 {
1438 -abs
1439 } else {
1440 abs
1441 };
1442 self.qp_delta = i32::try_from(value)
1443 .map_err(|_| Error::corrupt("HEVC slice syntax: cu_qp_delta_abs"))?;
1444 self.qp_delta_coded = true;
1445 Ok(())
1446 }
1447
1448 /// One transform block: its coefficients through the residual decoder, then
1449 /// the residual samples. A transquant-bypass coding unit's residual is its
1450 /// levels (8.6.2); otherwise dequantisation (8.6.3) and the inverse
1451 /// transform (8.6.4) at the picture's bit depth. The range extension adds the
1452 /// rotation of 4x4 transform-skipped or bypassed blocks and RDPCM (8.6.2).
1453 #[allow(clippy::too_many_arguments)] // a block's position, size and scan source
1454 fn residual_block(
1455 &mut self,
1456 dec: &mut CabacDecoder,
1457 c_idx: usize,
1458 x: usize,
1459 y: usize,
1460 log2: u32,
1461 intra_mode: Option<u8>,
1462 ) -> ResidualBlock {
1463 let n = 1usize << log2;
1464 let bypass = self.cu_bypass;
1465 let scan = intra_mode.map_or(0, |m| {
1466 intra::scan_index_fmt(m, log2, c_idx == 0, self.sps.chroma_format_idc == 3)
1467 });
1468 let range = &self.sps.range;
1469 let cfg = ResidualCfg {
1470 log2_size: log2,
1471 c_idx,
1472 scan_idx: scan,
1473 sign_hiding: self.pps.sign_data_hiding_enabled,
1474 bypass,
1475 ts_enabled: self.pps.transform_skip_enabled,
1476 log2_max_ts: 2 + self.pps.range.log2_max_transform_skip_block_size_minus2,
1477 ts_context: range.transform_skip_context_enabled,
1478 persistent_rice: range.persistent_rice_adaptation_enabled,
1479 implicit_rdpcm: range.implicit_rdpcm_enabled,
1480 explicit_rdpcm: range.explicit_rdpcm_enabled,
1481 intra_mode,
1482 };
1483 let mut levels = vec![0i32; n * n];
1484 let flags = decode_residual_ext(dec, &mut levels, &cfg);
1485 let transform_skip = flags.transform_skip;
1486 let rotate = range.transform_skip_rotation_enabled
1487 && n == 4
1488 && intra_mode.is_some()
1489 && (transform_skip || bypass);
1490 let samples = if bypass {
1491 if rotate {
1492 rext::rotate_180(&mut levels, n);
1493 }
1494 if let Some(dir) = flags.rdpcm {
1495 rext::rdpcm_accumulate(&mut levels, n, dir);
1496 }
1497 levels
1498 } else {
1499 let bd = self.pic.bit_depth(c_idx);
1500 let qp_y = self.cu_qp();
1501 let qp = if c_idx == 0 {
1502 qp_y + self.qp_bd_y
1503 } else {
1504 let offset = if c_idx == 1 {
1505 self.pps.cb_qp_offset + self.header.cb_qp_offset + self.cu_qp_offset[0]
1506 } else {
1507 self.pps.cr_qp_offset + self.header.cr_qp_offset + self.cu_qp_offset[1]
1508 };
1509 chroma_qp_for(
1510 qp_y,
1511 offset,
1512 self.pic.bit_depth_c,
1513 self.sps.chroma_format_idc,
1514 ) + self.qp_bd_c
1515 };
1516 // Scaling matrix (8.6.4.2): flat 16 when the lists are off, or for a
1517 // transform-skipped block larger than 4x4; otherwise the factor of the
1518 // block's size and matrixId (Table 7-4: 0..2 intra, 3..5 inter).
1519 let matrix = if transform_skip && n > 4 {
1520 None
1521 } else {
1522 self.scaling.as_ref().map(|f| {
1523 let matrix_id = c_idx + if intra_mode.is_some() { 0 } else { 3 };
1524 f.for_block(log2, matrix_id)
1525 })
1526 };
1527 let mut scaled = vec![0i32; n * n];
1528 dequantize_weighted(&levels, &mut scaled, n, qp, bd, matrix);
1529 let mut samples = vec![0i32; n * n];
1530 if transform_skip {
1531 if rotate {
1532 rext::rotate_180(&mut scaled, n);
1533 }
1534 inverse_transform_skip_bd(&scaled, &mut samples, n, bd);
1535 if let Some(dir) = flags.rdpcm {
1536 rext::rdpcm_accumulate(&mut samples, n, dir);
1537 }
1538 } else {
1539 let dst = intra_mode.is_some() && uses_dst(n, c_idx == 0);
1540 inverse_transform_bd(&scaled, &mut samples, n, dst, bd);
1541 }
1542 samples
1543 };
1544 ResidualBlock {
1545 component: c_idx,
1546 x,
1547 y,
1548 size: n,
1549 samples,
1550 }
1551 }
1552
1553 /// `sao(rx, ry)` (7.3.8.3): the CTB's SAO parameters, kept with the CTB. A
1554 /// merge copies the left or upper CTB's parameters (all components). The
1555 /// merge flags are read only when the neighbour is in the slice and the tile.
1556 fn sao(&mut self, dec: &mut CabacDecoder, rs: usize, rx: usize, ry: usize) -> Result<()> {
1557 self.stats.sao_ctus += 1;
1558 let cols = self.pic.ctb_cols;
1559 let slice_addr = self.pic.carry.slice_addr;
1560 let tile_of = &self.pic.tiles.tile_of_rs;
1561 let same_tile = |a: usize, b: usize| tile_of.get(a) == tile_of.get(b);
1562 let left_ok = rx > 0 && rs > slice_addr && same_tile(rs, rs.wrapping_sub(1));
1563 let up_ok =
1564 ry > 0 && rs >= cols && rs - cols >= slice_addr && same_tile(rs, rs.wrapping_sub(cols));
1565 let merge_left = left_ok && dec.decode_bin(ctx::SAO_MERGE) != 0;
1566 let merge_up = !merge_left && up_ok && dec.decode_bin(ctx::SAO_MERGE) != 0;
1567 if merge_left {
1568 self.pic.ctb[rs].sao = self.pic.ctb[rs - 1].sao;
1569 return Ok(());
1570 }
1571 if merge_up {
1572 self.pic.ctb[rs].sao = self.pic.ctb[rs - cols].sao;
1573 return Ok(());
1574 }
1575 let mut params = SaoParams::default();
1576 let mut chroma_type = 0u8;
1577 for c_idx in 0..3usize {
1578 let enabled = if c_idx == 0 {
1579 self.header.sao_luma
1580 } else {
1581 self.header.sao_chroma
1582 };
1583 if !enabled {
1584 continue;
1585 }
1586 let type_idx = if c_idx == 2 {
1587 chroma_type
1588 } else {
1589 // TR, cMax 2: "0" is 0, "10" is 1 (band), "11" is 2 (edge).
1590 let t = if dec.decode_bin(ctx::SAO_TYPE_IDX) == 0 {
1591 0
1592 } else {
1593 1 + dec.decode_bypass() as u8
1594 };
1595 if c_idx == 1 {
1596 chroma_type = t;
1597 }
1598 t
1599 };
1600 params.type_idx[c_idx] = type_idx;
1601 if type_idx == 0 {
1602 continue;
1603 }
1604 let bd = self.pic.bit_depth(c_idx);
1605 // sao_offset_abs: TR with cMax (1 << (Min(bitDepth, 10) - 5)) - 1, all bypass.
1606 let cmax = (1u32 << (bd.min(10) - 5)) - 1;
1607 let mut abs = [0i32; 4];
1608 for o in abs.iter_mut() {
1609 let mut v = 0;
1610 while v < cmax && dec.decode_bypass() != 0 {
1611 v += 1;
1612 }
1613 *o = v as i32;
1614 }
1615 // SaoOffsetVal is scaled by 1 << log2OffsetScale (7-72).
1616 let shift = if c_idx == 0 {
1617 self.pps.range.log2_sao_offset_scale_luma
1618 } else {
1619 self.pps.range.log2_sao_offset_scale_chroma
1620 };
1621 if type_idx == 1 {
1622 let mut vals = [0i32; 4];
1623 for (val, &a) in vals.iter_mut().zip(abs.iter()) {
1624 *val = if a != 0 && dec.decode_bypass() != 0 {
1625 -a
1626 } else {
1627 a
1628 };
1629 }
1630 params.band_position[c_idx] = dec.decode_bypass_bits(5) as u8;
1631 params.offset[c_idx] = vals.map(|v| (v << shift) as i16);
1632 } else {
1633 if c_idx != 2 {
1634 params.eo_class[c_idx] = dec.decode_bypass_bits(2) as u8;
1635 } else {
1636 params.eo_class[2] = params.eo_class[1];
1637 }
1638 params.offset[c_idx] =
1639 [abs[0], abs[1], -abs[2], -abs[3]].map(|v| (v << shift) as i16);
1640 }
1641 }
1642 self.pic.ctb[rs].sao = params;
1643 Ok(())
1644 }
1645
1646 /// `pcm_sample()` (7.3.8.7): the raw samples after `pcm_flag`, written
1647 /// straight into the picture, then the arithmetic decoder restarts after them
1648 /// (9.3.2.5). The samples are shifted up to the picture's bit depth.
1649 fn pcm_cu(&mut self, dec: &mut CabacDecoder, x0: usize, y0: usize, log2: u32) -> Result<()> {
1650 let Some((bd_y_m1, bd_c_m1, _, _, _)) = self.sps.pcm else {
1651 return Err(Error::corrupt(
1652 "HEVC slice syntax: pcm_flag without PCM parameters",
1653 ));
1654 };
1655 let pcm_bd = [bd_y_m1 + 1, bd_c_m1 + 1, bd_c_m1 + 1];
1656 let n = 1usize << log2;
1657 let data = dec.data();
1658 let mut pos = dec.byte_position_aligned() * 8;
1659 let (sx, sy) = chroma_shifts(self.sps.chroma_format_idc);
1660 let mut blocks: Vec<(usize, Vec<u16>)> = Vec::with_capacity(3);
1661 let planes = if self.sps.chroma_format_idc == 0 {
1662 1
1663 } else {
1664 3
1665 };
1666 for (c, &pcm_depth) in pcm_bd.iter().enumerate().take(planes) {
1667 let (sw, sh) = if c == 0 { (n, n) } else { (n >> sx, n >> sy) };
1668 let shift = self.pic.bit_depth(c) - pcm_depth;
1669 let mut samples = Vec::with_capacity(sw * sh);
1670 for _ in 0..sw * sh {
1671 let v = read_raw_bits(data, &mut pos, pcm_bd[c])?;
1672 samples.push((v << shift) as u16);
1673 }
1674 blocks.push((c, samples));
1675 }
1676 for (c, samples) in blocks {
1677 let (sw, sh) = if c == 0 { (n, n) } else { (n >> sx, n >> sy) };
1678 let (x, y) = if c == 0 {
1679 (x0, y0)
1680 } else {
1681 (x0 >> sx, y0 >> sy)
1682 };
1683 if self.pic.has_pixels() {
1684 let origin = self.pic.plane_origin(c);
1685 let (stride, plane) = self.pic.plane_view_mut(c);
1686 for j in 0..sh {
1687 let start = (y + j - origin) * stride + x;
1688 plane[start..start + sw].copy_from_slice(&samples[j * sw..j * sw + sw]);
1689 }
1690 }
1691 }
1692 self.pic.update_info(x0, y0, n, n, |b| b.pcm = true);
1693 dec.restart_at_byte(pos.div_ceil(8));
1694 Ok(())
1695 }
1696}
1697
1698/// Read `count` bits, most significant first, at bit position `pos` of `data`.
1699fn read_raw_bits(data: &[u8], pos: &mut usize, count: u32) -> Result<u32> {
1700 let mut v = 0u32;
1701 for _ in 0..count {
1702 let byte = *data
1703 .get(*pos / 8)
1704 .ok_or_else(|| Error::corrupt("HEVC slice syntax: PCM samples run past the slice"))?;
1705 v = (v << 1) | u32::from((byte >> (7 - (*pos % 8))) & 1);
1706 *pos += 1;
1707 }
1708 Ok(v)
1709}
1710
1711/// A truncated unary value with cMax `cmax`: the first bin in `first_ctx`, the
1712/// rest bypass. Used for `merge_idx` (9.3.3.2 with Table 9-41).
1713fn truncated_unary(dec: &mut CabacDecoder, cmax: u32, first_ctx: usize) -> u32 {
1714 let mut v = 0;
1715 while v < cmax {
1716 let bin = if v == 0 {
1717 dec.decode_bin(first_ctx)
1718 } else {
1719 dec.decode_bypass()
1720 };
1721 if bin == 0 {
1722 break;
1723 }
1724 v += 1;
1725 }
1726 v
1727}
1728
1729/// `inter_pred_idc` (9.3.3.8): one bin in context CtDepth then one bin in
1730/// context 4 for bi-prediction, or one bin in context 4 for 8x4 and 4x8 units.
1731fn inter_pred_idc(dec: &mut CabacDecoder, width: usize, height: usize, depth: u32) -> InterPredIdc {
1732 if width + height != 12 && dec.decode_bin(ctx::INTER_PRED_IDC + depth as usize) != 0 {
1733 return InterPredIdc::PredBi;
1734 }
1735 if dec.decode_bin(ctx::INTER_PRED_IDC + 4) != 0 {
1736 InterPredIdc::PredL1
1737 } else {
1738 InterPredIdc::PredL0
1739 }
1740}
1741
1742/// The k-th order Exp-Golomb bypass suffix (9.3.3.3). The value is capped so a
1743/// corrupt prefix cannot run past 32 bits.
1744fn decode_exp_golomb(dec: &mut CabacDecoder, mut k: u32) -> Result<u32> {
1745 let mut value = 0u32;
1746 while dec.decode_bypass() != 0 {
1747 if k >= 31 {
1748 return Err(Error::corrupt(
1749 "HEVC slice syntax: Exp-Golomb prefix too long",
1750 ));
1751 }
1752 value += 1 << k;
1753 k += 1;
1754 }
1755 Ok(value + dec.decode_bypass_bits(k))
1756}
1757
1758/// The luma prediction partitions of a coding unit, as `(x, y, w, h)`.
1759fn pu_rects(part: PartMode, x: usize, y: usize, n: usize) -> Vec<(usize, usize, usize, usize)> {
1760 let h = n / 2;
1761 let q = n / 4;
1762 match part {
1763 PartMode::Part2Nx2N => vec![(x, y, n, n)],
1764 PartMode::Part2NxN => vec![(x, y, n, h), (x, y + h, n, h)],
1765 PartMode::PartNx2N => vec![(x, y, h, n), (x + h, y, h, n)],
1766 PartMode::PartNxN => vec![
1767 (x, y, h, h),
1768 (x + h, y, h, h),
1769 (x, y + h, h, h),
1770 (x + h, y + h, h, h),
1771 ],
1772 PartMode::Part2NxnU => vec![(x, y, n, q), (x, y + q, n, n - q)],
1773 PartMode::Part2NxnD => vec![(x, y, n, n - q), (x, y + n - q, n, q)],
1774 PartMode::PartnLx2N => vec![(x, y, q, n), (x + q, y, n - q, n)],
1775 PartMode::PartnRx2N => vec![(x, y, n - q, n), (x + n - q, y, q, n)],
1776 }
1777}