forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust382.3 MiBe18142dTahinli10 hours ago4543 commits

header.rs1044 lines, 38.2 KiBHistoryRawDownload
1//! The uncompressed frame header (spec 6.2 `uncompressed_header`).
2
3use ec_core::{BitReader, Error, Result};
4
5use crate::{
6 MAX_SEGMENTS, NUM_REF_FRAMES, REFS_PER_FRAME, SEG_LVL_ALT_L, SEG_LVL_ALT_Q, SEG_LVL_MAX,
7};
8
9/// The three-byte frame sync code that opens a keyframe or intra-only frame.
10const SYNC_CODE: [u8; 3] = [0x49, 0x83, 0x42];
11/// Bits carried by each segment feature (spec 6.2, `segmentation_feature_bits`).
12const SEG_FEATURE_BITS: [u32; SEG_LVL_MAX] = [8, 6, 2, 0];
13/// Which segment features carry a sign bit (spec 6.2, `segmentation_feature_signed`).
14const SEG_FEATURE_SIGNED: [bool; SEG_LVL_MAX] = [true, true, false, false];
15/// Loop filter deltas after `setup_past_independence` (spec 7.2, "intra, last, golden, altref").
16const DEFAULT_REF_DELTAS: [i8; 4] = [1, 0, -1, -1];
17/// The largest loop filter level, and the clamp applied to every derived level.
18const MAX_LOOP_FILTER: i32 = 63;
19
20/// Frame type (spec 6.2, `frame_type`).
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub enum FrameType {
23 /// `KEY_FRAME`: refreshes every reference slot and resets all persistent state.
24 Key,
25 /// `NON_KEY_FRAME`: inter, or intra-only when `intra_only` is set.
26 Inter,
27}
28
29/// Colour space code point (spec 6.2, `color_space`).
30///
31/// These are VP9's own three-bit codes, not H.273; convert with
32/// [`ColorSpace::h273`] when handing them to the family colour model.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub enum ColorSpace {
35 /// `CS_UNKNOWN`, 0.
36 Unknown,
37 /// `CS_BT_601`, 1.
38 Bt601,
39 /// `CS_BT_709`, 2.
40 Bt709,
41 /// `CS_SMPTE_170`, 3.
42 Smpte170,
43 /// `CS_SMPTE_240`, 4.
44 Smpte240,
45 /// `CS_BT_2020`, 5.
46 Bt2020,
47 /// `CS_RESERVED`, 6.
48 Reserved,
49 /// `CS_RGB`, 7 — 4:4:4 with full range, profiles 1 and 3 only.
50 Rgb,
51}
52
53impl ColorSpace {
54 fn from_code(code: u32) -> ColorSpace {
55 match code {
56 1 => ColorSpace::Bt601,
57 2 => ColorSpace::Bt709,
58 3 => ColorSpace::Smpte170,
59 4 => ColorSpace::Smpte240,
60 5 => ColorSpace::Bt2020,
61 6 => ColorSpace::Reserved,
62 7 => ColorSpace::Rgb,
63 _ => ColorSpace::Unknown,
64 }
65 }
66
67 /// The H.273 `(colour_primaries, transfer_characteristics, matrix_coefficients)`
68 /// triplet VP9 means by this code point, as tabulated in the WebM container
69 /// guidelines; `None` for `CS_UNKNOWN` and `CS_RESERVED`, which say nothing.
70 pub fn h273(self) -> Option<(u8, u8, u8)> {
71 match self {
72 ColorSpace::Bt601 => Some((5, 6, 6)),
73 ColorSpace::Bt709 => Some((1, 1, 1)),
74 ColorSpace::Smpte170 => Some((6, 6, 6)),
75 ColorSpace::Smpte240 => Some((7, 7, 7)),
76 ColorSpace::Bt2020 => Some((9, 14, 9)),
77 ColorSpace::Rgb => Some((1, 13, 0)),
78 ColorSpace::Unknown | ColorSpace::Reserved => None,
79 }
80 }
81}
82
83/// Sub-pixel interpolation filter (spec 6.2, `read_interpolation_filter`).
84///
85/// The discriminants are the VP9 `interp_filter` values, which is also what
86/// `VADecPictureParameterBufferVP9::mcomp_filter_type` wants.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
88#[repr(u8)]
89pub enum InterpolationFilter {
90 /// `EIGHTTAP_SMOOTH`, 0.
91 EighttapSmooth = 0,
92 /// `EIGHTTAP`, 1.
93 Eighttap = 1,
94 /// `EIGHTTAP_SHARP`, 2.
95 EighttapSharp = 2,
96 /// `BILINEAR`, 3.
97 Bilinear = 3,
98 /// `SWITCHABLE`, 4 — chosen per block in the compressed header.
99 Switchable = 4,
100}
101
102/// Loop filter parameters (spec 6.2, `loop_filter_params`).
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub struct LoopFilterParams {
105 /// `loop_filter_level`, 0-63; 0 disables the filter for the frame.
106 pub level: u8,
107 /// `loop_filter_sharpness`, 0-7.
108 pub sharpness: u8,
109 /// `loop_filter_delta_enabled`: per-reference and per-mode adjustments apply.
110 pub delta_enabled: bool,
111 /// `loop_filter_delta_update`: this frame coded new delta values.
112 pub delta_update: bool,
113 /// `loop_filter_ref_deltas`, indexed intra, last, golden, altref. Persists
114 /// across frames until reset by `setup_past_independence`.
115 pub ref_deltas: [i8; 4],
116 /// `loop_filter_mode_deltas`, indexed by inter mode class. Persists likewise.
117 pub mode_deltas: [i8; 2],
118}
119
120impl Default for LoopFilterParams {
121 fn default() -> LoopFilterParams {
122 LoopFilterParams {
123 level: 0,
124 sharpness: 0,
125 delta_enabled: false,
126 delta_update: false,
127 ref_deltas: DEFAULT_REF_DELTAS,
128 mode_deltas: [0; 2],
129 }
130 }
131}
132
133/// Quantization parameters (spec 6.2, `quantization_params`).
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
135pub struct QuantizationParams {
136 /// `base_q_idx`, the frame-level quantizer index, 0-255.
137 pub base_q_idx: u8,
138 /// `delta_q_y_dc`, luma DC offset from `base_q_idx`.
139 pub delta_q_y_dc: i8,
140 /// `delta_q_uv_dc`, chroma DC offset from `base_q_idx`.
141 pub delta_q_uv_dc: i8,
142 /// `delta_q_uv_ac`, chroma AC offset from `base_q_idx`.
143 pub delta_q_uv_ac: i8,
144}
145
146impl QuantizationParams {
147 /// `LosslessFlag` (spec 6.2): quantizer index 0 with no plane offsets.
148 ///
149 /// This is `VADecPictureParameterBufferVP9::lossless_flag` verbatim.
150 pub fn lossless(&self) -> bool {
151 self.base_q_idx == 0
152 && self.delta_q_y_dc == 0
153 && self.delta_q_uv_dc == 0
154 && self.delta_q_uv_ac == 0
155 }
156}
157
158/// Segmentation parameters (spec 6.2, `segmentation_params`).
159///
160/// Everything but `enabled`, `update_map` and `update_data` persists from frame
161/// to frame: a frame may enable segmentation and code no data, meaning "keep
162/// using the previous frame's". [`Vp9Parser`] carries that state, so the copy in
163/// a parsed header is always the state in force *for that frame*.
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
165pub struct SegmentationParams {
166 /// `segmentation_enabled`.
167 pub enabled: bool,
168 /// `segmentation_update_map`: the tree probabilities below are new.
169 pub update_map: bool,
170 /// `segmentation_temporal_update`: the map is coded predictively, using
171 /// [`SegmentationParams::pred_probs`].
172 pub temporal_update: bool,
173 /// `segmentation_update_data`: the feature table below is new.
174 pub update_data: bool,
175 /// `segmentation_abs_or_delta_update`: feature data is absolute, not a delta
176 /// against the frame-level value.
177 pub abs_or_delta_update: bool,
178 /// `segmentation_tree_probs`, the 7 probabilities of the segment id tree;
179 /// 255 where not coded. `VADecPictureParameterBufferVP9::mb_segment_tree_probs`.
180 pub tree_probs: [u8; 7],
181 /// `segmentation_pred_prob`, the 3 temporal prediction probabilities; 255
182 /// where not coded. `VADecPictureParameterBufferVP9::segment_pred_probs`.
183 pub pred_probs: [u8; 3],
184 /// `FeatureEnabled[segment][feature]`, features indexed by the `SEG_LVL_*`
185 /// constants.
186 pub feature_enabled: [[bool; SEG_LVL_MAX]; MAX_SEGMENTS],
187 /// `FeatureData[segment][feature]`, sign already applied.
188 pub feature_data: [[i16; SEG_LVL_MAX]; MAX_SEGMENTS],
189}
190
191impl SegmentationParams {
192 /// Whether `feature` (a `SEG_LVL_*` index) is on for `segment_id`.
193 pub fn feature_active(&self, segment_id: u8, feature: usize) -> bool {
194 self.enabled
195 && self
196 .feature_enabled
197 .get(segment_id as usize)
198 .is_some_and(|f| f[feature])
199 }
200}
201
202/// Tile layout (spec 6.2, `tile_info`).
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
204pub struct TileInfo {
205 /// `tile_cols_log2`: the frame has `1 << tile_cols_log2` tile columns.
206 pub cols_log2: u8,
207 /// `tile_rows_log2`: the frame has `1 << tile_rows_log2` tile rows.
208 pub rows_log2: u8,
209}
210
211/// One decoded uncompressed frame header.
212///
213/// Field names follow the spec, so a reader can hold the two side by side. Every
214/// field of `VADecPictureParameterBufferVP9` is either here verbatim or derived
215/// by a method on this type; the two exceptions are the surface ids, which are a
216/// property of the caller's frame pool rather than the bitstream, and the
217/// per-segment dequantization scales, which need the spec 8.6.1 lookup tables.
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct FrameHeader {
220 /// `profile`, 0-3. Profiles 2 and 3 carry more than 8 bits per sample;
221 /// profiles 1 and 3 code their chroma subsampling.
222 pub profile: u8,
223 /// `show_existing_frame`: this frame is a bodiless instruction to output an
224 /// existing reference. No other field below was coded; they hold defaults.
225 pub show_existing_frame: bool,
226 /// `frame_to_show_map_idx`, the reference slot to output. Only meaningful
227 /// when [`FrameHeader::show_existing_frame`] is set.
228 pub frame_to_show_map_idx: u8,
229 /// `frame_type`.
230 pub frame_type: FrameType,
231 /// `show_frame`: this frame is output as well as decoded. Hidden frames
232 /// (ALTREFs) clear it and are shown later by a `show_existing_frame` header.
233 pub show_frame: bool,
234 /// `error_resilient_mode`: probability state is reset, so a decoder may
235 /// start here without the previous frame.
236 pub error_resilient_mode: bool,
237 /// `intra_only`: a non-key frame coded without inter prediction.
238 pub intra_only: bool,
239 /// `FrameIsIntra` (spec 6.2): a keyframe or an intra-only frame.
240 pub frame_is_intra: bool,
241 /// `BitDepth`: 8, 10 or 12.
242 pub bit_depth: u8,
243 /// `color_space`.
244 pub color_space: ColorSpace,
245 /// `color_range`: true for full range (0-255), false for studio swing.
246 pub color_range: bool,
247 /// `subsampling_x`: 1 for 4:2:0 and 4:2:2, 0 for 4:4:4.
248 pub subsampling_x: u8,
249 /// `subsampling_y`: 1 for 4:2:0, 0 for 4:2:2 and 4:4:4.
250 pub subsampling_y: u8,
251 /// `FrameWidth`, the coded width in samples.
252 pub width: u32,
253 /// `FrameHeight`, the coded height in samples.
254 pub height: u32,
255 /// `RenderWidth`, the width the frame should be displayed at.
256 pub render_width: u32,
257 /// `RenderHeight`, the height the frame should be displayed at.
258 pub render_height: u32,
259 /// `refresh_frame_flags`: bit *i* means reference slot *i* is replaced by
260 /// this frame. 0xff on a keyframe.
261 pub refresh_frame_flags: u8,
262 /// `ref_frame_idx[i]`, the reference slot used as LAST, GOLDEN and ALTREF.
263 pub ref_frame_idx: [u8; REFS_PER_FRAME],
264 /// `ref_frame_sign_bias[LAST_FRAME + i]`, in the same order.
265 pub ref_frame_sign_bias: [bool; REFS_PER_FRAME],
266 /// `allow_high_precision_mv`: motion vectors have 1/8-pel precision.
267 pub allow_high_precision_mv: bool,
268 /// `interpolation_filter`.
269 pub interpolation_filter: InterpolationFilter,
270 /// `reset_frame_context`, 0-3.
271 pub reset_frame_context: u8,
272 /// `refresh_frame_context`: the compressed header's probability updates are
273 /// saved back into the frame context.
274 pub refresh_frame_context: bool,
275 /// `frame_parallel_decoding_mode`: no backward probability adaptation.
276 pub frame_parallel_decoding_mode: bool,
277 /// `frame_context_idx`, 0-3, after the reset rules in spec 6.2 are applied.
278 pub frame_context_idx: u8,
279 /// Loop filter parameters in force for this frame.
280 pub loop_filter: LoopFilterParams,
281 /// Quantization parameters for this frame.
282 pub quantization: QuantizationParams,
283 /// Segmentation parameters in force for this frame.
284 pub segmentation: SegmentationParams,
285 /// Tile layout for this frame.
286 pub tile_info: TileInfo,
287 /// `header_size_in_bytes`, the length of the compressed header that follows.
288 /// This is `VASliceParameterBufferVP9`'s partition 0 size, better known as
289 /// `first_partition_size`.
290 pub header_size_in_bytes: u16,
291 /// Length of the uncompressed header itself, in bytes, counting from the
292 /// first byte of the frame. `VADecPictureParameterBufferVP9::frame_header_length_in_bytes`.
293 pub uncompressed_header_size: u8,
294}
295
296impl FrameHeader {
297 /// `get_qindex` (spec 8.6.1): the quantizer index in force for `segment_id`,
298 /// after the segment's `SEG_LVL_ALT_Q` feature is applied.
299 ///
300 /// Feed the result, plus [`QuantizationParams::delta_q_y_dc`] and friends,
301 /// into the spec 8.6.1 `dc_q`/`ac_q` tables to fill
302 /// `VASegmentParameterVP9::{luma,chroma}_{dc,ac}_quant_scale`.
303 pub fn segment_qindex(&self, segment_id: usize) -> u8 {
304 let base = self.quantization.base_q_idx as i32;
305 let seg = &self.segmentation;
306 if !seg.enabled
307 || segment_id >= MAX_SEGMENTS
308 || !seg.feature_enabled[segment_id][SEG_LVL_ALT_Q]
309 {
310 return self.quantization.base_q_idx;
311 }
312 let data = seg.feature_data[segment_id][SEG_LVL_ALT_Q] as i32;
313 let q = if seg.abs_or_delta_update {
314 data
315 } else {
316 base + data
317 };
318 q.clamp(0, 255) as u8
319 }
320
321 /// The four dequantization scales for `segment_id` (spec 8.6.1), which are
322 /// `VASegmentParameterVP9`'s `luma_dc_quant_scale` and its three siblings.
323 pub fn segment_dequant(&self, segment_id: usize) -> SegmentDequant {
324 let q = self.segment_qindex(segment_id) as i32;
325 let depth = self.bit_depth;
326 SegmentDequant {
327 luma_dc: crate::quant::dc_q(depth, q + self.quantization.delta_q_y_dc as i32),
328 luma_ac: crate::quant::ac_q(depth, q),
329 chroma_dc: crate::quant::dc_q(depth, q + self.quantization.delta_q_uv_dc as i32),
330 chroma_ac: crate::quant::ac_q(depth, q + self.quantization.delta_q_uv_ac as i32),
331 }
332 }
333
334 /// The loop filter level table for `segment_id` (spec 8.8.1, "loop filter
335 /// frame init process"), indexed `[reference][mode]` exactly like
336 /// `VASegmentParameterVP9::filter_level`.
337 ///
338 /// Reference 0 is intra, which has no mode delta; the spec writes only
339 /// `[0][0]` and this follows it, leaving `[0][1]` equal to it.
340 pub fn loop_filter_levels(&self, segment_id: usize) -> [[u8; 2]; 4] {
341 let lf = &self.loop_filter;
342 let seg = &self.segmentation;
343 let mut lvl_seg = lf.level as i32;
344 if seg.enabled
345 && segment_id < MAX_SEGMENTS
346 && seg.feature_enabled[segment_id][SEG_LVL_ALT_L]
347 {
348 let data = seg.feature_data[segment_id][SEG_LVL_ALT_L] as i32;
349 let v = if seg.abs_or_delta_update {
350 data
351 } else {
352 lvl_seg + data
353 };
354 lvl_seg = v.clamp(0, MAX_LOOP_FILTER);
355 }
356
357 if !lf.delta_enabled {
358 return [[lvl_seg as u8; 2]; 4];
359 }
360 let shift = lvl_seg >> 5;
361 let mut out = [[0u8; 2]; 4];
362 let intra =
363 (lvl_seg + ((lf.ref_deltas[0] as i32) << shift)).clamp(0, MAX_LOOP_FILTER) as u8;
364 out[0] = [intra, intra];
365 for (reference, levels) in out.iter_mut().enumerate().skip(1) {
366 for (mode, slot) in levels.iter_mut().enumerate() {
367 let level = lvl_seg
368 + ((lf.ref_deltas[reference] as i32) << shift)
369 + ((lf.mode_deltas[mode] as i32) << shift);
370 *slot = level.clamp(0, MAX_LOOP_FILTER) as u8;
371 }
372 }
373 out
374 }
375
376 /// `MiCols` (spec 6.2, `compute_image_size`): the frame width in 8x8 blocks.
377 pub fn mi_cols(&self) -> u32 {
378 self.width.div_ceil(8)
379 }
380
381 /// `MiRows`: the frame height in 8x8 blocks.
382 pub fn mi_rows(&self) -> u32 {
383 self.height.div_ceil(8)
384 }
385}
386
387impl Default for FrameHeader {
388 fn default() -> FrameHeader {
389 FrameHeader {
390 profile: 0,
391 show_existing_frame: false,
392 frame_to_show_map_idx: 0,
393 frame_type: FrameType::Key,
394 show_frame: true,
395 error_resilient_mode: false,
396 intra_only: false,
397 frame_is_intra: true,
398 bit_depth: 8,
399 color_space: ColorSpace::Unknown,
400 color_range: false,
401 subsampling_x: 1,
402 subsampling_y: 1,
403 width: 0,
404 height: 0,
405 render_width: 0,
406 render_height: 0,
407 refresh_frame_flags: 0,
408 ref_frame_idx: [0; REFS_PER_FRAME],
409 ref_frame_sign_bias: [false; REFS_PER_FRAME],
410 allow_high_precision_mv: false,
411 interpolation_filter: InterpolationFilter::Eighttap,
412 reset_frame_context: 0,
413 refresh_frame_context: false,
414 frame_parallel_decoding_mode: false,
415 frame_context_idx: 0,
416 loop_filter: LoopFilterParams::default(),
417 quantization: QuantizationParams::default(),
418 segmentation: SegmentationParams::default(),
419 tile_info: TileInfo::default(),
420 header_size_in_bytes: 0,
421 uncompressed_header_size: 0,
422 }
423 }
424}
425
426/// The per-segment dequantization scales of spec 8.6.1, in the shape
427/// `VASegmentParameterVP9` asks for them.
428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
429pub struct SegmentDequant {
430 /// `luma_dc_quant_scale`: `dc_q(qindex + delta_q_y_dc)`.
431 pub luma_dc: i16,
432 /// `luma_ac_quant_scale`: `ac_q(qindex)`.
433 pub luma_ac: i16,
434 /// `chroma_dc_quant_scale`: `dc_q(qindex + delta_q_uv_dc)`.
435 pub chroma_dc: i16,
436 /// `chroma_ac_quant_scale`: `ac_q(qindex + delta_q_uv_ac)`.
437 pub chroma_ac: i16,
438}
439
440/// Sample format, as last coded by a keyframe or intra-only frame.
441///
442/// Inter frames do not code `color_config`; they inherit it. A picture parameter
443/// buffer needs `bit_depth` and the subsampling for *every* frame, so the parser
444/// carries the last one seen and stamps it onto the frames that omit it.
445#[derive(Debug, Clone, Copy, PartialEq, Eq)]
446struct ColorConfig {
447 bit_depth: u8,
448 color_space: ColorSpace,
449 color_range: bool,
450 subsampling_x: u8,
451 subsampling_y: u8,
452}
453
454impl ColorConfig {
455 /// Stamp the sample format onto a header being parsed.
456 fn apply(&self, h: &mut FrameHeader) {
457 h.bit_depth = self.bit_depth;
458 h.color_space = self.color_space;
459 h.color_range = self.color_range;
460 h.subsampling_x = self.subsampling_x;
461 h.subsampling_y = self.subsampling_y;
462 }
463}
464
465impl Default for ColorConfig {
466 fn default() -> ColorConfig {
467 ColorConfig {
468 bit_depth: 8,
469 color_space: ColorSpace::Unknown,
470 color_range: false,
471 subsampling_x: 1,
472 subsampling_y: 1,
473 }
474 }
475}
476
477/// What the parser remembers about a reference slot: enough to answer
478/// `frame_size_with_refs`, and enough for a caller to size its surfaces.
479#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
480pub struct ReferenceSlot {
481 /// Whether any frame has been stored in this slot yet.
482 pub valid: bool,
483 /// `RefFrameWidth`.
484 pub width: u32,
485 /// `RefFrameHeight`.
486 pub height: u32,
487 /// `RefBitDepth`.
488 pub bit_depth: u8,
489 /// `RefSubsamplingX`.
490 pub subsampling_x: u8,
491 /// `RefSubsamplingY`.
492 pub subsampling_y: u8,
493}
494
495/// A VP9 header parser holding the state the format carries between frames.
496///
497/// Feed it every frame of a stream in order — [`crate::superframe::split`] first,
498/// since a chunk may hold several — and it applies the reference refresh after
499/// each one.
500#[derive(Debug, Clone, Default)]
501pub struct Vp9Parser {
502 refs: [ReferenceSlot; NUM_REF_FRAMES],
503 segmentation: SegmentationParams,
504 loop_filter: LoopFilterParams,
505 color: ColorConfig,
506}
507
508impl Vp9Parser {
509 /// A parser with no reference state, as at the start of a stream.
510 pub fn new() -> Vp9Parser {
511 Vp9Parser {
512 refs: [ReferenceSlot::default(); NUM_REF_FRAMES],
513 segmentation: SegmentationParams::default(),
514 loop_filter: LoopFilterParams::default(),
515 color: ColorConfig::default(),
516 }
517 }
518
519 /// Parse one frame's uncompressed header and apply its reference refresh.
520 ///
521 /// `frame` starts at the frame marker, i.e. it is one element of
522 /// [`crate::superframe::split`]'s output.
523 pub fn parse_frame(&mut self, frame: &[u8]) -> Result<FrameHeader> {
524 let mut r = BitReader::new(frame);
525 let mut h = FrameHeader::default();
526
527 let marker = r.read_bits(2)?;
528 if marker != 2 {
529 return Err(Error::corrupt(format!(
530 "VP9 frame marker is {marker}, expected 2"
531 )));
532 }
533 let profile_low = r.read_bits(1)?;
534 let profile_high = r.read_bits(1)?;
535 h.profile = ((profile_high << 1) | profile_low) as u8;
536 if h.profile == 3 && r.read_bit()? {
537 return Err(Error::corrupt("VP9 profile 3 reserved_zero bit is set"));
538 }
539
540 h.show_existing_frame = r.read_bit()?;
541 if h.show_existing_frame {
542 h.frame_to_show_map_idx = r.read_bits(3)? as u8;
543 let slot = &self.refs[h.frame_to_show_map_idx as usize];
544 h.width = slot.width;
545 h.height = slot.height;
546 h.render_width = slot.width;
547 h.render_height = slot.height;
548 self.color.apply(&mut h);
549 h.show_frame = true;
550 h.uncompressed_header_size = header_bytes(&r);
551 return Ok(h);
552 }
553
554 h.frame_type = if r.read_bit()? {
555 FrameType::Inter
556 } else {
557 FrameType::Key
558 };
559 h.show_frame = r.read_bit()?;
560 h.error_resilient_mode = r.read_bit()?;
561
562 if h.frame_type == FrameType::Key {
563 read_sync_code(&mut r)?;
564 read_color_config(&mut r, h.profile, &mut self.color)?;
565 self.color.apply(&mut h);
566 read_frame_size(&mut r, &mut h)?;
567 read_render_size(&mut r, &mut h)?;
568 h.refresh_frame_flags = 0xff;
569 h.frame_is_intra = true;
570 } else {
571 h.intra_only = if h.show_frame { false } else { r.read_bit()? };
572 h.frame_is_intra = h.intra_only;
573 if !h.error_resilient_mode {
574 h.reset_frame_context = r.read_bits(2)? as u8;
575 }
576 if h.intra_only {
577 read_sync_code(&mut r)?;
578 if h.profile > 0 {
579 read_color_config(&mut r, h.profile, &mut self.color)?;
580 } else {
581 // Profile 0 intra-only is 8-bit 4:2:0 BT.601 by definition.
582 self.color = ColorConfig {
583 bit_depth: 8,
584 color_space: ColorSpace::Bt601,
585 color_range: false,
586 subsampling_x: 1,
587 subsampling_y: 1,
588 };
589 }
590 self.color.apply(&mut h);
591 h.refresh_frame_flags = r.read_bits(8)? as u8;
592 read_frame_size(&mut r, &mut h)?;
593 read_render_size(&mut r, &mut h)?;
594 } else {
595 // An inter frame codes no color_config; it inherits the one the
596 // last keyframe or intra-only frame set.
597 self.color.apply(&mut h);
598 h.refresh_frame_flags = r.read_bits(8)? as u8;
599 for i in 0..REFS_PER_FRAME {
600 h.ref_frame_idx[i] = r.read_bits(3)? as u8;
601 h.ref_frame_sign_bias[i] = r.read_bit()?;
602 }
603 self.read_frame_size_with_refs(&mut r, &mut h)?;
604 h.allow_high_precision_mv = r.read_bit()?;
605 h.interpolation_filter = read_interpolation_filter(&mut r)?;
606 }
607 }
608
609 if !h.error_resilient_mode {
610 h.refresh_frame_context = r.read_bit()?;
611 h.frame_parallel_decoding_mode = r.read_bit()?;
612 } else {
613 h.refresh_frame_context = false;
614 h.frame_parallel_decoding_mode = true;
615 }
616 h.frame_context_idx = r.read_bits(2)? as u8;
617
618 if h.frame_is_intra || h.error_resilient_mode {
619 // setup_past_independence (spec 7.2): segmentation data and loop
620 // filter deltas go back to their defaults before this header codes
621 // over them, and the frame context index is forced to 0.
622 self.segmentation = SegmentationParams::default();
623 self.loop_filter = LoopFilterParams::default();
624 h.frame_context_idx = 0;
625 }
626
627 self.read_loop_filter_params(&mut r, &mut h)?;
628 read_quantization_params(&mut r, &mut h)?;
629 self.read_segmentation_params(&mut r, &mut h)?;
630 read_tile_info(&mut r, &mut h)?;
631 h.header_size_in_bytes = r.read_bits(16)? as u16;
632 if h.header_size_in_bytes == 0 {
633 return Err(Error::corrupt("VP9 header_size_in_bytes is 0"));
634 }
635 h.uncompressed_header_size = header_bytes(&r);
636
637 self.apply_refresh(&h);
638 Ok(h)
639 }
640
641 /// Reference update (spec 8.10): store this frame into every slot its
642 /// `refresh_frame_flags` names.
643 fn apply_refresh(&mut self, h: &FrameHeader) {
644 let slot = ReferenceSlot {
645 valid: true,
646 width: h.width,
647 height: h.height,
648 bit_depth: h.bit_depth,
649 subsampling_x: h.subsampling_x,
650 subsampling_y: h.subsampling_y,
651 };
652 for (i, dst) in self.refs.iter_mut().enumerate() {
653 if h.refresh_frame_flags & (1 << i) != 0 {
654 *dst = slot;
655 }
656 }
657 }
658
659 /// `frame_size_with_refs` (spec 6.2): take the size from the first reference
660 /// that claims it, else code it outright.
661 fn read_frame_size_with_refs(&self, r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
662 let mut found = false;
663 for i in 0..REFS_PER_FRAME {
664 if r.read_bit()? {
665 let slot = &self.refs[h.ref_frame_idx[i] as usize];
666 if !slot.valid {
667 return Err(Error::corrupt(format!(
668 "VP9 frame_size_with_refs names empty reference slot {}",
669 h.ref_frame_idx[i]
670 )));
671 }
672 h.width = slot.width;
673 h.height = slot.height;
674 found = true;
675 break;
676 }
677 }
678 if !found {
679 read_frame_size(r, h)?;
680 }
681 read_render_size(r, h)
682 }
683
684 fn read_loop_filter_params(
685 &mut self,
686 r: &mut BitReader<'_>,
687 h: &mut FrameHeader,
688 ) -> Result<()> {
689 let lf = &mut self.loop_filter;
690 lf.level = r.read_bits(6)? as u8;
691 lf.sharpness = r.read_bits(3)? as u8;
692 lf.delta_enabled = r.read_bit()?;
693 lf.delta_update = false;
694 if lf.delta_enabled {
695 lf.delta_update = r.read_bit()?;
696 if lf.delta_update {
697 for delta in lf.ref_deltas.iter_mut() {
698 if r.read_bit()? {
699 *delta = read_signed_magnitude(r, 6)? as i8;
700 }
701 }
702 for delta in lf.mode_deltas.iter_mut() {
703 if r.read_bit()? {
704 *delta = read_signed_magnitude(r, 6)? as i8;
705 }
706 }
707 }
708 }
709 h.loop_filter = *lf;
710 Ok(())
711 }
712
713 fn read_segmentation_params(
714 &mut self,
715 r: &mut BitReader<'_>,
716 h: &mut FrameHeader,
717 ) -> Result<()> {
718 let seg = &mut self.segmentation;
719 seg.enabled = r.read_bit()?;
720 seg.update_map = false;
721 seg.temporal_update = false;
722 seg.update_data = false;
723 if seg.enabled {
724 seg.update_map = r.read_bit()?;
725 if seg.update_map {
726 for prob in seg.tree_probs.iter_mut() {
727 *prob = if r.read_bit()? {
728 r.read_bits(8)? as u8
729 } else {
730 255
731 };
732 }
733 seg.temporal_update = r.read_bit()?;
734 for prob in seg.pred_probs.iter_mut() {
735 *prob = if seg.temporal_update && r.read_bit()? {
736 r.read_bits(8)? as u8
737 } else {
738 255
739 };
740 }
741 }
742 seg.update_data = r.read_bit()?;
743 if seg.update_data {
744 seg.abs_or_delta_update = r.read_bit()?;
745 for segment in 0..MAX_SEGMENTS {
746 for feature in 0..SEG_LVL_MAX {
747 let enabled = r.read_bit()?;
748 seg.feature_enabled[segment][feature] = enabled;
749 let mut value = 0i32;
750 if enabled {
751 let bits = SEG_FEATURE_BITS[feature];
752 if bits > 0 {
753 value = r.read_bits(bits)? as i32;
754 }
755 if SEG_FEATURE_SIGNED[feature] && r.read_bit()? {
756 value = -value;
757 }
758 }
759 seg.feature_data[segment][feature] = value as i16;
760 }
761 }
762 }
763 }
764 h.segmentation = *seg;
765 Ok(())
766 }
767}
768
769/// Bytes consumed so far, rounded up — the uncompressed header is byte-aligned
770/// at its end by construction, but rounding keeps a corrupt stream honest.
771fn header_bytes(r: &BitReader<'_>) -> u8 {
772 u8::try_from(r.bit_position().div_ceil(8)).unwrap_or(u8::MAX)
773}
774
775fn read_sync_code(r: &mut BitReader<'_>) -> Result<()> {
776 let code = [
777 r.read_bits(8)? as u8,
778 r.read_bits(8)? as u8,
779 r.read_bits(8)? as u8,
780 ];
781 if code != SYNC_CODE {
782 return Err(Error::corrupt(format!(
783 "VP9 frame sync code is {code:02x?}, expected {SYNC_CODE:02x?}"
784 )));
785 }
786 Ok(())
787}
788
789/// `color_config` (spec 6.2).
790fn read_color_config(r: &mut BitReader<'_>, profile: u8, c: &mut ColorConfig) -> Result<()> {
791 c.bit_depth = if profile >= 2 {
792 if r.read_bit()? { 12 } else { 10 }
793 } else {
794 8
795 };
796 c.color_space = ColorSpace::from_code(r.read_bits(3)?);
797 if c.color_space != ColorSpace::Rgb {
798 c.color_range = r.read_bit()?;
799 if profile == 1 || profile == 3 {
800 c.subsampling_x = r.read_bits(1)? as u8;
801 c.subsampling_y = r.read_bits(1)? as u8;
802 if r.read_bit()? {
803 return Err(Error::corrupt("VP9 color_config reserved_zero bit is set"));
804 }
805 } else {
806 c.subsampling_x = 1;
807 c.subsampling_y = 1;
808 }
809 } else {
810 // CS_RGB is 4:4:4 full range, and only profiles 1 and 3 may code it.
811 c.color_range = true;
812 if profile == 1 || profile == 3 {
813 c.subsampling_x = 0;
814 c.subsampling_y = 0;
815 if r.read_bit()? {
816 return Err(Error::corrupt("VP9 color_config reserved_zero bit is set"));
817 }
818 } else {
819 return Err(Error::corrupt(format!(
820 "VP9 CS_RGB is not allowed in profile {profile}"
821 )));
822 }
823 }
824 Ok(())
825}
826
827/// `frame_size` (spec 6.2).
828fn read_frame_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
829 h.width = r.read_bits(16)? + 1;
830 h.height = r.read_bits(16)? + 1;
831 Ok(())
832}
833
834/// `render_size` (spec 6.2).
835fn read_render_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
836 if r.read_bit()? {
837 h.render_width = r.read_bits(16)? + 1;
838 h.render_height = r.read_bits(16)? + 1;
839 } else {
840 h.render_width = h.width;
841 h.render_height = h.height;
842 }
843 Ok(())
844}
845
846/// `read_interpolation_filter` (spec 6.2), including the literal-to-type map.
847fn read_interpolation_filter(r: &mut BitReader<'_>) -> Result<InterpolationFilter> {
848 if r.read_bit()? {
849 return Ok(InterpolationFilter::Switchable);
850 }
851 Ok(match r.read_bits(2)? {
852 0 => InterpolationFilter::EighttapSmooth,
853 1 => InterpolationFilter::Eighttap,
854 2 => InterpolationFilter::EighttapSharp,
855 _ => InterpolationFilter::Bilinear,
856 })
857}
858
859/// `quantization_params` (spec 6.2).
860fn read_quantization_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
861 h.quantization.base_q_idx = r.read_bits(8)? as u8;
862 h.quantization.delta_q_y_dc = read_delta_q(r)?;
863 h.quantization.delta_q_uv_dc = read_delta_q(r)?;
864 h.quantization.delta_q_uv_ac = read_delta_q(r)?;
865 Ok(())
866}
867
868/// `read_delta_q` (spec 6.2): a flag, then a 4-bit magnitude and a sign.
869fn read_delta_q(r: &mut BitReader<'_>) -> Result<i8> {
870 if r.read_bit()? {
871 Ok(read_signed_magnitude(r, 4)? as i8)
872 } else {
873 Ok(0)
874 }
875}
876
877/// `s(n)` (spec 4.10): an `n`-bit magnitude followed by a sign bit.
878fn read_signed_magnitude(r: &mut BitReader<'_>, n: u32) -> Result<i32> {
879 let value = r.read_bits(n)? as i32;
880 Ok(if r.read_bit()? { -value } else { value })
881}
882
883/// `tile_info` (spec 6.2).
884fn read_tile_info(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
885 // libvpx `setup_tile_info`: exactly `max_log2 - min_log2` increment bits
886 // are consumed for columns AND for rows (the encoder always writes the
887 // terminating 0 bit), so both walks mirror `vp9_get_tile_n_bits`.
888 let sb64_cols = h.mi_cols().div_ceil(8);
889 let (min_log2, max_log2) = tile_cols_log2_bounds(sb64_cols);
890 let mut cols_log2 = min_log2;
891 while cols_log2 < max_log2 {
892 if r.read_bit()? {
893 cols_log2 += 1;
894 } else {
895 break;
896 }
897 }
898 // Rows: one bit always codes whether log2_tile_rows is nonzero, and a
899 // second bit only follows when it is (decodeframe.c `setup_tile_info`:
900 // `cm->log2_tile_rows = vpx_rb_read_bit(rb);
901 // if (cm->log2_tile_rows) cm->log2_tile_rows += vpx_rb_read_bit(rb);`).
902 // This is not a min..max walk like the columns side.
903 let mut rows_log2 = 0u8;
904 if r.read_bit()? {
905 rows_log2 = 1 + u8::from(r.read_bit()?);
906 }
907 h.tile_info = TileInfo {
908 cols_log2,
909 rows_log2,
910 };
911 Ok(())
912}
913
914/// `calc_min_log2_tile_cols` / `calc_max_log2_tile_cols` (spec 6.2).
915///
916/// A tile column is at most 64 superblocks wide and at least 4, which is what
917/// pins the range the increment bits then walk. The bounds are INCLUSIVE:
918/// libvpx consumes exactly `max_log2 - min_log2` increment bits (the encoder
919/// always writes the terminating 0), so `max_log2` itself is returned here.
920fn tile_cols_log2_bounds(sb64_cols: u32) -> (u8, u8) {
921 const MAX_TILE_WIDTH_B64: u32 = 64;
922 const MIN_TILE_WIDTH_B64: u32 = 4;
923 let mut min_log2 = 0u8;
924 while (MAX_TILE_WIDTH_B64 << min_log2) < sb64_cols {
925 min_log2 += 1;
926 }
927 let mut max_log2 = 1u8;
928 while (sb64_cols >> max_log2) >= MIN_TILE_WIDTH_B64 {
929 max_log2 += 1;
930 }
931 // libvpx `get_max_log2_tile_cols` returns max_log2 - 1 (tile_common.c:48).
932 let max_log2 = max_log2 - 1;
933 (min_log2, max_log2)
934}
935
936#[cfg(test)]
937mod tests {
938 use super::*;
939
940 /// Spec 6.2 worked bounds, with libvpx's `max_log2 - 1`
941 /// (`vp9_tile_common.c:45-49`): 1920 wide is 30 superblocks; a column must
942 /// stay at least 4 superblocks wide, so `max_log2_tile_cols` is 2 and the
943 /// decoder consumes `max - min = 2` increment bits.
944 #[test]
945 fn tile_bounds_match_the_spec_formulas() {
946 assert_eq!(
947 tile_cols_log2_bounds(1920u32.div_ceil(8).div_ceil(8)),
948 (0, 2)
949 );
950 assert_eq!(
951 tile_cols_log2_bounds(3840u32.div_ceil(8).div_ceil(8)),
952 (0, 3)
953 );
954 // 4096 superblocks wide forces at least 2^6 tile columns.
955 assert_eq!(tile_cols_log2_bounds(4096).0, 6);
956 // A single-superblock frame consumes NO increment bit: libvpx loops
957 // `while (max_ones-- && vpx_rb_read_bit(rb))` and `max_ones` is 0.
958 assert_eq!(tile_cols_log2_bounds(1), (0, 0));
959 }
960
961 #[test]
962 fn lossless_needs_every_delta_zero() {
963 let mut q = QuantizationParams::default();
964 assert!(q.lossless());
965 q.delta_q_uv_ac = -1;
966 assert!(!q.lossless());
967 q.delta_q_uv_ac = 0;
968 q.base_q_idx = 1;
969 assert!(!q.lossless());
970 }
971
972 #[test]
973 fn filter_levels_apply_deltas_and_clamp() {
974 let mut h = FrameHeader {
975 loop_filter: LoopFilterParams {
976 level: 32,
977 delta_enabled: true,
978 ref_deltas: [1, 0, -1, -1],
979 mode_deltas: [0, 2],
980 ..LoopFilterParams::default()
981 },
982 ..FrameHeader::default()
983 };
984 // lvlSeg 32 -> shift 1: intra 32 + (1<<1) = 34, altref 32 - 2 = 30,
985 // altref with mode delta 2: 30 + 4 = 34.
986 let levels = h.loop_filter_levels(0);
987 assert_eq!(levels[0], [34, 34]);
988 assert_eq!(levels[3], [30, 34]);
989
990 // A segment ALT_L override replaces the frame level before the deltas —
991 // which still apply, so a clamped-to-zero segment is not filter-free.
992 h.segmentation.enabled = true;
993 h.segmentation.feature_enabled[1][SEG_LVL_ALT_L] = true;
994 h.segmentation.feature_data[1][SEG_LVL_ALT_L] = -64;
995 assert_eq!(h.loop_filter_levels(1), [[1, 1], [0, 2], [0, 1], [0, 1]]);
996
997 // Deltas off means one level everywhere.
998 h.loop_filter.delta_enabled = false;
999 assert_eq!(h.loop_filter_levels(0), [[32; 2]; 4]);
1000 }
1001
1002 #[test]
1003 fn segment_qindex_is_absolute_or_relative() {
1004 let mut h = FrameHeader {
1005 quantization: QuantizationParams {
1006 base_q_idx: 100,
1007 ..QuantizationParams::default()
1008 },
1009 ..FrameHeader::default()
1010 };
1011 h.segmentation.enabled = true;
1012 h.segmentation.feature_enabled[2][SEG_LVL_ALT_Q] = true;
1013 h.segmentation.feature_data[2][SEG_LVL_ALT_Q] = -20;
1014 assert_eq!(h.segment_qindex(2), 80);
1015 assert_eq!(h.segment_qindex(0), 100);
1016 h.segmentation.abs_or_delta_update = true;
1017 assert_eq!(h.segment_qindex(2), 0); // clamped up from -20
1018 h.segmentation.feature_data[2][SEG_LVL_ALT_Q] = 200;
1019 assert_eq!(h.segment_qindex(2), 200);
1020 }
1021
1022 #[test]
1023 fn truncated_header_is_need_more_not_panic() {
1024 let mut p = Vp9Parser::new();
1025 for len in 0..12 {
1026 let frame = vec![0x82u8; len];
1027 assert!(p.parse_frame(&frame).is_err());
1028 }
1029 }
1030
1031 #[test]
1032 fn bad_marker_and_sync_code_are_corrupt() {
1033 let mut p = Vp9Parser::new();
1034 assert!(matches!(
1035 p.parse_frame(&[0x00, 0, 0, 0, 0, 0, 0, 0]),
1036 Err(Error::Corrupt { .. })
1037 ));
1038 // marker 2, profile 0, no show_existing, key frame, then a wrong sync code.
1039 assert!(matches!(
1040 p.parse_frame(&[0x80, 0x00, 0x00, 0x00, 0, 0, 0, 0]),
1041 Err(Error::Corrupt { .. })
1042 ));
1043 }
1044}