forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

header.rs1023 lines, 37.0 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
191/// Tile layout (spec 6.2, `tile_info`).
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
193pub struct TileInfo {
194 /// `tile_cols_log2`: the frame has `1 << tile_cols_log2` tile columns.
195 pub cols_log2: u8,
196 /// `tile_rows_log2`: the frame has `1 << tile_rows_log2` tile rows.
197 pub rows_log2: u8,
198}
199
200/// One decoded uncompressed frame header.
201///
202/// Field names follow the spec, so a reader can hold the two side by side. Every
203/// field of `VADecPictureParameterBufferVP9` is either here verbatim or derived
204/// by a method on this type; the two exceptions are the surface ids, which are a
205/// property of the caller's frame pool rather than the bitstream, and the
206/// per-segment dequantization scales, which need the spec 8.6.1 lookup tables.
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct FrameHeader {
209 /// `profile`, 0-3. Profiles 2 and 3 carry more than 8 bits per sample;
210 /// profiles 1 and 3 code their chroma subsampling.
211 pub profile: u8,
212 /// `show_existing_frame`: this frame is a bodiless instruction to output an
213 /// existing reference. No other field below was coded; they hold defaults.
214 pub show_existing_frame: bool,
215 /// `frame_to_show_map_idx`, the reference slot to output. Only meaningful
216 /// when [`FrameHeader::show_existing_frame`] is set.
217 pub frame_to_show_map_idx: u8,
218 /// `frame_type`.
219 pub frame_type: FrameType,
220 /// `show_frame`: this frame is output as well as decoded. Hidden frames
221 /// (ALTREFs) clear it and are shown later by a `show_existing_frame` header.
222 pub show_frame: bool,
223 /// `error_resilient_mode`: probability state is reset, so a decoder may
224 /// start here without the previous frame.
225 pub error_resilient_mode: bool,
226 /// `intra_only`: a non-key frame coded without inter prediction.
227 pub intra_only: bool,
228 /// `FrameIsIntra` (spec 6.2): a keyframe or an intra-only frame.
229 pub frame_is_intra: bool,
230 /// `BitDepth`: 8, 10 or 12.
231 pub bit_depth: u8,
232 /// `color_space`.
233 pub color_space: ColorSpace,
234 /// `color_range`: true for full range (0-255), false for studio swing.
235 pub color_range: bool,
236 /// `subsampling_x`: 1 for 4:2:0 and 4:2:2, 0 for 4:4:4.
237 pub subsampling_x: u8,
238 /// `subsampling_y`: 1 for 4:2:0, 0 for 4:2:2 and 4:4:4.
239 pub subsampling_y: u8,
240 /// `FrameWidth`, the coded width in samples.
241 pub width: u32,
242 /// `FrameHeight`, the coded height in samples.
243 pub height: u32,
244 /// `RenderWidth`, the width the frame should be displayed at.
245 pub render_width: u32,
246 /// `RenderHeight`, the height the frame should be displayed at.
247 pub render_height: u32,
248 /// `refresh_frame_flags`: bit *i* means reference slot *i* is replaced by
249 /// this frame. 0xff on a keyframe.
250 pub refresh_frame_flags: u8,
251 /// `ref_frame_idx[i]`, the reference slot used as LAST, GOLDEN and ALTREF.
252 pub ref_frame_idx: [u8; REFS_PER_FRAME],
253 /// `ref_frame_sign_bias[LAST_FRAME + i]`, in the same order.
254 pub ref_frame_sign_bias: [bool; REFS_PER_FRAME],
255 /// `allow_high_precision_mv`: motion vectors have 1/8-pel precision.
256 pub allow_high_precision_mv: bool,
257 /// `interpolation_filter`.
258 pub interpolation_filter: InterpolationFilter,
259 /// `reset_frame_context`, 0-3.
260 pub reset_frame_context: u8,
261 /// `refresh_frame_context`: the compressed header's probability updates are
262 /// saved back into the frame context.
263 pub refresh_frame_context: bool,
264 /// `frame_parallel_decoding_mode`: no backward probability adaptation.
265 pub frame_parallel_decoding_mode: bool,
266 /// `frame_context_idx`, 0-3, after the reset rules in spec 6.2 are applied.
267 pub frame_context_idx: u8,
268 /// Loop filter parameters in force for this frame.
269 pub loop_filter: LoopFilterParams,
270 /// Quantization parameters for this frame.
271 pub quantization: QuantizationParams,
272 /// Segmentation parameters in force for this frame.
273 pub segmentation: SegmentationParams,
274 /// Tile layout for this frame.
275 pub tile_info: TileInfo,
276 /// `header_size_in_bytes`, the length of the compressed header that follows.
277 /// This is `VASliceParameterBufferVP9`'s partition 0 size, better known as
278 /// `first_partition_size`.
279 pub header_size_in_bytes: u16,
280 /// Length of the uncompressed header itself, in bytes, counting from the
281 /// first byte of the frame. `VADecPictureParameterBufferVP9::frame_header_length_in_bytes`.
282 pub uncompressed_header_size: u8,
283}
284
285impl FrameHeader {
286 /// `get_qindex` (spec 8.6.1): the quantizer index in force for `segment_id`,
287 /// after the segment's `SEG_LVL_ALT_Q` feature is applied.
288 ///
289 /// Feed the result, plus [`QuantizationParams::delta_q_y_dc`] and friends,
290 /// into the spec 8.6.1 `dc_q`/`ac_q` tables to fill
291 /// `VASegmentParameterVP9::{luma,chroma}_{dc,ac}_quant_scale`.
292 pub fn segment_qindex(&self, segment_id: usize) -> u8 {
293 let base = self.quantization.base_q_idx as i32;
294 let seg = &self.segmentation;
295 if !seg.enabled
296 || segment_id >= MAX_SEGMENTS
297 || !seg.feature_enabled[segment_id][SEG_LVL_ALT_Q]
298 {
299 return self.quantization.base_q_idx;
300 }
301 let data = seg.feature_data[segment_id][SEG_LVL_ALT_Q] as i32;
302 let q = if seg.abs_or_delta_update {
303 data
304 } else {
305 base + data
306 };
307 q.clamp(0, 255) as u8
308 }
309
310 /// The four dequantization scales for `segment_id` (spec 8.6.1), which are
311 /// `VASegmentParameterVP9`'s `luma_dc_quant_scale` and its three siblings.
312 pub fn segment_dequant(&self, segment_id: usize) -> SegmentDequant {
313 let q = self.segment_qindex(segment_id) as i32;
314 let depth = self.bit_depth;
315 SegmentDequant {
316 luma_dc: crate::quant::dc_q(depth, q + self.quantization.delta_q_y_dc as i32),
317 luma_ac: crate::quant::ac_q(depth, q),
318 chroma_dc: crate::quant::dc_q(depth, q + self.quantization.delta_q_uv_dc as i32),
319 chroma_ac: crate::quant::ac_q(depth, q + self.quantization.delta_q_uv_ac as i32),
320 }
321 }
322
323 /// The loop filter level table for `segment_id` (spec 8.8.1, "loop filter
324 /// frame init process"), indexed `[reference][mode]` exactly like
325 /// `VASegmentParameterVP9::filter_level`.
326 ///
327 /// Reference 0 is intra, which has no mode delta; the spec writes only
328 /// `[0][0]` and this follows it, leaving `[0][1]` equal to it.
329 pub fn loop_filter_levels(&self, segment_id: usize) -> [[u8; 2]; 4] {
330 let lf = &self.loop_filter;
331 let seg = &self.segmentation;
332 let mut lvl_seg = lf.level as i32;
333 if seg.enabled
334 && segment_id < MAX_SEGMENTS
335 && seg.feature_enabled[segment_id][SEG_LVL_ALT_L]
336 {
337 let data = seg.feature_data[segment_id][SEG_LVL_ALT_L] as i32;
338 let v = if seg.abs_or_delta_update {
339 data
340 } else {
341 lvl_seg + data
342 };
343 lvl_seg = v.clamp(0, MAX_LOOP_FILTER);
344 }
345
346 if !lf.delta_enabled {
347 return [[lvl_seg as u8; 2]; 4];
348 }
349 let shift = lvl_seg >> 5;
350 let mut out = [[0u8; 2]; 4];
351 let intra =
352 (lvl_seg + ((lf.ref_deltas[0] as i32) << shift)).clamp(0, MAX_LOOP_FILTER) as u8;
353 out[0] = [intra, intra];
354 for (reference, levels) in out.iter_mut().enumerate().skip(1) {
355 for (mode, slot) in levels.iter_mut().enumerate() {
356 let level = lvl_seg
357 + ((lf.ref_deltas[reference] as i32) << shift)
358 + ((lf.mode_deltas[mode] as i32) << shift);
359 *slot = level.clamp(0, MAX_LOOP_FILTER) as u8;
360 }
361 }
362 out
363 }
364
365 /// `MiCols` (spec 6.2, `compute_image_size`): the frame width in 8x8 blocks.
366 pub fn mi_cols(&self) -> u32 {
367 self.width.div_ceil(8)
368 }
369
370 /// `MiRows`: the frame height in 8x8 blocks.
371 pub fn mi_rows(&self) -> u32 {
372 self.height.div_ceil(8)
373 }
374}
375
376impl Default for FrameHeader {
377 fn default() -> FrameHeader {
378 FrameHeader {
379 profile: 0,
380 show_existing_frame: false,
381 frame_to_show_map_idx: 0,
382 frame_type: FrameType::Key,
383 show_frame: true,
384 error_resilient_mode: false,
385 intra_only: false,
386 frame_is_intra: true,
387 bit_depth: 8,
388 color_space: ColorSpace::Unknown,
389 color_range: false,
390 subsampling_x: 1,
391 subsampling_y: 1,
392 width: 0,
393 height: 0,
394 render_width: 0,
395 render_height: 0,
396 refresh_frame_flags: 0,
397 ref_frame_idx: [0; REFS_PER_FRAME],
398 ref_frame_sign_bias: [false; REFS_PER_FRAME],
399 allow_high_precision_mv: false,
400 interpolation_filter: InterpolationFilter::Eighttap,
401 reset_frame_context: 0,
402 refresh_frame_context: false,
403 frame_parallel_decoding_mode: false,
404 frame_context_idx: 0,
405 loop_filter: LoopFilterParams::default(),
406 quantization: QuantizationParams::default(),
407 segmentation: SegmentationParams::default(),
408 tile_info: TileInfo::default(),
409 header_size_in_bytes: 0,
410 uncompressed_header_size: 0,
411 }
412 }
413}
414
415/// The per-segment dequantization scales of spec 8.6.1, in the shape
416/// `VASegmentParameterVP9` asks for them.
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418pub struct SegmentDequant {
419 /// `luma_dc_quant_scale`: `dc_q(qindex + delta_q_y_dc)`.
420 pub luma_dc: i16,
421 /// `luma_ac_quant_scale`: `ac_q(qindex)`.
422 pub luma_ac: i16,
423 /// `chroma_dc_quant_scale`: `dc_q(qindex + delta_q_uv_dc)`.
424 pub chroma_dc: i16,
425 /// `chroma_ac_quant_scale`: `ac_q(qindex + delta_q_uv_ac)`.
426 pub chroma_ac: i16,
427}
428
429/// Sample format, as last coded by a keyframe or intra-only frame.
430///
431/// Inter frames do not code `color_config`; they inherit it. A picture parameter
432/// buffer needs `bit_depth` and the subsampling for *every* frame, so the parser
433/// carries the last one seen and stamps it onto the frames that omit it.
434#[derive(Debug, Clone, Copy, PartialEq, Eq)]
435struct ColorConfig {
436 bit_depth: u8,
437 color_space: ColorSpace,
438 color_range: bool,
439 subsampling_x: u8,
440 subsampling_y: u8,
441}
442
443impl ColorConfig {
444 /// Stamp the sample format onto a header being parsed.
445 fn apply(&self, h: &mut FrameHeader) {
446 h.bit_depth = self.bit_depth;
447 h.color_space = self.color_space;
448 h.color_range = self.color_range;
449 h.subsampling_x = self.subsampling_x;
450 h.subsampling_y = self.subsampling_y;
451 }
452}
453
454impl Default for ColorConfig {
455 fn default() -> ColorConfig {
456 ColorConfig {
457 bit_depth: 8,
458 color_space: ColorSpace::Unknown,
459 color_range: false,
460 subsampling_x: 1,
461 subsampling_y: 1,
462 }
463 }
464}
465
466/// What the parser remembers about a reference slot: enough to answer
467/// `frame_size_with_refs`, and enough for a caller to size its surfaces.
468#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
469pub struct ReferenceSlot {
470 /// Whether any frame has been stored in this slot yet.
471 pub valid: bool,
472 /// `RefFrameWidth`.
473 pub width: u32,
474 /// `RefFrameHeight`.
475 pub height: u32,
476 /// `RefBitDepth`.
477 pub bit_depth: u8,
478 /// `RefSubsamplingX`.
479 pub subsampling_x: u8,
480 /// `RefSubsamplingY`.
481 pub subsampling_y: u8,
482}
483
484/// A VP9 header parser holding the state the format carries between frames.
485///
486/// Feed it every frame of a stream in order — [`crate::superframe::split`] first,
487/// since a chunk may hold several — and it applies the reference refresh after
488/// each one.
489#[derive(Debug, Clone, Default)]
490pub struct Vp9Parser {
491 refs: [ReferenceSlot; NUM_REF_FRAMES],
492 segmentation: SegmentationParams,
493 loop_filter: LoopFilterParams,
494 color: ColorConfig,
495}
496
497impl Vp9Parser {
498 /// A parser with no reference state, as at the start of a stream.
499 pub fn new() -> Vp9Parser {
500 Vp9Parser {
501 refs: [ReferenceSlot::default(); NUM_REF_FRAMES],
502 segmentation: SegmentationParams::default(),
503 loop_filter: LoopFilterParams::default(),
504 color: ColorConfig::default(),
505 }
506 }
507
508 /// The reference slots as they stand, after every frame parsed so far.
509 pub fn reference_slots(&self) -> &[ReferenceSlot; NUM_REF_FRAMES] {
510 &self.refs
511 }
512
513 /// Parse one frame's uncompressed header and apply its reference refresh.
514 ///
515 /// `frame` starts at the frame marker, i.e. it is one element of
516 /// [`crate::superframe::split`]'s output.
517 pub fn parse_frame(&mut self, frame: &[u8]) -> Result<FrameHeader> {
518 let mut r = BitReader::new(frame);
519 let mut h = FrameHeader::default();
520
521 let marker = r.read_bits(2)?;
522 if marker != 2 {
523 return Err(Error::corrupt(format!(
524 "VP9 frame marker is {marker}, expected 2"
525 )));
526 }
527 let profile_low = r.read_bits(1)?;
528 let profile_high = r.read_bits(1)?;
529 h.profile = ((profile_high << 1) | profile_low) as u8;
530 if h.profile == 3 && r.read_bit()? {
531 return Err(Error::corrupt("VP9 profile 3 reserved_zero bit is set"));
532 }
533
534 h.show_existing_frame = r.read_bit()?;
535 if h.show_existing_frame {
536 h.frame_to_show_map_idx = r.read_bits(3)? as u8;
537 let slot = &self.refs[h.frame_to_show_map_idx as usize];
538 h.width = slot.width;
539 h.height = slot.height;
540 h.render_width = slot.width;
541 h.render_height = slot.height;
542 self.color.apply(&mut h);
543 h.show_frame = true;
544 h.uncompressed_header_size = header_bytes(&r);
545 return Ok(h);
546 }
547
548 h.frame_type = if r.read_bit()? {
549 FrameType::Inter
550 } else {
551 FrameType::Key
552 };
553 h.show_frame = r.read_bit()?;
554 h.error_resilient_mode = r.read_bit()?;
555
556 if h.frame_type == FrameType::Key {
557 read_sync_code(&mut r)?;
558 read_color_config(&mut r, h.profile, &mut self.color)?;
559 self.color.apply(&mut h);
560 read_frame_size(&mut r, &mut h)?;
561 read_render_size(&mut r, &mut h)?;
562 h.refresh_frame_flags = 0xff;
563 h.frame_is_intra = true;
564 } else {
565 h.intra_only = if h.show_frame { false } else { r.read_bit()? };
566 h.frame_is_intra = h.intra_only;
567 if !h.error_resilient_mode {
568 h.reset_frame_context = r.read_bits(2)? as u8;
569 }
570 if h.intra_only {
571 read_sync_code(&mut r)?;
572 if h.profile > 0 {
573 read_color_config(&mut r, h.profile, &mut self.color)?;
574 } else {
575 // Profile 0 intra-only is 8-bit 4:2:0 BT.601 by definition.
576 self.color = ColorConfig {
577 bit_depth: 8,
578 color_space: ColorSpace::Bt601,
579 color_range: false,
580 subsampling_x: 1,
581 subsampling_y: 1,
582 };
583 }
584 self.color.apply(&mut h);
585 h.refresh_frame_flags = r.read_bits(8)? as u8;
586 read_frame_size(&mut r, &mut h)?;
587 read_render_size(&mut r, &mut h)?;
588 } else {
589 // An inter frame codes no color_config; it inherits the one the
590 // last keyframe or intra-only frame set.
591 self.color.apply(&mut h);
592 h.refresh_frame_flags = r.read_bits(8)? as u8;
593 for i in 0..REFS_PER_FRAME {
594 h.ref_frame_idx[i] = r.read_bits(3)? as u8;
595 h.ref_frame_sign_bias[i] = r.read_bit()?;
596 }
597 self.read_frame_size_with_refs(&mut r, &mut h)?;
598 h.allow_high_precision_mv = r.read_bit()?;
599 h.interpolation_filter = read_interpolation_filter(&mut r)?;
600 }
601 }
602
603 if !h.error_resilient_mode {
604 h.refresh_frame_context = r.read_bit()?;
605 h.frame_parallel_decoding_mode = r.read_bit()?;
606 } else {
607 h.refresh_frame_context = false;
608 h.frame_parallel_decoding_mode = true;
609 }
610 h.frame_context_idx = r.read_bits(2)? as u8;
611
612 if h.frame_is_intra || h.error_resilient_mode {
613 // setup_past_independence (spec 7.2): segmentation data and loop
614 // filter deltas go back to their defaults before this header codes
615 // over them, and the frame context index is forced to 0.
616 self.segmentation = SegmentationParams::default();
617 self.loop_filter = LoopFilterParams::default();
618 h.frame_context_idx = 0;
619 }
620
621 self.read_loop_filter_params(&mut r, &mut h)?;
622 read_quantization_params(&mut r, &mut h)?;
623 self.read_segmentation_params(&mut r, &mut h)?;
624 read_tile_info(&mut r, &mut h)?;
625 h.header_size_in_bytes = r.read_bits(16)? as u16;
626 if h.header_size_in_bytes == 0 {
627 return Err(Error::corrupt("VP9 header_size_in_bytes is 0"));
628 }
629 h.uncompressed_header_size = header_bytes(&r);
630
631 self.apply_refresh(&h);
632 Ok(h)
633 }
634
635 /// Reference update (spec 8.10): store this frame into every slot its
636 /// `refresh_frame_flags` names.
637 fn apply_refresh(&mut self, h: &FrameHeader) {
638 let slot = ReferenceSlot {
639 valid: true,
640 width: h.width,
641 height: h.height,
642 bit_depth: h.bit_depth,
643 subsampling_x: h.subsampling_x,
644 subsampling_y: h.subsampling_y,
645 };
646 for i in 0..NUM_REF_FRAMES {
647 if h.refresh_frame_flags & (1 << i) != 0 {
648 self.refs[i] = slot;
649 }
650 }
651 }
652
653 /// `frame_size_with_refs` (spec 6.2): take the size from the first reference
654 /// that claims it, else code it outright.
655 fn read_frame_size_with_refs(&self, r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
656 let mut found = false;
657 for i in 0..REFS_PER_FRAME {
658 if r.read_bit()? {
659 let slot = &self.refs[h.ref_frame_idx[i] as usize];
660 if !slot.valid {
661 return Err(Error::corrupt(format!(
662 "VP9 frame_size_with_refs names empty reference slot {}",
663 h.ref_frame_idx[i]
664 )));
665 }
666 h.width = slot.width;
667 h.height = slot.height;
668 found = true;
669 break;
670 }
671 }
672 if !found {
673 read_frame_size(r, h)?;
674 }
675 read_render_size(r, h)
676 }
677
678 fn read_loop_filter_params(
679 &mut self,
680 r: &mut BitReader<'_>,
681 h: &mut FrameHeader,
682 ) -> Result<()> {
683 let lf = &mut self.loop_filter;
684 lf.level = r.read_bits(6)? as u8;
685 lf.sharpness = r.read_bits(3)? as u8;
686 lf.delta_enabled = r.read_bit()?;
687 lf.delta_update = false;
688 if lf.delta_enabled {
689 lf.delta_update = r.read_bit()?;
690 if lf.delta_update {
691 for delta in lf.ref_deltas.iter_mut() {
692 if r.read_bit()? {
693 *delta = read_signed_magnitude(r, 6)? as i8;
694 }
695 }
696 for delta in lf.mode_deltas.iter_mut() {
697 if r.read_bit()? {
698 *delta = read_signed_magnitude(r, 6)? as i8;
699 }
700 }
701 }
702 }
703 h.loop_filter = *lf;
704 Ok(())
705 }
706
707 fn read_segmentation_params(
708 &mut self,
709 r: &mut BitReader<'_>,
710 h: &mut FrameHeader,
711 ) -> Result<()> {
712 let seg = &mut self.segmentation;
713 seg.enabled = r.read_bit()?;
714 seg.update_map = false;
715 seg.temporal_update = false;
716 seg.update_data = false;
717 if seg.enabled {
718 seg.update_map = r.read_bit()?;
719 if seg.update_map {
720 for prob in seg.tree_probs.iter_mut() {
721 *prob = if r.read_bit()? {
722 r.read_bits(8)? as u8
723 } else {
724 255
725 };
726 }
727 seg.temporal_update = r.read_bit()?;
728 for prob in seg.pred_probs.iter_mut() {
729 *prob = if seg.temporal_update && r.read_bit()? {
730 r.read_bits(8)? as u8
731 } else {
732 255
733 };
734 }
735 }
736 seg.update_data = r.read_bit()?;
737 if seg.update_data {
738 seg.abs_or_delta_update = r.read_bit()?;
739 for segment in 0..MAX_SEGMENTS {
740 for feature in 0..SEG_LVL_MAX {
741 let enabled = r.read_bit()?;
742 seg.feature_enabled[segment][feature] = enabled;
743 let mut value = 0i32;
744 if enabled {
745 let bits = SEG_FEATURE_BITS[feature];
746 if bits > 0 {
747 value = r.read_bits(bits)? as i32;
748 }
749 if SEG_FEATURE_SIGNED[feature] && r.read_bit()? {
750 value = -value;
751 }
752 }
753 seg.feature_data[segment][feature] = value as i16;
754 }
755 }
756 }
757 }
758 h.segmentation = *seg;
759 Ok(())
760 }
761}
762
763/// Bytes consumed so far, rounded up — the uncompressed header is byte-aligned
764/// at its end by construction, but rounding keeps a corrupt stream honest.
765fn header_bytes(r: &BitReader<'_>) -> u8 {
766 u8::try_from(r.bit_position().div_ceil(8)).unwrap_or(u8::MAX)
767}
768
769fn read_sync_code(r: &mut BitReader<'_>) -> Result<()> {
770 let code = [
771 r.read_bits(8)? as u8,
772 r.read_bits(8)? as u8,
773 r.read_bits(8)? as u8,
774 ];
775 if code != SYNC_CODE {
776 return Err(Error::corrupt(format!(
777 "VP9 frame sync code is {code:02x?}, expected {SYNC_CODE:02x?}"
778 )));
779 }
780 Ok(())
781}
782
783/// `color_config` (spec 6.2).
784fn read_color_config(r: &mut BitReader<'_>, profile: u8, c: &mut ColorConfig) -> Result<()> {
785 c.bit_depth = if profile >= 2 {
786 if r.read_bit()? { 12 } else { 10 }
787 } else {
788 8
789 };
790 c.color_space = ColorSpace::from_code(r.read_bits(3)?);
791 if c.color_space != ColorSpace::Rgb {
792 c.color_range = r.read_bit()?;
793 if profile == 1 || profile == 3 {
794 c.subsampling_x = r.read_bits(1)? as u8;
795 c.subsampling_y = r.read_bits(1)? as u8;
796 if r.read_bit()? {
797 return Err(Error::corrupt("VP9 color_config reserved_zero bit is set"));
798 }
799 } else {
800 c.subsampling_x = 1;
801 c.subsampling_y = 1;
802 }
803 } else {
804 // CS_RGB is 4:4:4 full range, and only profiles 1 and 3 may code it.
805 c.color_range = true;
806 if profile == 1 || profile == 3 {
807 c.subsampling_x = 0;
808 c.subsampling_y = 0;
809 if r.read_bit()? {
810 return Err(Error::corrupt("VP9 color_config reserved_zero bit is set"));
811 }
812 } else {
813 return Err(Error::corrupt(format!(
814 "VP9 CS_RGB is not allowed in profile {profile}"
815 )));
816 }
817 }
818 Ok(())
819}
820
821/// `frame_size` (spec 6.2).
822fn read_frame_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
823 h.width = r.read_bits(16)? + 1;
824 h.height = r.read_bits(16)? + 1;
825 Ok(())
826}
827
828/// `render_size` (spec 6.2).
829fn read_render_size(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
830 if r.read_bit()? {
831 h.render_width = r.read_bits(16)? + 1;
832 h.render_height = r.read_bits(16)? + 1;
833 } else {
834 h.render_width = h.width;
835 h.render_height = h.height;
836 }
837 Ok(())
838}
839
840/// `read_interpolation_filter` (spec 6.2), including the literal-to-type map.
841fn read_interpolation_filter(r: &mut BitReader<'_>) -> Result<InterpolationFilter> {
842 if r.read_bit()? {
843 return Ok(InterpolationFilter::Switchable);
844 }
845 Ok(match r.read_bits(2)? {
846 0 => InterpolationFilter::EighttapSmooth,
847 1 => InterpolationFilter::Eighttap,
848 2 => InterpolationFilter::EighttapSharp,
849 _ => InterpolationFilter::Bilinear,
850 })
851}
852
853/// `quantization_params` (spec 6.2).
854fn read_quantization_params(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
855 h.quantization.base_q_idx = r.read_bits(8)? as u8;
856 h.quantization.delta_q_y_dc = read_delta_q(r)?;
857 h.quantization.delta_q_uv_dc = read_delta_q(r)?;
858 h.quantization.delta_q_uv_ac = read_delta_q(r)?;
859 Ok(())
860}
861
862/// `read_delta_q` (spec 6.2): a flag, then a 4-bit magnitude and a sign.
863fn read_delta_q(r: &mut BitReader<'_>) -> Result<i8> {
864 if r.read_bit()? {
865 Ok(read_signed_magnitude(r, 4)? as i8)
866 } else {
867 Ok(0)
868 }
869}
870
871/// `s(n)` (spec 4.10): an `n`-bit magnitude followed by a sign bit.
872fn read_signed_magnitude(r: &mut BitReader<'_>, n: u32) -> Result<i32> {
873 let value = r.read_bits(n)? as i32;
874 Ok(if r.read_bit()? { -value } else { value })
875}
876
877/// `tile_info` (spec 6.2).
878fn read_tile_info(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> {
879 let sb64_cols = h.mi_cols().div_ceil(8);
880 let (min_log2, max_log2) = tile_cols_log2_bounds(sb64_cols);
881 let mut cols_log2 = min_log2;
882 while cols_log2 < max_log2 {
883 if r.read_bit()? {
884 cols_log2 += 1;
885 } else {
886 break;
887 }
888 }
889 let mut rows_log2 = u8::from(r.read_bit()?);
890 if rows_log2 > 0 && r.read_bit()? {
891 rows_log2 += 1;
892 }
893 h.tile_info = TileInfo {
894 cols_log2,
895 rows_log2,
896 };
897 Ok(())
898}
899
900/// `calc_min_log2_tile_cols` / `calc_max_log2_tile_cols` (spec 6.2).
901///
902/// A tile column is at most 64 superblocks wide and at least 4, which is what
903/// pins the range the increment bits then walk.
904fn tile_cols_log2_bounds(sb64_cols: u32) -> (u8, u8) {
905 const MAX_TILE_WIDTH_B64: u32 = 64;
906 const MIN_TILE_WIDTH_B64: u32 = 4;
907 let mut min_log2 = 0u8;
908 while (MAX_TILE_WIDTH_B64 << min_log2) < sb64_cols {
909 min_log2 += 1;
910 }
911 let mut max_log2 = 1u8;
912 while (sb64_cols >> max_log2) >= MIN_TILE_WIDTH_B64 {
913 max_log2 += 1;
914 }
915 (min_log2, max_log2 - 1)
916}
917
918#[cfg(test)]
919mod tests {
920 use super::*;
921
922 /// Spec 6.2 worked bounds: 1920 wide is 30 superblocks, so tile columns may
923 /// go up to 2^2 (a column must stay at least 4 superblocks wide) and none
924 /// are forced (a column may be up to 64 superblocks wide).
925 #[test]
926 fn tile_bounds_match_the_spec_formulas() {
927 assert_eq!(
928 tile_cols_log2_bounds(1920u32.div_ceil(8).div_ceil(8)),
929 (0, 2)
930 );
931 assert_eq!(
932 tile_cols_log2_bounds(3840u32.div_ceil(8).div_ceil(8)),
933 (0, 3)
934 );
935 // 4096 superblocks wide forces at least 2^6 tile columns.
936 assert_eq!(tile_cols_log2_bounds(4096).0, 6);
937 assert_eq!(tile_cols_log2_bounds(1), (0, 0));
938 }
939
940 #[test]
941 fn lossless_needs_every_delta_zero() {
942 let mut q = QuantizationParams::default();
943 assert!(q.lossless());
944 q.delta_q_uv_ac = -1;
945 assert!(!q.lossless());
946 q.delta_q_uv_ac = 0;
947 q.base_q_idx = 1;
948 assert!(!q.lossless());
949 }
950
951 #[test]
952 fn filter_levels_apply_deltas_and_clamp() {
953 let mut h = FrameHeader {
954 loop_filter: LoopFilterParams {
955 level: 32,
956 delta_enabled: true,
957 ref_deltas: [1, 0, -1, -1],
958 mode_deltas: [0, 2],
959 ..LoopFilterParams::default()
960 },
961 ..FrameHeader::default()
962 };
963 // lvlSeg 32 -> shift 1: intra 32 + (1<<1) = 34, altref 32 - 2 = 30,
964 // altref with mode delta 2: 30 + 4 = 34.
965 let levels = h.loop_filter_levels(0);
966 assert_eq!(levels[0], [34, 34]);
967 assert_eq!(levels[3], [30, 34]);
968
969 // A segment ALT_L override replaces the frame level before the deltas —
970 // which still apply, so a clamped-to-zero segment is not filter-free.
971 h.segmentation.enabled = true;
972 h.segmentation.feature_enabled[1][SEG_LVL_ALT_L] = true;
973 h.segmentation.feature_data[1][SEG_LVL_ALT_L] = -64;
974 assert_eq!(h.loop_filter_levels(1), [[1, 1], [0, 2], [0, 1], [0, 1]]);
975
976 // Deltas off means one level everywhere.
977 h.loop_filter.delta_enabled = false;
978 assert_eq!(h.loop_filter_levels(0), [[32; 2]; 4]);
979 }
980
981 #[test]
982 fn segment_qindex_is_absolute_or_relative() {
983 let mut h = FrameHeader {
984 quantization: QuantizationParams {
985 base_q_idx: 100,
986 ..QuantizationParams::default()
987 },
988 ..FrameHeader::default()
989 };
990 h.segmentation.enabled = true;
991 h.segmentation.feature_enabled[2][SEG_LVL_ALT_Q] = true;
992 h.segmentation.feature_data[2][SEG_LVL_ALT_Q] = -20;
993 assert_eq!(h.segment_qindex(2), 80);
994 assert_eq!(h.segment_qindex(0), 100);
995 h.segmentation.abs_or_delta_update = true;
996 assert_eq!(h.segment_qindex(2), 0); // clamped up from -20
997 h.segmentation.feature_data[2][SEG_LVL_ALT_Q] = 200;
998 assert_eq!(h.segment_qindex(2), 200);
999 }
1000
1001 #[test]
1002 fn truncated_header_is_need_more_not_panic() {
1003 let mut p = Vp9Parser::new();
1004 for len in 0..12 {
1005 let frame = vec![0x82u8; len];
1006 assert!(p.parse_frame(&frame).is_err());
1007 }
1008 }
1009
1010 #[test]
1011 fn bad_marker_and_sync_code_are_corrupt() {
1012 let mut p = Vp9Parser::new();
1013 assert!(matches!(
1014 p.parse_frame(&[0x00, 0, 0, 0, 0, 0, 0, 0]),
1015 Err(Error::Corrupt { .. })
1016 ));
1017 // marker 2, profile 0, no show_existing, key frame, then a wrong sync code.
1018 assert!(matches!(
1019 p.parse_frame(&[0x80, 0x00, 0x00, 0x00, 0, 0, 0, 0]),
1020 Err(Error::Corrupt { .. })
1021 ));
1022 }
1023}