forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB214cdf2Tahinli3 months ago821 commits

sps.rs648 lines, 23.1 KiBHistoryRawDownload
1//! Sequence parameter set (spec 7.3.2.1, 7.4.2.1) incl. VUI (Annex E).
2
3use ec_core::BitReader;
4use ec_core::error::{Error, Result};
5
6/// The 4x4 and 8x8 quantisation scaling lists (spec 7.3.2.1.1.1).
7///
8/// Stored fully resolved: fall-back rules (flat default / previous list) are
9/// applied at parse time so a decoder indexes these directly.
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct ScalingLists {
12 /// Six 4x4 lists in raster order: Intra Y/Cb/Cr, Inter Y/Cb/Cr.
13 pub list_4x4: [[u8; 16]; 6],
14 /// 8x8 lists: Intra Y, Inter Y (plus 4 chroma lists for 4:4:4).
15 pub list_8x8: [[u8; 64]; 6],
16}
17
18/// Default (flat) scaling: weightScale 16 everywhere = no weighting.
19pub const FLAT_4X4: [u8; 16] = [16; 16];
20/// Flat 8x8 list.
21pub const FLAT_8X8: [u8; 64] = [16; 64];
22
23/// Default Intra 4x4 scaling list (spec Table 7-3), in zig-zag scan order.
24pub const DEFAULT_4X4_INTRA: [u8; 16] = [
25 6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42,
26];
27/// Default Inter 4x4 scaling list (spec Table 7-3), in zig-zag scan order.
28pub const DEFAULT_4X4_INTER: [u8; 16] = [
29 10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34,
30];
31/// Default Intra 8x8 scaling list (spec Table 7-4), in zig-zag scan order.
32pub const DEFAULT_8X8_INTRA: [u8; 64] = [
33 6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18, 18, 18, 18, 23, 23, 23, 23, 23, 23, 25, 25, 25,
34 25, 25, 25, 25, 27, 27, 27, 27, 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31,
35 31, 33, 33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42,
36];
37/// Default Inter 8x8 scaling list (spec Table 7-4), in zig-zag scan order.
38pub const DEFAULT_8X8_INTER: [u8; 64] = [
39 9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19, 19, 19, 19, 21, 21, 21, 21, 21, 21, 22, 22, 22,
40 22, 22, 22, 22, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27,
41 27, 28, 28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35,
42];
43
44/// Place a zig-zag-scan-order list into raster order.
45fn scan_to_raster<const N: usize>(scan_order: &[u8; N], scan: &[u8; N]) -> [u8; N] {
46 let mut out = [0u8; N];
47 for (j, &v) in scan_order.iter().enumerate() {
48 out[scan[j] as usize] = v;
49 }
50 out
51}
52
53impl Default for ScalingLists {
54 /// Flat lists — the state when no scaling matrix is signalled.
55 fn default() -> ScalingLists {
56 ScalingLists {
57 list_4x4: [FLAT_4X4; 6],
58 list_8x8: [FLAT_8X8; 6],
59 }
60 }
61}
62
63/// Zig-zag scan for 4x4 blocks (spec Table 8-13, frame scan), used to place
64/// scaling-list entries and residual levels into raster order.
65pub const ZIGZAG_4X4: [u8; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
66
67/// Zig-zag (frame) scan for 8x8 blocks (spec Table 8-14).
68pub const ZIGZAG_8X8: [u8; 64] = [
69 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20,
70 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59,
71 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
72];
73
74/// Parse one `scaling_list` (spec 7.3.2.1.1.1) of `N` entries into raster
75/// order. Returns `None` when `use_default_scaling_matrix_flag` fired.
76fn parse_scaling_list<const N: usize>(
77 r: &mut BitReader<'_>,
78 scan: &[u8; N],
79) -> Result<Option<[u8; N]>> {
80 let mut list = [0u8; N];
81 let mut last_scale = 8i32;
82 let mut next_scale = 8i32;
83 for j in 0..N {
84 if next_scale != 0 {
85 let delta = r.read_se()?;
86 next_scale = (last_scale + delta + 256) % 256;
87 if j == 0 && next_scale == 0 {
88 return Ok(None); // use_default_scaling_matrix_flag
89 }
90 }
91 let v = if next_scale == 0 {
92 last_scale
93 } else {
94 next_scale
95 };
96 list[scan[j] as usize] = v as u8;
97 last_scale = v;
98 }
99 Ok(Some(list))
100}
101
102/// Parse the `seq_scaling_list` / `pic_scaling_list` block shared by SPS and
103/// PPS (spec 7.3.2.1, fall-back rules of Table 7-2). `count` is 8
104/// (4:2:0/4:2:2) or 12 (4:4:4). `sps_lists` is `None` in an SPS (fall-back
105/// rule A: absent list 0/3/6/7 takes the *default* list) and `Some` in a PPS
106/// whose SPS carried a matrix (rule B: those indices take the SPS list).
107/// Lists are returned in raster order, fully resolved.
108pub(crate) fn parse_scaling_matrix(
109 r: &mut BitReader<'_>,
110 count: usize,
111 sps_lists: Option<&ScalingLists>,
112) -> Result<ScalingLists> {
113 let mut out = ScalingLists::default();
114 let d4_intra = scan_to_raster(&DEFAULT_4X4_INTRA, &ZIGZAG_4X4);
115 let d4_inter = scan_to_raster(&DEFAULT_4X4_INTER, &ZIGZAG_4X4);
116 let d8_intra = scan_to_raster(&DEFAULT_8X8_INTRA, &ZIGZAG_8X8);
117 let d8_inter = scan_to_raster(&DEFAULT_8X8_INTER, &ZIGZAG_8X8);
118 for idx in 0..count {
119 let present = r.read_bit()?;
120 if idx < 6 {
121 let default = if idx < 3 { d4_intra } else { d4_inter };
122 let fallback = match idx {
123 0 | 3 => match sps_lists {
124 Some(s) => s.list_4x4[idx],
125 None => default,
126 },
127 _ => out.list_4x4[idx - 1],
128 };
129 out.list_4x4[idx] = if present {
130 parse_scaling_list::<16>(r, &ZIGZAG_4X4)?.unwrap_or(default)
131 } else {
132 fallback
133 };
134 } else {
135 let i = idx - 6;
136 let default = if i % 2 == 0 { d8_intra } else { d8_inter };
137 let fallback = if i < 2 {
138 match sps_lists {
139 Some(s) => s.list_8x8[i],
140 None => default,
141 }
142 } else {
143 out.list_8x8[i - 2]
144 };
145 out.list_8x8[i] = if present {
146 parse_scaling_list::<64>(r, &ZIGZAG_8X8)?.unwrap_or(default)
147 } else {
148 fallback
149 };
150 }
151 }
152 Ok(out)
153}
154
155/// HRD parameters (spec E.1.2), carried for completeness.
156#[derive(Debug, Clone, PartialEq, Eq, Default)]
157pub struct Hrd {
158 /// Per-CPB `(bit_rate_value_minus1, cpb_size_value_minus1, cbr_flag)`.
159 pub cpb: Vec<(u32, u32, bool)>,
160 /// `bit_rate_scale`.
161 pub bit_rate_scale: u8,
162 /// `cpb_size_scale`.
163 pub cpb_size_scale: u8,
164 /// `initial_cpb_removal_delay_length_minus1`.
165 pub initial_cpb_removal_delay_length_minus1: u8,
166 /// `cpb_removal_delay_length_minus1`.
167 pub cpb_removal_delay_length_minus1: u8,
168 /// `dpb_output_delay_length_minus1`.
169 pub dpb_output_delay_length_minus1: u8,
170 /// `time_offset_length`.
171 pub time_offset_length: u8,
172}
173
174impl Hrd {
175 fn parse(r: &mut BitReader<'_>) -> Result<Hrd> {
176 let cpb_cnt_minus1 = r.read_ue()?;
177 if cpb_cnt_minus1 > 31 {
178 return Err(Error::corrupt("cpb_cnt_minus1 > 31"));
179 }
180 let bit_rate_scale = r.read_bits(4)? as u8;
181 let cpb_size_scale = r.read_bits(4)? as u8;
182 let mut cpb = Vec::with_capacity(cpb_cnt_minus1 as usize + 1);
183 for _ in 0..=cpb_cnt_minus1 {
184 let bit_rate = r.read_ue()?;
185 let cpb_size = r.read_ue()?;
186 let cbr = r.read_bit()?;
187 cpb.push((bit_rate, cpb_size, cbr));
188 }
189 Ok(Hrd {
190 cpb,
191 bit_rate_scale,
192 cpb_size_scale,
193 initial_cpb_removal_delay_length_minus1: r.read_bits(5)? as u8,
194 cpb_removal_delay_length_minus1: r.read_bits(5)? as u8,
195 dpb_output_delay_length_minus1: r.read_bits(5)? as u8,
196 time_offset_length: r.read_bits(5)? as u8,
197 })
198 }
199}
200
201/// VUI parameters (spec E.1.1).
202#[derive(Debug, Clone, PartialEq, Eq, Default)]
203pub struct Vui {
204 /// Sample aspect ratio `(width, height)` when signalled; `aspect_ratio_idc`
205 /// table values are resolved here, Extended_SAR reads the pair verbatim.
206 pub sample_aspect_ratio: Option<(u16, u16)>,
207 /// `overscan_appropriate_flag` when `overscan_info_present_flag`.
208 pub overscan_appropriate: Option<bool>,
209 /// `video_format` (E-2) when signalled.
210 pub video_format: Option<u8>,
211 /// `video_full_range_flag`.
212 pub video_full_range: bool,
213 /// H.273 `(colour_primaries, transfer_characteristics, matrix_coefficients)`.
214 pub colour_description: Option<(u8, u8, u8)>,
215 /// `(chroma_sample_loc_type_top_field, chroma_sample_loc_type_bottom_field)`.
216 pub chroma_sample_loc: Option<(u32, u32)>,
217 /// `(num_units_in_tick, time_scale, fixed_frame_rate_flag)`.
218 pub timing_info: Option<(u32, u32, bool)>,
219 /// NAL HRD parameters.
220 pub nal_hrd: Option<Hrd>,
221 /// VCL HRD parameters.
222 pub vcl_hrd: Option<Hrd>,
223 /// `low_delay_hrd_flag` (present when either HRD is).
224 pub low_delay_hrd: bool,
225 /// `pic_struct_present_flag`.
226 pub pic_struct_present: bool,
227 /// Bitstream restriction fields, in spec order.
228 pub bitstream_restriction: Option<BitstreamRestriction>,
229}
230
231/// `bitstream_restriction` fields (spec E.1.1).
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
233pub struct BitstreamRestriction {
234 /// `motion_vectors_over_pic_boundaries_flag`.
235 pub motion_vectors_over_pic_boundaries: bool,
236 /// `max_bytes_per_pic_denom`.
237 pub max_bytes_per_pic_denom: u32,
238 /// `max_bits_per_mb_denom`.
239 pub max_bits_per_mb_denom: u32,
240 /// `log2_max_mv_length_horizontal`.
241 pub log2_max_mv_length_horizontal: u32,
242 /// `log2_max_mv_length_vertical`.
243 pub log2_max_mv_length_vertical: u32,
244 /// `max_num_reorder_frames`.
245 pub max_num_reorder_frames: u32,
246 /// `max_dec_frame_buffering`.
247 pub max_dec_frame_buffering: u32,
248}
249
250/// Table E-1 aspect ratios for `aspect_ratio_idc` 1..=16.
251const SAR_TABLE: [(u16, u16); 17] = [
252 (0, 0), // 0 = unspecified
253 (1, 1),
254 (12, 11),
255 (10, 11),
256 (16, 11),
257 (40, 33),
258 (24, 11),
259 (20, 11),
260 (32, 11),
261 (80, 33),
262 (18, 11),
263 (15, 11),
264 (64, 33),
265 (160, 99),
266 (4, 3),
267 (3, 2),
268 (2, 1),
269];
270
271impl Vui {
272 fn parse(r: &mut BitReader<'_>) -> Result<Vui> {
273 let mut vui = Vui::default();
274 if r.read_bit()? {
275 // aspect_ratio_info_present_flag
276 let idc = r.read_bits(8)? as u8;
277 vui.sample_aspect_ratio = match idc {
278 0 => None,
279 255 => Some((r.read_bits(16)? as u16, r.read_bits(16)? as u16)),
280 1..=16 => Some(SAR_TABLE[idc as usize]),
281 _ => None, // reserved: ignore per spec
282 };
283 }
284 if r.read_bit()? {
285 vui.overscan_appropriate = Some(r.read_bit()?);
286 }
287 if r.read_bit()? {
288 // video_signal_type_present_flag
289 vui.video_format = Some(r.read_bits(3)? as u8);
290 vui.video_full_range = r.read_bit()?;
291 if r.read_bit()? {
292 vui.colour_description = Some((
293 r.read_bits(8)? as u8,
294 r.read_bits(8)? as u8,
295 r.read_bits(8)? as u8,
296 ));
297 }
298 }
299 if r.read_bit()? {
300 vui.chroma_sample_loc = Some((r.read_ue()?, r.read_ue()?));
301 }
302 if r.read_bit()? {
303 vui.timing_info = Some((r.read_bits(32)?, r.read_bits(32)?, r.read_bit()?));
304 }
305 let nal_hrd_present = r.read_bit()?;
306 if nal_hrd_present {
307 vui.nal_hrd = Some(Hrd::parse(r)?);
308 }
309 let vcl_hrd_present = r.read_bit()?;
310 if vcl_hrd_present {
311 vui.vcl_hrd = Some(Hrd::parse(r)?);
312 }
313 if nal_hrd_present || vcl_hrd_present {
314 vui.low_delay_hrd = r.read_bit()?;
315 }
316 vui.pic_struct_present = r.read_bit()?;
317 if r.read_bit()? {
318 vui.bitstream_restriction = Some(BitstreamRestriction {
319 motion_vectors_over_pic_boundaries: r.read_bit()?,
320 max_bytes_per_pic_denom: r.read_ue()?,
321 max_bits_per_mb_denom: r.read_ue()?,
322 log2_max_mv_length_horizontal: r.read_ue()?,
323 log2_max_mv_length_vertical: r.read_ue()?,
324 max_num_reorder_frames: r.read_ue()?,
325 max_dec_frame_buffering: r.read_ue()?,
326 });
327 }
328 Ok(vui)
329 }
330}
331
332/// Sequence parameter set (spec 7.4.2.1) with decode-ready derived geometry.
333#[derive(Debug, Clone, PartialEq, Eq)]
334pub struct Sps {
335 /// `profile_idc`.
336 pub profile_idc: u8,
337 /// `constraint_setX_flag` bits (bit 7 = set0) + reserved bits, verbatim.
338 pub constraint_flags: u8,
339 /// `level_idc`.
340 pub level_idc: u8,
341 /// `seq_parameter_set_id` (0..=31).
342 pub id: u8,
343 /// `chroma_format_idc`: 0 mono, 1 = 4:2:0, 2 = 4:2:2, 3 = 4:4:4.
344 pub chroma_format_idc: u8,
345 /// `separate_colour_plane_flag` (4:4:4 only).
346 pub separate_colour_plane: bool,
347 /// Luma bit depth (8..=14).
348 pub bit_depth_luma: u8,
349 /// Chroma bit depth (8..=14).
350 pub bit_depth_chroma: u8,
351 /// `qpprime_y_zero_transform_bypass_flag`.
352 pub transform_bypass: bool,
353 /// Scaling lists when `seq_scaling_matrix_present_flag`, resolved.
354 pub scaling_lists: Option<ScalingLists>,
355 /// `log2_max_frame_num` (4..=16, offset applied).
356 pub log2_max_frame_num: u8,
357 /// `pic_order_cnt_type` (0..=2).
358 pub pic_order_cnt_type: u8,
359 /// `log2_max_pic_order_cnt_lsb` (POC type 0, offset applied).
360 pub log2_max_pic_order_cnt_lsb: u8,
361 /// `delta_pic_order_always_zero_flag` (POC type 1).
362 pub delta_pic_order_always_zero: bool,
363 /// `offset_for_non_ref_pic` (POC type 1).
364 pub offset_for_non_ref_pic: i32,
365 /// `offset_for_top_to_bottom_field` (POC type 1).
366 pub offset_for_top_to_bottom_field: i32,
367 /// `offset_for_ref_frame` list (POC type 1).
368 pub offsets_for_ref_frame: Vec<i32>,
369 /// `max_num_ref_frames`.
370 pub max_num_ref_frames: u32,
371 /// `gaps_in_frame_num_value_allowed_flag`.
372 pub gaps_in_frame_num_allowed: bool,
373 /// `frame_mbs_only_flag`.
374 pub frame_mbs_only: bool,
375 /// `mb_adaptive_frame_field_flag` (when `!frame_mbs_only`).
376 pub mb_adaptive_frame_field: bool,
377 /// `direct_8x8_inference_flag`.
378 pub direct_8x8_inference: bool,
379 /// Crop offsets in luma samples `(left, right, top, bottom)`, already
380 /// scaled by the chroma-format crop units (spec 7.4.2.1.1).
381 pub crop: (u32, u32, u32, u32),
382 /// VUI parameters when present.
383 pub vui: Option<Vui>,
384
385 // ---- derived, computed once at parse time ----
386 /// `PicWidthInMbs`.
387 pub mb_width: u32,
388 /// `FrameHeightInMbs` (frame coding).
389 pub mb_height: u32,
390 /// Coded luma width in samples (mb_width * 16).
391 pub coded_width: u32,
392 /// Coded luma height in samples.
393 pub coded_height: u32,
394 /// Visible width after cropping.
395 pub width: u32,
396 /// Visible height after cropping.
397 pub height: u32,
398}
399
400impl Sps {
401 /// Parse an SPS RBSP (header byte already consumed, emulation stripped).
402 pub fn parse(rbsp: &[u8]) -> Result<Sps> {
403 let mut r = BitReader::new(rbsp);
404 let r = &mut r;
405 let profile_idc = r.read_bits(8)? as u8;
406 let constraint_flags = r.read_bits(8)? as u8;
407 let level_idc = r.read_bits(8)? as u8;
408 let id = r.read_ue()?;
409 if id > 31 {
410 return Err(Error::corrupt("seq_parameter_set_id > 31"));
411 }
412
413 let mut chroma_format_idc = 1u8;
414 let mut separate_colour_plane = false;
415 let mut bit_depth_luma = 8u8;
416 let mut bit_depth_chroma = 8u8;
417 let mut transform_bypass = false;
418 let mut scaling_lists = None;
419 if matches!(
420 profile_idc,
421 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
422 ) {
423 let cf = r.read_ue()?;
424 if cf > 3 {
425 return Err(Error::corrupt("chroma_format_idc > 3"));
426 }
427 chroma_format_idc = cf as u8;
428 if chroma_format_idc == 3 {
429 separate_colour_plane = r.read_bit()?;
430 }
431 let bdl = r.read_ue()?;
432 let bdc = r.read_ue()?;
433 if bdl > 6 || bdc > 6 {
434 return Err(Error::corrupt("bit_depth_minus8 > 6"));
435 }
436 bit_depth_luma = 8 + bdl as u8;
437 bit_depth_chroma = 8 + bdc as u8;
438 transform_bypass = r.read_bit()?;
439 if r.read_bit()? {
440 let count = if chroma_format_idc == 3 { 12 } else { 8 };
441 scaling_lists = Some(parse_scaling_matrix(r, count, None)?);
442 }
443 }
444
445 let log2_mfn = r.read_ue()?;
446 if log2_mfn > 12 {
447 return Err(Error::corrupt("log2_max_frame_num_minus4 > 12"));
448 }
449 let log2_max_frame_num = 4 + log2_mfn as u8;
450 let pic_order_cnt_type = r.read_ue()?;
451 if pic_order_cnt_type > 2 {
452 return Err(Error::corrupt("pic_order_cnt_type > 2"));
453 }
454 let pic_order_cnt_type = pic_order_cnt_type as u8;
455 let mut log2_max_pic_order_cnt_lsb = 0u8;
456 let mut delta_pic_order_always_zero = false;
457 let mut offset_for_non_ref_pic = 0i32;
458 let mut offset_for_top_to_bottom_field = 0i32;
459 let mut offsets_for_ref_frame = Vec::new();
460 match pic_order_cnt_type {
461 0 => {
462 let v = r.read_ue()?;
463 if v > 12 {
464 return Err(Error::corrupt("log2_max_pic_order_cnt_lsb_minus4 > 12"));
465 }
466 log2_max_pic_order_cnt_lsb = 4 + v as u8;
467 }
468 1 => {
469 delta_pic_order_always_zero = r.read_bit()?;
470 offset_for_non_ref_pic = r.read_se()?;
471 offset_for_top_to_bottom_field = r.read_se()?;
472 let n = r.read_ue()?;
473 if n > 255 {
474 return Err(Error::corrupt(
475 "num_ref_frames_in_pic_order_cnt_cycle > 255",
476 ));
477 }
478 offsets_for_ref_frame.reserve(n as usize);
479 for _ in 0..n {
480 offsets_for_ref_frame.push(r.read_se()?);
481 }
482 }
483 _ => {}
484 }
485 let max_num_ref_frames = r.read_ue()?;
486 let gaps_in_frame_num_allowed = r.read_bit()?;
487 let pic_width_in_mbs_minus1 = r.read_ue()?;
488 let pic_height_in_map_units_minus1 = r.read_ue()?;
489 let frame_mbs_only = r.read_bit()?;
490 let mb_adaptive_frame_field = if !frame_mbs_only {
491 r.read_bit()?
492 } else {
493 false
494 };
495 let direct_8x8_inference = r.read_bit()?;
496
497 let mb_width = pic_width_in_mbs_minus1 + 1;
498 let map_height = pic_height_in_map_units_minus1 + 1;
499 let mb_height = map_height * if frame_mbs_only { 1 } else { 2 };
500 if mb_width > 1024 || mb_height > 1024 {
501 return Err(Error::corrupt("picture larger than 16384x16384"));
502 }
503 let coded_width = mb_width * 16;
504 let coded_height = mb_height * 16;
505
506 // Crop units (spec 7.4.2.1.1): chroma-format dependent.
507 let (crop_x, crop_y_frame) = match chroma_format_idc {
508 0 => (1, 1),
509 1 => (2, 2),
510 2 => (2, 1),
511 _ => (1, 1),
512 };
513 let crop_y = crop_y_frame * if frame_mbs_only { 1 } else { 2 };
514 let crop = if r.read_bit()? {
515 let l = r.read_ue()?;
516 let rr = r.read_ue()?;
517 let t = r.read_ue()?;
518 let b = r.read_ue()?;
519 (crop_x * l, crop_x * rr, crop_y * t, crop_y * b)
520 } else {
521 (0, 0, 0, 0)
522 };
523 let width = coded_width
524 .checked_sub(crop.0 + crop.1)
525 .filter(|&w| w > 0)
526 .ok_or_else(|| Error::corrupt("frame cropping wider than the picture"))?;
527 let height = coded_height
528 .checked_sub(crop.2 + crop.3)
529 .filter(|&h| h > 0)
530 .ok_or_else(|| Error::corrupt("frame cropping taller than the picture"))?;
531
532 let vui = if r.read_bit()? {
533 Some(Vui::parse(r)?)
534 } else {
535 None
536 };
537
538 Ok(Sps {
539 profile_idc,
540 constraint_flags,
541 level_idc,
542 id: id as u8,
543 chroma_format_idc,
544 separate_colour_plane,
545 bit_depth_luma,
546 bit_depth_chroma,
547 transform_bypass,
548 scaling_lists,
549 log2_max_frame_num,
550 pic_order_cnt_type,
551 log2_max_pic_order_cnt_lsb,
552 delta_pic_order_always_zero,
553 offset_for_non_ref_pic,
554 offset_for_top_to_bottom_field,
555 offsets_for_ref_frame,
556 max_num_ref_frames,
557 gaps_in_frame_num_allowed,
558 frame_mbs_only,
559 mb_adaptive_frame_field,
560 direct_8x8_inference,
561 crop,
562 vui,
563 mb_width,
564 mb_height,
565 coded_width,
566 coded_height,
567 width,
568 height,
569 })
570 }
571
572 /// Total macroblocks per picture.
573 pub fn mbs_per_picture(&self) -> u32 {
574 self.mb_width * self.mb_height
575 }
576}
577
578#[cfg(test)]
579mod tests {
580 use super::*;
581 use ec_core::BitWriter;
582
583 /// Build a minimal Baseline QCIF SPS and check the derived geometry.
584 #[test]
585 fn baseline_qcif_geometry() {
586 let mut w = BitWriter::new();
587 w.write_bits(66, 8); // profile_idc Baseline
588 w.write_bits(0xC0, 8); // constraint flags
589 w.write_bits(10, 8); // level_idc
590 w.write_ue(0); // sps id
591 w.write_ue(0); // log2_max_frame_num_minus4
592 w.write_ue(0); // pic_order_cnt_type
593 w.write_ue(0); // log2_max_pic_order_cnt_lsb_minus4
594 w.write_ue(1); // max_num_ref_frames
595 w.write_bit(false); // gaps allowed
596 w.write_ue(10); // width 11 MBs = 176
597 w.write_ue(8); // height 9 MBs = 144
598 w.write_bit(true); // frame_mbs_only
599 w.write_bit(true); // direct_8x8_inference
600 w.write_bit(false); // no cropping
601 w.write_bit(false); // no VUI
602 w.write_bit(true); // rbsp_stop_one_bit
603 w.align_to_byte();
604 let sps = Sps::parse(w.as_bytes()).unwrap();
605 assert_eq!(sps.profile_idc, 66);
606 assert_eq!((sps.mb_width, sps.mb_height), (11, 9));
607 assert_eq!((sps.width, sps.height), (176, 144));
608 assert_eq!(sps.chroma_format_idc, 1);
609 assert_eq!(sps.bit_depth_luma, 8);
610 assert!(sps.frame_mbs_only);
611 }
612
613 /// Cropping in 4:2:0 is in 2-sample units both directions.
614 #[test]
615 fn crop_units_420() {
616 let mut w = BitWriter::new();
617 w.write_bits(66, 8);
618 w.write_bits(0, 8);
619 w.write_bits(40, 8);
620 w.write_ue(0);
621 w.write_ue(0);
622 w.write_ue(2); // poc type 2
623 w.write_ue(1);
624 w.write_bit(false);
625 w.write_ue(119); // 1920
626 w.write_ue(67); // 68 MBs = 1088
627 w.write_bit(true);
628 w.write_bit(true);
629 w.write_bit(true); // cropping
630 w.write_ue(0);
631 w.write_ue(0);
632 w.write_ue(0);
633 w.write_ue(4); // bottom crop 4 units = 8 luma rows
634 w.write_bit(false); // no VUI
635 w.write_bit(true);
636 w.align_to_byte();
637 let sps = Sps::parse(w.as_bytes()).unwrap();
638 assert_eq!((sps.width, sps.height), (1920, 1080));
639 assert_eq!(sps.crop, (0, 0, 0, 8));
640 }
641
642 /// Truncated SPS is NeedMore, never a panic.
643 #[test]
644 fn truncated_is_need_more() {
645 assert!(Sps::parse(&[0x42]).unwrap_err().is_need_more());
646 assert!(Sps::parse(&[]).unwrap_err().is_need_more());
647 }
648}