forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

parser.rs5494 lines, 240.5 KiBHistoryRawDownload
1// Copyright 2023 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! An Annex B h.265 parser.
6//!
7//! Parses VPSs, SPSs, PPSs and Slices from NALUs.
8
9use std::collections::BTreeMap;
10use std::io::Read;
11use std::io::Seek;
12use std::io::SeekFrom;
13use std::rc::Rc;
14
15use crate::bitstream_utils::BitReader;
16use crate::codec::h264::nalu;
17use crate::codec::h264::nalu::Header;
18use crate::codec::h264::parser::Point;
19use crate::codec::h264::parser::Rect;
20
21// Given the max VPS id.
22const MAX_VPS_COUNT: usize = 16;
23// Given the max SPS id.
24const MAX_SPS_COUNT: usize = 16;
25// Given the max PPS id.
26const MAX_PPS_COUNT: usize = 64;
27// 7.4.7.1
28const MAX_REF_IDX_ACTIVE: u32 = 15;
29
30// 7.4.3.2.1:
31// num_short_term_ref_pic_sets specifies the number of st_ref_pic_set( ) syntax
32// structures included in the SPS. The value of num_short_term_ref_pic_sets
33// shall be in the range of 0 to 64, inclusive.
34// NOTE 5 – A decoder should allocate memory for a total number of
35// num_short_term_ref_pic_sets + 1 st_ref_pic_set( ) syntax structures since
36// there may be a st_ref_pic_set( ) syntax structure directly signalled in the
37// slice headers of a current picture. A st_ref_pic_set( ) syntax structure
38// directly signalled in the slice headers of a current picture has an index
39// equal to num_short_term_ref_pic_sets.
40const MAX_SHORT_TERM_REF_PIC_SETS: usize = 65;
41
42// 7.4.3.2.1:
43const MAX_LONG_TERM_REF_PIC_SETS: usize = 32;
44
45// From table 7-5.
46const DEFAULT_SCALING_LIST_0: [u8; 16] = [16; 16];
47
48// From Table 7-6.
49const DEFAULT_SCALING_LIST_1: [u8; 64] = [
50 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 17, 16, 17, 18, 17, 18, 18, 17, 18, 21, 19, 20,
51 21, 20, 19, 21, 24, 22, 22, 24, 24, 22, 22, 24, 25, 25, 27, 30, 27, 25, 25, 29, 31, 35, 35, 31,
52 29, 36, 41, 44, 41, 36, 47, 54, 54, 47, 65, 70, 65, 88, 88, 115,
53];
54
55// From Table 7-6.
56const DEFAULT_SCALING_LIST_2: [u8; 64] = [
57 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 20, 20, 20,
58 20, 20, 20, 20, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 28, 28, 28, 28, 28,
59 28, 33, 33, 33, 33, 33, 41, 41, 41, 41, 54, 54, 54, 71, 71, 91,
60];
61
62/// Table 7-1 – NAL unit type codes and NAL unit type classes
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
64pub enum NaluType {
65 #[default]
66 TrailN = 0,
67 TrailR = 1,
68 TsaN = 2,
69 TsaR = 3,
70 StsaN = 4,
71 StsaR = 5,
72 RadlN = 6,
73 RadlR = 7,
74 RaslN = 8,
75 RaslR = 9,
76 RsvVclN10 = 10,
77 RsvVclR11 = 11,
78 RsvVclN12 = 12,
79 RsvVclR13 = 13,
80 RsvVclN14 = 14,
81 RsvVclR15 = 15,
82 BlaWLp = 16,
83 BlaWRadl = 17,
84 BlaNLp = 18,
85 IdrWRadl = 19,
86 IdrNLp = 20,
87 CraNut = 21,
88 RsvIrapVcl22 = 22,
89 RsvIrapVcl23 = 23,
90 RsvVcl24 = 24,
91 RsvVcl25 = 25,
92 RsvVcl26 = 26,
93 RsvVcl27 = 27,
94 RsvVcl28 = 28,
95 RsvVcl29 = 29,
96 RsvVcl30 = 30,
97 RsvVcl31 = 31,
98 VpsNut = 32,
99 SpsNut = 33,
100 PpsNut = 34,
101 AudNut = 35,
102 EosNut = 36,
103 EobNut = 37,
104 FdNut = 38,
105 PrefixSeiNut = 39,
106 SuffixSeiNut = 40,
107 RsvNvcl41 = 41,
108 RsvNvcl42 = 42,
109 RsvNvcl43 = 43,
110 RsvNvcl44 = 44,
111 RsvNvcl45 = 45,
112 RsvNvcl46 = 46,
113 RsvNvcl47 = 47,
114}
115
116impl TryFrom<u32> for NaluType {
117 type Error = String;
118
119 fn try_from(value: u32) -> Result<Self, Self::Error> {
120 match value {
121 0 => Ok(NaluType::TrailN),
122 1 => Ok(NaluType::TrailR),
123 2 => Ok(NaluType::TsaN),
124 3 => Ok(NaluType::TsaR),
125 4 => Ok(NaluType::StsaN),
126 5 => Ok(NaluType::StsaR),
127 6 => Ok(NaluType::RadlN),
128 7 => Ok(NaluType::RadlR),
129 8 => Ok(NaluType::RaslN),
130 9 => Ok(NaluType::RaslR),
131 10 => Ok(NaluType::RsvVclN10),
132 11 => Ok(NaluType::RsvVclR11),
133 12 => Ok(NaluType::RsvVclN12),
134 13 => Ok(NaluType::RsvVclR13),
135 14 => Ok(NaluType::RsvVclN14),
136 15 => Ok(NaluType::RsvVclR15),
137 16 => Ok(NaluType::BlaWLp),
138 17 => Ok(NaluType::BlaWRadl),
139 18 => Ok(NaluType::BlaNLp),
140 19 => Ok(NaluType::IdrWRadl),
141 20 => Ok(NaluType::IdrNLp),
142 21 => Ok(NaluType::CraNut),
143 22 => Ok(NaluType::RsvIrapVcl22),
144 23 => Ok(NaluType::RsvIrapVcl23),
145 24 => Ok(NaluType::RsvVcl24),
146 25 => Ok(NaluType::RsvVcl25),
147 26 => Ok(NaluType::RsvVcl26),
148 27 => Ok(NaluType::RsvVcl27),
149 28 => Ok(NaluType::RsvVcl28),
150 29 => Ok(NaluType::RsvVcl29),
151 30 => Ok(NaluType::RsvVcl30),
152 31 => Ok(NaluType::RsvVcl31),
153 32 => Ok(NaluType::VpsNut),
154 33 => Ok(NaluType::SpsNut),
155 34 => Ok(NaluType::PpsNut),
156 35 => Ok(NaluType::AudNut),
157 36 => Ok(NaluType::EosNut),
158 37 => Ok(NaluType::EobNut),
159 38 => Ok(NaluType::FdNut),
160 39 => Ok(NaluType::PrefixSeiNut),
161 40 => Ok(NaluType::SuffixSeiNut),
162 41 => Ok(NaluType::RsvNvcl41),
163 42 => Ok(NaluType::RsvNvcl42),
164 43 => Ok(NaluType::RsvNvcl43),
165 44 => Ok(NaluType::RsvNvcl44),
166 45 => Ok(NaluType::RsvNvcl45),
167 46 => Ok(NaluType::RsvNvcl46),
168 47 => Ok(NaluType::RsvNvcl47),
169 _ => Err(format!("Invalid NaluType {}", value)),
170 }
171 }
172}
173
174impl NaluType {
175 /// Whether this is an IDR NALU.
176 pub fn is_idr(&self) -> bool {
177 matches!(self, Self::IdrWRadl | Self::IdrNLp)
178 }
179
180 /// Whether this is an IRAP NALU.
181 pub fn is_irap(&self) -> bool {
182 let type_ = *self as u32;
183 type_ >= Self::BlaWLp as u32 && type_ <= Self::RsvIrapVcl23 as u32
184 }
185
186 /// Whether this is a BLA NALU.
187 pub fn is_bla(&self) -> bool {
188 let type_ = *self as u32;
189 type_ >= Self::BlaWLp as u32 && type_ <= Self::BlaNLp as u32
190 }
191
192 /// Whether this is a CRA NALU.
193 pub fn is_cra(&self) -> bool {
194 matches!(self, Self::CraNut)
195 }
196
197 /// Whether this is a RADL NALU.
198 pub fn is_radl(&self) -> bool {
199 matches!(self, Self::RadlN | Self::RadlR)
200 }
201
202 /// Whether this is a RASL NALU.
203 pub fn is_rasl(&self) -> bool {
204 matches!(self, Self::RaslN | Self::RaslR)
205 }
206
207 //// Whether this is a SLNR NALU.
208 pub fn is_slnr(&self) -> bool {
209 // From the specification:
210 // If a picture has nal_unit_type equal to TRAIL_N, TSA_N, STSA_N,
211 // RADL_N, RASL_N, RSV_VCL_N10, RSV_VCL_N12 or RSV_VCL_N14, the picture
212 // is an SLNR picture. Otherwise, the picture is a sub-layer reference
213 // picture.
214 matches!(
215 self,
216 Self::TrailN
217 | Self::TsaN
218 | Self::StsaN
219 | Self::RadlN
220 | Self::RaslN
221 | Self::RsvVclN10
222 | Self::RsvVclN12
223 | Self::RsvVclN14
224 )
225 }
226}
227
228#[derive(Clone, Debug, Default, PartialEq, Eq)]
229pub struct NaluHeader {
230 /// The NALU type.
231 pub type_: NaluType,
232 /// Specifies the identifier of the layer to which a VCL NAL unit belongs or
233 /// the identifier of a layer to which a non-VCL NAL unit applies.
234 pub nuh_layer_id: u8,
235 /// Minus 1 specifies a temporal identifier for the NAL unit. The value of
236 /// nuh_temporal_id_plus1 shall not be equal to 0.
237 pub nuh_temporal_id_plus1: u8,
238}
239
240impl NaluHeader {
241 pub fn nuh_temporal_id(&self) -> u8 {
242 self.nuh_temporal_id_plus1.saturating_sub(1)
243 }
244}
245
246impl Header for NaluHeader {
247 fn parse<T: AsRef<[u8]>>(cursor: &mut std::io::Cursor<T>) -> Result<Self, String> {
248 let mut data = [0u8; 2];
249 cursor.read_exact(&mut data).map_err(|_| String::from("Broken Data"))?;
250 let mut r = BitReader::new(&data, false);
251 let _ = cursor.seek(SeekFrom::Current(-1 * data.len() as i64));
252
253 // Skip forbidden_zero_bit
254 r.skip_bits(1)?;
255
256 Ok(Self {
257 type_: NaluType::try_from(r.read_bits::<u32>(6)?)?,
258 nuh_layer_id: r.read_bits::<u8>(6)?,
259 nuh_temporal_id_plus1: r.read_bits::<u8>(3)?,
260 })
261 }
262
263 fn is_end(&self) -> bool {
264 matches!(self.type_, NaluType::EosNut | NaluType::EobNut)
265 }
266
267 fn len(&self) -> usize {
268 // 7.3.1.2
269 2
270 }
271}
272
273pub type Nalu<'a> = nalu::Nalu<'a, NaluHeader>;
274
275/// H265 levels as defined by table A.8.
276/// `general_level_idc` and `sub_layer_level_idc[ OpTid ]` shall be set equal to a
277/// value of 30 times the level number specified in Table A.8
278#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
279pub enum Level {
280 #[default]
281 L1 = 30,
282 L2 = 60,
283 L2_1 = 63,
284 L3 = 90,
285 L3_1 = 93,
286 L4 = 120,
287 L4_1 = 123,
288 L5 = 150,
289 L5_1 = 153,
290 L5_2 = 156,
291 L6 = 180,
292 L6_1 = 183,
293 L6_2 = 186,
294}
295
296impl TryFrom<u8> for Level {
297 type Error = String;
298
299 fn try_from(value: u8) -> Result<Self, Self::Error> {
300 match value {
301 30 => Ok(Level::L1),
302 60 => Ok(Level::L2),
303 63 => Ok(Level::L2_1),
304 90 => Ok(Level::L3),
305 93 => Ok(Level::L3_1),
306 120 => Ok(Level::L4),
307 123 => Ok(Level::L4_1),
308 150 => Ok(Level::L5),
309 153 => Ok(Level::L5_1),
310 156 => Ok(Level::L5_2),
311 180 => Ok(Level::L6),
312 183 => Ok(Level::L6_1),
313 186 => Ok(Level::L6_2),
314 _ => Err(format!("Invalid Level {}", value)),
315 }
316 }
317}
318
319/// H265 profiles. See A.3.
320#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
321pub enum Profile {
322 #[default]
323 Main = 1,
324 Main10 = 2,
325 MainStill = 3,
326 RangeExtensions = 4,
327 HighThroughput = 5,
328 MultiviewMain = 6,
329 ScalableMain = 7,
330 ThreeDMain = 8,
331 ScreenContentCoding = 9,
332 ScalableRangeExtensions = 10,
333 HighThroughputScreenContentCoding = 11,
334}
335
336impl TryFrom<u8> for Profile {
337 type Error = String;
338
339 fn try_from(value: u8) -> Result<Self, Self::Error> {
340 match value {
341 1 => Ok(Profile::Main),
342 2 => Ok(Profile::Main10),
343 3 => Ok(Profile::MainStill),
344 4 => Ok(Profile::RangeExtensions),
345 5 => Ok(Profile::HighThroughput),
346 6 => Ok(Profile::MultiviewMain),
347 7 => Ok(Profile::ScalableMain),
348 8 => Ok(Profile::ThreeDMain),
349 9 => Ok(Profile::ScreenContentCoding),
350 10 => Ok(Profile::ScalableRangeExtensions),
351 11 => Ok(Profile::HighThroughputScreenContentCoding),
352 _ => Err(format!("Invalid Profile {}", value)),
353 }
354 }
355}
356
357/// A H.265 Video Parameter Set.
358#[derive(Clone, Debug, PartialEq, Eq)]
359pub struct Vps {
360 /// Identifies the VPS for reference by other syntax elements.
361 pub video_parameter_set_id: u8,
362 /// If vps_base_layer_internal_flag is equal to 1 and
363 /// vps_base_layer_available_flag is equal to 1, the base layer is present
364 /// in the bitstream.
365 pub base_layer_internal_flag: bool,
366 /// See `base_layer_internal_flag`.
367 pub base_layer_available_flag: bool,
368 /// Plus 1 specifies the maximum allowed number of layers in each CVS
369 /// referring to the VPS.
370 pub max_layers_minus1: u8,
371 /// Plus 1 specifies the maximum number of temporal sub-layers that may be
372 /// present in each CVS referring to the VPS.
373 pub max_sub_layers_minus1: u8,
374 /// When vps_max_sub_layers_minus1 is greater than 0, specifies whether
375 /// inter prediction is additionally restricted for CVSs referring to the
376 /// VPS.
377 pub temporal_id_nesting_flag: bool,
378 /// ProfileTierLevel() data.
379 pub profile_tier_level: ProfileTierLevel,
380 /// When true, specifies that `vps_max_dec_pic_buffering_minus1[ i ]`,
381 /// `vps_max_num_reorder_pics[ i ]` and `vps_max_latency_increase_plus1[ i ]`
382 /// are present for vps_max_sub_layers_ minus1 + 1 sub-layers.
383 /// vps_sub_layer_ordering_info_present_flag equal to 0 specifies that the
384 /// values of `vps_max_dec_pic_buffering_minus1[ vps_max_sub_layers_minus1 ]`,
385 /// vps_max_num_reorder_pics[ vps_max_sub_ layers_minus1 ] and
386 /// `vps_max_latency_increase_plus1[ vps_max_sub_layers_minus1 ]` apply to all
387 /// sub-layers
388 pub sub_layer_ordering_info_present_flag: bool,
389 /// `max_dec_pic_buffering_minus1[i]` plus 1 specifies the maximum required
390 /// size of the decoded picture buffer for the CVS in units of picture
391 /// storage buffers when HighestTid is equal to i.
392 pub max_dec_pic_buffering_minus1: [u32; 7],
393 /// Indicates the maximum allowed number of pictures with PicOutputFlag
394 /// equal to 1 that can precede any picture with PicOutputFlag equal to 1 in
395 /// the CVS in decoding order and follow that picture with PicOutputFlag
396 /// equal to 1 in output order when HighestTid is equal to i.
397 pub max_num_reorder_pics: [u32; 7],
398 /// When true, `max_latency_increase_plus1[i]` is used to compute the value of
399 /// `VpsMaxLatencyPictures[ i ]`, which specifies the maximum number of
400 /// pictures with PicOutputFlag equal to 1 that can precede any picture with
401 /// PicOutputFlag equal to 1 in the CVS in output order and follow that
402 /// picture with PicOutputFlag equal to 1 in decoding order when HighestTid
403 /// is equal to i.
404 pub max_latency_increase_plus1: [u32; 7],
405 /// Specifies the maximum allowed value of nuh_layer_id of all NAL units in
406 /// each CVS referring to the VPS.
407 pub max_layer_id: u8,
408 /// num_layer_sets_minus1 plus 1 specifies the number of layer sets that are
409 /// specified by the VPS.
410 pub num_layer_sets_minus1: u32,
411 /// When true, specifies that num_units_in_tick, time_scale,
412 /// poc_proportional_to_timing_flag and num_hrd_parameters are present in
413 /// the VPS.
414 pub timing_info_present_flag: bool,
415 /// The number of time units of a clock operating at the frequency
416 /// vps_time_scale Hz that corresponds to one increment (called a clock
417 /// tick) of a clock tick counter. The value of vps_num_units_in_tick shall
418 /// be greater than 0. A clock tick, in units of seconds, is equal to the
419 /// quotient of vps_num_units_in_tick divided by vps_time_scale. For
420 /// example, when the picture rate of a video signal is 25 Hz,
421 /// vps_time_scale may be equal to 27 000 000 and vps_num_units_in_tick may
422 /// be equal to 1 080 000, and consequently a clock tick may be 0.04
423 /// seconds.
424 pub num_units_in_tick: u32,
425 /// The number of time units that pass in one second. For example, a time
426 /// coordinate system that measures time using a 27 MHz clock has a
427 /// vps_time_scale of 27 000 000.
428 pub time_scale: u32,
429 /// When true, indicates that the picture order count value for each picture
430 /// in the CVS that is not the first picture in the CVS, in decoding order,
431 /// is proportional to the output time of the picture relative to the output
432 /// time of the first picture in the CVS. When false, indicates that the
433 /// picture order count value for each picture in the CVS that is not the
434 /// first picture in the CVS, in decoding order, may or may not be
435 /// proportional to the output time of the picture relative to the output
436 /// time of the first picture in the CVS.
437 pub poc_proportional_to_timing_flag: bool,
438 /// num_ticks_poc_diff_one_minus1 plus 1 specifies the number of clock ticks
439 /// corresponding to a difference of picture order count values equal to 1.
440 pub num_ticks_poc_diff_one_minus1: u32,
441 /// Specifies the number of hrd_parameters( ) syntax structures present in
442 /// the VPS RBSP before the vps_extension_flag syntax element.
443 pub num_hrd_parameters: u32,
444 /// `hrd_layer_set_idx[ i ]` specifies the index, into the list of layer sets
445 /// specified by the VPS, of the layer set to which the i-th hrd_parameters(
446 /// ) syntax structure in the VPS applies.
447 pub hrd_layer_set_idx: Vec<u16>,
448 /// `cprms_present_flag[ i ]` equal to true specifies that the HRD parameters
449 /// that are common for all sub-layers are present in the i-th
450 /// hrd_parameters( ) syntax structure in the VPS. `cprms_present_flag[ i ]`
451 /// equal to false specifies that the HRD parameters that are common for all
452 /// sub-layers are not present in the i-th hrd_parameters( ) syntax
453 /// structure in the VPS and are derived to be the same as the ( i − 1 )-th
454 /// hrd_parameters( ) syntax structure in the VPS. `cprms_present_flag[ 0 ]`
455 /// is inferred to be equal to true.
456 pub cprms_present_flag: Vec<bool>,
457 /// The hrd_parameters() data.
458 pub hrd_parameters: Vec<HrdParams>,
459 /// When false, specifies that no vps_extension_data_flag syntax elements
460 /// are present in the VPS RBSP syntax structure. When true, specifies that
461 /// there are vps_extension_data_flag syntax elements present in the VPS
462 /// RBSP syntax structure. Decoders conforming to a profile specified in
463 /// Annex A but not supporting the INBLD capability specified in Annex F
464 /// shall ignore all data that follow the value 1 for vps_extension_flag in
465 /// a VPS NAL unit.
466 pub extension_flag: bool,
467}
468
469impl Default for Vps {
470 fn default() -> Self {
471 Self {
472 video_parameter_set_id: Default::default(),
473 base_layer_internal_flag: Default::default(),
474 base_layer_available_flag: Default::default(),
475 max_layers_minus1: Default::default(),
476 max_sub_layers_minus1: Default::default(),
477 temporal_id_nesting_flag: Default::default(),
478 profile_tier_level: Default::default(),
479 sub_layer_ordering_info_present_flag: Default::default(),
480 max_dec_pic_buffering_minus1: Default::default(),
481 max_num_reorder_pics: Default::default(),
482 max_latency_increase_plus1: Default::default(),
483 max_layer_id: Default::default(),
484 num_layer_sets_minus1: Default::default(),
485 timing_info_present_flag: Default::default(),
486 num_units_in_tick: Default::default(),
487 time_scale: Default::default(),
488 poc_proportional_to_timing_flag: Default::default(),
489 num_ticks_poc_diff_one_minus1: Default::default(),
490 num_hrd_parameters: Default::default(),
491 hrd_layer_set_idx: Default::default(),
492 cprms_present_flag: vec![true],
493 hrd_parameters: Default::default(),
494 extension_flag: Default::default(),
495 }
496 }
497}
498
499/// A builder for a [`Vps`], covering the syntax elements an encoder is
500/// expected to set. Anything else is left at its specification default.
501pub struct VpsBuilder(Vps);
502
503impl VpsBuilder {
504 pub fn new() -> Self {
505 VpsBuilder(Vps {
506 base_layer_internal_flag: true,
507 base_layer_available_flag: true,
508 temporal_id_nesting_flag: true,
509 sub_layer_ordering_info_present_flag: true,
510 profile_tier_level: ProfileTierLevel {
511 general_progressive_source_flag: true,
512 general_frame_only_constraint_flag: true,
513 ..Default::default()
514 },
515 ..Default::default()
516 })
517 }
518
519 pub fn video_parameter_set_id(mut self, value: u8) -> Self {
520 self.0.video_parameter_set_id = value;
521 self
522 }
523
524 pub fn max_layers_minus1(mut self, value: u8) -> Self {
525 self.0.max_layers_minus1 = value;
526 self
527 }
528
529 pub fn max_sub_layers_minus1(mut self, value: u8) -> Self {
530 self.0.max_sub_layers_minus1 = value;
531 self
532 }
533
534 pub fn temporal_id_nesting_flag(mut self, value: bool) -> Self {
535 self.0.temporal_id_nesting_flag = value;
536 self
537 }
538
539 pub fn general_profile(mut self, value: Profile) -> Self {
540 self.0.profile_tier_level.general_profile_idc = value as u8;
541 self.0.profile_tier_level.general_profile_compatibility_flag = [false; 32];
542 self.0.profile_tier_level.general_profile_compatibility_flag[value as usize] = true;
543 self
544 }
545
546 pub fn general_tier_flag(mut self, value: bool) -> Self {
547 self.0.profile_tier_level.general_tier_flag = value;
548 self
549 }
550
551 pub fn general_level_idc(mut self, value: Level) -> Self {
552 self.0.profile_tier_level.general_level_idc = value;
553 self
554 }
555
556 /// Sets `vps_max_dec_pic_buffering_minus1` for the highest sub-layer.
557 pub fn max_dec_pic_buffering_minus1(mut self, value: u32) -> Self {
558 self.0.max_dec_pic_buffering_minus1[usize::from(self.0.max_sub_layers_minus1)] = value;
559 self
560 }
561
562 /// Sets `vps_max_num_reorder_pics` for the highest sub-layer.
563 pub fn max_num_reorder_pics(mut self, value: u32) -> Self {
564 self.0.max_num_reorder_pics[usize::from(self.0.max_sub_layers_minus1)] = value;
565 self
566 }
567
568 /// Sets `vps_max_latency_increase_plus1` for the highest sub-layer.
569 pub fn max_latency_increase_plus1(mut self, value: u32) -> Self {
570 self.0.max_latency_increase_plus1[usize::from(self.0.max_sub_layers_minus1)] = value;
571 self
572 }
573
574 pub fn sub_layer_ordering_info_present_flag(mut self, value: bool) -> Self {
575 self.0.sub_layer_ordering_info_present_flag = value;
576 self
577 }
578
579 pub fn timing_info(mut self, num_units_in_tick: u32, time_scale: u32) -> Self {
580 self.0.timing_info_present_flag = true;
581 self.0.num_units_in_tick = num_units_in_tick;
582 self.0.time_scale = time_scale;
583 self
584 }
585
586 pub fn build(mut self) -> Rc<Vps> {
587 // 7.4.3.1: when vps_sub_layer_ordering_info_present_flag is 0, the
588 // values for the highest sub-layer apply to all sub-layers.
589 if !self.0.sub_layer_ordering_info_present_flag {
590 let max = usize::from(self.0.max_sub_layers_minus1);
591 for i in 0..max {
592 self.0.max_dec_pic_buffering_minus1[i] = self.0.max_dec_pic_buffering_minus1[max];
593 self.0.max_num_reorder_pics[i] = self.0.max_num_reorder_pics[max];
594 self.0.max_latency_increase_plus1[i] = self.0.max_latency_increase_plus1[max];
595 }
596 }
597
598 Rc::new(self.0)
599 }
600}
601
602impl Default for VpsBuilder {
603 fn default() -> Self {
604 Self::new()
605 }
606}
607
608#[derive(Clone, Debug, Default, PartialEq, Eq)]
609pub struct ProfileTierLevel {
610 /// Specifies the context for the interpretation of general_profile_idc and
611 /// `general_profile_compatibility_flag[ j ]` for all values of j in the range
612 /// of 0 to 31, inclusive.
613 pub general_profile_space: u8,
614 /// Specifies the tier context for the interpretation of general_level_idc
615 /// as specified in Annex A.
616 pub general_tier_flag: bool,
617 /// When general_profile_space is equal to 0, indicates a profile to which
618 /// the CVS conforms as specified in Annex A. Bitstreams shall not contain
619 /// values of general_profile_idc other than those specified in Annex A.
620 /// Other values of general_profile_idc are reserved for future use by ITU-T
621 /// | ISO/IEC.
622 pub general_profile_idc: u8,
623 /// `general_profile_compatibility_flag[ j ]` equal to true, when
624 /// general_profile_space is false, indicates that the CVS conforms to the
625 /// profile indicated by general_profile_idc equal to j as specified in
626 /// Annex A.
627 pub general_profile_compatibility_flag: [bool; 32],
628 /// general_progressive_source_flag and general_interlaced_source_flag are
629 /// interpreted as follows:
630 ///
631 /// –If general_progressive_source_flag is true and
632 /// general_interlaced_source_flag is false, the source scan type of the
633 /// pictures in the CVS should be interpreted as progressive only.
634 ///
635 /// –Otherwise, if general_progressive_source_flag is false and
636 /// general_interlaced_source_flag is true, the source scan type of the
637 /// pictures in the CVS should be interpreted as interlaced only.
638 ///
639 /// –Otherwise, if general_progressive_source_flag is false and
640 /// general_interlaced_source_flag is false, the source scan type of the
641 /// pictures in the CVS should be interpreted as unknown or unspecified.
642 ///
643 /// –Otherwise (general_progressive_source_flag is true and
644 /// general_interlaced_source_flag is true), the source scan type of each
645 /// picture in the CVS is indicated at the picture level using the syntax
646 /// element source_scan_type in a picture timing SEI message.
647 pub general_progressive_source_flag: bool,
648 /// See `general_progressive_source_flag`.
649 pub general_interlaced_source_flag: bool,
650 /// If true, specifies that there are no frame packing arrangement SEI
651 /// messages, segmented rectangular frame packing arrangement SEI messages,
652 /// equirectangular projection SEI messages, or cubemap projection SEI
653 /// messages present in the CVS. If false, indicates that there may or may
654 /// not be one or more frame packing arrangement SEI messages, segmented
655 /// rectangular frame packing arrangement SEI messages, equirectangular
656 /// projection SEI messages, or cubemap projection SEI messages present in
657 /// the CVS.
658 pub general_non_packed_constraint_flag: bool,
659 /// When true, specifies that field_seq_flag is false. When false, indicates
660 /// that field_seq_flag may or may not be false.
661 pub general_frame_only_constraint_flag: bool,
662 /// See Annex A.
663 pub general_max_12bit_constraint_flag: bool,
664 /// See Annex A.
665 pub general_max_10bit_constraint_flag: bool,
666 /// See Annex A.
667 pub general_max_8bit_constraint_flag: bool,
668 /// See Annex A.
669 pub general_max_422chroma_constraint_flag: bool,
670 /// See Annex A.
671 pub general_max_420chroma_constraint_flag: bool,
672 /// See Annex A.
673 pub general_max_monochrome_constraint_flag: bool,
674 /// See Annex A.
675 pub general_intra_constraint_flag: bool,
676 /// See Annex A.
677 pub general_lower_bit_rate_constraint_flag: bool,
678 /// See Annex A.
679 pub general_max_14bit_constraint_flag: bool,
680 /// See Annex A.
681 pub general_one_picture_only_constraint_flag: bool,
682 /// When true, specifies that the INBLD capability as specified in Annex F
683 /// is required for decoding of the layer to which the profile_tier_level( )
684 /// syntax structure applies. When false, specifies that the INBLD
685 /// capability as specified in Annex F is not required for decoding of the
686 /// layer to which the profile_tier_level( ) syntax structure applies.
687 pub general_inbld_flag: bool,
688 /// Indicates a level to which the CVS conforms as specified in Annex A.
689 pub general_level_idc: Level,
690 /// Sub-layer syntax element.
691 pub sub_layer_profile_present_flag: [bool; 6],
692 /// Sub-layer syntax element.
693 pub sub_layer_level_present_flag: [bool; 6],
694 /// Sub-layer syntax element.
695 pub sub_layer_profile_space: [u8; 6],
696 /// Sub-layer syntax element.
697 pub sub_layer_tier_flag: [bool; 6],
698 /// Sub-layer syntax element.
699 pub sub_layer_profile_idc: [u8; 6],
700 /// Sub-layer syntax element.
701 pub sub_layer_profile_compatibility_flag: [[bool; 32]; 6],
702 /// Sub-layer syntax element.
703 pub sub_layer_progressive_source_flag: [bool; 6],
704 /// Sub-layer syntax element.
705 pub sub_layer_interlaced_source_flag: [bool; 6],
706 /// Sub-layer syntax element.
707 pub sub_layer_non_packed_constraint_flag: [bool; 6],
708 /// Sub-layer syntax element.
709 pub sub_layer_frame_only_constraint_flag: [bool; 6],
710 /// Sub-layer syntax element.
711 pub sub_layer_max_12bit_constraint_flag: [bool; 6],
712 /// Sub-layer syntax element.
713 pub sub_layer_max_10bit_constraint_flag: [bool; 6],
714 /// Sub-layer syntax element.
715 pub sub_layer_max_8bit_constraint_flag: [bool; 6],
716 /// Sub-layer syntax element.
717 pub sub_layer_max_422chroma_constraint_flag: [bool; 6],
718 /// Sub-layer syntax element.
719 pub sub_layer_max_420chroma_constraint_flag: [bool; 6],
720 /// Sub-layer syntax element.
721 pub sub_layer_max_monochrome_constraint_flag: [bool; 6],
722 /// Sub-layer syntax element.
723 pub sub_layer_intra_constraint_flag: [bool; 6],
724 /// Sub-layer syntax element.
725 pub sub_layer_one_picture_only_constraint_flag: [bool; 6],
726 /// Sub-layer syntax element.
727 pub sub_layer_lower_bit_rate_constraint_flag: [bool; 6],
728 /// Sub-layer syntax element.
729 pub sub_layer_max_14bit_constraint_flag: [bool; 6],
730 /// Sub-layer syntax element.
731 pub sub_layer_inbld_flag: [bool; 6],
732 /// Sub-layer syntax element.
733 pub sub_layer_level_idc: [Level; 6],
734}
735
736impl ProfileTierLevel {
737 pub fn max_luma_ps(&self) -> u32 {
738 // See Table A.8.
739 match self.general_level_idc {
740 Level::L1 => 36864,
741 Level::L2 => 122880,
742 Level::L2_1 => 245760,
743 Level::L3 => 552960,
744 Level::L3_1 => 983040,
745 Level::L4 | Level::L4_1 => 2228224,
746 Level::L5 | Level::L5_1 | Level::L5_2 => 8912896,
747 _ => 35651584,
748 }
749 }
750
751 pub fn max_dpb_pic_buf(&self) -> u32 {
752 if self.general_profile_idc >= 1 && self.general_profile_idc <= 5 {
753 6
754 } else {
755 7
756 }
757 }
758}
759
760#[derive(Clone, Debug, Default, PartialEq, Eq)]
761pub struct SpsRangeExtension {
762 pub transform_skip_rotation_enabled_flag: bool,
763 pub transform_skip_context_enabled_flag: bool,
764 pub implicit_rdpcm_enabled_flag: bool,
765 pub explicit_rdpcm_enabled_flag: bool,
766 pub extended_precision_processing_flag: bool,
767 pub intra_smoothing_disabled_flag: bool,
768 pub high_precision_offsets_enabled_flag: bool,
769 pub persistent_rice_adaptation_enabled_flag: bool,
770 pub cabac_bypass_alignment_enabled_flag: bool,
771}
772
773#[derive(Clone, Debug, PartialEq, Eq)]
774pub struct SpsSccExtension {
775 /// When set, specifies that a picture in the CVS may be included in a
776 /// reference picture list of a slice of the picture itself. When not set,
777 /// specifies that a picture in the CVS is never included in a reference
778 /// picture list of a slice of the picture itself.
779 pub curr_pic_ref_enabled_flag: bool,
780 /// When set, specifies that the decoding process for palette mode may be
781 /// used for intra blocks. When not set, specifies that the decoding process
782 /// for palette mode is not applied.
783 pub palette_mode_enabled_flag: bool,
784 /// Specifies the maximum allowed palette size.
785 pub palette_max_size: u8,
786 /// Specifies the difference between the maximum allowed palette predictor
787 /// size and the maximum allowed palette size.
788 pub delta_palette_max_predictor_size: u8,
789 /// When set, specifies that the sequence palette predictors are initialized
790 /// using the sps_palette_predictor_initializers. When not set, specifies
791 /// that the entries in the sequence palette predictor are initialized to 0.
792 pub palette_predictor_initializers_present_flag: bool,
793 /// num_palette_predictor_initializers_minus1 plus 1 specifies the number of
794 /// entries in the sequence palette predictor initializer.
795 pub num_palette_predictor_initializer_minus1: u8,
796 /// `palette_predictor_initializer[ comp ][ i ]` specifies the value of the
797 /// comp-th component of the i-th palette entry in the SPS that is used to
798 /// initialize the array PredictorPaletteEntries.
799 pub palette_predictor_initializer: [[u32; 128]; 3],
800 /// Controls the presence and inference of the use_integer_mv_flag that
801 /// specifies the resolution of motion vectors for inter prediction.
802 pub motion_vector_resolution_control_idc: u8,
803 /// When set, specifies that the intra boundary filtering process is
804 /// unconditionally disabled for intra prediction. If not set, specifies
805 /// that the intra boundary filtering process may be used.
806 pub intra_boundary_filtering_disabled_flag: bool,
807}
808
809impl Default for SpsSccExtension {
810 fn default() -> Self {
811 Self {
812 curr_pic_ref_enabled_flag: Default::default(),
813 palette_mode_enabled_flag: Default::default(),
814 palette_max_size: Default::default(),
815 delta_palette_max_predictor_size: Default::default(),
816 palette_predictor_initializers_present_flag: Default::default(),
817 num_palette_predictor_initializer_minus1: Default::default(),
818 palette_predictor_initializer: [[0; 128]; 3],
819 motion_vector_resolution_control_idc: Default::default(),
820 intra_boundary_filtering_disabled_flag: Default::default(),
821 }
822 }
823}
824
825/// A H.265 Sequence Parameter Set.
826#[derive(Clone, Debug, Default, PartialEq, Eq)]
827pub struct Sps {
828 /// Specifies the value of the vps_video_parameter_set_id of the active VPS.
829 pub video_parameter_set_id: u8,
830 /// `max_sub_layers_minus1` plus 1 specifies the maximum number of temporal
831 /// sub-layers that may be present in each CVS referring to the SPS.
832 pub max_sub_layers_minus1: u8,
833 /// When sps_max_sub_layers_minus1 is greater than 0, specifies whether
834 /// inter prediction is additionally restricted for CVSs referring to the
835 /// SPS.
836 pub temporal_id_nesting_flag: bool,
837 /// profile_tier_level() data.
838 pub profile_tier_level: ProfileTierLevel,
839 /// Provides an identifier for the SPS for reference by other syntax
840 /// elements.
841 pub seq_parameter_set_id: u8,
842 /// Specifies the chroma sampling relative to the luma sampling as specified
843 /// in clause 6.2.
844 pub chroma_format_idc: u8,
845 /// When true, specifies that the three colour components of the 4:4:4
846 /// chroma format are coded separately. When false, specifies that the
847 /// colour components are not coded separately.
848 pub separate_colour_plane_flag: bool,
849 /// Specifies the width of each decoded picture in units of luma samples.
850 pub pic_width_in_luma_samples: u16,
851 /// Specifies the height of each decoded picture in units of luma samples.
852 pub pic_height_in_luma_samples: u16,
853 /// When true, indicates that the conformance cropping window offset
854 /// parameters follow next in the SPS. When false, indicates that the
855 /// conformance cropping window offset parameters are not present.
856 pub conformance_window_flag: bool,
857 /* if conformance_window_flag */
858 /// Specify the samples of the pictures in the CVS that are output from the
859 /// decoding process, in terms of a rectangular region specified in picture
860 /// coordinates for output.
861 pub conf_win_left_offset: u32,
862 pub conf_win_right_offset: u32,
863 pub conf_win_top_offset: u32,
864 pub conf_win_bottom_offset: u32,
865
866 /// Specifies the bit depth of the samples of the luma array BitDepthY and
867 /// the value of the luma quantization parameter range offset QpBdOffsetY.
868 pub bit_depth_luma_minus8: u8,
869 /// Specifies the bit depth of the samples of the chroma arrays BitDepthC
870 /// and the value of the chroma quantization parameter range offset
871 /// QpBdOffsetC.
872 pub bit_depth_chroma_minus8: u8,
873 /// Specifies the value of the variable MaxPicOrderCntLsb that is used in
874 /// the decoding process for picture order count.
875 pub log2_max_pic_order_cnt_lsb_minus4: u8,
876 /// When true, specifies that `max_dec_pic_buffering_minus1[ i ]`,
877 /// `max_num_reorder_pics[ i ]` and `max_latency_increase_plus1[ i ]` are
878 /// present for max_sub_layers_minus1 + 1 sub- layers. When false, specifies
879 /// that the values of `max_dec_pic_ buffering_minus1[ max_sub_layers_minus1
880 /// ]`, `max_num_reorder_pics[ max_sub_layers_minus1 ]` and max_
881 /// `latency_increase_plus1[ max_sub_layers_minus1 ]` apply to all sub-layers.
882 pub sub_layer_ordering_info_present_flag: bool,
883 /// `max_dec_pic_buffering_minus1[ i ]` plus 1 specifies the maximum required
884 /// size of the decoded picture buffer for the CVS in units of picture
885 /// storage buffers when HighestTid is equal to i.
886 pub max_dec_pic_buffering_minus1: [u8; 7],
887 /// `max_num_reorder_pics[ i ]` indicates the maximum allowed number of
888 /// pictures with PicOutputFlag equal to 1 that can precede any picture with
889 /// PicOutputFlag equal to 1 in the CVS in decoding order and follow that
890 /// picture with PicOutputFlag equal to 1 in output order when HighestTid is
891 /// equal to i.
892 pub max_num_reorder_pics: [u8; 7],
893 /// `max_latency_increase_plus1[ i ]` not equal to 0 is used to compute the
894 /// value of `SpsMaxLatencyPictures[ i ]`, which specifies the maximum number
895 /// of pictures with PicOutputFlag equal to 1 that can precede any picture
896 /// with PicOutputFlag equal to 1 in the CVS in output order and follow that
897 /// picture with PicOutputFlag equal to 1 in decoding order when HighestTid
898 /// is equal to i.
899 pub max_latency_increase_plus1: [u8; 7],
900 /// min_luma_coding_block_size_minus3 plus 3 specifies the minimum luma
901 /// coding block size.
902 pub log2_min_luma_coding_block_size_minus3: u8,
903 /// Specifies the difference between the maximum and minimum luma coding
904 /// block size.
905 pub log2_diff_max_min_luma_coding_block_size: u8,
906 /// min_luma_transform_block_size_minus2 plus 2 specifies the minimum luma
907 /// transform block size.
908 pub log2_min_luma_transform_block_size_minus2: u8,
909 /// Specifies the difference between the maximum and minimum luma transform
910 /// block size.
911 pub log2_diff_max_min_luma_transform_block_size: u8,
912 /// Specifies the maximum hierarchy depth for transform units of coding
913 /// units coded in inter prediction mode.
914 pub max_transform_hierarchy_depth_inter: u8,
915 /// Specifies the maximum hierarchy depth for transform units of coding
916 /// units coded in intra prediction mode.
917 pub max_transform_hierarchy_depth_intra: u8,
918 /// When true, specifies that a scaling list is used for the scaling process
919 /// for transform coefficients. When false, specifies that scaling list is
920 /// not used for the scaling process for transform coefficients.
921 pub scaling_list_enabled_flag: bool,
922 /* if scaling_list_enabled_flag */
923 /// When true, specifies that the scaling_list_data( ) syntax structure is
924 /// present in the SPS. When false, specifies that the scaling_list_data( )
925 /// syntax structure is not present in the SPS.
926 pub scaling_list_data_present_flag: bool,
927 /// The scaling_list_data() syntax data.
928 pub scaling_list: ScalingLists,
929 /// When true, specifies that asymmetric motion partitions, i.e., PartMode
930 /// equal to PART_2NxnU, PART_2NxnD, PART_nLx2N or PART_nRx2N, may be used
931 /// in CTBs. When false, specifies that asymmetric motion partitions cannot
932 /// be used in CTBs.
933 pub amp_enabled_flag: bool,
934 /// When true, specifies that the sample adaptive offset process is applied
935 /// to the reconstructed picture after the deblocking filter process. When
936 /// false, specifies that the sample adaptive offset process is not applied
937 /// to the reconstructed picture after the deblocking filter process.
938 pub sample_adaptive_offset_enabled_flag: bool,
939 /// When false, specifies that PCM-related syntax
940 /// (pcm_sample_bit_depth_luma_minus1, pcm_sample_ bit_depth_chroma_minus1,
941 /// log2_min_pcm_luma_coding_block_size_minus3, log2_diff_max_min_pcm_luma_
942 /// coding_block_size, pcm_loop_filter_disabled_flag, pcm_flag,
943 /// pcm_alignment_zero_bit syntax elements and pcm_sample( ) syntax
944 /// structure) is not present in the CVS.
945 pub pcm_enabled_flag: bool,
946
947 /* if pcm_enabled_flag */
948 pub pcm_sample_bit_depth_luma_minus1: u8,
949 /// Specifies the number of bits used to represent each of PCM sample values
950 /// of the luma component.
951 pub pcm_sample_bit_depth_chroma_minus1: u8,
952 /// Specifies the number of bits used to represent each of PCM sample values
953 /// of the chroma components.
954 pub log2_min_pcm_luma_coding_block_size_minus3: u8,
955 /// Specifies the difference between the maximum and minimum size of coding
956 /// blocks with pcm_flag equal to true.
957 pub log2_diff_max_min_pcm_luma_coding_block_size: u8,
958 /// Specifies whether the loop filter process is disabled on reconstructed
959 /// samples in a coding unit with pcm_flag equal to true as follows:
960 ///
961 /// – If pcm_loop_filter_disabled_flag is set, the deblocking filter and
962 /// sample adaptive offset filter processes on the reconstructed samples in
963 /// a coding unit with pcm_flag set are disabled.
964 ///
965 /// – Otherwise (pcm_loop_filter_disabled_flag value is not set), the
966 /// deblocking filter and sample adaptive offset filter processes on the
967 /// reconstructed samples in a coding unit with pcm_flag set are not
968 /// disabled.
969 pub pcm_loop_filter_disabled_flag: bool,
970 /// Specifies the number of st_ref_pic_set( ) syntax structures included in
971 /// the SPS.
972 pub num_short_term_ref_pic_sets: u8,
973 /// the st_ref_pic_set() data.
974 pub short_term_ref_pic_set: Vec<ShortTermRefPicSet>,
975 /// If unset, specifies that no long-term reference picture is used for
976 /// inter prediction of any coded picture in the CVS.
977 /// If set, specifies that long-term reference pictures may be used for
978 /// inter prediction of one or more coded pictures in the CVS.
979 pub long_term_ref_pics_present_flag: bool,
980
981 /* if long_term_ref_pics_present_flag */
982 /// Specifies the number of candidate long-term reference pictures that are
983 /// specified in the SPS.
984 pub num_long_term_ref_pics_sps: u8,
985 /// `lt_ref_pic_poc_lsb_sps[ i ]` specifies the picture order count modulo
986 /// MaxPicOrderCntLsb of the i-th candidate long-term reference picture
987 /// specified in the SPS.
988 pub lt_ref_pic_poc_lsb_sps: [u32; MAX_LONG_TERM_REF_PIC_SETS],
989 /// `used_by_curr_pic_lt_sps_flag[ i ]` equal to false specifies that the i-th
990 /// candidate long-term reference picture specified in the SPS is not used
991 /// for reference by a picture that includes in its long-term reference
992 /// picture set (RPS) the i-th candidate long-term reference picture
993 /// specified in the SPS.
994 pub used_by_curr_pic_lt_sps_flag: [bool; MAX_LONG_TERM_REF_PIC_SETS],
995 /// When set, specifies that slice_temporal_mvp_enabled_flag is present in
996 /// the slice headers of non-IDR pictures in the CVS. When not set,
997 /// specifies that slice_temporal_mvp_enabled_flag is not present in slice
998 /// headers and that temporal motion vector predictors are not used in the
999 /// CVS.
1000 pub temporal_mvp_enabled_flag: bool,
1001 /// When set, specifies that bi-linear interpolation is conditionally used
1002 /// in the intraprediction filtering process in the CVS as specified in
1003 /// clause 8.4.4.2.3.
1004 pub strong_intra_smoothing_enabled_flag: bool,
1005 /// When set, specifies that the vui_parameters( ) syntax structure as
1006 /// specified in Annex E is present. When not set, specifies that the
1007 /// vui_parameters( ) syntax structure as specified in Annex E is not
1008 /// present.
1009 pub vui_parameters_present_flag: bool,
1010 /// The vui_parameters() data.
1011 pub vui_parameters: VuiParams,
1012 /// When set, specifies that the syntax elements sps_range_extension_flag,
1013 /// sps_multilayer_extension_flag, sps_3d_extension_flag,
1014 /// sps_scc_extension_flag, and sps_extension_4bits are present in the SPS
1015 /// RBSP syntax structure. When not set, specifies that these syntax
1016 /// elements are not present.
1017 pub extension_present_flag: bool,
1018
1019 pub range_extension_flag: bool,
1020 /// The sps_range_extension() data.
1021 pub range_extension: SpsRangeExtension,
1022 /// When set, specifies that the sps_scc_extension( ) syntax structure is
1023 /// present in the SPS RBSP syntax structure. When not set, specifies that
1024 /// this syntax structure is not present
1025 pub scc_extension_flag: bool,
1026 /// The sps_scc_extension() data.
1027 pub scc_extension: SpsSccExtension,
1028
1029 // Internal H265 variables. Computed from the bitstream.
1030 /// Equivalent to MinCbLog2SizeY in the specification.
1031 pub min_cb_log2_size_y: u32,
1032 /// Equivalent to CtbLog2SizeY in the specification.
1033 pub ctb_log2_size_y: u32,
1034 /// Equivalent to CtbSizeY in the specification.
1035 pub ctb_size_y: u32,
1036 /// Equivalent to PicHeightInCtbsY in the specification.
1037 pub pic_height_in_ctbs_y: u32,
1038 /// Equivalent to PicWidthInCtbsY in the specification.
1039 pub pic_width_in_ctbs_y: u32,
1040 /// Equivalent to PicSizeInCtbsY in the specification.
1041 pub pic_size_in_ctbs_y: u32,
1042 /// Equivalent to ChromaArrayType in the specification.
1043 pub chroma_array_type: u8,
1044 /// Equivalent to WpOffsetHalfRangeY in the specification.
1045 pub wp_offset_half_range_y: u32,
1046 /// Equivalent to WpOffsetHalfRangeC in the specification.
1047 pub wp_offset_half_range_c: u32,
1048 /// Equivalent to MaxTbLog2SizeY in the specification.
1049 pub max_tb_log2_size_y: u32,
1050 /// Equivalent to PicSizeInSamplesY in the specification.
1051 pub pic_size_in_samples_y: u32,
1052
1053 /// The VPS referenced by this SPS, if any.
1054 pub vps: Option<Rc<Vps>>,
1055}
1056
1057impl Sps {
1058 pub fn max_dpb_size(&self) -> usize {
1059 let max_luma_ps = self.profile_tier_level.max_luma_ps();
1060 let max_dpb_pic_buf = self.profile_tier_level.max_dpb_pic_buf();
1061
1062 // Equation A-2
1063 let max = if self.pic_size_in_samples_y <= (max_luma_ps >> 2) {
1064 std::cmp::min(4 * max_dpb_pic_buf, 16)
1065 } else if self.pic_size_in_samples_y <= (max_luma_ps >> 1) {
1066 std::cmp::min(2 * max_dpb_pic_buf, 16)
1067 } else if self.pic_size_in_samples_y <= ((3 * max_luma_ps) >> 2) {
1068 std::cmp::min(4 * max_dpb_pic_buf / 3, 16)
1069 } else {
1070 max_dpb_pic_buf
1071 };
1072
1073 max as usize
1074 }
1075
1076 pub fn width(&self) -> u16 {
1077 self.pic_width_in_luma_samples
1078 }
1079
1080 pub fn height(&self) -> u16 {
1081 self.pic_height_in_luma_samples
1082 }
1083
1084 pub fn visible_rectangle(&self) -> Rect<u32> {
1085 // From the specification:
1086 // NOTE 3 – The conformance cropping window offset parameters are
1087 // only applied at the output. All internal decoding processes are
1088 // applied to the uncropped picture size.
1089 if !self.conformance_window_flag {
1090 return Rect {
1091 min: Point { x: 0, y: 0 },
1092 max: Point { x: u32::from(self.width()), y: u32::from(self.height()) },
1093 };
1094 }
1095 const SUB_HEIGHT_C: [u32; 5] = [1, 2, 1, 1, 1];
1096 const SUB_WIDTH_C: [u32; 5] = [1, 2, 2, 1, 1];
1097
1098 let crop_unit_y = SUB_HEIGHT_C[usize::from(self.chroma_array_type)];
1099 let crop_unit_x = SUB_WIDTH_C[usize::from(self.chroma_array_type)];
1100 let crop_left = crop_unit_x * self.conf_win_left_offset;
1101 let crop_right = crop_unit_x * self.conf_win_right_offset;
1102 let crop_top = crop_unit_y * self.conf_win_top_offset;
1103 let crop_bottom = crop_unit_y * self.conf_win_bottom_offset;
1104
1105 Rect {
1106 min: Point { x: crop_left, y: crop_top },
1107 max: Point {
1108 x: u32::from(self.width()) - crop_left - crop_right,
1109 y: u32::from(self.height()) - crop_top - crop_bottom,
1110 },
1111 }
1112 }
1113}
1114
1115/// A builder for a [`Sps`], covering the syntax elements an encoder is expected
1116/// to set. Anything else is left at its specification default.
1117pub struct SpsBuilder(Sps);
1118
1119impl SpsBuilder {
1120 /// Starts a SPS referring to `vps`, inheriting its profile_tier_level() and
1121 /// its sub-layer configuration.
1122 pub fn new(vps: Rc<Vps>) -> Self {
1123 SpsBuilder(Sps {
1124 video_parameter_set_id: vps.video_parameter_set_id,
1125 max_sub_layers_minus1: vps.max_sub_layers_minus1,
1126 temporal_id_nesting_flag: vps.temporal_id_nesting_flag,
1127 profile_tier_level: vps.profile_tier_level.clone(),
1128 chroma_format_idc: 1,
1129 // MaxPicOrderCntLsb = 256.
1130 log2_max_pic_order_cnt_lsb_minus4: 4,
1131 sub_layer_ordering_info_present_flag: true,
1132 // MinCbSizeY = 8, CtbSizeY = 64.
1133 log2_min_luma_coding_block_size_minus3: 0,
1134 log2_diff_max_min_luma_coding_block_size: 3,
1135 // MinTbSizeY = 4, MaxTbSizeY = 32.
1136 log2_min_luma_transform_block_size_minus2: 0,
1137 log2_diff_max_min_luma_transform_block_size: 3,
1138 vps: Some(vps),
1139 ..Default::default()
1140 })
1141 }
1142
1143 pub fn seq_parameter_set_id(mut self, value: u8) -> Self {
1144 self.0.seq_parameter_set_id = value;
1145 self
1146 }
1147
1148 pub fn general_profile(mut self, value: Profile) -> Self {
1149 self.0.profile_tier_level.general_profile_idc = value as u8;
1150 self.0.profile_tier_level.general_profile_compatibility_flag = [false; 32];
1151 self.0.profile_tier_level.general_profile_compatibility_flag[value as usize] = true;
1152 self
1153 }
1154
1155 pub fn general_tier_flag(mut self, value: bool) -> Self {
1156 self.0.profile_tier_level.general_tier_flag = value;
1157 self
1158 }
1159
1160 pub fn general_level_idc(mut self, value: Level) -> Self {
1161 self.0.profile_tier_level.general_level_idc = value;
1162 self
1163 }
1164
1165 pub fn chroma_format_idc(mut self, value: u8) -> Self {
1166 self.0.chroma_format_idc = value;
1167 self
1168 }
1169
1170 pub fn separate_colour_plane_flag(mut self, value: bool) -> Self {
1171 self.0.separate_colour_plane_flag = value;
1172 self
1173 }
1174
1175 pub fn bit_depth_luma_minus8(mut self, value: u8) -> Self {
1176 self.0.bit_depth_luma_minus8 = value;
1177 self
1178 }
1179
1180 pub fn bit_depth_luma(self, value: u8) -> Self {
1181 self.bit_depth_luma_minus8(value - 8u8)
1182 }
1183
1184 pub fn bit_depth_chroma_minus8(mut self, value: u8) -> Self {
1185 self.0.bit_depth_chroma_minus8 = value;
1186 self
1187 }
1188
1189 pub fn bit_depth_chroma(self, value: u8) -> Self {
1190 self.bit_depth_chroma_minus8(value - 8u8)
1191 }
1192
1193 /// Sets the conformance cropping window. The offsets are given in luma
1194 /// samples and are converted to the units of clause 7.4.3.2.1, so
1195 /// [`Self::chroma_format_idc`] must be set beforehand.
1196 pub fn conformance_window(mut self, left: u32, right: u32, top: u32, bottom: u32) -> Self {
1197 // Table 6-1.
1198 let (sub_width_c, sub_height_c) = match self.0.chroma_format_idc {
1199 1 => (2, 2),
1200 2 => (2, 1),
1201 _ => (1, 1),
1202 };
1203
1204 self.0.conformance_window_flag = true;
1205 self.0.conf_win_left_offset = left / sub_width_c;
1206 self.0.conf_win_right_offset = right / sub_width_c;
1207 self.0.conf_win_top_offset = top / sub_height_c;
1208 self.0.conf_win_bottom_offset = bottom / sub_height_c;
1209 self
1210 }
1211
1212 /// Sets the visible resolution. The coded resolution is aligned to
1213 /// MinCbSizeY, the difference being signalled through the conformance
1214 /// cropping window.
1215 pub fn resolution(mut self, width: u32, height: u32) -> Self {
1216 let min_cb_size = 1u32 << (self.0.log2_min_luma_coding_block_size_minus3 + 3);
1217
1218 let coded_width = (width + min_cb_size - 1) / min_cb_size * min_cb_size;
1219 let coded_height = (height + min_cb_size - 1) / min_cb_size * min_cb_size;
1220
1221 self.0.pic_width_in_luma_samples = coded_width as u16;
1222 self.0.pic_height_in_luma_samples = coded_height as u16;
1223
1224 if coded_width != width || coded_height != height {
1225 self = self.conformance_window(0, coded_width - width, 0, coded_height - height);
1226 }
1227
1228 self
1229 }
1230
1231 pub fn log2_max_pic_order_cnt_lsb_minus4(mut self, value: u8) -> Self {
1232 self.0.log2_max_pic_order_cnt_lsb_minus4 = value;
1233 self
1234 }
1235
1236 /// Saturating: a `value` under 16 has no legal `minus4` below zero and
1237 /// `0u8 - 4u8` wraps to 252 in release -- the H.264 twin of this shipped
1238 /// exactly that in every all-IDR SPS. Clamped above to the spec's 12.
1239 pub fn max_pic_order_cnt_lsb(self, value: u32) -> Self {
1240 self.log2_max_pic_order_cnt_lsb_minus4(value.ilog2().saturating_sub(4).min(12) as u8)
1241 }
1242
1243 pub fn sub_layer_ordering_info_present_flag(mut self, value: bool) -> Self {
1244 self.0.sub_layer_ordering_info_present_flag = value;
1245 self
1246 }
1247
1248 /// Sets `sps_max_dec_pic_buffering_minus1` for the highest sub-layer.
1249 pub fn max_dec_pic_buffering_minus1(mut self, value: u8) -> Self {
1250 self.0.max_dec_pic_buffering_minus1[usize::from(self.0.max_sub_layers_minus1)] = value;
1251 self
1252 }
1253
1254 /// Sets `sps_max_num_reorder_pics` for the highest sub-layer.
1255 pub fn max_num_reorder_pics(mut self, value: u8) -> Self {
1256 self.0.max_num_reorder_pics[usize::from(self.0.max_sub_layers_minus1)] = value;
1257 self
1258 }
1259
1260 /// Sets `sps_max_latency_increase_plus1` for the highest sub-layer.
1261 pub fn max_latency_increase_plus1(mut self, value: u8) -> Self {
1262 self.0.max_latency_increase_plus1[usize::from(self.0.max_sub_layers_minus1)] = value;
1263 self
1264 }
1265
1266 pub fn log2_min_luma_coding_block_size_minus3(mut self, value: u8) -> Self {
1267 self.0.log2_min_luma_coding_block_size_minus3 = value;
1268 self
1269 }
1270
1271 pub fn log2_diff_max_min_luma_coding_block_size(mut self, value: u8) -> Self {
1272 self.0.log2_diff_max_min_luma_coding_block_size = value;
1273 self
1274 }
1275
1276 pub fn log2_min_luma_transform_block_size_minus2(mut self, value: u8) -> Self {
1277 self.0.log2_min_luma_transform_block_size_minus2 = value;
1278 self
1279 }
1280
1281 pub fn log2_diff_max_min_luma_transform_block_size(mut self, value: u8) -> Self {
1282 self.0.log2_diff_max_min_luma_transform_block_size = value;
1283 self
1284 }
1285
1286 pub fn max_transform_hierarchy_depth_inter(mut self, value: u8) -> Self {
1287 self.0.max_transform_hierarchy_depth_inter = value;
1288 self
1289 }
1290
1291 pub fn max_transform_hierarchy_depth_intra(mut self, value: u8) -> Self {
1292 self.0.max_transform_hierarchy_depth_intra = value;
1293 self
1294 }
1295
1296 /// Enables `scaling_list_enabled_flag` and signals `value` in the SPS.
1297 pub fn scaling_list(mut self, value: ScalingLists) -> Self {
1298 self.0.scaling_list_enabled_flag = true;
1299 self.0.scaling_list_data_present_flag = true;
1300 self.0.scaling_list = value;
1301 self
1302 }
1303
1304 pub fn scaling_list_enabled_flag(mut self, value: bool) -> Self {
1305 self.0.scaling_list_enabled_flag = value;
1306 self
1307 }
1308
1309 pub fn amp_enabled_flag(mut self, value: bool) -> Self {
1310 self.0.amp_enabled_flag = value;
1311 self
1312 }
1313
1314 pub fn sample_adaptive_offset_enabled_flag(mut self, value: bool) -> Self {
1315 self.0.sample_adaptive_offset_enabled_flag = value;
1316 self
1317 }
1318
1319 /// Appends a st_ref_pic_set() to the SPS. Only sets that do not use inter
1320 /// RPS prediction can be synthesized.
1321 pub fn short_term_ref_pic_set(mut self, value: ShortTermRefPicSet) -> Self {
1322 self.0.short_term_ref_pic_set.push(value);
1323 self
1324 }
1325
1326 pub fn long_term_ref_pics_present_flag(mut self, value: bool) -> Self {
1327 self.0.long_term_ref_pics_present_flag = value;
1328 self
1329 }
1330
1331 pub fn temporal_mvp_enabled_flag(mut self, value: bool) -> Self {
1332 self.0.temporal_mvp_enabled_flag = value;
1333 self
1334 }
1335
1336 pub fn strong_intra_smoothing_enabled_flag(mut self, value: bool) -> Self {
1337 self.0.strong_intra_smoothing_enabled_flag = value;
1338 self
1339 }
1340
1341 pub fn vui_parameters_present(mut self) -> Self {
1342 self.0.vui_parameters_present_flag = true;
1343 self
1344 }
1345
1346 pub fn timing_info(
1347 mut self,
1348 num_units_in_tick: u32,
1349 time_scale: u32,
1350 poc_proportional_to_timing_flag: bool,
1351 ) -> Self {
1352 self = self.vui_parameters_present();
1353 self.0.vui_parameters.timing_info_present_flag = true;
1354 self.0.vui_parameters.num_units_in_tick = num_units_in_tick;
1355 self.0.vui_parameters.time_scale = time_scale;
1356 self.0.vui_parameters.poc_proportional_to_timing_flag = poc_proportional_to_timing_flag;
1357 self
1358 }
1359
1360 pub fn video_signal_type(mut self, video_format: u8, video_full_range_flag: bool) -> Self {
1361 self = self.vui_parameters_present();
1362 self.0.vui_parameters.video_signal_type_present_flag = true;
1363 self.0.vui_parameters.video_format = video_format;
1364 self.0.vui_parameters.video_full_range_flag = video_full_range_flag;
1365 self
1366 }
1367
1368 pub fn colour_description(
1369 mut self,
1370 colour_primaries: u32,
1371 transfer_characteristics: u32,
1372 matrix_coeffs: u32,
1373 ) -> Self {
1374 let video_format = self.0.vui_parameters.video_format;
1375 let video_full_range_flag = self.0.vui_parameters.video_full_range_flag;
1376
1377 self = self.video_signal_type(video_format, video_full_range_flag);
1378 self.0.vui_parameters.colour_description_present_flag = true;
1379 self.0.vui_parameters.colour_primaries = colour_primaries;
1380 self.0.vui_parameters.transfer_characteristics = transfer_characteristics;
1381 self.0.vui_parameters.matrix_coeffs = matrix_coeffs;
1382 self
1383 }
1384
1385 pub fn build(mut self) -> Rc<Sps> {
1386 let sps = &mut self.0;
1387
1388 sps.num_short_term_ref_pic_sets = sps.short_term_ref_pic_set.len() as u8;
1389
1390 // The same derivations the parser performs, see parse_sps().
1391 sps.chroma_array_type =
1392 if sps.separate_colour_plane_flag { 0 } else { sps.chroma_format_idc };
1393
1394 // (7-10)
1395 sps.min_cb_log2_size_y = u32::from(sps.log2_min_luma_coding_block_size_minus3 + 3);
1396 // (7-11)
1397 sps.ctb_log2_size_y =
1398 sps.min_cb_log2_size_y + u32::from(sps.log2_diff_max_min_luma_coding_block_size);
1399 // (7-12)
1400 sps.ctb_size_y = 1 << sps.ctb_log2_size_y;
1401 // (7-15)
1402 sps.pic_width_in_ctbs_y =
1403 (u32::from(sps.pic_width_in_luma_samples) + sps.ctb_size_y - 1) / sps.ctb_size_y;
1404 // (7-17)
1405 sps.pic_height_in_ctbs_y =
1406 (u32::from(sps.pic_height_in_luma_samples) + sps.ctb_size_y - 1) / sps.ctb_size_y;
1407 // (7-19)
1408 sps.pic_size_in_ctbs_y = sps.pic_width_in_ctbs_y * sps.pic_height_in_ctbs_y;
1409
1410 sps.max_tb_log2_size_y = u32::from(
1411 sps.log2_min_luma_transform_block_size_minus2
1412 + 2
1413 + sps.log2_diff_max_min_luma_transform_block_size,
1414 );
1415
1416 sps.pic_size_in_samples_y =
1417 u32::from(sps.pic_width_in_luma_samples) * u32::from(sps.pic_height_in_luma_samples);
1418
1419 let shift = if sps.range_extension.high_precision_offsets_enabled_flag {
1420 sps.bit_depth_luma_minus8 + 7
1421 } else {
1422 7
1423 };
1424 sps.wp_offset_half_range_y = 1 << shift;
1425
1426 let shift = if sps.range_extension.high_precision_offsets_enabled_flag {
1427 sps.bit_depth_chroma_minus8 + 7
1428 } else {
1429 7
1430 };
1431 sps.wp_offset_half_range_c = 1 << shift;
1432
1433 Rc::new(self.0)
1434 }
1435}
1436
1437#[derive(Clone, Debug, PartialEq, Eq)]
1438pub struct PpsSccExtension {
1439 /// When set, specifies that a picture referring to the PPS may be included
1440 /// in a reference picture list of a slice of the picture itself. If not
1441 /// set, specifies that a picture referring to the PPS is never included in
1442 /// a reference picture list of a slice of the picture itself.
1443 pub curr_pic_ref_enabled_flag: bool,
1444 /// When set, specifies that an adaptive colour transform may be applied to
1445 /// the residual in the decoding process. When not set, specifies that
1446 /// adaptive colour transform is not applied to the residual.
1447 pub residual_adaptive_colour_transform_enabled_flag: bool,
1448 /// When set, specifies that slice_act_y_qp_offset, slice_act_cb_qp_offset,
1449 /// slice_act_cr_qp_offset are present in the slice header. When not set,
1450 /// specifies that slice_act_y_qp_offset, slice_act_cb_qp_offset,
1451 /// slice_act_cr_qp_offset are not present in the slice header.
1452 pub slice_act_qp_offsets_present_flag: bool,
1453 /// See the specificartion for more details.
1454 pub act_y_qp_offset_plus5: i8,
1455 /// See the specificartion for more details.
1456 pub act_cb_qp_offset_plus5: i8,
1457 /// See the specificartion for more details.
1458 pub act_cr_qp_offset_plus3: i8,
1459 /// When set, specifies that the palette predictor initializers used for the
1460 /// pictures referring to the PPS are derived based on the palette predictor
1461 /// initializers specified by the PPS. If not set, specifies that the
1462 /// palette predictor initializers used for the pictures referring to the
1463 /// PPS are inferred to be equal to those specified by the active SPS.
1464 pub palette_predictor_initializers_present_flag: bool,
1465 /// Specifies the number of entries in the picture palette predictor
1466 /// initializer.
1467 pub num_palette_predictor_initializers: u8,
1468 /// When set, specifies that the pictures that refer to this PPS are
1469 /// monochrome. If not set, specifies that the pictures that refer to this
1470 /// PPS have multiple components.
1471 pub monochrome_palette_flag: bool,
1472 /// luma_bit_depth_entry_minus8 plus 8 specifies the bit depth of the luma
1473 /// component of the entries of the palette predictor initializer.
1474 pub luma_bit_depth_entry_minus8: u8,
1475 /// chroma_bit_depth_entry_minus8 plus 8 specifies the bit depth of the
1476 /// chroma components of the entries of the palette predictor initializer.
1477 pub chroma_bit_depth_entry_minus8: u8,
1478 /// `pps_palette_predictor_initializer[ comp ][ i ]` specifies the value of
1479 /// the comp-th component of the i-th palette entry in the PPS that is used
1480 /// to initialize the array PredictorPaletteEntries.
1481 pub palette_predictor_initializer: [[u8; 128]; 3],
1482}
1483
1484impl Default for PpsSccExtension {
1485 fn default() -> Self {
1486 Self {
1487 curr_pic_ref_enabled_flag: Default::default(),
1488 residual_adaptive_colour_transform_enabled_flag: Default::default(),
1489 slice_act_qp_offsets_present_flag: Default::default(),
1490 act_y_qp_offset_plus5: Default::default(),
1491 act_cb_qp_offset_plus5: Default::default(),
1492 act_cr_qp_offset_plus3: Default::default(),
1493 palette_predictor_initializers_present_flag: Default::default(),
1494 num_palette_predictor_initializers: Default::default(),
1495 monochrome_palette_flag: Default::default(),
1496 luma_bit_depth_entry_minus8: Default::default(),
1497 chroma_bit_depth_entry_minus8: Default::default(),
1498 palette_predictor_initializer: [[0; 128]; 3],
1499 }
1500 }
1501}
1502
1503#[derive(Clone, Debug, Default, PartialEq, Eq)]
1504pub struct PpsRangeExtension {
1505 /// log2_max_transform_skip_block_size_minus2 plus 2 specifies the maximum
1506 /// transform block size for which transform_skip_flag may be present in
1507 /// coded pictures referring to the PPS. When not present, the value of
1508 /// log2_max_transform_skip_block_size_minus2 is inferred to be equal to 0.
1509 /// When present, the value of log2_max_transform_skip_block_size_minus2
1510 /// shall be less than or equal to MaxTbLog2SizeY − 2.
1511 pub log2_max_transform_skip_block_size_minus2: u32,
1512 /// When set, specifies that log2_res_scale_abs_plus1 and
1513 /// res_scale_sign_flag may be present in the transform unit syntax for
1514 /// pictures referring to the PPS. When not set, specifies that
1515 /// log2_res_scale_abs_plus1 and res_scale_sign_flag are not present for
1516 /// pictures referring to the PPS.
1517 pub cross_component_prediction_enabled_flag: bool,
1518 /// When set, specifies that the cu_chroma_qp_offset_flag may be present in
1519 /// the transform unit syntax. When not set, specifies that the
1520 /// cu_chroma_qp_offset_flag is not present in the transform unit syntax.
1521 pub chroma_qp_offset_list_enabled_flag: bool,
1522 /// Specifies the difference between the luma CTB size and the minimum luma
1523 /// coding block size of coding units that convey cu_chroma_qp_offset_flag.
1524 pub diff_cu_chroma_qp_offset_depth: u32,
1525 /// chroma_qp_offset_list_len_minus1 plus 1 specifies the number of
1526 /// `cb_qp_offset_list[ i ]` and `cr_qp_offset_list[ i ]` syntax elements that
1527 /// are present in the PPS.
1528 pub chroma_qp_offset_list_len_minus1: u32,
1529 /// Specify offsets used in the derivation of Qp′Cb and Qp′Cr, respectively.
1530 pub cb_qp_offset_list: [i32; 6],
1531 /// Specify offsets used in the derivation of Qp′Cb and Qp′Cr, respectively.
1532 pub cr_qp_offset_list: [i32; 6],
1533 /// The base 2 logarithm of the scaling parameter that is used to scale
1534 /// sample adaptive offset (SAO) offset values for luma samples.
1535 pub log2_sao_offset_scale_luma: u32,
1536 /// The base 2 logarithm of the scaling parameter that is used to scale SAO
1537 /// offset values for chroma samples.
1538 pub log2_sao_offset_scale_chroma: u32,
1539}
1540
1541/// A H.265 Picture Parameter Set.
1542#[derive(Clone, Debug, PartialEq, Eq)]
1543pub struct Pps {
1544 /// Identifies the PPS for reference by other syntax elements.
1545 pub pic_parameter_set_id: u8,
1546 /// Specifies the value of sps_seq_parameter_set_id for the active SPS.
1547 pub seq_parameter_set_id: u8,
1548 /// When set, specifies the presence of the syntax element
1549 /// dependent_slice_segment_flag in the slice segment headers for coded
1550 /// pictures referring to the PPS. When not set, specifies the absence of
1551 /// the syntax element dependent_slice_segment_flag in the slice segment
1552 /// headers for coded pictures referring to the PPS.
1553 pub dependent_slice_segments_enabled_flag: bool,
1554 /// When set, indicates that the pic_output_flag syntax element is present
1555 /// in the associated slice headers. When not set, indicates that the
1556 /// pic_output_flag syntax element is not present in the associated slice
1557 /// headers.
1558 pub output_flag_present_flag: bool,
1559 /// Specifies the number of extra slice header bits that are present in the
1560 /// slice header RBSP for coded pictures referring to the PPS.
1561 pub num_extra_slice_header_bits: u8,
1562 /// When not set, specifies that sign bit hiding is disabled. Whens set,
1563 /// specifies that sign bit hiding is enabled.
1564 pub sign_data_hiding_enabled_flag: bool,
1565 /// When set, specifies that cabac_init_flag is present in slice headers
1566 /// referring to the PPS. When not set, specifies that cabac_init_flag is
1567 /// not present in slice headers referring to the PPS.
1568 pub cabac_init_present_flag: bool,
1569 /// Specifies the inferred value of num_ref_idx_l0_active_minus1 for P and B
1570 /// slices with num_ref_idx_active_override_flag not set.
1571 pub num_ref_idx_l0_default_active_minus1: u8,
1572 /// Specifies the inferred value of num_ref_idx_l1_active_minus1 for B
1573 /// slices with num_ref_idx_active_override_flag not set.
1574 pub num_ref_idx_l1_default_active_minus1: u8,
1575 /// init_qp_minus26 plus 26 specifies the initial value of SliceQpY for each
1576 /// slice referring to the PPS. The initial value of SliceQpY is modified at
1577 /// the slice segment layer when a non-zero value of slice_qp_delta is
1578 /// decoded.
1579 pub init_qp_minus26: i8,
1580 /// When not set, specifies that intra prediction allows usage of residual
1581 /// data and decoded samples of neighbouring coding blocks coded using
1582 /// either intra or inter prediction modes. When set, specifies constrained
1583 /// intra prediction, in which case intra prediction only uses residual data
1584 /// and decoded samples from neighbouring coding blocks coded using intra
1585 /// prediction modes.
1586 pub constrained_intra_pred_flag: bool,
1587 /// When set, specifies that transform_skip_flag may be present in the
1588 /// residual coding syntax. When not set, specifies that transform_skip_flag
1589 /// is not present in the residual coding syntax.
1590 pub transform_skip_enabled_flag: bool,
1591 /// When set, specifies that the diff_cu_qp_delta_depth syntax element is
1592 /// present in the PPS and that cu_qp_delta_abs may be present in the
1593 /// transform unit syntax and the palette syntax. When not set, specifies
1594 /// that the diff_cu_qp_delta_depth syntax element is not present in the PPS
1595 /// and that cu_qp_delta_abs is not present in the transform unit syntax and
1596 /// the palette syntax.
1597 pub cu_qp_delta_enabled_flag: bool,
1598
1599 /*if cu_qp_delta_enabled_flag */
1600 /// Specifies the difference between the luma CTB size and the minimum luma
1601 /// coding block size of coding units that convey cu_qp_delta_abs and
1602 /// cu_qp_delta_sign_flag.
1603 pub diff_cu_qp_delta_depth: u8,
1604 /// Specifies the offsets to the luma quantization parameter Qp′Y used for
1605 /// deriving Qp′Cb and Qp′Cr, respectively.
1606 pub cb_qp_offset: i8,
1607 /// Specifies the offsets to the luma quantization parameter Qp′Y used for
1608 /// deriving Qp′Cb and Qp′Cr, respectively.
1609 pub cr_qp_offset: i8,
1610 /// When set, indicates that the slice_cb_qp_offset and slice_cr_qp_offset
1611 /// syntax elements are present in the associated slice headers. When not
1612 /// set, indicates that these syntax elements are not present in the
1613 /// associated slice headers. When ChromaArrayType is equal to 0,
1614 /// pps_slice_chroma_qp_offsets_present_flag shall be equal to 0
1615 pub slice_chroma_qp_offsets_present_flag: bool,
1616 /// When not set, specifies that weighted prediction is not applied to P
1617 /// slices. When set, specifies that weighted prediction is applied to P
1618 /// slices.
1619 pub weighted_pred_flag: bool,
1620 /// When not set, specifies that the default weighted prediction is applied
1621 /// to B slices. When set, specifies that weighted prediction is applied to
1622 /// B slices.
1623 pub weighted_bipred_flag: bool,
1624 /// When set, specifies that `cu_transquant_bypass_flag` is present, When
1625 /// not set, specifies that `cu_transquant_bypass_flag` is not present.
1626 pub transquant_bypass_enabled_flag: bool,
1627 /// When set, specifies that there is more than one tile in each picture
1628 /// referring to the PPS. When not set, specifies that there is only one
1629 /// tile in each picture referring to the PPS.
1630 pub tiles_enabled_flag: bool,
1631 /// When set, specifies that a specific synchronization process for context
1632 /// variables, and when applicable, Rice parameter initialization states and
1633 /// palette predictor variables, is invoked before decoding the CTU which
1634 /// includes the first CTB of a row of CTBs in each tile in each picture
1635 /// referring to the PPS, and a specific storage process for context
1636 /// variables, and when applicable, Rice parameter initialization states and
1637 /// palette predictor variables, is invoked after decoding the CTU which
1638 /// includes the second CTB of a row of CTBs in each tile in each picture
1639 /// referring to the PPS. When not set, specifies that no specific
1640 /// synchronization process for context variables, and when applicable, Rice
1641 /// parameter initialization states and palette predictor variables, is
1642 /// required to be invoked before decoding the CTU which includes the first
1643 /// CTB of a row of CTBs in each tile in each picture referring to the PPS,
1644 /// and no specific storage process for context variables, and when
1645 /// applicable, Rice parameter initialization states and palette predictor
1646 /// variables, is required to be invoked after decoding the CTU which
1647 /// includes the second CTB of a row of CTBs in each tile in each picture
1648 /// referring to the PPS.
1649 pub entropy_coding_sync_enabled_flag: bool,
1650 /// num_tile_columns_minus1 plus 1 specifies the number of tile columns
1651 /// partitioning the picture.
1652 pub num_tile_columns_minus1: u8,
1653 /// num_tile_rows_minus1 plus 1 specifies the number of tile rows
1654 /// partitioning the picture.
1655 pub num_tile_rows_minus1: u8,
1656 /// When set, specifies that tile column boundaries and likewise tile row
1657 /// boundaries are distributed uniformly across the picture. When not set,
1658 /// specifies that tile column boundaries and likewise tile row boundaries
1659 /// are not distributed uniformly across the picture but signalled
1660 /// explicitly using the syntax elements `column_width_minus1[ i ]` and
1661 /// `row_height_minus1[ i ]`.
1662 pub uniform_spacing_flag: bool,
1663 /// `column_width_minus1[ i ]` plus 1 specifies the width of the i-th tile
1664 /// column in units of CTBs.
1665 pub column_width_minus1: [u32; 19],
1666 /// `row_height_minus1[ i ]` plus 1 specifies the height of the i-th tile row
1667 /// in units of CTBs.
1668 pub row_height_minus1: [u32; 21],
1669 /// When set, specifies that in-loop filtering operations may be performed
1670 /// across tile boundaries in pictures referring to the PPS. When not set,
1671 /// specifies that in-loop filtering operations are not performed across
1672 /// tile boundaries in pictures referring to the PPS. The in-loop filtering
1673 /// operations include the deblocking filter and sample adaptive offset
1674 /// filter operations.
1675 pub loop_filter_across_tiles_enabled_flag: bool,
1676 /// When set, specifies that in-loop filtering operations may be performed
1677 /// across left and upper boundaries of slices referring to the PPS. When
1678 /// not set, specifies that in-loop filtering operations are not performed
1679 /// across left and upper boundaries of slices referring to the PPS. The in-
1680 /// loop filtering operations include the deblocking filter and sample
1681 /// adaptive offset filter operations.
1682 pub loop_filter_across_slices_enabled_flag: bool,
1683 /// When set, specifies the presence of deblocking filter control syntax
1684 /// elements in the PPS. When not set, specifies the absence of deblocking
1685 /// filter control syntax elements in the PPS.
1686 pub deblocking_filter_control_present_flag: bool,
1687 /// When set, specifies the presence of deblocking_filter_override_flag in
1688 /// the slice headers for pictures referring to the PPS. When not set,
1689 /// specifies the absence of deblocking_filter_override_flag in the slice
1690 /// headers for pictures referring to the PPS.
1691 pub deblocking_filter_override_enabled_flag: bool,
1692 /// When set, specifies that the operation of deblocking filter is not
1693 /// applied for slices referring to the PPS in which
1694 /// slice_deblocking_filter_disabled_flag is not present. When not set,
1695 /// specifies that the operation of the deblocking filter is applied for
1696 /// slices referring to the PPS in which
1697 /// slice_deblocking_filter_disabled_flag is not present.
1698 pub deblocking_filter_disabled_flag: bool,
1699 /// Specify the default deblocking parameter offsets for β and tC (divided
1700 /// by 2) that are applied for slices referring to the PPS, unless the
1701 /// default deblocking parameter offsets are overridden by the deblocking
1702 /// parameter offsets present in the slice headers of the slices referring
1703 /// to the PPS.
1704 pub beta_offset_div2: i8,
1705 /// Specify the default deblocking parameter offsets for β and tC (divided
1706 /// by 2) that are applied for slices referring to the PPS, unless the
1707 /// default deblocking parameter offsets are overridden by the deblocking
1708 /// parameter offsets present in the slice headers of the slices referring
1709 /// to the PPS.
1710 pub tc_offset_div2: i8,
1711 /// When set, specifies that the scaling list data used for the pictures
1712 /// referring to the PPS are derived based on the scaling lists specified by
1713 /// the active SPS and the scaling lists specified by the PPS.
1714 /// pps_scaling_list_data_present_flag equal to 0 specifies that the scaling
1715 /// list data used for the pictures referring to the PPS are inferred to be
1716 /// equal to those specified by the active SPS.
1717 pub scaling_list_data_present_flag: bool,
1718 /// The scaling list data.
1719 pub scaling_list: ScalingLists,
1720 /// When set, specifies that the syntax structure
1721 /// ref_pic_lists_modification( ) is present in the slice segment header.
1722 /// When not set, specifies that the syntax structure
1723 /// ref_pic_lists_modification( ) is not present in the slice segment header
1724 pub lists_modification_present_flag: bool,
1725 /// log2_parallel_merge_level_minus2 plus 2 specifies the value of the
1726 /// variable Log2ParMrgLevel, which is used in the derivation process for
1727 /// luma motion vectors for merge mode as specified in clause 8.5.3.2.2 and
1728 /// the derivation process for spatial merging candidates as specified in
1729 /// clause 8.5.3.2.3.
1730 pub log2_parallel_merge_level_minus2: u8,
1731 /// When not set, specifies that no slice segment header extension syntax
1732 /// elements are present in the slice segment headers for coded pictures
1733 /// referring to the PPS. When set, specifies that slice segment header
1734 /// extension syntax elements are present in the slice segment headers for
1735 /// coded pictures referring to the PPS.
1736 pub slice_segment_header_extension_present_flag: bool,
1737 /// When set, specifies that the syntax elements pps_range_extension_flag,
1738 /// pps_multilayer_extension_flag, pps_3d_extension_flag,
1739 /// pps_scc_extension_flag, and pps_extension_4bits are present in the
1740 /// picture parameter set RBSP syntax structure. When not set, specifies
1741 /// that these syntax elements are not present.
1742 pub extension_present_flag: bool,
1743 /// When setspecifies that the pps_range_extension( ) syntax structure is
1744 /// present in the PPS RBSP syntax structure. When not set, specifies that
1745 /// this syntax structure is not present.
1746 pub range_extension_flag: bool,
1747 /// The range extension data.
1748 pub range_extension: PpsRangeExtension,
1749
1750 pub scc_extension_flag: bool,
1751 /// The SCC extension data.
1752 pub scc_extension: PpsSccExtension,
1753
1754 // Internal variables.
1755 /// Equivalent to QpBdOffsetY in the specification.
1756 pub qp_bd_offset_y: u32,
1757
1758 /// The SPS referenced by this PPS.
1759 pub sps: Rc<Sps>,
1760}
1761
1762/// A builder for a [`Pps`], covering the syntax elements an encoder is expected
1763/// to set. Anything else is left at its specification default.
1764pub struct PpsBuilder(Pps);
1765
1766impl PpsBuilder {
1767 /// Starts a PPS referring to `sps`.
1768 pub fn new(sps: Rc<Sps>) -> Self {
1769 let mut scaling_list = ScalingLists::default();
1770
1771 // When pps_scaling_list_data_present_flag is not set and the SPS does
1772 // not signal scaling lists either, the default lists apply, see 7.4.5.
1773 for size_id in 0..4 {
1774 let mut matrix_id = 0;
1775 while matrix_id < 6 {
1776 Parser::fill_default_scaling_list(&mut scaling_list, size_id, matrix_id);
1777 matrix_id += if size_id == 3 { 3 } else { 1 };
1778 }
1779 }
1780
1781 PpsBuilder(Pps {
1782 pic_parameter_set_id: 0,
1783 seq_parameter_set_id: sps.seq_parameter_set_id,
1784 dependent_slice_segments_enabled_flag: false,
1785 output_flag_present_flag: false,
1786 num_extra_slice_header_bits: 0,
1787 sign_data_hiding_enabled_flag: false,
1788 cabac_init_present_flag: false,
1789 num_ref_idx_l0_default_active_minus1: 0,
1790 num_ref_idx_l1_default_active_minus1: 0,
1791 init_qp_minus26: 0,
1792 constrained_intra_pred_flag: false,
1793 transform_skip_enabled_flag: false,
1794 cu_qp_delta_enabled_flag: false,
1795 diff_cu_qp_delta_depth: 0,
1796 cb_qp_offset: 0,
1797 cr_qp_offset: 0,
1798 slice_chroma_qp_offsets_present_flag: false,
1799 weighted_pred_flag: false,
1800 weighted_bipred_flag: false,
1801 transquant_bypass_enabled_flag: false,
1802 tiles_enabled_flag: false,
1803 entropy_coding_sync_enabled_flag: false,
1804 num_tile_columns_minus1: 0,
1805 num_tile_rows_minus1: 0,
1806 uniform_spacing_flag: true,
1807 column_width_minus1: Default::default(),
1808 row_height_minus1: Default::default(),
1809 loop_filter_across_tiles_enabled_flag: true,
1810 loop_filter_across_slices_enabled_flag: false,
1811 deblocking_filter_control_present_flag: false,
1812 deblocking_filter_override_enabled_flag: false,
1813 deblocking_filter_disabled_flag: false,
1814 beta_offset_div2: 0,
1815 tc_offset_div2: 0,
1816 scaling_list_data_present_flag: false,
1817 scaling_list,
1818 lists_modification_present_flag: false,
1819 log2_parallel_merge_level_minus2: 0,
1820 slice_segment_header_extension_present_flag: false,
1821 extension_present_flag: false,
1822 range_extension_flag: false,
1823 range_extension: Default::default(),
1824 scc_extension_flag: false,
1825 scc_extension: Default::default(),
1826 // (7-5)
1827 qp_bd_offset_y: 6 * u32::from(sps.bit_depth_luma_minus8),
1828 sps,
1829 })
1830 }
1831
1832 pub fn pic_parameter_set_id(mut self, value: u8) -> Self {
1833 self.0.pic_parameter_set_id = value;
1834 self
1835 }
1836
1837 pub fn dependent_slice_segments_enabled_flag(mut self, value: bool) -> Self {
1838 self.0.dependent_slice_segments_enabled_flag = value;
1839 self
1840 }
1841
1842 pub fn output_flag_present_flag(mut self, value: bool) -> Self {
1843 self.0.output_flag_present_flag = value;
1844 self
1845 }
1846
1847 pub fn num_extra_slice_header_bits(mut self, value: u8) -> Self {
1848 self.0.num_extra_slice_header_bits = value;
1849 self
1850 }
1851
1852 pub fn sign_data_hiding_enabled_flag(mut self, value: bool) -> Self {
1853 self.0.sign_data_hiding_enabled_flag = value;
1854 self
1855 }
1856
1857 pub fn cabac_init_present_flag(mut self, value: bool) -> Self {
1858 self.0.cabac_init_present_flag = value;
1859 self
1860 }
1861
1862 pub fn num_ref_idx_l0_default_active_minus1(mut self, value: u8) -> Self {
1863 self.0.num_ref_idx_l0_default_active_minus1 = value;
1864 self
1865 }
1866
1867 pub fn num_ref_idx_l1_default_active_minus1(mut self, value: u8) -> Self {
1868 self.0.num_ref_idx_l1_default_active_minus1 = value;
1869 self
1870 }
1871
1872 pub fn init_qp_minus26(mut self, value: i8) -> Self {
1873 self.0.init_qp_minus26 = value;
1874 self
1875 }
1876
1877 /// Sets `init_qp_minus26` from the initial SliceQpY value.
1878 pub fn init_qp(self, value: i8) -> Self {
1879 self.init_qp_minus26(value - 26)
1880 }
1881
1882 pub fn constrained_intra_pred_flag(mut self, value: bool) -> Self {
1883 self.0.constrained_intra_pred_flag = value;
1884 self
1885 }
1886
1887 pub fn transform_skip_enabled_flag(mut self, value: bool) -> Self {
1888 self.0.transform_skip_enabled_flag = value;
1889 self
1890 }
1891
1892 pub fn cu_qp_delta_enabled_flag(mut self, value: bool) -> Self {
1893 self.0.cu_qp_delta_enabled_flag = value;
1894 self
1895 }
1896
1897 pub fn diff_cu_qp_delta_depth(mut self, value: u8) -> Self {
1898 self.0.diff_cu_qp_delta_depth = value;
1899 self
1900 }
1901
1902 pub fn cb_qp_offset(mut self, value: i8) -> Self {
1903 self.0.cb_qp_offset = value;
1904 self
1905 }
1906
1907 pub fn cr_qp_offset(mut self, value: i8) -> Self {
1908 self.0.cr_qp_offset = value;
1909 self
1910 }
1911
1912 pub fn slice_chroma_qp_offsets_present_flag(mut self, value: bool) -> Self {
1913 self.0.slice_chroma_qp_offsets_present_flag = value;
1914 self
1915 }
1916
1917 pub fn weighted_pred_flag(mut self, value: bool) -> Self {
1918 self.0.weighted_pred_flag = value;
1919 self
1920 }
1921
1922 pub fn weighted_bipred_flag(mut self, value: bool) -> Self {
1923 self.0.weighted_bipred_flag = value;
1924 self
1925 }
1926
1927 pub fn transquant_bypass_enabled_flag(mut self, value: bool) -> Self {
1928 self.0.transquant_bypass_enabled_flag = value;
1929 self
1930 }
1931
1932 pub fn entropy_coding_sync_enabled_flag(mut self, value: bool) -> Self {
1933 self.0.entropy_coding_sync_enabled_flag = value;
1934 self
1935 }
1936
1937 pub fn loop_filter_across_slices_enabled_flag(mut self, value: bool) -> Self {
1938 self.0.loop_filter_across_slices_enabled_flag = value;
1939 self
1940 }
1941
1942 pub fn deblocking_filter_control_present_flag(mut self, value: bool) -> Self {
1943 self.0.deblocking_filter_control_present_flag = value;
1944 self
1945 }
1946
1947 pub fn deblocking_filter_override_enabled_flag(mut self, value: bool) -> Self {
1948 self.0.deblocking_filter_override_enabled_flag = value;
1949 self
1950 }
1951
1952 pub fn deblocking_filter_disabled_flag(mut self, value: bool) -> Self {
1953 self.0.deblocking_filter_disabled_flag = value;
1954 self
1955 }
1956
1957 /// Sets the default deblocking parameter offsets, which are only signalled
1958 /// when the deblocking filter is not disabled.
1959 pub fn deblocking_filter_offsets(mut self, beta_div2: i8, tc_div2: i8) -> Self {
1960 self.0.deblocking_filter_control_present_flag = true;
1961 self.0.beta_offset_div2 = beta_div2;
1962 self.0.tc_offset_div2 = tc_div2;
1963 self
1964 }
1965
1966 /// Signals `value` in the PPS, overriding the scaling lists of the SPS.
1967 pub fn scaling_list(mut self, value: ScalingLists) -> Self {
1968 self.0.scaling_list_data_present_flag = true;
1969 self.0.scaling_list = value;
1970 self
1971 }
1972
1973 pub fn lists_modification_present_flag(mut self, value: bool) -> Self {
1974 self.0.lists_modification_present_flag = value;
1975 self
1976 }
1977
1978 pub fn log2_parallel_merge_level_minus2(mut self, value: u8) -> Self {
1979 self.0.log2_parallel_merge_level_minus2 = value;
1980 self
1981 }
1982
1983 pub fn slice_segment_header_extension_present_flag(mut self, value: bool) -> Self {
1984 self.0.slice_segment_header_extension_present_flag = value;
1985 self
1986 }
1987
1988 pub fn build(self) -> Rc<Pps> {
1989 Rc::new(self.0)
1990 }
1991}
1992
1993#[derive(Clone, Debug, PartialEq, Eq)]
1994pub struct ScalingLists {
1995 /// plus 8 specifies the value of the variable `ScalingFactor[ 2 ][ matrixId
1996 /// ] [ 0 ][ 0 ]` for the scaling list for the 16x16 size.
1997 pub scaling_list_dc_coef_minus8_16x16: [i16; 6],
1998 /// plus 8 specifies the value of the variable `ScalingFactor[ 3 ][ matrixId
1999 /// ][ 0 ][ 0 ]` for the scaling list for the 32x32 size.
2000 pub scaling_list_dc_coef_minus8_32x32: [i16; 6],
2001 /// The 4x4 scaling list.
2002 pub scaling_list_4x4: [[u8; 16]; 6],
2003 /// The 8x8 scaling list.
2004 pub scaling_list_8x8: [[u8; 64]; 6],
2005 /// The 16x16 scaling list.
2006 pub scaling_list_16x16: [[u8; 64]; 6],
2007 /// The 32x32 scaling list.
2008 pub scaling_list_32x32: [[u8; 64]; 6],
2009}
2010
2011impl Default for ScalingLists {
2012 fn default() -> Self {
2013 Self {
2014 scaling_list_dc_coef_minus8_16x16: Default::default(),
2015 scaling_list_dc_coef_minus8_32x32: Default::default(),
2016 scaling_list_4x4: Default::default(),
2017 scaling_list_8x8: [[0; 64]; 6],
2018 scaling_list_16x16: [[0; 64]; 6],
2019 scaling_list_32x32: [[0; 64]; 6],
2020 }
2021 }
2022}
2023
2024#[derive(Clone, Debug, Default, PartialEq, Eq)]
2025pub struct RefPicListModification {
2026 /// Whenset, indicates that reference picture list 0 is specified explicitly
2027 /// by a list of `list_entry_l0[ i ]` values. When not set, indicates that
2028 /// reference picture list 0 is determined implicitly.
2029 pub ref_pic_list_modification_flag_l0: bool,
2030 /// `list_entry_l0[ i ]` specifies the index of the reference picture in
2031 /// RefPicListTemp0 to be placed at the current position of reference
2032 /// picture list 0.
2033 pub list_entry_l0: Vec<u32>,
2034 /// Whenset, indicates that reference picture list 1 is specified explicitly
2035 /// by a list of `list_entry_l1[ i ]` values. When not set, indicates that
2036 /// reference picture list 1 is determined implicitly.
2037 pub ref_pic_list_modification_flag_l1: bool,
2038 /// `list_entry_l1[ i ]` specifies the index of the reference picture in
2039 /// RefPicListTemp1 to be placed at the current position of reference
2040 /// picture list 1.
2041 pub list_entry_l1: Vec<u32>,
2042}
2043
2044#[derive(Clone, Debug, Default, PartialEq, Eq)]
2045pub struct PredWeightTable {
2046 /// The base 2 logarithm of the denominator for all luma weighting factors.
2047 pub luma_log2_weight_denom: u8,
2048 /// The difference of the base 2 logarithm of the denominator for all chroma
2049 /// weighting factors.
2050 pub delta_chroma_log2_weight_denom: i8,
2051 /// `luma_weight_l0_flag[ i ]` set specifies that weighting factors for the
2052 /// luma component of list 0 prediction using `RefPicList0[ i ]` are present.
2053 /// `luma_weight_l0_flag[ i ]` not set specifies that these weighting factors
2054 /// are not present.
2055 pub luma_weight_l0_flag: [bool; 15],
2056 /// `chroma_weight_l0_flag[ i ]` set specifies that weighting factors for the
2057 /// chroma prediction values of list 0 prediction using `RefPicList0[ i ]` are
2058 /// present. `chroma_weight_l0_flag[ i ]` not set specifies that these
2059 /// weighting factors are not present.
2060 pub chroma_weight_l0_flag: [bool; 15],
2061 /// `delta_luma_weight_l0[ i ]` is the difference of the weighting factor
2062 /// applied to the luma prediction value for list 0 prediction using
2063 /// `RefPicList0[ i ]`.
2064 pub delta_luma_weight_l0: [i8; 15],
2065 /// `luma_offset_l0[ i ]` is the additive offset applied to the luma
2066 /// prediction value for list 0 prediction using `RefPicList0[ i ]`.
2067 pub luma_offset_l0: [i8; 15],
2068 /// `delta_chroma_weight_l0[ i ][ j ]` is the difference of the weighting
2069 /// factor applied to the chroma prediction values for list 0 prediction
2070 /// using `RefPicList0[ i ]` with j equal to 0 for Cb and j equal to 1 for Cr.
2071 pub delta_chroma_weight_l0: [[i8; 2]; 15],
2072 /// `delta_chroma_offset_l0[ i ][ j ]` is the difference of the additive
2073 /// offset applied to the chroma prediction values for list 0 prediction
2074 /// using `RefPicList0[ i ]` with j equal to 0 for Cb and j equal to 1 for Cr.
2075 pub delta_chroma_offset_l0: [[i16; 2]; 15],
2076
2077 // `luma_weight_l1_flag[ i ]`, `chroma_weight_l1_flag[ i ]`,
2078 // `delta_luma_weight_l1[ i ]`, `luma_offset_l1[ i ]`, delta_chroma_weight_l1[ i
2079 // `][ j ]` and `delta_chroma_offset_l1[ i ]`[ j ] have the same
2080 // `semanticsasluma_weight_l0_flag[ i ]`, `chroma_weight_l0_flag[ i ]`,
2081 // `delta_luma_weight_l0[ i ]`, `luma_offset_l0[ i ]`, `delta_chroma_weight_l0[ i
2082 // ][ j ]` and `delta_chroma_offset_l0[ i ][ j ]`, respectively, with `l0`, `L0`,
2083 // `list 0` and `List0` replaced by `l1`, `L1`, `list 1` and `List1`, respectively.
2084 pub luma_weight_l1_flag: [bool; 15],
2085 pub chroma_weight_l1_flag: [bool; 15],
2086 pub delta_luma_weight_l1: [i8; 15],
2087 pub luma_offset_l1: [i8; 15],
2088
2089 pub delta_chroma_weight_l1: [[i8; 2]; 15],
2090 pub delta_chroma_offset_l1: [[i16; 2]; 15],
2091
2092 // Calculated.
2093 /// Same as ChromaLog2WeightDenom in the specification.
2094 pub chroma_log2_weight_denom: u8,
2095}
2096
2097#[derive(Clone, Debug, PartialEq, Eq)]
2098pub struct ShortTermRefPicSet {
2099 /// When set, specifies that the stRpsIdx-th candidate short-term RPS is
2100 /// predicted from another candidate short-term RPS, which is referred to as
2101 /// the source candidate short-term RPS.
2102 pub inter_ref_pic_set_prediction_flag: bool,
2103 /// delta_idx_minus1 plus 1 specifies the difference between the value of
2104 /// stRpsIdx and the index, into the list of the candidate short-term RPSs
2105 /// specified in the SPS, of the source candidate short-term RPS.
2106 pub delta_idx_minus1: u8,
2107 /// delta_rps_sign and abs_delta_rps_minus1 together specify the value of
2108 /// the variable deltaRps.
2109 pub delta_rps_sign: bool,
2110 /// delta_rps_sign and abs_delta_rps_minus1 together specify the value of
2111 /// the variable deltaRps.
2112 pub abs_delta_rps_minus1: u16,
2113 /// specifies the number of entries in the stRpsIdx-th candidate short-term
2114 /// RPS that have picture order count values less than the picture order
2115 /// count value of the current picture.
2116 pub num_negative_pics: u8,
2117 /// specifies the number of entries in the stRpsIdx-th candidate short-term
2118 /// RPS that have picture order count values greater than the picture order
2119 /// count value of the current picture.
2120 pub num_positive_pics: u8,
2121 /// Same as UsedByCurrPicS0 in the specification.
2122 pub used_by_curr_pic_s0: [bool; MAX_SHORT_TERM_REF_PIC_SETS],
2123 /// Same as UsedByCurrPicS1 in the specification.
2124 pub used_by_curr_pic_s1: [bool; MAX_SHORT_TERM_REF_PIC_SETS],
2125 /// Same as DeltaPocS0 in the specification.
2126 pub delta_poc_s0: [i32; MAX_SHORT_TERM_REF_PIC_SETS],
2127 /// Same as DeltaPocS1 in the specification.
2128 pub delta_poc_s1: [i32; MAX_SHORT_TERM_REF_PIC_SETS],
2129 /// Same as NumDeltaPocs in the specification.
2130 pub num_delta_pocs: u32,
2131}
2132
2133impl Default for ShortTermRefPicSet {
2134 fn default() -> Self {
2135 Self {
2136 inter_ref_pic_set_prediction_flag: Default::default(),
2137 delta_idx_minus1: Default::default(),
2138 delta_rps_sign: Default::default(),
2139 abs_delta_rps_minus1: Default::default(),
2140 num_negative_pics: Default::default(),
2141 num_positive_pics: Default::default(),
2142 used_by_curr_pic_s0: [false; MAX_SHORT_TERM_REF_PIC_SETS],
2143 used_by_curr_pic_s1: [false; MAX_SHORT_TERM_REF_PIC_SETS],
2144 delta_poc_s0: [0; MAX_SHORT_TERM_REF_PIC_SETS],
2145 delta_poc_s1: [0; MAX_SHORT_TERM_REF_PIC_SETS],
2146 num_delta_pocs: Default::default(),
2147 }
2148 }
2149}
2150
2151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2152/// See table 7-7 in the specification.
2153pub enum SliceType {
2154 B = 0,
2155 P = 1,
2156 I = 2,
2157}
2158
2159impl TryFrom<u32> for SliceType {
2160 type Error = String;
2161
2162 fn try_from(value: u32) -> Result<Self, Self::Error> {
2163 match value {
2164 0 => Ok(SliceType::B),
2165 1 => Ok(SliceType::P),
2166 2 => Ok(SliceType::I),
2167 _ => Err(format!("Invalid SliceType {}", value)),
2168 }
2169 }
2170}
2171
2172impl SliceType {
2173 /// Whether this is a P slice. See table 7-7 in the specification.
2174 pub fn is_p(&self) -> bool {
2175 matches!(self, SliceType::P)
2176 }
2177
2178 /// Whether this is a B slice. See table 7-7 in the specification.
2179 pub fn is_b(&self) -> bool {
2180 matches!(self, SliceType::B)
2181 }
2182
2183 /// Whether this is an I slice. See table 7-7 in the specification.
2184 pub fn is_i(&self) -> bool {
2185 matches!(self, SliceType::I)
2186 }
2187}
2188
2189impl Default for SliceType {
2190 fn default() -> Self {
2191 Self::P
2192 }
2193}
2194
2195#[derive(Clone, Debug, PartialEq, Eq)]
2196pub struct SliceHeader {
2197 /// When set, specifies that the slice segment is the first slice segment of
2198 /// the picture in decoding order. When not set, specifies that the slice
2199 /// segment is not the first slice segment of the picture in decoding order.
2200 pub first_slice_segment_in_pic_flag: bool,
2201 /// Affects the output of previously-decoded pictures in the decoded picture
2202 /// buffer after the decoding of an IDR or a BLA picture that is not the
2203 /// first picture in the bitstream as specified in Annex C.
2204 pub no_output_of_prior_pics_flag: bool,
2205 /// Specifies the value of pps_pic_parameter_set_id for the PPS in use.
2206 pub pic_parameter_set_id: u8,
2207 /// When set, specifies that the value of each slice segment header syntax
2208 /// element that is not present is inferred to be equal to the value of the
2209 /// corresponding slice segment header syntax element in the slice header.
2210 pub dependent_slice_segment_flag: bool,
2211 /// Specifies the address of the first CTB in the slice segment, in CTB
2212 /// raster scan of a picture.
2213 pub segment_address: u32,
2214 /// Specifies the coding type of the slice according to Table 7-7.
2215 pub type_: SliceType,
2216 /// Affects the decoded picture output and removal processes as specified in
2217 /// Annex C.
2218 pub pic_output_flag: bool,
2219 /// Specifies the colour plane associated with the current slice RBSP when
2220 /// separate_colour_plane_flag is set. The value of colour_plane_id shall be
2221 /// in the range of 0 to 2, inclusive. colour_plane_id values 0, 1 and 2
2222 /// correspond to the Y, Cb and Cr planes, respectively.
2223 pub colour_plane_id: u8,
2224 /// Specifies the picture order count modulo MaxPicOrderCntLsb for the
2225 /// current picture. The length of the slice_pic_order_cnt_lsb syntax
2226 /// element is log2_max_pic_order_cnt_lsb_minus4 + 4 bits.
2227 pub pic_order_cnt_lsb: u16,
2228 /// When set, specifies that the short-term RPS of the current picture is
2229 /// derived based on one of the st_ref_pic_set( ) syntax structures in the
2230 /// active SPS that is identified by the syntax element
2231 /// short_term_ref_pic_set_idx in the slice header. When not set, specifies
2232 /// that the short-term RPS of the current picture is derived based on the
2233 /// st_ref_pic_set( ) syntax structure that is directly included in the
2234 /// slice headers of the current picture.
2235 pub short_term_ref_pic_set_sps_flag: bool,
2236 /// The st_ref_pic_set() data.
2237 pub short_term_ref_pic_set: ShortTermRefPicSet,
2238 /// Specifies the index, into the list of the st_ref_pic_set( ) syntax
2239 /// structures included in the active SPS, of the st_ref_pic_set( ) syntax
2240 /// structure that is used for derivation of the short-term RPS of the
2241 /// current picture.
2242 pub short_term_ref_pic_set_idx: u8,
2243 /// Specifies the number of entries in the long-term RPS of the current
2244 /// picture that are derived based on the candidate long-term reference
2245 /// pictures specified in the active SPS.
2246 pub num_long_term_sps: u8,
2247 /// Specifies the number of entries in the long-term RPS of the current
2248 /// picture that are directly signalled in the slice header.
2249 pub num_long_term_pics: u8,
2250 /// `lt_idx_sps[ i ]` specifies an index, into the list of candidate long-term
2251 /// reference pictures specified in the active SPS, of the i-th entry in the
2252 /// long-term RPS of the current picture.
2253 pub lt_idx_sps: [u8; 16],
2254 /// Same as PocLsbLt in the specification.
2255 pub poc_lsb_lt: [u32; 16],
2256 /// Same as UsedByCurrPicLt in the specification.
2257 pub used_by_curr_pic_lt: [bool; 16],
2258 /// When set, specifies that that `delta_poc_msb_cycle_lt[i]` is present.
2259 pub delta_poc_msb_present_flag: [bool; 16],
2260 /// Same as DeltaPocMsbCycleLt in the specification.
2261 pub delta_poc_msb_cycle_lt: [u32; 16],
2262 /// Specifies whether temporal motion vector predictors can be used for
2263 /// inter prediction. If slice_temporal_mvp_enabled_flag is not set, the
2264 /// syntax elements of the current picture shall be constrained such that no
2265 /// temporal motion vector predictor is used in decoding of the current
2266 /// picture. Otherwise (slice_temporal_mvp_enabled_flag is set), temporal
2267 /// motion vector predictors may be used in decoding of the current picture.
2268 pub temporal_mvp_enabled_flag: bool,
2269 /// When set, specifies that SAO is enabled for the luma component in the
2270 /// current slice; slice_sao_luma_flag not set specifies that SAO is
2271 /// disabled for the luma component in the current slice.
2272 pub sao_luma_flag: bool,
2273 /// When set, specifies that SAO is enabled for the chroma component in the
2274 /// current slice; When not set, specifies that SAO is disabled for the
2275 /// chroma component in the current slice.
2276 pub sao_chroma_flag: bool,
2277 /// When set, specifies that the syntax element num_ref_idx_l0_active_minus1
2278 /// is present for P and B slices and that the syntax element
2279 /// num_ref_idx_l1_active_minus1 is present for B slices. When not set,
2280 /// specifies that the syntax elements num_ref_idx_l0_active_minus1 and
2281 /// num_ref_idx_l1_active_minus1 are not present.
2282 pub num_ref_idx_active_override_flag: bool,
2283 /// Specifies the maximum reference index for
2284 /// reference picture list 0 that may be used to decode the slice.
2285 pub num_ref_idx_l0_active_minus1: u8,
2286 /// Specifies the maximum reference index for reference picture list 1 that
2287 /// may be used to decode the slice.
2288 pub num_ref_idx_l1_active_minus1: u8,
2289 /// The RefPicListModification data.
2290 pub ref_pic_list_modification: RefPicListModification,
2291 /// When set, indicates that the mvd_coding( x0, y0, 1 ) syntax structure is
2292 /// not parsed and `MvdL1[ x0 ]`[ y0 `][ compIdx ]` is set equal to 0 for
2293 /// compIdx = 0..1. When not set, indicates that the mvd_coding( x0, y0, 1 )
2294 /// syntax structure is parsed.
2295 pub mvd_l1_zero_flag: bool,
2296 /// Specifies the method for determining the initialization table used in
2297 /// the initialization process for context variables.
2298 pub cabac_init_flag: bool,
2299 /// When set, specifies that the collocated picture used for temporal motion
2300 /// vector prediction is derived from reference picture list 0. When not
2301 /// set, specifies that the collocated picture used for temporal motion
2302 /// vector prediction is derived from reference picture list 1.
2303 pub collocated_from_l0_flag: bool,
2304 /// Specifies the reference index of the collocated picture used for
2305 /// temporal motion vector prediction.
2306 pub collocated_ref_idx: u8,
2307 /// The PredWeightTable data.
2308 pub pred_weight_table: PredWeightTable,
2309 /// Specifies the maximum number of merging motion vector prediction (MVP)
2310 /// candidates supported in the slice subtracted from 5.
2311 pub five_minus_max_num_merge_cand: u8,
2312 /// Specifies that the resolution of motion vectors for inter prediction in
2313 /// the current slice is integer. When not set, specifies
2314 /// that the resolution of motion vectors for inter prediction in the
2315 /// current slice that refer to pictures other than the current picture is
2316 /// fractional with quarter-sample precision in units of luma samples.
2317 pub use_integer_mv_flag: bool,
2318 /// Specifies the initial value of QpY to be used for the coding blocks in
2319 /// the slice until modified by the value of CuQpDeltaVal in the coding unit
2320 /// layer.
2321 pub qp_delta: i8,
2322 /// Specifies a difference to be added to the value of pps_cb_qp_offset when
2323 /// determining the value of the Qp′Cb quantization parameter.
2324 pub cb_qp_offset: i8,
2325 /// Specifies a difference to be added to the value of pps_cb_qr_offset when
2326 /// determining the value of the Qp′Cr quantization parameter.
2327 pub cr_qp_offset: i8,
2328 /// Specifies offsets to the quantization parameter values qP derived in
2329 /// clause 8.6.2 for luma, Cb, and Cr components, respectively.
2330 pub slice_act_y_qp_offset: i8,
2331 /// Specifies offsets to the quantization parameter values qP derived in
2332 /// clause 8.6.2 for luma, Cb, and Cr components, respectively.
2333 pub slice_act_cb_qp_offset: i8,
2334 /// Specifies offsets to the quantization parameter values qP derived in
2335 /// clause 8.6.2 for luma, Cb, and Cr components, respectively.
2336 pub slice_act_cr_qp_offset: i8,
2337 /// When set, specifies that the cu_chroma_qp_offset_flag may be present in
2338 /// the transform unit syntax. When not set, specifies that the
2339 /// cu_chroma_qp_offset_flag is not present in the transform unit syntax.
2340 pub cu_chroma_qp_offset_enabled_flag: bool,
2341 /// When set, specifies that deblocking parameters are present in the slice
2342 /// header. When not set, specifies that deblocking parameters are not
2343 /// present in the slice header.
2344 pub deblocking_filter_override_flag: bool,
2345 /// When set, specifies that the operation of the deblocking filter is not
2346 /// applied for the current slice. When not set, specifies that the
2347 /// operation of the deblocking filter is applied for the current slice.
2348 pub deblocking_filter_disabled_flag: bool,
2349 /// Specifies the deblocking parameter offsets for β and tC (divided by 2)
2350 /// for the current slice.
2351 pub beta_offset_div2: i8,
2352 /// Specifies the deblocking parameter offsets for β and tC (divided by 2)
2353 /// for the current slice.
2354 pub tc_offset_div2: i8,
2355 /// When set, specifies that in-loop filtering operations may be performed
2356 /// across the left and upper boundaries of the current slice. When not
2357 /// set, specifies that in-loop operations are not performed across left and
2358 /// upper boundaries of the current slice. The in-loop filtering operations
2359 /// include the deblocking filter and sample adaptive offset filter.
2360 pub loop_filter_across_slices_enabled_flag: bool,
2361 /// Specifies the number of `entry_point_offset_minus1[ i ]` syntax elements
2362 /// in the slice header.
2363 pub num_entry_point_offsets: u32,
2364 /// offset_len_minus1 plus 1 specifies the length, in bits, of the
2365 /// `entry_point_offset_minus1[ i ]` syntax elements.
2366 pub offset_len_minus1: u8,
2367 /// `entry_point_offset_minus1[ i ]` plus 1 specifies the i-th entry point
2368 /// offset in bytes, and is represented by offset_len_minus1 plus 1 bits.
2369 /// The slice segment data that follow the slice segment header consists of
2370 /// num_entry_point_offsets + 1 subsets, with subset index values ranging
2371 /// from 0 to num_entry_point_offsets, inclusive. See the specification for
2372 /// more details.
2373 ///
2374 /// Sized by the stream, not by a guess: §7.4.7.1 bounds
2375 /// `num_entry_point_offsets` by the picture's CTB grid, so a conformant
2376 /// 2160p WPP stream writes up to PicHeightInCtbsY - 1 == 33 of these and a
2377 /// tiled one many more. A fixed `[u32; 32]` here panicked on the 34th.
2378 pub entry_point_offset_minus1: Vec<u32>,
2379 /// Same as NumPicTotalCurr in the specification.
2380 pub num_pic_total_curr: u32,
2381 // Size of slice_header() in bits.
2382 pub header_bit_size: u32,
2383 // Number of emulation prevention bytes (EPB) in this slice_header().
2384 pub n_emulation_prevention_bytes: u32,
2385 /// Same as CurrRpsIdx in the specification.
2386 pub curr_rps_idx: u8,
2387 /// Number of bits taken by st_ref_pic_set minus Emulation Prevention Bytes.
2388 pub st_rps_bits: u32,
2389}
2390
2391impl Default for SliceHeader {
2392 fn default() -> Self {
2393 Self {
2394 first_slice_segment_in_pic_flag: Default::default(),
2395 no_output_of_prior_pics_flag: Default::default(),
2396 pic_parameter_set_id: Default::default(),
2397 dependent_slice_segment_flag: Default::default(),
2398 segment_address: Default::default(),
2399 type_: Default::default(),
2400 pic_output_flag: true,
2401 colour_plane_id: Default::default(),
2402 pic_order_cnt_lsb: Default::default(),
2403 short_term_ref_pic_set_sps_flag: Default::default(),
2404 short_term_ref_pic_set: Default::default(),
2405 short_term_ref_pic_set_idx: Default::default(),
2406 num_long_term_sps: Default::default(),
2407 num_long_term_pics: Default::default(),
2408 lt_idx_sps: Default::default(),
2409 poc_lsb_lt: Default::default(),
2410 used_by_curr_pic_lt: Default::default(),
2411 delta_poc_msb_present_flag: Default::default(),
2412 delta_poc_msb_cycle_lt: Default::default(),
2413 temporal_mvp_enabled_flag: Default::default(),
2414 sao_luma_flag: Default::default(),
2415 sao_chroma_flag: Default::default(),
2416 num_ref_idx_active_override_flag: Default::default(),
2417 num_ref_idx_l0_active_minus1: Default::default(),
2418 num_ref_idx_l1_active_minus1: Default::default(),
2419 ref_pic_list_modification: Default::default(),
2420 mvd_l1_zero_flag: Default::default(),
2421 cabac_init_flag: Default::default(),
2422 collocated_from_l0_flag: true,
2423 collocated_ref_idx: Default::default(),
2424 pred_weight_table: Default::default(),
2425 five_minus_max_num_merge_cand: Default::default(),
2426 use_integer_mv_flag: Default::default(),
2427 qp_delta: Default::default(),
2428 cb_qp_offset: Default::default(),
2429 cr_qp_offset: Default::default(),
2430 slice_act_y_qp_offset: Default::default(),
2431 slice_act_cb_qp_offset: Default::default(),
2432 slice_act_cr_qp_offset: Default::default(),
2433 cu_chroma_qp_offset_enabled_flag: Default::default(),
2434 deblocking_filter_override_flag: Default::default(),
2435 deblocking_filter_disabled_flag: Default::default(),
2436 beta_offset_div2: Default::default(),
2437 tc_offset_div2: Default::default(),
2438 loop_filter_across_slices_enabled_flag: Default::default(),
2439 num_entry_point_offsets: Default::default(),
2440 offset_len_minus1: Default::default(),
2441 entry_point_offset_minus1: Default::default(),
2442 num_pic_total_curr: Default::default(),
2443 header_bit_size: Default::default(),
2444 n_emulation_prevention_bytes: Default::default(),
2445 curr_rps_idx: Default::default(),
2446 st_rps_bits: Default::default(),
2447 }
2448 }
2449}
2450
2451/// A H265 slice. An integer number of macroblocks or macroblock pairs ordered
2452/// consecutively in the raster scan within a particular slice group
2453pub struct Slice<'a> {
2454 /// The slice header.
2455 pub header: SliceHeader,
2456 /// The NAL unit backing this slice.
2457 pub nalu: Nalu<'a>,
2458}
2459
2460impl<'a> Slice<'a> {
2461 /// Sets the header for dependent slices by copying from an independent
2462 /// slice.
2463 pub fn replace_header(&mut self, header: SliceHeader) -> Result<(), String> {
2464 if !self.header.dependent_slice_segment_flag {
2465 Err("Replacing the slice header is only possible for dependent slices".into())
2466 } else {
2467 let first_slice_segment_in_pic_flag = self.header.first_slice_segment_in_pic_flag;
2468 let no_output_of_prior_pics_flag = self.header.no_output_of_prior_pics_flag;
2469 let pic_parameter_set_id = self.header.pic_parameter_set_id;
2470 let dependent_slice_segment_flag = self.header.dependent_slice_segment_flag;
2471 let segment_address = self.header.segment_address;
2472
2473 let offset_len_minus1 = self.header.offset_len_minus1;
2474 let entry_point_offset_minus1 =
2475 std::mem::take(&mut self.header.entry_point_offset_minus1);
2476 let num_pic_total_curr = self.header.num_pic_total_curr;
2477 let header_bit_size = self.header.header_bit_size;
2478 let n_emulation_prevention_bytes = self.header.n_emulation_prevention_bytes;
2479 let curr_rps_idx = self.header.curr_rps_idx;
2480 let st_rps_bits = self.header.st_rps_bits;
2481
2482 self.header = header;
2483
2484 self.header.first_slice_segment_in_pic_flag = first_slice_segment_in_pic_flag;
2485 self.header.no_output_of_prior_pics_flag = no_output_of_prior_pics_flag;
2486 self.header.pic_parameter_set_id = pic_parameter_set_id;
2487 self.header.dependent_slice_segment_flag = dependent_slice_segment_flag;
2488 self.header.segment_address = segment_address;
2489 self.header.offset_len_minus1 = offset_len_minus1;
2490 self.header.entry_point_offset_minus1 = entry_point_offset_minus1;
2491 self.header.num_pic_total_curr = num_pic_total_curr;
2492 self.header.header_bit_size = header_bit_size;
2493 self.header.n_emulation_prevention_bytes = n_emulation_prevention_bytes;
2494 self.header.curr_rps_idx = curr_rps_idx;
2495 self.header.st_rps_bits = st_rps_bits;
2496
2497 Ok(())
2498 }
2499 }
2500}
2501
2502#[derive(Clone, Debug, Default, PartialEq, Eq)]
2503pub struct SublayerHrdParameters {
2504 // NOTE: The value of CpbCnt is cpb_cnt_minus1[i] + 1, and cpb_cnt_minus1
2505 // ranges from 0..=31
2506 /// `bit_rate_value_minus1[ i ]` (together with bit_rate_scale) specifies the
2507 /// maximum input bit rate for the i-th CPB when the CPB operates at the
2508 /// access unit level
2509 pub bit_rate_value_minus1: [u32; 32],
2510 /// `cpb_size_value_minus1[ i ]` is used together with cpb_size_scale to
2511 /// specify the i-th CPB size when the CPB operates at the access unit
2512 /// level.
2513 pub cpb_size_value_minus1: [u32; 32],
2514 /// `cpb_size_du_value_minus1[ i ]` is used together with cpb_size_du_scale to
2515 /// specify the i-th CPB size when the CPB operates at sub-picture level.
2516 pub cpb_size_du_value_minus1: [u32; 32],
2517 /// `bit_rate_du_value_minus1[ i ]` (together with bit_rate_scale) specifies
2518 /// the maximum input bit rate for the i-th CPB when the CPB operates at the
2519 /// sub-picture level.
2520 pub bit_rate_du_value_minus1: [u32; 32],
2521 /// `cbr_flag[ i ]` not set specifies that to decode this CVS by the HRD using
2522 /// the i-th CPB specification.
2523 pub cbr_flag: [bool; 32],
2524}
2525
2526#[derive(Clone, Debug, PartialEq, Eq)]
2527pub struct HrdParams {
2528 /// When set, specifies that NAL HRD parameters (pertaining to the Type II
2529 /// bitstream conformance point) are present in the hrd_parameters( ) syntax
2530 /// structure. When not set, specifies that NAL HRD parameters are not
2531 /// present in the hrd_parameters( ) syntax structure.
2532 pub nal_hrd_parameters_present_flag: bool,
2533 /// When set, specifies that VCL HRD parameters (pertaining to the Type I
2534 /// bitstream conformance point) are present in the hrd_parameters( ) syntax
2535 /// structure. When not set, specifies that VCL HRD parameters are not
2536 /// present in the hrd_parameters( ) syntax structure.
2537 pub vcl_hrd_parameters_present_flag: bool,
2538 /// When set, specifies that sub-picture level HRD parameters are present
2539 /// and the HRD may operate at access unit level or sub-picture level. When
2540 /// not set, specifies that sub-picture level HRD parameters are not present
2541 /// and the HRD operates at access unit level.
2542 pub sub_pic_hrd_params_present_flag: bool,
2543 /// Used to specify the clock sub-tick. A clock sub-tick is the minimum
2544 /// interval of time that can be represented in the coded data when
2545 /// sub_pic_hrd_params_present_flag is set.
2546 pub tick_divisor_minus2: u8,
2547 /// du_cpb_removal_delay_increment_length_minus1 plus 1 specifies the
2548 /// length, in bits, of the `du_cpb_removal_delay_increment_minus1[ i ]` and
2549 /// du_common_cpb_removal_delay_increment_minus1 syntax elements of the
2550 /// picture timing SEI message and the du_spt_cpb_removal_delay_increment
2551 /// syntax element in the decoding unit information SEI message.
2552 pub du_cpb_removal_delay_increment_length_minus1: u8,
2553 /// When set, specifies that sub-picture level CPB removal delay parameters
2554 /// are present in picture timing SEI messages and no decoding unit
2555 /// information SEI message is available (in the CVS or provided through
2556 /// external means not specified in this Specification). When not set,
2557 /// specifies that sub-picture level CPB removal delay parameters are
2558 /// present in decoding unit information SEI messages and picture timing SEI
2559 /// messages do not include sub-picture level CPB removal delay parameters.
2560 pub sub_pic_cpb_params_in_pic_timing_sei_flag: bool,
2561 /// dpb_output_delay_du_length_minus1 plus 1 specifies the length, in bits,
2562 /// of the pic_dpb_output_du_delay syntax element in the picture timing SEI
2563 /// message and the pic_spt_dpb_output_du_delay syntax element in the
2564 /// decoding unit information SEI message.
2565 pub dpb_output_delay_du_length_minus1: u8,
2566 /// Together with `bit_rate_value_minus1[ i ]`, specifies the maximum input
2567 /// bit rate of the i-th CPB.
2568 pub bit_rate_scale: u8,
2569 /// Together with `cpb_size_du_value_minus1[ i ]`, specifies the CPB size of
2570 /// the i-th CPB when the CPB operates at sub-picture level.
2571 pub cpb_size_scale: u8,
2572 /// Together with `cpb_size_du_value_minus1[ i ]`, specifies the CPB size of
2573 /// the i-th CPB when the CPB operates at sub-picture level.
2574 pub cpb_size_du_scale: u8,
2575 /// initial_cpb_removal_delay_length_minus1 plus 1 specifies the length, in
2576 /// bits, of the `nal_initial_cpb_removal_delay[ i ]`,
2577 /// `nal_initial_cpb_removal_offset[ i ]`, `vcl_initial_cpb_removal_delay[ i ]`
2578 /// and `vcl_initial_cpb_removal_offset[ i ]` syntax elements of the buffering
2579 /// period SEI message.
2580 pub initial_cpb_removal_delay_length_minus1: u8,
2581 /// au_cpb_removal_delay_length_minus1 plus 1 specifies the length, in bits,
2582 /// of the cpb_delay_offset syntax element in the buffering period SEI
2583 /// message and the au_cpb_removal_delay_minus1 syntax element in the
2584 /// picture timing SEI message.
2585 pub au_cpb_removal_delay_length_minus1: u8,
2586 /// dpb_output_delay_length_minus1 plus 1 specifies the length, in bits, of
2587 /// the dpb_delay_offset syntax element in the buffering period SEI message
2588 /// and the pic_dpb_output_delay syntax element in the picture timing SEI
2589 /// message.
2590 pub dpb_output_delay_length_minus1: u8,
2591 /// `fixed_pic_rate_general_flag[ i ]` set indicates that, when HighestTid is
2592 /// equal to i, the temporal distance between the HRD output times of
2593 /// consecutive pictures in output order is constrained as specified in the
2594 /// specification. `fixed_pic_rate_general_flag[ i ]` not set indicates that
2595 /// this constraint may not apply.
2596 pub fixed_pic_rate_general_flag: [bool; 7],
2597 /// `fixed_pic_rate_within_cvs_flag[ i ]` set indicates that, when HighestTid
2598 /// is equal to i, the temporal distance between the HRD output times of
2599 /// consecutive pictures in output order is constrained as specified in the
2600 /// specification. `fixed_pic_rate_within_cvs_flag[ i ]` not set indicates
2601 /// that this constraint may not apply.
2602 pub fixed_pic_rate_within_cvs_flag: [bool; 7],
2603 /// `elemental_duration_in_tc_minus1[ i ]` plus 1 (when present) specifies,
2604 /// when HighestTid is equal to i, the temporal distance, in clock ticks,
2605 /// between the elemental units that specify the HRD output times of
2606 /// consecutive pictures in output order as specified in the specification.
2607 pub elemental_duration_in_tc_minus1: [u32; 7],
2608 /// `low_delay_hrd_flag[ i ]` specifies the HRD operational mode, when
2609 /// HighestTid is equal to i, as specified in Annex C or clause F.13.
2610 pub low_delay_hrd_flag: [bool; 7],
2611 /// `cpb_cnt_minus1[ i ]` plus 1 specifies the number of alternative CPB
2612 /// specifications in the bitstream of the CVS when HighestTid is equal to
2613 /// i.
2614 pub cpb_cnt_minus1: [u32; 7],
2615 /// The NAL HRD data.
2616 pub nal_hrd: [SublayerHrdParameters; 7],
2617 /// The VCL HRD data.
2618 pub vcl_hrd: [SublayerHrdParameters; 7],
2619}
2620
2621impl Default for HrdParams {
2622 fn default() -> Self {
2623 Self {
2624 initial_cpb_removal_delay_length_minus1: 23,
2625 au_cpb_removal_delay_length_minus1: 23,
2626 dpb_output_delay_du_length_minus1: 23,
2627 nal_hrd_parameters_present_flag: Default::default(),
2628 vcl_hrd_parameters_present_flag: Default::default(),
2629 sub_pic_hrd_params_present_flag: Default::default(),
2630 tick_divisor_minus2: Default::default(),
2631 du_cpb_removal_delay_increment_length_minus1: Default::default(),
2632 sub_pic_cpb_params_in_pic_timing_sei_flag: Default::default(),
2633 bit_rate_scale: Default::default(),
2634 cpb_size_scale: Default::default(),
2635 cpb_size_du_scale: Default::default(),
2636 dpb_output_delay_length_minus1: Default::default(),
2637 fixed_pic_rate_general_flag: Default::default(),
2638 fixed_pic_rate_within_cvs_flag: Default::default(),
2639 elemental_duration_in_tc_minus1: Default::default(),
2640 low_delay_hrd_flag: Default::default(),
2641 cpb_cnt_minus1: Default::default(),
2642 nal_hrd: Default::default(),
2643 vcl_hrd: Default::default(),
2644 }
2645 }
2646}
2647
2648#[derive(Clone, Debug, PartialEq, Eq)]
2649pub struct VuiParams {
2650 /// When set, specifies that aspect_ratio_idc is present. When not set,
2651 /// specifies that aspect_ratio_idc is not present.
2652 pub aspect_ratio_info_present_flag: bool,
2653 /// Specifies the value of the sample aspect ratio of the luma samples.
2654 pub aspect_ratio_idc: u32,
2655 /// Indicates the horizontal size of the sample aspect ratio (in arbitrary
2656 /// units).
2657 pub sar_width: u32,
2658 /// Indicates the vertical size of the sample aspect ratio (in arbitrary
2659 /// units).
2660 pub sar_height: u32,
2661 /// When set, specifies that the overscan_appropriate_flag is present. When
2662 /// not set, the preferred display method for the video signal is
2663 /// unspecified.
2664 pub overscan_info_present_flag: bool,
2665 /// When set indicates that the cropped decoded pictures output are suitable
2666 /// for display using overscan. When not set, indicates that the cropped
2667 /// decoded pictures output contain visually important information in the
2668 /// entire region out to the edges of the conformance cropping window of the
2669 /// picture, such that the cropped decoded pictures output should not be
2670 /// displayed using overscan.
2671 pub overscan_appropriate_flag: bool,
2672 /// When set, specifies that video_format, video_full_range_flag and
2673 /// colour_description_present_flag are present. When not set, specify that
2674 /// video_format, video_full_range_flag and colour_description_present_flag
2675 /// are not present.
2676 pub video_signal_type_present_flag: bool,
2677 /// Indicates the representation of the pictures as specified in Table E.2,
2678 /// before being coded in accordance with this Specification.
2679 pub video_format: u8,
2680 /// Indicates the black level and range of the luma and chroma signals as
2681 /// derived from E′Y, E′PB, and E′PR or E′R, E′G, and E′B real-valued
2682 /// component signals.
2683 pub video_full_range_flag: bool,
2684 /// When set, specifies that colour_primaries, transfer_characteristics, and
2685 /// matrix_coeffs are present. When not set, specifies that
2686 /// colour_primaries, transfer_characteristics, and matrix_coeffs are not
2687 /// present.
2688 pub colour_description_present_flag: bool,
2689 /// Indicates the chromaticity coordinates of the source primaries as
2690 /// specified in Table E.3 in terms of the CIE 1931 definition of x and y as
2691 /// specified in ISO 11664-1.
2692 pub colour_primaries: u32,
2693 /// See table E.4 in the specification.
2694 pub transfer_characteristics: u32,
2695 /// Describes the matrix coefficients used in deriving luma and chroma
2696 /// signals from the green, blue, and red, or Y, Z, and X primaries, as
2697 /// specified in Table E.5.
2698 pub matrix_coeffs: u32,
2699 /// When true, specifies that chroma_sample_loc_type_top_field and
2700 /// chroma_sample_loc_type_bottom_field are present. When false, specifies
2701 /// that chroma_sample_loc_type_top_field and
2702 /// chroma_sample_loc_type_bottom_field are not present.
2703 pub chroma_loc_info_present_flag: bool,
2704 /// See the specification for more details.
2705 pub chroma_sample_loc_type_top_field: u32,
2706 /// See the specification for more details.
2707 pub chroma_sample_loc_type_bottom_field: u32,
2708 /// When true, indicates that the value of all decoded chroma samples is
2709 /// equal to 1 << ( BitDepthC − 1 ). When false, provides no indication of
2710 /// decoded chroma sample values.
2711 pub neutral_chroma_indication_flag: bool,
2712 /// When true, indicates that the CVS conveys pictures that represent
2713 /// fields, and specifies that a picture timing SEI message shall be present
2714 /// in every access unit of the current CVS. When false, indicates that the
2715 /// CVS conveys pictures that represent frames and that a picture timing SEI
2716 /// message may or may not be present in any access unit of the current CVS.
2717 pub field_seq_flag: bool,
2718 /// When true, specifies that picture timing SEI messages are present for
2719 /// every picture and include the pic_struct, source_scan_type and
2720 /// duplicate_flag syntax elements. When false, specifies that the
2721 /// pic_struct syntax element is not present in picture timing SEI messages.
2722 pub frame_field_info_present_flag: bool,
2723 /// When true, indicates that the default display window parameters follow
2724 /// next in the VUI. When false, indicates that the default display window
2725 /// parameters are not present.
2726 pub default_display_window_flag: bool,
2727 /// Specifies the samples of the pictures in the CVS that are within the
2728 /// default display window, in terms of a rectangular region specified in
2729 /// picture coordinates for display.
2730 pub def_disp_win_left_offset: u32,
2731 /// Specifies the samples of the pictures in the CVS that are within the
2732 /// default display window, in terms of a rectangular region specified in
2733 /// picture coordinates for display.
2734 pub def_disp_win_right_offset: u32,
2735 /// Specifies the samples of the pictures in the CVS that are within the
2736 /// default display window, in terms of a rectangular region specified in
2737 /// picture coordinates for display.
2738 pub def_disp_win_top_offset: u32,
2739 /// Specifies the samples of the pictures in the CVS that are within the
2740 /// default display window, in terms of a rectangular region specified in
2741 /// picture coordinates for display.
2742 pub def_disp_win_bottom_offset: u32,
2743 /// When set, specifies that vui_num_units_in_tick, vui_time_scale,
2744 /// vui_poc_proportional_to_timing_flag and vui_hrd_parameters_present_flag
2745 /// are present in the vui_parameters( ) syntax structure. When not set,
2746 /// specifies that vui_num_units_in_tick, vui_time_scale,
2747 /// vui_poc_proportional_to_timing_flag and vui_hrd_parameters_present_flag
2748 /// are not present in the vui_parameters( ) syntax structure
2749 pub timing_info_present_flag: bool,
2750 /// The number of time units of a clock operating at the frequency
2751 /// vui_time_scale Hz that corresponds to one increment (called a clock
2752 /// tick) of a clock tick counter.
2753 pub num_units_in_tick: u32,
2754 /// Is the number of time units that pass in one second. For example, a time
2755 /// coordinate system that measures time using a 27 MHz clock has a
2756 /// vui_time_scale of 27 000 000.
2757 pub time_scale: u32,
2758 /// When set, indicates that the picture order count value for each picture
2759 /// in the CVS that is not the first picture in the CVS, in decoding order,
2760 /// is proportional to the output time of the picture relative to the output
2761 /// time of the first picture in the CVS. When not set, indicates that the
2762 /// picture order count value for each picture in the CVS that is not the
2763 /// first picture in the CVS, in decoding order, may or may not be
2764 /// proportional to the output time of the picture relative to the output
2765 /// time of the first picture in the CVS.
2766 pub poc_proportional_to_timing_flag: bool,
2767 /// vui_num_ticks_poc_diff_one_minus1 plus 1 specifies the number of clock
2768 /// ticks corresponding to a difference of picture order count values equal
2769 /// to 1.
2770 pub num_ticks_poc_diff_one_minus1: u32,
2771 /// When set, specifies that the syntax structure hrd_parameters( ) is
2772 /// present in the vui_parameters( ) syntax structure. When not set,
2773 /// specifies that the syntax structure hrd_parameters( ) is not present in
2774 /// the vui_parameters( ) syntax structure.
2775 pub hrd_parameters_present_flag: bool,
2776 /// The hrd_parameters() data.
2777 pub hrd: HrdParams,
2778 /// When set, specifies that the bitstream restriction parameters for the
2779 /// CVS are present. When not set, specifies that the bitstream restriction
2780 /// parameters for the CVS are not present.
2781 pub bitstream_restriction_flag: bool,
2782 /// When set, indicates that each PPS that is active in the CVS has the same
2783 /// value of the syntax elements num_tile_columns_minus1,
2784 /// num_tile_rows_minus1, uniform_spacing_flag, `column_width_minus1[ i ]`,
2785 /// `row_height_minus1[ i ]` and loop_filter_across_tiles_enabled_flag, when
2786 /// present. When not set, indicates that tiles syntax elements in different
2787 /// PPSs may or may not have the same value
2788 pub tiles_fixed_structure_flag: bool,
2789 /// When not set, indicates that no sample outside the picture boundaries
2790 /// and no sample at a fractional sample position for which the sample value
2791 /// is derived using one or more samples outside the picture boundaries is
2792 /// used for inter prediction of any sample. When set, indicates that one
2793 /// or more samples outside the picture boundaries may be used in inter
2794 /// prediction.
2795 pub motion_vectors_over_pic_boundaries_flag: bool,
2796 /// When set, indicates that all P and B slices (when present) that belong
2797 /// to the same picture have an identical reference picture list 0 and that
2798 /// all B slices (when present) that belong to the same picture have an
2799 /// identical reference picture list 1.
2800 pub restricted_ref_pic_lists_flag: bool,
2801 /// When not equal to 0, establishes a bound on the maximum possible size of
2802 /// distinct coded spatial segmentation regions in the pictures of the CVS.
2803 pub min_spatial_segmentation_idc: u32,
2804 /// Indicates a number of bytes not exceeded by the sum of the sizes of the
2805 /// VCL NAL units associated with any coded picture in the CVS.
2806 pub max_bytes_per_pic_denom: u32,
2807 /// Indicates an upper bound for the number of coded bits of coding_unit( )
2808 /// data for anycoding block in any picture of the CVS.
2809 pub max_bits_per_min_cu_denom: u32,
2810 /// Indicate the maximum absolute value of a decoded horizontal and vertical
2811 /// motion vector component, respectively, in quarter luma sample units, for
2812 /// all pictures in the CVS.
2813 pub log2_max_mv_length_horizontal: u32,
2814 /// Indicate the maximum absolute value of a decoded horizontal and vertical
2815 /// motion vector component, respectively, in quarter luma sample units, for
2816 /// all pictures in the CVS.
2817 pub log2_max_mv_length_vertical: u32,
2818}
2819
2820impl Default for VuiParams {
2821 fn default() -> Self {
2822 Self {
2823 aspect_ratio_info_present_flag: Default::default(),
2824 aspect_ratio_idc: Default::default(),
2825 sar_width: Default::default(),
2826 sar_height: Default::default(),
2827 overscan_info_present_flag: Default::default(),
2828 overscan_appropriate_flag: Default::default(),
2829 video_signal_type_present_flag: Default::default(),
2830 video_format: 5,
2831 video_full_range_flag: Default::default(),
2832 colour_description_present_flag: Default::default(),
2833 colour_primaries: 2,
2834 transfer_characteristics: 2,
2835 matrix_coeffs: 2,
2836 chroma_loc_info_present_flag: Default::default(),
2837 chroma_sample_loc_type_top_field: Default::default(),
2838 chroma_sample_loc_type_bottom_field: Default::default(),
2839 neutral_chroma_indication_flag: Default::default(),
2840 field_seq_flag: Default::default(),
2841 frame_field_info_present_flag: Default::default(),
2842 default_display_window_flag: Default::default(),
2843 def_disp_win_left_offset: Default::default(),
2844 def_disp_win_right_offset: Default::default(),
2845 def_disp_win_top_offset: Default::default(),
2846 def_disp_win_bottom_offset: Default::default(),
2847 timing_info_present_flag: Default::default(),
2848 num_units_in_tick: Default::default(),
2849 time_scale: Default::default(),
2850 poc_proportional_to_timing_flag: Default::default(),
2851 num_ticks_poc_diff_one_minus1: Default::default(),
2852 hrd_parameters_present_flag: Default::default(),
2853 hrd: Default::default(),
2854 bitstream_restriction_flag: Default::default(),
2855 tiles_fixed_structure_flag: Default::default(),
2856 motion_vectors_over_pic_boundaries_flag: true,
2857 restricted_ref_pic_lists_flag: Default::default(),
2858 min_spatial_segmentation_idc: Default::default(),
2859 max_bytes_per_pic_denom: 2,
2860 max_bits_per_min_cu_denom: 1,
2861 log2_max_mv_length_horizontal: 15,
2862 log2_max_mv_length_vertical: 15,
2863 }
2864 }
2865}
2866
2867#[derive(Clone, Debug, Default)]
2868pub struct Parser {
2869 active_vpses: BTreeMap<u8, Rc<Vps>>,
2870 active_spses: BTreeMap<u8, Rc<Sps>>,
2871 active_ppses: BTreeMap<u8, Rc<Pps>>,
2872}
2873
2874impl Parser {
2875 /// Parse a VPS NALU.
2876 pub fn parse_vps(&mut self, nalu: &Nalu) -> Result<&Vps, String> {
2877 if !matches!(nalu.header.type_, NaluType::VpsNut) {
2878 return Err(format!(
2879 "Invalid NALU type, expected {:?}, got {:?}",
2880 NaluType::VpsNut,
2881 nalu.header.type_
2882 ));
2883 }
2884
2885 let data = nalu.as_ref();
2886 let header = &nalu.header;
2887 let hdr_len = header.len();
2888 // Skip the header
2889 let mut r = BitReader::new(&data[hdr_len..], true);
2890
2891 let mut vps = Vps {
2892 video_parameter_set_id: r.read_bits(4)?,
2893 base_layer_internal_flag: r.read_bit()?,
2894 base_layer_available_flag: r.read_bit()?,
2895 max_layers_minus1: r.read_bits(6)?,
2896 max_sub_layers_minus1: r.read_bits(3)?,
2897 temporal_id_nesting_flag: r.read_bit()?,
2898 ..Default::default()
2899 };
2900
2901 r.skip_bits(16)?; // vps_reserved_0xffff_16bits
2902
2903 // §7.4.3.1: 0..6. The three bits can say 7, and every sub-layer array
2904 // below is 7 long -- refuse rather than index one out of bounds.
2905 if vps.max_sub_layers_minus1 > 6 {
2906 return Err(format!(
2907 "Invalid vps_max_sub_layers_minus1 {}",
2908 vps.max_sub_layers_minus1
2909 ));
2910 }
2911
2912 let ptl = &mut vps.profile_tier_level;
2913 Self::parse_profile_tier_level(ptl, &mut r, true, vps.max_sub_layers_minus1)?;
2914
2915 vps.sub_layer_ordering_info_present_flag = r.read_bit()?;
2916
2917 let start =
2918 if vps.sub_layer_ordering_info_present_flag { 0 } else { vps.max_sub_layers_minus1 }
2919 as usize;
2920
2921 for i in start..=usize::from(vps.max_sub_layers_minus1) {
2922 vps.max_dec_pic_buffering_minus1[i] = r.read_ue_max(15)?;
2923 vps.max_num_reorder_pics[i] = r.read_ue_max(vps.max_dec_pic_buffering_minus1[i])?;
2924 vps.max_latency_increase_plus1[i] = r.read_ue()?;
2925
2926 if i > 0 {
2927 if vps.max_dec_pic_buffering_minus1[i] < vps.max_dec_pic_buffering_minus1[i - 1] {
2928 return Err(format!(
2929 "Invalid max_dec_pic_buffering_minus1[{}]: {}",
2930 i, vps.max_dec_pic_buffering_minus1[i]
2931 ));
2932 }
2933
2934 if vps.max_num_reorder_pics[i] < vps.max_num_reorder_pics[i - 1] {
2935 return Err(format!(
2936 "Invalid max_num_reorder_pics[{}]: {}",
2937 i, vps.max_num_reorder_pics[i]
2938 ));
2939 }
2940 }
2941 }
2942
2943 // vps_sub_layer_ordering_info_present_flag equal to 0 specifies that
2944 // the values of vps_max_dec_pic_buffering_minus1[
2945 // vps_max_sub_layers_minus1 ], vps_max_num_reorder_pics[ vps_max_sub_
2946 // layers_minus1 ] and vps_max_latency_increase_plus1[
2947 // vps_max_sub_layers_minus1 ] apply to all sub-layers
2948 if !vps.sub_layer_ordering_info_present_flag {
2949 let max_num_sublayers = usize::from(vps.max_sub_layers_minus1);
2950 for i in 0..max_num_sublayers {
2951 vps.max_dec_pic_buffering_minus1[i] =
2952 vps.max_dec_pic_buffering_minus1[max_num_sublayers];
2953
2954 vps.max_num_reorder_pics[i] = vps.max_num_reorder_pics[max_num_sublayers];
2955
2956 vps.max_latency_increase_plus1[i] =
2957 vps.max_latency_increase_plus1[max_num_sublayers];
2958 }
2959 }
2960
2961 vps.max_layer_id = r.read_bits(6)?;
2962 if vps.max_layer_id > 62 {
2963 return Err(format!("Invalid max_layer_id {}", vps.max_layer_id));
2964 }
2965
2966 vps.num_layer_sets_minus1 = r.read_ue_max(1023)?;
2967
2968 for _ in 1..=vps.num_layer_sets_minus1 {
2969 for _ in 0..=vps.max_layer_id {
2970 // Skip layer_id_included_flag[i][j] for now.
2971 r.skip_bits(1)?;
2972 }
2973 }
2974
2975 vps.timing_info_present_flag = r.read_bit()?;
2976
2977 if vps.timing_info_present_flag {
2978 vps.num_units_in_tick = r.read_bits::<u32>(31)? << 1;
2979 vps.num_units_in_tick |= r.read_bits::<u32>(1)?;
2980
2981 vps.time_scale = r.read_bits::<u32>(31)? << 1;
2982 vps.time_scale |= r.read_bits::<u32>(1)?;
2983
2984 vps.poc_proportional_to_timing_flag = r.read_bit()?;
2985 if vps.poc_proportional_to_timing_flag {
2986 vps.num_ticks_poc_diff_one_minus1 = r.read_ue()?;
2987 }
2988
2989 vps.num_hrd_parameters = r.read_ue()?;
2990
2991 for i in 0..vps.num_hrd_parameters as usize {
2992 vps.hrd_layer_set_idx.push(r.read_ue()?);
2993 if i > 0 {
2994 vps.cprms_present_flag.push(r.read_bit()?);
2995 }
2996
2997 let mut hrd = HrdParams::default();
2998 Self::parse_hrd_parameters(
2999 vps.cprms_present_flag[i],
3000 vps.max_sub_layers_minus1,
3001 &mut hrd,
3002 &mut r,
3003 )?;
3004
3005 vps.hrd_parameters.push(hrd);
3006 }
3007 }
3008
3009 vps.extension_flag = r.read_bit()?;
3010
3011 if self.active_vpses.keys().len() >= MAX_VPS_COUNT {
3012 return Err("Broken data: Number of active VPSs > MAX_VPS_COUNT".into());
3013 }
3014
3015 let key = vps.video_parameter_set_id;
3016 let vps = Rc::new(vps);
3017 self.active_vpses.remove(&key);
3018 Ok(self.active_vpses.entry(key).or_insert(vps))
3019 }
3020
3021 fn parse_profile_tier_level(
3022 ptl: &mut ProfileTierLevel,
3023 r: &mut BitReader,
3024 profile_present_flag: bool,
3025 sps_max_sub_layers_minus_1: u8,
3026 ) -> Result<(), String> {
3027 if profile_present_flag {
3028 ptl.general_profile_space = r.read_bits(2)?;
3029 ptl.general_tier_flag = r.read_bit()?;
3030 ptl.general_profile_idc = r.read_bits(5)?;
3031
3032 for i in 0..32 {
3033 ptl.general_profile_compatibility_flag[i] = r.read_bit()?;
3034 }
3035
3036 ptl.general_progressive_source_flag = r.read_bit()?;
3037 ptl.general_interlaced_source_flag = r.read_bit()?;
3038 ptl.general_non_packed_constraint_flag = r.read_bit()?;
3039 ptl.general_frame_only_constraint_flag = r.read_bit()?;
3040
3041 if ptl.general_profile_idc == 4
3042 || ptl.general_profile_compatibility_flag[4]
3043 || ptl.general_profile_idc == 5
3044 || ptl.general_profile_compatibility_flag[5]
3045 || ptl.general_profile_idc == 6
3046 || ptl.general_profile_compatibility_flag[6]
3047 || ptl.general_profile_idc == 7
3048 || ptl.general_profile_compatibility_flag[7]
3049 || ptl.general_profile_idc == 8
3050 || ptl.general_profile_compatibility_flag[8]
3051 || ptl.general_profile_idc == 9
3052 || ptl.general_profile_compatibility_flag[9]
3053 || ptl.general_profile_idc == 10
3054 || ptl.general_profile_compatibility_flag[10]
3055 || ptl.general_profile_idc == 11
3056 || ptl.general_profile_compatibility_flag[11]
3057 {
3058 ptl.general_max_12bit_constraint_flag = r.read_bit()?;
3059 ptl.general_max_10bit_constraint_flag = r.read_bit()?;
3060 ptl.general_max_8bit_constraint_flag = r.read_bit()?;
3061 ptl.general_max_422chroma_constraint_flag = r.read_bit()?;
3062 ptl.general_max_420chroma_constraint_flag = r.read_bit()?;
3063 ptl.general_max_monochrome_constraint_flag = r.read_bit()?;
3064 ptl.general_intra_constraint_flag = r.read_bit()?;
3065 ptl.general_one_picture_only_constraint_flag = r.read_bit()?;
3066 ptl.general_lower_bit_rate_constraint_flag = r.read_bit()?;
3067 if ptl.general_profile_idc == 5
3068 || ptl.general_profile_compatibility_flag[5]
3069 || ptl.general_profile_idc == 9
3070 || ptl.general_profile_compatibility_flag[9]
3071 || ptl.general_profile_idc == 10
3072 || ptl.general_profile_compatibility_flag[10]
3073 || ptl.general_profile_idc == 11
3074 || ptl.general_profile_compatibility_flag[11]
3075 {
3076 ptl.general_max_14bit_constraint_flag = r.read_bit()?;
3077 // Skip general_reserved_zero_33bits
3078 r.skip_bits(31)?;
3079 r.skip_bits(2)?;
3080 } else {
3081 // Skip general_reserved_zero_34bits
3082 r.skip_bits(31)?;
3083 r.skip_bits(3)?;
3084 }
3085 } else if ptl.general_profile_idc == 2 || ptl.general_profile_compatibility_flag[2] {
3086 // Skip general_reserved_zero_7bits
3087 r.skip_bits(7)?;
3088 ptl.general_one_picture_only_constraint_flag = r.read_bit()?;
3089 // Skip general_reserved_zero_35bits
3090 r.skip_bits(31)?;
3091 r.skip_bits(4)?;
3092 } else {
3093 r.skip_bits(31)?;
3094 r.skip_bits(12)?;
3095 }
3096
3097 if ptl.general_profile_idc == 1
3098 || ptl.general_profile_compatibility_flag[1]
3099 || ptl.general_profile_idc == 2
3100 || ptl.general_profile_compatibility_flag[2]
3101 || ptl.general_profile_idc == 3
3102 || ptl.general_profile_compatibility_flag[3]
3103 || ptl.general_profile_idc == 4
3104 || ptl.general_profile_compatibility_flag[4]
3105 || ptl.general_profile_idc == 5
3106 || ptl.general_profile_compatibility_flag[5]
3107 || ptl.general_profile_idc == 9
3108 || ptl.general_profile_compatibility_flag[9]
3109 || ptl.general_profile_idc == 11
3110 || ptl.general_profile_compatibility_flag[11]
3111 {
3112 ptl.general_inbld_flag = r.read_bit()?;
3113 } else {
3114 r.skip_bits(1)?;
3115 }
3116 }
3117
3118 let level: u8 = r.read_bits(8)?;
3119 ptl.general_level_idc = Level::try_from(level)?;
3120
3121 for i in 0..sps_max_sub_layers_minus_1 as usize {
3122 ptl.sub_layer_profile_present_flag[i] = r.read_bit()?;
3123 ptl.sub_layer_level_present_flag[i] = r.read_bit()?;
3124 }
3125
3126 if sps_max_sub_layers_minus_1 > 0 {
3127 for _ in sps_max_sub_layers_minus_1..8 {
3128 r.skip_bits(2)?;
3129 }
3130 }
3131
3132 for i in 0..sps_max_sub_layers_minus_1 as usize {
3133 if ptl.sub_layer_level_present_flag[i] {
3134 ptl.sub_layer_profile_space[i] = r.read_bits(2)?;
3135 ptl.sub_layer_tier_flag[i] = r.read_bit()?;
3136 ptl.sub_layer_profile_idc[i] = r.read_bits(5)?;
3137 for j in 0..32 {
3138 ptl.sub_layer_profile_compatibility_flag[i][j] = r.read_bit()?;
3139 }
3140 ptl.sub_layer_progressive_source_flag[i] = r.read_bit()?;
3141 ptl.sub_layer_interlaced_source_flag[i] = r.read_bit()?;
3142 ptl.sub_layer_non_packed_constraint_flag[i] = r.read_bit()?;
3143 ptl.sub_layer_frame_only_constraint_flag[i] = r.read_bit()?;
3144
3145 if ptl.sub_layer_profile_idc[i] == 4
3146 || ptl.sub_layer_profile_compatibility_flag[i][4]
3147 || ptl.sub_layer_profile_idc[i] == 5
3148 || ptl.sub_layer_profile_compatibility_flag[i][5]
3149 || ptl.sub_layer_profile_idc[i] == 6
3150 || ptl.sub_layer_profile_compatibility_flag[i][6]
3151 || ptl.sub_layer_profile_idc[i] == 7
3152 || ptl.sub_layer_profile_compatibility_flag[i][7]
3153 || ptl.sub_layer_profile_idc[i] == 8
3154 || ptl.sub_layer_profile_compatibility_flag[i][8]
3155 || ptl.sub_layer_profile_idc[i] == 9
3156 || ptl.sub_layer_profile_compatibility_flag[i][9]
3157 || ptl.sub_layer_profile_idc[i] == 10
3158 || ptl.sub_layer_profile_compatibility_flag[i][10]
3159 || ptl.sub_layer_profile_idc[i] == 11
3160 || ptl.sub_layer_profile_compatibility_flag[i][11]
3161 {
3162 ptl.sub_layer_max_12bit_constraint_flag[i] = r.read_bit()?;
3163 ptl.sub_layer_max_10bit_constraint_flag[i] = r.read_bit()?;
3164 ptl.sub_layer_max_8bit_constraint_flag[i] = r.read_bit()?;
3165 ptl.sub_layer_max_422chroma_constraint_flag[i] = r.read_bit()?;
3166 ptl.sub_layer_max_420chroma_constraint_flag[i] = r.read_bit()?;
3167 ptl.sub_layer_max_monochrome_constraint_flag[i] = r.read_bit()?;
3168 ptl.sub_layer_intra_constraint_flag[i] = r.read_bit()?;
3169 ptl.sub_layer_one_picture_only_constraint_flag[i] = r.read_bit()?;
3170 ptl.sub_layer_lower_bit_rate_constraint_flag[i] = r.read_bit()?;
3171
3172 if ptl.sub_layer_profile_idc[i] == 5
3173 || ptl.sub_layer_profile_compatibility_flag[i][5]
3174 || ptl.sub_layer_profile_idc[i] == 9
3175 || ptl.sub_layer_profile_compatibility_flag[i][9]
3176 || ptl.sub_layer_profile_idc[i] == 10
3177 || ptl.sub_layer_profile_compatibility_flag[i][10]
3178 || ptl.sub_layer_profile_idc[i] == 11
3179 || ptl.sub_layer_profile_compatibility_flag[i][11]
3180 {
3181 ptl.sub_layer_max_14bit_constraint_flag[i] = r.read_bit()?;
3182 r.skip_bits(33)?;
3183 } else {
3184 r.skip_bits(34)?;
3185 }
3186 } else if ptl.sub_layer_profile_idc[i] == 2
3187 || ptl.sub_layer_profile_compatibility_flag[i][2]
3188 {
3189 r.skip_bits(7)?;
3190 ptl.sub_layer_one_picture_only_constraint_flag[i] = r.read_bit()?;
3191 r.skip_bits(35)?;
3192 } else {
3193 r.skip_bits(43)?;
3194 }
3195
3196 if ptl.sub_layer_profile_idc[i] == 1
3197 || ptl.sub_layer_profile_compatibility_flag[i][1]
3198 || ptl.sub_layer_profile_idc[i] == 2
3199 || ptl.sub_layer_profile_compatibility_flag[i][2]
3200 || ptl.sub_layer_profile_idc[i] == 3
3201 || ptl.sub_layer_profile_compatibility_flag[i][3]
3202 || ptl.sub_layer_profile_idc[i] == 4
3203 || ptl.sub_layer_profile_compatibility_flag[i][4]
3204 || ptl.sub_layer_profile_idc[i] == 5
3205 || ptl.sub_layer_profile_compatibility_flag[i][5]
3206 || ptl.sub_layer_profile_idc[i] == 9
3207 || ptl.sub_layer_profile_compatibility_flag[i][9]
3208 || ptl.sub_layer_profile_idc[i] == 11
3209 || ptl.sub_layer_profile_compatibility_flag[i][11]
3210 {
3211 ptl.sub_layer_inbld_flag[i] = r.read_bit()?;
3212 } else {
3213 r.skip_bits(1)?;
3214 }
3215
3216 if ptl.sub_layer_level_present_flag[i] {
3217 let level: u8 = r.read_bits(8)?;
3218 ptl.sub_layer_level_idc[i] = Level::try_from(level)?;
3219 }
3220 }
3221 }
3222 Ok(())
3223 }
3224
3225 fn fill_default_scaling_list(sl: &mut ScalingLists, size_id: i32, matrix_id: i32) {
3226 if size_id == 0 {
3227 sl.scaling_list_4x4[matrix_id as usize] = DEFAULT_SCALING_LIST_0;
3228 return;
3229 }
3230
3231 let dst = match size_id {
3232 1 => &mut sl.scaling_list_8x8[matrix_id as usize],
3233 2 => &mut sl.scaling_list_16x16[matrix_id as usize],
3234 3 => &mut sl.scaling_list_32x32[matrix_id as usize],
3235 _ => panic!("Invalid size_id {}", size_id),
3236 };
3237
3238 let src = if matrix_id < 3 {
3239 &DEFAULT_SCALING_LIST_1
3240 } else if matrix_id <= 5 {
3241 &DEFAULT_SCALING_LIST_2
3242 } else {
3243 panic!("Invalid matrix_id {}", matrix_id);
3244 };
3245
3246 *dst = *src;
3247
3248 // When `scaling_list_pred_mode_flag[ sizeId ]`[ matrixId ] is equal to
3249 // 0, scaling_list_pred_matrix_id_ `delta[ sizeId ]`[ matrixId ] is equal
3250 // to 0 and sizeId is greater than 1, the value of
3251 // scaling_list_dc_coef_minus8[ sizeId − 2 `][ matrixId ]` is inferred to
3252 // be equal to 8.
3253 //
3254 // Since we are using a slightly different layout here, with two
3255 // different field names (i.e. 16x16, and 32x32), we must differentiate
3256 // between size_id == 2 or size_id == 3.
3257 if size_id == 2 {
3258 sl.scaling_list_dc_coef_minus8_16x16[matrix_id as usize] = 8;
3259 } else if size_id == 3 {
3260 sl.scaling_list_dc_coef_minus8_32x32[matrix_id as usize] = 8;
3261 }
3262 }
3263
3264 fn parse_scaling_list_data(sl: &mut ScalingLists, r: &mut BitReader) -> Result<(), String> {
3265 // 7.4.5
3266 for size_id in 0..4 {
3267 let mut matrix_id = 0;
3268 while matrix_id < 6 {
3269 let scaling_list_pred_mode_flag = r.read_bit()?;
3270 // If `scaling_list_pred_matrix_id_delta[ sizeId ]`[ matrixId ] is
3271 // equal to 0, the scaling list is inferred from the default
3272 // scaling list `ScalingList[ sizeId ]`[ matrixId `][ i ]` as specified
3273 // in Table 7-5 and Table 7-6 for i = 0..Min( 63, ( 1 << ( 4 + (
3274 // sizeId << 1 ) ) ) − 1 ).
3275 if !scaling_list_pred_mode_flag {
3276 let scaling_list_pred_matrix_id_delta: u32 = r.read_ue()?;
3277 if scaling_list_pred_matrix_id_delta == 0 {
3278 Self::fill_default_scaling_list(sl, size_id, matrix_id);
3279 } else {
3280 // Equation 7-42
3281 let factor = if size_id == 3 { 3 } else { 1 };
3282 let ref_matrix_id =
3283 matrix_id as u32 - scaling_list_pred_matrix_id_delta * factor;
3284 if size_id == 0 {
3285 sl.scaling_list_4x4[matrix_id as usize] =
3286 sl.scaling_list_4x4[ref_matrix_id as usize];
3287 } else {
3288 let src = match size_id {
3289 1 => sl.scaling_list_8x8[ref_matrix_id as usize],
3290 2 => sl.scaling_list_16x16[ref_matrix_id as usize],
3291 3 => sl.scaling_list_32x32[ref_matrix_id as usize],
3292 _ => return Err(format!("Invalid size_id {}", size_id)),
3293 };
3294
3295 let dst = match size_id {
3296 1 => &mut sl.scaling_list_8x8[matrix_id as usize],
3297 2 => &mut sl.scaling_list_16x16[matrix_id as usize],
3298 3 => &mut sl.scaling_list_32x32[matrix_id as usize],
3299 _ => return Err(format!("Invalid size_id {}", size_id)),
3300 };
3301
3302 *dst = src;
3303
3304 if size_id == 2 {
3305 sl.scaling_list_dc_coef_minus8_16x16[matrix_id as usize] =
3306 sl.scaling_list_dc_coef_minus8_16x16[ref_matrix_id as usize];
3307 } else if size_id == 3 {
3308 sl.scaling_list_dc_coef_minus8_32x32[matrix_id as usize] =
3309 sl.scaling_list_dc_coef_minus8_32x32[ref_matrix_id as usize];
3310 }
3311 }
3312 }
3313 } else {
3314 let mut next_coef = 8i32;
3315 let coef_num = std::cmp::min(64, 1 << (4 + (size_id << 1)));
3316
3317 if size_id > 1 {
3318 if size_id == 2 {
3319 sl.scaling_list_dc_coef_minus8_16x16[matrix_id as usize] =
3320 r.read_se_bounded(-7, 247)?;
3321 next_coef =
3322 i32::from(sl.scaling_list_dc_coef_minus8_16x16[matrix_id as usize])
3323 + 8;
3324 } else if size_id == 3 {
3325 sl.scaling_list_dc_coef_minus8_32x32[matrix_id as usize] =
3326 r.read_se_bounded(-7, 247)?;
3327 next_coef =
3328 i32::from(sl.scaling_list_dc_coef_minus8_32x32[matrix_id as usize])
3329 + 8;
3330 }
3331 }
3332
3333 for i in 0..coef_num as usize {
3334 let scaling_list_delta_coef: i32 = r.read_se_bounded(-128, 127)?;
3335 next_coef = (next_coef + scaling_list_delta_coef + 256) % 256;
3336 match size_id {
3337 0 => sl.scaling_list_4x4[matrix_id as usize][i] = next_coef as _,
3338 1 => sl.scaling_list_8x8[matrix_id as usize][i] = next_coef as _,
3339 2 => sl.scaling_list_16x16[matrix_id as usize][i] = next_coef as _,
3340 3 => sl.scaling_list_32x32[matrix_id as usize][i] = next_coef as _,
3341 _ => return Err(format!("Invalid size_id {}", size_id)),
3342 }
3343 }
3344 }
3345 let step = if size_id == 3 { 3 } else { 1 };
3346 matrix_id += step;
3347 }
3348 }
3349 Ok(())
3350 }
3351
3352 fn parse_short_term_ref_pic_set(
3353 sps: &Sps,
3354 st: &mut ShortTermRefPicSet,
3355 r: &mut BitReader,
3356 st_rps_idx: u8,
3357 ) -> Result<(), String> {
3358 if st_rps_idx != 0 {
3359 st.inter_ref_pic_set_prediction_flag = r.read_bit()?;
3360 }
3361
3362 // (7-59)
3363 if st.inter_ref_pic_set_prediction_flag {
3364 if st_rps_idx == sps.num_short_term_ref_pic_sets {
3365 st.delta_idx_minus1 = r.read_ue_max(st_rps_idx as u32 - 1)?;
3366 }
3367
3368 st.delta_rps_sign = r.read_bit()?;
3369 // The value of abs_delta_rps_minus1 shall be in the range of 0 to
3370 // 2^15 − 1, inclusive.
3371 st.abs_delta_rps_minus1 = r.read_ue_max(32767)?;
3372
3373 let ref_rps_idx = st_rps_idx - (st.delta_idx_minus1 + 1);
3374 let delta_rps =
3375 (1 - 2 * st.delta_rps_sign as i32) * (st.abs_delta_rps_minus1 as i32 + 1);
3376
3377 let ref_st = sps
3378 .short_term_ref_pic_set
3379 .get(usize::from(ref_rps_idx))
3380 .ok_or::<String>("Invalid ref_rps_idx".into())?;
3381
3382 let mut used_by_curr_pic_flag = [false; 64];
3383
3384 // 7.4.8 - defaults to 1 if not present
3385 let mut use_delta_flag = [true; 64];
3386
3387 for j in 0..=ref_st.num_delta_pocs as usize {
3388 used_by_curr_pic_flag[j] = r.read_bit()?;
3389 if !used_by_curr_pic_flag[j] {
3390 use_delta_flag[j] = r.read_bit()?;
3391 }
3392 }
3393
3394 // (7-61)
3395 let mut i = 0;
3396 // Ranges are [a,b[, but the real loop is [b, a], i.e.
3397 // [num_positive_pics - 1, 0]. Use ..= so that b is included when
3398 // rev() is called.
3399 for j in (0..=isize::from(ref_st.num_positive_pics) - 1)
3400 .rev()
3401 .take_while(|j| *j >= 0)
3402 .map(|j| j as usize)
3403 {
3404 let d_poc = ref_st.delta_poc_s1[j] + delta_rps;
3405 if d_poc < 0 && use_delta_flag[usize::from(ref_st.num_negative_pics) + j] {
3406 st.delta_poc_s0[i] = d_poc;
3407 st.used_by_curr_pic_s0[i] =
3408 used_by_curr_pic_flag[usize::from(ref_st.num_negative_pics) + j];
3409
3410 i += 1;
3411 }
3412 }
3413
3414 if delta_rps < 0 && use_delta_flag[ref_st.num_delta_pocs as usize] {
3415 st.delta_poc_s0[i] = delta_rps;
3416 st.used_by_curr_pic_s0[i] = used_by_curr_pic_flag[ref_st.num_delta_pocs as usize];
3417
3418 i += 1;
3419 }
3420
3421 // Let's *not* change the original algorithm in any way.
3422 #[allow(clippy::needless_range_loop)]
3423 for j in 0..ref_st.num_negative_pics as usize {
3424 let d_poc = ref_st.delta_poc_s0[j] + delta_rps;
3425 if d_poc < 0 && use_delta_flag[j] {
3426 st.delta_poc_s0[i] = d_poc;
3427 st.used_by_curr_pic_s0[i] = used_by_curr_pic_flag[j];
3428
3429 i += 1;
3430 }
3431 }
3432
3433 st.num_negative_pics = i as u8;
3434
3435 // (7-62)
3436 let mut i = 0;
3437 // Ranges are [a,b[, but the real loop is [b, a], i.e.
3438 // [num_negative_pics - 1, 0]. Use ..= so that b is included when
3439 // rev() is called.
3440 for j in (0..=isize::from(ref_st.num_negative_pics) - 1)
3441 .rev()
3442 .take_while(|j| *j >= 0)
3443 .map(|j| j as usize)
3444 {
3445 let d_poc = ref_st.delta_poc_s0[j] + delta_rps;
3446 if d_poc > 0 && use_delta_flag[j] {
3447 st.delta_poc_s1[i] = d_poc;
3448 st.used_by_curr_pic_s1[i] = used_by_curr_pic_flag[j];
3449
3450 i += 1;
3451 }
3452 }
3453
3454 if delta_rps > 0 && use_delta_flag[ref_st.num_delta_pocs as usize] {
3455 st.delta_poc_s1[i] = delta_rps;
3456 st.used_by_curr_pic_s1[i] = used_by_curr_pic_flag[ref_st.num_delta_pocs as usize];
3457
3458 i += 1;
3459 }
3460
3461 for j in 0..usize::from(ref_st.num_positive_pics) {
3462 let d_poc = ref_st.delta_poc_s1[j] + delta_rps;
3463 if d_poc > 0 && use_delta_flag[ref_st.num_negative_pics as usize + j] {
3464 st.delta_poc_s1[i] = d_poc;
3465 st.used_by_curr_pic_s1[i] =
3466 used_by_curr_pic_flag[ref_st.num_negative_pics as usize + j];
3467
3468 i += 1;
3469 }
3470 }
3471
3472 st.num_positive_pics = i as u8;
3473 } else {
3474 st.num_negative_pics = r.read_ue_max(u32::from(
3475 sps.max_dec_pic_buffering_minus1[usize::from(sps.max_sub_layers_minus1)],
3476 ))?;
3477
3478 st.num_positive_pics = r.read_ue_max(u32::from(
3479 sps.max_dec_pic_buffering_minus1[usize::from(sps.max_sub_layers_minus1)]
3480 - st.num_negative_pics,
3481 ))?;
3482
3483 for i in 0..usize::from(st.num_negative_pics) {
3484 let delta_poc_s0_minus1: u32 = r.read_ue_max(32767)?;
3485
3486 if i == 0 {
3487 st.delta_poc_s0[i] = -(delta_poc_s0_minus1 as i32 + 1);
3488 } else {
3489 st.delta_poc_s0[i] = st.delta_poc_s0[i - 1] - (delta_poc_s0_minus1 as i32 + 1);
3490 }
3491
3492 st.used_by_curr_pic_s0[i] = r.read_bit()?;
3493 }
3494
3495 for i in 0..usize::from(st.num_positive_pics) {
3496 let delta_poc_s1_minus1: u32 = r.read_ue_max(32767)?;
3497
3498 if i == 0 {
3499 st.delta_poc_s1[i] = delta_poc_s1_minus1 as i32 + 1;
3500 } else {
3501 st.delta_poc_s1[i] = st.delta_poc_s1[i - 1] + (delta_poc_s1_minus1 as i32 + 1);
3502 }
3503
3504 st.used_by_curr_pic_s1[i] = r.read_bit()?;
3505 }
3506 }
3507
3508 st.num_delta_pocs = u32::from(st.num_negative_pics + st.num_positive_pics);
3509
3510 Ok(())
3511 }
3512
3513 fn parse_sublayer_hrd_parameters(
3514 h: &mut SublayerHrdParameters,
3515 cpb_cnt: u32,
3516 sub_pic_hrd_params_present_flag: bool,
3517 r: &mut BitReader,
3518 ) -> Result<(), String> {
3519 for i in 0..cpb_cnt as usize {
3520 h.bit_rate_value_minus1[i] = r.read_ue_max((2u64.pow(32) - 2) as u32)?;
3521 h.cpb_size_value_minus1[i] = r.read_ue_max((2u64.pow(32) - 2) as u32)?;
3522 if sub_pic_hrd_params_present_flag {
3523 h.cpb_size_du_value_minus1[i] = r.read_ue_max((2u64.pow(32) - 2) as u32)?;
3524 h.bit_rate_du_value_minus1[i] = r.read_ue_max((2u64.pow(32) - 2) as u32)?;
3525 }
3526
3527 h.cbr_flag[i] = r.read_bit()?;
3528 }
3529
3530 Ok(())
3531 }
3532
3533 fn parse_hrd_parameters(
3534 common_inf_present_flag: bool,
3535 max_num_sublayers_minus1: u8,
3536 hrd: &mut HrdParams,
3537 r: &mut BitReader,
3538 ) -> Result<(), String> {
3539 if common_inf_present_flag {
3540 hrd.nal_hrd_parameters_present_flag = r.read_bit()?;
3541 hrd.vcl_hrd_parameters_present_flag = r.read_bit()?;
3542 if hrd.nal_hrd_parameters_present_flag || hrd.vcl_hrd_parameters_present_flag {
3543 hrd.sub_pic_hrd_params_present_flag = r.read_bit()?;
3544 if hrd.sub_pic_hrd_params_present_flag {
3545 hrd.tick_divisor_minus2 = r.read_bits(8)?;
3546 hrd.du_cpb_removal_delay_increment_length_minus1 = r.read_bits(5)?;
3547 hrd.sub_pic_cpb_params_in_pic_timing_sei_flag = r.read_bit()?;
3548 hrd.dpb_output_delay_du_length_minus1 = r.read_bits(5)?;
3549 }
3550 hrd.bit_rate_scale = r.read_bits(4)?;
3551 hrd.cpb_size_scale = r.read_bits(4)?;
3552 if hrd.sub_pic_hrd_params_present_flag {
3553 hrd.cpb_size_du_scale = r.read_bits(4)?;
3554 }
3555 hrd.initial_cpb_removal_delay_length_minus1 = r.read_bits(5)?;
3556 hrd.au_cpb_removal_delay_length_minus1 = r.read_bits(5)?;
3557 hrd.dpb_output_delay_length_minus1 = r.read_bits(5)?;
3558 }
3559 }
3560
3561 for i in 0..=max_num_sublayers_minus1 as usize {
3562 hrd.fixed_pic_rate_general_flag[i] = r.read_bit()?;
3563 if !hrd.fixed_pic_rate_general_flag[i] {
3564 hrd.fixed_pic_rate_within_cvs_flag[i] = r.read_bit()?;
3565 }
3566 if hrd.fixed_pic_rate_within_cvs_flag[i] {
3567 hrd.elemental_duration_in_tc_minus1[i] = r.read_ue_max(2047)?;
3568 } else {
3569 hrd.low_delay_hrd_flag[i] = r.read_bit()?;
3570 }
3571
3572 if !hrd.low_delay_hrd_flag[i] {
3573 hrd.cpb_cnt_minus1[i] = r.read_ue_max(31)?;
3574 }
3575
3576 if hrd.nal_hrd_parameters_present_flag {
3577 Self::parse_sublayer_hrd_parameters(
3578 &mut hrd.nal_hrd[i],
3579 hrd.cpb_cnt_minus1[i] + 1,
3580 hrd.sub_pic_hrd_params_present_flag,
3581 r,
3582 )?;
3583 }
3584
3585 if hrd.vcl_hrd_parameters_present_flag {
3586 Self::parse_sublayer_hrd_parameters(
3587 &mut hrd.vcl_hrd[i],
3588 hrd.cpb_cnt_minus1[i] + 1,
3589 hrd.sub_pic_hrd_params_present_flag,
3590 r,
3591 )?;
3592 }
3593 }
3594
3595 Ok(())
3596 }
3597
3598 fn parse_vui_parameters(sps: &mut Sps, r: &mut BitReader) -> Result<(), String> {
3599 let vui = &mut sps.vui_parameters;
3600
3601 vui.aspect_ratio_info_present_flag = r.read_bit()?;
3602 if vui.aspect_ratio_info_present_flag {
3603 vui.aspect_ratio_idc = r.read_bits(8)?;
3604 const EXTENDED_SAR: u32 = 255;
3605 if vui.aspect_ratio_idc == EXTENDED_SAR {
3606 vui.sar_width = r.read_bits(16)?;
3607 vui.sar_height = r.read_bits(16)?;
3608 }
3609 }
3610
3611 vui.overscan_info_present_flag = r.read_bit()?;
3612 if vui.overscan_info_present_flag {
3613 vui.overscan_appropriate_flag = r.read_bit()?;
3614 }
3615
3616 vui.video_signal_type_present_flag = r.read_bit()?;
3617 if vui.video_signal_type_present_flag {
3618 vui.video_format = r.read_bits(3)?;
3619 vui.video_full_range_flag = r.read_bit()?;
3620 vui.colour_description_present_flag = r.read_bit()?;
3621 if vui.colour_description_present_flag {
3622 vui.colour_primaries = r.read_bits(8)?;
3623 vui.transfer_characteristics = r.read_bits(8)?;
3624 vui.matrix_coeffs = r.read_bits(8)?;
3625 }
3626 }
3627
3628 vui.chroma_loc_info_present_flag = r.read_bit()?;
3629 if vui.chroma_loc_info_present_flag {
3630 vui.chroma_sample_loc_type_top_field = r.read_ue_max(5)?;
3631 vui.chroma_sample_loc_type_bottom_field = r.read_ue_max(5)?;
3632 }
3633
3634 vui.neutral_chroma_indication_flag = r.read_bit()?;
3635 vui.field_seq_flag = r.read_bit()?;
3636 vui.frame_field_info_present_flag = r.read_bit()?;
3637 vui.default_display_window_flag = r.read_bit()?;
3638
3639 if vui.default_display_window_flag {
3640 vui.def_disp_win_left_offset = r.read_ue()?;
3641 vui.def_disp_win_right_offset = r.read_ue()?;
3642 vui.def_disp_win_top_offset = r.read_ue()?;
3643 vui.def_disp_win_bottom_offset = r.read_ue()?;
3644 }
3645
3646 vui.timing_info_present_flag = r.read_bit()?;
3647 if vui.timing_info_present_flag {
3648 vui.num_units_in_tick = r.read_bits::<u32>(31)? << 1;
3649 vui.num_units_in_tick |= r.read_bits::<u32>(1)?;
3650
3651 if vui.num_units_in_tick == 0 {
3652 log::warn!("Incompliant value for num_units_in_tick {}", vui.num_units_in_tick);
3653 }
3654
3655 vui.time_scale = r.read_bits::<u32>(31)? << 1;
3656 vui.time_scale |= r.read_bits::<u32>(1)?;
3657
3658 if vui.time_scale == 0 {
3659 log::warn!("Incompliant value for time_scale {}", vui.time_scale);
3660 }
3661
3662 vui.poc_proportional_to_timing_flag = r.read_bit()?;
3663 if vui.poc_proportional_to_timing_flag {
3664 vui.num_ticks_poc_diff_one_minus1 = r.read_ue_max((2u64.pow(32) - 2) as u32)?;
3665 }
3666
3667 vui.hrd_parameters_present_flag = r.read_bit()?;
3668 if vui.hrd_parameters_present_flag {
3669 let sps_max_sub_layers_minus1 = sps.max_sub_layers_minus1;
3670 Self::parse_hrd_parameters(true, sps_max_sub_layers_minus1, &mut vui.hrd, r)?;
3671 }
3672 }
3673
3674 vui.bitstream_restriction_flag = r.read_bit()?;
3675 if vui.bitstream_restriction_flag {
3676 vui.tiles_fixed_structure_flag = r.read_bit()?;
3677 vui.motion_vectors_over_pic_boundaries_flag = r.read_bit()?;
3678 vui.restricted_ref_pic_lists_flag = r.read_bit()?;
3679
3680 vui.min_spatial_segmentation_idc = r.read_ue_max(4095)?;
3681 vui.max_bytes_per_pic_denom = r.read_ue()?;
3682 vui.max_bits_per_min_cu_denom = r.read_ue()?;
3683 vui.log2_max_mv_length_horizontal = r.read_ue_max(16)?;
3684 vui.log2_max_mv_length_vertical = r.read_ue_max(15)?;
3685 }
3686
3687 Ok(())
3688 }
3689
3690 fn parse_sps_scc_extension(sps: &mut Sps, r: &mut BitReader) -> Result<(), String> {
3691 let scc = &mut sps.scc_extension;
3692
3693 scc.curr_pic_ref_enabled_flag = r.read_bit()?;
3694 scc.palette_mode_enabled_flag = r.read_bit()?;
3695 if scc.palette_mode_enabled_flag {
3696 scc.palette_max_size = r.read_ue_max(64)?;
3697 scc.delta_palette_max_predictor_size =
3698 r.read_ue_max(128 - u32::from(scc.palette_max_size))?;
3699 scc.palette_predictor_initializers_present_flag = r.read_bit()?;
3700 if scc.palette_predictor_initializers_present_flag {
3701 let max =
3702 u32::from(scc.palette_max_size + scc.delta_palette_max_predictor_size - 1);
3703 scc.num_palette_predictor_initializer_minus1 = r.read_ue_max(max)?;
3704
3705 let num_comps = if sps.chroma_format_idc == 0 { 1 } else { 3 };
3706 for comp in 0..num_comps {
3707 for i in 0..=usize::from(scc.num_palette_predictor_initializer_minus1) {
3708 let num_bits = if comp == 0 {
3709 sps.bit_depth_luma_minus8 + 8
3710 } else {
3711 sps.bit_depth_chroma_minus8 + 8
3712 };
3713 scc.palette_predictor_initializer[comp][i] =
3714 r.read_bits(usize::from(num_bits))?;
3715 }
3716 }
3717 }
3718 }
3719
3720 scc.motion_vector_resolution_control_idc = r.read_bits(2)?;
3721 scc.intra_boundary_filtering_disabled_flag = r.read_bit()?;
3722
3723 Ok(())
3724 }
3725
3726 fn parse_sps_range_extension(sps: &mut Sps, r: &mut BitReader) -> Result<(), String> {
3727 let ext = &mut sps.range_extension;
3728
3729 ext.transform_skip_rotation_enabled_flag = r.read_bit()?;
3730 ext.transform_skip_context_enabled_flag = r.read_bit()?;
3731 ext.implicit_rdpcm_enabled_flag = r.read_bit()?;
3732 ext.explicit_rdpcm_enabled_flag = r.read_bit()?;
3733 ext.extended_precision_processing_flag = r.read_bit()?;
3734 ext.intra_smoothing_disabled_flag = r.read_bit()?;
3735 ext.high_precision_offsets_enabled_flag = r.read_bit()?;
3736 ext.persistent_rice_adaptation_enabled_flag = r.read_bit()?;
3737 ext.cabac_bypass_alignment_enabled_flag = r.read_bit()?;
3738
3739 Ok(())
3740 }
3741
3742 /// Parse a SPS NALU.
3743 pub fn parse_sps(&mut self, nalu: &Nalu) -> Result<&Sps, String> {
3744 if !matches!(nalu.header.type_, NaluType::SpsNut) {
3745 return Err(format!(
3746 "Invalid NALU type, expected {:?}, got {:?}",
3747 NaluType::SpsNut,
3748 nalu.header.type_
3749 ));
3750 }
3751
3752 let data = nalu.as_ref();
3753 let header = &nalu.header;
3754 let hdr_len = header.len();
3755 // Skip the header
3756 let mut r = BitReader::new(&data[hdr_len..], true);
3757
3758 let video_parameter_set_id = r.read_bits(4)?;
3759
3760 // A non-existing VPS means the SPS is not using any VPS.
3761 let vps = self.get_vps(video_parameter_set_id).cloned();
3762
3763 let mut sps = Sps {
3764 video_parameter_set_id,
3765 max_sub_layers_minus1: r.read_bits(3)?,
3766 temporal_id_nesting_flag: r.read_bit()?,
3767 vps,
3768 ..Default::default()
3769 };
3770
3771 // §7.4.3.2.1: 0..6, and the sub-layer arrays below are 7 long.
3772 if sps.max_sub_layers_minus1 > 6 {
3773 return Err(format!(
3774 "Invalid sps_max_sub_layers_minus1 {}",
3775 sps.max_sub_layers_minus1
3776 ));
3777 }
3778
3779 Self::parse_profile_tier_level(
3780 &mut sps.profile_tier_level,
3781 &mut r,
3782 true,
3783 sps.max_sub_layers_minus1,
3784 )?;
3785
3786 sps.seq_parameter_set_id = r.read_ue_max(MAX_SPS_COUNT as u32 - 1)?;
3787 sps.chroma_format_idc = r.read_ue_max(3)?;
3788
3789 if sps.chroma_format_idc == 3 {
3790 sps.separate_colour_plane_flag = r.read_bit()?;
3791 }
3792
3793 sps.chroma_array_type =
3794 if sps.separate_colour_plane_flag { 0 } else { sps.chroma_format_idc };
3795
3796 sps.pic_width_in_luma_samples = r.read_ue_bounded(1, 16888)?;
3797 sps.pic_height_in_luma_samples = r.read_ue_bounded(1, 16888)?;
3798
3799 sps.conformance_window_flag = r.read_bit()?;
3800 if sps.conformance_window_flag {
3801 sps.conf_win_left_offset = r.read_ue()?;
3802 sps.conf_win_right_offset = r.read_ue()?;
3803 sps.conf_win_top_offset = r.read_ue()?;
3804 sps.conf_win_bottom_offset = r.read_ue()?;
3805 }
3806
3807 sps.bit_depth_luma_minus8 = r.read_ue_max(6)?;
3808 sps.bit_depth_chroma_minus8 = r.read_ue_max(6)?;
3809 sps.log2_max_pic_order_cnt_lsb_minus4 = r.read_ue_max(12)?;
3810 sps.sub_layer_ordering_info_present_flag = r.read_bit()?;
3811
3812 {
3813 let i = if sps.sub_layer_ordering_info_present_flag {
3814 0
3815 } else {
3816 sps.max_sub_layers_minus1
3817 };
3818
3819 for j in i..=sps.max_sub_layers_minus1 {
3820 sps.max_dec_pic_buffering_minus1[j as usize] = r.read_ue_max(16)?;
3821 sps.max_num_reorder_pics[j as usize] =
3822 r.read_ue_max(sps.max_dec_pic_buffering_minus1[j as usize] as _)?;
3823 sps.max_latency_increase_plus1[j as usize] = r.read_ue_max(u32::MAX - 1)?;
3824 }
3825 }
3826
3827 sps.log2_min_luma_coding_block_size_minus3 = r.read_ue_max(3)?;
3828 sps.log2_diff_max_min_luma_coding_block_size = r.read_ue_max(6)?;
3829 sps.log2_min_luma_transform_block_size_minus2 = r.read_ue_max(3)?;
3830 sps.log2_diff_max_min_luma_transform_block_size = r.read_ue_max(3)?;
3831
3832 // (7-10)
3833 sps.min_cb_log2_size_y = u32::from(sps.log2_min_luma_coding_block_size_minus3 + 3);
3834 // (7-11)
3835 sps.ctb_log2_size_y =
3836 sps.min_cb_log2_size_y + u32::from(sps.log2_diff_max_min_luma_coding_block_size);
3837 // (7-12)
3838 sps.ctb_size_y = 1 << sps.ctb_log2_size_y;
3839 // (7-17)
3840 sps.pic_height_in_ctbs_y =
3841 (sps.pic_height_in_luma_samples as f64 / sps.ctb_size_y as f64).ceil() as u32;
3842 // (7-15)
3843 sps.pic_width_in_ctbs_y =
3844 (sps.pic_width_in_luma_samples as f64 / sps.ctb_size_y as f64).ceil() as u32;
3845
3846 sps.max_tb_log2_size_y = u32::from(
3847 sps.log2_min_luma_transform_block_size_minus2
3848 + 2
3849 + sps.log2_diff_max_min_luma_transform_block_size,
3850 );
3851
3852 sps.pic_size_in_samples_y =
3853 u32::from(sps.pic_width_in_luma_samples) * u32::from(sps.pic_height_in_luma_samples);
3854
3855 if sps.max_tb_log2_size_y > std::cmp::min(sps.ctb_log2_size_y, 5) {
3856 return Err(format!("Invalid value for MaxTbLog2SizeY: {}", sps.max_tb_log2_size_y));
3857 }
3858
3859 sps.pic_size_in_ctbs_y = sps.pic_width_in_ctbs_y * sps.pic_height_in_ctbs_y;
3860
3861 sps.max_transform_hierarchy_depth_inter = r.read_ue_max(4)?;
3862 sps.max_transform_hierarchy_depth_intra = r.read_ue_max(4)?;
3863
3864 sps.scaling_list_enabled_flag = r.read_bit()?;
3865 if sps.scaling_list_enabled_flag {
3866 sps.scaling_list_data_present_flag = r.read_bit()?;
3867 if sps.scaling_list_data_present_flag {
3868 Self::parse_scaling_list_data(&mut sps.scaling_list, &mut r)?;
3869 }
3870 }
3871
3872 sps.amp_enabled_flag = r.read_bit()?;
3873 sps.sample_adaptive_offset_enabled_flag = r.read_bit()?;
3874
3875 sps.pcm_enabled_flag = r.read_bit()?;
3876 if sps.pcm_enabled_flag {
3877 sps.pcm_sample_bit_depth_luma_minus1 = r.read_bits(4)?;
3878 sps.pcm_sample_bit_depth_chroma_minus1 = r.read_bits(4)?;
3879 sps.log2_min_pcm_luma_coding_block_size_minus3 = r.read_ue_max(2)?;
3880 sps.log2_diff_max_min_pcm_luma_coding_block_size = r.read_ue_max(2)?;
3881 sps.pcm_loop_filter_disabled_flag = r.read_bit()?;
3882 }
3883
3884 sps.num_short_term_ref_pic_sets = r.read_ue_max(64)?;
3885
3886 for i in 0..sps.num_short_term_ref_pic_sets {
3887 let mut st = ShortTermRefPicSet::default();
3888 Self::parse_short_term_ref_pic_set(&sps, &mut st, &mut r, i)?;
3889 sps.short_term_ref_pic_set.push(st);
3890 }
3891
3892 sps.long_term_ref_pics_present_flag = r.read_bit()?;
3893 if sps.long_term_ref_pics_present_flag {
3894 sps.num_long_term_ref_pics_sps = r.read_ue_max(32)?;
3895 for i in 0..usize::from(sps.num_long_term_ref_pics_sps) {
3896 sps.lt_ref_pic_poc_lsb_sps[i] =
3897 r.read_bits(usize::from(sps.log2_max_pic_order_cnt_lsb_minus4) + 4)?;
3898 sps.used_by_curr_pic_lt_sps_flag[i] = r.read_bit()?;
3899 }
3900 }
3901
3902 sps.temporal_mvp_enabled_flag = r.read_bit()?;
3903 sps.strong_intra_smoothing_enabled_flag = r.read_bit()?;
3904
3905 sps.vui_parameters_present_flag = r.read_bit()?;
3906 if sps.vui_parameters_present_flag {
3907 Self::parse_vui_parameters(&mut sps, &mut r)?;
3908 }
3909
3910 sps.extension_present_flag = r.read_bit()?;
3911 if sps.extension_present_flag {
3912 sps.range_extension_flag = r.read_bit()?;
3913 if sps.range_extension_flag {
3914 Self::parse_sps_range_extension(&mut sps, &mut r)?;
3915 }
3916
3917 let multilayer_extension_flag = r.read_bit()?;
3918 if multilayer_extension_flag {
3919 return Err("Multilayer extension not supported.".into());
3920 }
3921
3922 let three_d_extension_flag = r.read_bit()?;
3923 if three_d_extension_flag {
3924 return Err("3D extension not supported.".into());
3925 }
3926
3927 sps.scc_extension_flag = r.read_bit()?;
3928 if sps.scc_extension_flag {
3929 Self::parse_sps_scc_extension(&mut sps, &mut r)?;
3930 }
3931 }
3932
3933 let shift = if sps.range_extension.high_precision_offsets_enabled_flag {
3934 sps.bit_depth_luma_minus8 + 7
3935 } else {
3936 7
3937 };
3938
3939 sps.wp_offset_half_range_y = 1 << shift;
3940
3941 let shift = if sps.range_extension.high_precision_offsets_enabled_flag {
3942 sps.bit_depth_chroma_minus8 + 7
3943 } else {
3944 7
3945 };
3946
3947 sps.wp_offset_half_range_c = 1 << shift;
3948
3949 log::debug!(
3950 "Parsed SPS({}), resolution: ({}, {}): NAL size was {}",
3951 sps.seq_parameter_set_id,
3952 sps.width(),
3953 sps.height(),
3954 nalu.size
3955 );
3956
3957 if self.active_spses.keys().len() >= MAX_SPS_COUNT {
3958 return Err("Broken data: Number of active SPSs > MAX_SPS_COUNT".into());
3959 }
3960
3961 let key = sps.seq_parameter_set_id;
3962 let sps = Rc::new(sps);
3963 self.active_spses.remove(&key);
3964 Ok(self.active_spses.entry(key).or_insert(sps))
3965 }
3966
3967 fn parse_pps_scc_extension(pps: &mut Pps, sps: &Sps, r: &mut BitReader) -> Result<(), String> {
3968 let scc = &mut pps.scc_extension;
3969 scc.curr_pic_ref_enabled_flag = r.read_bit()?;
3970 scc.residual_adaptive_colour_transform_enabled_flag = r.read_bit()?;
3971 if scc.residual_adaptive_colour_transform_enabled_flag {
3972 scc.slice_act_qp_offsets_present_flag = r.read_bit()?;
3973 scc.act_y_qp_offset_plus5 = r.read_se_bounded(-7, 17)?;
3974 scc.act_cb_qp_offset_plus5 = r.read_se_bounded(-7, 17)?;
3975 scc.act_cr_qp_offset_plus3 = r.read_se_bounded(-9, 15)?;
3976 }
3977
3978 scc.palette_predictor_initializers_present_flag = r.read_bit()?;
3979 if scc.palette_predictor_initializers_present_flag {
3980 let max = sps.scc_extension.palette_max_size
3981 + sps.scc_extension.delta_palette_max_predictor_size;
3982 scc.num_palette_predictor_initializers = r.read_ue_max(max.into())?;
3983 if scc.num_palette_predictor_initializers > 0 {
3984 scc.monochrome_palette_flag = r.read_bit()?;
3985 scc.luma_bit_depth_entry_minus8 = r.read_ue_bounded(
3986 sps.bit_depth_luma_minus8.into(),
3987 sps.bit_depth_luma_minus8.into(),
3988 )?;
3989 if !scc.monochrome_palette_flag {
3990 scc.chroma_bit_depth_entry_minus8 = r.read_ue_bounded(
3991 sps.bit_depth_chroma_minus8.into(),
3992 sps.bit_depth_chroma_minus8.into(),
3993 )?;
3994 }
3995
3996 let num_comps = if scc.monochrome_palette_flag { 1 } else { 3 };
3997 for comp in 0..num_comps {
3998 let num_bits = if comp == 0 {
3999 scc.luma_bit_depth_entry_minus8 + 8
4000 } else {
4001 scc.chroma_bit_depth_entry_minus8 + 8
4002 };
4003 for i in 0..usize::from(scc.num_palette_predictor_initializers) {
4004 scc.palette_predictor_initializer[comp][i] =
4005 r.read_bits(num_bits.into())?;
4006 }
4007 }
4008 }
4009 }
4010 Ok(())
4011 }
4012
4013 fn parse_pps_range_extension(
4014 pps: &mut Pps,
4015 sps: &Sps,
4016 r: &mut BitReader,
4017 ) -> Result<(), String> {
4018 let rext = &mut pps.range_extension;
4019
4020 if pps.transform_skip_enabled_flag {
4021 rext.log2_max_transform_skip_block_size_minus2 =
4022 r.read_ue_max(sps.max_tb_log2_size_y - 2)?;
4023 }
4024
4025 rext.cross_component_prediction_enabled_flag = r.read_bit()?;
4026 rext.chroma_qp_offset_list_enabled_flag = r.read_bit()?;
4027 if rext.chroma_qp_offset_list_enabled_flag {
4028 rext.diff_cu_chroma_qp_offset_depth = r.read_ue()?;
4029 rext.chroma_qp_offset_list_len_minus1 = r.read_ue_max(5)?;
4030 for i in 0..=rext.chroma_qp_offset_list_len_minus1 as usize {
4031 rext.cb_qp_offset_list[i] = r.read_se_bounded(-12, 12)?;
4032 rext.cr_qp_offset_list[i] = r.read_se_bounded(-12, 12)?;
4033 }
4034 }
4035
4036 let bit_depth_y = sps.bit_depth_luma_minus8 + 8;
4037 let max = u32::from(std::cmp::max(0, bit_depth_y - 10));
4038
4039 rext.log2_sao_offset_scale_luma = r.read_ue_max(max)?;
4040 rext.log2_sao_offset_scale_chroma = r.read_ue_max(max)?;
4041
4042 Ok(())
4043 }
4044
4045 /// Parse a PPS NALU.
4046 pub fn parse_pps(&mut self, nalu: &Nalu) -> Result<&Pps, String> {
4047 if !matches!(nalu.header.type_, NaluType::PpsNut) {
4048 return Err(format!(
4049 "Invalid NALU type, expected {:?}, got {:?}",
4050 NaluType::PpsNut,
4051 nalu.header.type_
4052 ));
4053 }
4054
4055 let data = nalu.as_ref();
4056 let header = &nalu.header;
4057 let hdr_len = header.len();
4058 // Skip the header
4059 let mut r = BitReader::new(&data[hdr_len..], true);
4060
4061 let pic_parameter_set_id = r.read_ue_max(MAX_PPS_COUNT as u32 - 1)?;
4062 let seq_parameter_set_id = r.read_ue_max(MAX_SPS_COUNT as u32 - 1)?;
4063
4064 let sps = self.get_sps(seq_parameter_set_id).ok_or::<String>(format!(
4065 "Could not get SPS for seq_parameter_set_id {}",
4066 seq_parameter_set_id
4067 ))?;
4068
4069 let mut pps = Pps {
4070 pic_parameter_set_id,
4071 seq_parameter_set_id,
4072 dependent_slice_segments_enabled_flag: Default::default(),
4073 output_flag_present_flag: Default::default(),
4074 num_extra_slice_header_bits: Default::default(),
4075 sign_data_hiding_enabled_flag: Default::default(),
4076 cabac_init_present_flag: Default::default(),
4077 num_ref_idx_l0_default_active_minus1: Default::default(),
4078 num_ref_idx_l1_default_active_minus1: Default::default(),
4079 init_qp_minus26: Default::default(),
4080 constrained_intra_pred_flag: Default::default(),
4081 transform_skip_enabled_flag: Default::default(),
4082 cu_qp_delta_enabled_flag: Default::default(),
4083 diff_cu_qp_delta_depth: Default::default(),
4084 cb_qp_offset: Default::default(),
4085 cr_qp_offset: Default::default(),
4086 slice_chroma_qp_offsets_present_flag: Default::default(),
4087 weighted_pred_flag: Default::default(),
4088 weighted_bipred_flag: Default::default(),
4089 transquant_bypass_enabled_flag: Default::default(),
4090 tiles_enabled_flag: Default::default(),
4091 entropy_coding_sync_enabled_flag: Default::default(),
4092 num_tile_columns_minus1: Default::default(),
4093 num_tile_rows_minus1: Default::default(),
4094 uniform_spacing_flag: true,
4095 column_width_minus1: Default::default(),
4096 row_height_minus1: Default::default(),
4097 loop_filter_across_tiles_enabled_flag: true,
4098 loop_filter_across_slices_enabled_flag: Default::default(),
4099 deblocking_filter_control_present_flag: Default::default(),
4100 deblocking_filter_override_enabled_flag: Default::default(),
4101 deblocking_filter_disabled_flag: Default::default(),
4102 beta_offset_div2: Default::default(),
4103 tc_offset_div2: Default::default(),
4104 scaling_list_data_present_flag: Default::default(),
4105 scaling_list: Default::default(),
4106 lists_modification_present_flag: Default::default(),
4107 log2_parallel_merge_level_minus2: Default::default(),
4108 slice_segment_header_extension_present_flag: Default::default(),
4109 extension_present_flag: Default::default(),
4110 range_extension_flag: Default::default(),
4111 range_extension: Default::default(),
4112 qp_bd_offset_y: Default::default(),
4113 scc_extension: Default::default(),
4114 scc_extension_flag: Default::default(),
4115 sps: Rc::clone(sps),
4116 };
4117
4118 pps.dependent_slice_segments_enabled_flag = r.read_bit()?;
4119 pps.output_flag_present_flag = r.read_bit()?;
4120 pps.num_extra_slice_header_bits = r.read_bits(3)?;
4121 pps.sign_data_hiding_enabled_flag = r.read_bit()?;
4122 pps.cabac_init_present_flag = r.read_bit()?;
4123
4124 // 7.4.7.1
4125 pps.num_ref_idx_l0_default_active_minus1 = r.read_ue_max(14)?;
4126 pps.num_ref_idx_l1_default_active_minus1 = r.read_ue_max(14)?;
4127
4128 // (7-5)
4129 let qp_bd_offset_y = 6 * i32::from(sps.bit_depth_luma_minus8);
4130
4131 pps.init_qp_minus26 = r.read_se_bounded(-(26 + qp_bd_offset_y), 25)?;
4132 pps.qp_bd_offset_y = qp_bd_offset_y as u32;
4133 pps.constrained_intra_pred_flag = r.read_bit()?;
4134 pps.transform_skip_enabled_flag = r.read_bit()?;
4135 pps.cu_qp_delta_enabled_flag = r.read_bit()?;
4136
4137 if pps.cu_qp_delta_enabled_flag {
4138 pps.diff_cu_qp_delta_depth =
4139 r.read_ue_max(u32::from(sps.log2_diff_max_min_luma_coding_block_size))?;
4140 }
4141
4142 pps.cb_qp_offset = r.read_se_bounded(-12, 12)?;
4143 pps.cr_qp_offset = r.read_se_bounded(-12, 12)?;
4144
4145 pps.slice_chroma_qp_offsets_present_flag = r.read_bit()?;
4146 pps.weighted_pred_flag = r.read_bit()?;
4147 pps.weighted_bipred_flag = r.read_bit()?;
4148 pps.transquant_bypass_enabled_flag = r.read_bit()?;
4149 pps.tiles_enabled_flag = r.read_bit()?;
4150 pps.entropy_coding_sync_enabled_flag = r.read_bit()?;
4151
4152 // A mix of the rbsp data and the algorithm in 6.5.1
4153 if pps.tiles_enabled_flag {
4154 // §7.4.3.3.1 bounds these by the CTB grid, which at 4K is far more
4155 // tiles than either these arrays or the VA-API picture parameter
4156 // (`column_width_minus1[19]`, `row_height_minus1[21]`, the level-6
4157 // tile limits) can hold. Refuse the stream instead of indexing past
4158 // them -- a decode we could not have handed to the driver anyway.
4159 let max_cols = pps.column_width_minus1.len() as u32 - 1;
4160 let max_rows = pps.row_height_minus1.len() as u32 - 1;
4161 pps.num_tile_columns_minus1 =
4162 r.read_ue_max((sps.pic_width_in_ctbs_y - 1).min(max_cols))?;
4163 pps.num_tile_rows_minus1 = r.read_ue_max((sps.pic_height_in_ctbs_y - 1).min(max_rows))?;
4164 pps.uniform_spacing_flag = r.read_bit()?;
4165 if !pps.uniform_spacing_flag {
4166 pps.column_width_minus1[usize::from(pps.num_tile_columns_minus1)] =
4167 sps.pic_width_in_ctbs_y - 1;
4168
4169 for i in 0..usize::from(pps.num_tile_columns_minus1) {
4170 pps.column_width_minus1[i] = r.read_ue_max(
4171 pps.column_width_minus1[usize::from(pps.num_tile_columns_minus1)] - 1,
4172 )?;
4173 pps.column_width_minus1[usize::from(pps.num_tile_columns_minus1)] -=
4174 pps.column_width_minus1[i] + 1;
4175 }
4176
4177 pps.row_height_minus1[usize::from(pps.num_tile_rows_minus1)] =
4178 sps.pic_height_in_ctbs_y - 1;
4179
4180 for i in 0..usize::from(pps.num_tile_rows_minus1) {
4181 pps.row_height_minus1[i] = r.read_ue_max(
4182 pps.row_height_minus1[usize::from(pps.num_tile_rows_minus1)] - 1,
4183 )?;
4184 pps.row_height_minus1[usize::from(pps.num_tile_rows_minus1)] -=
4185 pps.row_height_minus1[i] + 1;
4186 }
4187 } else {
4188 let nrows = u32::from(pps.num_tile_rows_minus1) + 1;
4189 let ncols = u32::from(pps.num_tile_columns_minus1) + 1;
4190
4191 for j in 0..ncols {
4192 pps.column_width_minus1[j as usize] = ((j + 1) * sps.pic_width_in_ctbs_y)
4193 / ncols
4194 - j * sps.pic_width_in_ctbs_y / ncols
4195 - 1;
4196 }
4197
4198 for j in 0..nrows {
4199 pps.row_height_minus1[j as usize] = ((j + 1) * sps.pic_height_in_ctbs_y)
4200 / nrows
4201 - j * sps.pic_height_in_ctbs_y / nrows
4202 - 1;
4203 }
4204 }
4205
4206 pps.loop_filter_across_tiles_enabled_flag = r.read_bit()?;
4207 }
4208
4209 pps.loop_filter_across_slices_enabled_flag = r.read_bit()?;
4210 pps.deblocking_filter_control_present_flag = r.read_bit()?;
4211
4212 if pps.deblocking_filter_control_present_flag {
4213 pps.deblocking_filter_override_enabled_flag = r.read_bit()?;
4214 pps.deblocking_filter_disabled_flag = r.read_bit()?;
4215 if !pps.deblocking_filter_disabled_flag {
4216 pps.beta_offset_div2 = r.read_se_bounded(-6, 6)?;
4217 pps.tc_offset_div2 = r.read_se_bounded(-6, 6)?;
4218 }
4219 }
4220
4221 pps.scaling_list_data_present_flag = r.read_bit()?;
4222
4223 if pps.scaling_list_data_present_flag {
4224 Self::parse_scaling_list_data(&mut pps.scaling_list, &mut r)?;
4225 } else {
4226 for size_id in 0..4 {
4227 let mut matrix_id = 0;
4228 while matrix_id < 6 {
4229 Self::fill_default_scaling_list(&mut pps.scaling_list, size_id, matrix_id);
4230 let step = if size_id == 3 { 3 } else { 1 };
4231 matrix_id += step;
4232 }
4233 }
4234 }
4235
4236 pps.lists_modification_present_flag = r.read_bit()?;
4237 pps.log2_parallel_merge_level_minus2 = r.read_ue_max(sps.ctb_log2_size_y - 2)?;
4238 pps.slice_segment_header_extension_present_flag = r.read_bit()?;
4239
4240 pps.extension_present_flag = r.read_bit()?;
4241 if pps.extension_present_flag {
4242 pps.range_extension_flag = r.read_bit()?;
4243
4244 if pps.range_extension_flag {
4245 Self::parse_pps_range_extension(&mut pps, sps, &mut r)?;
4246 }
4247
4248 let multilayer_extension_flag = r.read_bit()?;
4249 if multilayer_extension_flag {
4250 return Err("Multilayer extension is not supported".into());
4251 }
4252
4253 let three_d_extension_flag = r.read_bit()?;
4254 if three_d_extension_flag {
4255 return Err("3D extension is not supported".into());
4256 }
4257
4258 pps.scc_extension_flag = r.read_bit()?;
4259 if pps.scc_extension_flag {
4260 Self::parse_pps_scc_extension(&mut pps, sps, &mut r)?;
4261 }
4262
4263 r.skip_bits(4)?; // pps_extension_4bits
4264 }
4265
4266 log::debug!("Parsed PPS({}), NAL size was {}", pps.pic_parameter_set_id, nalu.size);
4267
4268 if self.active_ppses.keys().len() >= MAX_PPS_COUNT {
4269 return Err("Broken Data: number of active PPSs > MAX_PPS_COUNT".into());
4270 }
4271
4272 let key = pps.pic_parameter_set_id;
4273 let pps = Rc::new(pps);
4274 self.active_ppses.remove(&key);
4275 Ok(self.active_ppses.entry(key).or_insert(pps))
4276 }
4277
4278 fn parse_pred_weight_table(
4279 hdr: &mut SliceHeader,
4280 r: &mut BitReader,
4281 sps: &Sps,
4282 ) -> Result<(), String> {
4283 let pwt = &mut hdr.pred_weight_table;
4284
4285 pwt.luma_log2_weight_denom = r.read_ue_max(7)?;
4286 if sps.chroma_array_type != 0 {
4287 pwt.delta_chroma_log2_weight_denom = r.read_se()?;
4288 pwt.chroma_log2_weight_denom = (pwt.luma_log2_weight_denom as i32
4289 + pwt.delta_chroma_log2_weight_denom as i32)
4290 .try_into()
4291 .map_err(|_| {
4292 String::from("Integer overflow on chroma_log2_weight_denom calculation")
4293 })?;
4294 }
4295
4296 for i in 0..=usize::from(hdr.num_ref_idx_l0_active_minus1) {
4297 pwt.luma_weight_l0_flag[i] = r.read_bit()?;
4298 }
4299
4300 if sps.chroma_array_type != 0 {
4301 for i in 0..=usize::from(hdr.num_ref_idx_l0_active_minus1) {
4302 pwt.chroma_weight_l0_flag[i] = r.read_bit()?;
4303 }
4304 }
4305
4306 for i in 0..=usize::from(hdr.num_ref_idx_l0_active_minus1) {
4307 if pwt.luma_weight_l0_flag[i] {
4308 pwt.delta_luma_weight_l0[i] = r.read_se_bounded(-128, 127)?;
4309 pwt.luma_offset_l0[i] = r.read_se_bounded(-128, 127)?;
4310 }
4311
4312 if pwt.chroma_weight_l0_flag[i] {
4313 for j in 0..2 {
4314 pwt.delta_chroma_weight_l0[i][j] = r.read_se_bounded(-128, 127)?;
4315 pwt.delta_chroma_offset_l0[i][j] = r.read_se_bounded(
4316 -4 * sps.wp_offset_half_range_c as i32,
4317 4 * sps.wp_offset_half_range_c as i32 - 1,
4318 )?;
4319 }
4320 }
4321 }
4322
4323 if hdr.type_.is_b() {
4324 for i in 0..=usize::from(hdr.num_ref_idx_l1_active_minus1) {
4325 pwt.luma_weight_l1_flag[i] = r.read_bit()?;
4326 }
4327
4328 if sps.chroma_format_idc != 0 {
4329 for i in 0..=usize::from(hdr.num_ref_idx_l1_active_minus1) {
4330 pwt.chroma_weight_l1_flag[i] = r.read_bit()?;
4331 }
4332 }
4333
4334 for i in 0..=usize::from(hdr.num_ref_idx_l1_active_minus1) {
4335 if pwt.luma_weight_l1_flag[i] {
4336 pwt.delta_luma_weight_l1[i] = r.read_se_bounded(-128, 127)?;
4337 pwt.luma_offset_l1[i] = r.read_se_bounded(-128, 127)?;
4338 }
4339
4340 if pwt.chroma_weight_l1_flag[i] {
4341 for j in 0..2 {
4342 pwt.delta_chroma_weight_l1[i][j] = r.read_se_bounded(-128, 127)?;
4343 pwt.delta_chroma_offset_l1[i][j] = r.read_se_bounded(
4344 -4 * sps.wp_offset_half_range_c as i32,
4345 4 * sps.wp_offset_half_range_c as i32 - 1,
4346 )?;
4347 }
4348 }
4349 }
4350 }
4351
4352 Ok(())
4353 }
4354
4355 fn parse_ref_pic_lists_modification(
4356 hdr: &mut SliceHeader,
4357 r: &mut BitReader,
4358 ) -> Result<(), String> {
4359 let rplm = &mut hdr.ref_pic_list_modification;
4360
4361 rplm.ref_pic_list_modification_flag_l0 = r.read_bit()?;
4362 if rplm.ref_pic_list_modification_flag_l0 {
4363 for _ in 0..=hdr.num_ref_idx_l0_active_minus1 {
4364 let num_bits = (hdr.num_pic_total_curr as f64).log2().ceil() as _;
4365
4366 let entry = r.read_bits(num_bits)?;
4367
4368 if entry > hdr.num_pic_total_curr - 1 {
4369 return Err(format!(
4370 "Invalid list_entry_l0 {}, expected at max NumPicTotalCurr - 1: {}",
4371 entry,
4372 hdr.num_pic_total_curr - 1
4373 ));
4374 }
4375
4376 rplm.list_entry_l0.push(entry);
4377 }
4378 }
4379
4380 if hdr.type_.is_b() {
4381 rplm.ref_pic_list_modification_flag_l1 = r.read_bit()?;
4382 if rplm.ref_pic_list_modification_flag_l1 {
4383 for _ in 0..=hdr.num_ref_idx_l1_active_minus1 {
4384 let num_bits = (hdr.num_pic_total_curr as f64).log2().ceil() as _;
4385
4386 let entry = r.read_bits(num_bits)?;
4387
4388 if entry > hdr.num_pic_total_curr - 1 {
4389 return Err(format!(
4390 "Invalid list_entry_l1 {}, expected at max NumPicTotalCurr - 1: {}",
4391 entry,
4392 hdr.num_pic_total_curr - 1
4393 ));
4394 }
4395
4396 rplm.list_entry_l1.push(entry);
4397 }
4398 }
4399 }
4400
4401 Ok(())
4402 }
4403
4404 /// Further sets default values given `sps` and `pps`.
4405 pub fn slice_header_set_defaults(hdr: &mut SliceHeader, sps: &Sps, pps: &Pps) {
4406 // Set some defaults that can't be defined in Default::default().
4407 hdr.deblocking_filter_disabled_flag = pps.deblocking_filter_disabled_flag;
4408 hdr.beta_offset_div2 = pps.beta_offset_div2;
4409 hdr.tc_offset_div2 = pps.tc_offset_div2;
4410 hdr.loop_filter_across_slices_enabled_flag = pps.loop_filter_across_slices_enabled_flag;
4411 hdr.curr_rps_idx = sps.num_short_term_ref_pic_sets;
4412 hdr.use_integer_mv_flag = sps.scc_extension.motion_vector_resolution_control_idc != 0;
4413 }
4414
4415 /// Parses a slice header from a slice NALU.
4416 pub fn parse_slice_header<'a>(&mut self, nalu: Nalu<'a>) -> Result<Slice<'a>, String> {
4417 if !matches!(
4418 nalu.header.type_,
4419 NaluType::TrailN
4420 | NaluType::TrailR
4421 | NaluType::TsaN
4422 | NaluType::TsaR
4423 | NaluType::StsaN
4424 | NaluType::StsaR
4425 | NaluType::RadlN
4426 | NaluType::RadlR
4427 | NaluType::RaslN
4428 | NaluType::RaslR
4429 | NaluType::BlaWLp
4430 | NaluType::BlaWRadl
4431 | NaluType::BlaNLp
4432 | NaluType::IdrWRadl
4433 | NaluType::IdrNLp
4434 | NaluType::CraNut,
4435 ) {
4436 return Err(format!("Invalid NALU type: {:?} is not a slice NALU", nalu.header.type_));
4437 }
4438
4439 let data = nalu.as_ref();
4440 let nalu_header = &nalu.header;
4441 let hdr_len = nalu_header.len();
4442 // Skip the header
4443 let mut r = BitReader::new(&data[hdr_len..], true);
4444
4445 let mut hdr =
4446 SliceHeader { first_slice_segment_in_pic_flag: r.read_bit()?, ..Default::default() };
4447
4448 if nalu.header.type_.is_irap() {
4449 hdr.no_output_of_prior_pics_flag = r.read_bit()?;
4450 }
4451
4452 hdr.pic_parameter_set_id = r.read_ue_max(63)?;
4453
4454 let pps = self.get_pps(hdr.pic_parameter_set_id).ok_or::<String>(format!(
4455 "Could not get PPS for pic_parameter_set_id {}",
4456 hdr.pic_parameter_set_id
4457 ))?;
4458
4459 let sps = &pps.sps;
4460
4461 Self::slice_header_set_defaults(&mut hdr, sps, pps);
4462
4463 if !hdr.first_slice_segment_in_pic_flag {
4464 if pps.dependent_slice_segments_enabled_flag {
4465 hdr.dependent_slice_segment_flag = r.read_bit()?;
4466 }
4467
4468 let num_bits = (sps.pic_size_in_ctbs_y as f64).log2().ceil() as _;
4469 hdr.segment_address = r.read_bits(num_bits)?;
4470
4471 if hdr.segment_address > sps.pic_size_in_ctbs_y - 1 {
4472 return Err(format!("Invalid slice_segment_address {}", hdr.segment_address));
4473 }
4474 }
4475
4476 if !hdr.dependent_slice_segment_flag {
4477 r.skip_bits(usize::from(pps.num_extra_slice_header_bits))?;
4478
4479 let slice_type: u32 = r.read_ue()?;
4480 hdr.type_ = SliceType::try_from(slice_type)?;
4481
4482 if pps.output_flag_present_flag {
4483 hdr.pic_output_flag = r.read_bit()?;
4484 }
4485
4486 if sps.separate_colour_plane_flag {
4487 hdr.colour_plane_id = r.read_bits(2)?;
4488 }
4489
4490 if !matches!(nalu_header.type_, NaluType::IdrWRadl | NaluType::IdrNLp) {
4491 let num_bits = usize::from(sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
4492 hdr.pic_order_cnt_lsb = r.read_bits(num_bits)?;
4493
4494 if u32::from(hdr.pic_order_cnt_lsb)
4495 > 2u32.pow(u32::from(sps.log2_max_pic_order_cnt_lsb_minus4 + 4))
4496 {
4497 return Err(format!("Invalid pic_order_cnt_lsb {}", hdr.pic_order_cnt_lsb));
4498 }
4499
4500 hdr.short_term_ref_pic_set_sps_flag = r.read_bit()?;
4501
4502 if !hdr.short_term_ref_pic_set_sps_flag {
4503 let epb_before = r.num_epb();
4504 let bits_left_before = r.num_bits_left();
4505
4506 let st_rps_idx = sps.num_short_term_ref_pic_sets;
4507
4508 Self::parse_short_term_ref_pic_set(
4509 sps,
4510 &mut hdr.short_term_ref_pic_set,
4511 &mut r,
4512 st_rps_idx,
4513 )?;
4514
4515 hdr.st_rps_bits = ((bits_left_before - r.num_bits_left())
4516 - 8 * (r.num_epb() - epb_before))
4517 as u32;
4518 } else if sps.num_short_term_ref_pic_sets > 1 {
4519 let num_bits = (sps.num_short_term_ref_pic_sets as f64).log2().ceil() as _;
4520 hdr.short_term_ref_pic_set_idx = r.read_bits(num_bits)?;
4521
4522 if hdr.short_term_ref_pic_set_idx > sps.num_short_term_ref_pic_sets - 1 {
4523 return Err(format!(
4524 "Invalid short_term_ref_pic_set_idx {}",
4525 hdr.short_term_ref_pic_set_idx
4526 ));
4527 }
4528 }
4529
4530 if hdr.short_term_ref_pic_set_sps_flag {
4531 hdr.curr_rps_idx = hdr.short_term_ref_pic_set_idx;
4532 }
4533
4534 if sps.long_term_ref_pics_present_flag {
4535 if sps.num_long_term_ref_pics_sps > 0 {
4536 hdr.num_long_term_sps =
4537 r.read_ue_max(u32::from(sps.num_long_term_ref_pics_sps))?;
4538 }
4539
4540 hdr.num_long_term_pics = r.read_ue_max(
4541 MAX_LONG_TERM_REF_PIC_SETS as u32 - u32::from(hdr.num_long_term_sps),
4542 )?;
4543
4544 let num_lt = hdr.num_long_term_sps + hdr.num_long_term_pics;
4545 // §7.4.7.1 keeps the sum inside the DPB, so the 16-entry
4546 // arrays below hold every conformant stream; the two reads
4547 // above can each say more than that on their own.
4548 if usize::from(num_lt) > hdr.poc_lsb_lt.len() {
4549 return Err(format!(
4550 "Invalid num_long_term_sps + num_long_term_pics {num_lt}"
4551 ));
4552 }
4553 for i in 0..usize::from(num_lt) {
4554 // The variables `PocLsbLt[ i ]` and `UsedByCurrPicLt[ i ]` are derived as follows:
4555 //
4556 // – If i is less than num_long_term_sps, `PocLsbLt[ i ]` is set equal to
4557 // lt_ref_pic_poc_lsb_sps[ `lt_idx_sps[ i ]` ] and `UsedByCurrPicLt[ i ]` is set equal
4558 // to used_by_curr_pic_lt_sps_flag[ `lt_idx_sps[ i ]` ].
4559 //
4560 // – Otherwise, `PocLsbLt[ i ]`
4561 // is set equal to `poc_lsb_lt[ i ]` and `UsedByCurrPicLt[ i ]` is set equal to
4562 // `used_by_curr_pic_lt_flag[ i ]`.
4563 if i < usize::from(hdr.num_long_term_sps) {
4564 if sps.num_long_term_ref_pics_sps > 1 {
4565 let num_bits =
4566 (sps.num_long_term_ref_pics_sps as f64).log2().ceil() as _;
4567
4568 hdr.lt_idx_sps[i] = r.read_bits(num_bits)?;
4569
4570 if hdr.lt_idx_sps[i] > sps.num_long_term_ref_pics_sps - 1 {
4571 return Err(format!(
4572 "Invalid lt_idx_sps[{}] {}",
4573 i, hdr.lt_idx_sps[i]
4574 ));
4575 }
4576 }
4577
4578 hdr.poc_lsb_lt[i] =
4579 sps.lt_ref_pic_poc_lsb_sps[usize::from(hdr.lt_idx_sps[i])];
4580 hdr.used_by_curr_pic_lt[i] =
4581 sps.used_by_curr_pic_lt_sps_flag[usize::from(hdr.lt_idx_sps[i])];
4582 } else {
4583 let num_bits = usize::from(sps.log2_max_pic_order_cnt_lsb_minus4) + 4;
4584 hdr.poc_lsb_lt[i] = r.read_bits(num_bits)?;
4585 hdr.used_by_curr_pic_lt[i] = r.read_bit()?;
4586 }
4587
4588 hdr.delta_poc_msb_present_flag[i] = r.read_bit()?;
4589 if hdr.delta_poc_msb_present_flag[i] {
4590 // The value of `delta_poc_msb_cycle_lt[ i ]` shall be
4591 // in the range of 0 to 2(32 −
4592 // log2_max_pic_order_cnt_lsb_minus4 − 4 ),
4593 // inclusive. When `delta_poc_msb_cycle_lt[ i ]` is
4594 // not present, it is inferred to be equal to 0.
4595 let max =
4596 2u32.pow(32 - u32::from(sps.log2_max_pic_order_cnt_lsb_minus4) - 4);
4597 hdr.delta_poc_msb_cycle_lt[i] = r.read_ue_max(max)?;
4598 }
4599 // Equation 7-52 (simplified)
4600 if i != 0 && i != usize::from(hdr.num_long_term_sps) {
4601 hdr.delta_poc_msb_cycle_lt[i] += hdr.delta_poc_msb_cycle_lt[i - 1];
4602 }
4603 }
4604 }
4605
4606 if sps.temporal_mvp_enabled_flag {
4607 hdr.temporal_mvp_enabled_flag = r.read_bit()?;
4608 }
4609 }
4610
4611 if sps.sample_adaptive_offset_enabled_flag {
4612 hdr.sao_luma_flag = r.read_bit()?;
4613 if sps.chroma_array_type != 0 {
4614 hdr.sao_chroma_flag = r.read_bit()?;
4615 }
4616 }
4617
4618 if hdr.type_.is_p() || hdr.type_.is_b() {
4619 hdr.num_ref_idx_active_override_flag = r.read_bit()?;
4620 if hdr.num_ref_idx_active_override_flag {
4621 hdr.num_ref_idx_l0_active_minus1 = r.read_ue_max(MAX_REF_IDX_ACTIVE - 1)?;
4622 if hdr.type_.is_b() {
4623 hdr.num_ref_idx_l1_active_minus1 = r.read_ue_max(MAX_REF_IDX_ACTIVE - 1)?;
4624 }
4625 } else {
4626 hdr.num_ref_idx_l0_active_minus1 = pps.num_ref_idx_l0_default_active_minus1;
4627 hdr.num_ref_idx_l1_active_minus1 = pps.num_ref_idx_l1_default_active_minus1;
4628 }
4629
4630 // 7-57
4631 let mut num_pic_total_curr = 0;
4632 let rps = if hdr.short_term_ref_pic_set_sps_flag {
4633 sps.short_term_ref_pic_set
4634 .get(usize::from(hdr.curr_rps_idx))
4635 .ok_or::<String>("Invalid RPS".into())?
4636 } else {
4637 &hdr.short_term_ref_pic_set
4638 };
4639
4640 for i in 0..usize::from(rps.num_negative_pics) {
4641 if rps.used_by_curr_pic_s0[i] {
4642 num_pic_total_curr += 1;
4643 }
4644 }
4645
4646 for i in 0..usize::from(rps.num_positive_pics) {
4647 if rps.used_by_curr_pic_s1[i] {
4648 num_pic_total_curr += 1;
4649 }
4650 }
4651
4652 for i in 0..usize::from(hdr.num_long_term_sps + hdr.num_long_term_pics) {
4653 if hdr.used_by_curr_pic_lt[i] {
4654 num_pic_total_curr += 1;
4655 }
4656 }
4657
4658 if pps.scc_extension.curr_pic_ref_enabled_flag {
4659 num_pic_total_curr += 1;
4660 }
4661
4662 hdr.num_pic_total_curr = num_pic_total_curr;
4663
4664 if pps.lists_modification_present_flag && hdr.num_pic_total_curr > 1 {
4665 Self::parse_ref_pic_lists_modification(&mut hdr, &mut r)?;
4666 }
4667
4668 if hdr.type_.is_b() {
4669 hdr.mvd_l1_zero_flag = r.read_bit()?;
4670 }
4671
4672 if pps.cabac_init_present_flag {
4673 hdr.cabac_init_flag = r.read_bit()?;
4674 }
4675
4676 if hdr.temporal_mvp_enabled_flag {
4677 if hdr.type_.is_b() {
4678 hdr.collocated_from_l0_flag = r.read_bit()?;
4679 }
4680
4681 if (hdr.collocated_from_l0_flag && hdr.num_ref_idx_l0_active_minus1 > 0)
4682 || (!hdr.collocated_from_l0_flag && hdr.num_ref_idx_l1_active_minus1 > 0)
4683 {
4684 let max = if (hdr.type_.is_p() || hdr.type_.is_b())
4685 && hdr.collocated_from_l0_flag
4686 {
4687 hdr.num_ref_idx_l0_active_minus1
4688 } else if hdr.type_.is_b() && !hdr.collocated_from_l0_flag {
4689 hdr.num_ref_idx_l1_active_minus1
4690 } else {
4691 return Err("Invalid value for collocated_ref_idx".into());
4692 };
4693
4694 {
4695 hdr.collocated_ref_idx = r.read_ue_max(u32::from(max))?;
4696 }
4697 }
4698 }
4699
4700 if (pps.weighted_pred_flag && hdr.type_.is_p())
4701 || (pps.weighted_bipred_flag && hdr.type_.is_b())
4702 {
4703 Self::parse_pred_weight_table(&mut hdr, &mut r, sps)?;
4704 }
4705
4706 hdr.five_minus_max_num_merge_cand = r.read_ue()?;
4707
4708 if sps.scc_extension.motion_vector_resolution_control_idc == 2 {
4709 hdr.use_integer_mv_flag = r.read_bit()?;
4710 }
4711 }
4712
4713 hdr.qp_delta = r.read_se_bounded(-87, 77)?;
4714
4715 let slice_qp_y = (26 + pps.init_qp_minus26 + hdr.qp_delta) as i32;
4716 if slice_qp_y < -(pps.qp_bd_offset_y as i32) || slice_qp_y > 51 {
4717 return Err(format!("Invalid slice_qp_delta: {}", hdr.qp_delta));
4718 }
4719
4720 if pps.slice_chroma_qp_offsets_present_flag {
4721 hdr.cb_qp_offset = r.read_se_bounded(-12, 12)?;
4722
4723 let qp_offset = pps.cb_qp_offset + hdr.cb_qp_offset;
4724 if !(-12..=12).contains(&qp_offset) {
4725 return Err(format!(
4726 "Invalid value for slice_cb_qp_offset: {}",
4727 hdr.cb_qp_offset
4728 ));
4729 }
4730
4731 hdr.cr_qp_offset = r.read_se_bounded(-12, 12)?;
4732
4733 let qp_offset = pps.cr_qp_offset + hdr.cr_qp_offset;
4734 if !(-12..=12).contains(&qp_offset) {
4735 return Err(format!(
4736 "Invalid value for slice_cr_qp_offset: {}",
4737 hdr.cr_qp_offset
4738 ));
4739 }
4740 }
4741
4742 if pps.scc_extension.slice_act_qp_offsets_present_flag {
4743 hdr.slice_act_y_qp_offset = r.read_se_bounded(-12, 12)?;
4744 hdr.slice_act_cb_qp_offset = r.read_se_bounded(-12, 12)?;
4745 hdr.slice_act_cr_qp_offset = r.read_se_bounded(-12, 12)?;
4746 }
4747
4748 if pps.range_extension.chroma_qp_offset_list_enabled_flag {
4749 hdr.cu_chroma_qp_offset_enabled_flag = r.read_bit()?;
4750 }
4751
4752 if pps.deblocking_filter_override_enabled_flag {
4753 hdr.deblocking_filter_override_flag = r.read_bit()?;
4754 }
4755
4756 if hdr.deblocking_filter_override_flag {
4757 hdr.deblocking_filter_disabled_flag = r.read_bit()?;
4758 if !hdr.deblocking_filter_disabled_flag {
4759 hdr.beta_offset_div2 = r.read_se_bounded(-6, 6)?;
4760 hdr.tc_offset_div2 = r.read_se_bounded(-6, 6)?;
4761 }
4762 }
4763
4764 if pps.loop_filter_across_slices_enabled_flag
4765 && (hdr.sao_luma_flag
4766 || hdr.sao_chroma_flag
4767 || !hdr.deblocking_filter_disabled_flag)
4768 {
4769 hdr.loop_filter_across_slices_enabled_flag = r.read_bit()?;
4770 }
4771 }
4772
4773 if pps.tiles_enabled_flag || pps.entropy_coding_sync_enabled_flag {
4774 let max = if !pps.tiles_enabled_flag && pps.entropy_coding_sync_enabled_flag {
4775 sps.pic_height_in_ctbs_y - 1
4776 } else if pps.tiles_enabled_flag && !pps.entropy_coding_sync_enabled_flag {
4777 // Widened first: the tile counts are `u8`, and §7.4.3.3.1 lets
4778 // this parser accept 20 columns by 22 rows, whose product is
4779 // 440 -- past a `u8` long before it is past the §7.4.7.1 bound.
4780 // Multiplied narrow it wrapped to 183 in release (every entry
4781 // point past the 184th refused on a conformant stream, which is
4782 // this bug's own black picture again) and panicked in debug.
4783 (u32::from(pps.num_tile_columns_minus1) + 1)
4784 * (u32::from(pps.num_tile_rows_minus1) + 1)
4785 - 1
4786 } else {
4787 (u32::from(pps.num_tile_columns_minus1) + 1) * sps.pic_height_in_ctbs_y - 1
4788 };
4789
4790 hdr.num_entry_point_offsets = r.read_ue_max(max)?;
4791 if hdr.num_entry_point_offsets > 0 {
4792 hdr.offset_len_minus1 = r.read_ue_max(31)?;
4793 let num_bits = usize::from(hdr.offset_len_minus1 + 1);
4794 hdr.entry_point_offset_minus1.clear();
4795 for _ in 0..hdr.num_entry_point_offsets {
4796 hdr.entry_point_offset_minus1.push(r.read_bits(num_bits)?);
4797 }
4798 }
4799 }
4800
4801 if pps.slice_segment_header_extension_present_flag {
4802 let segment_header_extension_length = r.read_ue_max(256)?;
4803 for _ in 0..segment_header_extension_length {
4804 r.skip_bits(8)?; // slice_segment_header_extension_data_byte[i]
4805 }
4806 }
4807
4808 // byte_alignment()
4809 r.skip_bits(1)?; // Alignment bit
4810 let num_bits = r.num_bits_left() % 8;
4811 r.skip_bits(num_bits)?;
4812
4813 let epb = r.num_epb();
4814 hdr.header_bit_size = ((nalu.size - epb) * 8 - r.num_bits_left()) as u32;
4815
4816 hdr.n_emulation_prevention_bytes = epb as u32;
4817
4818 log::debug!("Parsed slice {:?}, NAL size was {}", nalu_header.type_, nalu.size);
4819
4820 Ok(Slice { header: hdr, nalu })
4821 }
4822
4823 /// Returns a previously parsed vps given `vps_id`, if any.
4824 pub fn get_vps(&self, vps_id: u8) -> Option<&Rc<Vps>> {
4825 self.active_vpses.get(&vps_id)
4826 }
4827
4828 /// Returns a previously parsed sps given `sps_id`, if any.
4829 pub fn get_sps(&self, sps_id: u8) -> Option<&Rc<Sps>> {
4830 self.active_spses.get(&sps_id)
4831 }
4832
4833 /// Returns a previously parsed pps given `pps_id`, if any.
4834 pub fn get_pps(&self, pps_id: u8) -> Option<&Rc<Pps>> {
4835 self.active_ppses.get(&pps_id)
4836 }
4837}
4838
4839#[cfg(test)]
4840mod tests {
4841 use std::io::Cursor;
4842
4843 use crate::codec::h264::nalu::Nalu;
4844 use crate::codec::h265::parser::Level;
4845 use crate::codec::h265::parser::NaluHeader;
4846 use crate::codec::h265::parser::NaluType;
4847 use crate::codec::h265::parser::Parser;
4848 use crate::codec::h265::parser::SliceType;
4849
4850 const STREAM_BEAR: &[u8] = include_bytes!("test_data/bear.h265");
4851 const STREAM_BEAR_NUM_NALUS: usize = 35;
4852
4853 const STREAM_BBB: &[u8] = include_bytes!("test_data/bbb.h265");
4854 const STREAM_BBB_NUM_NALUS: usize = 64;
4855
4856 const STREAM_TEST25FPS: &[u8] = include_bytes!("test_data/test-25fps.h265");
4857 const STREAM_TEST25FPS_NUM_NALUS: usize = 254;
4858
4859 const STREAM_TEST_25_FPS_SLICE_0: &[u8] =
4860 include_bytes!("test_data/test-25fps-h265-slice-data-0.bin");
4861 const STREAM_TEST_25_FPS_SLICE_1: &[u8] =
4862 include_bytes!("test_data/test-25fps-h265-slice-data-1.bin");
4863
4864 fn dispatch_parse_call(parser: &mut Parser, nalu: Nalu<NaluHeader>) -> Result<(), String> {
4865 match nalu.header.type_ {
4866 NaluType::TrailN
4867 | NaluType::TrailR
4868 | NaluType::TsaN
4869 | NaluType::TsaR
4870 | NaluType::StsaN
4871 | NaluType::StsaR
4872 | NaluType::RadlN
4873 | NaluType::RadlR
4874 | NaluType::RaslN
4875 | NaluType::RaslR
4876 | NaluType::BlaWLp
4877 | NaluType::BlaWRadl
4878 | NaluType::BlaNLp
4879 | NaluType::IdrWRadl
4880 | NaluType::IdrNLp
4881 | NaluType::CraNut => {
4882 parser.parse_slice_header(nalu).unwrap();
4883 }
4884 NaluType::VpsNut => {
4885 parser.parse_vps(&nalu).unwrap();
4886 }
4887 NaluType::SpsNut => {
4888 parser.parse_sps(&nalu).unwrap();
4889 }
4890 NaluType::PpsNut => {
4891 parser.parse_pps(&nalu).unwrap();
4892 }
4893 _ => { /* ignore */ }
4894 }
4895 Ok(())
4896 }
4897
4898 fn find_nalu_by_type(
4899 bitstream: &[u8],
4900 nalu_type: NaluType,
4901 mut nskip: i32,
4902 ) -> Option<Nalu<NaluHeader>> {
4903 let mut cursor = Cursor::new(bitstream);
4904 while let Ok(nalu) = Nalu::<NaluHeader>::next(&mut cursor) {
4905 if nalu.header.type_ == nalu_type {
4906 if nskip == 0 {
4907 return Some(nalu);
4908 } else {
4909 nskip -= 1;
4910 }
4911 }
4912 }
4913
4914 None
4915 }
4916
4917 /// This test is adapted from chromium, available at media/video/h265_parser_unittest.cc
4918 #[test]
4919 fn parse_nalus_from_stream_file() {
4920 let mut cursor = Cursor::new(STREAM_BEAR);
4921 let mut num_nalus = 0;
4922 while Nalu::<NaluHeader>::next(&mut cursor).is_ok() {
4923 num_nalus += 1;
4924 }
4925
4926 assert_eq!(num_nalus, STREAM_BEAR_NUM_NALUS);
4927
4928 let mut cursor = Cursor::new(STREAM_BBB);
4929 let mut num_nalus = 0;
4930 while Nalu::<NaluHeader>::next(&mut cursor).is_ok() {
4931 num_nalus += 1;
4932 }
4933
4934 assert_eq!(num_nalus, STREAM_BBB_NUM_NALUS);
4935
4936 let mut cursor = Cursor::new(STREAM_TEST25FPS);
4937 let mut num_nalus = 0;
4938 while Nalu::<NaluHeader>::next(&mut cursor).is_ok() {
4939 num_nalus += 1;
4940 }
4941
4942 assert_eq!(num_nalus, STREAM_TEST25FPS_NUM_NALUS);
4943 }
4944
4945 /// Parse the syntax, making sure we can parse the files without crashing.
4946 /// Does not check whether the parsed values are correct.
4947 #[test]
4948 fn parse_syntax_from_nals() {
4949 let mut cursor = Cursor::new(STREAM_BBB);
4950 let mut parser = Parser::default();
4951
4952 while let Ok(nalu) = Nalu::<NaluHeader>::next(&mut cursor) {
4953 dispatch_parse_call(&mut parser, nalu).unwrap();
4954 }
4955
4956 let mut cursor = Cursor::new(STREAM_BEAR);
4957 let mut parser = Parser::default();
4958
4959 while let Ok(nalu) = Nalu::<NaluHeader>::next(&mut cursor) {
4960 dispatch_parse_call(&mut parser, nalu).unwrap();
4961 }
4962
4963 let mut cursor = Cursor::new(STREAM_TEST25FPS);
4964 let mut parser = Parser::default();
4965
4966 while let Ok(nalu) = Nalu::<NaluHeader>::next(&mut cursor) {
4967 dispatch_parse_call(&mut parser, nalu).unwrap();
4968 }
4969 }
4970
4971 /// Adapted from Chromium (media/video/h265_parser_unittest.cc::VpsParsing())
4972 #[test]
4973 fn chromium_vps_parsing() {
4974 let mut cursor = Cursor::new(STREAM_BEAR);
4975 let mut parser = Parser::default();
4976
4977 let vps_nalu = Nalu::<NaluHeader>::next(&mut cursor).unwrap();
4978 let vps = parser.parse_vps(&vps_nalu).unwrap();
4979
4980 assert!(vps.base_layer_internal_flag);
4981 assert!(vps.base_layer_available_flag);
4982 assert_eq!(vps.max_layers_minus1, 0);
4983 assert_eq!(vps.max_sub_layers_minus1, 0);
4984 assert!(vps.temporal_id_nesting_flag);
4985 assert_eq!(vps.profile_tier_level.general_profile_idc, 1);
4986 assert_eq!(vps.profile_tier_level.general_level_idc, Level::L2);
4987 assert_eq!(vps.max_dec_pic_buffering_minus1[0], 4);
4988 assert_eq!(vps.max_num_reorder_pics[0], 2);
4989 assert_eq!(vps.max_latency_increase_plus1[0], 0);
4990 for i in 1..7 {
4991 assert_eq!(vps.max_dec_pic_buffering_minus1[i], 0);
4992 assert_eq!(vps.max_num_reorder_pics[i], 0);
4993 assert_eq!(vps.max_latency_increase_plus1[i], 0);
4994 }
4995 assert_eq!(vps.max_layer_id, 0);
4996 assert_eq!(vps.num_layer_sets_minus1, 0);
4997 assert!(!vps.timing_info_present_flag);
4998 }
4999
5000 /// Adapted from Chromium (media/video/h265_parser_unittest.cc::SpsParsing())
5001 #[test]
5002 fn chromium_sps_parsing() {
5003 let mut parser = Parser::default();
5004 let sps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::SpsNut, 0).unwrap();
5005 let sps = parser.parse_sps(&sps_nalu).unwrap();
5006
5007 assert_eq!(sps.max_sub_layers_minus1, 0);
5008 assert_eq!(sps.profile_tier_level.general_profile_idc, 1);
5009 assert_eq!(sps.profile_tier_level.general_level_idc, Level::L2);
5010 assert_eq!(sps.seq_parameter_set_id, 0);
5011 assert_eq!(sps.chroma_format_idc, 1);
5012 assert!(!sps.separate_colour_plane_flag);
5013 assert_eq!(sps.pic_width_in_luma_samples, 320);
5014 assert_eq!(sps.pic_height_in_luma_samples, 184);
5015 assert_eq!(sps.conf_win_left_offset, 0);
5016 assert_eq!(sps.conf_win_right_offset, 0);
5017 assert_eq!(sps.conf_win_top_offset, 0);
5018 assert_eq!(sps.conf_win_bottom_offset, 2);
5019 assert_eq!(sps.bit_depth_luma_minus8, 0);
5020 assert_eq!(sps.bit_depth_chroma_minus8, 0);
5021 assert_eq!(sps.log2_max_pic_order_cnt_lsb_minus4, 4);
5022 assert_eq!(sps.max_dec_pic_buffering_minus1[0], 4);
5023 assert_eq!(sps.max_num_reorder_pics[0], 2);
5024 assert_eq!(sps.max_latency_increase_plus1[0], 0);
5025 for i in 1..7 {
5026 assert_eq!(sps.max_dec_pic_buffering_minus1[i], 0);
5027 assert_eq!(sps.max_num_reorder_pics[i], 0);
5028 assert_eq!(sps.max_latency_increase_plus1[i], 0);
5029 }
5030 assert_eq!(sps.log2_min_luma_coding_block_size_minus3, 0);
5031 assert_eq!(sps.log2_diff_max_min_luma_coding_block_size, 3);
5032 assert_eq!(sps.log2_min_luma_transform_block_size_minus2, 0);
5033 assert_eq!(sps.log2_diff_max_min_luma_transform_block_size, 3);
5034 assert_eq!(sps.max_transform_hierarchy_depth_inter, 0);
5035 assert_eq!(sps.max_transform_hierarchy_depth_intra, 0);
5036 assert!(!sps.scaling_list_enabled_flag);
5037 assert!(!sps.scaling_list_data_present_flag);
5038 assert!(!sps.amp_enabled_flag);
5039 assert!(sps.sample_adaptive_offset_enabled_flag);
5040 assert!(!sps.pcm_enabled_flag);
5041 assert_eq!(sps.pcm_sample_bit_depth_luma_minus1, 0);
5042 assert_eq!(sps.pcm_sample_bit_depth_chroma_minus1, 0);
5043 assert_eq!(sps.log2_min_pcm_luma_coding_block_size_minus3, 0);
5044 assert_eq!(sps.log2_diff_max_min_pcm_luma_coding_block_size, 0);
5045 assert!(!sps.pcm_loop_filter_disabled_flag);
5046 assert_eq!(sps.num_short_term_ref_pic_sets, 0);
5047 assert_eq!(sps.num_long_term_ref_pics_sps, 0);
5048 assert!(sps.temporal_mvp_enabled_flag);
5049 assert!(sps.strong_intra_smoothing_enabled_flag);
5050 assert_eq!(sps.vui_parameters.sar_width, 0);
5051 assert_eq!(sps.vui_parameters.sar_height, 0);
5052 assert!(!sps.vui_parameters.video_full_range_flag);
5053 assert!(!sps.vui_parameters.colour_description_present_flag);
5054
5055 // Note: the original test has 0 for the three variables below, but they
5056 // have valid defaults in the spec (i.e.: 2).
5057 assert_eq!(sps.vui_parameters.colour_primaries, 2);
5058 assert_eq!(sps.vui_parameters.transfer_characteristics, 2);
5059 assert_eq!(sps.vui_parameters.matrix_coeffs, 2);
5060
5061 assert_eq!(sps.vui_parameters.def_disp_win_left_offset, 0);
5062 assert_eq!(sps.vui_parameters.def_disp_win_right_offset, 0);
5063 assert_eq!(sps.vui_parameters.def_disp_win_top_offset, 0);
5064 assert_eq!(sps.vui_parameters.def_disp_win_bottom_offset, 0);
5065 }
5066
5067 /// Adapted from Chromium (media/video/h265_parser_unittest.cc::PpsParsing())
5068 #[test]
5069 fn chromium_pps_parsing() {
5070 let mut parser = Parser::default();
5071
5072 // Have to parse the SPS to set up the parser's internal state.
5073 let sps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::SpsNut, 0).unwrap();
5074 parser.parse_sps(&sps_nalu).unwrap();
5075
5076 let pps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::PpsNut, 0).unwrap();
5077 let pps = parser.parse_pps(&pps_nalu).unwrap();
5078
5079 assert_eq!(pps.pic_parameter_set_id, 0);
5080 assert_eq!(pps.seq_parameter_set_id, 0);
5081 assert!(!pps.dependent_slice_segments_enabled_flag);
5082 assert!(!pps.output_flag_present_flag);
5083 assert_eq!(pps.num_extra_slice_header_bits, 0);
5084 assert!(pps.sign_data_hiding_enabled_flag);
5085 assert!(!pps.cabac_init_present_flag);
5086 assert_eq!(pps.num_ref_idx_l0_default_active_minus1, 0);
5087 assert_eq!(pps.num_ref_idx_l1_default_active_minus1, 0);
5088 assert_eq!(pps.init_qp_minus26, 0);
5089 assert!(!pps.constrained_intra_pred_flag);
5090 assert!(!pps.transform_skip_enabled_flag);
5091 assert!(pps.cu_qp_delta_enabled_flag);
5092 assert_eq!(pps.diff_cu_qp_delta_depth, 0);
5093 assert_eq!(pps.cb_qp_offset, 0);
5094 assert_eq!(pps.cr_qp_offset, 0);
5095 assert!(!pps.slice_chroma_qp_offsets_present_flag);
5096 assert!(pps.weighted_pred_flag);
5097 assert!(!pps.weighted_bipred_flag);
5098 assert!(!pps.transquant_bypass_enabled_flag);
5099 assert!(!pps.tiles_enabled_flag);
5100 assert!(pps.entropy_coding_sync_enabled_flag);
5101 assert!(pps.loop_filter_across_tiles_enabled_flag);
5102 assert!(!pps.scaling_list_data_present_flag);
5103 assert!(!pps.lists_modification_present_flag);
5104 assert_eq!(pps.log2_parallel_merge_level_minus2, 0);
5105 assert!(!pps.slice_segment_header_extension_present_flag);
5106 }
5107
5108 /// Adapted from Chromium (media/video/h265_parser_unittest.cc::SliceHeaderParsing())
5109 #[test]
5110 fn chromium_slice_header_parsing() {
5111 let mut parser = Parser::default();
5112
5113 // Have to parse the SPS/VPS/PPS to set up the parser's internal state.
5114 let vps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::VpsNut, 0).unwrap();
5115 parser.parse_vps(&vps_nalu).unwrap();
5116
5117 let sps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::SpsNut, 0).unwrap();
5118 parser.parse_sps(&sps_nalu).unwrap();
5119
5120 let pps_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::PpsNut, 0).unwrap();
5121 parser.parse_pps(&pps_nalu).unwrap();
5122
5123 // Just like the Chromium test, do an IDR slice, then a non IDR slice.
5124 let slice_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::IdrWRadl, 0).unwrap();
5125 let slice = parser.parse_slice_header(slice_nalu).unwrap();
5126 let hdr = &slice.header;
5127 assert!(hdr.first_slice_segment_in_pic_flag);
5128 assert!(!hdr.no_output_of_prior_pics_flag);
5129 assert_eq!(hdr.pic_parameter_set_id, 0);
5130 assert!(!hdr.dependent_slice_segment_flag);
5131 assert_eq!(hdr.type_, SliceType::I);
5132 assert!(hdr.sao_luma_flag);
5133 assert!(hdr.sao_chroma_flag);
5134 assert_eq!(hdr.qp_delta, 8);
5135 assert!(hdr.loop_filter_across_slices_enabled_flag);
5136
5137 let slice_nalu = find_nalu_by_type(STREAM_BEAR, NaluType::TrailR, 0).unwrap();
5138 let slice = parser.parse_slice_header(slice_nalu).unwrap();
5139 let hdr = &slice.header;
5140 assert!(hdr.first_slice_segment_in_pic_flag);
5141 assert_eq!(hdr.pic_parameter_set_id, 0);
5142 assert!(!hdr.dependent_slice_segment_flag);
5143 assert_eq!(hdr.type_, SliceType::P);
5144 assert_eq!(hdr.pic_order_cnt_lsb, 4);
5145 assert!(!hdr.short_term_ref_pic_set_sps_flag);
5146 assert_eq!(hdr.short_term_ref_pic_set.num_negative_pics, 1);
5147 assert_eq!(hdr.short_term_ref_pic_set.num_positive_pics, 0);
5148 assert_eq!(hdr.short_term_ref_pic_set.delta_poc_s0[0], -4);
5149 assert!(hdr.short_term_ref_pic_set.used_by_curr_pic_s0[0]);
5150 assert!(hdr.temporal_mvp_enabled_flag);
5151 assert!(hdr.sao_luma_flag);
5152 assert!(hdr.sao_chroma_flag);
5153 assert!(!hdr.num_ref_idx_active_override_flag);
5154 assert_eq!(hdr.pred_weight_table.luma_log2_weight_denom, 0);
5155 assert_eq!(hdr.pred_weight_table.delta_chroma_log2_weight_denom, 7);
5156 assert_eq!(hdr.pred_weight_table.delta_luma_weight_l0[0], 0);
5157 assert_eq!(hdr.pred_weight_table.luma_offset_l0[0], -2);
5158 assert_eq!(hdr.pred_weight_table.delta_chroma_weight_l0[0][0], -9);
5159 assert_eq!(hdr.pred_weight_table.delta_chroma_weight_l0[0][1], -9);
5160 assert_eq!(hdr.pred_weight_table.delta_chroma_offset_l0[0][0], 0);
5161 assert_eq!(hdr.pred_weight_table.delta_chroma_offset_l0[0][1], 0);
5162 assert_eq!(hdr.five_minus_max_num_merge_cand, 3);
5163 assert_eq!(hdr.qp_delta, 8);
5164 assert!(hdr.loop_filter_across_slices_enabled_flag);
5165 }
5166
5167 /// A custom test for VPS parsing with data manually extracted from
5168 /// GStreamer using GDB.
5169 #[test]
5170 fn test25fps_vps_header_parsing() {
5171 let mut cursor = Cursor::new(STREAM_TEST25FPS);
5172 let mut parser = Parser::default();
5173
5174 let vps_nalu = Nalu::<NaluHeader>::next(&mut cursor).unwrap();
5175 let vps = parser.parse_vps(&vps_nalu).unwrap();
5176 assert!(vps.base_layer_internal_flag);
5177 assert!(vps.base_layer_available_flag);
5178 assert_eq!(vps.max_layers_minus1, 0);
5179 assert_eq!(vps.max_sub_layers_minus1, 0);
5180 assert!(vps.temporal_id_nesting_flag);
5181 assert_eq!(vps.profile_tier_level.general_profile_space, 0);
5182 assert!(!vps.profile_tier_level.general_tier_flag);
5183 assert_eq!(vps.profile_tier_level.general_profile_idc, 1);
5184 for i in 0..32 {
5185 let val = i == 1 || i == 2;
5186 assert_eq!(vps.profile_tier_level.general_profile_compatibility_flag[i], val);
5187 }
5188 assert!(vps.profile_tier_level.general_progressive_source_flag);
5189 assert!(!vps.profile_tier_level.general_interlaced_source_flag);
5190 assert!(!vps.profile_tier_level.general_non_packed_constraint_flag,);
5191 assert!(vps.profile_tier_level.general_frame_only_constraint_flag,);
5192 assert!(!vps.profile_tier_level.general_max_12bit_constraint_flag,);
5193 assert!(!vps.profile_tier_level.general_max_10bit_constraint_flag,);
5194 assert!(!vps.profile_tier_level.general_max_8bit_constraint_flag,);
5195 assert!(!vps.profile_tier_level.general_max_422chroma_constraint_flag,);
5196 assert!(!vps.profile_tier_level.general_max_420chroma_constraint_flag,);
5197 assert!(!vps.profile_tier_level.general_max_monochrome_constraint_flag,);
5198 assert!(!vps.profile_tier_level.general_intra_constraint_flag);
5199 assert!(!vps.profile_tier_level.general_one_picture_only_constraint_flag,);
5200 assert!(!vps.profile_tier_level.general_lower_bit_rate_constraint_flag,);
5201 assert!(!vps.profile_tier_level.general_max_14bit_constraint_flag,);
5202 assert_eq!(vps.profile_tier_level.general_level_idc, Level::L2);
5203
5204 assert!(vps.sub_layer_ordering_info_present_flag);
5205 assert_eq!(vps.max_dec_pic_buffering_minus1[0], 4);
5206 assert_eq!(vps.max_num_reorder_pics[0], 2);
5207 assert_eq!(vps.max_latency_increase_plus1[0], 5);
5208 for i in 1..7 {
5209 assert_eq!(vps.max_dec_pic_buffering_minus1[i], 0);
5210 assert_eq!(vps.max_num_reorder_pics[i], 0);
5211 assert_eq!(vps.max_latency_increase_plus1[i], 0);
5212 }
5213
5214 assert_eq!(vps.max_layer_id, 0);
5215 assert_eq!(vps.num_layer_sets_minus1, 0);
5216 assert!(!vps.timing_info_present_flag);
5217 assert_eq!(vps.num_units_in_tick, 0);
5218 assert_eq!(vps.time_scale, 0);
5219 assert!(!vps.poc_proportional_to_timing_flag);
5220 assert_eq!(vps.num_ticks_poc_diff_one_minus1, 0);
5221 assert_eq!(vps.num_hrd_parameters, 0);
5222 }
5223
5224 /// A custom test for SPS parsing with data manually extracted from
5225 /// GStreamer using GDB.
5226 #[test]
5227 fn test25fps_sps_header_parsing() {
5228 let mut parser = Parser::default();
5229
5230 let sps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::SpsNut, 0).unwrap();
5231 let sps = parser.parse_sps(&sps_nalu).unwrap();
5232
5233 assert_eq!(sps.max_sub_layers_minus1, 0);
5234
5235 assert_eq!(sps.profile_tier_level.general_profile_space, 0);
5236 assert!(!sps.profile_tier_level.general_tier_flag);
5237 assert_eq!(sps.profile_tier_level.general_profile_idc, 1);
5238 for i in 0..32 {
5239 let val = i == 1 || i == 2;
5240 assert_eq!(sps.profile_tier_level.general_profile_compatibility_flag[i], val);
5241 }
5242 assert!(sps.profile_tier_level.general_progressive_source_flag);
5243 assert!(!sps.profile_tier_level.general_interlaced_source_flag);
5244 assert!(!sps.profile_tier_level.general_non_packed_constraint_flag,);
5245 assert!(sps.profile_tier_level.general_frame_only_constraint_flag,);
5246 assert!(!sps.profile_tier_level.general_max_12bit_constraint_flag,);
5247 assert!(!sps.profile_tier_level.general_max_10bit_constraint_flag,);
5248 assert!(!sps.profile_tier_level.general_max_8bit_constraint_flag,);
5249 assert!(!sps.profile_tier_level.general_max_422chroma_constraint_flag,);
5250 assert!(!sps.profile_tier_level.general_max_420chroma_constraint_flag,);
5251 assert!(!sps.profile_tier_level.general_max_monochrome_constraint_flag,);
5252 assert!(!sps.profile_tier_level.general_intra_constraint_flag);
5253 assert!(!sps.profile_tier_level.general_one_picture_only_constraint_flag,);
5254 assert!(!sps.profile_tier_level.general_lower_bit_rate_constraint_flag,);
5255 assert!(!sps.profile_tier_level.general_max_14bit_constraint_flag,);
5256 assert_eq!(sps.profile_tier_level.general_level_idc, Level::L2);
5257
5258 assert_eq!(sps.seq_parameter_set_id, 0);
5259 assert_eq!(sps.chroma_format_idc, 1);
5260 assert!(!sps.separate_colour_plane_flag);
5261 assert_eq!(sps.pic_width_in_luma_samples, 320);
5262 assert_eq!(sps.pic_height_in_luma_samples, 240);
5263 assert_eq!(sps.conf_win_left_offset, 0);
5264 assert_eq!(sps.conf_win_right_offset, 0);
5265 assert_eq!(sps.conf_win_top_offset, 0);
5266 assert_eq!(sps.conf_win_bottom_offset, 0);
5267 assert_eq!(sps.bit_depth_luma_minus8, 0);
5268 assert_eq!(sps.bit_depth_chroma_minus8, 0);
5269 assert_eq!(sps.log2_max_pic_order_cnt_lsb_minus4, 4);
5270 assert!(sps.sub_layer_ordering_info_present_flag);
5271 assert_eq!(sps.max_dec_pic_buffering_minus1[0], 4);
5272 assert_eq!(sps.max_num_reorder_pics[0], 2);
5273 assert_eq!(sps.max_latency_increase_plus1[0], 5);
5274 for i in 1..7 {
5275 assert_eq!(sps.max_dec_pic_buffering_minus1[i], 0);
5276 assert_eq!(sps.max_num_reorder_pics[i], 0);
5277 assert_eq!(sps.max_latency_increase_plus1[i], 0);
5278 }
5279 assert_eq!(sps.log2_min_luma_coding_block_size_minus3, 0);
5280 assert_eq!(sps.log2_diff_max_min_luma_coding_block_size, 3);
5281 assert_eq!(sps.log2_min_luma_transform_block_size_minus2, 0);
5282 assert_eq!(sps.log2_diff_max_min_luma_transform_block_size, 3);
5283 assert_eq!(sps.max_transform_hierarchy_depth_inter, 0);
5284 assert_eq!(sps.max_transform_hierarchy_depth_intra, 0);
5285 assert!(!sps.scaling_list_enabled_flag);
5286 assert!(!sps.scaling_list_data_present_flag);
5287 assert!(!sps.amp_enabled_flag);
5288 assert!(sps.sample_adaptive_offset_enabled_flag);
5289 assert!(!sps.pcm_enabled_flag);
5290 assert_eq!(sps.pcm_sample_bit_depth_luma_minus1, 0);
5291 assert_eq!(sps.pcm_sample_bit_depth_chroma_minus1, 0);
5292 assert_eq!(sps.log2_min_pcm_luma_coding_block_size_minus3, 0);
5293 assert_eq!(sps.log2_diff_max_min_pcm_luma_coding_block_size, 0);
5294 assert!(!sps.pcm_loop_filter_disabled_flag);
5295 assert_eq!(sps.num_short_term_ref_pic_sets, 0);
5296 assert_eq!(sps.num_long_term_ref_pics_sps, 0);
5297 assert!(sps.temporal_mvp_enabled_flag);
5298 assert!(sps.strong_intra_smoothing_enabled_flag);
5299 assert_eq!(sps.vui_parameters.sar_width, 0);
5300 assert_eq!(sps.vui_parameters.sar_height, 0);
5301 assert!(!sps.vui_parameters.video_full_range_flag);
5302 assert!(!sps.vui_parameters.colour_description_present_flag);
5303 assert!(sps.vui_parameters.video_signal_type_present_flag);
5304 assert!(sps.vui_parameters.timing_info_present_flag);
5305 assert_eq!(sps.vui_parameters.num_units_in_tick, 1);
5306 assert_eq!(sps.vui_parameters.time_scale, 25);
5307 assert!(!sps.vui_parameters.poc_proportional_to_timing_flag);
5308 assert_eq!(sps.vui_parameters.num_ticks_poc_diff_one_minus1, 0);
5309 assert!(!sps.vui_parameters.hrd_parameters_present_flag);
5310 assert_eq!(sps.vui_parameters.colour_primaries, 2);
5311 assert_eq!(sps.vui_parameters.transfer_characteristics, 2);
5312 assert_eq!(sps.vui_parameters.matrix_coeffs, 2);
5313 assert_eq!(sps.vui_parameters.def_disp_win_left_offset, 0);
5314 assert_eq!(sps.vui_parameters.def_disp_win_right_offset, 0);
5315 assert_eq!(sps.vui_parameters.def_disp_win_top_offset, 0);
5316 assert_eq!(sps.vui_parameters.def_disp_win_bottom_offset, 0);
5317 }
5318
5319 /// A custom test for PPS parsing with data manually extracted from
5320 /// GStreamer using GDB.
5321 #[test]
5322 fn test25fps_pps_header_parsing() {
5323 let mut parser = Parser::default();
5324
5325 let sps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::SpsNut, 0).unwrap();
5326 parser.parse_sps(&sps_nalu).unwrap();
5327
5328 let pps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::PpsNut, 0).unwrap();
5329 let pps = parser.parse_pps(&pps_nalu).unwrap();
5330
5331 assert!(!pps.dependent_slice_segments_enabled_flag);
5332 assert!(!pps.output_flag_present_flag);
5333 assert_eq!(pps.num_extra_slice_header_bits, 0);
5334 assert!(pps.sign_data_hiding_enabled_flag);
5335 assert!(!pps.cabac_init_present_flag);
5336 assert_eq!(pps.num_ref_idx_l0_default_active_minus1, 0);
5337 assert_eq!(pps.num_ref_idx_l1_default_active_minus1, 0);
5338 assert_eq!(pps.init_qp_minus26, 0);
5339 assert!(!pps.constrained_intra_pred_flag);
5340 assert!(!pps.transform_skip_enabled_flag);
5341 assert!(pps.cu_qp_delta_enabled_flag);
5342 assert_eq!(pps.diff_cu_qp_delta_depth, 1);
5343 assert_eq!(pps.cb_qp_offset, 0);
5344 assert_eq!(pps.cr_qp_offset, 0);
5345 assert!(!pps.slice_chroma_qp_offsets_present_flag);
5346 assert!(pps.weighted_pred_flag);
5347 assert!(!pps.weighted_bipred_flag);
5348 assert!(!pps.transquant_bypass_enabled_flag);
5349 assert!(!pps.tiles_enabled_flag);
5350 assert!(pps.entropy_coding_sync_enabled_flag);
5351 assert_eq!(pps.num_tile_rows_minus1, 0);
5352 assert_eq!(pps.num_tile_columns_minus1, 0);
5353 assert!(pps.uniform_spacing_flag);
5354 assert_eq!(pps.column_width_minus1, [0; 19]);
5355 assert_eq!(pps.row_height_minus1, [0; 21]);
5356 assert!(pps.loop_filter_across_slices_enabled_flag);
5357 assert!(pps.loop_filter_across_tiles_enabled_flag);
5358 assert!(!pps.deblocking_filter_control_present_flag);
5359 assert!(!pps.deblocking_filter_override_enabled_flag);
5360 assert!(!pps.deblocking_filter_disabled_flag);
5361 assert_eq!(pps.beta_offset_div2, 0);
5362 assert_eq!(pps.tc_offset_div2, 0);
5363 assert!(!pps.lists_modification_present_flag);
5364 assert_eq!(pps.log2_parallel_merge_level_minus2, 0);
5365 assert!(!pps.slice_segment_header_extension_present_flag);
5366 assert!(!pps.extension_present_flag);
5367 }
5368
5369 /// A custom test for slice header parsing with data manually extracted from
5370 /// GStreamer using GDB.
5371 #[test]
5372 fn test25fps_slice_header_parsing() {
5373 let mut parser = Parser::default();
5374
5375 // Have to parse the SPS/VPS/PPS to set up the parser's internal state.
5376 let vps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::VpsNut, 0).unwrap();
5377 parser.parse_vps(&vps_nalu).unwrap();
5378
5379 let sps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::SpsNut, 0).unwrap();
5380 parser.parse_sps(&sps_nalu).unwrap();
5381
5382 let pps_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::PpsNut, 0).unwrap();
5383 parser.parse_pps(&pps_nalu).unwrap();
5384
5385 let slice_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::IdrNLp, 0).unwrap();
5386 let slice = parser.parse_slice_header(slice_nalu).unwrap();
5387 let hdr = &slice.header;
5388
5389 assert!(hdr.first_slice_segment_in_pic_flag);
5390 assert!(!hdr.no_output_of_prior_pics_flag);
5391 assert!(!hdr.dependent_slice_segment_flag);
5392 assert_eq!(hdr.type_, SliceType::I);
5393 assert!(hdr.pic_output_flag);
5394 assert_eq!(hdr.colour_plane_id, 0);
5395 assert_eq!(hdr.pic_order_cnt_lsb, 0);
5396 assert!(!hdr.short_term_ref_pic_set_sps_flag);
5397 assert_eq!(hdr.lt_idx_sps, [0; 16]);
5398 assert_eq!(hdr.poc_lsb_lt, [0; 16]);
5399 assert_eq!(hdr.used_by_curr_pic_lt, [false; 16]);
5400 assert_eq!(hdr.delta_poc_msb_cycle_lt, [0; 16]);
5401 assert_eq!(hdr.delta_poc_msb_present_flag, [false; 16]);
5402 assert!(!hdr.temporal_mvp_enabled_flag);
5403 assert!(hdr.sao_luma_flag);
5404 assert!(hdr.sao_chroma_flag);
5405 assert!(!hdr.num_ref_idx_active_override_flag);
5406 assert_eq!(hdr.num_ref_idx_l0_active_minus1, 0);
5407 assert_eq!(hdr.num_ref_idx_l1_active_minus1, 0);
5408 assert!(!hdr.cabac_init_flag);
5409 assert!(hdr.collocated_from_l0_flag);
5410 assert_eq!(hdr.five_minus_max_num_merge_cand, 0);
5411 assert!(!hdr.use_integer_mv_flag);
5412 assert_eq!(hdr.qp_delta, 7);
5413 assert_eq!(hdr.cb_qp_offset, 0);
5414 assert_eq!(hdr.cr_qp_offset, 0);
5415 assert!(!hdr.cu_chroma_qp_offset_enabled_flag);
5416 assert!(!hdr.deblocking_filter_override_flag);
5417 assert!(!hdr.deblocking_filter_override_flag);
5418 assert_eq!(hdr.beta_offset_div2, 0);
5419 assert_eq!(hdr.tc_offset_div2, 0);
5420 assert!(hdr.loop_filter_across_slices_enabled_flag);
5421 assert_eq!(hdr.num_entry_point_offsets, 3);
5422 assert_eq!(hdr.offset_len_minus1, 11);
5423 assert_eq!(hdr.num_pic_total_curr, 0);
5424
5425 // Remove the 2 bytes from the NALU header.
5426 assert_eq!(hdr.header_bit_size - 16, 72);
5427
5428 assert_eq!(hdr.n_emulation_prevention_bytes, 0);
5429
5430 assert_eq!(slice.nalu.as_ref(), STREAM_TEST_25_FPS_SLICE_0);
5431
5432 // Next slice
5433 let slice_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::TrailR, 0).unwrap();
5434 let slice = parser.parse_slice_header(slice_nalu).unwrap();
5435 let hdr = &slice.header;
5436
5437 assert!(hdr.first_slice_segment_in_pic_flag);
5438 assert!(!hdr.no_output_of_prior_pics_flag);
5439 assert!(!hdr.dependent_slice_segment_flag);
5440 assert_eq!(hdr.type_, SliceType::P);
5441 assert!(hdr.pic_output_flag);
5442 assert_eq!(hdr.colour_plane_id, 0);
5443 assert_eq!(hdr.pic_order_cnt_lsb, 3);
5444 assert!(!hdr.short_term_ref_pic_set_sps_flag);
5445 assert_eq!(hdr.short_term_ref_pic_set.num_delta_pocs, 1);
5446 assert_eq!(hdr.short_term_ref_pic_set.num_negative_pics, 1);
5447 assert_eq!(hdr.short_term_ref_pic_set.num_positive_pics, 0);
5448 assert!(hdr.short_term_ref_pic_set.used_by_curr_pic_s0[0]);
5449 assert_eq!(hdr.short_term_ref_pic_set.delta_poc_s0[0], -3);
5450 assert_eq!(hdr.lt_idx_sps, [0; 16]);
5451 assert_eq!(hdr.poc_lsb_lt, [0; 16]);
5452 assert_eq!(hdr.used_by_curr_pic_lt, [false; 16]);
5453 assert_eq!(hdr.delta_poc_msb_cycle_lt, [0; 16]);
5454 assert_eq!(hdr.delta_poc_msb_present_flag, [false; 16]);
5455 assert!(hdr.temporal_mvp_enabled_flag);
5456 assert!(hdr.sao_luma_flag);
5457 assert!(hdr.sao_chroma_flag);
5458 assert!(!hdr.num_ref_idx_active_override_flag);
5459 assert_eq!(hdr.num_ref_idx_l0_active_minus1, 0);
5460 assert_eq!(hdr.num_ref_idx_l1_active_minus1, 0);
5461 assert!(!hdr.cabac_init_flag);
5462 assert!(hdr.collocated_from_l0_flag);
5463 assert_eq!(hdr.pred_weight_table.luma_log2_weight_denom, 7);
5464 assert_eq!(hdr.five_minus_max_num_merge_cand, 2);
5465 assert!(!hdr.use_integer_mv_flag);
5466 assert_eq!(hdr.num_entry_point_offsets, 3);
5467 assert_eq!(hdr.qp_delta, 7);
5468 assert_eq!(hdr.cb_qp_offset, 0);
5469 assert_eq!(hdr.cr_qp_offset, 0);
5470 assert!(!hdr.cu_chroma_qp_offset_enabled_flag);
5471 assert!(!hdr.deblocking_filter_override_flag);
5472 assert!(!hdr.deblocking_filter_override_flag);
5473 assert_eq!(hdr.beta_offset_div2, 0);
5474 assert_eq!(hdr.tc_offset_div2, 0);
5475 assert!(!hdr.loop_filter_across_slices_enabled_flag);
5476 assert_eq!(hdr.num_entry_point_offsets, 3);
5477 assert_eq!(hdr.offset_len_minus1, 10);
5478 assert_eq!(hdr.num_pic_total_curr, 1);
5479
5480 assert_eq!(slice.nalu.size, 2983);
5481 // Subtract 2 bytes to account for the header size.
5482 assert_eq!(hdr.header_bit_size - 16, 96);
5483 assert_eq!(slice.nalu.as_ref(), STREAM_TEST_25_FPS_SLICE_1);
5484
5485 // Next slice
5486 let slice_nalu = find_nalu_by_type(STREAM_TEST25FPS, NaluType::TrailR, 1).unwrap();
5487 let slice = parser.parse_slice_header(slice_nalu).unwrap();
5488 let hdr = &slice.header;
5489
5490 assert_eq!(slice.nalu.size, 290);
5491 // Subtract 2 bytes to account for the header size.
5492 assert_eq!(hdr.header_bit_size - 16, 80);
5493 }
5494}