forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB48bcb5cTahinli2 months ago2531 commits

sequence.rs557 lines, 20.9 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 if std::env::var_os("EC_AV1_SEQDUMP").is_some() {
376 eprintln!(
377 "SEQDUMP profile={seq_profile} still={still_picture} reduced={reduced_still_picture_header} \
378 timing_present={} op_cnt={} idc0={} level0={} frame_width_bits={frame_width_bits} \
379 frame_height_bits={frame_height_bits} max_w={max_frame_width} max_h={max_frame_height} \
380 frame_id_present={frame_id_numbers_present_flag} use_128={} filter_intra={} edge_filter={} \
381 interintra={} masked={} warped={} dual_filter={} order_hint={} jnt_comp={} ref_frame_mvs={}",
382 timing_info.is_some(),
383 seq.operating_points.len(),
384 seq.operating_points.first().map_or(0, |o| o.idc),
385 seq.operating_points.first().map_or(0, |o| o.seq_level_idx),
386 use_128x128_superblock, enable_filter_intra, enable_intra_edge_filter,
387 seq.enable_interintra_compound, seq.enable_masked_compound,
388 seq.enable_warped_motion, seq.enable_dual_filter, seq.enable_order_hint,
389 seq.enable_jnt_comp, seq.enable_ref_frame_mvs
390 );
391 }
392 Ok(seq)
393 }
394
395 /// `sbShift` (spec 5.9.15): 5 for 128x128 superblocks, 4 for 64x64. Pass it
396 /// to [`crate::TileInfo::width_in_sbs_minus_1`] and its row counterpart.
397 pub fn sb_shift(&self) -> u32 {
398 if self.use_128x128_superblock { 5 } else { 4 }
399 }
400
401 /// `bit_depth_idx` as `VADecPictureParameterBufferAV1` indexes it: 0 for
402 /// 8-bit, 1 for 10-bit, 2 for 12-bit.
403 pub fn bit_depth_idx(&self) -> u8 {
404 (self.color_config.bit_depth - 8) >> 1
405 }
406
407 /// `MaxTileWidthSb`-style geometry: how many superblocks a frame of
408 /// `mi_cols` 4x4 units is wide.
409 pub(crate) fn sb_cols(&self, mi_cols: u32) -> u32 {
410 if self.use_128x128_superblock {
411 mi_cols.div_ceil(32)
412 } else {
413 mi_cols.div_ceil(16)
414 }
415 }
416
417 /// As [`SequenceHeader::sb_cols`], vertically.
418 pub(crate) fn sb_rows(&self, mi_rows: u32) -> u32 {
419 if self.use_128x128_superblock {
420 mi_rows.div_ceil(32)
421 } else {
422 mi_rows.div_ceil(16)
423 }
424 }
425}
426
427/// `color_config()` (spec 5.5.2).
428fn read_color_config(r: &mut BitReader<'_>, seq_profile: u8) -> Result<ColorConfig> {
429 let high_bitdepth = r.read_bit()?;
430 let bit_depth = if seq_profile == 2 && high_bitdepth {
431 if r.read_bit()? { 12 } else { 10 }
432 } else if high_bitdepth {
433 10
434 } else {
435 8
436 };
437 let mono_chrome = if seq_profile == 1 {
438 false
439 } else {
440 r.read_bit()?
441 };
442 let mut c = ColorConfig {
443 bit_depth,
444 mono_chrome,
445 num_planes: if mono_chrome { 1 } else { 3 },
446 ..ColorConfig::default()
447 };
448 if r.read_bit()? {
449 c.color_primaries = r.read_bits(8)? as u8;
450 c.transfer_characteristics = r.read_bits(8)? as u8;
451 c.matrix_coefficients = r.read_bits(8)? as u8;
452 }
453
454 if mono_chrome {
455 c.color_range = r.read_bit()?;
456 c.subsampling_x = 1;
457 c.subsampling_y = 1;
458 c.separate_uv_delta_q = false;
459 return Ok(c);
460 }
461 // sRGB: BT.709 primaries, sRGB transfer, identity matrix. Full range 4:4:4
462 // by definition, and none of it is coded.
463 if c.color_primaries == 1 && c.transfer_characteristics == 13 && c.matrix_coefficients == 0 {
464 c.color_range = true;
465 c.subsampling_x = 0;
466 c.subsampling_y = 0;
467 } else {
468 c.color_range = r.read_bit()?;
469 match seq_profile {
470 0 => {
471 c.subsampling_x = 1;
472 c.subsampling_y = 1;
473 }
474 1 => {
475 c.subsampling_x = 0;
476 c.subsampling_y = 0;
477 }
478 _ => {
479 if bit_depth == 12 {
480 c.subsampling_x = r.read_bits(1)? as u8;
481 c.subsampling_y = if c.subsampling_x == 1 {
482 r.read_bits(1)? as u8
483 } else {
484 0
485 };
486 } else {
487 // Profile 2 below 12-bit is 4:2:2 and nothing else.
488 c.subsampling_x = 1;
489 c.subsampling_y = 0;
490 }
491 }
492 }
493 if c.subsampling_x == 1 && c.subsampling_y == 1 {
494 c.chroma_sample_position = match r.read_bits(2)? {
495 0 => ChromaSamplePosition::Unknown,
496 1 => ChromaSamplePosition::Vertical,
497 2 => ChromaSamplePosition::Colocated,
498 _ => ChromaSamplePosition::Reserved,
499 };
500 }
501 }
502 c.separate_uv_delta_q = r.read_bit()?;
503 Ok(c)
504}
505
506/// `metadata_obu()` (spec 5.8.1): the type, and nothing else parsed.
507///
508/// Metadata carries HDR mastering display and content light level among other
509/// things, but those belong to [`ec_core::color`]'s vocabulary rather than to a
510/// hardware decode submission, so this returns the type and leaves the payload
511/// to a caller that wants it.
512pub fn metadata_type(payload: &[u8]) -> Result<u32> {
513 read_leb128(&mut BitReader::new(payload))
514}
515
516#[cfg(test)]
517mod tests {
518 use super::*;
519
520 /// Profile 2 at 12-bit is the only place subsampling is coded outright.
521 #[test]
522 fn profile_shapes_the_subsampling() {
523 // profile 0: high_bitdepth 0, mono_chrome 0, no color description,
524 // range 0, chroma position 00, separate_uv_delta_q 0.
525 let bits = [0b0000_0000u8];
526 let c = read_color_config(&mut BitReader::new(&bits), 0).unwrap();
527 assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (8, 1, 1));
528 assert_eq!(c.num_planes, 3);
529
530 // profile 1: high_bitdepth 1, no color description, range 0, sep 0;
531 // mono_chrome is not coded and 4:4:4 is implied.
532 let bits = [0b1000_0000u8];
533 let c = read_color_config(&mut BitReader::new(&bits), 1).unwrap();
534 assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (10, 0, 0));
535
536 // profile 2, 10-bit: 4:2:2, and no chroma_sample_position is coded.
537 let bits = [0b1000_0000u8];
538 let c = read_color_config(&mut BitReader::new(&bits), 2).unwrap();
539 assert_eq!((c.bit_depth, c.subsampling_x, c.subsampling_y), (10, 1, 0));
540 }
541
542 #[test]
543 fn monochrome_stops_before_the_chroma_fields() {
544 // high_bitdepth 0, mono_chrome 1, no color description, range 1, sep 0.
545 let bits = [0b0101_0000u8];
546 let c = read_color_config(&mut BitReader::new(&bits), 0).unwrap();
547 assert!(c.mono_chrome);
548 assert_eq!(c.num_planes, 1);
549 assert!(c.color_range);
550 assert!(!c.separate_uv_delta_q);
551 }
552
553 #[test]
554 fn reserved_profile_is_corrupt() {
555 assert!(SequenceHeader::parse(&mut BitReader::new(&[0xff; 16])).is_err());
556 }
557}