-
Notifications
You must be signed in to change notification settings - Fork 25
/
sps.rs
1643 lines (1588 loc) · 57.8 KB
/
sps.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::rbsp::{BitRead, BitReaderError};
use std::fmt::{self, Debug};
#[derive(Debug, PartialEq)]
pub enum SeqParamSetIdError {
IdTooLarge(u32),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SeqParamSetId(u8);
impl SeqParamSetId {
pub fn from_u32(id: u32) -> Result<SeqParamSetId, SeqParamSetIdError> {
if id > 31 {
Err(SeqParamSetIdError::IdTooLarge(id))
} else {
Ok(SeqParamSetId(id as u8))
}
}
pub fn id(self) -> u8 {
self.0
}
}
#[derive(Debug)]
pub enum SpsError {
/// Signals that bit_depth_luma_minus8 was greater than the max value, 6
BitDepthOutOfRange(u32),
RbspReaderError(BitReaderError),
PicOrderCnt(PicOrderCntError),
ScalingMatrix(ScalingMatrixError),
/// log2_max_frame_num_minus4 must be between 0 and 12
Log2MaxFrameNumMinus4OutOfRange(u32),
BadSeqParamSetId(SeqParamSetIdError),
UnknownSeqParamSetId(SeqParamSetId),
/// A field in the bitstream had a value too large for a subsequent calculation
FieldValueTooLarge {
name: &'static str,
value: u32,
},
/// The frame-cropping values are too large vs. the coded picture size,
CroppingError(FrameCropping),
/// The `cpb_cnt_minus1` field must be between 0 and 31 inclusive.
CpbCountOutOfRange(u32),
}
impl From<BitReaderError> for SpsError {
fn from(e: BitReaderError) -> Self {
SpsError::RbspReaderError(e)
}
}
#[derive(Debug)]
pub enum Profile {
Unknown(u8),
Baseline,
Main,
High,
High422,
High10,
High444,
Extended,
ScalableBase,
ScalableHigh,
MultiviewHigh,
StereoHigh,
MFCDepthHigh,
MultiviewDepthHigh,
EnhancedMultiviewDepthHigh,
}
impl Profile {
pub fn from_profile_idc(profile_idc: ProfileIdc) -> Profile {
// TODO: accept constraint_flags too, as Level does?
match profile_idc.0 {
66 => Profile::Baseline,
77 => Profile::Main,
100 => Profile::High,
122 => Profile::High422,
110 => Profile::High10,
244 => Profile::High444,
88 => Profile::Extended,
83 => Profile::ScalableBase,
86 => Profile::ScalableHigh,
118 => Profile::MultiviewHigh,
128 => Profile::StereoHigh,
135 => Profile::MFCDepthHigh,
138 => Profile::MultiviewDepthHigh,
139 => Profile::EnhancedMultiviewDepthHigh,
other => Profile::Unknown(other),
}
}
pub fn profile_idc(&self) -> u8 {
match *self {
Profile::Baseline => 66,
Profile::Main => 77,
Profile::High => 100,
Profile::High422 => 122,
Profile::High10 => 110,
Profile::High444 => 144,
Profile::Extended => 88,
Profile::ScalableBase => 83,
Profile::ScalableHigh => 86,
Profile::MultiviewHigh => 118,
Profile::StereoHigh => 128,
Profile::MFCDepthHigh => 135,
Profile::MultiviewDepthHigh => 138,
Profile::EnhancedMultiviewDepthHigh => 139,
Profile::Unknown(profile_idc) => profile_idc,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct ConstraintFlags(u8);
impl From<u8> for ConstraintFlags {
fn from(v: u8) -> Self {
ConstraintFlags(v)
}
}
impl From<ConstraintFlags> for u8 {
fn from(v: ConstraintFlags) -> Self {
v.0
}
}
impl ConstraintFlags {
pub fn flag0(self) -> bool {
self.0 & 0b1000_0000 != 0
}
pub fn flag1(self) -> bool {
self.0 & 0b0100_0000 != 0
}
pub fn flag2(self) -> bool {
self.0 & 0b0010_0000 != 0
}
pub fn flag3(self) -> bool {
self.0 & 0b0001_0000 != 0
}
pub fn flag4(self) -> bool {
self.0 & 0b0000_1000 != 0
}
pub fn flag5(self) -> bool {
self.0 & 0b0000_0100 != 0
}
pub fn reserved_zero_two_bits(self) -> u8 {
self.0 & 0b0000_0011
}
}
impl Debug for ConstraintFlags {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.debug_struct("ConstraintFlags")
.field("flag0", &self.flag0())
.field("flag1", &self.flag1())
.field("flag2", &self.flag2())
.field("flag3", &self.flag3())
.field("flag4", &self.flag4())
.field("flag5", &self.flag5())
.field("reserved_zero_two_bits", &self.reserved_zero_two_bits())
.finish()
}
}
#[derive(Debug, PartialEq)]
#[allow(non_camel_case_types)]
pub enum Level {
Unknown(u8),
L1,
L1_b,
L1_1,
L1_2,
L1_3,
L2,
L2_1,
L2_2,
L3,
L3_1,
L3_2,
L4,
L4_1,
L4_2,
L5,
L5_1,
L5_2,
}
impl Level {
pub fn from_constraint_flags_and_level_idc(
constraint_flags: ConstraintFlags,
level_idc: u8,
) -> Level {
match level_idc {
10 => Level::L1,
11 => {
if constraint_flags.flag3() {
Level::L1_b
} else {
Level::L1_1
}
}
12 => Level::L1_2,
13 => Level::L1_3,
20 => Level::L2,
21 => Level::L2_1,
22 => Level::L2_2,
30 => Level::L3,
31 => Level::L3_1,
32 => Level::L3_2,
40 => Level::L4,
41 => Level::L4_1,
42 => Level::L4_2,
50 => Level::L5,
51 => Level::L5_1,
52 => Level::L5_2,
_ => Level::Unknown(level_idc),
}
}
pub fn level_idc(&self) -> u8 {
match *self {
Level::L1 => 10,
Level::L1_1 | Level::L1_b => 11,
Level::L1_2 => 12,
Level::L1_3 => 13,
Level::L2 => 20,
Level::L2_1 => 21,
Level::L2_2 => 22,
Level::L3 => 30,
Level::L3_1 => 31,
Level::L3_2 => 32,
Level::L4 => 40,
Level::L4_1 => 41,
Level::L4_2 => 42,
Level::L5 => 50,
Level::L5_1 => 51,
Level::L5_2 => 52,
Level::Unknown(level_idc) => level_idc,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ChromaFormat {
Monochrome,
#[default]
YUV420,
YUV422,
YUV444,
Invalid(u32),
}
impl ChromaFormat {
fn from_chroma_format_idc(chroma_format_idc: u32) -> ChromaFormat {
match chroma_format_idc {
0 => ChromaFormat::Monochrome,
1 => ChromaFormat::YUV420,
2 => ChromaFormat::YUV422,
3 => ChromaFormat::YUV444,
_ => ChromaFormat::Invalid(chroma_format_idc),
}
}
}
// _Profile Indication_ value
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct ProfileIdc(u8);
impl ProfileIdc {
pub fn has_chroma_info(self) -> bool {
match self.0 {
100 | 110 | 122 | 244 | 44 | 83 | 86 => true,
_ => false,
}
}
}
impl From<u8> for ProfileIdc {
fn from(v: u8) -> Self {
ProfileIdc(v)
}
}
impl From<ProfileIdc> for u8 {
fn from(v: ProfileIdc) -> Self {
v.0
}
}
pub struct ScalingList {
// TODO
}
impl ScalingList {
pub fn read<R: BitRead>(r: &mut R, size: u8) -> Result<ScalingList, ScalingMatrixError> {
let mut scaling_list = vec![];
let mut last_scale = 8;
let mut next_scale = 8;
let mut _use_default_scaling_matrix_flag = false;
for j in 0..size {
if next_scale != 0 {
let delta_scale = r.read_se("delta_scale")?;
if delta_scale < -128 || delta_scale > 127 {
return Err(ScalingMatrixError::DeltaScaleOutOfRange(delta_scale));
}
next_scale = (last_scale + delta_scale + 256) % 256;
_use_default_scaling_matrix_flag = j == 0 && next_scale == 0;
}
let new_value = if next_scale == 0 {
last_scale
} else {
next_scale
};
scaling_list.push(new_value);
last_scale = new_value;
}
Ok(ScalingList {})
}
}
#[derive(Debug)]
pub enum ScalingMatrixError {
ReaderError(BitReaderError),
/// The `delta_scale` field must be between -128 and 127 inclusive.
DeltaScaleOutOfRange(i32),
}
impl From<BitReaderError> for ScalingMatrixError {
fn from(e: BitReaderError) -> Self {
ScalingMatrixError::ReaderError(e)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SeqScalingMatrix {
// TODO
}
impl SeqScalingMatrix {
fn read<R: BitRead>(
r: &mut R,
chroma_format_idc: u32,
) -> Result<SeqScalingMatrix, ScalingMatrixError> {
let mut scaling_list4x4 = vec![];
let mut scaling_list8x8 = vec![];
let count = if chroma_format_idc == 3 { 12 } else { 8 };
for i in 0..count {
let seq_scaling_list_present_flag = r.read_bool("seq_scaling_list_present_flag")?;
if seq_scaling_list_present_flag {
if i < 6 {
scaling_list4x4.push(ScalingList::read(r, 16)?);
} else {
scaling_list8x8.push(ScalingList::read(r, 64)?);
}
}
}
Ok(SeqScalingMatrix {})
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ChromaInfo {
pub chroma_format: ChromaFormat,
pub separate_colour_plane_flag: bool,
pub bit_depth_luma_minus8: u8,
pub bit_depth_chroma_minus8: u8,
pub qpprime_y_zero_transform_bypass_flag: bool,
pub scaling_matrix: SeqScalingMatrix,
}
impl ChromaInfo {
pub fn read<R: BitRead>(r: &mut R, profile_idc: ProfileIdc) -> Result<ChromaInfo, SpsError> {
if profile_idc.has_chroma_info() {
let chroma_format_idc = r.read_ue("chroma_format_idc")?;
Ok(ChromaInfo {
chroma_format: ChromaFormat::from_chroma_format_idc(chroma_format_idc),
separate_colour_plane_flag: if chroma_format_idc == 3 {
r.read_bool("separate_colour_plane_flag")?
} else {
false
},
bit_depth_luma_minus8: Self::read_bit_depth_minus8(r)?,
bit_depth_chroma_minus8: Self::read_bit_depth_minus8(r)?,
qpprime_y_zero_transform_bypass_flag: r
.read_bool("qpprime_y_zero_transform_bypass_flag")?,
scaling_matrix: Self::read_scaling_matrix(r, chroma_format_idc)?,
})
} else {
Ok(ChromaInfo::default())
}
}
fn read_bit_depth_minus8<R: BitRead>(r: &mut R) -> Result<u8, SpsError> {
let value = r.read_ue("read_bit_depth_minus8")?;
if value > 6 {
Err(SpsError::BitDepthOutOfRange(value))
} else {
Ok(value as u8)
}
}
fn read_scaling_matrix<R: BitRead>(
r: &mut R,
chroma_format_idc: u32,
) -> Result<SeqScalingMatrix, SpsError> {
let scaling_matrix_present_flag = r.read_bool("scaling_matrix_present_flag")?;
if scaling_matrix_present_flag {
SeqScalingMatrix::read(r, chroma_format_idc).map_err(SpsError::ScalingMatrix)
} else {
Ok(SeqScalingMatrix::default())
}
}
}
#[derive(Debug)]
pub enum PicOrderCntError {
InvalidPicOrderCountType(u32),
ReaderError(BitReaderError),
/// log2_max_pic_order_cnt_lsb_minus4 must be between 0 and 12
Log2MaxPicOrderCntLsbMinus4OutOfRange(u32),
/// num_ref_frames_in_pic_order_cnt_cycle must be between 0 and 255
NumRefFramesInPicOrderCntCycleOutOfRange(u32),
}
impl From<BitReaderError> for PicOrderCntError {
fn from(e: BitReaderError) -> Self {
PicOrderCntError::ReaderError(e)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PicOrderCntType {
TypeZero {
log2_max_pic_order_cnt_lsb_minus4: u8,
},
TypeOne {
delta_pic_order_always_zero_flag: bool,
offset_for_non_ref_pic: i32,
offset_for_top_to_bottom_field: i32,
offsets_for_ref_frame: Vec<i32>,
},
TypeTwo,
}
impl PicOrderCntType {
fn read<R: BitRead>(r: &mut R) -> Result<PicOrderCntType, PicOrderCntError> {
let pic_order_cnt_type = r.read_ue("pic_order_cnt_type")?;
match pic_order_cnt_type {
0 => Ok(PicOrderCntType::TypeZero {
log2_max_pic_order_cnt_lsb_minus4: Self::read_log2_max_pic_order_cnt_lsb_minus4(r)?,
}),
1 => Ok(PicOrderCntType::TypeOne {
delta_pic_order_always_zero_flag: r
.read_bool("delta_pic_order_always_zero_flag")?,
offset_for_non_ref_pic: r.read_se("offset_for_non_ref_pic")?,
offset_for_top_to_bottom_field: r.read_se("offset_for_top_to_bottom_field")?,
offsets_for_ref_frame: Self::read_offsets_for_ref_frame(r)?,
}),
2 => Ok(PicOrderCntType::TypeTwo),
_ => Err(PicOrderCntError::InvalidPicOrderCountType(
pic_order_cnt_type,
)),
}
}
fn read_log2_max_pic_order_cnt_lsb_minus4<R: BitRead>(
r: &mut R,
) -> Result<u8, PicOrderCntError> {
let val = r.read_ue("log2_max_pic_order_cnt_lsb_minus4")?;
if val > 12 {
Err(PicOrderCntError::Log2MaxPicOrderCntLsbMinus4OutOfRange(val))
} else {
Ok(val as u8)
}
}
fn read_offsets_for_ref_frame<R: BitRead>(r: &mut R) -> Result<Vec<i32>, PicOrderCntError> {
let num_ref_frames_in_pic_order_cnt_cycle =
r.read_ue("num_ref_frames_in_pic_order_cnt_cycle")?;
if num_ref_frames_in_pic_order_cnt_cycle > 255 {
return Err(PicOrderCntError::NumRefFramesInPicOrderCntCycleOutOfRange(
num_ref_frames_in_pic_order_cnt_cycle,
));
}
let mut offsets = Vec::with_capacity(num_ref_frames_in_pic_order_cnt_cycle as usize);
for _ in 0..num_ref_frames_in_pic_order_cnt_cycle {
offsets.push(r.read_se("offset_for_ref_frame")?);
}
Ok(offsets)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FrameMbsFlags {
Frames,
Fields { mb_adaptive_frame_field_flag: bool },
}
impl FrameMbsFlags {
fn read<R: BitRead>(r: &mut R) -> Result<FrameMbsFlags, BitReaderError> {
let frame_mbs_only_flag = r.read_bool("frame_mbs_only_flag")?;
if frame_mbs_only_flag {
Ok(FrameMbsFlags::Frames)
} else {
Ok(FrameMbsFlags::Fields {
mb_adaptive_frame_field_flag: r.read_bool("mb_adaptive_frame_field_flag")?,
})
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FrameCropping {
pub left_offset: u32,
pub right_offset: u32,
pub top_offset: u32,
pub bottom_offset: u32,
}
impl FrameCropping {
fn read<R: BitRead>(r: &mut R) -> Result<Option<FrameCropping>, BitReaderError> {
let frame_cropping_flag = r.read_bool("frame_cropping_flag")?;
Ok(if frame_cropping_flag {
Some(FrameCropping {
left_offset: r.read_ue("left_offset")?,
right_offset: r.read_ue("right_offset")?,
top_offset: r.read_ue("top_offset")?,
bottom_offset: r.read_ue("bottom_offset")?,
})
} else {
None
})
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum AspectRatioInfo {
#[default]
Unspecified,
Ratio1_1,
Ratio12_11,
Ratio10_11,
Ratio16_11,
Ratio40_33,
Ratio24_11,
Ratio20_11,
Ratio32_11,
Ratio80_33,
Ratio18_11,
Ratio15_11,
Ratio64_33,
Ratio160_99,
Ratio4_3,
Ratio3_2,
Ratio2_1,
Reserved(u8),
Extended(u16, u16),
}
impl AspectRatioInfo {
fn read<R: BitRead>(r: &mut R) -> Result<Option<AspectRatioInfo>, BitReaderError> {
let aspect_ratio_info_present_flag = r.read_bool("aspect_ratio_info_present_flag")?;
Ok(if aspect_ratio_info_present_flag {
let aspect_ratio_idc = r.read_u8(8, "aspect_ratio_idc")?;
Some(match aspect_ratio_idc {
0 => AspectRatioInfo::Unspecified,
1 => AspectRatioInfo::Ratio1_1,
2 => AspectRatioInfo::Ratio12_11,
3 => AspectRatioInfo::Ratio10_11,
4 => AspectRatioInfo::Ratio16_11,
5 => AspectRatioInfo::Ratio40_33,
6 => AspectRatioInfo::Ratio24_11,
7 => AspectRatioInfo::Ratio20_11,
8 => AspectRatioInfo::Ratio32_11,
9 => AspectRatioInfo::Ratio80_33,
10 => AspectRatioInfo::Ratio18_11,
11 => AspectRatioInfo::Ratio15_11,
12 => AspectRatioInfo::Ratio64_33,
13 => AspectRatioInfo::Ratio160_99,
14 => AspectRatioInfo::Ratio4_3,
15 => AspectRatioInfo::Ratio3_2,
16 => AspectRatioInfo::Ratio2_1,
255 => AspectRatioInfo::Extended(
r.read_u16(16, "sar_width")?,
r.read_u16(16, "sar_height")?,
),
_ => AspectRatioInfo::Reserved(aspect_ratio_idc),
})
} else {
None
})
}
/// Returns the aspect ratio as `(width, height)`, if specified.
pub fn get(&self) -> Option<(u16, u16)> {
match self {
AspectRatioInfo::Unspecified => None,
AspectRatioInfo::Ratio1_1 => Some((1, 1)),
AspectRatioInfo::Ratio12_11 => Some((12, 11)),
AspectRatioInfo::Ratio10_11 => Some((10, 11)),
AspectRatioInfo::Ratio16_11 => Some((16, 11)),
AspectRatioInfo::Ratio40_33 => Some((40, 33)),
AspectRatioInfo::Ratio24_11 => Some((24, 11)),
AspectRatioInfo::Ratio20_11 => Some((20, 11)),
AspectRatioInfo::Ratio32_11 => Some((32, 11)),
AspectRatioInfo::Ratio80_33 => Some((80, 33)),
AspectRatioInfo::Ratio18_11 => Some((18, 11)),
AspectRatioInfo::Ratio15_11 => Some((15, 11)),
AspectRatioInfo::Ratio64_33 => Some((64, 33)),
AspectRatioInfo::Ratio160_99 => Some((160, 99)),
AspectRatioInfo::Ratio4_3 => Some((4, 3)),
AspectRatioInfo::Ratio3_2 => Some((3, 2)),
AspectRatioInfo::Ratio2_1 => Some((2, 1)),
AspectRatioInfo::Reserved(_) => None,
&AspectRatioInfo::Extended(width, height) => {
// ISO/IEC 14496-10 section E.2.1: "When ... sar_width is equal to 0 or sar_height
// is equal to 0, the sample aspect ratio shall be considered unspecified by this
// Recommendation | International Standard."
if width == 0 || height == 0 {
None
} else {
Some((width, height))
}
}
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum OverscanAppropriate {
#[default]
Unspecified,
Appropriate,
Inappropriate,
}
impl OverscanAppropriate {
fn read<R: BitRead>(r: &mut R) -> Result<OverscanAppropriate, BitReaderError> {
let overscan_info_present_flag = r.read_bool("overscan_info_present_flag")?;
Ok(if overscan_info_present_flag {
let overscan_appropriate_flag = r.read_bool("overscan_appropriate_flag")?;
if overscan_appropriate_flag {
OverscanAppropriate::Appropriate
} else {
OverscanAppropriate::Inappropriate
}
} else {
OverscanAppropriate::Unspecified
})
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum VideoFormat {
#[default]
Component,
PAL,
NTSC,
SECAM,
MAC,
Unspecified,
Reserved(u8),
}
impl VideoFormat {
fn from(video_format: u8) -> VideoFormat {
match video_format {
0 => VideoFormat::Component,
1 => VideoFormat::PAL,
2 => VideoFormat::NTSC,
3 => VideoFormat::SECAM,
4 => VideoFormat::MAC,
5 => VideoFormat::Unspecified,
6 | 7 => VideoFormat::Reserved(video_format),
_ => panic!("unsupported video_format value {}", video_format),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ColourDescription {
pub colour_primaries: u8,
pub transfer_characteristics: u8,
pub matrix_coefficients: u8,
}
impl ColourDescription {
fn read<R: BitRead>(r: &mut R) -> Result<Option<ColourDescription>, BitReaderError> {
let colour_description_present_flag = r.read_bool("colour_description_present_flag")?;
Ok(if colour_description_present_flag {
Some(ColourDescription {
colour_primaries: r.read_u8(8, "colour_primaries")?,
transfer_characteristics: r.read_u8(8, "transfer_characteristics")?,
matrix_coefficients: r.read_u8(8, "matrix_coefficients")?,
})
} else {
None
})
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct VideoSignalType {
pub video_format: VideoFormat,
pub video_full_range_flag: bool,
pub colour_description: Option<ColourDescription>,
}
impl VideoSignalType {
fn read<R: BitRead>(r: &mut R) -> Result<Option<VideoSignalType>, BitReaderError> {
let video_signal_type_present_flag = r.read_bool("video_signal_type_present_flag")?;
Ok(if video_signal_type_present_flag {
Some(VideoSignalType {
video_format: VideoFormat::from(r.read_u8(3, "video_format")?),
video_full_range_flag: r.read_bool("video_full_range_flag")?,
colour_description: ColourDescription::read(r)?,
})
} else {
None
})
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ChromaLocInfo {
pub chroma_sample_loc_type_top_field: u32,
pub chroma_sample_loc_type_bottom_field: u32,
}
impl ChromaLocInfo {
fn read<R: BitRead>(r: &mut R) -> Result<Option<ChromaLocInfo>, BitReaderError> {
let chroma_loc_info_present_flag = r.read_bool("chroma_loc_info_present_flag")?;
Ok(if chroma_loc_info_present_flag {
Some(ChromaLocInfo {
chroma_sample_loc_type_top_field: r.read_ue("chroma_sample_loc_type_top_field")?,
chroma_sample_loc_type_bottom_field: r
.read_ue("chroma_sample_loc_type_bottom_field")?,
})
} else {
None
})
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TimingInfo {
pub num_units_in_tick: u32,
pub time_scale: u32,
pub fixed_frame_rate_flag: bool,
}
impl TimingInfo {
fn read<R: BitRead>(r: &mut R) -> Result<Option<TimingInfo>, BitReaderError> {
let timing_info_present_flag = r.read_bool("timing_info_present_flag")?;
Ok(if timing_info_present_flag {
Some(TimingInfo {
num_units_in_tick: r.read_u32(32, "num_units_in_tick")?,
time_scale: r.read_u32(32, "time_scale")?,
fixed_frame_rate_flag: r.read_bool("fixed_frame_rate_flag")?,
})
} else {
None
})
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CpbSpec {
pub bit_rate_value_minus1: u32,
pub cpb_size_value_minus1: u32,
pub cbr_flag: bool,
}
impl CpbSpec {
fn read<R: BitRead>(r: &mut R) -> Result<CpbSpec, BitReaderError> {
Ok(CpbSpec {
bit_rate_value_minus1: r.read_ue("bit_rate_value_minus1")?,
cpb_size_value_minus1: r.read_ue("cpb_size_value_minus1")?,
cbr_flag: r.read_bool("cbr_flag")?,
})
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HrdParameters {
pub bit_rate_scale: u8,
pub cpb_size_scale: u8,
pub cpb_specs: Vec<CpbSpec>,
pub initial_cpb_removal_delay_length_minus1: u8,
pub cpb_removal_delay_length_minus1: u8,
pub dpb_output_delay_length_minus1: u8,
pub time_offset_length: u8,
}
impl HrdParameters {
fn read<R: BitRead>(
r: &mut R,
hrd_parameters_present: &mut bool,
) -> Result<Option<HrdParameters>, SpsError> {
let hrd_parameters_present_flag = r.read_bool("hrd_parameters_present_flag")?;
*hrd_parameters_present |= hrd_parameters_present_flag;
Ok(if hrd_parameters_present_flag {
let cpb_cnt_minus1 = r.read_ue("cpb_cnt_minus1")?;
if cpb_cnt_minus1 > 31 {
return Err(SpsError::CpbCountOutOfRange(cpb_cnt_minus1));
}
let cpb_cnt = cpb_cnt_minus1 + 1;
Some(HrdParameters {
bit_rate_scale: r.read_u8(4, "bit_rate_scale")?,
cpb_size_scale: r.read_u8(4, "cpb_size_scale")?,
cpb_specs: Self::read_cpb_specs(r, cpb_cnt)?,
initial_cpb_removal_delay_length_minus1: r
.read_u8(5, "initial_cpb_removal_delay_length_minus1")?,
cpb_removal_delay_length_minus1: r.read_u8(5, "cpb_removal_delay_length_minus1")?,
dpb_output_delay_length_minus1: r.read_u8(5, "dpb_output_delay_length_minus1")?,
time_offset_length: r.read_u8(5, "time_offset_length")?,
})
} else {
None
})
}
fn read_cpb_specs<R: BitRead>(r: &mut R, cpb_cnt: u32) -> Result<Vec<CpbSpec>, BitReaderError> {
let mut cpb_specs = Vec::with_capacity(cpb_cnt as usize);
for _ in 0..cpb_cnt {
cpb_specs.push(CpbSpec::read(r)?);
}
Ok(cpb_specs)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BitstreamRestrictions {
pub motion_vectors_over_pic_boundaries_flag: bool,
pub max_bytes_per_pic_denom: u32,
pub max_bits_per_mb_denom: u32,
pub log2_max_mv_length_horizontal: u32,
pub log2_max_mv_length_vertical: u32,
pub max_num_reorder_frames: u32,
pub max_dec_frame_buffering: u32,
}
impl BitstreamRestrictions {
fn read<R: BitRead>(r: &mut R) -> Result<Option<BitstreamRestrictions>, BitReaderError> {
let bitstream_restriction_flag = r.read_bool("bitstream_restriction_flag")?;
Ok(if bitstream_restriction_flag {
Some(BitstreamRestrictions {
motion_vectors_over_pic_boundaries_flag: r
.read_bool("motion_vectors_over_pic_boundaries_flag")?,
max_bytes_per_pic_denom: r.read_ue("max_bytes_per_pic_denom")?,
max_bits_per_mb_denom: r.read_ue("max_bits_per_mb_denom")?,
log2_max_mv_length_horizontal: r.read_ue("log2_max_mv_length_horizontal")?,
log2_max_mv_length_vertical: r.read_ue("log2_max_mv_length_vertical")?,
max_num_reorder_frames: r.read_ue("max_num_reorder_frames")?,
max_dec_frame_buffering: r.read_ue("max_dec_frame_buffering")?,
})
} else {
None
})
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct VuiParameters {
pub aspect_ratio_info: Option<AspectRatioInfo>,
pub overscan_appropriate: OverscanAppropriate,
pub video_signal_type: Option<VideoSignalType>,
pub chroma_loc_info: Option<ChromaLocInfo>,
pub timing_info: Option<TimingInfo>,
pub nal_hrd_parameters: Option<HrdParameters>,
pub vcl_hrd_parameters: Option<HrdParameters>,
pub low_delay_hrd_flag: Option<bool>,
pub pic_struct_present_flag: bool,
pub bitstream_restrictions: Option<BitstreamRestrictions>,
}
impl VuiParameters {
fn read<R: BitRead>(r: &mut R) -> Result<Option<VuiParameters>, SpsError> {
let vui_parameters_present_flag = r.read_bool("vui_parameters_present_flag")?;
Ok(if vui_parameters_present_flag {
let mut hrd_parameters_present = false;
Some(VuiParameters {
aspect_ratio_info: AspectRatioInfo::read(r)?,
overscan_appropriate: OverscanAppropriate::read(r)?,
video_signal_type: VideoSignalType::read(r)?,
chroma_loc_info: ChromaLocInfo::read(r)?,
timing_info: TimingInfo::read(r)?,
nal_hrd_parameters: HrdParameters::read(r, &mut hrd_parameters_present)?,
vcl_hrd_parameters: HrdParameters::read(r, &mut hrd_parameters_present)?,
low_delay_hrd_flag: if hrd_parameters_present {
Some(r.read_bool("low_delay_hrd_flag")?)
} else {
None
},
pic_struct_present_flag: r.read_bool("pic_struct_present_flag")?,
bitstream_restrictions: BitstreamRestrictions::read(r)?,
})
} else {
None
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SeqParameterSet {
pub profile_idc: ProfileIdc,
pub constraint_flags: ConstraintFlags,
pub level_idc: u8,
pub seq_parameter_set_id: SeqParamSetId,
pub chroma_info: ChromaInfo,
pub log2_max_frame_num_minus4: u8,
pub pic_order_cnt: PicOrderCntType,
pub max_num_ref_frames: u32,
pub gaps_in_frame_num_value_allowed_flag: bool,
pub pic_width_in_mbs_minus1: u32,
pub pic_height_in_map_units_minus1: u32,
pub frame_mbs_flags: FrameMbsFlags,
pub direct_8x8_inference_flag: bool,
pub frame_cropping: Option<FrameCropping>,
pub vui_parameters: Option<VuiParameters>,
}
impl SeqParameterSet {
pub fn from_bits<R: BitRead>(mut r: R) -> Result<SeqParameterSet, SpsError> {
let profile_idc = r.read_u8(8, "profile_idc")?.into();
let sps = SeqParameterSet {
profile_idc,
constraint_flags: r.read_u8(8, "constraint_flags")?.into(),
level_idc: r.read_u8(8, "level_idc")?,
seq_parameter_set_id: SeqParamSetId::from_u32(r.read_ue("seq_parameter_set_id")?)
.map_err(SpsError::BadSeqParamSetId)?,
chroma_info: ChromaInfo::read(&mut r, profile_idc)?,
log2_max_frame_num_minus4: Self::read_log2_max_frame_num_minus4(&mut r)?,
pic_order_cnt: PicOrderCntType::read(&mut r).map_err(SpsError::PicOrderCnt)?,
max_num_ref_frames: r.read_ue("max_num_ref_frames")?,
gaps_in_frame_num_value_allowed_flag: r
.read_bool("gaps_in_frame_num_value_allowed_flag")?,
pic_width_in_mbs_minus1: r.read_ue("pic_width_in_mbs_minus1")?,
pic_height_in_map_units_minus1: r.read_ue("pic_height_in_map_units_minus1")?,
frame_mbs_flags: FrameMbsFlags::read(&mut r)?,
direct_8x8_inference_flag: r.read_bool("direct_8x8_inference_flag")?,
frame_cropping: FrameCropping::read(&mut r)?,
vui_parameters: VuiParameters::read(&mut r)?,
};
r.finish_rbsp()?;
Ok(sps)
}
pub fn id(&self) -> SeqParamSetId {
self.seq_parameter_set_id
}
fn read_log2_max_frame_num_minus4<R: BitRead>(r: &mut R) -> Result<u8, SpsError> {
let val = r.read_ue("log2_max_frame_num_minus4")?;
if val > 12 {
Err(SpsError::Log2MaxFrameNumMinus4OutOfRange(val))
} else {
Ok(val as u8)
}
}
pub fn profile(&self) -> Profile {
Profile::from_profile_idc(self.profile_idc)
}
pub fn level(&self) -> Level {
Level::from_constraint_flags_and_level_idc(self.constraint_flags, self.level_idc)
}
/// returned value will be in the range 4 to 16 inclusive
pub fn log2_max_frame_num(&self) -> u8 {
self.log2_max_frame_num_minus4 + 4
}
/// Helper to calculate the pixel-dimensions of the video image specified by this SPS, taking
/// into account sample-format, interlacing and cropping.
pub fn pixel_dimensions(&self) -> Result<(u32, u32), SpsError> {
let width = self
.pic_width_in_mbs_minus1
.checked_add(1)
.and_then(|w| w.checked_mul(16))
.ok_or_else(|| SpsError::FieldValueTooLarge {
name: "pic_width_in_mbs_minus1",
value: self.pic_width_in_mbs_minus1,
})?;
let mul = match self.frame_mbs_flags {
FrameMbsFlags::Fields { .. } => 2,
FrameMbsFlags::Frames => 1,
};
let vsub = if self.chroma_info.chroma_format == ChromaFormat::YUV420 {
1
} else {
0
};
let hsub = if self.chroma_info.chroma_format == ChromaFormat::YUV420
|| self.chroma_info.chroma_format == ChromaFormat::YUV422
{
1
} else {
0
};
let step_x = 1 << hsub;
let step_y = mul << vsub;
let height = (self.pic_height_in_map_units_minus1 + 1)
.checked_mul(mul * 16)
.ok_or_else(|| SpsError::FieldValueTooLarge {
name: "pic_height_in_map_units_minus1",
value: self.pic_height_in_map_units_minus1,
})?;
if let Some(ref crop) = self.frame_cropping {
let left_offset = crop.left_offset.checked_mul(step_x).ok_or_else(|| {
SpsError::FieldValueTooLarge {
name: "left_offset",
value: crop.left_offset,
}
})?;
let right_offset = crop.right_offset.checked_mul(step_x).ok_or_else(|| {
SpsError::FieldValueTooLarge {
name: "right_offset",
value: crop.right_offset,
}
})?;
let top_offset = crop.top_offset.checked_mul(step_y).ok_or_else(|| {
SpsError::FieldValueTooLarge {
name: "top_offset",
value: crop.top_offset,
}