forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

header.rs484 lines, 17.3 KiBHistoryRawDownload
1//! The frame context (bool-coded probabilities) and the compressed
2//! header (spec 6.2 `compressed_header` / 8.2): thin wrap over
3//! [`ec_vp9_syntax::Vp9Parser`] for the uncompressed part, plus the
4//! differential probability-update machinery (libvpx `vp9_dsubexp.c`).
5
6use crate::bool::BoolDecoder;
7use crate::inter::{COMPOUND_REFERENCE, REFERENCE_MODE_SELECT, SINGLE_REFERENCE};
8use crate::tables::*;
9use ec_vp9_syntax::FrameHeader;
10
11/// All bool-coded probabilities a keyframe reads.
12#[derive(Clone)]
13pub(crate) struct FrameContext {
14 pub coef: [[[[[[u8; 3]; 6]; 6]; 2]; 2]; 4],
15 pub partition: [[u8; 3]; 16],
16 pub tx_p8x8: [[u8; 1]; 2],
17 pub tx_p16x16: [[u8; 2]; 2],
18 pub tx_p32x32: [[u8; 3]; 2],
19 pub skip: [u8; 3],
20 /// Inter-frame tables (all defaults until a compressed header updates
21 /// them): `inter_mode_probs`, `switchable_interp_prob`, `intra_inter_prob`,
22 /// `comp_inter_prob`, `single_ref_prob`, `comp_ref_prob`, `y_mode_prob`,
23 /// `uv_mode_prob`, and the MV probs.
24 pub inter_mode: [[u8; 3]; 7],
25 pub switchable_interp: [[u8; 2]; 4],
26 pub intra_inter: [u8; 4],
27 pub comp_inter: [u8; 5],
28 pub single_ref: [[u8; 2]; 5],
29 pub comp_ref: [u8; 5],
30 pub y_mode: [[u8; 9]; 4],
31 pub uv_mode: [[u8; 9]; 10],
32 pub nmv_joints: [u8; 3],
33 pub nmv_sign: [u8; 2],
34 pub nmv_classes: [[u8; 10]; 2],
35 pub nmv_class0: [[u8; 1]; 2],
36 pub nmv_bits: [[u8; 10]; 2],
37 pub nmv_class0_fp: [[[u8; 3]; 2]; 2],
38 pub nmv_fp: [[u8; 3]; 2],
39 pub nmv_class0_hp: [u8; 2],
40 pub nmv_hp: [u8; 2],
41}
42
43/// Rows from a flat C initializer.
44fn rows<const R: usize, const C: usize>(flat: &[u8]) -> [[u8; C]; R] {
45 let mut out = [[0u8; C]; R];
46 for (i, row) in out.iter_mut().enumerate() {
47 row.copy_from_slice(&flat[i * C..i * C + C]);
48 }
49 out
50}
51
52impl FrameContext {
53 /// Spec 7.2 `setup_past_independence`: back to the defaults. Key
54 /// frames code partitions with `vp9_kf_partition_probs`, every other
55 /// table is type-independent.
56 pub(crate) fn new(key_frame: bool) -> Self {
57 let partition_src: &[u8] = if key_frame {
58 &KF_PARTITION_PROBS
59 } else {
60 &DEFAULT_PARTITION_PROBS
61 };
62 FrameContext {
63 coef: [
64 DEFAULT_COEF_PROBS_4X4,
65 DEFAULT_COEF_PROBS_8X8,
66 DEFAULT_COEF_PROBS_16X16,
67 DEFAULT_COEF_PROBS_32X32,
68 ],
69 partition: {
70 let mut p = [[0u8; 3]; 16];
71 for (i, row) in p.iter_mut().enumerate() {
72 row.copy_from_slice(&partition_src[i * 3..i * 3 + 3]);
73 }
74 p
75 },
76 tx_p8x8: [[TX_P8X8_PROB[0]], [TX_P8X8_PROB[1]]],
77 tx_p16x16: [
78 [TX_P16X16_PROB[0], TX_P16X16_PROB[1]],
79 [TX_P16X16_PROB[2], TX_P16X16_PROB[3]],
80 ],
81 tx_p32x32: [
82 [TX_P32X32_PROB[0], TX_P32X32_PROB[1], TX_P32X32_PROB[2]],
83 [TX_P32X32_PROB[3], TX_P32X32_PROB[4], TX_P32X32_PROB[5]],
84 ],
85 skip: DEFAULT_SKIP_PROBS,
86 // `vp9_init_frame_context` / `vp9_init_mv_probs` defaults. Key
87 // frames do not use these; inter frames start from them unless a
88 // stored context (or a compressed header) says otherwise.
89 inter_mode: rows(&DEFAULT_INTER_MODE_PROBS),
90 switchable_interp: rows(&DEFAULT_SWITCHABLE_INTERP_PROBS),
91 intra_inter: DEFAULT_INTRA_INTER_PROBS,
92 comp_inter: DEFAULT_COMP_INTER_PROBS,
93 single_ref: rows(&DEFAULT_SINGLE_REF_PROBS),
94 comp_ref: DEFAULT_COMP_REF_PROBS,
95 y_mode: rows(&DEFAULT_Y_MODE_PROBS),
96 uv_mode: rows(&DEFAULT_IF_UV_PROBS),
97 nmv_joints: DEFAULT_NMVC_JOINTS,
98 nmv_sign: DEFAULT_NMVC_SIGN,
99 nmv_classes: rows(&DEFAULT_NMVC_CLASSES),
100 nmv_class0: [[DEFAULT_NMVC_CLASS0[0]], [DEFAULT_NMVC_CLASS0[1]]],
101 nmv_bits: rows(&DEFAULT_NMVC_BITS),
102 nmv_class0_fp: [
103 [
104 [DEFAULT_NMVC_CLASS0_FP[0], DEFAULT_NMVC_CLASS0_FP[1], DEFAULT_NMVC_CLASS0_FP[2]],
105 [DEFAULT_NMVC_CLASS0_FP[3], DEFAULT_NMVC_CLASS0_FP[4], DEFAULT_NMVC_CLASS0_FP[5]],
106 ],
107 [
108 [DEFAULT_NMVC_CLASS0_FP[6], DEFAULT_NMVC_CLASS0_FP[7], DEFAULT_NMVC_CLASS0_FP[8]],
109 [DEFAULT_NMVC_CLASS0_FP[9], DEFAULT_NMVC_CLASS0_FP[10], DEFAULT_NMVC_CLASS0_FP[11]],
110 ],
111 ],
112 nmv_fp: rows(&DEFAULT_NMVC_FP),
113 nmv_class0_hp: DEFAULT_NMVC_CLASS0_HP,
114 nmv_hp: DEFAULT_NMVC_HP,
115 }
116 }
117}
118
119impl FrameContext {
120 /// `vp9_kf_partition_probs` are NOT a `FRAME_CONTEXT` field in libvpx
121 /// (`get_partition_probs` picks the const table for intra-only frames);
122 /// a context that a keyframe stored must therefore go back to the inter
123 /// defaults before the next frame reads it.
124 pub(crate) fn reset_inter_partition(&mut self) {
125 self.partition = rows(&DEFAULT_PARTITION_PROBS);
126 }
127
128 /// `set_partition_probs` (`vp9/onyxc_int.h:367`): a key frame OR an
129 /// intra-only frame reads partitions from the const
130 /// `vp9_kf_partition_probs`, never from the stored `FRAME_CONTEXT`. An
131 /// intra-only frame's context otherwise comes from storage, so its own
132 /// `partition` field must be left alone (this only swaps the field on the
133 /// active read copy).
134 pub(crate) fn use_key_partition(&mut self) {
135 for (i, row) in self.partition.iter_mut().enumerate() {
136 row.copy_from_slice(&KF_PARTITION_PROBS[i * 3..i * 3 + 3]);
137 }
138 }
139}
140
141/// `inv_recenter_nonneg` (vp9_dsubexp.c).
142fn inv_recenter_nonneg(v: i32, m: i32) -> i32 {
143 if v > 2 * m {
144 return v;
145 }
146 if v & 1 != 0 {
147 m - ((v + 1) >> 1)
148 } else {
149 m + (v >> 1)
150 }
151}
152
153/// `decode_uniform` (vp9_dsubexp.c): l = 8.
154fn decode_uniform(r: &mut BoolDecoder) -> i32 {
155 let l = 8;
156 let m = (1 << l) - 191;
157 let v = r.read_literal(7) as i32;
158 if v < m {
159 v
160 } else {
161 (v << 1) - m + r.read_bool(128) as i32
162 }
163}
164
165/// `decode_term_subexp` (vp9_dsubexp.c).
166fn decode_term_subexp(r: &mut BoolDecoder) -> i32 {
167 if !r.read_bool(128) {
168 return r.read_literal(4) as i32;
169 }
170 if !r.read_bool(128) {
171 return r.read_literal(4) as i32 + 16;
172 }
173 if !r.read_bool(128) {
174 return r.read_literal(5) as i32 + 32;
175 }
176 decode_uniform(r) + 64
177}
178
179/// `inv_remap_prob` with libvpx's 255-entry map table.
180fn inv_remap_prob(v: i32, m: u8) -> u8 {
181 const MAP: [u8; 255] = [
182 7, 20, 33, 46, 59, 72, 85, 98, 111, 124, 137, 150, 163, 176, 189, 202, 215, 228, 241, 254,
183 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27,
184 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 47, 48, 49, 50, 51, 52,
185 53, 54, 55, 56, 57, 58, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 73, 74, 75, 76, 77,
186 78, 79, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 100, 101,
187 102, 103, 104, 105, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119, 120,
188 121, 122, 123, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 138, 139, 140,
189 141, 142, 143, 144, 145, 146, 147, 148, 149, 151, 152, 153, 154, 155, 156, 157, 158, 159,
190 160, 161, 162, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179,
191 180, 181, 182, 183, 184, 185, 186, 187, 188, 190, 191, 192, 193, 194, 195, 196, 197, 198,
192 199, 200, 201, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 216, 217, 218,
193 219, 220, 221, 222, 223, 224, 225, 226, 227, 229, 230, 231, 232, 233, 234, 235, 236, 237,
194 238, 239, 240, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 253,
195 ];
196 let v = MAP[v as usize] as i32;
197 let m = m as i32 - 1;
198 if (m << 1) <= 255 {
199 (1 + inv_recenter_nonneg(v, m)) as u8
200 } else {
201 (255 - inv_recenter_nonneg(v, 255 - 1 - m)) as u8
202 }
203}
204
205/// `vp9_diff_update_prob`.
206fn diff_update_prob(r: &mut BoolDecoder, p: &mut u8) {
207 if r.read_bool(DIFF_UPDATE_PROB) {
208 let delp = decode_term_subexp(r);
209 *p = inv_remap_prob(delp, *p);
210 }
211}
212
213/// `MV_UPDATE_PROB` (`vp9_entropymv.h`): the flag prob of `update_mv_probs`.
214const MV_UPDATE_PROB: u8 = 252;
215
216/// `update_mv_probs` (vp9_decodeframe.c:136). NOT a `vp9_diff_update_prob`:
217/// a flag at `MV_UPDATE_PROB`, then seven LITERAL bits, and the new prob is
218/// `(literal << 1) | 1` — no `decode_term_subexp`, no `inv_remap_prob`.
219fn update_mv_probs(r: &mut BoolDecoder, p: &mut [u8]) {
220 for v in p.iter_mut() {
221 if r.read_bool(MV_UPDATE_PROB) {
222 *v = ((r.read_literal(7) << 1) | 1) as u8;
223 }
224 }
225}
226
227/// `read_coef_probs_common` (decodeframe.c:1314): one flag per tx size
228/// covers all plane/ref/band/context updates of the first three (base)
229/// probs per slot.
230fn read_coef_probs(r: &mut BoolDecoder, ctx: &mut FrameContext, tx_mode: u8) {
231 let max_tx = TX_MODE_TO_BIGGEST_TX_SIZE[tx_mode as usize];
232 for tx in 0..=max_tx {
233 if r.read_bool(128) {
234 for plane in 0..2 {
235 for _ref in 0..2 {
236 for band in 0..6 {
237 let n_ctx = if band == 0 { 3 } else { 6 };
238 for ci in 0..n_ctx {
239 for m in 0..3 {
240 diff_update_prob(r, &mut ctx.coef[tx][plane][_ref][band][ci][m]);
241 }
242 }
243 }
244 }
245 }
246 }
247 }
248}
249
250/// `read_tx_mode` (decodeframe.c:58).
251fn read_tx_mode(r: &mut BoolDecoder) -> u8 {
252 let mut m = r.read_literal(2) as u8;
253 if m == ALLOW_32X32 {
254 m += r.read_bool(128) as u8;
255 }
256 m
257}
258
259/// What `read_compressed_header` decides for the frame.
260#[derive(Debug, Clone, Copy, PartialEq, Eq)]
261pub(crate) struct CompressedHeader {
262 pub tx_mode: u8,
263 pub reference_mode: u8,
264}
265
266/// `read_compressed_header` (libvpx `vp9_decodeframe.c:2889`): tx mode, tx
267/// probs, coef probs, skip probs, then — for inter frames only — the inter
268/// mode, switchable-interp, intra/inter, reference-mode, y-mode, partition
269/// and MV probability updates.
270///
271/// Lossless forces `ONLY_4X4` and consumes no tx-mode bits — decodeframe.c
272/// `read_compressed_header`: `cm->tx_mode = xd->lossless ? ONLY_4X4 :
273/// read_tx_mode(&r);`.
274pub(crate) fn read_compressed_header(
275 data: &[u8],
276 ctx: &mut FrameContext,
277 hdr: &FrameHeader,
278) -> crate::Result<CompressedHeader> {
279 if crate::interdump_enabled() && !hdr.frame_is_intra {
280 let mut line = String::from("PPFLAT_PRE");
281 for row in ctx.partition.iter() {
282 for v in row.iter() {
283 line.push_str(&format!(" {v}"));
284 }
285 }
286 eprintln!("{line}");
287 }
288 let lossless = hdr.quantization.lossless();
289 let mut r = BoolDecoder::new(data)?;
290 let tx_mode = if lossless {
291 ONLY_4X4
292 } else {
293 read_tx_mode(&mut r)
294 };
295 if crate::trace_enabled() {
296 eprintln!("SECT txmode");
297 }
298 if tx_mode == TX_MODE_SELECT {
299 for row in 0..2 {
300 for j in 0..1 {
301 diff_update_prob(&mut r, &mut ctx.tx_p8x8[row][j]);
302 }
303 }
304 for row in 0..2 {
305 for j in 0..2 {
306 diff_update_prob(&mut r, &mut ctx.tx_p16x16[row][j]);
307 }
308 }
309 for row in 0..2 {
310 for j in 0..3 {
311 diff_update_prob(&mut r, &mut ctx.tx_p32x32[row][j]);
312 }
313 }
314 }
315 if crate::trace_enabled() {
316 eprintln!("SECT txprobs");
317 }
318 read_coef_probs(&mut r, ctx, tx_mode);
319 if crate::trace_enabled() {
320 eprintln!("SECT coef");
321 }
322 for p in &mut ctx.skip {
323 diff_update_prob(&mut r, p);
324 }
325 let mut reference_mode = SINGLE_REFERENCE;
326 if crate::trace_enabled() {
327 eprintln!("SECT skip");
328 }
329 if !hdr.frame_is_intra {
330 if crate::trace_enabled() {
331 eprintln!("SECT intermode");
332 }
333 for i in 0..7 {
334 for j in 0..3 {
335 diff_update_prob(&mut r, &mut ctx.inter_mode[i][j]);
336 }
337 }
338 if crate::trace_enabled() {
339 eprintln!("SECT switchable");
340 }
341 if hdr.interpolation_filter as u8 == crate::inter::SWITCHABLE {
342 for j in 0..4 {
343 for i in 0..2 {
344 diff_update_prob(&mut r, &mut ctx.switchable_interp[j][i]);
345 }
346 }
347 }
348 if crate::trace_enabled() {
349 eprintln!("SECT intrainter");
350 }
351 for p in &mut ctx.intra_inter {
352 diff_update_prob(&mut r, p);
353 }
354 // read_frame_reference_mode: `vp9_compound_reference_allowed` gates
355 // the two bits (bias[GOLDEN]/bias[ALTREF] vs bias[LAST]).
356 if crate::trace_enabled() {
357 eprintln!("SECT refmode");
358 }
359 let allowed = hdr.ref_frame_sign_bias[1] != hdr.ref_frame_sign_bias[0]
360 || hdr.ref_frame_sign_bias[2] != hdr.ref_frame_sign_bias[0];
361 reference_mode = if allowed {
362 if r.read_bool(128) {
363 if r.read_bool(128) {
364 REFERENCE_MODE_SELECT
365 } else {
366 COMPOUND_REFERENCE
367 }
368 } else {
369 SINGLE_REFERENCE
370 }
371 } else {
372 SINGLE_REFERENCE
373 };
374 // read_frame_reference_mode_probs.
375 if crate::trace_enabled() {
376 eprintln!("SECT refprobs");
377 }
378 if reference_mode == REFERENCE_MODE_SELECT {
379 for p in &mut ctx.comp_inter {
380 diff_update_prob(&mut r, p);
381 }
382 }
383 if reference_mode != COMPOUND_REFERENCE {
384 for i in 0..5 {
385 for j in 0..2 {
386 diff_update_prob(&mut r, &mut ctx.single_ref[i][j]);
387 }
388 }
389 }
390 if reference_mode != SINGLE_REFERENCE {
391 for p in &mut ctx.comp_ref {
392 diff_update_prob(&mut r, p);
393 }
394 }
395 if crate::trace_enabled() {
396 eprintln!("SECT ymode");
397 }
398 for j in 0..4 {
399 for i in 0..9 {
400 diff_update_prob(&mut r, &mut ctx.y_mode[j][i]);
401 }
402 }
403 if crate::trace_enabled() {
404 eprintln!("SECT partition");
405 }
406 for j in 0..16 {
407 for i in 0..3 {
408 let before = ctx.partition[j][i];
409 diff_update_prob(&mut r, &mut ctx.partition[j][i]);
410 if crate::interdump_enabled() {
411 eprintln!("PUPD {} {} {} {}", j, i, before, ctx.partition[j][i]);
412 }
413 }
414 }
415 // read_mv_probs (vp9_decodeframe.c:76): joints, then per component
416 // sign/classes/class0/bits, then the fractional parts, then hp.
417 if crate::trace_enabled() {
418 eprintln!("SECT mv");
419 }
420 update_mv_probs(&mut r, &mut ctx.nmv_joints);
421 for comp in 0..2 {
422 update_mv_probs(&mut r, &mut ctx.nmv_sign[comp..comp + 1]);
423 update_mv_probs(&mut r, &mut ctx.nmv_classes[comp]);
424 update_mv_probs(&mut r, &mut ctx.nmv_class0[comp]);
425 update_mv_probs(&mut r, &mut ctx.nmv_bits[comp]);
426 }
427 for comp in 0..2 {
428 for j in 0..2 {
429 update_mv_probs(&mut r, &mut ctx.nmv_class0_fp[comp][j]);
430 }
431 update_mv_probs(&mut r, &mut ctx.nmv_fp[comp]);
432 }
433 if hdr.allow_high_precision_mv {
434 for comp in 0..2 {
435 update_mv_probs(&mut r, &mut ctx.nmv_class0_hp[comp..comp + 1]);
436 update_mv_probs(&mut r, &mut ctx.nmv_hp[comp..comp + 1]);
437 if crate::mvdump_enabled() {
438 eprintln!(
439 "MVPROB j0={} j1={} j2={}",
440 ctx.nmv_joints[0], ctx.nmv_joints[1], ctx.nmv_joints[2]
441 );
442 for comp in 0..2 {
443 eprintln!(
444 "MVPROB c{} sign={} class0={} class0hp={} hp={}",
445 comp,
446 ctx.nmv_sign[comp],
447 ctx.nmv_class0[comp][0],
448 ctx.nmv_class0_hp[comp],
449 ctx.nmv_hp[comp]
450 );
451 eprint!("MVPROB c{} cls", comp);
452 for v in ctx.nmv_classes[comp].iter() { eprint!(" {}", v); }
453 eprintln!();
454 eprint!("MVPROB c{} bits", comp);
455 for v in ctx.nmv_bits[comp].iter() { eprint!(" {}", v); }
456 eprintln!();
457 eprint!("MVPROB c{} c0fp", comp);
458 for row in ctx.nmv_class0_fp[comp].iter() { for v in row.iter() { eprint!(" {}", v); } }
459 eprintln!();
460 eprint!("MVPROB c{} fp", comp);
461 for v in ctx.nmv_fp[comp].iter() { eprint!(" {}", v); }
462 eprintln!();
463 }
464 }
465 }
466 }
467 }
468 if std::env::var_os("EC_VP9_DBG").is_some() {
469 eprintln!("DBG tx_mode={} consumed={}", tx_mode, r.byte_offset());
470 eprintln!(
471 "DBG skip_probs={:?} p8x8={:?} p16={:?}",
472 ctx.skip, ctx.tx_p8x8, ctx.tx_p16x16
473 );
474 eprintln!(
475 "DBG coef[0][0][0][0][0..3]={:?} coef[0][0][1][1][0..3]={:?}",
476 ctx.coef[0][0][0][0], ctx.coef[0][0][1][1]
477 );
478 }
479 ensure(r.overreads() == 0, "compressed header desync")?;
480 Ok(CompressedHeader {
481 tx_mode,
482 reference_mode,
483 })
484}