forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8a5feaaTahinli2 months ago3162 commits

header.rs475 lines, 18.2 KiBHistoryRawDownload
1//! Uncompressed chunk and first-partition header parsing
2//! (RFC 6386 §9-§10, following the reference decoder's field order).
3//!
4//! Three pieces of state persist across frames until the next key frame
5//! resets them: the entropy context (coefficient, MV and intra-mode
6//! probabilities), the segmentation feature data and the per-macroblock
7//! loop-filter deltas. They live in [`PersistedState`]; every frame's
8//! [`FrameHeader::parse`] folds that frame's updates into it.
9
10use crate::bool::BoolDecoder;
11use crate::frame::{FrameTag, FrameType, KEYFRAME_HEADER_SZ, parse_keyframe_dims};
12use crate::tables::{DEFAULT_COEFF_PROBS, DEFAULT_MV_PROBS, MV_UPDATE_PROBS};
13use ec_core::{Error, Result};
14
15/// Probability-array length per MV component (dixie `MV_PROB_CNT`):
16/// is_short, sign, 7 short-tree, 10 long-bits probabilities.
17pub const MV_PROB_CNT: usize = 19;
18
19/// Everything that survives from frame to frame until a key frame.
20#[derive(Debug, Clone)]
21pub struct PersistedState {
22 /// Token-tree probabilities, `[block_type][band][ctx][node]`
23 /// (RFC 6386 §13.3).
24 /// Token-tree probabilities `[block_type][band][ctx][node]` (§13.3).
25 pub coeff_probs: [[[[u8; 11]; 3]; 8]; 4],
26 /// Per-MV-component probabilities `[component][prob]` (RFC §17.2).
27 /// Per-MV-component probabilities `[component][prob]` (§17.2).
28 pub mv_probs: [[u8; MV_PROB_CNT]; 2],
29 /// Interframe Y-mode tree probabilities (RFC §16.1).
30 /// Interframe Y-mode tree probabilities (§16.1).
31 pub ymode_probs: [u8; 4],
32 /// Interframe chroma-mode tree probabilities (RFC §16.1).
33 /// Interframe chroma-mode tree probabilities (§16.1).
34 pub uv_mode_probs: [u8; 3],
35 /// Segment feature state (RFC §10), zeroed at each key frame.
36 /// Segment feature state (§10), zeroed at each key frame.
37 pub segmentation: SegmentationState,
38 /// Per-MB loop-filter deltas (RFC §9.4), zeroed at each key frame.
39 /// Reference-frame-based loop-filter deltas (§9.4; intra, last,
40 /// golden, altref order).
41 pub ref_lf_delta: [i32; 4],
42 /// Mode-based loop-filter deltas (§9.4; B_PRED, ZEROMV, MV,
43 /// SPLITMV order).
44 pub mode_lf_delta: [i32; 4],
45}
46
47impl Default for PersistedState {
48 fn default() -> Self {
49 Self {
50 coeff_probs: DEFAULT_COEFF_PROBS,
51 mv_probs: DEFAULT_MV_PROBS,
52 // Interframe tree defaults (libvpx vp8_ymode_prob /
53 // vp8_uv_mode_prob); key frames reset these too.
54 ymode_probs: [112, 86, 140, 37],
55 uv_mode_probs: [162, 101, 204],
56 segmentation: SegmentationState::default(),
57 ref_lf_delta: [0; 4],
58 mode_lf_delta: [0; 4],
59 }
60 }
61}
62
63/// Segment feature state (RFC 6386 §10). `quant_idx`/`lf_level` hold the
64/// raw transmitted values; they are absolute in absolute mode and deltas
65/// in delta mode.
66#[derive(Debug, Clone, Default)]
67pub struct SegmentationState {
68 /// Segment features active for the current frame.
69 pub enabled: bool,
70 /// The per-MB segment map is re-coded this frame.
71 pub update_map: bool,
72 /// Segment feature values are re-coded this frame.
73 pub update_data: bool,
74 /// 0 = absolute values, 1 = deltas against the frame baseline.
75 /// 0 = absolute values, 1 = deltas against the frame baseline.
76 pub abs_delta: bool,
77 /// Per-segment quantizer value or delta (§10).
78 pub quant_idx: [i32; 4],
79 /// Per-segment loop-filter level or delta (§10).
80 pub lf_level: [i32; 4],
81 /// Segment-map decoding tree probabilities (default 255).
82 /// Segment-map tree probabilities (default 255; §9.3 item 5).
83 pub tree_probs: [u8; 3],
84}
85
86/// Frame-level fields parsed from the uncompressed chunk and the first
87/// data partition. Everything the per-macroblock decode needs.
88#[derive(Debug, Clone)]
89pub struct FrameHeader {
90 /// Parsed 3-byte frame tag.
91 pub tag: FrameTag,
92 /// Key-frame dimensions (key frames only).
93 pub dims: Option<crate::frame::KeyFrameDims>,
94 /// Key-frame-only colour-space bit (0 = YUV; 1 is reserved).
95 pub color_space: u8,
96 /// Key-frame-only clamping bit (1 = reconstructed pixels guaranteed
97 /// 0..255, clamping optional).
98 pub clamping_type: u8,
99 /// Segment feature snapshot this frame decodes under.
100 pub segmentation: SegmentationState,
101 /// Loop filter type/level/sharpness (§9.4).
102 /// 0 = normal loop filter, 1 = simple (§9.4).
103 pub filter_type: u8,
104 /// Baseline loop filter strength 0-63 (0 disables filtering).
105 pub filter_level: u8,
106 /// Loop filter sharpness 0-7 (§9.4, §15.2).
107 pub sharpness_level: u8,
108 /// Per-MB loop-filter delta adjustment enabled for this frame.
109 pub lf_delta_enabled: bool,
110 /// This frame updated the (persisted) delta values.
111 pub lf_delta_update: bool,
112 /// log2 of the token partition count (1, 2, 4 or 8 partitions).
113 pub log2_partitions: u8,
114 /// Quantization indices (§9.6): base Y-AC index plus per-plane deltas.
115 pub quant: QuantIndices,
116 /// Probability an interframe MB is intra-coded (§9.10 `prob_intra`).
117 pub prob_intra: u8,
118 /// Probability an inter MB uses the last-frame reference.
119 pub prob_last: u8,
120 /// Probability an inter MB uses the golden rather than altref ref.
121 pub prob_gf: u8,
122 /// Whether this frame updated the interframe Y-mode probabilities.
123 pub ymode_probs_updated: bool,
124 /// Whether this frame updated the chroma-mode probabilities.
125 pub uv_mode_probs_updated: bool,
126 /// Reference-frame refresh/copies/sign-biases (§9.7-§9.8).
127 pub refresh: RefreshHeader,
128 /// mb_no_skip_coeff (§9.10/§9.11): per-MB "no non-zero coefficients"
129 /// flag is coded at all.
130 pub coeff_skip_enabled: bool,
131 /// Probability for the per-MB skip flag (meaningful when enabled).
132 pub prob_skip_false: u8,
133 /// Offset of the first token partition from the start of `data`
134 /// (i.e. uncompressed chunk + first partition).
135 pub token_data_offset: usize,
136 /// Token partition sizes in bytes; last entry is the remainder.
137 pub partition_sizes: Vec<u32>,
138}
139
140/// Six dequantization indices (§9.6): the always-coded Y-AC index plus
141/// signed deltas for the other five factors.
142#[derive(Debug, Clone, Copy, Default)]
143pub struct QuantIndices {
144 /// Base quantizer index for Y AC (7 bits).
145 pub yac_qi: u8,
146 /// Signed delta applied to the Y-DC dequant index (§9.6).
147 pub ydc_delta: i32,
148 /// Signed delta applied to the Y2-DC dequant index (§9.6).
149 pub y2dc_delta: i32,
150 /// Signed delta applied to the Y2-AC dequant index (§9.6).
151 pub y2ac_delta: i32,
152 /// Signed delta applied to the chroma-DC dequant index (§9.6).
153 pub uvdc_delta: i32,
154 /// Signed delta applied to the chroma-AC dequant index (§9.6).
155 pub uvac_delta: i32,
156}
157
158/// Reference-frame refresh state for one frame (§9.7-§9.8). Key frames
159/// refresh every reference and read only `refresh_entropy`.
160#[derive(Debug, Clone, Copy)]
161pub struct RefreshHeader {
162 /// The golden buffer is refreshed with the current frame.
163 pub refresh_gf: bool,
164 /// The altref buffer is refreshed with the current frame.
165 pub refresh_arf: bool,
166 /// 0 = none, 1 = copy last, 2 = copy altref (to golden).
167 pub copy_gf: u8,
168 /// 0 = none, 1 = copy last, 2 = copy golden (to altref).
169 pub copy_arf: u8,
170 /// Sign bias applied to MVs referencing the golden frame (§9.7).
171 pub sign_bias_golden: bool,
172 /// Sign bias applied to MVs referencing the altref frame (§9.7).
173 pub sign_bias_altref: bool,
174 /// Whether this frame's entropy updates persist to the next frame.
175 pub refresh_entropy: bool,
176 /// The last-frame buffer is refreshed with the current frame.
177 pub refresh_last: bool,
178}
179
180impl FrameHeader {
181 /// The frame's type (key or inter), from the frame tag.
182 pub fn frame_type(&self) -> FrameType {
183 self.tag.frame_type
184 }
185
186 /// Parse one frame's uncompressed chunk + first partition from
187 /// `data`, folding entropy/segmentation/filter-delta updates into
188 /// `state`. Returns the header and the partition-1 slice.
189 ///
190 /// `token_data_offset` + every `partition_sizes[i]` together describe
191 /// the bytes after partition 1.
192 pub fn parse<'a>(
193 data: &'a [u8],
194 state: &mut PersistedState,
195 ) -> Result<(FrameHeader, BoolDecoder<'a>)> {
196 let tag = FrameTag::parse(data)?;
197 let key = tag.frame_type == FrameType::Key;
198 let mut off = crate::frame::FRAME_TAG_SZ;
199
200 let mut dims = None;
201 if key {
202 let kf = parse_keyframe_dims(data)?;
203 dims = Some(kf);
204 off += KEYFRAME_HEADER_SZ;
205 // A key frame resets every piece of persisted entropy and
206 // segment/filter state (dixie `decode_frame`).
207 *state = PersistedState::default();
208 }
209
210 let part0_end = off + tag.first_part_size as usize;
211 if data.len() < part0_end {
212 return Err(Error::corrupt(format!(
213 "VP8 first partition extends past end of frame \
214 (need {part0_end} bytes, have {})",
215 data.len()
216 )));
217 }
218 let mut d = BoolDecoder::new(&data[off..part0_end])?;
219
220 // Colour space + clamping (key frames only): two literal bits;
221 // the colour-space bit is reserved and must be 0 (dixie reads
222 // both together and refuses any non-zero pair; we keep the
223 // (legal) clamping bit decodable and refuse only the reserved
224 // colour-space one).
225 let (color_space, clamping_type) = if key {
226 let cs = d.read_literal(1) as u8;
227 let clamp = d.read_literal(1) as u8;
228 if cs != 0 {
229 return Err(Error::unsupported(
230 "VP8 reserved colour-space bit",
231 "bit 0 of the key-frame colour-space pair was set",
232 ));
233 }
234 (cs, clamp)
235 } else {
236 (0, 0)
237 };
238
239 // --- segmentation (§9.3, dixie decode_segmentation_header) ---
240 let mut segmentation = if key {
241 SegmentationState::default()
242 } else {
243 state.segmentation.clone()
244 };
245 segmentation.enabled = d.read_bool(128);
246 if segmentation.enabled {
247 segmentation.update_map = d.read_bool(128);
248 segmentation.update_data = d.read_bool(128);
249 if segmentation.update_data {
250 segmentation.abs_delta = d.read_bool(128);
251 for i in 0..4 {
252 segmentation.quant_idx[i] = d.read_maybe_signed(7);
253 }
254 for i in 0..4 {
255 segmentation.lf_level[i] = d.read_maybe_signed(6);
256 }
257 }
258 if segmentation.update_map {
259 for i in 0..3 {
260 segmentation.tree_probs[i] = if d.read_bool(128) {
261 d.read_literal(8) as u8
262 } else {
263 255
264 };
265 }
266 }
267 } else {
268 segmentation.update_map = false;
269 segmentation.update_data = false;
270 }
271 state.segmentation = segmentation.clone();
272
273 // --- loop filter (§9.4, dixie decode_loopfilter_header) ---
274 let mut ref_lf_delta = state.ref_lf_delta;
275 let mut mode_lf_delta = state.mode_lf_delta;
276 if key {
277 ref_lf_delta = [0; 4];
278 mode_lf_delta = [0; 4];
279 }
280 let filter_type = d.read_literal(1) as u8;
281 let filter_level = d.read_literal(6) as u8;
282 let sharpness_level = d.read_literal(3) as u8;
283 let lf_delta_enabled = d.read_bool(128);
284 let mut lf_delta_update = false;
285 if lf_delta_enabled && d.read_bool(128) {
286 lf_delta_update = true;
287 for i in 0..4 {
288 ref_lf_delta[i] = d.read_maybe_signed(6);
289 }
290 for i in 0..4 {
291 mode_lf_delta[i] = d.read_maybe_signed(6);
292 }
293 }
294 state.ref_lf_delta = ref_lf_delta;
295 state.mode_lf_delta = mode_lf_delta;
296
297 // --- token partitions (§9.5) ---
298 let log2_partitions = d.read_literal(2) as u8;
299 let partitions = 1usize << log2_partitions;
300 let sizes_area = 3 * (partitions - 1);
301 if data.len() < part0_end + sizes_area {
302 return Err(Error::corrupt(
303 "VP8 token partition size table extends past end of frame",
304 ));
305 }
306 let mut partition_sizes = Vec::with_capacity(partitions);
307 let mut size_off = part0_end;
308 let mut remaining = (data.len() - part0_end - sizes_area) as u32;
309 for i in 0..partitions {
310 if i < partitions - 1 {
311 let sz = u32::from(data[size_off])
312 | (u32::from(data[size_off + 1]) << 8)
313 | (u32::from(data[size_off + 2]) << 16);
314 size_off += 3;
315 partition_sizes.push(sz);
316 remaining = remaining
317 .checked_sub(sz)
318 .ok_or_else(|| Error::corrupt("VP8 token partitions exceed frame size"))?;
319 } else {
320 partition_sizes.push(remaining);
321 }
322 }
323
324 // --- quantization indices (§9.6) ---
325 let mut quant = QuantIndices {
326 yac_qi: d.read_literal(7) as u8,
327 ..QuantIndices::default()
328 };
329 quant.ydc_delta = d.read_maybe_signed(4);
330 quant.y2dc_delta = d.read_maybe_signed(4);
331 quant.y2ac_delta = d.read_maybe_signed(4);
332 quant.uvdc_delta = d.read_maybe_signed(4);
333 quant.uvac_delta = d.read_maybe_signed(4);
334
335 // --- reference refresh (§9.7-§9.8) ---
336 let refresh = if key {
337 RefreshHeader {
338 refresh_gf: true,
339 refresh_arf: true,
340 copy_gf: 0,
341 copy_arf: 0,
342 sign_bias_golden: false,
343 sign_bias_altref: false,
344 refresh_entropy: d.read_bool(128),
345 refresh_last: true,
346 }
347 } else {
348 let refresh_gf = d.read_bool(128);
349 let refresh_arf = d.read_bool(128);
350 let copy_gf = if refresh_gf {
351 0
352 } else {
353 d.read_literal(2) as u8
354 };
355 let copy_arf = if refresh_arf {
356 0
357 } else {
358 d.read_literal(2) as u8
359 };
360 RefreshHeader {
361 refresh_gf,
362 refresh_arf,
363 copy_gf,
364 copy_arf,
365 sign_bias_golden: d.read_bool(128),
366 sign_bias_altref: d.read_bool(128),
367 refresh_entropy: d.read_bool(128),
368 refresh_last: d.read_bool(128),
369 }
370 };
371
372 // --- entropy updates (§9.9; dixie decode_entropy_header) ---
373 // Coefficient probability updates are read for every frame; on
374 // key frames the tables were reset to defaults above.
375 for i in 0..4 {
376 for j in 0..8 {
377 for k in 0..3 {
378 for l in 0..11 {
379 if d.read_bool(crate::tables::COEFF_UPDATE_PROBS[i][j][k][l]) {
380 state.coeff_probs[i][j][k][l] = d.read_literal(8) as u8;
381 }
382 }
383 }
384 }
385 }
386
387 // mb_no_skip_coeff (§9.11 / inter §9.10).
388 let coeff_skip_enabled = d.read_bool(128);
389 let prob_skip_false = if coeff_skip_enabled {
390 d.read_literal(8) as u8
391 } else {
392 128
393 };
394 // Interframe-only probability updates.
395 if crate::trace_enabled() {
396 eprintln!("STAGE interprobs");
397 }
398 let mut ymode_probs_updated = false;
399 let mut uv_mode_probs_updated = false;
400 let (prob_intra, prob_last, prob_gf) = if !key {
401 let probs = (
402 d.read_literal(8) as u8,
403 d.read_literal(8) as u8,
404 d.read_literal(8) as u8,
405 );
406 ymode_probs_updated = d.read_bool(128);
407 if ymode_probs_updated {
408 for i in 0..4 {
409 state.ymode_probs[i] = d.read_literal(8) as u8;
410 }
411 }
412 uv_mode_probs_updated = d.read_bool(128);
413 if uv_mode_probs_updated {
414 for i in 0..3 {
415 state.uv_mode_probs[i] = d.read_literal(8) as u8;
416 }
417 }
418 // MV probability updates: P(7) form, x ? x << 1 : 1 (§17.2).
419 for c in 0..2 {
420 for j in 0..MV_PROB_CNT {
421 if d.read_bool(MV_UPDATE_PROBS[c][j]) {
422 state.mv_probs[c][j] = d.read_prob7();
423 }
424 }
425 }
426 if crate::trace_enabled() {
427 eprintln!("YUV ymode = {:?} uv = {:?}", state.ymode_probs, state.uv_mode_probs);
428 eprintln!("MVT c0 = {:?}", state.mv_probs[0]);
429 eprintln!("MVT c1 = {:?}", state.mv_probs[1]);
430 }
431 probs
432 } else {
433 (112, 86, 140) // placeholders; only read on inter frames
434 };
435
436 // The reference decoder zero-fills past the end of a partition;
437 // tiny partitions (e.g. one-MB key frames) can legitimately
438 // overrun by a byte or two. Gross overruns are still desyncs.
439 if d.overreads() > 16 {
440 return Err(Error::corrupt(format!(
441 "VP8 first partition over-read by {} bytes (header desync)",
442 d.overreads()
443 )));
444 }
445
446 let header = FrameHeader {
447 tag,
448 dims,
449 color_space,
450 clamping_type,
451 segmentation,
452 filter_type,
453 filter_level,
454 sharpness_level,
455 lf_delta_enabled,
456 lf_delta_update,
457 log2_partitions,
458 quant,
459 refresh,
460 prob_intra,
461 prob_last,
462 prob_gf,
463 ymode_probs_updated,
464 uv_mode_probs_updated,
465 coeff_skip_enabled,
466 prob_skip_false,
467 token_data_offset: part0_end,
468 partition_sizes,
469 };
470 let _ = off;
471 // The partition-0 decoder is returned mid-stream: the per-MB
472 // mode records continue from exactly where the header stopped.
473 Ok((header, d))
474 }
475}