forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

modes.rs323 lines, 11.0 KiBHistoryRawDownload
1//! Partition coding and intra-frame mode info (spec 6.3.4/6.3.5,
2//! libvpx `vp9_decodeframe.c decode_partition` + `vp9_decodemv.c
3//! read_intra_frame_mode_info`).
4
5use crate::bool::BoolDecoder;
6use crate::header::FrameContext;
7use crate::tables::*;
8
9/// One block's parsed prediction record (`MODE_INFO`).
10#[derive(Clone, Default)]
11pub(crate) struct MiInfo {
12 pub sb_type: usize,
13 pub segment: u8,
14 pub skip: bool,
15 pub tx_size: usize,
16 pub mode: u8,
17 pub uv_mode: u8,
18 /// Per-4x4 sub-block y modes, valid when `sb_type < 3` (BLOCK_8X8).
19 pub bmi: [u8; 4],
20 /// `is_inter_block(mi)`: `ref_frame[0] > INTRA_FRAME`.
21 pub is_inter: bool,
22 /// `mi->ref_frame[0]`/`[1]`: `INTRA_FRAME` (0), `LAST`/`GOLDEN`/`ALTREF`
23 /// (1..3), `NO_REF_FRAME` (-1).
24 pub ref_frame: [i8; 2],
25 /// `mi->mv[..]`: the refreshed MV (predictor + codeword diff).
26 pub mv: [(i32, i32); 2],
27 /// The raw MV codeword diff of each reference frame.
28 pub mv_diff: [(i32, i32); 2],
29 /// `mi->bmi[j].as_mv`.
30 pub bmi_mv: [[(i32, i32); 2]; 4],
31 /// `mi->seg_id_predicted`.
32 pub seg_id_predicted: bool,
33 /// `mi->interp_filter`.
34 pub interp_filter: u8,
35}
36
37/// The mode-info grid and the partition contexts of the frame.
38pub(crate) struct MiState {
39 pub mi_cols: usize,
40 pub mi_rows: usize,
41 /// `mi_row * mi_cols + mi_col`; every cell a block covers holds a
42 /// clone of its record (libvpx shares the pointer). Frame-scoped: a
43 /// tile row k > 0 reads the rows written by tile row k - 1.
44 pub grid: Vec<Option<MiInfo>>,
45 /// `above_seg_context`, one byte per 8x8 column (frame-scoped, like
46 /// libvpx's `cm->above_seg_context`, memset once per frame).
47 pub above_seg: Vec<u8>,
48 /// `left_seg_context`, one byte per 8x8 row (reset per SB row).
49 pub left_seg: [u8; 32],
50}
51
52impl MiState {
53 pub(crate) fn new(mi_cols: usize, mi_rows: usize) -> Self {
54 MiState {
55 mi_cols,
56 mi_rows,
57 grid: vec![None; mi_cols * mi_rows],
58 // `above_seg_context` is `mi_cols_aligned_to_sb` long in libvpx;
59 // `update_partition_ctx` fills `[col .. col + bw)` which can
60 // overrun `mi_cols` by up to a full superblock (a 64x64 block at
61 // the last mi col).
62 above_seg: vec![0; mi_cols.div_ceil(8) * 8],
63 left_seg: [0; 32],
64 }
65 }
66
67 /// The grid cell at an absolute (row, col), `None` when not decoded yet.
68 pub(crate) fn at(&self, row: usize, col: usize) -> Option<&MiInfo> {
69 self.grid.get(row * self.mi_cols + col).and_then(|c| c.as_ref())
70 }
71
72 /// `xd->above_mi` (`set_mi_row_col`, vp9_onyxc_int.h:430): available iff
73 /// the block is not on the FRAME's first mi row. libvpx gates on
74 /// `mi_row != 0`, not on the tile row start — for a tile-row stream the
75 /// row above tile row k > 0 was decoded by tile row k - 1 into the same
76 /// frame-scoped mi grid.
77 pub(crate) fn above_mi(&self, row: usize, col: usize) -> Option<&MiInfo> {
78 if row > 0 {
79 self.grid[(row - 1) * self.mi_cols + col].as_ref()
80 } else {
81 None
82 }
83 }
84
85 pub(crate) fn left_mi(&self, row: usize, col: usize, tile_col_start: usize) -> Option<&MiInfo> {
86 if col > tile_col_start {
87 self.grid[row * self.mi_cols + col - 1].as_ref()
88 } else {
89 None
90 }
91 }
92
93 /// `dec_partition_plane_context`.
94 pub(crate) fn partition_ctx(&self, row: usize, col: usize, bsl: u32) -> usize {
95 let above = (self.above_seg[col] >> bsl) & 1;
96 let left = (self.left_seg[row & 31] >> bsl) & 1;
97 (left * 2 + above) as usize + (bsl as usize) * 4
98 }
99
100 /// `dec_update_partition_context`; `partition_context_lookup[subsize]`.
101 pub(crate) fn update_partition_ctx(
102 &mut self,
103 row: usize,
104 col: usize,
105 subsize: usize,
106 bw: usize,
107 ) {
108 // (above, left) per BLOCK_SIZE, common_data.c:230.
109 const LOOKUP: [(u8, u8); 13] = [
110 (15, 15),
111 (15, 14),
112 (14, 15),
113 (14, 14),
114 (14, 12),
115 (12, 14),
116 (12, 12),
117 (12, 8),
118 (8, 12),
119 (8, 8),
120 (8, 0),
121 (0, 8),
122 (0, 0),
123 ];
124 let (a, l) = LOOKUP[subsize];
125 self.above_seg[col..col + bw].fill(a);
126 self.left_seg[row & 31..(row & 31) + bw].fill(l);
127 }
128}
129
130/// `read_partition` (decodeframe.c:1195).
131fn read_partition(
132 r: &mut BoolDecoder,
133 st: &MiState,
134 partition_probs: &[[u8; 3]; 16],
135 row: usize,
136 col: usize,
137 has_rows: bool,
138 has_cols: bool,
139 bsl: u32,
140) -> crate::Result<u8> {
141 let ctx = st.partition_ctx(row, col, bsl);
142 let probs = &partition_probs[ctx];
143 if has_rows && has_cols {
144 Ok(r.read_tree(&PARTITION_TREE, probs))
145 } else if !has_rows && has_cols {
146 Ok(if r.read_bool(probs[1]) {
147 3 /* SPLIT */
148 } else {
149 1 /* HORZ */
150 })
151 } else if has_rows && !has_cols {
152 Ok(if r.read_bool(probs[2]) {
153 3 /* SPLIT */
154 } else {
155 2 /* VERT */
156 })
157 } else {
158 Ok(3)
159 }
160}
161
162/// `read_intra_mode_kf` + `read_intra_frame_mode_info` (decodemv.c).
163pub(crate) fn read_intra_frame_mode_info(
164 r: &mut BoolDecoder,
165 st: &mut MiState,
166 seg: &ec_vp9_syntax::SegmentationParams,
167 partition_probs: &[[u8; 3]; 16],
168 row: usize,
169 col: usize,
170 sb_type: usize,
171 x_mis: usize,
172 y_mis: usize,
173 tile_col_start: usize,
174 tx_mode: u8,
175 fc: &FrameContext,
176) -> crate::Result<MiInfo> {
177 let above_mi = st.above_mi(row, col).cloned();
178 let left_mi = st.left_mi(row, col, tile_col_start).cloned();
179
180 // read_intra_segment_id: keyframes have no temporal prediction; a
181 // map that is not updated keeps the previous id, which for a
182 // keyframe's fresh map is 0 (setup_past_independence cleared it).
183 let segment = if seg.enabled && seg.update_map {
184 r.read_tree(&SEGMENT_TREE, &seg.tree_probs)
185 } else {
186 0
187 };
188
189 // read_skip
190 let skip_ctx = above_mi.as_ref().map_or(0, |m| u32::from(m.skip))
191 + left_mi.as_ref().map_or(0, |u| u32::from(u.skip));
192 let skip_ctx = skip_ctx as usize;
193 let seg_skip = seg.enabled
194 && seg
195 .feature_enabled
196 .get(segment as usize)
197 .is_some_and(|f| f[3]);
198 let skip = if seg_skip {
199 true
200 } else {
201 r.read_bool(fc.skip[skip_ctx])
202 };
203
204 // read_tx_size
205 let max_tx = MAX_TXSIZE_LOOKUP[sb_type] as usize;
206 let tx_size = if tx_mode == TX_MODE_SELECT && sb_type >= 3 {
207 // get_tx_size_context (vp9_pred_common.h:156): default each side to
208 // max_tx, then substitute the other side when one is missing, in
209 // this exact order — the `!has_above` fallback is load-bearing.
210 let ctx = {
211 let a = above_mi
212 .as_ref()
213 .map_or(max_tx, |m| if m.skip { max_tx } else { m.tx_size });
214 let mut l = left_mi
215 .as_ref()
216 .map_or(max_tx, |m| if m.skip { max_tx } else { m.tx_size });
217 if left_mi.is_none() {
218 l = a;
219 }
220 let mut a = a;
221 if above_mi.is_none() {
222 a = l;
223 }
224 usize::from(a + l > max_tx)
225 };
226 // get_tx_probs (vp9_pred_common.h:173): the FRAME-updated tables
227 // (`cm->fc->tx_probs`), not the const defaults.
228 let probs: &[u8] = match max_tx {
229 1 => &fc.tx_p8x8[ctx][..],
230 2 => &fc.tx_p16x16[ctx][..],
231 _ => &fc.tx_p32x32[ctx][..],
232 };
233 let mut tx = r.read_bool(probs[0]) as usize;
234 if tx != TX_4X4 && max_tx >= TX_16X16 {
235 tx += r.read_bool(probs[1]) as usize;
236 if tx != TX_8X8 && max_tx >= TX_32X32 {
237 tx += r.read_bool(probs[2]) as usize;
238 }
239 }
240 tx
241 } else {
242 max_tx.min(TX_MODE_TO_BIGGEST_TX_SIZE[tx_mode as usize])
243 };
244
245 // y mode(s), per sub-block for sub-8x8 blocks
246 let above_pair: Option<(usize, [u8; 4], u8)> =
247 above_mi.as_ref().map(|m| (m.sb_type, m.bmi, m.mode));
248 let left_pair: Option<(usize, [u8; 4], u8)> =
249 left_mi.as_ref().map(|m| (m.sb_type, m.bmi, m.mode));
250 let mut mi = MiInfo {
251 sb_type,
252 segment,
253 skip,
254 tx_size,
255 mode: DC_PRED,
256 uv_mode: DC_PRED,
257 bmi: [DC_PRED; 4],
258 is_inter: false,
259 ref_frame: [0, -1],
260 mv: [(0, 0); 2],
261 mv_diff: [(0, 0); 2],
262 bmi_mv: [[(0, 0); 2]; 4],
263 seg_id_predicted: false,
264 // read_intra_block_mode_info sets this so a later
265 // get_pred_context_switchable_interp never sees a stale filter.
266 interp_filter: 3,
267 };
268 match sb_type {
269 0 => {
270 // BLOCK_4X4
271 for i in 0..4 {
272 let a = above_block_mode(&mi.bmi, above_pair, i);
273 let l = left_block_mode(&mi.bmi, left_pair, i);
274 mi.bmi[i] = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a, l));
275 }
276 mi.mode = mi.bmi[3];
277 }
278 1 => {
279 // BLOCK_4X8; decodemv.c commits bmi[0]/bmi[2] BEFORE the
280 // second mode's probs are derived from the current bmi.
281 let a0 = above_block_mode(&mi.bmi, above_pair, 0);
282 let l0 = left_block_mode(&mi.bmi, left_pair, 0);
283 let m0 = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a0, l0));
284 mi.bmi[0] = m0;
285 mi.bmi[2] = m0;
286 let a1 = above_block_mode(&mi.bmi, above_pair, 1);
287 let l1 = left_block_mode(&mi.bmi, left_pair, 1);
288 let m1 = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a1, l1));
289 mi.bmi[1] = m1;
290 mi.bmi[3] = m1;
291 mi.mode = m1;
292 }
293 2 => {
294 // BLOCK_8X4; same commit-before-read ordering.
295 let a0 = above_block_mode(&mi.bmi, above_pair, 0);
296 let l0 = left_block_mode(&mi.bmi, left_pair, 0);
297 let m0 = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a0, l0));
298 mi.bmi[0] = m0;
299 mi.bmi[1] = m0;
300 let a2 = above_block_mode(&mi.bmi, above_pair, 2);
301 let l2 = left_block_mode(&mi.bmi, left_pair, 2);
302 let m2 = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a2, l2));
303 mi.bmi[2] = m2;
304 mi.bmi[3] = m2;
305 mi.mode = m2;
306 }
307 _ => {
308 let a = above_block_mode(&mi.bmi, above_pair, 0);
309 let l = left_block_mode(&mi.bmi, left_pair, 0);
310 mi.mode = r.read_tree(&INTRA_MODE_TREE, &kf_y_mode_probs(a, l));
311 }
312 }
313 // uv mode: `vp9_kf_uv_mode_prob` indexed by y mode, decoded with the
314 // SAME intra_mode_tree (decodemv.c:232 calls read_intra_mode).
315 mi.uv_mode = r.read_tree(&INTRA_MODE_TREE, &kf_uv_probs(mi.mode));
316 if crate::trace_enabled() {
317 eprintln!(
318 "MODE row={} col={} bsize={} skip={} tx={} y={} uv={}",
319 row, col, sb_type, mi.skip as u8, mi.tx_size, mi.mode, mi.uv_mode
320 );
321 }
322 Ok(mi)
323}