forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

ps.rs1237 lines, 46.9 KiBHistoryRawDownload
1//! Parameter sets: VPS, SPS and PPS, written and parsed.
2//!
3//! The field sets here are sized by what a *stateless hardware decoder* asks
4//! for, not by what this family's own encoder writes: everything in
5//! `VAPictureParameterBufferHEVC` is either a field on [`Sps`]/[`Pps`] or
6//! derivable from one by a named method. Anything the parser walks past but does
7//! not model (scaling lists, HRD, the multilayer and 3D extensions) is a thing
8//! no consumer in this family reads, and each such skip says so where it happens.
9
10use crate::vui::VuiParameters;
11use ec_core::bitio::{BitReader, BitWriter};
12use ec_core::error::{Error, Result};
13
14/// `profile_tier_level()` for a single-sub-layer stream (7.3.3).
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct ProfileTierLevel {
17 /// `general_profile_space`, 0 for everything in the wild.
18 pub profile_space: u8,
19 /// False = Main tier, true = High tier.
20 pub tier_flag: bool,
21 /// 1 = Main, 2 = Main 10, 3 = Main Still Picture, 4 = range extensions.
22 pub profile_idc: u8,
23 /// `general_profile_compatibility_flag[0..32]` as a bit set, bit `j` = flag `j`.
24 pub profile_compatibility: u32,
25 /// `general_progressive_source_flag`.
26 pub progressive_source: bool,
27 /// `general_interlaced_source_flag`.
28 pub interlaced_source: bool,
29 /// `general_non_packed_constraint_flag`.
30 pub non_packed_constraint: bool,
31 /// `general_frame_only_constraint_flag`.
32 pub frame_only_constraint: bool,
33 /// The 44 bits between the source flags and `general_level_idc`: the
34 /// profile-dependent constraint flags, their reserved padding and
35 /// `general_inbld_flag`. Kept verbatim so a re-write is byte-identical,
36 /// because their *meaning* depends on `profile_idc` while their length
37 /// never does.
38 pub constraint_bits: u64,
39 /// `general_level_idc`: 30 x the level number (level 4 = 120).
40 pub level_idc: u8,
41}
42
43impl ProfileTierLevel {
44 /// Main profile at `level_idc`, progressive, frame-only — what an intra
45 /// 8-bit 4:2:0 encoder emits.
46 pub fn main(level_idc: u8) -> ProfileTierLevel {
47 ProfileTierLevel {
48 profile_space: 0,
49 tier_flag: false,
50 profile_idc: 1,
51 // Main is compatible with itself; bit 1 is what every decoder checks.
52 profile_compatibility: 1 << 1,
53 progressive_source: true,
54 interlaced_source: false,
55 non_packed_constraint: true,
56 frame_only_constraint: true,
57 constraint_bits: 0,
58 level_idc,
59 }
60 }
61
62 /// The smallest level whose limits hold for `width x height` at `fps`
63 /// (Annex A, Table A.8/A.9 luma sample and sample-rate limits).
64 ///
65 /// Levels are a decoder's promise about buffer sizes; naming one too small
66 /// is what makes a hardware decoder refuse a stream it could otherwise play,
67 /// so this rounds up and stops at 6.2.
68 pub fn level_for(width: u32, height: u32, fps: f64) -> u8 {
69 // (level_idc, MaxLumaPs, MaxLumaSr)
70 const LIMITS: &[(u8, u64, u64)] = &[
71 (30, 36_864, 552_960),
72 (60, 122_880, 3_686_400),
73 (63, 245_760, 7_372_800),
74 (90, 552_960, 16_588_800),
75 (93, 983_040, 33_177_600),
76 (120, 2_228_224, 66_846_720),
77 (123, 2_228_224, 133_693_440),
78 (126, 2_228_224, 267_386_880),
79 (150, 8_912_896, 534_773_760),
80 (153, 8_912_896, 1_069_547_520),
81 (156, 8_912_896, 1_069_547_520),
82 (180, 35_651_584, 2_139_095_040),
83 (183, 35_651_584, 4_278_190_080),
84 (186, 35_651_584, 4_278_190_080),
85 ];
86 let samples = u64::from(width) * u64::from(height);
87 let rate = (samples as f64 * fps.max(1.0)) as u64;
88 for &(idc, max_ps, max_sr) in LIMITS {
89 if samples <= max_ps && rate <= max_sr {
90 return idc;
91 }
92 }
93 186
94 }
95
96 /// Write `profile_tier_level(1, 0)` — 96 bits, always.
97 pub fn write(&self, w: &mut BitWriter) {
98 w.write_bits(u32::from(self.profile_space), 2);
99 w.write_bit(self.tier_flag);
100 w.write_bits(u32::from(self.profile_idc), 5);
101 for j in 0..32 {
102 w.write_bit(self.profile_compatibility & (1 << j) != 0);
103 }
104 w.write_bit(self.progressive_source);
105 w.write_bit(self.interlaced_source);
106 w.write_bit(self.non_packed_constraint);
107 w.write_bit(self.frame_only_constraint);
108 w.write_bits64(self.constraint_bits, 44);
109 w.write_bits(u32::from(self.level_idc), 8);
110 }
111
112 /// Parse `profile_tier_level(1, max_sub_layers_minus1)`.
113 pub fn parse(r: &mut BitReader, max_sub_layers_minus1: u32) -> Result<ProfileTierLevel> {
114 let profile_space = r.read_bits(2)? as u8;
115 let tier_flag = r.read_bit()?;
116 let profile_idc = r.read_bits(5)? as u8;
117 let mut profile_compatibility = 0u32;
118 for j in 0..32 {
119 if r.read_bit()? {
120 profile_compatibility |= 1 << j;
121 }
122 }
123 let progressive_source = r.read_bit()?;
124 let interlaced_source = r.read_bit()?;
125 let non_packed_constraint = r.read_bit()?;
126 let frame_only_constraint = r.read_bit()?;
127 let constraint_bits = r.read_bits64(44)?;
128 let level_idc = r.read_bits(8)? as u8;
129 let mut sub_layer_profile = Vec::new();
130 let mut sub_layer_level = Vec::new();
131 for _ in 0..max_sub_layers_minus1 {
132 sub_layer_profile.push(r.read_bit()?);
133 sub_layer_level.push(r.read_bit()?);
134 }
135 if max_sub_layers_minus1 > 0 {
136 for _ in max_sub_layers_minus1..8 {
137 r.read_bits(2)?;
138 }
139 }
140 for i in 0..max_sub_layers_minus1 as usize {
141 if sub_layer_profile[i] {
142 r.skip_bits(88)?;
143 }
144 if sub_layer_level[i] {
145 r.read_bits(8)?;
146 }
147 }
148 Ok(ProfileTierLevel {
149 profile_space,
150 tier_flag,
151 profile_idc,
152 profile_compatibility,
153 progressive_source,
154 interlaced_source,
155 non_packed_constraint,
156 frame_only_constraint,
157 constraint_bits,
158 level_idc,
159 })
160 }
161}
162
163/// The video parameter set (7.3.2.1).
164///
165/// A single-layer stream needs one and nothing in it varies, but a decoder that
166/// never sees a VPS refuses the stream, so it is written all the same.
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168pub struct Vps {
169 /// `vps_video_parameter_set_id`.
170 pub id: u8,
171 /// Profile, tier and level of the base layer.
172 pub ptl: ProfileTierLevel,
173 /// `vps_max_dec_pic_buffering_minus1[0]`.
174 pub max_dec_pic_buffering_minus1: u32,
175 /// `vps_max_num_reorder_pics[0]`; 0 for an intra-only stream.
176 pub max_num_reorder_pics: u32,
177}
178
179impl Vps {
180 /// The RBSP, trailing bits included.
181 pub fn to_rbsp(&self) -> Vec<u8> {
182 let mut w = BitWriter::with_capacity(32);
183 w.write_bits(u32::from(self.id), 4);
184 w.write_bit(true); // vps_base_layer_internal_flag
185 w.write_bit(true); // vps_base_layer_available_flag
186 w.write_bits(0, 6); // vps_max_layers_minus1
187 w.write_bits(0, 3); // vps_max_sub_layers_minus1
188 w.write_bit(true); // vps_temporal_id_nesting_flag
189 w.write_bits(0xffff, 16); // vps_reserved_0xffff_16bits
190 self.ptl.write(&mut w);
191 w.write_bit(true); // vps_sub_layer_ordering_info_present_flag
192 w.write_ue(self.max_dec_pic_buffering_minus1);
193 w.write_ue(self.max_num_reorder_pics);
194 w.write_ue(0); // vps_max_latency_increase_plus1
195 w.write_bits(0, 6); // vps_max_layer_id
196 w.write_ue(0); // vps_num_layer_sets_minus1
197 w.write_bit(false); // vps_timing_info_present_flag
198 w.write_bit(false); // vps_extension_flag
199 rbsp_trailing_bits(&mut w);
200 w.into_bytes()
201 }
202
203 /// Parse a VPS RBSP.
204 pub fn parse(rbsp: &[u8]) -> Result<Vps> {
205 let mut r = BitReader::new(rbsp);
206 let id = r.read_bits(4)? as u8;
207 r.read_bit()?;
208 r.read_bit()?;
209 r.read_bits(6)?; // vps_max_layers_minus1
210 let max_sub_layers_minus1 = r.read_bits(3)?;
211 r.read_bit()?;
212 r.read_bits(16)?;
213 let ptl = ProfileTierLevel::parse(&mut r, max_sub_layers_minus1)?;
214 let ordering_info = r.read_bit()?;
215 let first = if ordering_info {
216 0
217 } else {
218 max_sub_layers_minus1
219 };
220 let mut max_dec_pic_buffering_minus1 = 0;
221 let mut max_num_reorder_pics = 0;
222 for _ in first..=max_sub_layers_minus1 {
223 max_dec_pic_buffering_minus1 = r.read_ue()?;
224 max_num_reorder_pics = r.read_ue()?;
225 r.read_ue()?;
226 }
227 Ok(Vps {
228 id,
229 ptl,
230 max_dec_pic_buffering_minus1,
231 max_num_reorder_pics,
232 })
233 }
234}
235
236/// The conformance window: how many samples to crop off a coded picture.
237///
238/// This is how 1920x1080 is coded with 64x64 coding tree blocks — the picture is
239/// coded 1920x1088 and eight rows are cropped — and it is a first-class field
240/// here rather than a caller's problem, because a caller that pads its own
241/// planes has to guess what the encoder does with the padding.
242#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
243pub struct ConformanceWindow {
244 /// `conf_win_left_offset`, in chroma units.
245 pub left: u32,
246 /// `conf_win_right_offset`, in chroma units.
247 pub right: u32,
248 /// `conf_win_top_offset`, in chroma units.
249 pub top: u32,
250 /// `conf_win_bottom_offset`, in chroma units.
251 pub bottom: u32,
252}
253
254impl ConformanceWindow {
255 /// True when nothing is cropped.
256 pub fn is_empty(&self) -> bool {
257 *self == ConformanceWindow::default()
258 }
259}
260
261/// The sequence parameter set (7.3.2.2.1).
262#[derive(Debug, Clone, PartialEq, Eq)]
263pub struct Sps {
264 /// `sps_video_parameter_set_id`.
265 pub vps_id: u8,
266 /// `sps_seq_parameter_set_id`.
267 pub id: u32,
268 /// 0 = monochrome, 1 = 4:2:0, 2 = 4:2:2, 3 = 4:4:4.
269 pub chroma_format_idc: u32,
270 /// `separate_colour_plane_flag`.
271 pub separate_colour_plane: bool,
272 /// Coded width — a multiple of the minimum coding block size.
273 pub pic_width_in_luma_samples: u32,
274 /// Coded height.
275 pub pic_height_in_luma_samples: u32,
276 /// What to crop off the coded picture for display.
277 pub conf_win: ConformanceWindow,
278 /// `bit_depth_luma_minus8`.
279 pub bit_depth_luma_minus8: u32,
280 /// `bit_depth_chroma_minus8`.
281 pub bit_depth_chroma_minus8: u32,
282 /// `log2_max_pic_order_cnt_lsb_minus4`.
283 pub log2_max_poc_lsb_minus4: u32,
284 /// `sps_max_dec_pic_buffering_minus1[HighestTid]`.
285 pub max_dec_pic_buffering_minus1: u32,
286 /// `sps_max_num_reorder_pics[HighestTid]`.
287 pub max_num_reorder_pics: u32,
288 /// `log2_min_luma_coding_block_size_minus3`.
289 pub log2_min_cb_size_minus3: u32,
290 /// `log2_diff_max_min_luma_coding_block_size`.
291 pub log2_diff_max_min_cb_size: u32,
292 /// `log2_min_luma_transform_block_size_minus2`.
293 pub log2_min_tb_size_minus2: u32,
294 /// `log2_diff_max_min_luma_transform_block_size`.
295 pub log2_diff_max_min_tb_size: u32,
296 /// `max_transform_hierarchy_depth_inter`.
297 pub max_transform_hierarchy_depth_inter: u32,
298 /// `max_transform_hierarchy_depth_intra`.
299 pub max_transform_hierarchy_depth_intra: u32,
300 /// `scaling_list_enabled_flag`; this family never writes scaling lists.
301 pub scaling_list_enabled: bool,
302 /// `amp_enabled_flag`.
303 pub amp_enabled: bool,
304 /// `sample_adaptive_offset_enabled_flag`.
305 pub sao_enabled: bool,
306 /// `pcm_enabled_flag`.
307 pub pcm_enabled: bool,
308 /// PCM sample depths and block sizes, present when `pcm_enabled`:
309 /// `(pcm_sample_bit_depth_luma_minus1, pcm_sample_bit_depth_chroma_minus1,
310 /// log2_min_pcm_luma_coding_block_size_minus3,
311 /// log2_diff_max_min_pcm_luma_coding_block_size, pcm_loop_filter_disabled_flag)`.
312 pub pcm: Option<(u32, u32, u32, u32, bool)>,
313 /// `num_short_term_ref_pic_sets`.
314 pub num_short_term_ref_pic_sets: u32,
315 /// The sets themselves, in bitstream order: a slice header may name one by
316 /// index instead of carrying it, and a decoder then needs it from here.
317 pub short_term_ref_pic_sets: Vec<ShortTermRefPicSet>,
318 /// `long_term_ref_pics_present_flag`.
319 pub long_term_ref_pics_present: bool,
320 /// `num_long_term_ref_pics_sps`.
321 pub num_long_term_ref_pics_sps: u32,
322 /// `(lt_ref_pic_poc_lsb_sps, used_by_curr_pic_lt_sps_flag)` per SPS long
323 /// term picture, which a slice header names by index.
324 pub long_term_ref_pics_sps: Vec<(u32, bool)>,
325 /// `sps_temporal_mvp_enabled_flag`.
326 pub temporal_mvp_enabled: bool,
327 /// `strong_intra_smoothing_enabled_flag`.
328 pub strong_intra_smoothing: bool,
329 /// Profile, tier, level.
330 pub ptl: ProfileTierLevel,
331 /// VUI, when present.
332 pub vui: Option<VuiParameters>,
333}
334
335impl Sps {
336 /// Coding tree block size in luma samples (`CtbSizeY`).
337 pub fn ctb_size(&self) -> u32 {
338 1 << (self.log2_min_cb_size_minus3 + 3 + self.log2_diff_max_min_cb_size)
339 }
340
341 /// `PicWidthInCtbsY`.
342 pub fn pic_width_in_ctbs(&self) -> u32 {
343 self.pic_width_in_luma_samples.div_ceil(self.ctb_size())
344 }
345
346 /// `PicHeightInCtbsY`.
347 pub fn pic_height_in_ctbs(&self) -> u32 {
348 self.pic_height_in_luma_samples.div_ceil(self.ctb_size())
349 }
350
351 /// `SubWidthC`, `SubHeightC` for the chroma format.
352 pub fn chroma_subsampling(&self) -> (u32, u32) {
353 match self.chroma_format_idc {
354 1 => (2, 2),
355 2 => (2, 1),
356 _ => (1, 1),
357 }
358 }
359
360 /// Displayed size after the conformance window is applied.
361 pub fn display_size(&self) -> (u32, u32) {
362 let (sub_w, sub_h) = self.chroma_subsampling();
363 (
364 self.pic_width_in_luma_samples - sub_w * (self.conf_win.left + self.conf_win.right),
365 self.pic_height_in_luma_samples - sub_h * (self.conf_win.top + self.conf_win.bottom),
366 )
367 }
368
369 /// Number of bits `slice_segment_address` occupies in a slice header:
370 /// `Ceil( Log2( PicSizeInCtbsY ) )`.
371 pub fn slice_address_bits(&self) -> u32 {
372 ceil_log2(self.pic_width_in_ctbs() * self.pic_height_in_ctbs())
373 }
374
375 /// The RBSP, trailing bits included.
376 pub fn to_rbsp(&self) -> Vec<u8> {
377 let mut w = BitWriter::with_capacity(64);
378 w.write_bits(u32::from(self.vps_id), 4);
379 w.write_bits(0, 3); // sps_max_sub_layers_minus1
380 w.write_bit(true); // sps_temporal_id_nesting_flag
381 self.ptl.write(&mut w);
382 w.write_ue(self.id);
383 w.write_ue(self.chroma_format_idc);
384 if self.chroma_format_idc == 3 {
385 w.write_bit(self.separate_colour_plane);
386 }
387 w.write_ue(self.pic_width_in_luma_samples);
388 w.write_ue(self.pic_height_in_luma_samples);
389 if self.conf_win.is_empty() {
390 w.write_bit(false);
391 } else {
392 w.write_bit(true);
393 w.write_ue(self.conf_win.left);
394 w.write_ue(self.conf_win.right);
395 w.write_ue(self.conf_win.top);
396 w.write_ue(self.conf_win.bottom);
397 }
398 w.write_ue(self.bit_depth_luma_minus8);
399 w.write_ue(self.bit_depth_chroma_minus8);
400 w.write_ue(self.log2_max_poc_lsb_minus4);
401 w.write_bit(true); // sps_sub_layer_ordering_info_present_flag
402 w.write_ue(self.max_dec_pic_buffering_minus1);
403 w.write_ue(self.max_num_reorder_pics);
404 w.write_ue(0); // sps_max_latency_increase_plus1
405 w.write_ue(self.log2_min_cb_size_minus3);
406 w.write_ue(self.log2_diff_max_min_cb_size);
407 w.write_ue(self.log2_min_tb_size_minus2);
408 w.write_ue(self.log2_diff_max_min_tb_size);
409 w.write_ue(self.max_transform_hierarchy_depth_inter);
410 w.write_ue(self.max_transform_hierarchy_depth_intra);
411 w.write_bit(self.scaling_list_enabled);
412 if self.scaling_list_enabled {
413 w.write_bit(false); // sps_scaling_list_data_present_flag
414 }
415 w.write_bit(self.amp_enabled);
416 w.write_bit(self.sao_enabled);
417 w.write_bit(self.pcm_enabled);
418 if let Some((luma, chroma, log2_min, log2_diff, filter_off)) = self.pcm {
419 w.write_bits(luma, 4);
420 w.write_bits(chroma, 4);
421 w.write_ue(log2_min);
422 w.write_ue(log2_diff);
423 w.write_bit(filter_off);
424 }
425 w.write_ue(self.num_short_term_ref_pic_sets);
426 for (i, set) in self.short_term_ref_pic_sets.iter().enumerate() {
427 set.write(&mut w, i as u32);
428 }
429 w.write_bit(self.long_term_ref_pics_present);
430 if self.long_term_ref_pics_present {
431 w.write_ue(self.num_long_term_ref_pics_sps);
432 for &(poc_lsb_lt, used_by_curr) in &self.long_term_ref_pics_sps {
433 w.write_bits(poc_lsb_lt, self.log2_max_poc_lsb_minus4 + 4);
434 w.write_bit(used_by_curr);
435 }
436 }
437 w.write_bit(self.temporal_mvp_enabled);
438 w.write_bit(self.strong_intra_smoothing);
439 match &self.vui {
440 Some(vui) => {
441 w.write_bit(true);
442 vui.write(&mut w);
443 }
444 None => w.write_bit(false),
445 }
446 w.write_bit(false); // sps_extension_present_flag
447 rbsp_trailing_bits(&mut w);
448 w.into_bytes()
449 }
450
451 /// Parse an SPS RBSP.
452 ///
453 /// Short-term reference picture sets are walked but not kept: a decoder
454 /// resolves them from the slice header, and this family's own streams have
455 /// none. A stream with scaling lists is refused rather than mis-decoded.
456 pub fn parse(rbsp: &[u8]) -> Result<Sps> {
457 let mut r = BitReader::new(rbsp);
458 let vps_id = r.read_bits(4)? as u8;
459 let max_sub_layers_minus1 = r.read_bits(3)?;
460 r.read_bit()?; // sps_temporal_id_nesting_flag
461 let ptl = ProfileTierLevel::parse(&mut r, max_sub_layers_minus1)?;
462 let id = r.read_ue()?;
463 let chroma_format_idc = r.read_ue()?;
464 if chroma_format_idc > 3 {
465 return Err(Error::corrupt(format!(
466 "HEVC SPS: chroma_format_idc = {chroma_format_idc}"
467 )));
468 }
469 let separate_colour_plane = if chroma_format_idc == 3 {
470 r.read_bit()?
471 } else {
472 false
473 };
474 let pic_width_in_luma_samples = r.read_ue()?;
475 let pic_height_in_luma_samples = r.read_ue()?;
476 // A dimension is a bit width elsewhere (slice_segment_address is
477 // Ceil(Log2(PicSizeInCtbsY)) bits), so an absurd one is refused here
478 // rather than turned into an absurd shift there.
479 if pic_width_in_luma_samples == 0
480 || pic_height_in_luma_samples == 0
481 || pic_width_in_luma_samples > 65_536
482 || pic_height_in_luma_samples > 65_536
483 {
484 return Err(Error::corrupt(format!(
485 "HEVC SPS: picture size {pic_width_in_luma_samples}x{pic_height_in_luma_samples}"
486 )));
487 }
488 let mut conf_win = ConformanceWindow::default();
489 if r.read_bit()? {
490 conf_win = ConformanceWindow {
491 left: r.read_ue()?,
492 right: r.read_ue()?,
493 top: r.read_ue()?,
494 bottom: r.read_ue()?,
495 };
496 }
497 let bit_depth_luma_minus8 = r.read_ue()?;
498 let bit_depth_chroma_minus8 = r.read_ue()?;
499 if bit_depth_luma_minus8 > 8 || bit_depth_chroma_minus8 > 8 {
500 return Err(Error::corrupt("HEVC SPS: bit depth out of range"));
501 }
502 let log2_max_poc_lsb_minus4 = r.read_ue()?;
503 if log2_max_poc_lsb_minus4 > 12 {
504 return Err(Error::corrupt(format!(
505 "HEVC SPS: log2_max_pic_order_cnt_lsb_minus4 = {log2_max_poc_lsb_minus4}"
506 )));
507 }
508 let ordering_info = r.read_bit()?;
509 let first = if ordering_info {
510 0
511 } else {
512 max_sub_layers_minus1
513 };
514 let mut max_dec_pic_buffering_minus1 = 0;
515 let mut max_num_reorder_pics = 0;
516 for _ in first..=max_sub_layers_minus1 {
517 max_dec_pic_buffering_minus1 = r.read_ue()?;
518 max_num_reorder_pics = r.read_ue()?;
519 r.read_ue()?;
520 }
521 let log2_min_cb_size_minus3 = r.read_ue()?;
522 let log2_diff_max_min_cb_size = r.read_ue()?;
523 let log2_min_tb_size_minus2 = r.read_ue()?;
524 let log2_diff_max_min_tb_size = r.read_ue()?;
525 if log2_min_cb_size_minus3 + log2_diff_max_min_cb_size > 3 {
526 return Err(Error::corrupt("HEVC SPS: CTB larger than 64x64"));
527 }
528 let max_transform_hierarchy_depth_inter = r.read_ue()?;
529 let max_transform_hierarchy_depth_intra = r.read_ue()?;
530 let scaling_list_enabled = r.read_bit()?;
531 if scaling_list_enabled && r.read_bit()? {
532 return Err(Error::unsupported(
533 "HEVC SPS scaling lists",
534 "this family codes with the flat 16 matrix only",
535 ));
536 }
537 let amp_enabled = r.read_bit()?;
538 let sao_enabled = r.read_bit()?;
539 let pcm_enabled = r.read_bit()?;
540 let pcm = if pcm_enabled {
541 Some((
542 r.read_bits(4)?,
543 r.read_bits(4)?,
544 r.read_ue()?,
545 r.read_ue()?,
546 r.read_bit()?,
547 ))
548 } else {
549 None
550 };
551 let num_short_term_ref_pic_sets = r.read_ue()?;
552 if num_short_term_ref_pic_sets > 64 {
553 return Err(Error::corrupt("HEVC SPS: num_short_term_ref_pic_sets > 64"));
554 }
555 let mut sets = Vec::new();
556 for i in 0..num_short_term_ref_pic_sets {
557 let set = ShortTermRefPicSet::parse(&mut r, i, &sets)?;
558 sets.push(set);
559 }
560 let long_term_ref_pics_present = r.read_bit()?;
561 let mut num_long_term_ref_pics_sps = 0;
562 let mut long_term_ref_pics_sps = Vec::new();
563 if long_term_ref_pics_present {
564 num_long_term_ref_pics_sps = r.read_ue()?;
565 if num_long_term_ref_pics_sps > 32 {
566 return Err(Error::corrupt(format!(
567 "HEVC SPS: num_long_term_ref_pics_sps = {num_long_term_ref_pics_sps}"
568 )));
569 }
570 for _ in 0..num_long_term_ref_pics_sps {
571 let poc_lsb_lt = r.read_bits(log2_max_poc_lsb_minus4 + 4)?;
572 let used_by_curr = r.read_bit()?;
573 long_term_ref_pics_sps.push((poc_lsb_lt, used_by_curr));
574 }
575 }
576 let temporal_mvp_enabled = r.read_bit()?;
577 let strong_intra_smoothing = r.read_bit()?;
578 let vui = if r.read_bit()? {
579 Some(VuiParameters::parse(&mut r, max_sub_layers_minus1)?)
580 } else {
581 None
582 };
583 Ok(Sps {
584 vps_id,
585 id,
586 chroma_format_idc,
587 separate_colour_plane,
588 pic_width_in_luma_samples,
589 pic_height_in_luma_samples,
590 conf_win,
591 bit_depth_luma_minus8,
592 bit_depth_chroma_minus8,
593 log2_max_poc_lsb_minus4,
594 max_dec_pic_buffering_minus1,
595 max_num_reorder_pics,
596 log2_min_cb_size_minus3,
597 log2_diff_max_min_cb_size,
598 log2_min_tb_size_minus2,
599 log2_diff_max_min_tb_size,
600 max_transform_hierarchy_depth_inter,
601 max_transform_hierarchy_depth_intra,
602 scaling_list_enabled,
603 amp_enabled,
604 sao_enabled,
605 pcm_enabled,
606 pcm,
607 num_short_term_ref_pic_sets,
608 short_term_ref_pic_sets: sets,
609 long_term_ref_pics_present,
610 num_long_term_ref_pics_sps,
611 long_term_ref_pics_sps,
612 temporal_mvp_enabled,
613 strong_intra_smoothing,
614 ptl,
615 vui,
616 })
617 }
618}
619
620/// Largest `st_ref_pic_set()` this crate carries in either direction; the spec
621/// caps `NumNegativePics` and `NumPositivePics` at `sps_max_dec_pic_buffering`,
622/// which itself cannot exceed 16.
623pub const MAX_ST_REF_PICS: usize = 16;
624
625/// One `st_ref_pic_set()` (7.3.7), with the POC deltas a decoder needs.
626///
627/// A *stateless hardware* decoder is the reason the deltas are here: the driver
628/// is handed `RefPicSetStCurrBefore` / `StCurrAfter` as picture lists, so
629/// something has to turn `delta_poc_sX_minus1` into actual reference pictures,
630/// and that something is the caller of this crate.
631#[derive(Debug, Clone, Copy, PartialEq, Eq)]
632pub struct ShortTermRefPicSet {
633 /// `NumNegativePics`.
634 pub num_negative: u32,
635 /// `NumPositivePics`.
636 pub num_positive: u32,
637 /// How many of them have `used_by_curr_pic` set — the count that feeds
638 /// `NumPicTotalCurr`, which sizes the reference list modification syntax.
639 pub num_used_by_curr: u32,
640 /// `DeltaPocS0[i]`, negative, in decreasing order (7-59).
641 pub delta_poc_s0: [i32; MAX_ST_REF_PICS],
642 /// `UsedByCurrPicS0[i]`.
643 pub used_s0: [bool; MAX_ST_REF_PICS],
644 /// `DeltaPocS1[i]`, positive, in increasing order (7-60).
645 pub delta_poc_s1: [i32; MAX_ST_REF_PICS],
646 /// `UsedByCurrPicS1[i]`.
647 pub used_s1: [bool; MAX_ST_REF_PICS],
648}
649
650impl Default for ShortTermRefPicSet {
651 fn default() -> ShortTermRefPicSet {
652 ShortTermRefPicSet {
653 num_negative: 0,
654 num_positive: 0,
655 num_used_by_curr: 0,
656 delta_poc_s0: [0; MAX_ST_REF_PICS],
657 used_s0: [false; MAX_ST_REF_PICS],
658 delta_poc_s1: [0; MAX_ST_REF_PICS],
659 used_s1: [false; MAX_ST_REF_PICS],
660 }
661 }
662}
663
664impl ShortTermRefPicSet {
665 /// Parse one set; `prev` holds the sets already parsed for inter-set prediction.
666 pub fn parse(
667 r: &mut BitReader,
668 idx: u32,
669 prev: &[ShortTermRefPicSet],
670 ) -> Result<ShortTermRefPicSet> {
671 let inter_ref_pic_set_prediction = if idx != 0 { r.read_bit()? } else { false };
672 if inter_ref_pic_set_prediction {
673 let delta_idx_minus1 = if idx == prev.len() as u32 {
674 r.read_ue()?
675 } else {
676 0
677 };
678 let ref_idx = idx
679 .checked_sub(delta_idx_minus1 + 1)
680 .ok_or_else(|| Error::corrupt("HEVC st_ref_pic_set: delta_idx out of range"))?;
681 let reference = *prev
682 .get(ref_idx as usize)
683 .ok_or_else(|| Error::corrupt("HEVC st_ref_pic_set: unknown reference set"))?;
684 let delta_rps_sign = r.read_bit()?;
685 let abs_delta_rps_minus1 = r.read_ue()?;
686 let delta_rps = if delta_rps_sign {
687 -((abs_delta_rps_minus1 + 1) as i32)
688 } else {
689 (abs_delta_rps_minus1 + 1) as i32
690 };
691 let num_delta_pocs = (reference.num_negative + reference.num_positive) as usize;
692 if num_delta_pocs >= MAX_ST_REF_PICS * 2 {
693 return Err(Error::corrupt(
694 "HEVC st_ref_pic_set: reference set too large",
695 ));
696 }
697 let mut used_by_curr = [false; MAX_ST_REF_PICS * 2 + 1];
698 let mut use_delta = [true; MAX_ST_REF_PICS * 2 + 1];
699 for j in 0..=num_delta_pocs {
700 used_by_curr[j] = r.read_bit()?;
701 if !used_by_curr[j] {
702 use_delta[j] = r.read_bit()?;
703 }
704 }
705 Ok(reference.predict(delta_rps, &used_by_curr, &use_delta))
706 } else {
707 let num_negative = r.read_ue()?;
708 let num_positive = r.read_ue()?;
709 if num_negative as usize > MAX_ST_REF_PICS || num_positive as usize > MAX_ST_REF_PICS {
710 return Err(Error::corrupt("HEVC st_ref_pic_set: too many pictures"));
711 }
712 let mut set = ShortTermRefPicSet {
713 num_negative,
714 num_positive,
715 ..ShortTermRefPicSet::default()
716 };
717 let mut poc = 0i32;
718 for i in 0..num_negative as usize {
719 let delta = r.read_ue()? as i32 + 1;
720 poc -= delta;
721 set.delta_poc_s0[i] = poc;
722 set.used_s0[i] = r.read_bit()?;
723 if set.used_s0[i] {
724 set.num_used_by_curr += 1;
725 }
726 }
727 let mut poc = 0i32;
728 for i in 0..num_positive as usize {
729 let delta = r.read_ue()? as i32 + 1;
730 poc += delta;
731 set.delta_poc_s1[i] = poc;
732 set.used_s1[i] = r.read_bit()?;
733 if set.used_s1[i] {
734 set.num_used_by_curr += 1;
735 }
736 }
737 Ok(set)
738 }
739 }
740
741 /// Derive a set predicted from this one (7-61, 7-62).
742 ///
743 /// The two loops per direction are the spec's, and their order is what puts
744 /// `DeltaPocS0` in decreasing and `DeltaPocS1` in increasing order without a
745 /// sort: entries derived from the *other* direction of the reference set
746 /// come first, then the reference picture itself, then the same direction.
747 fn predict(
748 &self,
749 delta_rps: i32,
750 used_by_curr: &[bool],
751 use_delta: &[bool],
752 ) -> ShortTermRefPicSet {
753 let mut out = ShortTermRefPicSet::default();
754 let neg = self.num_negative as usize;
755 let pos = self.num_positive as usize;
756 let num_delta_pocs = neg + pos;
757
758 let mut i = 0usize;
759 for j in (0..pos).rev() {
760 let d = self.delta_poc_s1[j] + delta_rps;
761 if d < 0 && use_delta[neg + j] && i < MAX_ST_REF_PICS {
762 out.delta_poc_s0[i] = d;
763 out.used_s0[i] = used_by_curr[neg + j];
764 i += 1;
765 }
766 }
767 if delta_rps < 0 && use_delta[num_delta_pocs] && i < MAX_ST_REF_PICS {
768 out.delta_poc_s0[i] = delta_rps;
769 out.used_s0[i] = used_by_curr[num_delta_pocs];
770 i += 1;
771 }
772 for j in 0..neg {
773 let d = self.delta_poc_s0[j] + delta_rps;
774 if d < 0 && use_delta[j] && i < MAX_ST_REF_PICS {
775 out.delta_poc_s0[i] = d;
776 out.used_s0[i] = used_by_curr[j];
777 i += 1;
778 }
779 }
780 out.num_negative = i as u32;
781
782 let mut i = 0usize;
783 for j in (0..neg).rev() {
784 let d = self.delta_poc_s0[j] + delta_rps;
785 if d > 0 && use_delta[j] && i < MAX_ST_REF_PICS {
786 out.delta_poc_s1[i] = d;
787 out.used_s1[i] = used_by_curr[j];
788 i += 1;
789 }
790 }
791 if delta_rps > 0 && use_delta[num_delta_pocs] && i < MAX_ST_REF_PICS {
792 out.delta_poc_s1[i] = delta_rps;
793 out.used_s1[i] = used_by_curr[num_delta_pocs];
794 i += 1;
795 }
796 for j in 0..pos {
797 let d = self.delta_poc_s1[j] + delta_rps;
798 if d > 0 && use_delta[neg + j] && i < MAX_ST_REF_PICS {
799 out.delta_poc_s1[i] = d;
800 out.used_s1[i] = used_by_curr[neg + j];
801 i += 1;
802 }
803 }
804 out.num_positive = i as u32;
805 out.num_used_by_curr = out.used_s0[..out.num_negative as usize]
806 .iter()
807 .chain(out.used_s1[..out.num_positive as usize].iter())
808 .filter(|&&u| u)
809 .count() as u32;
810 out
811 }
812
813 /// Write the set in its non-predicted form (7.3.7), which is always legal.
814 pub fn write(&self, w: &mut ec_core::BitWriter, idx: u32) {
815 if idx != 0 {
816 w.write_bit(false); // inter_ref_pic_set_prediction_flag
817 }
818 w.write_ue(self.num_negative);
819 w.write_ue(self.num_positive);
820 let mut prev = 0i32;
821 for i in 0..self.num_negative as usize {
822 w.write_ue((prev - self.delta_poc_s0[i] - 1).max(0) as u32);
823 prev = self.delta_poc_s0[i];
824 w.write_bit(self.used_s0[i]);
825 }
826 let mut prev = 0i32;
827 for i in 0..self.num_positive as usize {
828 w.write_ue((self.delta_poc_s1[i] - prev - 1).max(0) as u32);
829 prev = self.delta_poc_s1[i];
830 w.write_bit(self.used_s1[i]);
831 }
832 }
833}
834
835/// The picture parameter set (7.3.2.3.1).
836#[derive(Debug, Clone, PartialEq, Eq)]
837pub struct Pps {
838 /// `pps_pic_parameter_set_id`.
839 pub id: u32,
840 /// `pps_seq_parameter_set_id`.
841 pub sps_id: u32,
842 /// `dependent_slice_segments_enabled_flag`.
843 pub dependent_slice_segments_enabled: bool,
844 /// `output_flag_present_flag`.
845 pub output_flag_present: bool,
846 /// `num_extra_slice_header_bits`.
847 pub num_extra_slice_header_bits: u32,
848 /// `sign_data_hiding_enabled_flag`.
849 pub sign_data_hiding_enabled: bool,
850 /// `cabac_init_present_flag`.
851 pub cabac_init_present: bool,
852 /// `num_ref_idx_l0_default_active_minus1`.
853 pub num_ref_idx_l0_default_active_minus1: u32,
854 /// `num_ref_idx_l1_default_active_minus1`.
855 pub num_ref_idx_l1_default_active_minus1: u32,
856 /// `init_qp_minus26`.
857 pub init_qp_minus26: i32,
858 /// `constrained_intra_pred_flag`.
859 pub constrained_intra_pred: bool,
860 /// `transform_skip_enabled_flag`.
861 pub transform_skip_enabled: bool,
862 /// `cu_qp_delta_enabled_flag`.
863 pub cu_qp_delta_enabled: bool,
864 /// `diff_cu_qp_delta_depth`.
865 pub diff_cu_qp_delta_depth: u32,
866 /// `pps_cb_qp_offset`.
867 pub cb_qp_offset: i32,
868 /// `pps_cr_qp_offset`.
869 pub cr_qp_offset: i32,
870 /// `pps_slice_chroma_qp_offsets_present_flag`.
871 pub slice_chroma_qp_offsets_present: bool,
872 /// `weighted_pred_flag`.
873 pub weighted_pred: bool,
874 /// `weighted_bipred_flag`.
875 pub weighted_bipred: bool,
876 /// `transquant_bypass_enabled_flag`.
877 pub transquant_bypass_enabled: bool,
878 /// `tiles_enabled_flag`.
879 pub tiles_enabled: bool,
880 /// `entropy_coding_sync_enabled_flag` — wavefront parallel processing.
881 pub entropy_coding_sync_enabled: bool,
882 /// `num_tile_columns_minus1`.
883 pub num_tile_columns_minus1: u32,
884 /// `num_tile_rows_minus1`.
885 pub num_tile_rows_minus1: u32,
886 /// `uniform_spacing_flag`.
887 pub uniform_spacing: bool,
888 /// `column_width_minus1[]`, empty when the spacing is uniform (a decoder
889 /// derives the widths then, and so should a caller).
890 pub column_width_minus1: Vec<u32>,
891 /// `row_height_minus1[]`, empty when the spacing is uniform.
892 pub row_height_minus1: Vec<u32>,
893 /// `loop_filter_across_tiles_enabled_flag`.
894 pub loop_filter_across_tiles_enabled: bool,
895 /// `pps_loop_filter_across_slices_enabled_flag`.
896 pub loop_filter_across_slices_enabled: bool,
897 /// `deblocking_filter_control_present_flag`.
898 pub deblocking_filter_control_present: bool,
899 /// `deblocking_filter_override_enabled_flag`.
900 pub deblocking_filter_override_enabled: bool,
901 /// `pps_deblocking_filter_disabled_flag`.
902 pub deblocking_filter_disabled: bool,
903 /// `pps_beta_offset_div2`.
904 pub beta_offset_div2: i32,
905 /// `pps_tc_offset_div2`.
906 pub tc_offset_div2: i32,
907 /// `lists_modification_present_flag`.
908 pub lists_modification_present: bool,
909 /// `log2_parallel_merge_level_minus2`.
910 pub log2_parallel_merge_level_minus2: u32,
911 /// `slice_segment_header_extension_present_flag`.
912 pub slice_segment_header_extension_present: bool,
913}
914
915impl Default for Pps {
916 fn default() -> Self {
917 Pps {
918 id: 0,
919 sps_id: 0,
920 dependent_slice_segments_enabled: false,
921 output_flag_present: false,
922 num_extra_slice_header_bits: 0,
923 sign_data_hiding_enabled: false,
924 cabac_init_present: false,
925 num_ref_idx_l0_default_active_minus1: 0,
926 num_ref_idx_l1_default_active_minus1: 0,
927 init_qp_minus26: 0,
928 constrained_intra_pred: false,
929 transform_skip_enabled: false,
930 cu_qp_delta_enabled: false,
931 diff_cu_qp_delta_depth: 0,
932 cb_qp_offset: 0,
933 cr_qp_offset: 0,
934 slice_chroma_qp_offsets_present: false,
935 weighted_pred: false,
936 weighted_bipred: false,
937 transquant_bypass_enabled: false,
938 tiles_enabled: false,
939 entropy_coding_sync_enabled: false,
940 num_tile_columns_minus1: 0,
941 num_tile_rows_minus1: 0,
942 uniform_spacing: true,
943 column_width_minus1: Vec::new(),
944 row_height_minus1: Vec::new(),
945 loop_filter_across_tiles_enabled: true,
946 loop_filter_across_slices_enabled: true,
947 deblocking_filter_control_present: false,
948 deblocking_filter_override_enabled: false,
949 deblocking_filter_disabled: false,
950 beta_offset_div2: 0,
951 tc_offset_div2: 0,
952 lists_modification_present: false,
953 log2_parallel_merge_level_minus2: 0,
954 slice_segment_header_extension_present: false,
955 }
956 }
957}
958
959impl Pps {
960 /// The RBSP, trailing bits included.
961 pub fn to_rbsp(&self) -> Vec<u8> {
962 let mut w = BitWriter::with_capacity(32);
963 w.write_ue(self.id);
964 w.write_ue(self.sps_id);
965 w.write_bit(self.dependent_slice_segments_enabled);
966 w.write_bit(self.output_flag_present);
967 w.write_bits(self.num_extra_slice_header_bits, 3);
968 w.write_bit(self.sign_data_hiding_enabled);
969 w.write_bit(self.cabac_init_present);
970 w.write_ue(self.num_ref_idx_l0_default_active_minus1);
971 w.write_ue(self.num_ref_idx_l1_default_active_minus1);
972 w.write_se(self.init_qp_minus26);
973 w.write_bit(self.constrained_intra_pred);
974 w.write_bit(self.transform_skip_enabled);
975 w.write_bit(self.cu_qp_delta_enabled);
976 if self.cu_qp_delta_enabled {
977 w.write_ue(self.diff_cu_qp_delta_depth);
978 }
979 w.write_se(self.cb_qp_offset);
980 w.write_se(self.cr_qp_offset);
981 w.write_bit(self.slice_chroma_qp_offsets_present);
982 w.write_bit(self.weighted_pred);
983 w.write_bit(self.weighted_bipred);
984 w.write_bit(self.transquant_bypass_enabled);
985 w.write_bit(self.tiles_enabled);
986 w.write_bit(self.entropy_coding_sync_enabled);
987 if self.tiles_enabled {
988 w.write_ue(self.num_tile_columns_minus1);
989 w.write_ue(self.num_tile_rows_minus1);
990 w.write_bit(self.uniform_spacing);
991 if !self.uniform_spacing {
992 for &width in &self.column_width_minus1 {
993 w.write_ue(width);
994 }
995 for &height in &self.row_height_minus1 {
996 w.write_ue(height);
997 }
998 }
999 w.write_bit(self.loop_filter_across_tiles_enabled);
1000 }
1001 w.write_bit(self.loop_filter_across_slices_enabled);
1002 w.write_bit(self.deblocking_filter_control_present);
1003 if self.deblocking_filter_control_present {
1004 w.write_bit(self.deblocking_filter_override_enabled);
1005 w.write_bit(self.deblocking_filter_disabled);
1006 if !self.deblocking_filter_disabled {
1007 w.write_se(self.beta_offset_div2);
1008 w.write_se(self.tc_offset_div2);
1009 }
1010 }
1011 w.write_bit(false); // pps_scaling_list_data_present_flag
1012 w.write_bit(self.lists_modification_present);
1013 w.write_ue(self.log2_parallel_merge_level_minus2);
1014 w.write_bit(self.slice_segment_header_extension_present);
1015 w.write_bit(false); // pps_extension_present_flag
1016 rbsp_trailing_bits(&mut w);
1017 w.into_bytes()
1018 }
1019
1020 /// Parse a PPS RBSP.
1021 pub fn parse(rbsp: &[u8]) -> Result<Pps> {
1022 let mut r = BitReader::new(rbsp);
1023 let mut pps = Pps {
1024 id: r.read_ue()?,
1025 sps_id: r.read_ue()?,
1026 ..Pps::default()
1027 };
1028 pps.dependent_slice_segments_enabled = r.read_bit()?;
1029 pps.output_flag_present = r.read_bit()?;
1030 pps.num_extra_slice_header_bits = r.read_bits(3)?;
1031 pps.sign_data_hiding_enabled = r.read_bit()?;
1032 pps.cabac_init_present = r.read_bit()?;
1033 pps.num_ref_idx_l0_default_active_minus1 = r.read_ue()?;
1034 pps.num_ref_idx_l1_default_active_minus1 = r.read_ue()?;
1035 pps.init_qp_minus26 = r.read_se()?;
1036 pps.constrained_intra_pred = r.read_bit()?;
1037 pps.transform_skip_enabled = r.read_bit()?;
1038 pps.cu_qp_delta_enabled = r.read_bit()?;
1039 if pps.cu_qp_delta_enabled {
1040 pps.diff_cu_qp_delta_depth = r.read_ue()?;
1041 }
1042 pps.cb_qp_offset = r.read_se()?;
1043 pps.cr_qp_offset = r.read_se()?;
1044 pps.slice_chroma_qp_offsets_present = r.read_bit()?;
1045 pps.weighted_pred = r.read_bit()?;
1046 pps.weighted_bipred = r.read_bit()?;
1047 pps.transquant_bypass_enabled = r.read_bit()?;
1048 pps.tiles_enabled = r.read_bit()?;
1049 pps.entropy_coding_sync_enabled = r.read_bit()?;
1050 if pps.tiles_enabled {
1051 pps.num_tile_columns_minus1 = r.read_ue()?;
1052 pps.num_tile_rows_minus1 = r.read_ue()?;
1053 pps.uniform_spacing = r.read_bit()?;
1054 if !pps.uniform_spacing {
1055 if pps.num_tile_columns_minus1 > 20 || pps.num_tile_rows_minus1 > 22 {
1056 return Err(Error::corrupt("HEVC PPS: tile count beyond any level"));
1057 }
1058 for _ in 0..pps.num_tile_columns_minus1 {
1059 let value = r.read_ue()?;
1060 pps.column_width_minus1.push(value);
1061 }
1062 for _ in 0..pps.num_tile_rows_minus1 {
1063 let value = r.read_ue()?;
1064 pps.row_height_minus1.push(value);
1065 }
1066 }
1067 pps.loop_filter_across_tiles_enabled = r.read_bit()?;
1068 }
1069 pps.loop_filter_across_slices_enabled = r.read_bit()?;
1070 pps.deblocking_filter_control_present = r.read_bit()?;
1071 if pps.deblocking_filter_control_present {
1072 pps.deblocking_filter_override_enabled = r.read_bit()?;
1073 pps.deblocking_filter_disabled = r.read_bit()?;
1074 if !pps.deblocking_filter_disabled {
1075 pps.beta_offset_div2 = r.read_se()?;
1076 pps.tc_offset_div2 = r.read_se()?;
1077 }
1078 }
1079 if r.read_bit()? {
1080 return Err(Error::unsupported(
1081 "HEVC PPS scaling lists",
1082 "this family codes with the flat 16 matrix only",
1083 ));
1084 }
1085 pps.lists_modification_present = r.read_bit()?;
1086 pps.log2_parallel_merge_level_minus2 = r.read_ue()?;
1087 pps.slice_segment_header_extension_present = r.read_bit()?;
1088 Ok(pps)
1089 }
1090}
1091
1092/// `rbsp_trailing_bits()`: a one bit then zeros to the byte boundary.
1093pub fn rbsp_trailing_bits(w: &mut BitWriter) {
1094 w.write_bit(true);
1095 w.align_to_byte();
1096}
1097
1098/// `Ceil( Log2( v ) )`, the width of a `u(v)` field counting `v` values.
1099pub fn ceil_log2(v: u32) -> u32 {
1100 let mut bits = 0;
1101 while (1u64 << bits) < u64::from(v) {
1102 bits += 1;
1103 }
1104 bits
1105}
1106
1107#[cfg(test)]
1108mod tests {
1109 use super::*;
1110 use crate::vui::{ColourDescription, VideoSignalType};
1111
1112 fn sample_sps() -> Sps {
1113 Sps {
1114 vps_id: 0,
1115 id: 0,
1116 chroma_format_idc: 1,
1117 separate_colour_plane: false,
1118 pic_width_in_luma_samples: 1920,
1119 pic_height_in_luma_samples: 1088,
1120 conf_win: ConformanceWindow {
1121 left: 0,
1122 right: 0,
1123 top: 0,
1124 bottom: 4,
1125 },
1126 bit_depth_luma_minus8: 0,
1127 bit_depth_chroma_minus8: 0,
1128 log2_max_poc_lsb_minus4: 4,
1129 max_dec_pic_buffering_minus1: 0,
1130 max_num_reorder_pics: 0,
1131 log2_min_cb_size_minus3: 0,
1132 log2_diff_max_min_cb_size: 3,
1133 log2_min_tb_size_minus2: 0,
1134 log2_diff_max_min_tb_size: 3,
1135 max_transform_hierarchy_depth_inter: 0,
1136 max_transform_hierarchy_depth_intra: 0,
1137 scaling_list_enabled: false,
1138 amp_enabled: false,
1139 sao_enabled: false,
1140 pcm_enabled: false,
1141 pcm: None,
1142 num_short_term_ref_pic_sets: 0,
1143 short_term_ref_pic_sets: Vec::new(),
1144 long_term_ref_pics_present: false,
1145 num_long_term_ref_pics_sps: 0,
1146 long_term_ref_pics_sps: Vec::new(),
1147 temporal_mvp_enabled: false,
1148 strong_intra_smoothing: true,
1149 ptl: ProfileTierLevel::main(120),
1150 vui: Some(VuiParameters {
1151 sample_aspect_ratio: Some((1, 1)),
1152 video_signal_type: Some(VideoSignalType {
1153 video_format: 5,
1154 video_full_range_flag: false,
1155 colour_description: Some(ColourDescription {
1156 colour_primaries: 1,
1157 transfer_characteristics: 1,
1158 matrix_coeffs: 1,
1159 }),
1160 }),
1161 timing: Some((1, 30)),
1162 }),
1163 }
1164 }
1165
1166 #[test]
1167 fn parameter_sets_round_trip() {
1168 let vps = Vps {
1169 id: 0,
1170 ptl: ProfileTierLevel::main(120),
1171 max_dec_pic_buffering_minus1: 0,
1172 max_num_reorder_pics: 0,
1173 };
1174 assert_eq!(Vps::parse(&vps.to_rbsp()).unwrap(), vps);
1175
1176 let sps = sample_sps();
1177 let parsed = Sps::parse(&sps.to_rbsp()).unwrap();
1178 assert_eq!(parsed, sps);
1179 // 1080 is cropped back out of the 1088 coded rows.
1180 assert_eq!(parsed.display_size(), (1920, 1080));
1181 assert_eq!(parsed.ctb_size(), 64);
1182 assert_eq!(parsed.pic_width_in_ctbs(), 30);
1183 assert_eq!(parsed.pic_height_in_ctbs(), 17);
1184
1185 let pps = Pps {
1186 entropy_coding_sync_enabled: true,
1187 init_qp_minus26: 1,
1188 deblocking_filter_control_present: true,
1189 deblocking_filter_disabled: true,
1190 ..Pps::default()
1191 };
1192 assert_eq!(Pps::parse(&pps.to_rbsp()).unwrap(), pps);
1193
1194 // The fields a hardware decoder needs but this family's own encoder
1195 // never writes: explicit tile geometry and PCM.
1196 let tiled = Pps {
1197 tiles_enabled: true,
1198 num_tile_columns_minus1: 2,
1199 num_tile_rows_minus1: 1,
1200 uniform_spacing: false,
1201 column_width_minus1: vec![9, 19],
1202 row_height_minus1: vec![7],
1203 loop_filter_across_tiles_enabled: false,
1204 cu_qp_delta_enabled: true,
1205 diff_cu_qp_delta_depth: 2,
1206 cb_qp_offset: -3,
1207 cr_qp_offset: 4,
1208 ..Pps::default()
1209 };
1210 assert_eq!(Pps::parse(&tiled.to_rbsp()).unwrap(), tiled);
1211
1212 let pcm = Sps {
1213 pcm_enabled: true,
1214 pcm: Some((7, 7, 0, 2, true)),
1215 sao_enabled: true,
1216 ..sample_sps()
1217 };
1218 assert_eq!(Sps::parse(&pcm.to_rbsp()).unwrap(), pcm);
1219 }
1220
1221 #[test]
1222 fn levels_round_up_with_size_and_rate() {
1223 assert_eq!(ProfileTierLevel::level_for(1920, 1080, 30.0), 120); // 4
1224 assert_eq!(ProfileTierLevel::level_for(1920, 1080, 60.0), 123); // 4.1
1225 assert_eq!(ProfileTierLevel::level_for(3840, 2160, 30.0), 150); // 5
1226 assert_eq!(ProfileTierLevel::level_for(640, 480, 30.0), 90); // 3
1227 }
1228
1229 #[test]
1230 fn ceil_log2_counts_values() {
1231 assert_eq!(ceil_log2(1), 0);
1232 assert_eq!(ceil_log2(2), 1);
1233 assert_eq!(ceil_log2(510), 9);
1234 assert_eq!(ceil_log2(512), 9);
1235 assert_eq!(ceil_log2(513), 10);
1236 }
1237}