forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBef5832fTahinli3 months ago597 commits

parser.rs3030 lines, 114.7 KiBHistoryRawDownload
1// Copyright 2022 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// Can't reasonably expect client code to consume everything that has been parsed.
6#![allow(dead_code)]
7
8use std::collections::BTreeMap;
9use std::io::Cursor;
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::picture::Field;
19
20pub type Nalu<'a> = nalu::Nalu<'a, NaluHeader>;
21
22pub(super) const DEFAULT_4X4_INTRA: [u8; 16] =
23 [6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42];
24
25pub(super) const DEFAULT_4X4_INTER: [u8; 16] =
26 [10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34];
27
28pub(super) const DEFAULT_8X8_INTRA: [u8; 64] = [
29 6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18, 18, 18, 18, 23, 23, 23, 23, 23, 23, 25, 25, 25,
30 25, 25, 25, 25, 27, 27, 27, 27, 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31,
31 31, 33, 33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42,
32];
33
34pub(super) const DEFAULT_8X8_INTER: [u8; 64] = [
35 9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19, 19, 19, 19, 21, 21, 21, 21, 21, 21, 22, 22, 22,
36 22, 22, 22, 22, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27,
37 27, 28, 28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35,
38];
39
40const MAX_PPS_COUNT: u16 = 256;
41const MAX_SPS_COUNT: u8 = 32;
42
43/// The maximum number of pictures in the DPB, as per A.3.1, clause h)
44const DPB_MAX_SIZE: usize = 16;
45
46#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
47pub struct Point<T> {
48 pub x: T,
49 pub y: T,
50}
51
52#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
53pub struct Rect<T> {
54 pub min: Point<T>,
55 pub max: Point<T>,
56}
57
58#[derive(Debug, PartialEq, Eq, Clone, Copy)]
59pub enum NaluType {
60 Unknown = 0,
61 Slice = 1,
62 SliceDpa = 2,
63 SliceDpb = 3,
64 SliceDpc = 4,
65 SliceIdr = 5,
66 Sei = 6,
67 Sps = 7,
68 Pps = 8,
69 AuDelimiter = 9,
70 SeqEnd = 10,
71 StreamEnd = 11,
72 FillerData = 12,
73 SpsExt = 13,
74 PrefixUnit = 14,
75 SubsetSps = 15,
76 DepthSps = 16,
77 SliceAux = 19,
78 SliceExt = 20,
79 SliceDepth = 21,
80}
81
82impl TryFrom<u8> for NaluType {
83 type Error = String;
84
85 fn try_from(value: u8) -> Result<Self, Self::Error> {
86 match value {
87 0 => Ok(NaluType::Unknown),
88 1 => Ok(NaluType::Slice),
89 2 => Ok(NaluType::SliceDpa),
90 3 => Ok(NaluType::SliceDpb),
91 4 => Ok(NaluType::SliceDpc),
92 5 => Ok(NaluType::SliceIdr),
93 6 => Ok(NaluType::Sei),
94 7 => Ok(NaluType::Sps),
95 8 => Ok(NaluType::Pps),
96 9 => Ok(NaluType::AuDelimiter),
97 10 => Ok(NaluType::SeqEnd),
98 11 => Ok(NaluType::StreamEnd),
99 12 => Ok(NaluType::FillerData),
100 13 => Ok(NaluType::SpsExt),
101 14 => Ok(NaluType::PrefixUnit),
102 15 => Ok(NaluType::SubsetSps),
103 16 => Ok(NaluType::DepthSps),
104 19 => Ok(NaluType::SliceAux),
105 20 => Ok(NaluType::SliceExt),
106 21 => Ok(NaluType::SliceDepth),
107 _ => Err(format!("Invalid NaluType {}", value)),
108 }
109 }
110}
111
112#[derive(Clone, Debug, Default, PartialEq, Eq)]
113pub struct RefPicListModification {
114 pub modification_of_pic_nums_idc: u8,
115 /* if modification_of_pic_nums_idc == 0 || 1 */
116 pub abs_diff_pic_num_minus1: u32,
117 /* if modification_of_pic_nums_idc == 2 */
118 pub long_term_pic_num: u32,
119 /* if modification_of_pic_nums_idc == 4 || 5 */
120 pub abs_diff_view_idx_minus1: u32,
121}
122
123#[derive(Clone, Debug, Default, PartialEq, Eq)]
124pub struct PredWeightTable {
125 pub luma_log2_weight_denom: u8,
126 pub chroma_log2_weight_denom: u8,
127
128 pub luma_weight_l0: [i16; 32],
129 pub luma_offset_l0: [i8; 32],
130
131 /* if seq->ChromaArrayType != 0 */
132 pub chroma_weight_l0: [[i16; 2]; 32],
133 pub chroma_offset_l0: [[i8; 2]; 32],
134
135 /* if slice->slice_type % 5 == 1 */
136 pub luma_weight_l1: [i16; 32],
137 pub luma_offset_l1: [i16; 32],
138
139 /* and if seq->ChromaArrayType != 0 */
140 pub chroma_weight_l1: [[i16; 2]; 32],
141 pub chroma_offset_l1: [[i8; 2]; 32],
142}
143
144/// Representation of `MaxLongTermFrameIdx`.
145///
146/// `MaxLongTermFrameIdx` is derived from `max_long_term_frame_idx_plus1`, an unsigned integer with
147/// a special value indicating "no long-term frame indices". This type allows easy conversion
148/// between the actual and "plus1" representation, while ensuring that the special value is always
149/// handled by the code.
150#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
151pub enum MaxLongTermFrameIdx {
152 #[default]
153 NoLongTermFrameIndices,
154 Idx(u32),
155}
156
157impl MaxLongTermFrameIdx {
158 /// Create a value from `max_long_term_frame_idx_plus1`.
159 pub fn from_value_plus1(max_long_term_frame_idx_plus1: u32) -> Self {
160 match max_long_term_frame_idx_plus1 {
161 0 => Self::NoLongTermFrameIndices,
162 i @ 1.. => Self::Idx(i - 1),
163 }
164 }
165
166 /// Convert this value to the representation used by `max_long_term_frame_idx_plus1`.
167 pub fn to_value_plus1(self) -> u32 {
168 match self {
169 Self::NoLongTermFrameIndices => 0,
170 Self::Idx(i) => i + 1,
171 }
172 }
173}
174
175impl PartialEq<u32> for MaxLongTermFrameIdx {
176 fn eq(&self, other: &u32) -> bool {
177 match self {
178 MaxLongTermFrameIdx::NoLongTermFrameIndices => false,
179 MaxLongTermFrameIdx::Idx(idx) => idx.eq(other),
180 }
181 }
182}
183
184impl PartialOrd<u32> for MaxLongTermFrameIdx {
185 fn partial_cmp(&self, other: &u32) -> Option<std::cmp::Ordering> {
186 match self {
187 MaxLongTermFrameIdx::NoLongTermFrameIndices => Some(std::cmp::Ordering::Less),
188 MaxLongTermFrameIdx::Idx(idx) => Some(idx.cmp(other)),
189 }
190 }
191}
192
193#[derive(Clone, Debug, Default, PartialEq, Eq)]
194pub struct RefPicMarkingInner {
195 /// Specifies a control operation to be applied to affect the reference
196 /// picture marking. The `memory_management_control_operation` syntax element
197 /// is followed by data necessary for the operation specified by the value
198 /// of `memory_management_control_operation`. The values and control
199 /// operations associated with `memory_management_control_operation` are
200 /// specified in Table 7-9
201 pub memory_management_control_operation: u8,
202
203 /// Used (with memory_management_control_operation equal to 3 or 1) to
204 /// assign a long-term frame index to a short-term reference picture or to
205 /// mark a short-term reference picture as "unused for reference".
206 pub difference_of_pic_nums_minus1: u32,
207
208 /// Used (with memory_management_control_operation equal to 2) to mark a
209 /// long-term reference picture as "unused for reference".
210 pub long_term_pic_num: u32,
211
212 /// Used (with memory_management_control_operation equal to 3 or 6) to
213 /// assign a long-term frame index to a picture.
214 pub long_term_frame_idx: u32,
215
216 /// Specifies the maximum value of long-term frame index allowed for
217 /// long-term reference pictures (until receipt of another value of
218 /// `max_long_term_frame_idx_plus1`).
219 pub max_long_term_frame_idx: MaxLongTermFrameIdx,
220}
221
222#[derive(Clone, Debug, Default, PartialEq, Eq)]
223pub struct RefPicMarking {
224 /// Specifies how the previously-decoded pictures in the decoded picture
225 /// buffer are treated after decoding of an IDR picture. See Annex C.
226 pub no_output_of_prior_pics_flag: bool,
227
228 /// If unset, specifies that the MaxLongTermFrameIdx variable is set equal
229 /// to "no long-term frame indices" and that the IDR picture is marked as
230 /// "used for short-term reference". If set, specifies that the
231 /// MaxLongTermFrameIdx variable is set equal to 0 and that the current IDR
232 /// picture is marked "used for long-term reference" and is assigned
233 /// LongTermFrameIdx equal to 0.
234 pub long_term_reference_flag: bool,
235
236 /// Selects the reference picture marking mode of the currently decoded
237 /// picture as specified in Table 7-8.
238 pub adaptive_ref_pic_marking_mode_flag: bool,
239
240 /// An Vec with additional data used in the marking process.
241 pub inner: Vec<RefPicMarkingInner>,
242}
243
244#[derive(Clone, Debug, Default, PartialEq, Eq)]
245pub struct SliceHeader {
246 /// Specifies the address of the first macroblock in the slice.
247 pub first_mb_in_slice: u32,
248
249 /// Specifies the coding type of the slice according to Table 7-6.
250 pub slice_type: SliceType,
251
252 // Specifies the picture parameter set in use
253 pub pic_parameter_set_id: u8,
254
255 /// Specifies the colour plane associated with the current slice RBSP when
256 /// `separate_colour_plane_flag` is set.
257 pub colour_plane_id: u8,
258
259 /// Used as an identifier for pictures and shall be represented by
260 /// `log2_max_frame_num_minus4 + 4` bits in the bitstream.
261 pub frame_num: u16,
262
263 /// If set, specifies that the slice is a slice of a coded field. If not
264 /// set, specifies that the slice is a slice of a coded frame.
265 pub field_pic_flag: bool,
266
267 /// If set, specifies that the slice is part of a coded bottom field. If not
268 /// set, specifies that the picture is a coded top field.
269 pub bottom_field_flag: bool,
270
271 /// Identifies an IDR picture. The values of `idr_pic_id` in all the slices
272 /// of an IDR picture shall remain unchanged. When two consecutive access
273 /// units in decoding order are both IDR access units, the value of
274 /// `idr_pic_id` in the slices of the first such IDR access unit shall
275 /// differ from the `idr_pic_id` in the second such IDR access unit
276 pub idr_pic_id: u16,
277
278 /// Specifies the picture order count modulo `MaxPicOrderCntLsb` for the top
279 /// field of a coded frame or for a coded field. The length of the
280 /// `pic_order_cnt_lsb` syntax element is
281 /// `log2_max_pic_order_cnt_lsb_minus4` + 4 bits.
282 pub pic_order_cnt_lsb: u16,
283
284 /// Specifies the picture order count difference between the bottom field
285 /// and the top field of a coded frame as follows
286 pub delta_pic_order_cnt_bottom: i32,
287
288 /// The first entry specifies the picture order count difference from the
289 /// expected picture order count for the top field of a coded frame or for a
290 /// coded field as specified in clause 8.2.1 The second entry specifies the
291 /// picture order count difference from the expected picture order count for
292 /// the bottom field of a coded frame specified in clause 8.2.1.
293 pub delta_pic_order_cnt: [i32; 2],
294
295 /// This value is required by V4L2 stateless decode params so it is calculated
296 /// by parser while processing slice header.
297 pub pic_order_cnt_bit_size: usize,
298
299 /// Shall be equal to 0 for slices and slice data partitions belonging to
300 /// the primary coded picture. The value of `redundant_pic_cnt shall` be
301 /// greater than 0 for coded slices or coded slice data partitions of a
302 /// redundant coded picture
303 pub redundant_pic_cnt: u8,
304
305 /// Specifies the method used in the decoding process to derive motion
306 /// vectors and reference indices for inter prediction >
307 pub direct_spatial_mv_pred_flag: bool,
308
309 /// If set, specifies that the syntax element `num_ref_idx_l0_active_minus1`
310 /// is present for P, SP, and B slices and that the syntax element
311 /// `num_ref_idx_l1_active_minus1` is present for B slices. If not set,
312 /// specifies that the syntax elements `num_ref_idx_l0_active_minus1` and
313 /// `num_ref_idx_l1_active_minus1` are not present.
314 pub num_ref_idx_active_override_flag: bool,
315
316 /// Specifies the maximum reference index for reference picture list 0 that
317 /// shall be used to decode the slice.
318 pub num_ref_idx_l0_active_minus1: u8,
319
320 /// Specifies the maximum reference index for reference picture list 1 that
321 /// shall be used to decode the slice.
322 pub num_ref_idx_l1_active_minus1: u8,
323
324 /// If set, specifies that the syntax element `modification_of_pic_nums_idc`
325 /// is present for specifying reference picture list 0. If not set,
326 /// specifies that this syntax element is not present.
327 pub ref_pic_list_modification_flag_l0: bool,
328
329 /// Reference picture list 0 modification as parsed with the
330 /// `ref_pic_list_modification()` process.
331 pub ref_pic_list_modification_l0: Vec<RefPicListModification>,
332
333 /// If set, specifies that the syntax element `modification_of_pic_nums_idc`
334 /// is present for specifying reference picture list 1. If not set,
335 /// specifies that this syntax element is not present.
336 pub ref_pic_list_modification_flag_l1: bool,
337
338 /// Reference picture list 1 modification as parsed with the
339 /// `ref_pic_list_modification()` process.
340 pub ref_pic_list_modification_l1: Vec<RefPicListModification>,
341
342 /// Prediction weight table as parsed using 7.3.3.2
343 pub pred_weight_table: PredWeightTable,
344
345 /// Decoded reference picture marking parsed using 7.3.3.3
346 pub dec_ref_pic_marking: RefPicMarking,
347
348 /// This value is required by V4L2 stateless decode params so it is calculated
349 /// by parser while processing slice header.
350 pub dec_ref_pic_marking_bit_size: usize,
351
352 /// Specifies the index for determining the initialization table used in the
353 /// initialization process for context variables.
354 pub cabac_init_idc: u8,
355
356 /// Specifies the initial value of QP Y to be used for all the macroblocks
357 /// in the slice until modified by the value of `mb_qp_delta` in the
358 /// macroblock layer. The initial QPY quantization parameter for the slice
359 /// is computed using 7-30.
360 pub slice_qp_delta: i8,
361
362 /// Specifies the decoding process to be used to decode P macroblocks in an
363 /// SP slice.
364 pub sp_for_switch_flag: bool,
365
366 /// Specifies the value of QSY for all the macroblocks in SP and SI slices.
367 /// The QSY quantization parameter for the slice is computed using 7-31.
368 pub slice_qs_delta: i8,
369
370 /// Specifies whether the operation of the deblocking filter shall be
371 /// disabled across some block edges of the slice and specifies for which
372 /// edges the filtering is disabled.
373 pub disable_deblocking_filter_idc: u8,
374
375 /// Specifies the offset used in accessing the α and tC0 deblocking filter
376 /// tables for filtering operations controlled by the macroblocks within the
377 /// slice. From this value, the offset that shall be applied when addressing
378 /// these tables shall be computed using 7-32.
379 pub slice_alpha_c0_offset_div2: i8,
380
381 /// Specifies the offset used in accessing the β deblocking filter table for
382 /// filtering operations controlled by the macroblocks within the slice.
383 /// From this value, the offset that is applied when addressing the β table
384 /// of the deblocking filter shall be computed using 7-33.
385 pub slice_beta_offset_div2: i8,
386
387 /// Same as `MaxPicNum` in the specification.
388 pub max_pic_num: u32,
389
390 /// Size of the slice_header() in bits
391 pub header_bit_size: usize,
392
393 /// Number of emulation prevention bytes (EPB) in this slice_header()
394 pub n_emulation_prevention_bytes: usize,
395}
396
397impl SliceHeader {
398 /// Returns the field that is coded by this header.
399 pub fn field(&self) -> Field {
400 if self.field_pic_flag {
401 if self.bottom_field_flag {
402 Field::Bottom
403 } else {
404 Field::Top
405 }
406 } else {
407 Field::Frame
408 }
409 }
410}
411
412pub struct SliceHeaderBuilder(SliceHeader);
413
414impl SliceHeaderBuilder {
415 pub fn new(pps: &Pps) -> Self {
416 SliceHeaderBuilder(SliceHeader {
417 pic_parameter_set_id: pps.pic_parameter_set_id,
418 ..Default::default()
419 })
420 }
421
422 pub fn slice_type(mut self, type_: SliceType) -> Self {
423 self.0.slice_type = type_;
424 self
425 }
426
427 pub fn first_mb_in_slice(mut self, value: u32) -> Self {
428 self.0.first_mb_in_slice = value;
429 self
430 }
431
432 pub fn pic_order_cnt_lsb(mut self, value: u16) -> Self {
433 self.0.pic_order_cnt_lsb = value;
434 self
435 }
436
437 pub fn idr_pic_id(mut self, value: u16) -> Self {
438 self.0.idr_pic_id = value;
439 self
440 }
441
442 pub fn num_ref_idx_active_override_flag(mut self, value: bool) -> Self {
443 self.0.num_ref_idx_active_override_flag = value;
444 self
445 }
446
447 pub fn num_ref_idx_l0_active_minus1(mut self, value: u8) -> Self {
448 self = self.num_ref_idx_active_override_flag(true);
449 self.0.num_ref_idx_l0_active_minus1 = value;
450 self
451 }
452
453 pub fn num_ref_idx_l0_active(self, value: u8) -> Self {
454 self.num_ref_idx_l0_active_minus1(value - 1)
455 }
456
457 pub fn num_ref_idx_l1_active_minus1(mut self, value: u8) -> Self {
458 self = self.num_ref_idx_active_override_flag(true);
459 self.0.num_ref_idx_l1_active_minus1 = value;
460 self
461 }
462
463 pub fn num_ref_idx_l1_active(self, value: u8) -> Self {
464 self.num_ref_idx_l1_active_minus1(value - 1)
465 }
466
467 pub fn build(self) -> SliceHeader {
468 self.0
469 }
470}
471
472/// A H264 slice. An integer number of macroblocks or macroblock pairs ordered
473/// consecutively in the raster scan within a particular slice group
474pub struct Slice<'a> {
475 /// The slice header.
476 pub header: SliceHeader,
477 /// The NAL unit backing this slice.
478 pub nalu: Nalu<'a>,
479}
480
481#[derive(Clone, Copy, Debug, PartialEq, Eq)]
482/// See table 7-6 in the specification.
483pub enum SliceType {
484 P = 0,
485 B = 1,
486 I = 2,
487 Sp = 3,
488 Si = 4,
489}
490
491impl TryFrom<u8> for SliceType {
492 type Error = String;
493
494 fn try_from(value: u8) -> Result<Self, Self::Error> {
495 match value {
496 0 => Ok(SliceType::P),
497 1 => Ok(SliceType::B),
498 2 => Ok(SliceType::I),
499 3 => Ok(SliceType::Sp),
500 4 => Ok(SliceType::Si),
501 _ => Err(format!("Invalid SliceType {}", value)),
502 }
503 }
504}
505
506impl SliceType {
507 /// Whether this is a P slice. See table 7-6 in the specification.
508 pub fn is_p(&self) -> bool {
509 matches!(self, SliceType::P)
510 }
511
512 /// Whether this is a B slice. See table 7-6 in the specification.
513 pub fn is_b(&self) -> bool {
514 matches!(self, SliceType::B)
515 }
516
517 /// Whether this is an I slice. See table 7-6 in the specification.
518 pub fn is_i(&self) -> bool {
519 matches!(self, SliceType::I)
520 }
521
522 /// Whether this is a SP slice. See table 7-6 in the specification.
523 pub fn is_sp(&self) -> bool {
524 matches!(self, SliceType::Sp)
525 }
526
527 /// Whether this is a SI slice. See table 7-6 in the specification.
528 pub fn is_si(&self) -> bool {
529 matches!(self, SliceType::Si)
530 }
531}
532
533impl Default for SliceType {
534 fn default() -> Self {
535 Self::P
536 }
537}
538
539#[derive(Clone, Copy)]
540#[repr(u8)]
541pub enum Profile {
542 Baseline = 66,
543 Main = 77,
544 Extended = 88,
545 High = 100,
546 High10 = 110,
547 High422P = 122,
548}
549
550impl TryFrom<u8> for Profile {
551 type Error = String;
552
553 fn try_from(value: u8) -> Result<Self, Self::Error> {
554 match value {
555 66 => Ok(Profile::Baseline),
556 77 => Ok(Profile::Main),
557 88 => Ok(Profile::Extended),
558 100 => Ok(Profile::High),
559 110 => Ok(Profile::High10),
560 122 => Ok(Profile::High422P),
561 _ => Err(format!("Invalid Profile {}", value)),
562 }
563 }
564}
565
566#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
567pub enum Level {
568 #[default]
569 L1 = 10,
570 L1B = 9,
571 L1_1 = 11,
572 L1_2 = 12,
573 L1_3 = 13,
574 L2_0 = 20,
575 L2_1 = 21,
576 L2_2 = 22,
577 L3 = 30,
578 L3_1 = 31,
579 L3_2 = 32,
580 L4 = 40,
581 L4_1 = 41,
582 L4_2 = 42,
583 L5 = 50,
584 L5_1 = 51,
585 L5_2 = 52,
586 L6 = 60,
587 L6_1 = 61,
588 L6_2 = 62,
589}
590
591impl TryFrom<u8> for Level {
592 type Error = String;
593
594 fn try_from(value: u8) -> Result<Self, Self::Error> {
595 match value {
596 10 => Ok(Level::L1),
597 9 => Ok(Level::L1B),
598 11 => Ok(Level::L1_1),
599 12 => Ok(Level::L1_2),
600 13 => Ok(Level::L1_3),
601 20 => Ok(Level::L2_0),
602 21 => Ok(Level::L2_1),
603 22 => Ok(Level::L2_2),
604 30 => Ok(Level::L3),
605 31 => Ok(Level::L3_1),
606 32 => Ok(Level::L3_2),
607 40 => Ok(Level::L4),
608 41 => Ok(Level::L4_1),
609 42 => Ok(Level::L4_2),
610 50 => Ok(Level::L5),
611 51 => Ok(Level::L5_1),
612 52 => Ok(Level::L5_2),
613 60 => Ok(Level::L6),
614 61 => Ok(Level::L6_1),
615 62 => Ok(Level::L6_2),
616 _ => Err(format!("Invalid Level {}", value)),
617 }
618 }
619}
620
621/// A H264 Sequence Parameter Set. A syntax structure containing syntax elements
622/// that apply to zero or more entire coded video sequences as determined by the
623/// content of a seq_parameter_set_id syntax element found in the picture
624/// parameter set referred to by the pic_parameter_set_id syntax element found
625/// in each slice header.
626#[derive(Debug, PartialEq, Eq)]
627pub struct Sps {
628 /// Identifies the sequence parameter set that is referred to by the picture
629 /// parameter set
630 pub seq_parameter_set_id: u8,
631
632 /// Profile to which the coded video sequence conforms
633 pub profile_idc: u8,
634
635 /// Retains the same meaning as in the specification. See 7.4.2.1.1
636 pub constraint_set0_flag: bool,
637 /// Retains the same meaning as in the specification. See 7.4.2.1.1
638 pub constraint_set1_flag: bool,
639 /// Retains the same meaning as in the specification. See 7.4.2.1.1
640 pub constraint_set2_flag: bool,
641 /// Retains the same meaning as in the specification. See 7.4.2.1.1
642 pub constraint_set3_flag: bool,
643 /// Retains the same meaning as in the specification. See 7.4.2.1.1
644 pub constraint_set4_flag: bool,
645 /// Retains the same meaning as in the specification. See 7.4.2.1.1
646 pub constraint_set5_flag: bool,
647
648 /// Level to which the coded video sequence conforms
649 pub level_idc: Level,
650
651 /// Specifies the chroma sampling relative to the luma sampling as specified
652 /// in clause 6.2.
653 pub chroma_format_idc: u8,
654
655 /// Specifies whether the three colour components of the 4:4:4 chroma format
656 /// are coded separately.
657 pub separate_colour_plane_flag: bool,
658
659 /// Specifies the bit depth of the samples of the luma array and the value
660 /// of the luma quantization parameter range offset QpBdOffsetY. See 7-3 and
661 /// 7-4.
662 pub bit_depth_luma_minus8: u8,
663
664 /// Specifies the bit depth of the samples of the chroma arrays and the
665 /// value of the chroma quantization parameter range offset QpBdOffsetC. See
666 /// 7-5 and 7-6.
667 pub bit_depth_chroma_minus8: u8,
668
669 /// qpprime_y_zero_transform_bypass_flag equal to 1 specifies that, when
670 /// QP′Y is equal to 0, a transform bypass operation for the transform
671 /// coefficient decoding process and picture construction process prior to
672 /// deblocking filter process as specified in clause 8.5 shall be applied.
673 /// qpprime_y_zero_transform_bypass_flag equal to 0 specifies that the
674 /// transform coefficient decoding process and picture construction process
675 /// prior to deblocking filter process shall not use the transform bypass
676 /// operation
677 /// QP′Y is defined in 7-38 as QP′Y = QPY + QpBdOffsetY
678 pub qpprime_y_zero_transform_bypass_flag: bool,
679
680 /// Whether `seq_scaling_list_present_flag[i]` for i = 0..7 or i = 0..11 is
681 /// present or whether the sequence level scaling list shall be specified by
682 /// Flat_4x4_16 for i = 0..5 and flat_8x8_16 for i = 6..11
683 pub seq_scaling_matrix_present_flag: bool,
684
685 /// 4x4 Scaling list as read with 7.3.2.1.1.1
686 pub scaling_lists_4x4: [[u8; 16]; 6],
687 /// 8x8 Scaling list as read with 7.3.2.1.1.1
688 pub scaling_lists_8x8: [[u8; 64]; 6],
689
690 /// Specifies the value of the variable MaxFrameNum that is used in
691 /// frame_num related derivations as follows: MaxFrameNum = 2 ^
692 /// (log2_max_frame_num_minus4 + 4 )
693 pub log2_max_frame_num_minus4: u8,
694
695 /// Specifies the method to decode picture order count (as specified in
696 /// clause 8.2.1)
697 pub pic_order_cnt_type: u8,
698
699 /// Specifies the value of the variable MaxPicOrderCntLsb that is used in
700 /// the decoding process for picture order count as specified in clause
701 /// 8.2.1 as follows: MaxPicOrderCntLsb = 2 ^ (
702 /// log2_max_pic_order_cnt_lsb_minus4 + 4 ).
703 pub log2_max_pic_order_cnt_lsb_minus4: u8,
704
705 /// If true, specifies that `delta_pic_order_cnt[0]` and
706 /// `delta_pic_order_cnt[1]` are not present in the slice headers of the
707 /// sequence and shall be inferred to be equal to 0.
708 /// If false, specifies that `delta_pic_order_cnt[0]` is present in the
709 /// slice headers of the sequence and `delta_pic_order_cnt[1]` may be
710 /// present in the slice headers of the sequence.
711 pub delta_pic_order_always_zero_flag: bool,
712
713 /// Used to calculate the picture order count of a non-reference picture as
714 /// specified in clause 8.2.1.
715 pub offset_for_non_ref_pic: i32,
716
717 /// Used to calculate the picture order count of a bottom field as specified
718 /// in clause 8.2.1.
719 pub offset_for_top_to_bottom_field: i32,
720
721 /// Used in the decoding process for picture order count as specified in
722 /// clause 8.2.1
723 pub num_ref_frames_in_pic_order_cnt_cycle: u8,
724
725 /// An element of a list of num_ref_frames_in_pic_order_cnt_cycle values
726 /// used in the decoding process for picture order count as specified in
727 /// clause 8.2.
728 pub offset_for_ref_frame: [i32; 255],
729
730 /// Specifies the maximum number of short-term and long-term reference
731 /// frames, complementary reference field pairs, and non-paired reference
732 /// fields that may be used by the decoding process for inter prediction of
733 /// any picture in the coded video sequence. Also
734 /// determines the size of the sliding window operation as specified in
735 /// clause 8.2.5.3.
736 pub max_num_ref_frames: u8,
737
738 /// Specifies the allowed values of frame_num as specified in clause 7.4.3
739 /// and the decoding process in case of an inferred gap between values of
740 /// frame_num as specified in clause 8.2.5.2
741 pub gaps_in_frame_num_value_allowed_flag: bool,
742
743 /// Plus 1 specifies the width of each decoded picture in units of
744 /// macroblocks.
745 pub pic_width_in_mbs_minus1: u16,
746 /// Plus 1 specifies the height in slice group map units of a decoded frame
747 /// or field.
748 pub pic_height_in_map_units_minus1: u16,
749
750 /// If true, specifies that every coded picture of the coded video sequence
751 /// is a coded frame containing only frame macroblocks, else specifies that
752 /// coded pictures of the coded video sequence may either be coded fields or
753 /// coded frames.
754 pub frame_mbs_only_flag: bool,
755
756 /// If true, specifies the possible use of switching between frame and field
757 /// macroblocks within frames, else, specifies no switching between frame
758 /// and field macroblocks within a picture.
759 pub mb_adaptive_frame_field_flag: bool,
760
761 /// Specifies the method used in the derivation process for luma motion
762 /// vectors for B_Skip, B_Direct_16x16 and B_Direct_8x8 as specified in
763 /// clause 8.4.1.2.
764 pub direct_8x8_inference_flag: bool,
765
766 /// If true, specifies that the frame cropping offset parameters follow next
767 /// in the sequence parameter, else specifies that the frame cropping offset
768 /// parameters are not present
769 pub frame_cropping_flag: bool,
770
771 /// Specify the samples of the pictures in the coded video sequence that are
772 /// output from the decoding process, in terms of a rectangular region
773 /// specified in frame coordinates for output.
774 pub frame_crop_left_offset: u32,
775 /// Specify the samples of the pictures in the coded video sequence that are
776 /// output from the decoding process, in terms of a rectangular region
777 /// specified in frame coordinates for output.
778 pub frame_crop_right_offset: u32,
779 /// Specify the samples of the pictures in the coded video sequence that are
780 /// output from the decoding process, in terms of a rectangular region
781 /// specified in frame coordinates for output.
782 pub frame_crop_top_offset: u32,
783 /// Specify the samples of the pictures in the coded video sequence that are
784 /// output from the decoding process, in terms of a rectangular region
785 /// specified in frame coordinates for output.
786 pub frame_crop_bottom_offset: u32,
787
788 // Calculated
789 /// Same as ExpectedDeltaPerPicOrderCntCycle, see 7-12 in the specification.
790 pub expected_delta_per_pic_order_cnt_cycle: i32,
791
792 pub vui_parameters_present_flag: bool,
793 pub vui_parameters: VuiParams,
794}
795
796impl Sps {
797 /// Returns the coded width of the stream.
798 ///
799 /// See 7-13 through 7-17 in the specification.
800 pub const fn width(&self) -> u32 {
801 (self.pic_width_in_mbs_minus1 as u32 + 1) * 16
802 }
803
804 /// Returns the coded height of the stream.
805 ///
806 /// See 7-13 through 7-17 in the specification.
807 pub const fn height(&self) -> u32 {
808 (self.pic_height_in_map_units_minus1 as u32 + 1)
809 * 16
810 * (2 - self.frame_mbs_only_flag as u32)
811 }
812
813 /// Returns `ChromaArrayType`, as computed in the specification.
814 pub const fn chroma_array_type(&self) -> u8 {
815 match self.separate_colour_plane_flag {
816 false => self.chroma_format_idc,
817 true => 0,
818 }
819 }
820
821 /// Returns `SubWidthC` and `SubHeightC`.
822 ///
823 /// See table 6-1 in the specification.
824 fn sub_width_height_c(&self) -> (u32, u32) {
825 match (self.chroma_format_idc, self.separate_colour_plane_flag) {
826 (1, false) => (2, 2),
827 (2, false) => (2, 1),
828 (3, false) => (1, 1),
829 // undefined.
830 _ => (1, 1),
831 }
832 }
833
834 /// Returns `CropUnitX` and `CropUnitY`.
835 ///
836 /// See 7-19 through 7-22 in the specification.
837 fn crop_unit_x_y(&self) -> (u32, u32) {
838 match self.chroma_array_type() {
839 0 => (1, 2 - u32::from(self.frame_mbs_only_flag)),
840 _ => {
841 let (sub_width_c, sub_height_c) = self.sub_width_height_c();
842 (sub_width_c, sub_height_c * (2 - u32::from(self.frame_mbs_only_flag)))
843 }
844 }
845 }
846
847 /// Same as MaxFrameNum. See 7-10 in the specification.
848 pub fn max_frame_num(&self) -> u32 {
849 1 << (self.log2_max_frame_num_minus4 + 4)
850 }
851
852 pub fn visible_rectangle(&self) -> Rect<u32> {
853 if !self.frame_cropping_flag {
854 return Rect {
855 min: Point { x: 0, y: 0 },
856 max: Point { x: self.width(), y: self.height() },
857 };
858 }
859
860 let (crop_unit_x, crop_unit_y) = self.crop_unit_x_y();
861
862 let crop_left = crop_unit_x * self.frame_crop_left_offset;
863 let crop_right = crop_unit_x * self.frame_crop_right_offset;
864 let crop_top = crop_unit_y * self.frame_crop_top_offset;
865 let crop_bottom = crop_unit_y * self.frame_crop_bottom_offset;
866
867 Rect {
868 min: Point { x: crop_left, y: crop_top },
869 max: Point {
870 x: self.width() - crop_left - crop_right,
871 y: self.height() - crop_top - crop_bottom,
872 },
873 }
874 }
875
876 pub fn max_dpb_frames(&self) -> usize {
877 let profile = self.profile_idc;
878 let mut level = self.level_idc;
879
880 // A.3.1 and A.3.2: Level 1b for Baseline, Constrained Baseline and Main
881 // profile if level_idc == 11 and constraint_set3_flag == 1
882 if matches!(level, Level::L1_1)
883 && (profile == Profile::Baseline as u8 || profile == Profile::Main as u8)
884 && self.constraint_set3_flag
885 {
886 level = Level::L1B;
887 };
888
889 // Table A.1
890 let max_dpb_mbs = match level {
891 Level::L1 => 396,
892 Level::L1B => 396,
893 Level::L1_1 => 900,
894 Level::L1_2 => 2376,
895 Level::L1_3 => 2376,
896 Level::L2_0 => 2376,
897 Level::L2_1 => 4752,
898 Level::L2_2 => 8100,
899 Level::L3 => 8100,
900 Level::L3_1 => 18000,
901 Level::L3_2 => 20480,
902 Level::L4 => 32768,
903 Level::L4_1 => 32768,
904 Level::L4_2 => 34816,
905 Level::L5 => 110400,
906 Level::L5_1 => 184320,
907 Level::L5_2 => 184320,
908 Level::L6 => 696320,
909 Level::L6_1 => 696320,
910 Level::L6_2 => 696320,
911 };
912
913 let width_mb = self.width() / 16;
914 let height_mb = self.height() / 16;
915
916 let max_dpb_frames =
917 std::cmp::min(max_dpb_mbs / (width_mb * height_mb), DPB_MAX_SIZE as u32) as usize;
918
919 let mut max_dpb_frames = std::cmp::max(max_dpb_frames, self.max_num_ref_frames as usize);
920
921 if self.vui_parameters_present_flag && self.vui_parameters.bitstream_restriction_flag {
922 max_dpb_frames = std::cmp::max(1, self.vui_parameters.max_dec_frame_buffering as usize);
923 }
924
925 max_dpb_frames
926 }
927
928 pub fn max_num_order_frames(&self) -> u32 {
929 let vui = &self.vui_parameters;
930 let present = self.vui_parameters_present_flag && vui.bitstream_restriction_flag;
931
932 if present {
933 vui.max_num_reorder_frames
934 } else {
935 let profile = self.profile_idc;
936 if (profile == 44
937 || profile == 86
938 || profile == 100
939 || profile == 110
940 || profile == 122
941 || profile == 244)
942 && self.constraint_set3_flag
943 {
944 0
945 } else {
946 self.max_dpb_frames() as u32
947 }
948 }
949 }
950}
951
952// TODO: Replace with builder
953impl Default for Sps {
954 fn default() -> Self {
955 Self {
956 scaling_lists_4x4: [[0; 16]; 6],
957 scaling_lists_8x8: [[0; 64]; 6],
958 offset_for_ref_frame: [0; 255],
959 seq_parameter_set_id: Default::default(),
960 profile_idc: Default::default(),
961 constraint_set0_flag: Default::default(),
962 constraint_set1_flag: Default::default(),
963 constraint_set2_flag: Default::default(),
964 constraint_set3_flag: Default::default(),
965 constraint_set4_flag: Default::default(),
966 constraint_set5_flag: Default::default(),
967 level_idc: Default::default(),
968 chroma_format_idc: Default::default(),
969 separate_colour_plane_flag: Default::default(),
970 bit_depth_luma_minus8: Default::default(),
971 bit_depth_chroma_minus8: Default::default(),
972 qpprime_y_zero_transform_bypass_flag: Default::default(),
973 seq_scaling_matrix_present_flag: Default::default(),
974 log2_max_frame_num_minus4: Default::default(),
975 pic_order_cnt_type: Default::default(),
976 log2_max_pic_order_cnt_lsb_minus4: Default::default(),
977 delta_pic_order_always_zero_flag: Default::default(),
978 offset_for_non_ref_pic: Default::default(),
979 offset_for_top_to_bottom_field: Default::default(),
980 num_ref_frames_in_pic_order_cnt_cycle: Default::default(),
981 max_num_ref_frames: Default::default(),
982 gaps_in_frame_num_value_allowed_flag: Default::default(),
983 pic_width_in_mbs_minus1: Default::default(),
984 pic_height_in_map_units_minus1: Default::default(),
985 frame_mbs_only_flag: Default::default(),
986 mb_adaptive_frame_field_flag: Default::default(),
987 direct_8x8_inference_flag: Default::default(),
988 frame_cropping_flag: Default::default(),
989 frame_crop_left_offset: Default::default(),
990 frame_crop_right_offset: Default::default(),
991 frame_crop_top_offset: Default::default(),
992 frame_crop_bottom_offset: Default::default(),
993 expected_delta_per_pic_order_cnt_cycle: Default::default(),
994 vui_parameters_present_flag: Default::default(),
995 vui_parameters: Default::default(),
996 }
997 }
998}
999
1000#[derive(Default)]
1001pub struct SpsBuilder(Sps);
1002
1003impl SpsBuilder {
1004 pub fn new() -> Self {
1005 Default::default()
1006 }
1007
1008 pub fn seq_parameter_set_id(mut self, value: u8) -> Self {
1009 self.0.seq_parameter_set_id = value;
1010 self
1011 }
1012
1013 pub fn profile_idc(mut self, value: Profile) -> Self {
1014 self.0.profile_idc = value as u8;
1015 self
1016 }
1017
1018 pub fn level_idc(mut self, value: Level) -> Self {
1019 self.0.level_idc = value;
1020 self
1021 }
1022
1023 pub fn frame_crop_offsets(mut self, top: u32, bottom: u32, left: u32, right: u32) -> Self {
1024 self.0.frame_cropping_flag = true;
1025 self.0.frame_crop_top_offset = top;
1026 self.0.frame_crop_bottom_offset = bottom;
1027 self.0.frame_crop_left_offset = left;
1028 self.0.frame_crop_right_offset = right;
1029 self
1030 }
1031
1032 pub fn frame_crop(self, top: u32, bottom: u32, left: u32, right: u32) -> Self {
1033 let sub_width_c = if self.0.chroma_format_idc > 2 { 1 } else { 2 };
1034 let sub_height_c = if self.0.chroma_format_idc > 1 { 1 } else { 2 };
1035
1036 let crop_unit_x = sub_width_c;
1037 let crop_unit_y = sub_height_c * (if self.0.frame_mbs_only_flag { 1 } else { 2 });
1038
1039 self.frame_crop_offsets(
1040 top / crop_unit_y,
1041 bottom / crop_unit_y,
1042 left / crop_unit_x,
1043 right / crop_unit_x,
1044 )
1045 }
1046
1047 pub fn resolution(mut self, width: u32, height: u32) -> Self {
1048 const MB_SIZE: u32 = 16;
1049
1050 let mb_width = (width + MB_SIZE - 1) / MB_SIZE;
1051 let mb_height = (height + MB_SIZE - 1) / MB_SIZE;
1052
1053 self.0.pic_width_in_mbs_minus1 = (mb_width - 1) as u16;
1054 self.0.pic_height_in_map_units_minus1 = (mb_height - 1) as u16;
1055
1056 let compressed_width = mb_width * MB_SIZE;
1057 let compressed_height = mb_height * MB_SIZE;
1058
1059 if compressed_width != width || compressed_height != height {
1060 self = self.frame_crop(0, compressed_height - height, 0, compressed_width - width);
1061 }
1062
1063 self
1064 }
1065
1066 pub fn chroma_format_idc(mut self, value: u8) -> Self {
1067 self.0.chroma_format_idc = value;
1068 self
1069 }
1070
1071 pub fn max_num_ref_frames(mut self, value: u8) -> Self {
1072 self.0.max_num_ref_frames = value;
1073 self
1074 }
1075
1076 pub fn frame_mbs_only_flag(mut self, value: bool) -> Self {
1077 self.0.frame_mbs_only_flag = value;
1078 self
1079 }
1080
1081 pub fn mb_adaptive_frame_field_flag(mut self, value: bool) -> Self {
1082 self.0.mb_adaptive_frame_field_flag = value;
1083 self
1084 }
1085
1086 pub fn seq_scaling_matrix_present_flag(mut self, value: bool) -> Self {
1087 self.0.seq_scaling_matrix_present_flag = value;
1088 self
1089 }
1090
1091 pub fn direct_8x8_inference_flag(mut self, value: bool) -> Self {
1092 self.0.direct_8x8_inference_flag = value;
1093 self
1094 }
1095
1096 pub fn vui_parameters_present(mut self) -> Self {
1097 if self.0.vui_parameters_present_flag {
1098 return self;
1099 }
1100
1101 self.0.vui_parameters_present_flag = true;
1102 // Disable all options at default
1103 self.0.vui_parameters.aspect_ratio_info_present_flag = false;
1104 self.0.vui_parameters.overscan_info_present_flag = false;
1105 self.0.vui_parameters.video_signal_type_present_flag = false;
1106 self.0.vui_parameters.colour_description_present_flag = false;
1107 self.0.vui_parameters.chroma_loc_info_present_flag = false;
1108 self.0.vui_parameters.timing_info_present_flag = false;
1109 self.0.vui_parameters.nal_hrd_parameters_present_flag = false;
1110 self.0.vui_parameters.vcl_hrd_parameters_present_flag = false;
1111 self.0.vui_parameters.pic_struct_present_flag = false;
1112 self.0.vui_parameters.bitstream_restriction_flag = false;
1113 self
1114 }
1115
1116 pub fn aspect_ratio_idc(mut self, value: u8) -> Self {
1117 self = self.vui_parameters_present();
1118 self.0.vui_parameters.aspect_ratio_info_present_flag = true;
1119 self.0.vui_parameters.aspect_ratio_idc = value;
1120 self
1121 }
1122
1123 pub fn sar_resolution(mut self, width: u16, height: u16) -> Self {
1124 self = self.aspect_ratio_idc(255);
1125 self.0.vui_parameters.sar_width = width;
1126 self.0.vui_parameters.sar_height = height;
1127 self
1128 }
1129
1130 pub fn aspect_ratio(self, width_ratio: u16, height_ratio: u16) -> Self {
1131 // H.264 Table E-1
1132 match (width_ratio, height_ratio) {
1133 (1, 1) => self.aspect_ratio_idc(1),
1134 (12, 11) => self.aspect_ratio_idc(2),
1135 (10, 11) => self.aspect_ratio_idc(3),
1136 (16, 11) => self.aspect_ratio_idc(4),
1137 (40, 33) => self.aspect_ratio_idc(5),
1138 (24, 11) => self.aspect_ratio_idc(6),
1139 (20, 11) => self.aspect_ratio_idc(7),
1140 (32, 11) => self.aspect_ratio_idc(8),
1141 (80, 33) => self.aspect_ratio_idc(9),
1142 (18, 11) => self.aspect_ratio_idc(10),
1143 (15, 11) => self.aspect_ratio_idc(11),
1144 (64, 33) => self.aspect_ratio_idc(12),
1145 (160, 99) => self.aspect_ratio_idc(13),
1146 (4, 3) => self.aspect_ratio_idc(14),
1147 (3, 2) => self.aspect_ratio_idc(15),
1148 (2, 1) => self.aspect_ratio_idc(16),
1149
1150 _ => self.sar_resolution(width_ratio, height_ratio),
1151 }
1152 }
1153
1154 pub fn timing_info(
1155 mut self,
1156 num_units_in_tick: u32,
1157 time_scale: u32,
1158 fixed_frame_rate_flag: bool,
1159 ) -> Self {
1160 self = self.vui_parameters_present();
1161 self.0.vui_parameters.timing_info_present_flag = true;
1162 self.0.vui_parameters.num_units_in_tick = num_units_in_tick;
1163 self.0.vui_parameters.time_scale = time_scale;
1164 self.0.vui_parameters.fixed_frame_rate_flag = fixed_frame_rate_flag;
1165 self
1166 }
1167
1168 pub fn log2_max_frame_num_minus4(mut self, value: u8) -> Self {
1169 self.0.log2_max_frame_num_minus4 = value;
1170 self
1171 }
1172
1173 /// Saturating, because an all-IDR stream asks for `max_frame_num` 1: its
1174 /// `ilog2()` is 0 and `0u8 - 4u8` wraps to 252 in release, an SPS out of
1175 /// the spec's 0..=12 that every decoder refuses. Zero is not merely legal
1176 /// there, it is right: `frame_num` never leaves 0 when every picture is an
1177 /// IDR.
1178 pub fn max_frame_num(self, value: u32) -> Self {
1179 self.log2_max_frame_num_minus4(value.ilog2().saturating_sub(4).min(12) as u8)
1180 }
1181
1182 pub fn pic_order_cnt_type(mut self, value: u8) -> Self {
1183 self.0.pic_order_cnt_type = value;
1184 self
1185 }
1186
1187 pub fn log2_max_pic_order_cnt_lsb_minus4(mut self, value: u8) -> Self {
1188 self.0.log2_max_pic_order_cnt_lsb_minus4 = value;
1189 self
1190 }
1191
1192 /// Saturating for the same reason as [`SpsBuilder::max_frame_num`]: the
1193 /// all-IDR caller asks for 2 here, whose `ilog2()` is 1.
1194 pub fn max_pic_order_cnt_lsb(self, value: u32) -> Self {
1195 self.log2_max_pic_order_cnt_lsb_minus4(value.ilog2().saturating_sub(4).min(12) as u8)
1196 }
1197
1198 pub fn delta_pic_order_always_zero_flag(mut self, value: bool) -> Self {
1199 self.0.delta_pic_order_always_zero_flag = value;
1200 self
1201 }
1202
1203 pub fn bit_depth_chroma_minus8(mut self, value: u8) -> Self {
1204 self.0.bit_depth_chroma_minus8 = value;
1205 self
1206 }
1207
1208 pub fn bit_depth_chroma(self, value: u8) -> Self {
1209 self.bit_depth_luma_minus8(value - 8u8)
1210 }
1211
1212 pub fn bit_depth_luma_minus8(mut self, value: u8) -> Self {
1213 self.0.bit_depth_luma_minus8 = value;
1214 self
1215 }
1216
1217 pub fn bit_depth_luma(self, value: u8) -> Self {
1218 self.bit_depth_luma_minus8(value - 8u8)
1219 }
1220
1221 pub fn build(self) -> Rc<Sps> {
1222 Rc::new(self.0)
1223 }
1224}
1225
1226#[derive(Clone, Debug, Default, PartialEq, Eq)]
1227pub struct HrdParams {
1228 /// Plus 1 specifies the number of alternative CPB specifications in the
1229 /// bitstream. The value of `cpb_cnt_minus1` shall be in the range of 0 to 31,
1230 /// inclusive
1231 pub cpb_cnt_minus1: u8,
1232 /// Together with `bit_rate_value_minus1[ SchedSelIdx ]` specifies the
1233 /// maximum input bit rate of the `SchedSelIdx`-th CPB.
1234 pub bit_rate_scale: u8,
1235 /// Together with `cpb_size_value_minus1[ SchedSelIdx ]` specifies the CPB
1236 /// size of the SchedSelIdx-th CPB.
1237 pub cpb_size_scale: u8,
1238
1239 /// `[ SchedSelIdx ]` (together with bit_rate_scale) specifies the maximum
1240 /// input bit rate for the SchedSelIdx-th CPB.
1241 pub bit_rate_value_minus1: [u32; 32],
1242 /// `[ SchedSelIdx ]` is used together with cpb_size_scale to specify the
1243 /// SchedSelIdx-th CPB size.
1244 pub cpb_size_value_minus1: [u32; 32],
1245 /// `[ SchedSelIdx ]` equal to 0 specifies that to decode this bitstream by
1246 /// the HRD using the `SchedSelIdx`-th CPB specification, the hypothetical
1247 /// stream delivery scheduler (HSS) operates in an intermittent bit rate
1248 /// mode. `cbr_flag[ SchedSelIdx ]` equal to 1 specifies that the HSS operates
1249 /// in a constant bit rate (CBR) mode
1250 pub cbr_flag: [bool; 32],
1251
1252 /// Specifies the length in bits of the `initial_cpb_removal_delay[
1253 /// SchedSelIdx ]` and `initial_cpb_removal_delay_offset[ SchedSelIdx ]` syntax
1254 /// elements of the buffering period SEI message.
1255 pub initial_cpb_removal_delay_length_minus1: u8,
1256 /// Specifies the length in bits of the `cpb_removal_delay` syntax element.
1257 pub cpb_removal_delay_length_minus1: u8,
1258 /// Specifies the length in bits of the `dpb_output_delay` syntax element.
1259 pub dpb_output_delay_length_minus1: u8,
1260 /// If greater than 0, specifies the length in bits of the `time_offset`
1261 /// syntax element. `time_offset_length` equal to 0 specifies that the
1262 /// `time_offset` syntax element is not present
1263 pub time_offset_length: u8,
1264}
1265
1266#[derive(Clone, Debug, PartialEq, Eq)]
1267pub struct VuiParams {
1268 /// Specifies whether `aspect_ratio_idc` is present.
1269 pub aspect_ratio_info_present_flag: bool,
1270 /// Specifies the value of the sample aspect ratio of the luma samples.
1271 /// Table E-1 shows the meaning of the code. When aspect_ratio_idc indicates
1272 /// Extended_SAR, the sample aspect ratio is represented by sar_width :
1273 /// sar_height. When the aspect_ratio_idc syntax element is not present,
1274 /// aspect_ratio_idc value shall be inferred to be equal to 0
1275 pub aspect_ratio_idc: u8,
1276
1277 /* if aspect_ratio_idc == 255 */
1278 /// Indicates the horizontal size of the sample aspect ratio (in arbitrary
1279 /// units)
1280 pub sar_width: u16,
1281 /// Indicates the vertical size of the sample aspect ratio (in the same
1282 /// arbitrary units as sar_width).
1283 pub sar_height: u16,
1284
1285 /// If true specifies that the overscan_appropriate_flag is present. Else,
1286 /// the preferred display method for the video signal is unspecified
1287 pub overscan_info_present_flag: bool,
1288 /* if overscan_info_present_flag */
1289 /// If true, indicates that the cropped decoded pictures output are suitable
1290 /// for display using overscan. Else, indicates that the cropped decoded
1291 /// pictures output contain visually important information in the entire
1292 /// region out to the edges of the cropping rectangle of the picture, such
1293 /// that the cropped decoded pictures output should not be displayed using
1294 /// overscan.
1295 pub overscan_appropriate_flag: bool,
1296
1297 /// Specifies that video_format, video_full_range_flag and
1298 /// colour_description_present_flag are present
1299 pub video_signal_type_present_flag: bool,
1300 /// Indicates the representation of the pictures as specified in Table E-2,
1301 /// before being coded in accordance with this Recommendation |
1302 /// International Standard. When the video_format syntax element is not
1303 /// present, video_format value shall be inferred to be equal to 5.
1304 pub video_format: u8,
1305 /// Indicates the black level and range of the luma and chroma signals as
1306 /// derived from E′Y, E′PB, and E′PR or E′ R, E′G, and E′B real-valued
1307 /// component signals.
1308 pub video_full_range_flag: bool,
1309 /// Specifies that colour_primaries, transfer_characteristics and
1310 /// matrix_coefficients are present.
1311 pub colour_description_present_flag: bool,
1312 /// Indicates the chromaticity coordinates of the source primaries as
1313 /// specified in Table E-3 in terms of the CIE 1931 definition of x and y as
1314 /// specified by ISO 11664-1.
1315 pub colour_primaries: u8,
1316 /// Retains same meaning as in the specification.
1317 pub transfer_characteristics: u8,
1318 /// Describes the matrix coefficients used in deriving luma and chroma
1319 /// signals from the green, blue, and red, or Y, Z, and X primaries, as
1320 /// specified in Table E-5.
1321 pub matrix_coefficients: u8,
1322
1323 /// Specifies that chroma_sample_loc_type_top_field and
1324 /// chroma_sample_loc_type_bottom_field are present
1325 pub chroma_loc_info_present_flag: bool,
1326 /// Specify the location of chroma samples. See the spec for more details.
1327 pub chroma_sample_loc_type_top_field: u8,
1328 /// Specify the location of chroma samples. See the spec for more details.
1329 pub chroma_sample_loc_type_bottom_field: u8,
1330
1331 /// Specifies that num_units_in_tick, time_scale and fixed_frame_rate_flag
1332 /// are present in the bitstream
1333 pub timing_info_present_flag: bool,
1334 /* if timing_info_present_flag */
1335 /// The number of time units of a clock operating at the frequency
1336 /// time_scale Hz that corresponds to one increment (called a clock tick) of
1337 /// a clock tick counter
1338 pub num_units_in_tick: u32,
1339 /// The number of time units that pass in one second. For example, a time
1340 /// coordinate system that measures time using a 27 MHz clock has a
1341 /// time_scale of 27 000 000. time_scale shall be greater than 0.
1342 pub time_scale: u32,
1343 /// Retains the same meaning as the specification.
1344 pub fixed_frame_rate_flag: bool,
1345
1346 /// Specifies that NAL HRD parameters (pertaining to Type II bitstream
1347 /// conformance) are present.
1348 pub nal_hrd_parameters_present_flag: bool,
1349 /* if nal_hrd_parameters_present_flag */
1350 /// The NAL HDR parameters
1351 pub nal_hrd_parameters: HrdParams,
1352 /// Specifies that VCL HRD parameters (pertaining to all bitstream
1353 /// conformance) are present.
1354 pub vcl_hrd_parameters_present_flag: bool,
1355 /* if vcl_hrd_parameters_present_flag */
1356 /// The VCL HRD parameters
1357 pub vcl_hrd_parameters: HrdParams,
1358
1359 /// Specifies the HRD operational mode as specified in Annex C.
1360 pub low_delay_hrd_flag: bool,
1361
1362 /// Specifies that picture timing SEI messages (clause D.2.3) are present
1363 /// that include the pic_struct syntax element.
1364 pub pic_struct_present_flag: bool,
1365
1366 /// Specifies that the following coded video sequence bitstream restriction
1367 /// parameters are present
1368 pub bitstream_restriction_flag: bool,
1369 /* if bitstream_restriction_flag */
1370 /// If false, indicates that no sample outside the picture boundaries and no
1371 /// sample at a fractional sample position for which the sample value is
1372 /// derived using one or more samples outside the picture boundaries is used
1373 /// for inter prediction of any sample. If true, indicates that one or more
1374 /// samples outside picture boundaries may be used in inter prediction. When
1375 /// the motion_vectors_over_pic_boundaries_flag syntax element is not
1376 /// present, motion_vectors_over_pic_boundaries_flag value shall be inferred
1377 /// to be true.
1378 pub motion_vectors_over_pic_boundaries_flag: bool,
1379 /// Indicates a number of bytes not exceeded by the sum of the sizes of the
1380 /// VCL NAL units associated with any coded picture in the coded video
1381 /// sequence.
1382 pub max_bytes_per_pic_denom: u32,
1383 /// Indicates an upper bound for the number of coded bits of
1384 /// macroblock_layer( ) data for any macroblock in any picture of the coded
1385 /// video sequence
1386 pub max_bits_per_mb_denom: u32,
1387 /// Retains the same meaning as the specification.
1388 pub log2_max_mv_length_horizontal: u32,
1389 /// Retains the same meaning as the specification.
1390 pub log2_max_mv_length_vertical: u32,
1391 /// Indicates an upper bound for the number of frames buffers, in the
1392 /// decoded picture buffer (DPB), that are required for storing frames,
1393 /// complementary field pairs, and non-paired fields before output. It is a
1394 /// requirement of bitstream conformance that the maximum number of frames,
1395 /// complementary field pairs, or non-paired fields that precede any frame,
1396 /// complementary field pair, or non-paired field in the coded video
1397 /// sequence in decoding order and follow it in output order shall be less
1398 /// than or equal to max_num_reorder_frames. The value of
1399 /// max_num_reorder_frames shall be in the range of 0 to
1400 /// max_dec_frame_buffering, inclusive.
1401 ///
1402 /// When the max_num_reorder_frames syntax element is not present, the value
1403 /// of max_num_reorder_frames value shall be inferred as follows:
1404 /// If profile_idc is equal to 44, 86, 100, 110, 122, or 244 and
1405 /// constraint_set3_flag is equal to 1, the value of max_num_reorder_frames
1406 /// shall be inferred to be equal to 0.
1407 ///
1408 /// Otherwise (profile_idc is not equal to 44, 86, 100, 110, 122, or 244 or
1409 /// constraint_set3_flag is equal to 0), the value of max_num_reorder_frames
1410 /// shall be inferred to be equal to MaxDpbFrames.
1411 pub max_num_reorder_frames: u32,
1412 /// Specifies the required size of the HRD decoded picture buffer (DPB) in
1413 /// units of frame buffers. It is a requirement of bitstream conformance
1414 /// that the coded video sequence shall not require a decoded picture buffer
1415 /// with size of more than Max( 1, max_dec_frame_buffering ) frame buffers
1416 /// to enable the output of decoded pictures at the output times specified
1417 /// by dpb_output_delay of the picture timing SEI messages. The value of
1418 /// max_dec_frame_buffering shall be greater than or equal to
1419 /// max_num_ref_frames. An upper bound for the value of
1420 /// max_dec_frame_buffering is specified by the level limits in clauses
1421 /// A.3.1, A.3.2, G.10.2.1, and H.10.2.
1422 ///
1423 /// When the max_dec_frame_buffering syntax element is not present, the
1424 /// value of max_dec_frame_buffering shall be inferred as follows:
1425 ///
1426 /// If profile_idc is equal to 44, 86, 100, 110, 122, or 244 and
1427 /// constraint_set3_flag is equal to 1, the value of max_dec_frame_buffering
1428 /// shall be inferred to be equal to 0.
1429 ///
1430 /// Otherwise (profile_idc is not equal to 44, 86, 100, 110, 122, or 244 or
1431 /// constraint_set3_flag is equal to 0), the value of
1432 /// max_dec_frame_buffering shall be inferred to be equal to MaxDpbFrames.
1433 pub max_dec_frame_buffering: u32,
1434}
1435
1436impl Default for VuiParams {
1437 fn default() -> Self {
1438 Self {
1439 aspect_ratio_info_present_flag: Default::default(),
1440 aspect_ratio_idc: Default::default(),
1441 sar_width: Default::default(),
1442 sar_height: Default::default(),
1443 overscan_info_present_flag: Default::default(),
1444 overscan_appropriate_flag: Default::default(),
1445 video_signal_type_present_flag: Default::default(),
1446 video_format: 5,
1447 video_full_range_flag: Default::default(),
1448 colour_description_present_flag: Default::default(),
1449 colour_primaries: 2,
1450 transfer_characteristics: 2,
1451 matrix_coefficients: 2,
1452 chroma_loc_info_present_flag: Default::default(),
1453 chroma_sample_loc_type_top_field: Default::default(),
1454 chroma_sample_loc_type_bottom_field: Default::default(),
1455 timing_info_present_flag: Default::default(),
1456 num_units_in_tick: Default::default(),
1457 time_scale: Default::default(),
1458 fixed_frame_rate_flag: Default::default(),
1459 nal_hrd_parameters_present_flag: Default::default(),
1460 nal_hrd_parameters: Default::default(),
1461 vcl_hrd_parameters_present_flag: Default::default(),
1462 vcl_hrd_parameters: Default::default(),
1463 low_delay_hrd_flag: Default::default(),
1464 pic_struct_present_flag: Default::default(),
1465 bitstream_restriction_flag: Default::default(),
1466 motion_vectors_over_pic_boundaries_flag: Default::default(),
1467 max_bytes_per_pic_denom: Default::default(),
1468 max_bits_per_mb_denom: Default::default(),
1469 log2_max_mv_length_horizontal: Default::default(),
1470 log2_max_mv_length_vertical: Default::default(),
1471 max_num_reorder_frames: Default::default(),
1472 max_dec_frame_buffering: Default::default(),
1473 }
1474 }
1475}
1476
1477/// A H264 Picture Parameter Set. A syntax structure containing syntax elements
1478/// that apply to zero or more entire coded pictures as determined by the
1479/// `pic_parameter_set_id` syntax element found in each slice header.
1480#[derive(Debug, PartialEq, Eq)]
1481pub struct Pps {
1482 /// Identifies the picture parameter set that is referred to in the slice header.
1483 pub pic_parameter_set_id: u8,
1484
1485 /// Refers to the active sequence parameter set.
1486 pub seq_parameter_set_id: u8,
1487
1488 /// Selects the entropy decoding method to be applied for the syntax
1489 /// elements for which two descriptors appear in the syntax tables as
1490 /// follows: If `entropy_coding_mode_flag` is false, the method specified by
1491 /// the left descriptor in the syntax table is applied (Exp-Golomb coded,
1492 /// see clause 9.1 or CAVLC, see clause 9.2). Otherwise
1493 /// (`entropy_coding_mode_flag` is true), the method specified by the right
1494 /// descriptor in the syntax table is applied (CABAC, see clause 9.3).
1495 pub entropy_coding_mode_flag: bool,
1496
1497 /// If true, specifies that the syntax elements delta_pic_order_cnt_bottom
1498 /// (when `pic_order_cnt_type` is equal to 0) or `delta_pic_order_cnt[1]`
1499 /// (when `pic_order_cnt_type` is equal to 1), which are related to picture
1500 /// order counts for the bottom field of a coded frame, are present in the
1501 /// slice headers for coded frames as specified in clause 7.3.3. Otherwise,
1502 /// specifies that the syntax elements `delta_pic_order_cnt_bottom` and
1503 /// `delta_pic_order_cnt[1]` are not present in the slice headers.
1504 pub bottom_field_pic_order_in_frame_present_flag: bool,
1505
1506 /// Plus 1 specifies the number of slice groups for a picture. When
1507 /// `num_slice_groups_minus1` is equal to 0, all slices of the picture
1508 /// belong to the same slice group. The allowed range of
1509 /// `num_slice_groups_minus1` is specified in Annex A.
1510 pub num_slice_groups_minus1: u32,
1511
1512 /// Specifies how `num_ref_idx_l0_active_minus1` is inferred for P, SP, and
1513 /// B slices with `num_ref_idx_active_override_flag` not set.
1514 pub num_ref_idx_l0_default_active_minus1: u8,
1515
1516 /// Specifies how `num_ref_idx_l1_active_minus1` is inferred for B slices
1517 /// with `num_ref_idx_active_override_flag` not set.
1518 pub num_ref_idx_l1_default_active_minus1: u8,
1519
1520 /// If not set, specifies that the default weighted prediction shall be
1521 /// applied to P and SP slices. If set, specifies that explicit weighted
1522 /// prediction shall be applied to P and SP slices.
1523 pub weighted_pred_flag: bool,
1524
1525 /// `weighted_bipred_idc` equal to 0 specifies that the default weighted
1526 /// prediction shall be applied to B slices. `weighted_bipred_idc` equal to
1527 /// 1 specifies that explicit weighted prediction shall be applied to B
1528 /// slices. `weighted_bipred_idc` equal to 2 specifies that implicit
1529 /// weighted prediction shall be applied to B slices
1530 pub weighted_bipred_idc: u8,
1531
1532 /// Specifies the initial value minus 26 of SliceQPY for each slice. The
1533 /// initial value is modified at the slice layer when a non-zero value of
1534 /// `slice_qp_delta` is decoded, and is modified further when a non-zero
1535 /// value of `mb_qp_delta` is decoded at the macroblock layer.
1536 pub pic_init_qp_minus26: i8,
1537
1538 /// Specifies the initial value minus 26 of SliceQSY for all macroblocks in
1539 /// SP or SI slices. The initial value is modified at the slice layer when a
1540 /// non-zero value of `slice_qs_delta` is decoded.
1541 pub pic_init_qs_minus26: i8,
1542
1543 /// Specifies the offset that shall be added to QP Y and QSY for addressing
1544 /// the table of QPC values for the Cb chroma component.
1545 pub chroma_qp_index_offset: i8,
1546
1547 /// If set, specifies that a set of syntax elements controlling the
1548 /// characteristics of the deblocking filter is present in the slice header.
1549 /// If not set, specifies that the set of syntax elements controlling the
1550 /// characteristics of the deblocking filter is not present in the slice
1551 /// headers and their inferred values are in effect.
1552 pub deblocking_filter_control_present_flag: bool,
1553
1554 /// If not set, specifies that intra prediction allows usage of residual
1555 /// data and decoded samples of neighbouring macroblocks coded using Inter
1556 /// macroblock prediction modes for the prediction of macroblocks coded
1557 /// using Intra macroblock prediction modes. If set, specifies constrained
1558 /// intra prediction, in which case prediction of macroblocks coded using
1559 /// Intra macroblock prediction modes only uses residual data and decoded
1560 /// samples from I or SI macroblock types.
1561 pub constrained_intra_pred_flag: bool,
1562
1563 /// If not set, specifies that the `redundant_pic_cnt` syntax element is not
1564 /// present in slice headers, coded slice data partition B NAL units, and
1565 /// coded slice data partition C NAL units that refer (either directly or by
1566 /// association with a corresponding coded slice data partition A NAL unit)
1567 /// to the picture parameter set. If set, specifies that the
1568 /// `redundant_pic_cnt` syntax element is present in all slice headers,
1569 /// coded slice data partition B NAL units, and coded slice data partition C
1570 /// NAL units that refer (either directly or by association with a
1571 /// corresponding coded slice data partition A NAL unit) to the picture
1572 /// parameter set.
1573 pub redundant_pic_cnt_present_flag: bool,
1574
1575 /// If set, specifies that the 8x8 transform decoding process may be in use
1576 /// (see clause 8.5). If not set, specifies that the 8x8 transform decoding
1577 /// process is not in use.
1578 pub transform_8x8_mode_flag: bool,
1579
1580 /// If set, specifies that parameters are present to modify the scaling
1581 /// lists specified in the sequence parameter set. If not set, specifies
1582 /// that the scaling lists used for the picture shall be inferred to be
1583 /// equal to those specified by the sequence parameter set.
1584 pub pic_scaling_matrix_present_flag: bool,
1585
1586 /// 4x4 Scaling list as read with 7.3.2.1.1.1
1587 pub scaling_lists_4x4: [[u8; 16]; 6],
1588 /// 8x8 Scaling list as read with 7.3.2.1.1.1
1589 pub scaling_lists_8x8: [[u8; 64]; 6],
1590
1591 /// Specifies the offset that shall be added to QPY and QSY for addressing
1592 /// the table of QPC values for the Cr chroma component. When
1593 /// `second_chroma_qp_index_offset` is not present, it shall be inferred to be
1594 /// equal to `chroma_qp_index_offset`.
1595 pub second_chroma_qp_index_offset: i8,
1596
1597 /// The SPS referenced by this PPS.
1598 pub sps: Rc<Sps>,
1599}
1600
1601pub struct PpsBuilder(Pps);
1602
1603impl PpsBuilder {
1604 pub fn new(sps: Rc<Sps>) -> Self {
1605 PpsBuilder(Pps {
1606 pic_parameter_set_id: 0,
1607 seq_parameter_set_id: sps.seq_parameter_set_id,
1608 entropy_coding_mode_flag: false,
1609 bottom_field_pic_order_in_frame_present_flag: false,
1610 num_slice_groups_minus1: 0,
1611 num_ref_idx_l0_default_active_minus1: 0,
1612 num_ref_idx_l1_default_active_minus1: 0,
1613 weighted_pred_flag: false,
1614 weighted_bipred_idc: 0,
1615 pic_init_qp_minus26: 0,
1616 pic_init_qs_minus26: 0,
1617 chroma_qp_index_offset: 0,
1618 deblocking_filter_control_present_flag: false,
1619 constrained_intra_pred_flag: false,
1620 redundant_pic_cnt_present_flag: false,
1621 transform_8x8_mode_flag: false,
1622 pic_scaling_matrix_present_flag: false,
1623 scaling_lists_4x4: [[0; 16]; 6],
1624 scaling_lists_8x8: [[0; 64]; 6],
1625 second_chroma_qp_index_offset: 0,
1626 sps,
1627 })
1628 }
1629
1630 pub fn pic_parameter_set_id(mut self, value: u8) -> Self {
1631 self.0.pic_parameter_set_id = value;
1632 self
1633 }
1634
1635 pub fn pic_init_qp_minus26(mut self, value: i8) -> Self {
1636 self.0.pic_init_qp_minus26 = value;
1637 self
1638 }
1639
1640 pub fn pic_init_qp(self, value: u8) -> Self {
1641 self.pic_init_qp_minus26(value as i8 - 26)
1642 }
1643
1644 pub fn deblocking_filter_control_present_flag(mut self, value: bool) -> Self {
1645 self.0.deblocking_filter_control_present_flag = value;
1646 self
1647 }
1648
1649 pub fn num_ref_idx_l0_default_active_minus1(mut self, value: u8) -> Self {
1650 self.0.num_ref_idx_l0_default_active_minus1 = value;
1651 self
1652 }
1653
1654 pub fn num_ref_idx_l0_default_active(self, value: u8) -> Self {
1655 self.num_ref_idx_l0_default_active_minus1(value - 1)
1656 }
1657
1658 pub fn num_ref_idx_l1_default_active_minus1(mut self, value: u8) -> Self {
1659 self.0.num_ref_idx_l1_default_active_minus1 = value;
1660 self
1661 }
1662
1663 pub fn num_ref_idx_l1_default_active(self, value: u8) -> Self {
1664 self.num_ref_idx_l1_default_active_minus1(value - 1)
1665 }
1666
1667 pub fn build(self) -> Rc<Pps> {
1668 Rc::new(self.0)
1669 }
1670}
1671
1672#[derive(Debug, Default)]
1673pub struct Parser {
1674 active_spses: BTreeMap<u8, Rc<Sps>>,
1675 active_ppses: BTreeMap<u8, Rc<Pps>>,
1676}
1677
1678impl Parser {
1679 fn fill_default_scaling_list_4x4(scaling_list4x4: &mut [u8; 16], i: usize) {
1680 // See table 7.2 in the spec.
1681 assert!(i < 6);
1682 if i < 3 {
1683 *scaling_list4x4 = DEFAULT_4X4_INTRA;
1684 } else if i < 6 {
1685 *scaling_list4x4 = DEFAULT_4X4_INTER;
1686 }
1687 }
1688
1689 fn fill_default_scaling_list_8x8(scaling_list8x8: &mut [u8; 64], i: usize) {
1690 assert!(i < 6);
1691 if i % 2 == 0 {
1692 *scaling_list8x8 = DEFAULT_8X8_INTRA;
1693 } else {
1694 *scaling_list8x8 = DEFAULT_8X8_INTER;
1695 }
1696 }
1697
1698 fn fill_fallback_scaling_list_4x4(
1699 scaling_list4x4: &mut [[u8; 16]; 6],
1700 i: usize,
1701 default_scaling_list_intra: &[u8; 16],
1702 default_scaling_list_inter: &[u8; 16],
1703 ) {
1704 // See table 7.2 in the spec.
1705 scaling_list4x4[i] = match i {
1706 0 => *default_scaling_list_intra,
1707 1 => scaling_list4x4[0],
1708 2 => scaling_list4x4[1],
1709 3 => *default_scaling_list_inter,
1710 4 => scaling_list4x4[3],
1711 5 => scaling_list4x4[4],
1712 _ => panic!("Unexpected value {}", i),
1713 }
1714 }
1715
1716 fn fill_fallback_scaling_list_8x8(
1717 scaling_list8x8: &mut [[u8; 64]; 6],
1718 i: usize,
1719 default_scaling_list_intra: &[u8; 64],
1720 default_scaling_list_inter: &[u8; 64],
1721 ) {
1722 // See table 7.2 in the spec.
1723 scaling_list8x8[i] = match i {
1724 0 => *default_scaling_list_intra,
1725 1 => *default_scaling_list_inter,
1726 2 => scaling_list8x8[0],
1727 3 => scaling_list8x8[1],
1728 4 => scaling_list8x8[2],
1729 5 => scaling_list8x8[3],
1730 _ => panic!("Unexpected value {}", i),
1731 }
1732 }
1733
1734 fn fill_scaling_list_flat(
1735 scaling_list4x4: &mut [[u8; 16]; 6],
1736 scaling_list8x8: &mut [[u8; 64]; 6],
1737 ) {
1738 // (7-8) in the spec.
1739 for outer in scaling_list4x4 {
1740 for inner in outer {
1741 *inner = 16;
1742 }
1743 }
1744
1745 // (7-9) in the spec.
1746 for outer in scaling_list8x8 {
1747 for inner in outer {
1748 *inner = 16;
1749 }
1750 }
1751 }
1752
1753 fn parse_scaling_list<U: AsMut<[u8]>>(
1754 r: &mut BitReader,
1755 scaling_list: &mut U,
1756 use_default: &mut bool,
1757 ) -> Result<(), String> {
1758 // 7.3.2.1.1.1
1759 let mut last_scale = 8u8;
1760 let mut next_scale = 8u8;
1761
1762 for j in 0..scaling_list.as_mut().len() {
1763 if next_scale != 0 {
1764 let delta_scale = r.read_se::<i32>()?;
1765 next_scale = ((last_scale as i32 + delta_scale + 256) % 256) as u8;
1766 *use_default = j == 0 && next_scale == 0;
1767 if *use_default {
1768 return Ok(());
1769 }
1770 }
1771
1772 scaling_list.as_mut()[j] = if next_scale == 0 { last_scale } else { next_scale };
1773
1774 last_scale = scaling_list.as_mut()[j];
1775 }
1776
1777 Ok(())
1778 }
1779
1780 fn parse_sps_scaling_lists(r: &mut BitReader, sps: &mut Sps) -> Result<(), String> {
1781 let scaling_lists4x4 = &mut sps.scaling_lists_4x4;
1782 let scaling_lisst8x8 = &mut sps.scaling_lists_8x8;
1783
1784 // Parse scaling_list4x4
1785 for i in 0..6 {
1786 let seq_scaling_list_present_flag = r.read_bit()?;
1787 if seq_scaling_list_present_flag {
1788 let mut use_default = false;
1789
1790 Parser::parse_scaling_list(r, &mut scaling_lists4x4[i], &mut use_default)?;
1791
1792 if use_default {
1793 Parser::fill_default_scaling_list_4x4(&mut scaling_lists4x4[i], i);
1794 }
1795 } else {
1796 Parser::fill_fallback_scaling_list_4x4(
1797 scaling_lists4x4,
1798 i,
1799 &DEFAULT_4X4_INTRA,
1800 &DEFAULT_4X4_INTER,
1801 );
1802 }
1803 }
1804
1805 // Parse scaling_list8x8
1806 let num_8x8 = if sps.chroma_format_idc != 3 { 2 } else { 6 };
1807 for i in 0..num_8x8 {
1808 let seq_scaling_list_present_flag = r.read_bit()?;
1809 if seq_scaling_list_present_flag {
1810 let mut use_default = false;
1811 Parser::parse_scaling_list(r, &mut scaling_lisst8x8[i], &mut use_default)?;
1812
1813 if use_default {
1814 Parser::fill_default_scaling_list_8x8(&mut scaling_lisst8x8[i], i);
1815 }
1816 } else {
1817 Parser::fill_fallback_scaling_list_8x8(
1818 scaling_lisst8x8,
1819 i,
1820 &DEFAULT_8X8_INTRA,
1821 &DEFAULT_8X8_INTER,
1822 );
1823 }
1824 }
1825 Ok(())
1826 }
1827
1828 fn parse_pps_scaling_lists(r: &mut BitReader, pps: &mut Pps, sps: &Sps) -> Result<(), String> {
1829 let scaling_lists4x4 = &mut pps.scaling_lists_4x4;
1830 let scaling_lists8x8 = &mut pps.scaling_lists_8x8;
1831
1832 for i in 0..6 {
1833 let pic_scaling_list_present_flag = r.read_bit()?;
1834 if pic_scaling_list_present_flag {
1835 let mut use_default = false;
1836
1837 Parser::parse_scaling_list(r, &mut scaling_lists4x4[i], &mut use_default)?;
1838
1839 if use_default {
1840 Parser::fill_default_scaling_list_4x4(&mut scaling_lists4x4[i], i);
1841 }
1842 } else if !sps.seq_scaling_matrix_present_flag {
1843 // Table 7-2: Fallback rule A
1844 Parser::fill_fallback_scaling_list_4x4(
1845 scaling_lists4x4,
1846 i,
1847 &DEFAULT_4X4_INTRA,
1848 &DEFAULT_4X4_INTER,
1849 );
1850 } else {
1851 // Table 7-2: Fallback rule B
1852 Parser::fill_fallback_scaling_list_4x4(
1853 scaling_lists4x4,
1854 i,
1855 &sps.scaling_lists_4x4[0],
1856 &sps.scaling_lists_4x4[3],
1857 );
1858 }
1859 }
1860
1861 if pps.transform_8x8_mode_flag {
1862 let num8x8 = if sps.chroma_format_idc != 3 { 2 } else { 6 };
1863
1864 for i in 0..num8x8 {
1865 let pic_scaling_list_present_flag = r.read_bit()?;
1866 if pic_scaling_list_present_flag {
1867 let mut use_default = false;
1868
1869 Parser::parse_scaling_list(r, &mut scaling_lists8x8[i], &mut use_default)?;
1870
1871 if use_default {
1872 Parser::fill_default_scaling_list_8x8(&mut scaling_lists8x8[i], i);
1873 }
1874 } else if !sps.seq_scaling_matrix_present_flag {
1875 // Table 7-2: Fallback rule A
1876 Parser::fill_fallback_scaling_list_8x8(
1877 scaling_lists8x8,
1878 i,
1879 &DEFAULT_8X8_INTRA,
1880 &DEFAULT_8X8_INTER,
1881 );
1882 } else {
1883 // Table 7-2: Fallback rule B
1884 Parser::fill_fallback_scaling_list_8x8(
1885 scaling_lists8x8,
1886 i,
1887 &sps.scaling_lists_8x8[0],
1888 &sps.scaling_lists_8x8[1],
1889 );
1890 }
1891 }
1892 }
1893
1894 Ok(())
1895 }
1896
1897 fn parse_hrd(r: &mut BitReader, hrd: &mut HrdParams) -> Result<(), String> {
1898 hrd.cpb_cnt_minus1 = r.read_ue_max(31)?;
1899 hrd.bit_rate_scale = r.read_bits(4)?;
1900 hrd.cpb_size_scale = r.read_bits(4)?;
1901
1902 for sched_sel_idx in 0..=usize::from(hrd.cpb_cnt_minus1) {
1903 hrd.bit_rate_value_minus1[sched_sel_idx] = r.read_ue()?;
1904 hrd.cpb_size_value_minus1[sched_sel_idx] = r.read_ue()?;
1905 hrd.cbr_flag[sched_sel_idx] = r.read_bit()?;
1906 }
1907
1908 hrd.initial_cpb_removal_delay_length_minus1 = r.read_bits(5)?;
1909 hrd.cpb_removal_delay_length_minus1 = r.read_bits(5)?;
1910 hrd.dpb_output_delay_length_minus1 = r.read_bits(5)?;
1911 hrd.time_offset_length = r.read_bits(5)?;
1912 Ok(())
1913 }
1914
1915 fn parse_vui(r: &mut BitReader, sps: &mut Sps) -> Result<(), String> {
1916 let vui = &mut sps.vui_parameters;
1917
1918 vui.aspect_ratio_info_present_flag = r.read_bit()?;
1919 if vui.aspect_ratio_info_present_flag {
1920 vui.aspect_ratio_idc = r.read_bits(8)?;
1921 if vui.aspect_ratio_idc == 255 {
1922 vui.sar_width = r.read_bits(16)?;
1923 vui.sar_height = r.read_bits(16)?;
1924 }
1925 }
1926
1927 vui.overscan_info_present_flag = r.read_bit()?;
1928 if vui.overscan_info_present_flag {
1929 vui.overscan_appropriate_flag = r.read_bit()?;
1930 }
1931
1932 vui.video_signal_type_present_flag = r.read_bit()?;
1933 if vui.video_signal_type_present_flag {
1934 vui.video_format = r.read_bits(3)?;
1935 vui.video_full_range_flag = r.read_bit()?;
1936 vui.colour_description_present_flag = r.read_bit()?;
1937 if vui.colour_description_present_flag {
1938 vui.colour_primaries = r.read_bits(8)?;
1939 vui.transfer_characteristics = r.read_bits(8)?;
1940 vui.matrix_coefficients = r.read_bits(8)?;
1941 }
1942 }
1943
1944 vui.chroma_loc_info_present_flag = r.read_bit()?;
1945 if vui.chroma_loc_info_present_flag {
1946 vui.chroma_sample_loc_type_top_field = r.read_ue_max(5)?;
1947 vui.chroma_sample_loc_type_bottom_field = r.read_ue_max(5)?;
1948 }
1949
1950 vui.timing_info_present_flag = r.read_bit()?;
1951 if vui.timing_info_present_flag {
1952 vui.num_units_in_tick = r.read_bits::<u32>(31)? << 1;
1953 vui.num_units_in_tick |= r.read_bit()? as u32;
1954 if vui.num_units_in_tick == 0 {
1955 return Err("num_units_in_tick == 0, which is not allowed by E.2.1".into());
1956 }
1957
1958 vui.time_scale = r.read_bits::<u32>(31)? << 1;
1959 vui.time_scale |= r.read_bit()? as u32;
1960 if vui.time_scale == 0 {
1961 return Err("time_scale == 0, which is not allowed by E.2.1".into());
1962 }
1963
1964 vui.fixed_frame_rate_flag = r.read_bit()?;
1965 }
1966
1967 vui.nal_hrd_parameters_present_flag = r.read_bit()?;
1968 if vui.nal_hrd_parameters_present_flag {
1969 Parser::parse_hrd(r, &mut vui.nal_hrd_parameters)?;
1970 }
1971
1972 vui.vcl_hrd_parameters_present_flag = r.read_bit()?;
1973 if vui.vcl_hrd_parameters_present_flag {
1974 Parser::parse_hrd(r, &mut vui.vcl_hrd_parameters)?;
1975 }
1976
1977 if vui.nal_hrd_parameters_present_flag || vui.vcl_hrd_parameters_present_flag {
1978 vui.low_delay_hrd_flag = r.read_bit()?;
1979 }
1980
1981 vui.pic_struct_present_flag = r.read_bit()?;
1982 vui.bitstream_restriction_flag = r.read_bit()?;
1983
1984 if vui.bitstream_restriction_flag {
1985 vui.motion_vectors_over_pic_boundaries_flag = r.read_bit()?;
1986 vui.max_bytes_per_pic_denom = r.read_ue()?;
1987 vui.max_bits_per_mb_denom = r.read_ue_max(16)?;
1988 vui.log2_max_mv_length_horizontal = r.read_ue_max(16)?;
1989 vui.log2_max_mv_length_vertical = r.read_ue_max(16)?;
1990 vui.max_num_reorder_frames = r.read_ue()?;
1991 vui.max_dec_frame_buffering = r.read_ue()?;
1992 }
1993
1994 Ok(())
1995 }
1996
1997 /// Parse a SPS and add it to the list of active SPSes.
1998 ///
1999 /// Returns a reference to the new SPS.
2000 pub fn parse_sps(&mut self, nalu: &Nalu) -> Result<&Rc<Sps>, String> {
2001 if !matches!(nalu.header.type_, NaluType::Sps) {
2002 return Err(format!(
2003 "Invalid NALU type, expected {:?}, got {:?}",
2004 NaluType::Sps,
2005 nalu.header.type_
2006 ));
2007 }
2008
2009 let data = nalu.as_ref();
2010 // Skip the header
2011 let mut r = BitReader::new(&data[nalu.header.len()..], true);
2012 let mut sps = Sps {
2013 profile_idc: r.read_bits(8)?,
2014 constraint_set0_flag: r.read_bit()?,
2015 constraint_set1_flag: r.read_bit()?,
2016 constraint_set2_flag: r.read_bit()?,
2017 constraint_set3_flag: r.read_bit()?,
2018 constraint_set4_flag: r.read_bit()?,
2019 constraint_set5_flag: r.read_bit()?,
2020 ..Default::default()
2021 };
2022
2023 // skip reserved_zero_2bits
2024 r.skip_bits(2)?;
2025
2026 let level: u8 = r.read_bits(8)?;
2027 sps.level_idc = Level::try_from(level)?;
2028 sps.seq_parameter_set_id = r.read_ue_max(31)?;
2029
2030 if sps.profile_idc == 100
2031 || sps.profile_idc == 110
2032 || sps.profile_idc == 122
2033 || sps.profile_idc == 244
2034 || sps.profile_idc == 44
2035 || sps.profile_idc == 83
2036 || sps.profile_idc == 86
2037 || sps.profile_idc == 118
2038 || sps.profile_idc == 128
2039 || sps.profile_idc == 138
2040 || sps.profile_idc == 139
2041 || sps.profile_idc == 134
2042 || sps.profile_idc == 135
2043 {
2044 sps.chroma_format_idc = r.read_ue_max(3)?;
2045 if sps.chroma_format_idc == 3 {
2046 sps.separate_colour_plane_flag = r.read_bit()?;
2047 }
2048
2049 sps.bit_depth_luma_minus8 = r.read_ue_max(6)?;
2050 sps.bit_depth_chroma_minus8 = r.read_ue_max(6)?;
2051 sps.qpprime_y_zero_transform_bypass_flag = r.read_bit()?;
2052 sps.seq_scaling_matrix_present_flag = r.read_bit()?;
2053
2054 if sps.seq_scaling_matrix_present_flag {
2055 Parser::parse_sps_scaling_lists(&mut r, &mut sps)?;
2056 } else {
2057 Parser::fill_scaling_list_flat(
2058 &mut sps.scaling_lists_4x4,
2059 &mut sps.scaling_lists_8x8,
2060 );
2061 }
2062 } else {
2063 sps.chroma_format_idc = 1;
2064 Parser::fill_scaling_list_flat(&mut sps.scaling_lists_4x4, &mut sps.scaling_lists_8x8);
2065 }
2066
2067 sps.log2_max_frame_num_minus4 = r.read_ue_max(12)?;
2068
2069 sps.pic_order_cnt_type = r.read_ue_max(2)?;
2070
2071 if sps.pic_order_cnt_type == 0 {
2072 sps.log2_max_pic_order_cnt_lsb_minus4 = r.read_ue_max(12)?;
2073 sps.expected_delta_per_pic_order_cnt_cycle = 0;
2074 } else if sps.pic_order_cnt_type == 1 {
2075 sps.delta_pic_order_always_zero_flag = r.read_bit()?;
2076 sps.offset_for_non_ref_pic = r.read_se()?;
2077 sps.offset_for_top_to_bottom_field = r.read_se()?;
2078 sps.num_ref_frames_in_pic_order_cnt_cycle = r.read_ue_max(254)?;
2079
2080 let mut offset_acc = 0;
2081 for i in 0..usize::from(sps.num_ref_frames_in_pic_order_cnt_cycle) {
2082 sps.offset_for_ref_frame[i] = r.read_se()?;
2083
2084 // (7-12) in the spec.
2085 offset_acc += sps.offset_for_ref_frame[i];
2086 }
2087
2088 sps.expected_delta_per_pic_order_cnt_cycle = offset_acc;
2089 }
2090
2091 sps.max_num_ref_frames = r.read_ue_max(DPB_MAX_SIZE as u32)?;
2092 sps.gaps_in_frame_num_value_allowed_flag = r.read_bit()?;
2093 sps.pic_width_in_mbs_minus1 = r.read_ue()?;
2094 sps.pic_height_in_map_units_minus1 = r.read_ue()?;
2095 sps.frame_mbs_only_flag = r.read_bit()?;
2096
2097 if !sps.frame_mbs_only_flag {
2098 sps.mb_adaptive_frame_field_flag = r.read_bit()?;
2099 }
2100
2101 sps.direct_8x8_inference_flag = r.read_bit()?;
2102 sps.frame_cropping_flag = r.read_bit()?;
2103
2104 if sps.frame_cropping_flag {
2105 sps.frame_crop_left_offset = r.read_ue()?;
2106 sps.frame_crop_right_offset = r.read_ue()?;
2107 sps.frame_crop_top_offset = r.read_ue()?;
2108 sps.frame_crop_bottom_offset = r.read_ue()?;
2109
2110 // Validate that cropping info is valid.
2111 let (crop_unit_x, crop_unit_y) = sps.crop_unit_x_y();
2112
2113 let _ = sps
2114 .frame_crop_left_offset
2115 .checked_add(sps.frame_crop_right_offset)
2116 .and_then(|r| r.checked_mul(crop_unit_x))
2117 .and_then(|r| sps.width().checked_sub(r))
2118 .ok_or::<String>("Invalid frame crop width".into())?;
2119
2120 let _ = sps
2121 .frame_crop_top_offset
2122 .checked_add(sps.frame_crop_bottom_offset)
2123 .and_then(|r| r.checked_mul(crop_unit_y))
2124 .and_then(|r| sps.height().checked_sub(r))
2125 .ok_or::<String>("invalid frame crop height".into())?;
2126 }
2127
2128 sps.vui_parameters_present_flag = r.read_bit()?;
2129 if sps.vui_parameters_present_flag {
2130 Parser::parse_vui(&mut r, &mut sps)?;
2131 }
2132
2133 let key = sps.seq_parameter_set_id;
2134
2135 if self.active_spses.keys().len() >= MAX_SPS_COUNT as usize {
2136 return Err("Broken data: Number of active SPSs > MAX_SPS_COUNT".into());
2137 }
2138
2139 let sps = Rc::new(sps);
2140 self.active_spses.remove(&key);
2141 Ok(self.active_spses.entry(key).or_insert(sps))
2142 }
2143
2144 pub fn parse_pps(&mut self, nalu: &Nalu) -> Result<&Pps, String> {
2145 if !matches!(nalu.header.type_, NaluType::Pps) {
2146 return Err(format!(
2147 "Invalid NALU type, expected {:?}, got {:?}",
2148 NaluType::Pps,
2149 nalu.header.type_
2150 ));
2151 }
2152
2153 let data = nalu.as_ref();
2154 // Skip the header
2155 let mut r = BitReader::new(&data[nalu.header.len()..], true);
2156 let pic_parameter_set_id = r.read_ue_max(MAX_PPS_COUNT as u32 - 1)?;
2157 let seq_parameter_set_id = r.read_ue_max(MAX_SPS_COUNT as u32 - 1)?;
2158 let sps = self.get_sps(seq_parameter_set_id).ok_or::<String>(format!(
2159 "Could not get SPS for seq_parameter_set_id {}",
2160 seq_parameter_set_id
2161 ))?;
2162 let mut pps = Pps {
2163 pic_parameter_set_id,
2164 seq_parameter_set_id,
2165 sps: Rc::clone(sps),
2166 scaling_lists_4x4: [[0; 16]; 6],
2167 scaling_lists_8x8: [[0; 64]; 6],
2168 entropy_coding_mode_flag: Default::default(),
2169 bottom_field_pic_order_in_frame_present_flag: Default::default(),
2170 num_slice_groups_minus1: Default::default(),
2171 num_ref_idx_l0_default_active_minus1: Default::default(),
2172 num_ref_idx_l1_default_active_minus1: Default::default(),
2173 weighted_pred_flag: Default::default(),
2174 weighted_bipred_idc: Default::default(),
2175 pic_init_qp_minus26: Default::default(),
2176 pic_init_qs_minus26: Default::default(),
2177 chroma_qp_index_offset: Default::default(),
2178 deblocking_filter_control_present_flag: Default::default(),
2179 constrained_intra_pred_flag: Default::default(),
2180 redundant_pic_cnt_present_flag: Default::default(),
2181 transform_8x8_mode_flag: Default::default(),
2182 second_chroma_qp_index_offset: Default::default(),
2183 pic_scaling_matrix_present_flag: Default::default(),
2184 };
2185
2186 pps.entropy_coding_mode_flag = r.read_bit()?;
2187 pps.bottom_field_pic_order_in_frame_present_flag = r.read_bit()?;
2188 pps.num_slice_groups_minus1 = r.read_ue_max(7)?;
2189
2190 if pps.num_slice_groups_minus1 > 0 {
2191 return Err("Stream contain unsupported/unimplemented NALs".into());
2192 }
2193
2194 pps.num_ref_idx_l0_default_active_minus1 = r.read_ue_max(31)?;
2195 pps.num_ref_idx_l1_default_active_minus1 = r.read_ue_max(31)?;
2196
2197 pps.weighted_pred_flag = r.read_bit()?;
2198 pps.weighted_bipred_idc = r.read_bits(2)?;
2199
2200 let qp_bd_offset_y = i32::from(6 * (sps.bit_depth_luma_minus8));
2201 pps.pic_init_qp_minus26 = r.read_se_bounded(-(26 + qp_bd_offset_y), 25)?;
2202 pps.pic_init_qs_minus26 = r.read_se_bounded(-26, 25)?;
2203
2204 pps.chroma_qp_index_offset = r.read_se_bounded(-12, 12)?;
2205
2206 // When second_chroma_qp_index_offset is not present, it shall be
2207 // inferred to be equal to chroma_qp_index_offset.
2208 pps.second_chroma_qp_index_offset = pps.chroma_qp_index_offset;
2209
2210 pps.deblocking_filter_control_present_flag = r.read_bit()?;
2211 pps.constrained_intra_pred_flag = r.read_bit()?;
2212 pps.redundant_pic_cnt_present_flag = r.read_bit()?;
2213
2214 if r.has_more_rsbp_data() {
2215 pps.transform_8x8_mode_flag = r.read_bit()?;
2216 pps.pic_scaling_matrix_present_flag = r.read_bit()?;
2217
2218 if pps.pic_scaling_matrix_present_flag {
2219 Parser::parse_pps_scaling_lists(&mut r, &mut pps, sps)?;
2220 }
2221
2222 pps.second_chroma_qp_index_offset = r.read_se()?;
2223 }
2224
2225 if !pps.pic_scaling_matrix_present_flag {
2226 // If not set, specifies that the scaling lists used for the picture
2227 // shall be inferred to be equal to those specified by the sequence
2228 // parameter set. When pic_scaling_matrix_present_flag is not
2229 // present, it shall be inferred to be not set.
2230 pps.scaling_lists_4x4 = sps.scaling_lists_4x4;
2231 pps.scaling_lists_8x8 = sps.scaling_lists_8x8;
2232 }
2233
2234 let key = pps.pic_parameter_set_id;
2235
2236 if self.active_ppses.keys().len() >= MAX_PPS_COUNT as usize {
2237 return Err("Broken Data: number of active PPSs > MAX_PPS_COUNT".into());
2238 }
2239
2240 let pps = Rc::new(pps);
2241 self.active_ppses.remove(&key);
2242 Ok(self.active_ppses.entry(key).or_insert(pps))
2243 }
2244
2245 fn parse_ref_pic_list_modification(
2246 r: &mut BitReader,
2247 num_ref_idx_active_minus1: u8,
2248 ref_list_mods: &mut Vec<RefPicListModification>,
2249 ) -> Result<(), String> {
2250 if num_ref_idx_active_minus1 >= 32 {
2251 return Err("Broken Data: num_ref_idx_active_minus1 >= 32".into());
2252 }
2253
2254 loop {
2255 let mut pic_num_mod = RefPicListModification {
2256 modification_of_pic_nums_idc: r.read_ue_max(3)?,
2257 ..Default::default()
2258 };
2259
2260 match pic_num_mod.modification_of_pic_nums_idc {
2261 0 | 1 => {
2262 pic_num_mod.abs_diff_pic_num_minus1 = r.read_ue()?;
2263 }
2264
2265 2 => {
2266 pic_num_mod.long_term_pic_num = r.read_ue()?;
2267 }
2268
2269 3 => {
2270 ref_list_mods.push(pic_num_mod);
2271 break;
2272 }
2273
2274 _ => return Err("Broken Data: modification_of_pic_nums_idc > 3".into()),
2275 }
2276
2277 ref_list_mods.push(pic_num_mod);
2278 }
2279
2280 Ok(())
2281 }
2282
2283 fn parse_ref_pic_list_modifications(
2284 r: &mut BitReader,
2285 header: &mut SliceHeader,
2286 ) -> Result<(), String> {
2287 if !header.slice_type.is_i() && !header.slice_type.is_si() {
2288 header.ref_pic_list_modification_flag_l0 = r.read_bit()?;
2289 if header.ref_pic_list_modification_flag_l0 {
2290 Parser::parse_ref_pic_list_modification(
2291 r,
2292 header.num_ref_idx_l0_active_minus1,
2293 &mut header.ref_pic_list_modification_l0,
2294 )?;
2295 }
2296 }
2297
2298 if header.slice_type.is_b() {
2299 header.ref_pic_list_modification_flag_l1 = r.read_bit()?;
2300 if header.ref_pic_list_modification_flag_l1 {
2301 Parser::parse_ref_pic_list_modification(
2302 r,
2303 header.num_ref_idx_l1_active_minus1,
2304 &mut header.ref_pic_list_modification_l1,
2305 )?;
2306 }
2307 }
2308
2309 Ok(())
2310 }
2311
2312 fn parse_pred_weight_table(
2313 r: &mut BitReader,
2314 sps: &Sps,
2315 header: &mut SliceHeader,
2316 ) -> Result<(), String> {
2317 let pt = &mut header.pred_weight_table;
2318 pt.luma_log2_weight_denom = r.read_ue_max(7)?;
2319
2320 // When luma_weight_l0_flag is equal to 0, luma_weight_l0[i] shall be
2321 // inferred to be equal to 2 ^ luma_log2_weight_denom for
2322 // RefPicList0[i].
2323 let default_luma_weight = 1 << pt.luma_log2_weight_denom;
2324 for i in 0..=header.num_ref_idx_l0_active_minus1 {
2325 pt.luma_weight_l0[usize::from(i)] = default_luma_weight;
2326 }
2327
2328 // When luma_weight_l1_flag is equal to 1, luma_weight_l1[i] shall be
2329 // inferred to be equal to 2 ^ luma_log2_weight_denom for
2330 // RefPicList1[i].
2331 if header.slice_type.is_b() {
2332 for i in 0..=header.num_ref_idx_l1_active_minus1 {
2333 pt.luma_weight_l1[usize::from(i)] = default_luma_weight;
2334 }
2335 }
2336
2337 if sps.chroma_array_type() != 0 {
2338 pt.chroma_log2_weight_denom = r.read_ue_max(7)?;
2339 let default_chroma_weight = 1 << pt.chroma_log2_weight_denom;
2340
2341 // When chroma_weight_l0_flag is equal to 0, chroma_weight_l0[i]
2342 // shall be inferred to be equal to 2 ^ chroma_log2_weight_denom for
2343 // RefPicList0[i].
2344 for i in 0..=header.num_ref_idx_l0_active_minus1 {
2345 pt.chroma_weight_l0[usize::from(i)][0] = default_chroma_weight;
2346 pt.chroma_weight_l0[usize::from(i)][1] = default_chroma_weight;
2347 }
2348
2349 // When chroma_weight_l1_flag is equal to 0, chroma_weight_l1[i]
2350 // shall be inferred to be equal to 2 ^ chroma_log2_weight_denom for
2351 // RefPicList1[i].
2352 for i in 0..=header.num_ref_idx_l1_active_minus1 {
2353 pt.chroma_weight_l1[usize::from(i)][0] = default_chroma_weight;
2354 pt.chroma_weight_l1[usize::from(i)][1] = default_chroma_weight;
2355 }
2356 }
2357
2358 for i in 0..=header.num_ref_idx_l0_active_minus1 {
2359 let luma_weight_l0_flag = r.read_bit()?;
2360
2361 if luma_weight_l0_flag {
2362 pt.luma_weight_l0[usize::from(i)] = r.read_se_bounded(-128, 127)?;
2363 pt.luma_offset_l0[usize::from(i)] = r.read_se_bounded(-128, 127)?;
2364 }
2365
2366 if sps.chroma_array_type() != 0 {
2367 let chroma_weight_l0_flag = r.read_bit()?;
2368 if chroma_weight_l0_flag {
2369 for j in 0..2 {
2370 pt.chroma_weight_l0[usize::from(i)][j] = r.read_se_bounded(-128, 127)?;
2371 pt.chroma_offset_l0[usize::from(i)][j] = r.read_se_bounded(-128, 127)?;
2372 }
2373 }
2374 }
2375 }
2376
2377 if header.slice_type.is_b() {
2378 for i in 0..=header.num_ref_idx_l1_active_minus1 {
2379 let luma_weight_l1_flag = r.read_bit()?;
2380
2381 if luma_weight_l1_flag {
2382 pt.luma_weight_l1[usize::from(i)] = r.read_se_bounded(-128, 127)?;
2383 pt.luma_offset_l1[usize::from(i)] = r.read_se_bounded(-128, 127)?;
2384 }
2385
2386 if sps.chroma_array_type() != 0 {
2387 let chroma_weight_l1_flag = r.read_bit()?;
2388 if chroma_weight_l1_flag {
2389 for j in 0..2 {
2390 pt.chroma_weight_l1[usize::from(i)][j] =
2391 r.read_se_bounded(-128, 127)?;
2392 pt.chroma_offset_l1[usize::from(i)][j] =
2393 r.read_se_bounded(-128, 127)?;
2394 }
2395 }
2396 }
2397 }
2398 }
2399
2400 Ok(())
2401 }
2402
2403 fn parse_dec_ref_pic_marking(
2404 r: &mut BitReader,
2405 nalu: &Nalu,
2406 header: &mut SliceHeader,
2407 ) -> Result<(), String> {
2408 let rpm = &mut header.dec_ref_pic_marking;
2409
2410 let num_bits_left = r.num_bits_left();
2411 if nalu.header.idr_pic_flag {
2412 rpm.no_output_of_prior_pics_flag = r.read_bit()?;
2413 rpm.long_term_reference_flag = r.read_bit()?;
2414 } else {
2415 rpm.adaptive_ref_pic_marking_mode_flag = r.read_bit()?;
2416
2417 if rpm.adaptive_ref_pic_marking_mode_flag {
2418 loop {
2419 let mut marking = RefPicMarkingInner::default();
2420
2421 let mem_mgmt_ctrl_op = r.read_ue_max::<u8>(6)?;
2422 marking.memory_management_control_operation = mem_mgmt_ctrl_op;
2423
2424 if mem_mgmt_ctrl_op == 0 {
2425 break;
2426 }
2427
2428 if mem_mgmt_ctrl_op == 1 || mem_mgmt_ctrl_op == 3 {
2429 marking.difference_of_pic_nums_minus1 = r.read_ue()?;
2430 }
2431
2432 if mem_mgmt_ctrl_op == 2 {
2433 marking.long_term_pic_num = r.read_ue()?;
2434 }
2435
2436 if mem_mgmt_ctrl_op == 3 || mem_mgmt_ctrl_op == 6 {
2437 marking.long_term_frame_idx = r.read_ue()?;
2438 }
2439
2440 if mem_mgmt_ctrl_op == 4 {
2441 marking.max_long_term_frame_idx =
2442 MaxLongTermFrameIdx::from_value_plus1(r.read_ue()?);
2443 }
2444
2445 rpm.inner.push(marking);
2446 }
2447 }
2448 }
2449 header.dec_ref_pic_marking_bit_size = num_bits_left - r.num_bits_left();
2450
2451 Ok(())
2452 }
2453
2454 pub fn parse_slice_header<'a>(&self, nalu: Nalu<'a>) -> Result<Slice<'a>, String> {
2455 if !matches!(
2456 nalu.header.type_,
2457 NaluType::Slice
2458 | NaluType::SliceDpa
2459 | NaluType::SliceDpb
2460 | NaluType::SliceDpc
2461 | NaluType::SliceIdr
2462 | NaluType::SliceExt
2463 ) {
2464 return Err(format!("Invalid NALU type: {:?} is not a slice NALU", nalu.header.type_));
2465 }
2466
2467 let data = nalu.as_ref();
2468 // Skip the header
2469 let mut r = BitReader::new(&data[nalu.header.len()..], true);
2470
2471 let mut header = SliceHeader { first_mb_in_slice: r.read_ue()?, ..Default::default() };
2472
2473 let slice_type = r.read_ue_max::<u8>(9)? % 5;
2474 header.slice_type = SliceType::try_from(slice_type)?;
2475
2476 header.pic_parameter_set_id = r.read_ue()?;
2477
2478 let pps = self.get_pps(header.pic_parameter_set_id).ok_or::<String>(format!(
2479 "Could not get PPS for pic_parameter_set_id {}",
2480 header.pic_parameter_set_id
2481 ))?;
2482
2483 let sps = &pps.sps;
2484
2485 if sps.separate_colour_plane_flag {
2486 header.colour_plane_id = r.read_bits(2)?;
2487 }
2488
2489 header.frame_num = r.read_bits(usize::from(sps.log2_max_frame_num_minus4) + 4)?;
2490
2491 if !sps.frame_mbs_only_flag {
2492 header.field_pic_flag = r.read_bit()?;
2493 if header.field_pic_flag {
2494 header.bottom_field_flag = r.read_bit()?;
2495 }
2496 }
2497
2498 if header.field_pic_flag {
2499 header.max_pic_num = 2 * sps.max_frame_num();
2500 } else {
2501 header.max_pic_num = sps.max_frame_num();
2502 }
2503
2504 if nalu.header.idr_pic_flag {
2505 header.idr_pic_id = r.read_ue_max(0xffff)?;
2506 }
2507
2508 let num_bits_left = r.num_bits_left();
2509 if sps.pic_order_cnt_type == 0 {
2510 header.pic_order_cnt_lsb =
2511 r.read_bits(usize::from(sps.log2_max_pic_order_cnt_lsb_minus4) + 4)?;
2512
2513 if pps.bottom_field_pic_order_in_frame_present_flag && !header.field_pic_flag {
2514 header.delta_pic_order_cnt_bottom = r.read_se()?;
2515 }
2516 }
2517
2518 if sps.pic_order_cnt_type == 1 && !sps.delta_pic_order_always_zero_flag {
2519 header.delta_pic_order_cnt[0] = r.read_se()?;
2520 if pps.bottom_field_pic_order_in_frame_present_flag && !header.field_pic_flag {
2521 header.delta_pic_order_cnt[1] = r.read_se()?;
2522 }
2523 }
2524 header.pic_order_cnt_bit_size = num_bits_left - r.num_bits_left();
2525
2526 if pps.redundant_pic_cnt_present_flag {
2527 header.redundant_pic_cnt = r.read_ue_max(127)?;
2528 }
2529
2530 if header.slice_type.is_b() {
2531 header.direct_spatial_mv_pred_flag = r.read_bit()?;
2532 }
2533
2534 if header.slice_type.is_p() || header.slice_type.is_sp() || header.slice_type.is_b() {
2535 header.num_ref_idx_active_override_flag = r.read_bit()?;
2536 if header.num_ref_idx_active_override_flag {
2537 header.num_ref_idx_l0_active_minus1 = r.read_ue()?;
2538 if header.slice_type.is_b() {
2539 header.num_ref_idx_l1_active_minus1 = r.read_ue()?;
2540 }
2541 } else {
2542 header.num_ref_idx_l0_active_minus1 = pps.num_ref_idx_l0_default_active_minus1;
2543 if header.slice_type.is_b() {
2544 header.num_ref_idx_l1_active_minus1 = pps.num_ref_idx_l1_default_active_minus1;
2545 }
2546 }
2547 }
2548
2549 if header.field_pic_flag {
2550 if header.num_ref_idx_l0_active_minus1 > 31 || header.num_ref_idx_l1_active_minus1 > 31
2551 {
2552 return Err("Broken Data".into());
2553 }
2554 } else if header.num_ref_idx_l0_active_minus1 > 15
2555 || header.num_ref_idx_l1_active_minus1 > 15
2556 {
2557 return Err("Broken Data".into());
2558 }
2559
2560 if let NaluType::SliceExt = nalu.header.type_ {
2561 return Err("Stream contain unsupported/unimplemented NALs".into());
2562 }
2563
2564 Parser::parse_ref_pic_list_modifications(&mut r, &mut header)?;
2565
2566 if (pps.weighted_pred_flag && (header.slice_type.is_p() || header.slice_type.is_sp()))
2567 || (pps.weighted_bipred_idc == 1 && header.slice_type.is_b())
2568 {
2569 Parser::parse_pred_weight_table(&mut r, sps, &mut header)?;
2570 }
2571
2572 if nalu.header.ref_idc != 0 {
2573 Parser::parse_dec_ref_pic_marking(&mut r, &nalu, &mut header)?;
2574 }
2575
2576 if pps.entropy_coding_mode_flag && !header.slice_type.is_i() && !header.slice_type.is_si() {
2577 header.cabac_init_idc = r.read_ue_max(2)?;
2578 }
2579
2580 header.slice_qp_delta = r.read_se_bounded(-87, 77)?;
2581
2582 if header.slice_type.is_sp() || header.slice_type.is_si() {
2583 if header.slice_type.is_sp() {
2584 header.sp_for_switch_flag = r.read_bit()?;
2585 }
2586
2587 header.slice_qs_delta = r.read_se_bounded(-51, 51)?;
2588 }
2589
2590 if pps.deblocking_filter_control_present_flag {
2591 header.disable_deblocking_filter_idc = r.read_ue_max(2)?;
2592
2593 if header.disable_deblocking_filter_idc != 1 {
2594 header.slice_alpha_c0_offset_div2 = r.read_se_bounded(-6, 6)?;
2595 header.slice_beta_offset_div2 = r.read_se_bounded(-6, 6)?;
2596 }
2597 }
2598
2599 if pps.num_slice_groups_minus1 > 0 {
2600 return Err("Stream contain unsupported/unimplemented NALs".into());
2601 }
2602
2603 let epb = r.num_epb();
2604 header.header_bit_size = (nalu.size - epb) * 8 - r.num_bits_left();
2605
2606 header.n_emulation_prevention_bytes = epb;
2607
2608 Ok(Slice { header, nalu })
2609 }
2610
2611 pub fn get_sps(&self, sps_id: u8) -> Option<&Rc<Sps>> {
2612 self.active_spses.get(&sps_id)
2613 }
2614
2615 pub fn get_pps(&self, pps_id: u8) -> Option<&Rc<Pps>> {
2616 self.active_ppses.get(&pps_id)
2617 }
2618}
2619
2620#[derive(Debug)]
2621pub struct NaluHeader {
2622 pub ref_idc: u8,
2623 pub type_: NaluType,
2624 pub idr_pic_flag: bool,
2625}
2626
2627impl Header for NaluHeader {
2628 fn parse<T: AsRef<[u8]>>(cursor: &mut Cursor<T>) -> Result<Self, String> {
2629 let mut byte_buf = [0u8; 1];
2630 cursor.read_exact(&mut byte_buf).map_err(|_| String::from("Broken Data"))?;
2631 let byte = byte_buf[0];
2632 let _ = cursor.seek(SeekFrom::Current(-1 * byte_buf.len() as i64));
2633
2634 let type_ = NaluType::try_from(byte & 0x1f)?;
2635
2636 if let NaluType::SliceExt = type_ {
2637 return Err("Stream contain unsupported/unimplemented NALs".into());
2638 }
2639
2640 let ref_idc = (byte & 0x60) >> 5;
2641 let idr_pic_flag = matches!(type_, NaluType::SliceIdr);
2642
2643 Ok(NaluHeader { ref_idc, type_, idr_pic_flag })
2644 }
2645
2646 fn is_end(&self) -> bool {
2647 matches!(self.type_, NaluType::SeqEnd | NaluType::StreamEnd)
2648 }
2649
2650 fn len(&self) -> usize {
2651 1
2652 }
2653}
2654
2655#[cfg(test)]
2656mod tests {
2657 use std::io::Cursor;
2658
2659 use crate::codec::h264::parser::Level;
2660 use crate::codec::h264::parser::MaxLongTermFrameIdx;
2661 use crate::codec::h264::parser::Nalu;
2662 use crate::codec::h264::parser::NaluType;
2663 use crate::codec::h264::parser::Parser;
2664
2665 const STREAM_TEST_25_FPS: &[u8] = include_bytes!("test_data/test-25fps.h264");
2666 const STREAM_TEST_25_FPS_NUM_NALUS: usize = 759;
2667
2668 const STREAM_TEST_25_FPS_SLICE_0: &[u8] =
2669 include_bytes!("test_data/test-25fps-h264-slice-data-0.bin");
2670 const STREAM_TEST_25_FPS_SLICE_2: &[u8] =
2671 include_bytes!("test_data/test-25fps-h264-slice-data-2.bin");
2672 const STREAM_TEST_25_FPS_SLICE_4: &[u8] =
2673 include_bytes!("test_data/test-25fps-h264-slice-data-4.bin");
2674
2675 /// This test is adapted from chromium, available at media/video/h264_parser_unittest.cc
2676 #[test]
2677 fn parse_nalus_from_stream_file() {
2678 let mut cursor = Cursor::new(STREAM_TEST_25_FPS);
2679 let mut num_nalus = 0;
2680 while Nalu::next(&mut cursor).is_ok() {
2681 num_nalus += 1;
2682 }
2683
2684 assert_eq!(num_nalus, STREAM_TEST_25_FPS_NUM_NALUS)
2685 }
2686
2687 /// The results were manually extracted from the GStreamer parser using GDB
2688 /// (gsth264parser.c) in order to compare both implementations using the
2689 /// following pipeline:
2690 /// gst-launch-1.0 filesrc location=test-25fps.h264 ! h264parse ! 'video/x-h264,stream-format=byte-stream' ! vah264dec ! fakevideosink
2691 #[test]
2692 fn parse_test25fps() {
2693 let mut cursor = Cursor::new(STREAM_TEST_25_FPS);
2694 let mut sps_ids = Vec::new();
2695 let mut pps_ids = Vec::new();
2696 let mut slices = Vec::new();
2697
2698 let mut parser = Parser::default();
2699
2700 while let Ok(nalu) = Nalu::next(&mut cursor) {
2701 match nalu.header.type_ {
2702 NaluType::Slice
2703 | NaluType::SliceDpa
2704 | NaluType::SliceDpb
2705 | NaluType::SliceDpc
2706 | NaluType::SliceIdr
2707 | NaluType::SliceExt => {
2708 let slice = parser.parse_slice_header(nalu).unwrap();
2709 slices.push(slice);
2710 }
2711 NaluType::Sps => {
2712 let sps = parser.parse_sps(&nalu).unwrap();
2713 sps_ids.push(sps.seq_parameter_set_id);
2714 }
2715 NaluType::Pps => {
2716 let pps = parser.parse_pps(&nalu).unwrap();
2717 pps_ids.push(pps.pic_parameter_set_id);
2718 }
2719 _ => {
2720 continue;
2721 }
2722 }
2723 }
2724
2725 for sps_id in &sps_ids {
2726 // four identical SPSes in this stream
2727 let sps = parser.get_sps(*sps_id).unwrap();
2728
2729 assert_eq!(sps.seq_parameter_set_id, 0);
2730 assert_eq!(sps.profile_idc, 77);
2731 assert!(!sps.constraint_set0_flag);
2732 assert!(sps.constraint_set1_flag);
2733 assert!(!sps.constraint_set2_flag);
2734 assert!(!sps.constraint_set3_flag);
2735 assert!(!sps.constraint_set4_flag);
2736 assert!(!sps.constraint_set5_flag);
2737 assert_eq!(sps.level_idc, Level::L1_3);
2738 assert_eq!(sps.chroma_format_idc, 1);
2739 assert!(!sps.separate_colour_plane_flag);
2740 assert_eq!(sps.bit_depth_luma_minus8, 0);
2741 assert_eq!(sps.bit_depth_chroma_minus8, 0);
2742 assert!(!sps.qpprime_y_zero_transform_bypass_flag);
2743 assert!(!sps.seq_scaling_matrix_present_flag);
2744
2745 for outer in &sps.scaling_lists_4x4 {
2746 for inner in outer {
2747 assert_eq!(*inner, 16);
2748 }
2749 }
2750
2751 for outer in &sps.scaling_lists_8x8 {
2752 for inner in outer {
2753 assert_eq!(*inner, 16);
2754 }
2755 }
2756
2757 assert_eq!(sps.log2_max_frame_num_minus4, 1);
2758 assert_eq!(sps.pic_order_cnt_type, 0);
2759 assert_eq!(sps.log2_max_pic_order_cnt_lsb_minus4, 3);
2760 assert!(!sps.delta_pic_order_always_zero_flag);
2761 assert_eq!(sps.offset_for_non_ref_pic, 0);
2762 assert_eq!(sps.offset_for_top_to_bottom_field, 0);
2763 assert_eq!(sps.num_ref_frames_in_pic_order_cnt_cycle, 0);
2764
2765 for offset in sps.offset_for_ref_frame {
2766 assert_eq!(offset, 0);
2767 }
2768
2769 assert_eq!(sps.max_num_ref_frames, 2);
2770 assert!(!sps.gaps_in_frame_num_value_allowed_flag);
2771 assert_eq!(sps.pic_width_in_mbs_minus1, 19);
2772 assert_eq!(sps.pic_height_in_map_units_minus1, 14);
2773 assert!(sps.frame_mbs_only_flag);
2774 assert!(!sps.mb_adaptive_frame_field_flag);
2775 assert!(!sps.direct_8x8_inference_flag);
2776 assert!(!sps.frame_cropping_flag);
2777 assert_eq!(sps.frame_crop_left_offset, 0);
2778 assert_eq!(sps.frame_crop_right_offset, 0);
2779 assert_eq!(sps.frame_crop_top_offset, 0);
2780 assert_eq!(sps.frame_crop_bottom_offset, 0);
2781 assert_eq!(sps.chroma_array_type(), 1);
2782 assert_eq!(sps.max_frame_num(), 32);
2783 assert_eq!(sps.width(), 320);
2784 assert_eq!(sps.height(), 240);
2785 }
2786
2787 for pps_id in &pps_ids {
2788 // four identical SPSes in this stream
2789 let pps = parser.get_pps(*pps_id).unwrap();
2790 assert_eq!(pps.pic_parameter_set_id, 0);
2791 assert_eq!(pps.seq_parameter_set_id, 0);
2792 assert!(pps.bottom_field_pic_order_in_frame_present_flag);
2793 assert_eq!(pps.num_slice_groups_minus1, 0);
2794 assert_eq!(pps.num_ref_idx_l0_default_active_minus1, 0);
2795 assert_eq!(pps.num_ref_idx_l1_default_active_minus1, 0);
2796 assert!(!pps.weighted_pred_flag);
2797 assert_eq!(pps.weighted_bipred_idc, 0);
2798 assert_eq!(pps.pic_init_qp_minus26, 2);
2799 assert_eq!(pps.pic_init_qs_minus26, 0);
2800 assert_eq!(pps.chroma_qp_index_offset, 0);
2801 assert!(!pps.deblocking_filter_control_present_flag);
2802 assert!(!pps.constrained_intra_pred_flag);
2803 assert!(!pps.redundant_pic_cnt_present_flag);
2804 assert!(!pps.transform_8x8_mode_flag);
2805
2806 for outer in &pps.scaling_lists_4x4 {
2807 for inner in outer {
2808 assert_eq!(*inner, 16);
2809 }
2810 }
2811
2812 for outer in &pps.scaling_lists_8x8 {
2813 for inner in outer {
2814 assert_eq!(*inner, 16);
2815 }
2816 }
2817
2818 assert_eq!(pps.second_chroma_qp_index_offset, 0);
2819 assert!(!pps.pic_scaling_matrix_present_flag);
2820 }
2821
2822 // test an I slice
2823 let hdr = &slices[0].header;
2824 let nalu = &slices[0].nalu;
2825 assert_eq!(nalu.as_ref(), STREAM_TEST_25_FPS_SLICE_0);
2826
2827 assert_eq!(hdr.first_mb_in_slice, 0);
2828 assert!(hdr.slice_type.is_i());
2829 assert_eq!(hdr.colour_plane_id, 0);
2830 assert_eq!(hdr.frame_num, 0);
2831 assert!(!hdr.field_pic_flag);
2832 assert!(!hdr.bottom_field_flag);
2833 assert_eq!(hdr.idr_pic_id, 0);
2834 assert_eq!(hdr.pic_order_cnt_lsb, 0);
2835 assert_eq!(hdr.delta_pic_order_cnt_bottom, 0);
2836 assert_eq!(hdr.delta_pic_order_cnt[0], 0);
2837 assert_eq!(hdr.delta_pic_order_cnt[1], 0);
2838 assert_eq!(hdr.redundant_pic_cnt, 0);
2839 assert!(!hdr.direct_spatial_mv_pred_flag);
2840 assert_eq!(hdr.num_ref_idx_l0_active_minus1, 0);
2841 assert_eq!(hdr.num_ref_idx_l1_active_minus1, 0);
2842 assert!(!hdr.ref_pic_list_modification_flag_l0);
2843
2844 assert_eq!(hdr.ref_pic_list_modification_l0.len(), 0);
2845
2846 for rplm in &hdr.ref_pic_list_modification_l0 {
2847 assert_eq!(rplm.modification_of_pic_nums_idc, 0);
2848 assert_eq!(rplm.abs_diff_pic_num_minus1, 0);
2849 assert_eq!(rplm.long_term_pic_num, 0);
2850 assert_eq!(rplm.abs_diff_view_idx_minus1, 0);
2851 }
2852
2853 assert!(!hdr.ref_pic_list_modification_flag_l1);
2854 assert_eq!(hdr.ref_pic_list_modification_l1.len(), 0);
2855
2856 for rplm in &hdr.ref_pic_list_modification_l1 {
2857 assert_eq!(rplm.modification_of_pic_nums_idc, 0);
2858 assert_eq!(rplm.abs_diff_pic_num_minus1, 0);
2859 assert_eq!(rplm.long_term_pic_num, 0);
2860 assert_eq!(rplm.abs_diff_view_idx_minus1, 0);
2861 }
2862
2863 // Safe because this type does not have any references
2864 assert_eq!(hdr.pred_weight_table, unsafe { std::mem::zeroed() });
2865
2866 assert_eq!(hdr.dec_ref_pic_marking, Default::default());
2867
2868 assert_eq!(hdr.cabac_init_idc, 0);
2869 assert_eq!(hdr.slice_qp_delta, 12);
2870 assert_eq!(hdr.slice_qs_delta, 0);
2871 assert_eq!(hdr.disable_deblocking_filter_idc, 0);
2872 assert_eq!(hdr.slice_alpha_c0_offset_div2, 0);
2873 assert_eq!(hdr.slice_beta_offset_div2, 0);
2874 assert_eq!(hdr.max_pic_num, 32);
2875 assert_eq!(hdr.header_bit_size, 38);
2876 assert!(!hdr.num_ref_idx_active_override_flag);
2877
2878 // test a P slice
2879 let hdr = &slices[2].header;
2880 let nalu = &slices[2].nalu;
2881 assert_eq!(nalu.as_ref(), STREAM_TEST_25_FPS_SLICE_2);
2882
2883 assert_eq!(hdr.first_mb_in_slice, 0);
2884 assert!(hdr.slice_type.is_p());
2885 assert_eq!(hdr.colour_plane_id, 0);
2886 assert_eq!(hdr.frame_num, 1);
2887 assert!(!hdr.field_pic_flag);
2888 assert!(!hdr.bottom_field_flag);
2889 assert_eq!(hdr.idr_pic_id, 0);
2890 assert_eq!(hdr.pic_order_cnt_lsb, 4);
2891 assert_eq!(hdr.delta_pic_order_cnt_bottom, 0);
2892 assert_eq!(hdr.delta_pic_order_cnt[0], 0);
2893 assert_eq!(hdr.delta_pic_order_cnt[1], 0);
2894 assert_eq!(hdr.redundant_pic_cnt, 0);
2895 assert!(!hdr.direct_spatial_mv_pred_flag);
2896 assert_eq!(hdr.num_ref_idx_l0_active_minus1, 0);
2897 assert_eq!(hdr.num_ref_idx_l1_active_minus1, 0);
2898 assert!(!hdr.ref_pic_list_modification_flag_l0);
2899
2900 assert_eq!(hdr.ref_pic_list_modification_l0.len(), 0);
2901
2902 for rplm in &hdr.ref_pic_list_modification_l0 {
2903 assert_eq!(rplm.modification_of_pic_nums_idc, 0);
2904 assert_eq!(rplm.abs_diff_pic_num_minus1, 0);
2905 assert_eq!(rplm.long_term_pic_num, 0);
2906 assert_eq!(rplm.abs_diff_view_idx_minus1, 0);
2907 }
2908
2909 assert!(!hdr.ref_pic_list_modification_flag_l1);
2910 assert_eq!(hdr.ref_pic_list_modification_l1.len(), 0);
2911
2912 for rplm in &hdr.ref_pic_list_modification_l1 {
2913 assert_eq!(rplm.modification_of_pic_nums_idc, 0);
2914 assert_eq!(rplm.abs_diff_pic_num_minus1, 0);
2915 assert_eq!(rplm.long_term_pic_num, 0);
2916 assert_eq!(rplm.abs_diff_view_idx_minus1, 0);
2917 }
2918
2919 // Safe because this type does not have any references
2920 assert_eq!(hdr.pred_weight_table, unsafe { std::mem::zeroed() });
2921
2922 assert_eq!(hdr.dec_ref_pic_marking, Default::default());
2923
2924 assert_eq!(hdr.cabac_init_idc, 0);
2925 assert_eq!(hdr.slice_qp_delta, 0);
2926 assert_eq!(hdr.slice_qs_delta, 0);
2927 assert_eq!(hdr.disable_deblocking_filter_idc, 0);
2928 assert_eq!(hdr.slice_alpha_c0_offset_div2, 0);
2929 assert_eq!(hdr.slice_beta_offset_div2, 0);
2930 assert_eq!(hdr.max_pic_num, 32);
2931 assert_eq!(hdr.header_bit_size, 28);
2932 assert!(!hdr.num_ref_idx_active_override_flag);
2933
2934 // test a B slice
2935 let hdr = &slices[4].header;
2936 let nalu = &slices[4].nalu;
2937 assert_eq!(nalu.as_ref(), STREAM_TEST_25_FPS_SLICE_4);
2938
2939 assert_eq!(hdr.first_mb_in_slice, 0);
2940 assert!(hdr.slice_type.is_b());
2941 assert_eq!(hdr.colour_plane_id, 0);
2942 assert_eq!(hdr.frame_num, 2);
2943 assert!(!hdr.field_pic_flag);
2944 assert!(!hdr.bottom_field_flag);
2945 assert_eq!(hdr.idr_pic_id, 0);
2946 assert_eq!(hdr.pic_order_cnt_lsb, 2);
2947 assert_eq!(hdr.delta_pic_order_cnt_bottom, 0);
2948 assert_eq!(hdr.delta_pic_order_cnt[0], 0);
2949 assert_eq!(hdr.delta_pic_order_cnt[1], 0);
2950 assert_eq!(hdr.redundant_pic_cnt, 0);
2951 assert!(hdr.direct_spatial_mv_pred_flag);
2952 assert_eq!(hdr.num_ref_idx_l0_active_minus1, 0);
2953 assert_eq!(hdr.num_ref_idx_l1_active_minus1, 0);
2954 assert!(!hdr.ref_pic_list_modification_flag_l0);
2955
2956 assert_eq!(hdr.ref_pic_list_modification_l0.len(), 0);
2957
2958 for rplm in &hdr.ref_pic_list_modification_l0 {
2959 assert_eq!(rplm.modification_of_pic_nums_idc, 0);
2960 assert_eq!(rplm.abs_diff_pic_num_minus1, 0);
2961 assert_eq!(rplm.long_term_pic_num, 0);
2962 assert_eq!(rplm.abs_diff_view_idx_minus1, 0);
2963 }
2964
2965 assert!(!hdr.ref_pic_list_modification_flag_l1);
2966 assert_eq!(hdr.ref_pic_list_modification_l1.len(), 0);
2967
2968 for rplm in &hdr.ref_pic_list_modification_l1 {
2969 assert_eq!(rplm.modification_of_pic_nums_idc, 0);
2970 assert_eq!(rplm.abs_diff_pic_num_minus1, 0);
2971 assert_eq!(rplm.long_term_pic_num, 0);
2972 assert_eq!(rplm.abs_diff_view_idx_minus1, 0);
2973 }
2974
2975 // Safe because this type does not have any references
2976 assert_eq!(hdr.pred_weight_table, unsafe { std::mem::zeroed() });
2977
2978 assert_eq!(hdr.dec_ref_pic_marking, Default::default());
2979
2980 assert_eq!(hdr.cabac_init_idc, 0);
2981 assert_eq!(hdr.slice_qp_delta, 16);
2982 assert_eq!(hdr.slice_qs_delta, 0);
2983 assert_eq!(hdr.disable_deblocking_filter_idc, 0);
2984 assert_eq!(hdr.slice_alpha_c0_offset_div2, 0);
2985 assert_eq!(hdr.slice_beta_offset_div2, 0);
2986 assert_eq!(hdr.max_pic_num, 32);
2987 assert_eq!(hdr.header_bit_size, 41);
2988 assert!(!hdr.num_ref_idx_active_override_flag);
2989 }
2990
2991 #[test]
2992 fn invalid_sps_crop_width() {
2993 // This SPS contains invalid frame_crop_*_offset settings. This led to
2994 // unconditional panic in the parser in the past. This test make sure a
2995 // panic is avoided.
2996 let invalid_sps =
2997 vec![0x00, 0x00, 0x01, 0x07, 0x00, 0x00, 0x0a, 0xfb, 0xb0, 0x32, 0xc0, 0xca, 0x80];
2998
2999 let mut cursor = Cursor::new(invalid_sps.as_ref());
3000 let mut parser = Parser::default();
3001
3002 while let Ok(nalu) = Nalu::next(&mut cursor) {
3003 assert_eq!(nalu.header.type_, NaluType::Sps);
3004 parser.parse_sps(&nalu).unwrap_err();
3005 }
3006 }
3007
3008 #[test]
3009 fn max_long_term_frame_idx() {
3010 assert_eq!(
3011 MaxLongTermFrameIdx::from_value_plus1(0),
3012 MaxLongTermFrameIdx::NoLongTermFrameIndices
3013 );
3014 assert_eq!(MaxLongTermFrameIdx::NoLongTermFrameIndices.to_value_plus1(), 0);
3015
3016 assert_eq!(MaxLongTermFrameIdx::from_value_plus1(1), MaxLongTermFrameIdx::Idx(0));
3017 assert_eq!(MaxLongTermFrameIdx::Idx(0).to_value_plus1(), 1);
3018
3019 assert_eq!(MaxLongTermFrameIdx::from_value_plus1(25), MaxLongTermFrameIdx::Idx(24));
3020 assert_eq!(MaxLongTermFrameIdx::Idx(24).to_value_plus1(), 25);
3021
3022 // Check PartialOrd<u32> implementation.
3023 assert!(MaxLongTermFrameIdx::NoLongTermFrameIndices < 0);
3024 assert_ne!(MaxLongTermFrameIdx::NoLongTermFrameIndices, 0);
3025 assert_eq!(MaxLongTermFrameIdx::Idx(0), 0);
3026 assert!(MaxLongTermFrameIdx::Idx(0) < 1);
3027 assert_eq!(MaxLongTermFrameIdx::Idx(24), 24);
3028 assert!(MaxLongTermFrameIdx::Idx(24) < 25);
3029 }
3030}