forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

pic.rs500 lines, 18.6 KiBHistoryRawDownload
1//! The per-picture decoding state: the sample planes and the maps the
2//! parser, the intra reconstruction and the in-loop filters share.
3//!
4//! One [`PicState`] lives from the first slice segment of a picture until the
5//! picture is finished. The coding-tree parser ([`super::cu_syntax`]) writes
6//! the block maps as it parses; the reconstruction ([`super::recon`]) writes
7//! the samples in decoding order; the deblocking filter and SAO
8//! ([`super::deblock`], [`super::sao`]) read the maps and rewrite the samples
9//! once the whole picture is reconstructed.
10//!
11//! All maps are per 4x4 luma unit (`w4` units per row) except the per-CTB
12//! tables. Positions are luma samples.
13
14use super::mc::PlaneMut;
15use super::tiles::TileScan;
16use crate::cabac::Contexts;
17use crate::decode::DecodedPicture;
18use ec_h265_syntax::{Pps, Sps};
19
20/// [`BlockInfo::edge_v`] / [`BlockInfo::edge_h`] bit: the left (top) edge of
21/// this unit is a transform block edge.
22pub const EDGE_TU: u8 = 1;
23/// [`BlockInfo::edge_v`] / [`BlockInfo::edge_h`] bit: the left (top) edge of
24/// this unit is a prediction block edge.
25pub const EDGE_PU: u8 = 2;
26
27/// What is known about one 4x4 luma unit once its coding unit is parsed.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29pub struct BlockInfo {
30 /// `CuPredMode` is MODE_INTRA (false for skipped and inter units, and for
31 /// units not yet decoded).
32 pub intra: bool,
33 /// `cu_skip_flag` of the coding unit.
34 pub skip: bool,
35 /// The unit belongs to a PCM coding unit (`pcm_flag` 1).
36 pub pcm: bool,
37 /// `cu_transquant_bypass_flag` of the coding unit.
38 pub bypass: bool,
39 /// `CtDepth` of the coding unit.
40 pub depth: u8,
41 /// `IntraPredModeY`; 1 (DC) for inter, PCM and not yet decoded units.
42 pub intra_mode: u8,
43 /// `QpY` of the coding unit (may be negative at high bit depths).
44 pub qp: i8,
45 /// The luma transform block covering this unit has `cbf_luma` 1.
46 pub nz_luma: bool,
47 /// Bit set of [`EDGE_TU`] and [`EDGE_PU`] for the vertical edge at the left
48 /// of this unit. Only edges on the 8x8 grid are filtered.
49 pub edge_v: u8,
50 /// Same for the horizontal edge at the top of this unit.
51 pub edge_h: u8,
52}
53
54/// Motion of one 4x4 unit, for the deblocking boundary strength (8.7.2.4).
55/// Intra and unset units have no prediction flags. Filled at the end of the picture
56/// from its [`MotionField`](super::motion_field::MotionField), so one derivation feeds both.
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
58pub struct PuMotion {
59 /// `predFlagLX` for X = 0, 1.
60 pub pred: [bool; 2],
61 /// Identity of the reference picture per list (its POC); -1 when the list is
62 /// unused. Two entries are the same picture iff their values are equal.
63 pub ref_pic: [i32; 2],
64 /// Motion vector per list, `[x, y]` in quarter luma samples.
65 pub mv: [[i32; 2]; 2],
66}
67
68/// `SaoTypeIdx`, `sao_band_position`, `SaoEoClass` and `SaoOffsetVal` of one
69/// CTB, for the three colour components (7.4.9.3).
70#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
71pub struct SaoParams {
72 /// 0 not applied, 1 band offset, 2 edge offset, per component.
73 pub type_idx: [u8; 3],
74 /// `sao_band_position`, per component.
75 pub band_position: [u8; 3],
76 /// `SaoEoClass`, per component (Cb and Cr share the class of Cb).
77 pub eo_class: [u8; 3],
78 /// `SaoOffsetVal[1..=4]` per component, sign applied, already scaled by
79 /// `1 << (bitDepth - Min(bitDepth, 10))`.
80 pub offset: [[i16; 4]; 3],
81}
82
83/// Per-CTB state.
84#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub struct CtbInfo {
86 /// Index into [`PicState::slices`] of the slice segment that contains the CTB.
87 pub slice: u16,
88 /// `SliceAddrRs` of the slice (the address of its first CTB, which a dependent
89 /// slice segment shares with the independent segment before it).
90 pub slice_addr: u32,
91 /// `TileId` of the CTB.
92 pub tile: u16,
93 /// The CTB's SAO parameters (all zero when SAO is off or not coded).
94 pub sao: SaoParams,
95}
96
97/// The slice-header values the in-loop filters read, one entry per slice
98/// segment of the picture.
99#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
100pub struct SliceFilter {
101 /// `slice_deblocking_filter_disabled_flag`.
102 pub deblock_disabled: bool,
103 /// `slice_beta_offset_div2`.
104 pub beta_offset_div2: i32,
105 /// `slice_tc_offset_div2`.
106 pub tc_offset_div2: i32,
107 /// `slice_loop_filter_across_slices_enabled_flag`.
108 pub loop_filter_across_slices: bool,
109 /// `slice_sao_luma_flag`.
110 pub sao_luma: bool,
111 /// `slice_sao_chroma_flag`.
112 pub sao_chroma: bool,
113}
114
115/// State that runs across the slice segments of one picture: the contexts
116/// that a later segment restores (9.3.1), and the QP predictor (8.6.1).
117#[derive(Default)]
118pub struct SliceCarry {
119 /// `SliceAddrRs` of the slice the current segment belongs to.
120 pub slice_addr: usize,
121 /// `TableStateIdxWpp`: the contexts after the second CTB of the last row
122 /// that stored them.
123 pub wpp: Option<Contexts>,
124 /// `TableStateIdxDs`: the contexts at the end of the last slice segment.
125 pub ds: Option<Contexts>,
126 /// `qPY_PREV` at the end of the last slice segment.
127 pub last_qp: i32,
128}
129
130/// The decoding state of one picture.
131pub struct PicState {
132 /// Luma width in samples.
133 pub width: usize,
134 /// `chroma_format_idc`: 1 (4:2:0), 2 (4:2:2) or 3 (4:4:4).
135 pub chroma_format_idc: u32,
136 /// Luma height in samples.
137 pub height: usize,
138 /// `log2_min_luma_transform_block_size`.
139 pub min_tb_log2: u32,
140 /// `CtbLog2SizeY`.
141 pub ctb_log2: u32,
142 /// CTBs per row.
143 pub ctb_cols: usize,
144 /// CTB rows.
145 pub ctb_rows: usize,
146 /// Units (4x4 luma) per row.
147 pub w4: usize,
148 /// Units per column.
149 pub h4: usize,
150 /// `BitDepthY`.
151 pub bit_depth_y: u32,
152 /// `BitDepthC`.
153 pub bit_depth_c: u32,
154 /// `constrained_intra_pred_flag`.
155 pub constrained_intra_pred: bool,
156 /// `strong_intra_smoothing_enabled_flag`.
157 pub strong_intra_smoothing: bool,
158 /// `intra_smoothing_disabled_flag`.
159 pub intra_smoothing_disabled: bool,
160 /// `pcm_loop_filter_disabled_flag` (false when PCM is off).
161 pub pcm_loop_filter_disabled: bool,
162 /// `pps_cb_qp_offset` and `pps_cr_qp_offset` (the chroma QP of the deblocking filter).
163 pub pps_cb_qp_offset: i32,
164 /// See `pps_cb_qp_offset`.
165 pub pps_cr_qp_offset: i32,
166 /// The samples. Empty planes when the decoder runs without pixel decode.
167 pub planes: DecodedPicture,
168 /// Per 4x4 unit, `w4 * h4`.
169 pub info: Vec<BlockInfo>,
170 /// Per 4x4 unit motion, `w4 * h4`; set from the picture's motion field before deblocking.
171 pub motion: Vec<PuMotion>,
172 /// Per CTB, raster order.
173 pub ctb: Vec<CtbInfo>,
174 /// Slice filter parameters; `CtbInfo::slice` indexes this.
175 pub slices: Vec<SliceFilter>,
176 /// The tile scan: CTB addressing and the tile of each CTB.
177 pub tiles: TileScan,
178 /// `loop_filter_across_tiles_enabled_flag`.
179 pub loop_filter_across_tiles: bool,
180 /// The state the slice segments share.
181 pub carry: SliceCarry,
182 /// Luma row of the first stored sample row. Zero for a whole picture; a wavefront
183 /// row band stores the row above it first (see [`super::wpp`]).
184 pub origin_y: usize,
185 /// Chroma row of the first stored chroma row.
186 pub origin_c: usize,
187 /// Luma row of the first stored 4x4 unit row (a multiple of 4).
188 pub origin_unit: usize,
189}
190
191impl PicState {
192 /// The state of a `width` x `height` picture. With `pixels` false the
193 /// sample planes are left empty and only the maps are kept.
194 #[allow(clippy::too_many_arguments)] // one value per picture-level SPS/PPS fact
195 pub fn new(
196 width: usize,
197 height: usize,
198 ctb_log2: u32,
199 min_tb_log2: u32,
200 bit_depth_y: u32,
201 bit_depth_c: u32,
202 pixels: bool,
203 ) -> PicState {
204 let ctb = 1usize << ctb_log2;
205 let ctb_cols = width.div_ceil(ctb);
206 let ctb_rows = height.div_ceil(ctb);
207 let w4 = width.div_ceil(4);
208 let h4 = height.div_ceil(4);
209 let planes = if pixels {
210 DecodedPicture::grey_planes(width, height, bit_depth_y, bit_depth_c)
211 } else {
212 DecodedPicture {
213 width,
214 height,
215 bit_depth: bit_depth_y,
216 bit_depth_c,
217 chroma_format_idc: 1,
218 y: Vec::new(),
219 cb: Vec::new(),
220 cr: Vec::new(),
221 }
222 };
223 PicState {
224 width,
225 height,
226 chroma_format_idc: 1,
227 min_tb_log2,
228 ctb_log2,
229 ctb_cols,
230 ctb_rows,
231 w4,
232 h4,
233 bit_depth_y,
234 bit_depth_c,
235 constrained_intra_pred: false,
236 strong_intra_smoothing: false,
237 intra_smoothing_disabled: false,
238 pcm_loop_filter_disabled: false,
239 pps_cb_qp_offset: 0,
240 pps_cr_qp_offset: 0,
241 planes,
242 info: vec![BlockInfo::default(); w4 * h4],
243 motion: vec![PuMotion::default(); w4 * h4],
244 ctb: vec![CtbInfo::default(); ctb_cols * ctb_rows],
245 slices: Vec::new(),
246 tiles: TileScan::single(ctb_cols, ctb_rows),
247 loop_filter_across_tiles: true,
248 carry: SliceCarry::default(),
249 origin_y: 0,
250 origin_c: 0,
251 origin_unit: 0,
252 }
253 }
254
255 /// The log2 horizontal chroma subsampling (1 for 4:2:0 and 4:2:2).
256 pub fn sub_x(&self) -> u32 {
257 crate::decode::chroma_shifts(self.chroma_format_idc).0
258 }
259
260 /// The log2 vertical chroma subsampling (1 for 4:2:0 only).
261 pub fn sub_y(&self) -> u32 {
262 crate::decode::chroma_shifts(self.chroma_format_idc).1
263 }
264
265 /// Whether the sample planes are allocated (pixel decode is on).
266 pub fn has_pixels(&self) -> bool {
267 !self.planes.y.is_empty()
268 }
269
270 /// The three writable sample planes, for motion compensation.
271 pub fn planes_mut(&mut self) -> [PlaneMut<'_>; 3] {
272 let (bd_y, bd_c) = (self.bit_depth_y, self.bit_depth_c);
273 let w = self.planes.width;
274 let cw = self.width.div_ceil(1 << self.sub_x());
275 let (oy, oc) = (self.origin_y, self.origin_c);
276 let p = &mut self.planes;
277 [
278 PlaneMut {
279 samples: &mut p.y,
280 stride: w,
281 bit_depth: bd_y,
282 origin: oy,
283 },
284 PlaneMut {
285 samples: &mut p.cb,
286 stride: cw,
287 bit_depth: bd_c,
288 origin: oc,
289 },
290 PlaneMut {
291 samples: &mut p.cr,
292 stride: cw,
293 bit_depth: bd_c,
294 origin: oc,
295 },
296 ]
297 }
298
299 /// The first stored row of component `c`, in that component's rows.
300 pub fn plane_origin(&self, c: usize) -> usize {
301 if c == 0 { self.origin_y } else { self.origin_c }
302 }
303
304 /// The index of the 4x4 unit containing luma position `(x, y)`.
305 pub fn unit(&self, x: usize, y: usize) -> usize {
306 ((y >> 2) - self.origin_unit / 4) * self.w4 + (x >> 2)
307 }
308
309 /// `MinTbAddrZs` at 4x4 granularity (6.5.2): the tile scan address of the
310 /// CTB, then the z-order of the unit inside the CTB. Comparing two positions
311 /// with this tells which one is decoded first.
312 pub fn zscan(&self, x: usize, y: usize) -> usize {
313 let rs = (y >> self.ctb_log2) * self.ctb_cols + (x >> self.ctb_log2);
314 let ts = self.tiles.rs_to_ts.get(rs).copied().unwrap_or(rs);
315 let units_per_ctb_side = 1usize << (self.ctb_log2 - 2);
316 let mask = units_per_ctb_side - 1;
317 let (ux, uy) = ((x >> 2) & mask, (y >> 2) & mask);
318 let mut z = 0usize;
319 for bit in 0..self.ctb_log2 as usize - 2 {
320 z |= ((ux >> bit) & 1) << (2 * bit);
321 z |= ((uy >> bit) & 1) << (2 * bit + 1);
322 }
323 (ts << (2 * (self.ctb_log2 as usize - 2))) | z
324 }
325
326 /// The availability of the neighbouring luma position `(xn, yn)` for the
327 /// block at `(xc, yc)` (6.4.1): inside the picture, decoded before the current
328 /// block, and in the same slice and the same tile.
329 pub fn available(&self, xc: usize, yc: usize, xn: isize, yn: isize) -> bool {
330 if xn < 0 || yn < 0 || xn as usize >= self.width || yn as usize >= self.height {
331 return false;
332 }
333 let (xn, yn) = (xn as usize, yn as usize);
334 if self.zscan(xn, yn) > self.zscan(xc, yc) {
335 return false;
336 }
337 let rs_n = (yn >> self.ctb_log2) * self.ctb_cols + (xn >> self.ctb_log2);
338 let rs_c = (yc >> self.ctb_log2) * self.ctb_cols + (xc >> self.ctb_log2);
339 if rs_n == rs_c {
340 return true;
341 }
342 match (self.ctb.get(rs_n), self.ctb.get(rs_c)) {
343 (Some(n), Some(c)) => n.slice_addr == c.slice_addr && n.tile == c.tile,
344 _ => false,
345 }
346 }
347
348 /// The raster address of the CTB containing luma position `(x, y)`.
349 pub fn ctb_rs(&self, x: usize, y: usize) -> usize {
350 (y >> self.ctb_log2) * self.ctb_cols + (x >> self.ctb_log2)
351 }
352
353 /// Set `f` on every unit under the `w` x `h` luma area at `(x, y)`.
354 pub fn update_info(
355 &mut self,
356 x: usize,
357 y: usize,
358 w: usize,
359 h: usize,
360 f: impl Fn(&mut BlockInfo),
361 ) {
362 for by in (y..(y + h).min(self.height)).step_by(4) {
363 for bx in (x..(x + w).min(self.width)).step_by(4) {
364 let idx = self.unit(bx, by);
365 f(&mut self.info[idx]);
366 }
367 }
368 }
369
370 /// Mark the left and top edges of the `w` x `h` block at `(x, y)` with
371 /// `kind` (an [`EDGE_TU`] or [`EDGE_PU`] bit).
372 pub fn mark_edges(&mut self, x: usize, y: usize, w: usize, h: usize, kind: u8) {
373 for by in (y..(y + h).min(self.height)).step_by(4) {
374 let idx = self.unit(x, by);
375 if x < self.width {
376 self.info[idx].edge_v |= kind;
377 }
378 }
379 for bx in (x..(x + w).min(self.width)).step_by(4) {
380 let idx = self.unit(bx, y);
381 if y < self.height {
382 self.info[idx].edge_h |= kind;
383 }
384 }
385 }
386
387 /// The state of a picture of `sps` and `pps`. With `pixels` on, the sample
388 /// planes are allocated, grey.
389 pub fn for_sps_pps(sps: &Sps, pps: &Pps, pixels: bool) -> PicState {
390 let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3;
391 let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size;
392 let min_tb_log2 = sps.log2_min_tb_size_minus2 + 2;
393 let mut pic = PicState::new(
394 sps.pic_width_in_luma_samples as usize,
395 sps.pic_height_in_luma_samples as usize,
396 ctb_log2,
397 min_tb_log2,
398 8 + sps.bit_depth_luma_minus8,
399 8 + sps.bit_depth_chroma_minus8,
400 pixels,
401 );
402 if sps.chroma_format_idc != 1 {
403 pic.chroma_format_idc = sps.chroma_format_idc;
404 if pixels {
405 pic.planes = DecodedPicture::grey_planes_fmt(
406 pic.width,
407 pic.height,
408 pic.bit_depth_y,
409 pic.bit_depth_c,
410 sps.chroma_format_idc,
411 );
412 }
413 }
414 pic.constrained_intra_pred = pps.constrained_intra_pred;
415 pic.strong_intra_smoothing = sps.strong_intra_smoothing;
416 pic.intra_smoothing_disabled = sps.range.intra_smoothing_disabled;
417 pic.pcm_loop_filter_disabled = sps.pcm_enabled && sps.pcm.is_some_and(|p| p.4);
418 pic.pps_cb_qp_offset = pps.cb_qp_offset;
419 pic.pps_cr_qp_offset = pps.cr_qp_offset;
420 pic.loop_filter_across_tiles = pps.loop_filter_across_tiles_enabled;
421 pic
422 }
423
424 /// A wavefront band of this picture for the CTB row that starts at luma row `y0`
425 /// and holds `own` luma rows. A row below the first one stores the row above it
426 /// first, so the band's first sample, unit and CTB rows are that row (copied in by
427 /// the wavefront driver). The maps cover only the band; the CTB table is the
428 /// whole picture's shape, and the tile scan and slice state are copied.
429 pub fn band(&self, y0: usize, own: usize, pixels: bool) -> PicState {
430 let bound = usize::from(y0 > 0);
431 let own_units = own.div_ceil(4);
432 let (sx, sy) = crate::decode::chroma_shifts(self.chroma_format_idc);
433 let cw = self.width.div_ceil(1 << sx);
434 let own_c = own.div_ceil(1 << sy);
435 let planes = DecodedPicture {
436 width: self.width,
437 height: self.height,
438 bit_depth: self.bit_depth_y,
439 bit_depth_c: self.bit_depth_c,
440 chroma_format_idc: self.chroma_format_idc,
441 y: if pixels {
442 vec![0; (bound + own) * self.width]
443 } else {
444 Vec::new()
445 },
446 cb: if pixels {
447 vec![0; (bound + own_c) * cw]
448 } else {
449 Vec::new()
450 },
451 cr: if pixels {
452 vec![0; (bound + own_c) * cw]
453 } else {
454 Vec::new()
455 },
456 };
457 PicState {
458 width: self.width,
459 height: self.height,
460 chroma_format_idc: self.chroma_format_idc,
461 min_tb_log2: self.min_tb_log2,
462 ctb_log2: self.ctb_log2,
463 ctb_cols: self.ctb_cols,
464 ctb_rows: self.ctb_rows,
465 w4: self.w4,
466 h4: self.h4,
467 bit_depth_y: self.bit_depth_y,
468 bit_depth_c: self.bit_depth_c,
469 constrained_intra_pred: self.constrained_intra_pred,
470 strong_intra_smoothing: self.strong_intra_smoothing,
471 intra_smoothing_disabled: self.intra_smoothing_disabled,
472 pcm_loop_filter_disabled: self.pcm_loop_filter_disabled,
473 pps_cb_qp_offset: self.pps_cb_qp_offset,
474 pps_cr_qp_offset: self.pps_cr_qp_offset,
475 planes,
476 info: vec![BlockInfo::default(); (bound + own_units) * self.w4],
477 motion: Vec::new(),
478 ctb: vec![CtbInfo::default(); self.ctb.len()],
479 slices: Vec::new(),
480 tiles: self.tiles.clone(),
481 loop_filter_across_tiles: self.loop_filter_across_tiles,
482 carry: SliceCarry {
483 slice_addr: self.carry.slice_addr,
484 ..SliceCarry::default()
485 },
486 origin_y: y0 - bound,
487 origin_c: (y0 >> sy) - bound,
488 origin_unit: y0 - 4 * bound,
489 }
490 }
491
492 /// The bit depth of component `c` (0 luma, 1 and 2 chroma).
493 pub fn bit_depth(&self, c: usize) -> u32 {
494 if c == 0 {
495 self.bit_depth_y
496 } else {
497 self.bit_depth_c
498 }
499 }
500}