forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB24272c3Tahinli3 months ago336 commits

sequence.rs540 lines, 19.8 KiBHistoryRawDownload
1//! The sequence header OBU (spec 5.5).
2
3use ec_core::{BitReader, Error, Result};
4
5use crate::obu::{read_leb128, read_uvlc};
6
7/// `SELECT_SCREEN_CONTENT_TOOLS` and `SELECT_INTEGER_MV` (spec 3): "the frame
8/// header decides", rather than a value forced by the sequence.
9pub const SELECT_SCREEN_CONTENT_TOOLS: u8 = 2;
10/// See [`SELECT_SCREEN_CONTENT_TOOLS`].
11pub const SELECT_INTEGER_MV: u8 = 2;
12
13/// `timing_info()` (spec 5.5.3).
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct TimingInfo {
16 /// `num_units_in_display_tick`.
17 pub num_units_in_display_tick: u32,
18 /// `time_scale`.
19 pub time_scale: u32,
20 /// `equal_picture_interval`: every frame is displayed for the same time,
21 /// which is what makes [`TimingInfo::num_ticks_per_picture`] meaningful.
22 pub equal_picture_interval: bool,
23 /// `num_ticks_per_picture_minus_1 + 1`, or 0 when not coded.
24 pub num_ticks_per_picture: u32,
25}
26
27/// `decoder_model_info()` (spec 5.5.4).
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct DecoderModelInfo {
30 /// `buffer_delay_length_minus_1 + 1`.
31 pub buffer_delay_length: u32,
32 /// `num_units_in_decoding_tick`.
33 pub num_units_in_decoding_tick: u32,
34 /// `buffer_removal_time_length_minus_1 + 1`.
35 pub buffer_removal_time_length: u32,
36 /// `frame_presentation_time_length_minus_1 + 1`.
37 pub frame_presentation_time_length: u32,
38}
39
40/// One entry of the operating point list (spec 5.5.1).
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub struct OperatingPoint {
43 /// `operating_point_idc`: which spatial and temporal layers this point has.
44 pub idc: u32,
45 /// `seq_level_idx`.
46 pub seq_level_idx: u8,
47 /// `seq_tier`.
48 pub seq_tier: u8,
49 /// `decoder_model_present_for_this_op`.
50 pub decoder_model_present: bool,
51 /// `decoder_buffer_delay`, when the decoder model is present.
52 pub decoder_buffer_delay: u32,
53 /// `encoder_buffer_delay`, when the decoder model is present.
54 pub encoder_buffer_delay: u32,
55 /// `low_delay_mode_flag`, when the decoder model is present.
56 pub low_delay_mode_flag: bool,
57 /// `initial_display_delay_minus_1 + 1`, or 0 when not coded.
58 pub initial_display_delay: u8,
59}
60
61/// Chroma sample position (spec 6.4.2, `chroma_sample_position`).
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63#[repr(u8)]
64pub enum ChromaSamplePosition {
65 /// `CSP_UNKNOWN`, 0.
66 Unknown = 0,
67 /// `CSP_VERTICAL`, 1 — co-sited horizontally, between rows vertically (MPEG-2).
68 Vertical = 1,
69 /// `CSP_COLOCATED`, 2 — co-sited both ways.
70 Colocated = 2,
71 /// `CSP_RESERVED`, 3.
72 Reserved = 3,
73}
74
75/// `color_config()` (spec 5.5.2).
76///
77/// The three code points are H.273 (CICP) values, the same vocabulary
78/// [`ec_core::color`] speaks, so they can be handed to it unchanged.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub struct ColorConfig {
81 /// `BitDepth`: 8, 10 or 12.
82 pub bit_depth: u8,
83 /// `mono_chrome`: no chroma planes are coded.
84 pub mono_chrome: bool,
85 /// `NumPlanes`: 1 when monochrome, else 3.
86 pub num_planes: u8,
87 /// `color_primaries`, H.273; 2 (unspecified) when not coded.
88 pub color_primaries: u8,
89 /// `transfer_characteristics`, H.273; 2 when not coded.
90 pub transfer_characteristics: u8,
91 /// `matrix_coefficients`, H.273; 2 when not coded.
92 pub matrix_coefficients: u8,
93 /// `color_range`: true for full range.
94 pub color_range: bool,
95 /// `subsampling_x`.
96 pub subsampling_x: u8,
97 /// `subsampling_y`.
98 pub subsampling_y: u8,
99 /// `chroma_sample_position`.
100 pub chroma_sample_position: ChromaSamplePosition,
101 /// `separate_uv_delta_q`: U and V may carry different quantizer deltas.
102 pub separate_uv_delta_q: bool,
103}
104
105impl Default for ColorConfig {
106 fn default() -> ColorConfig {
107 ColorConfig {
108 bit_depth: 8,
109 mono_chrome: false,
110 num_planes: 3,
111 color_primaries: 2,
112 transfer_characteristics: 2,
113 matrix_coefficients: 2,
114 color_range: false,
115 subsampling_x: 1,
116 subsampling_y: 1,
117 chroma_sample_position: ChromaSamplePosition::Unknown,
118 separate_uv_delta_q: false,
119 }
120 }
121}
122
123/// A parsed sequence header OBU (spec 5.5.1).
124///
125/// Everything a frame header needs in order to parse at all lives here: the
126/// frame size field widths, whether order hints exist and how wide they are,
127/// which coding tools the sequence enables. A frame header without its sequence
128/// header is unparseable, which is why [`crate::Av1Parser`] refuses one.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct SequenceHeader {
131 /// `seq_profile`, 0-2. 0 is 4:2:0 8/10-bit, 1 adds 4:4:4, 2 adds 4:2:2 and 12-bit.
132 pub seq_profile: u8,
133 /// `still_picture`: the sequence is a single frame.
134 pub still_picture: bool,
135 /// `reduced_still_picture_header`: the cut-down header a still image uses.
136 pub reduced_still_picture_header: bool,
137 /// `timing_info()`, when present.
138 pub timing_info: Option<TimingInfo>,
139 /// `decoder_model_info()`, when present.
140 pub decoder_model_info: Option<DecoderModelInfo>,
141 /// `initial_display_delay_present_flag`.
142 pub initial_display_delay_present_flag: bool,
143 /// The operating points, at least one.
144 pub operating_points: Vec<OperatingPoint>,
145 /// The operating point this parse selected — always 0, the highest quality
146 /// one, since a stateless decoder here decodes everything it is given.
147 pub operating_point: usize,
148 /// `OperatingPointIdc` of the selected operating point.
149 pub operating_point_idc: u32,
150 /// `frame_width_bits_minus_1 + 1`.
151 pub frame_width_bits: u32,
152 /// `frame_height_bits_minus_1 + 1`.
153 pub frame_height_bits: u32,
154 /// `max_frame_width_minus_1 + 1`.
155 pub max_frame_width: u32,
156 /// `max_frame_height_minus_1 + 1`.
157 pub max_frame_height: u32,
158 /// `frame_id_numbers_present_flag`.
159 pub frame_id_numbers_present_flag: bool,
160 /// `delta_frame_id_length_minus_2 + 2`.
161 pub delta_frame_id_length: u32,
162 /// `additional_frame_id_length_minus_1 + 1`.
163 pub additional_frame_id_length: u32,
164 /// `use_128x128_superblock`.
165 pub use_128x128_superblock: bool,
166 /// `enable_filter_intra`.
167 pub enable_filter_intra: bool,
168 /// `enable_intra_edge_filter`.
169 pub enable_intra_edge_filter: bool,
170 /// `enable_interintra_compound`.
171 pub enable_interintra_compound: bool,
172 /// `enable_masked_compound`.
173 pub enable_masked_compound: bool,
174 /// `enable_warped_motion`.
175 pub enable_warped_motion: bool,
176 /// `enable_dual_filter`.
177 pub enable_dual_filter: bool,
178 /// `enable_order_hint`: without it there is no reference ordering, and half
179 /// the inter tools below switch off.
180 pub enable_order_hint: bool,
181 /// `enable_jnt_comp`.
182 pub enable_jnt_comp: bool,
183 /// `enable_ref_frame_mvs`.
184 pub enable_ref_frame_mvs: bool,
185 /// `seq_force_screen_content_tools`, or [`SELECT_SCREEN_CONTENT_TOOLS`].
186 pub seq_force_screen_content_tools: u8,
187 /// `seq_force_integer_mv`, or [`SELECT_INTEGER_MV`].
188 pub seq_force_integer_mv: u8,
189 /// `OrderHintBits`: 0 when order hints are disabled.
190 pub order_hint_bits: u32,
191 /// `enable_superres`.
192 pub enable_superres: bool,
193 /// `enable_cdef`.
194 pub enable_cdef: bool,
195 /// `enable_restoration`.
196 pub enable_restoration: bool,
197 /// `color_config()`.
198 pub color_config: ColorConfig,
199 /// `film_grain_params_present`.
200 pub film_grain_params_present: bool,
201}
202
203impl SequenceHeader {
204 /// Parse a sequence header OBU payload (spec 5.5.1).
205 pub fn parse(r: &mut BitReader<'_>) -> Result<SequenceHeader> {
206 let seq_profile = r.read_bits(3)? as u8;
207 if seq_profile > 2 {
208 return Err(Error::corrupt(format!(
209 "AV1 seq_profile {seq_profile} is reserved"
210 )));
211 }
212 let still_picture = r.read_bit()?;
213 let reduced_still_picture_header = r.read_bit()?;
214
215 let mut timing_info = None;
216 let mut decoder_model_info = None;
217 let mut initial_display_delay_present_flag = false;
218 let mut operating_points = Vec::new();
219
220 if reduced_still_picture_header {
221 operating_points.push(OperatingPoint {
222 seq_level_idx: r.read_bits(5)? as u8,
223 ..OperatingPoint::default()
224 });
225 } else {
226 if r.read_bit()? {
227 let info = TimingInfo {
228 num_units_in_display_tick: r.read_bits(32)?,
229 time_scale: r.read_bits(32)?,
230 equal_picture_interval: r.read_bit()?,
231 num_ticks_per_picture: 0,
232 };
233 let info = if info.equal_picture_interval {
234 TimingInfo {
235 num_ticks_per_picture: read_uvlc(r)?.saturating_add(1),
236 ..info
237 }
238 } else {
239 info
240 };
241 timing_info = Some(info);
242 if r.read_bit()? {
243 decoder_model_info = Some(DecoderModelInfo {
244 buffer_delay_length: r.read_bits(5)? + 1,
245 num_units_in_decoding_tick: r.read_bits(32)?,
246 buffer_removal_time_length: r.read_bits(5)? + 1,
247 frame_presentation_time_length: r.read_bits(5)? + 1,
248 });
249 }
250 }
251 initial_display_delay_present_flag = r.read_bit()?;
252 let count = r.read_bits(5)? as usize + 1;
253 for _ in 0..count {
254 let idc = r.read_bits(12)?;
255 let seq_level_idx = r.read_bits(5)? as u8;
256 let seq_tier = if seq_level_idx > 7 {
257 r.read_bits(1)? as u8
258 } else {
259 0
260 };
261 let mut op = OperatingPoint {
262 idc,
263 seq_level_idx,
264 seq_tier,
265 ..OperatingPoint::default()
266 };
267 if let Some(model) = decoder_model_info {
268 op.decoder_model_present = r.read_bit()?;
269 if op.decoder_model_present {
270 let n = model.buffer_delay_length;
271 op.decoder_buffer_delay = r.read_bits(n)?;
272 op.encoder_buffer_delay = r.read_bits(n)?;
273 op.low_delay_mode_flag = r.read_bit()?;
274 }
275 }
276 if initial_display_delay_present_flag && r.read_bit()? {
277 op.initial_display_delay = r.read_bits(4)? as u8 + 1;
278 }
279 operating_points.push(op);
280 }
281 }
282
283 // choose_operating_point() (spec 6.4.1): a decoder that outputs every
284 // layer picks 0, the operating point that includes all of them.
285 let operating_point = 0;
286 let operating_point_idc = operating_points[operating_point].idc;
287
288 let frame_width_bits = r.read_bits(4)? + 1;
289 let frame_height_bits = r.read_bits(4)? + 1;
290 let max_frame_width = r.read_bits(frame_width_bits)? + 1;
291 let max_frame_height = r.read_bits(frame_height_bits)? + 1;
292
293 let frame_id_numbers_present_flag = !reduced_still_picture_header && r.read_bit()?;
294 let (delta_frame_id_length, additional_frame_id_length) = if frame_id_numbers_present_flag {
295 (r.read_bits(4)? + 2, r.read_bits(3)? + 1)
296 } else {
297 (0, 0)
298 };
299
300 let use_128x128_superblock = r.read_bit()?;
301 let enable_filter_intra = r.read_bit()?;
302 let enable_intra_edge_filter = r.read_bit()?;
303
304 let mut seq = SequenceHeader {
305 seq_profile,
306 still_picture,
307 reduced_still_picture_header,
308 timing_info,
309 decoder_model_info,
310 initial_display_delay_present_flag,
311 operating_points,
312 operating_point,
313 operating_point_idc,
314 frame_width_bits,
315 frame_height_bits,
316 max_frame_width,
317 max_frame_height,
318 frame_id_numbers_present_flag,
319 delta_frame_id_length,
320 additional_frame_id_length,
321 use_128x128_superblock,
322 enable_filter_intra,
323 enable_intra_edge_filter,
324 enable_interintra_compound: false,
325 enable_masked_compound: false,
326 enable_warped_motion: false,
327 enable_dual_filter: false,
328 enable_order_hint: false,
329 enable_jnt_comp: false,
330 enable_ref_frame_mvs: false,
331 seq_force_screen_content_tools: SELECT_SCREEN_CONTENT_TOOLS,
332 seq_force_integer_mv: SELECT_INTEGER_MV,
333 order_hint_bits: 0,
334 enable_superres: false,
335 enable_cdef: false,
336 enable_restoration: false,
337 color_config: ColorConfig::default(),
338 film_grain_params_present: false,
339 };
340
341 if !reduced_still_picture_header {
342 seq.enable_interintra_compound = r.read_bit()?;
343 seq.enable_masked_compound = r.read_bit()?;
344 seq.enable_warped_motion = r.read_bit()?;
345 seq.enable_dual_filter = r.read_bit()?;
346 seq.enable_order_hint = r.read_bit()?;
347 if seq.enable_order_hint {
348 seq.enable_jnt_comp = r.read_bit()?;
349 seq.enable_ref_frame_mvs = r.read_bit()?;
350 }
351 seq.seq_force_screen_content_tools = if r.read_bit()? {
352 SELECT_SCREEN_CONTENT_TOOLS
353 } else {
354 r.read_bits(1)? as u8
355 };
356 seq.seq_force_integer_mv = if seq.seq_force_screen_content_tools > 0 {
357 if r.read_bit()? {
358 SELECT_INTEGER_MV
359 } else {
360 r.read_bits(1)? as u8
361 }
362 } else {
363 SELECT_INTEGER_MV
364 };
365 if seq.enable_order_hint {
366 seq.order_hint_bits = r.read_bits(3)? + 1;
367 }
368 }
369
370 seq.enable_superres = r.read_bit()?;
371 seq.enable_cdef = r.read_bit()?;
372 seq.enable_restoration = r.read_bit()?;
373 seq.color_config = read_color_config(r, seq_profile)?;
374 seq.film_grain_params_present = r.read_bit()?;
375 Ok(seq)
376 }
377
378 /// `sbShift` (spec 5.9.15): 5 for 128x128 superblocks, 4 for 64x64. Pass it
379 /// to [`crate::TileInfo::width_in_sbs_minus_1`] and its row counterpart.
380 pub fn sb_shift(&self) -> u32 {
381 if self.use_128x128_superblock { 5 } else { 4 }
382 }
383
384 /// `bit_depth_idx` as `VADecPictureParameterBufferAV1` indexes it: 0 for
385 /// 8-bit, 1 for 10-bit, 2 for 12-bit.
386 pub fn bit_depth_idx(&self) -> u8 {
387 (self.color_config.bit_depth - 8) >> 1
388 }
389
390 /// `MaxTileWidthSb`-style geometry: how many superblocks a frame of
391 /// `mi_cols` 4x4 units is wide.
392 pub(crate) fn sb_cols(&self, mi_cols: u32) -> u32 {
393 if self.use_128x128_superblock {
394 mi_cols.div_ceil(32)
395 } else {
396 mi_cols.div_ceil(16)
397 }
398 }
399
400 /// As [`SequenceHeader::sb_cols`], vertically.
401 pub(crate) fn sb_rows(&self, mi_rows: u32) -> u32 {
402 if self.use_128x128_superblock {
403 mi_rows.div_ceil(32)
404 } else {
405 mi_rows.div_ceil(16)
406 }
407 }
408}
409
410/// `color_config()` (spec 5.5.2).
411fn read_color_config(r: &mut BitReader<'_>, seq_profile: u8) -> Result<ColorConfig> {
412 let high_bitdepth = r.read_bit()?;
413 let bit_depth = if seq_profile == 2 && high_bitdepth {
414 if r.read_bit()? { 12 } else { 10 }
415 } else if high_bitdepth {
416 10
417 } else {
418 8
419 };
420 let mono_chrome = if seq_profile == 1 {
421 false
422 } else {
423 r.read_bit()?
424 };
425 let mut c = ColorConfig {
426 bit_depth,
427 mono_chrome,
428 num_planes: if mono_chrome { 1 } else { 3 },
429 ..ColorConfig::default()
430 };
431 if r.read_bit()? {
432 c.color_primaries = r.read_bits(8)? as u8;
433 c.transfer_characteristics = r.read_bits(8)? as u8;
434 c.matrix_coefficients = r.read_bits(8)? as u8;
435 }
436
437 if mono_chrome {
438 c.color_range = r.read_bit()?;
439 c.subsampling_x = 1;
440 c.subsampling_y = 1;
441 c.separate_uv_delta_q = false;
442 return Ok(c);
443 }
444 // sRGB: BT.709 primaries, sRGB transfer, identity matrix. Full range 4:4:4
445 // by definition, and none of it is coded.
446 if c.color_primaries == 1 && c.transfer_characteristics == 13 && c.matrix_coefficients == 0 {
447 c.color_range = true;
448 c.subsampling_x = 0;
449 c.subsampling_y = 0;
450 } else {
451 c.color_range = r.read_bit()?;
452 match seq_profile {
453 0 => {
454 c.subsampling_x = 1;
455 c.subsampling_y = 1;
456 }
457 1 => {
458 c.subsampling_x = 0;
459 c.subsampling_y = 0;
460 }
461 _ => {
462 if bit_depth == 12 {
463 c.subsampling_x = r.read_bits(1)? as u8;
464 c.subsampling_y = if c.subsampling_x == 1 {
465 r.read_bits(1)? as u8
466 } else {
467 0
468 };
469 } else {
470 // Profile 2 below 12-bit is 4:2:2 and nothing else.
471 c.subsampling_x = 1;
472 c.subsampling_y = 0;
473 }
474 }
475 }
476 if c.subsampling_x == 1 && c.subsampling_y == 1 {
477 c.chroma_sample_position = match r.read_bits(2)? {
478 0 => ChromaSamplePosition::Unknown,
479 1 => ChromaSamplePosition::Vertical,
480 2 => ChromaSamplePosition::Colocated,
481 _ => ChromaSamplePosition::Reserved,
482 };
483 }
484 }
485 c.separate_uv_delta_q = r.read_bit()?;
486 Ok(c)
487}
488
489/// `metadata_obu()` (spec 5.8.1): the type, and nothing else parsed.
490///
491/// Metadata carries HDR mastering display and content light level among other
492/// things, but those belong to [`ec_core::color`]'s vocabulary rather than to a
493/// hardware decode submission, so this returns the type and leaves the payload
494/// to a caller that wants it.
495pub fn metadata_type(payload: &[u8]) -> Result<u32> {
496 read_leb128(&mut BitReader::new(payload))
497}
498
499#[cfg(test)]
500mod tests {
501 use super::*;
502
503 /// Profile 2 at 12-bit is the only place subsampling is coded outright.
504 #[test]
505 fn profile_shapes_the_subsampling() {
506 // profile 0: high_bitdepth 0, mono_chrome 0, no color description,
507 // range 0, chroma position 00, separate_uv_delta_q 0.
508 let bits = [0b0000_0000u8];
509 let c = read_color_config(&mut BitReader::new(&bits), 0).unwrap();
510 assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (8, 1, 1));
511 assert_eq!(c.num_planes, 3);
512
513 // profile 1: high_bitdepth 1, no color description, range 0, sep 0;
514 // mono_chrome is not coded and 4:4:4 is implied.
515 let bits = [0b1000_0000u8];
516 let c = read_color_config(&mut BitReader::new(&bits), 1).unwrap();
517 assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (10, 0, 0));
518
519 // profile 2, 10-bit: 4:2:2, and no chroma_sample_position is coded.
520 let bits = [0b1000_0000u8];
521 let c = read_color_config(&mut BitReader::new(&bits), 2).unwrap();
522 assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (10, 1, 0));
523 }
524
525 #[test]
526 fn monochrome_stops_before_the_chroma_fields() {
527 // high_bitdepth 0, mono_chrome 1, no color description, range 1, sep 0.
528 let bits = [0b0101_0000u8];
529 let c = read_color_config(&mut BitReader::new(&bits), 0).unwrap();
530 assert!(c.mono_chrome);
531 assert_eq!(c.num_planes, 1);
532 assert!(c.color_range);
533 assert!(!c.separate_uv_delta_q);
534 }
535
536 #[test]
537 fn reserved_profile_is_corrupt() {
538 assert!(SequenceHeader::parse(&mut BitReader::new(&[0xff; 16])).is_err());
539 }
540}