forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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