oxideav-h264 0.1.9

Pure-Rust H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) codec for oxideav — under spec-driven rewrite, no decode/encode functionality yet
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
//! §7.3.2.1 — Sequence Parameter Set parsing.
//!
//! Spec-driven implementation of `seq_parameter_set_rbsp()` per ITU-T
//! Rec. H.264 (08/2024). VUI body (§E.1) and scaling_list body
//! (§7.3.2.1.1.1) are fully parsed — their bodies delegate to
//! [`crate::vui`] and [`crate::scaling_list`] respectively.
//!
//! The parser takes an already-de-emulated RBSP (`emulation_prevention_three_byte`
//! stripped by [`crate::nal::parse_nal_unit`]). The caller peels off the
//! NAL header byte before handing us the slice.

use crate::bitstream::{BitError, BitReader};
use crate::scaling_list::{parse_scaling_list, ScalingListError, ScalingListResult};
use crate::vui::{VuiError, VuiParameters};

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum SpsError {
    #[error("bitstream read failed: {0}")]
    Bitstream(#[from] BitError),
    /// §7.3.2.1.1 — `reserved_zero_2bits` shall be equal to 0.
    #[error("reserved_zero_2bits is not 0 (got {0})")]
    ReservedNotZero(u32),
    /// §A.1 / §A.2 — profile_idc must be one of the values enumerated
    /// in clause A.2 (66 Baseline, 77 Main, 88 Extended, 100 High,
    /// 110 High 10, 122 High 4:2:2, 244 High 4:4:4 Predictive, 44
    /// CAVLC 4:4:4 Intra, 83 Scalable Baseline, 86 Scalable High,
    /// 118 Multiview High, 128 Stereo High, 138 Multiview Depth High,
    /// 139 Enhanced Multiview Depth High, 134 MFC High, 135 MFC Depth
    /// High). All other values are "reserved for future use by ITU-T
    /// | ISO/IEC" and the decoder cannot honour them — reject early
    /// (matching the strictness of common H.264 decoders) instead of
    /// silently mis-decoding.
    #[error("profile_idc {0} is reserved (not enumerated in §A.2)")]
    ProfileIdcReserved(u8),
    /// §7.4.2.1.1 — `chroma_format_idc` in range 0..=3.
    #[error("chroma_format_idc out of range (got {0}, max 3)")]
    ChromaFormatIdcOutOfRange(u32),
    /// §7.4.2.1.1 — `bit_depth_luma_minus8` in range 0..=6.
    #[error("bit_depth_luma_minus8 out of range (got {0}, max 6)")]
    BitDepthLumaOutOfRange(u32),
    /// §7.4.2.1.1 — `bit_depth_chroma_minus8` in range 0..=6.
    #[error("bit_depth_chroma_minus8 out of range (got {0}, max 6)")]
    BitDepthChromaOutOfRange(u32),
    /// §7.4.2.1.1 — `log2_max_frame_num_minus4` in range 0..=12.
    #[error("log2_max_frame_num_minus4 out of range (got {0}, max 12)")]
    Log2MaxFrameNumOutOfRange(u32),
    /// §7.4.2.1.1 — `pic_order_cnt_type` in range 0..=2.
    #[error("pic_order_cnt_type out of range (got {0}, max 2)")]
    PicOrderCntTypeOutOfRange(u32),
    /// §7.4.2.1.1 — `log2_max_pic_order_cnt_lsb_minus4` in range 0..=12.
    #[error("log2_max_pic_order_cnt_lsb_minus4 out of range (got {0}, max 12)")]
    Log2MaxPocLsbOutOfRange(u32),
    /// §7.4.2.1.1 — `num_ref_frames_in_pic_order_cnt_cycle` in range 0..=255.
    #[error("num_ref_frames_in_pic_order_cnt_cycle out of range (got {0}, max 255)")]
    NumRefFramesInPocCycleOutOfRange(u32),
    /// §7.3.2.1.1 — `seq_parameter_set_id` range 0..=31.
    #[error("seq_parameter_set_id out of range (got {0}, max 31)")]
    SpsIdOutOfRange(u32),
    /// §A.3 — picture dimensions are bounded by Annex A level limits.
    /// `pic_width_in_mbs_minus1` is capped at 510 here so the derived
    /// `Picture::new` allocation (luma + 2× chroma at 4:4:4 = 3 ×
    /// width_samples × height_samples bytes) stays within ~200 MB
    /// even at the worst-case bit depth + chroma subsampling. Real
    /// streams sit far below this — Level 6.2's MaxFS = 139264 implies
    /// a per-axis upper bound of ~1056 mbs (and 4K-class streams need
    /// only ~240 mbs / axis).
    #[error("pic_width_in_mbs_minus1 out of range (got {0}, max 510)")]
    PicWidthInMbsOutOfRange(u32),
    /// §A.3 — see `PicWidthInMbsOutOfRange`. Same rationale.
    #[error("pic_height_in_map_units_minus1 out of range (got {0}, max 510)")]
    PicHeightInMapUnitsOutOfRange(u32),
    /// §7.3.2.1.1.1 — scaling_list body parse error.
    #[error("scaling_list: {0}")]
    ScalingList(#[from] ScalingListError),
    /// §E.1 — VUI parameters body parse error.
    #[error("vui_parameters: {0}")]
    Vui(#[from] VuiError),
    /// §7.4.2.1.1 — `max_num_ref_frames` shall be in the range of 0 to
    /// MaxDpbFrames (clause A.3), which is itself capped at 16 by the
    /// Min(...) expression in A.3.1 step a regardless of level. Any
    /// value above 16 is malformed (common H.264 decoders reject with
    /// a "too many reference frames" diagnostic).
    #[error("max_num_ref_frames out of range (got {0}, max 16)")]
    MaxNumRefFramesOutOfRange(u32),
    /// §7.4.2.1.1 — frame-cropping rectangle leaves the coded picture
    /// boundary. The spec says:
    ///
    ///   * `frame_crop_left_offset` ∈ `[0, (PicWidthInSamplesL /
    ///     CropUnitX) − (frame_crop_right_offset + 1)]`,
    ///   * `frame_crop_top_offset`  ∈ `[0, (16 * FrameHeightInMbs /
    ///     CropUnitY) − (frame_crop_bottom_offset + 1)]`.
    ///
    /// Reformulated as a positivity check, the cropped rectangle's
    /// width and height must each be at least 1 luma sample. Strings
    /// with a `frame_cropping_flag = 1` SPS that violate these are
    /// rejected by common H.264 decoders at SPS-parse time with a
    /// "crop values invalid X Y W H" diagnostic; the access unit's
    /// slices then dangle with no activated SPS. Caught by the
    /// `ffmpeg_oracle_decode` fuzz oracle on `crash-8e8b38ae…`
    /// (round 91).
    #[error(
        "frame_cropping invalid: CropUnitX={cux}*(left={left}+right={right}+1) > PicWidthInSamplesL={width}, or CropUnitY={cuy}*(top={top}+bottom={bottom}+1) > FrameHeightInSamplesL={height}"
    )]
    FrameCroppingOutOfRange {
        cux: u32,
        cuy: u32,
        left: u32,
        right: u32,
        top: u32,
        bottom: u32,
        width: u32,
        height: u32,
    },
}

/// §A.3 derived ceiling — the maximum representable
/// `pic_width_in_mbs_minus1` / `pic_height_in_map_units_minus1` after
/// safety bounding. Anything > this is treated as malformed input.
///
/// Chosen so that the worst-case `Picture::new` allocation (luma +
/// 2× chroma at 4:4:4 = 3 × width_samples × height_samples bytes)
/// stays under ~200 MB, well within typical fuzz / decoder memory
/// budgets. Real Annex A Level 6.2 streams need ~1056 mbs per axis;
/// the cap of 510 (8176 luma samples / axis) is comfortably above
/// any realistic 4K-class stream while preventing pathological
/// PicSizeInMbs from driving multi-GB allocations.
const MAX_PIC_DIM_IN_MBS_MINUS1: u32 = (1 << 9) - 2;

/// §A.2 — return true iff `profile_idc` is one of the 16 values
/// enumerated in clause A.2 (Baseline / Constrained Baseline → 66,
/// Main → 77, Extended → 88, High → 100, High 10 / High 10 Intra →
/// 110, High 4:2:2 / High 4:2:2 Intra → 122, High 4:4:4 Predictive /
/// High 4:4:4 Intra → 244, CAVLC 4:4:4 Intra → 44, Scalable Baseline
/// (Annex G) → 83, Scalable High (Annex G) → 86, Multiview High
/// (Annex H) → 118, Stereo High (Annex H) → 128, Multiview Depth High
/// (Annex I) → 138, Enhanced Multiview Depth High (Annex I) → 139,
/// MFC High (Annex H) → 134, MFC Depth High (Annex I) → 135). All
/// other values are "reserved for future use" per §A.1 and the
/// decoder cannot safely consume them.
fn is_valid_profile_idc(profile_idc: u8) -> bool {
    matches!(
        profile_idc,
        66 | 77 | 88 | 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
    )
}

/// §7.3.2.1.1 — per-index entry in the SPS scaling-matrix list.
///
/// Each slot corresponds to one `seq_scaling_list_present_flag[i]` bit.
/// When the flag is 0 (`NotPresent`), the decoder inherits per
/// §7.4.2.1.1.1 Table 7-3 ("fall-back rule A" / "fall-back rule B").
/// When the flag is 1, the scaling_list body is parsed; if the spec's
/// `useDefaultScalingMatrixFlag` is triggered we mark `UseDefault`,
/// otherwise we carry the parsed values in `Explicit`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScalingListEntry {
    /// `seq_scaling_list_present_flag[i] == 0` — use the fall-back rule.
    NotPresent,
    /// Flag was 1 and `useDefaultScalingMatrixFlag` fired.
    UseDefault,
    /// Flag was 1 and explicit values were parsed. Length 16 for i<6,
    /// length 64 otherwise.
    Explicit(Vec<i32>),
}

impl ScalingListEntry {
    fn from_result(r: ScalingListResult) -> Self {
        if r.use_default {
            Self::UseDefault
        } else {
            Self::Explicit(r.scaling_list)
        }
    }
}

/// §7.3.2.1.1 — SPS scaling matrices.
///
/// The first 6 entries are 4x4 scaling lists (Intra Y, Cb, Cr; Inter Y,
/// Cb, Cr per Table 7-2). The remaining 0, 2, or 6 entries are 8x8
/// scaling lists — 0 when `transform_8x8_mode_flag == 0` (this SPS-level
/// matrix doesn't carry 8x8 lists when the PPS tail wouldn't enable
/// them), 2 when chroma_format_idc != 3, 6 when chroma_format_idc == 3.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SeqScalingLists {
    pub entries: Vec<ScalingListEntry>,
}

/// §7.4.2.1.1 — frame cropping offsets. Present when
/// `frame_cropping_flag == 1`. Derived `CropUnitX` / `CropUnitY` depend
/// on `ChromaArrayType` (§7.4.2.1.1 eq. 7-19 .. 7-22).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrameCropping {
    pub left: u32,
    pub right: u32,
    pub top: u32,
    pub bottom: u32,
}

/// §7.3.2.1.1 — parsed `seq_parameter_set_data()`.
///
/// Fields that the spec infers (not present in the bitstream for the
/// current profile path) are stored at their inferred values, as
/// documented in §7.4.2.1.1:
/// * `chroma_format_idc` ← 1 (4:2:0) when not present,
/// * `separate_colour_plane_flag` ← 0,
/// * `bit_depth_luma_minus8` / `bit_depth_chroma_minus8` ← 0,
/// * `qpprime_y_zero_transform_bypass_flag` ← 0,
/// * `seq_scaling_matrix_present_flag` ← 0,
/// * `mb_adaptive_frame_field_flag` ← 0 when `frame_mbs_only_flag == 1`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sps {
    // §7.3.2.1.1
    pub profile_idc: u8,
    /// Packed bits: bit 0 = constraint_set0_flag, …, bit 5 = constraint_set5_flag.
    /// Bits 6..=7 are always 0 (they hold `reserved_zero_2bits`, which
    /// we validate to be zero during parsing).
    pub constraint_set_flags: u8,
    pub level_idc: u8,
    pub seq_parameter_set_id: u32,

    // Only present when profile_idc is one of the "chroma-extended"
    // profiles listed in §7.3.2.1.1 (100/110/122/244/44/83/86/118/128/138/139/134/135).
    pub chroma_format_idc: u32,
    pub separate_colour_plane_flag: bool,
    pub bit_depth_luma_minus8: u32,
    pub bit_depth_chroma_minus8: u32,
    pub qpprime_y_zero_transform_bypass_flag: bool,
    pub seq_scaling_matrix_present_flag: bool,
    /// §7.3.2.1.1.1 — parsed scaling matrices, when present.
    pub seq_scaling_lists: Option<SeqScalingLists>,

    pub log2_max_frame_num_minus4: u32,
    pub pic_order_cnt_type: u32,

    // pic_order_cnt_type == 0 branch:
    pub log2_max_pic_order_cnt_lsb_minus4: u32,

    // pic_order_cnt_type == 1 branch:
    pub delta_pic_order_always_zero_flag: bool,
    pub offset_for_non_ref_pic: i32,
    pub offset_for_top_to_bottom_field: i32,
    pub num_ref_frames_in_pic_order_cnt_cycle: u32,
    pub offset_for_ref_frame: Vec<i32>,

    // Common tail:
    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_only_flag: bool,
    pub mb_adaptive_frame_field_flag: bool,
    pub direct_8x8_inference_flag: bool,
    pub frame_cropping: Option<FrameCropping>,
    pub vui_parameters_present_flag: bool,
    /// §E.1 — parsed VUI parameters, when signalled.
    pub vui: Option<VuiParameters>,
}

impl Sps {
    /// §7.3.2.1 — parse a `seq_parameter_set_rbsp()` from a slice that
    /// holds the RBSP body (i.e. the bytes *after* the NAL header byte,
    /// with emulation prevention bytes already stripped — normally
    /// obtained from [`crate::nal::parse_nal_unit`]).
    ///
    /// Both the VUI body (§E.1) and the scaling_list body
    /// (§7.3.2.1.1.1) are fully parsed inline.
    pub fn parse(rbsp: &[u8]) -> Result<Self, SpsError> {
        let mut r = BitReader::new(rbsp);
        let sps = Self::parse_seq_parameter_set_data(&mut r)?;
        // §7.3.2.11 — trailing stop bit + zero alignment. Some producers
        // pad with extra zeros; don't reject on mis-match.
        let _ = r.rbsp_trailing_bits();
        Ok(sps)
    }

    /// §7.3.2.1.1 — parse a `seq_parameter_set_data()` syntax structure
    /// from the current cursor position, leaving the reader positioned
    /// on the first bit after it (rbsp_trailing_bits are NOT consumed).
    ///
    /// This is the shared body between `seq_parameter_set_rbsp()`
    /// (§7.3.2.1, see [`Sps::parse`]) and
    /// `subset_seq_parameter_set_rbsp()` (§7.3.2.1.3, see
    /// [`crate::subset_sps::SubsetSps::parse`]) — the latter continues
    /// reading a per-profile extension structure after this one.
    pub fn parse_seq_parameter_set_data(r: &mut BitReader<'_>) -> Result<Self, SpsError> {
        // §7.3.2.1.1 — profile_idc / constraint_setN_flag / reserved_zero_2bits / level_idc.
        let profile_idc = r.u(8)? as u8;
        // §A.1 / §A.2 — only the 16 enumerated profiles are allowed;
        // other values are "reserved for future use" and we cannot
        // safely decode bitstreams using them. Reject up front to
        // match the strictness of common H.264 decoders (closes a fuzz-oracle
        // divergence on profile_idc=251 + 243 inputs).
        if !is_valid_profile_idc(profile_idc) {
            return Err(SpsError::ProfileIdcReserved(profile_idc));
        }
        let cs0 = r.u(1)? as u8;
        let cs1 = r.u(1)? as u8;
        let cs2 = r.u(1)? as u8;
        let cs3 = r.u(1)? as u8;
        let cs4 = r.u(1)? as u8;
        let cs5 = r.u(1)? as u8;
        // §7.3.2.1.1 — reserved_zero_2bits /* equal to 0 */.
        let reserved = r.u(2)?;
        if reserved != 0 {
            return Err(SpsError::ReservedNotZero(reserved));
        }
        let level_idc = r.u(8)? as u8;

        let constraint_set_flags =
            cs0 | (cs1 << 1) | (cs2 << 2) | (cs3 << 3) | (cs4 << 4) | (cs5 << 5);

        // §7.3.2.1.1 — seq_parameter_set_id ue(v); semantics clamp to 0..=31.
        let seq_parameter_set_id = r.ue()?;
        if seq_parameter_set_id > 31 {
            return Err(SpsError::SpsIdOutOfRange(seq_parameter_set_id));
        }

        // §7.3.2.1.1 — the "chroma-extended" profile gate.
        let mut chroma_format_idc: u32 = 1; // §7.4.2.1.1 default when absent
        let mut separate_colour_plane_flag = false;
        let mut bit_depth_luma_minus8: u32 = 0;
        let mut bit_depth_chroma_minus8: u32 = 0;
        let mut qpprime_y_zero_transform_bypass_flag = false;
        let mut seq_scaling_matrix_present_flag = false;

        if matches!(
            profile_idc,
            100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
        ) {
            chroma_format_idc = r.ue()?;
            if chroma_format_idc > 3 {
                return Err(SpsError::ChromaFormatIdcOutOfRange(chroma_format_idc));
            }
            if chroma_format_idc == 3 {
                separate_colour_plane_flag = r.u(1)? == 1;
            }
            bit_depth_luma_minus8 = r.ue()?;
            if bit_depth_luma_minus8 > 6 {
                return Err(SpsError::BitDepthLumaOutOfRange(bit_depth_luma_minus8));
            }
            bit_depth_chroma_minus8 = r.ue()?;
            if bit_depth_chroma_minus8 > 6 {
                return Err(SpsError::BitDepthChromaOutOfRange(bit_depth_chroma_minus8));
            }
            qpprime_y_zero_transform_bypass_flag = r.u(1)? == 1;
            seq_scaling_matrix_present_flag = r.u(1)? == 1;
        }
        // §7.3.2.1.1 — scaling_list body outside the chroma-extended gate.
        // When `seq_scaling_matrix_present_flag` is only set by that gate,
        // this loop runs exactly when the flag is true.
        let seq_scaling_lists = if seq_scaling_matrix_present_flag {
            // §7.3.2.1.1 — loop bound: 8 for chroma_format_idc != 3, 12 for 4:4:4.
            let n = if chroma_format_idc != 3 { 8 } else { 12 };
            let mut entries = Vec::with_capacity(n);
            for i in 0..n {
                let present = r.u(1)? == 1;
                if !present {
                    entries.push(ScalingListEntry::NotPresent);
                } else {
                    // First 6 entries are 4x4 (size 16), rest are 8x8 (size 64).
                    let size = if i < 6 { 16 } else { 64 };
                    let result = parse_scaling_list(r, size)?;
                    entries.push(ScalingListEntry::from_result(result));
                }
            }
            Some(SeqScalingLists { entries })
        } else {
            None
        };

        // §7.3.2.1.1 — log2_max_frame_num_minus4 ue(v); range 0..=12.
        let log2_max_frame_num_minus4 = r.ue()?;
        if log2_max_frame_num_minus4 > 12 {
            return Err(SpsError::Log2MaxFrameNumOutOfRange(
                log2_max_frame_num_minus4,
            ));
        }

        // §7.3.2.1.1 — pic_order_cnt_type ue(v); range 0..=2.
        let pic_order_cnt_type = r.ue()?;
        if pic_order_cnt_type > 2 {
            return Err(SpsError::PicOrderCntTypeOutOfRange(pic_order_cnt_type));
        }

        let mut log2_max_pic_order_cnt_lsb_minus4: u32 = 0;
        let mut delta_pic_order_always_zero_flag = false;
        let mut offset_for_non_ref_pic: i32 = 0;
        let mut offset_for_top_to_bottom_field: i32 = 0;
        let mut num_ref_frames_in_pic_order_cnt_cycle: u32 = 0;
        let mut offset_for_ref_frame: Vec<i32> = Vec::new();

        if pic_order_cnt_type == 0 {
            log2_max_pic_order_cnt_lsb_minus4 = r.ue()?;
            if log2_max_pic_order_cnt_lsb_minus4 > 12 {
                return Err(SpsError::Log2MaxPocLsbOutOfRange(
                    log2_max_pic_order_cnt_lsb_minus4,
                ));
            }
        } else if pic_order_cnt_type == 1 {
            delta_pic_order_always_zero_flag = r.u(1)? == 1;
            offset_for_non_ref_pic = r.se()?;
            offset_for_top_to_bottom_field = r.se()?;
            num_ref_frames_in_pic_order_cnt_cycle = r.ue()?;
            if num_ref_frames_in_pic_order_cnt_cycle > 255 {
                return Err(SpsError::NumRefFramesInPocCycleOutOfRange(
                    num_ref_frames_in_pic_order_cnt_cycle,
                ));
            }
            offset_for_ref_frame.reserve_exact(num_ref_frames_in_pic_order_cnt_cycle as usize);
            for _ in 0..num_ref_frames_in_pic_order_cnt_cycle {
                offset_for_ref_frame.push(r.se()?);
            }
        }
        // pic_order_cnt_type == 2: no extra fields.

        // §7.3.2.1.1 — common tail.
        // §7.4.2.1.1 / Annex A.3.1 — `max_num_ref_frames` ≤ MaxDpbFrames
        // which is capped at 16 regardless of level. Beyond 16, downstream
        // ref-list construction is invalid and the bitstream is malformed.
        let max_num_ref_frames = r.ue()?;
        if max_num_ref_frames > 16 {
            return Err(SpsError::MaxNumRefFramesOutOfRange(max_num_ref_frames));
        }
        let gaps_in_frame_num_value_allowed_flag = r.u(1)? == 1;
        let pic_width_in_mbs_minus1 = r.ue()?;
        if pic_width_in_mbs_minus1 > MAX_PIC_DIM_IN_MBS_MINUS1 {
            return Err(SpsError::PicWidthInMbsOutOfRange(pic_width_in_mbs_minus1));
        }
        let pic_height_in_map_units_minus1 = r.ue()?;
        if pic_height_in_map_units_minus1 > MAX_PIC_DIM_IN_MBS_MINUS1 {
            return Err(SpsError::PicHeightInMapUnitsOutOfRange(
                pic_height_in_map_units_minus1,
            ));
        }
        let frame_mbs_only_flag = r.u(1)? == 1;
        let mb_adaptive_frame_field_flag = if !frame_mbs_only_flag {
            r.u(1)? == 1
        } else {
            false
        };
        let direct_8x8_inference_flag = r.u(1)? == 1;

        // §7.3.2.1.1 — frame_cropping_flag + four offsets.
        let frame_cropping_flag = r.u(1)? == 1;
        let frame_cropping = if frame_cropping_flag {
            let left = r.ue()?;
            let right = r.ue()?;
            let top = r.ue()?;
            let bottom = r.ue()?;

            // §7.4.2.1.1 — validate the cropping rectangle stays
            // within the coded picture. Required by:
            //   `frame_crop_left_offset ∈ [0, (PicWidthInSamplesL /
            //    CropUnitX) − (frame_crop_right_offset + 1)]`,
            //   `frame_crop_top_offset  ∈ [0, (16 * FrameHeightInMbs
            //    / CropUnitY) − (frame_crop_bottom_offset + 1)]`.
            //
            // CropUnitX / CropUnitY (eqs. 7-19..7-22) depend on
            // ChromaArrayType:
            //   * ChromaArrayType == 0 (monochrome OR
            //     separate_colour_plane_flag == 1):
            //       CropUnitX = 1, CropUnitY = 2 − frame_mbs_only_flag
            //   * Otherwise (1=4:2:0, 2=4:2:2, 3=4:4:4):
            //       CropUnitX = SubWidthC,
            //       CropUnitY = SubHeightC * (2 − frame_mbs_only_flag)
            // with SubWidthC / SubHeightC from §6.2 Table 6-1:
            //       1 (4:2:0) → 2, 2
            //       2 (4:2:2) → 2, 1
            //       3 (4:4:4) → 1, 1
            //
            // The cast to u32 is safe: chroma_format_idc was already
            // bounded to 0..=3 above, separate_colour_plane_flag is
            // a single bit, frame_mbs_only_flag likewise.
            let chroma_array_type = if separate_colour_plane_flag {
                0
            } else {
                chroma_format_idc
            };
            let (sub_w_c, sub_h_c) = match chroma_array_type {
                1 => (2u32, 2u32),
                2 => (2u32, 1u32),
                3 => (1u32, 1u32),
                _ => (1u32, 1u32), // ChromaArrayType == 0
            };
            let mbs_only_factor = if frame_mbs_only_flag { 1u32 } else { 2u32 };
            let (cux, cuy) = if chroma_array_type == 0 {
                (1u32, mbs_only_factor)
            } else {
                (sub_w_c, sub_h_c * mbs_only_factor)
            };
            // PicWidthInSamplesL = (pic_width_in_mbs_minus1 + 1) * 16
            // FrameHeightInSamplesL = (2 - frame_mbs_only_flag) *
            //                          (pic_height_in_map_units_minus1 + 1) * 16
            let width_samples = (pic_width_in_mbs_minus1 + 1) * 16;
            let height_samples = mbs_only_factor * (pic_height_in_map_units_minus1 + 1) * 16;
            // Use u64 to avoid an overflow on the multiplication when
            // the input is pathological (cropping offsets are ue(v)
            // and the picture-dim cap is 510 mbs/axis = 8160 samples,
            // so cux * (left + right + 1) at worst is 2 * (u32::MAX +
            // 1) — fits comfortably in u64).
            let need_w = u64::from(cux) * (u64::from(left) + u64::from(right) + 1);
            let need_h = u64::from(cuy) * (u64::from(top) + u64::from(bottom) + 1);
            if need_w > u64::from(width_samples) || need_h > u64::from(height_samples) {
                return Err(SpsError::FrameCroppingOutOfRange {
                    cux,
                    cuy,
                    left,
                    right,
                    top,
                    bottom,
                    width: width_samples,
                    height: height_samples,
                });
            }

            Some(FrameCropping {
                left,
                right,
                top,
                bottom,
            })
        } else {
            None
        };

        // §7.3.2.1.1 / §E.1 — VUI parameters.
        let vui_parameters_present_flag = r.u(1)? == 1;
        let vui = if vui_parameters_present_flag {
            Some(VuiParameters::parse(r)?)
        } else {
            None
        };

        Ok(Sps {
            profile_idc,
            constraint_set_flags,
            level_idc,
            seq_parameter_set_id,
            chroma_format_idc,
            separate_colour_plane_flag,
            bit_depth_luma_minus8,
            bit_depth_chroma_minus8,
            qpprime_y_zero_transform_bypass_flag,
            seq_scaling_matrix_present_flag,
            seq_scaling_lists,
            log2_max_frame_num_minus4,
            pic_order_cnt_type,
            log2_max_pic_order_cnt_lsb_minus4,
            delta_pic_order_always_zero_flag,
            offset_for_non_ref_pic,
            offset_for_top_to_bottom_field,
            num_ref_frames_in_pic_order_cnt_cycle,
            offset_for_ref_frame,
            max_num_ref_frames,
            gaps_in_frame_num_value_allowed_flag,
            pic_width_in_mbs_minus1,
            pic_height_in_map_units_minus1,
            frame_mbs_only_flag,
            mb_adaptive_frame_field_flag,
            direct_8x8_inference_flag,
            frame_cropping,
            vui_parameters_present_flag,
            vui,
        })
    }

    /// §6.2 — `ChromaArrayType`:
    /// * `separate_colour_plane_flag == 0`: equal to `chroma_format_idc`
    /// * `separate_colour_plane_flag == 1`: equal to 0 (each plane is
    ///   coded as an independent monochrome picture).
    pub fn chroma_array_type(&self) -> u32 {
        if self.separate_colour_plane_flag {
            0
        } else {
            self.chroma_format_idc
        }
    }

    /// §7.4.2.1.1 eq. (7-13) — `PicWidthInMbs = pic_width_in_mbs_minus1 + 1`.
    pub fn pic_width_in_mbs(&self) -> u32 {
        self.pic_width_in_mbs_minus1 + 1
    }

    /// §7.4.2.1.1 eq. (7-16) — `PicHeightInMapUnits = pic_height_in_map_units_minus1 + 1`.
    pub fn pic_height_in_map_units(&self) -> u32 {
        self.pic_height_in_map_units_minus1 + 1
    }

    /// §7.4.2.1.1 eq. (7-18) — `FrameHeightInMbs = (2 - frame_mbs_only_flag) * PicHeightInMapUnits`.
    pub fn frame_height_in_mbs(&self) -> u32 {
        let factor = if self.frame_mbs_only_flag { 1 } else { 2 };
        factor * self.pic_height_in_map_units()
    }

    /// §7.4.2.1.1 eq. (7-26) — `PicHeightInMbs = FrameHeightInMbs / (1 + field_pic_flag)`.
    ///
    /// A field-coded picture (`field_pic_flag == 1`) is half the frame
    /// height in macroblocks; a frame-coded picture (`field_pic_flag == 0`,
    /// the MBAFF / progressive case) covers the full `FrameHeightInMbs`.
    pub fn pic_height_in_mbs(&self, field_pic_flag: bool) -> u32 {
        self.frame_height_in_mbs() / (1 + u32::from(field_pic_flag))
    }

    /// §7.4.2.1.1 eq. (7-25/7-27) — `PicSizeInMbs = PicWidthInMbs *
    /// PicHeightInMbs`. For a field picture this is half the frame's
    /// macroblock count.
    pub fn pic_size_in_mbs(&self, field_pic_flag: bool) -> u32 {
        self.pic_width_in_mbs()
            .saturating_mul(self.pic_height_in_mbs(field_pic_flag))
    }

    /// §7.4.2.1.1 eq. (7-10) — `MaxFrameNum = 2^(log2_max_frame_num_minus4 + 4)`.
    pub fn max_frame_num(&self) -> u32 {
        1u32 << (self.log2_max_frame_num_minus4 + 4)
    }

    /// §7.4.2.1.1 eq. (7-19) .. (7-22) — `(CropUnitX, CropUnitY)`.
    ///
    /// * `ChromaArrayType == 0`: `CropUnitX = 1`,
    ///   `CropUnitY = 2 − frame_mbs_only_flag`;
    /// * otherwise: `CropUnitX = SubWidthC`,
    ///   `CropUnitY = SubHeightC * (2 − frame_mbs_only_flag)`
    ///   (Table 6-1: 4:2:0 → 2/2, 4:2:2 → 2/1, 4:4:4 → 1/1).
    pub fn crop_units(&self) -> (u32, u32) {
        let field_factor = if self.frame_mbs_only_flag { 1 } else { 2 };
        let (sub_w, sub_h) = match self.chroma_array_type() {
            0 => (1, 1),
            1 => (2, 2),
            2 => (2, 1),
            _ => (1, 1),
        };
        (sub_w, sub_h * field_factor)
    }

    /// §7.4.2.1.1 — the frame cropping rectangle as luma-sample margins
    /// of the decoded *frame*: `(left, right, top, bottom)`, i.e. the
    /// `frame_crop_*_offset` values scaled by `CropUnitX` / `CropUnitY`.
    /// All zero when `frame_cropping_flag == 0`. The output frame keeps
    /// the luma samples with frame coordinates
    /// `CropUnitX * frame_crop_left_offset ..=
    /// PicWidthInSamplesL − (CropUnitX * frame_crop_right_offset + 1)`
    /// horizontally and the analogous range vertically.
    pub fn frame_crop_margins(&self) -> FrameCropMargins {
        let Some(c) = &self.frame_cropping else {
            return FrameCropMargins::default();
        };
        let (cux, cuy) = self.crop_units();
        FrameCropMargins {
            left: c.left.saturating_mul(cux),
            right: c.right.saturating_mul(cux),
            top: c.top.saturating_mul(cuy),
            bottom: c.bottom.saturating_mul(cuy),
        }
    }

    /// The dimensions of the cropped output frame in luma samples:
    /// `PicWidthInSamplesL` / `FrameHeightInMbs * 16` minus the
    /// [`Self::frame_crop_margins`].
    pub fn cropped_dimensions(&self) -> (u32, u32) {
        let m = self.frame_crop_margins();
        let w = self.pic_width_in_mbs() * 16;
        let h = self.frame_height_in_mbs() * 16;
        (
            w.saturating_sub(m.left.saturating_add(m.right)),
            h.saturating_sub(m.top.saturating_add(m.bottom)),
        )
    }
}

/// §7.4.2.1.1 — frame cropping rectangle expressed as luma-sample
/// margins removed from each edge of the decoded picture. See
/// [`Sps::frame_crop_margins`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FrameCropMargins {
    pub left: u32,
    pub right: u32,
    pub top: u32,
    pub bottom: u32,
}

impl FrameCropMargins {
    /// The margins as they apply to one *field* of the frame (a coded
    /// field, or an unpaired field emitted on its own): the vertical
    /// margins cover half as many rows. `CropUnitY` is even whenever
    /// fields exist (`frame_mbs_only_flag == 0`), so the halving is
    /// exact.
    pub fn for_field(self) -> Self {
        Self {
            top: self.top / 2,
            bottom: self.bottom / 2,
            ..self
        }
    }

    /// `true` when no sample is cropped.
    pub fn is_empty(&self) -> bool {
        self.left == 0 && self.right == 0 && self.top == 0 && self.bottom == 0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Tiny MSB-first bit writer — only for constructing test fixtures.
    /// Not part of the crate API.
    struct BitWriter {
        bytes: Vec<u8>,
        bit_pos: u8, // 0..=7, 0 = next bit goes into MSB of a fresh byte
    }

    impl BitWriter {
        fn new() -> Self {
            Self {
                bytes: Vec::new(),
                bit_pos: 0,
            }
        }

        fn u(&mut self, bits: u32, value: u32) {
            for i in (0..bits).rev() {
                let bit = ((value >> i) & 1) as u8;
                if self.bit_pos == 0 {
                    self.bytes.push(0);
                }
                let idx = self.bytes.len() - 1;
                self.bytes[idx] |= bit << (7 - self.bit_pos);
                self.bit_pos = (self.bit_pos + 1) % 8;
            }
        }

        fn ue(&mut self, value: u32) {
            // §9.1: codeNum = value ⇒ leadingZeros = floor(log2(value + 1)),
            // followed by (value + 1) written in `leadingZeros + 1` bits.
            let v = value + 1;
            let leading = 31 - v.leading_zeros();
            for _ in 0..leading {
                self.u(1, 0);
            }
            self.u(leading + 1, v);
        }

        fn se(&mut self, value: i32) {
            // §9.1.1: k=0→0, k=1→1, k=2→-1, k=3→2, …
            let k = if value <= 0 {
                (-2 * value) as u32
            } else {
                (2 * value - 1) as u32
            };
            self.ue(k);
        }

        fn trailing(&mut self) {
            self.u(1, 1);
            while self.bit_pos != 0 {
                self.u(1, 0);
            }
        }

        fn into_bytes(self) -> Vec<u8> {
            self.bytes
        }
    }

    /// Build a minimal Baseline (profile_idc=66) SPS byte-by-byte.
    /// Matches the §7.3.2.1.1 syntax table.
    fn build_baseline_sps(
        level_idc: u8,
        width_mbs: u32,
        height_mbs: u32,
        with_vui: bool,
    ) -> Vec<u8> {
        let mut w = BitWriter::new();
        w.u(8, 66); // profile_idc — Baseline
                    // constraint_set0..5_flag = 0, reserved_zero_2bits = 00
        w.u(8, 0);
        w.u(8, level_idc as u32); // level_idc
        w.ue(0); // seq_parameter_set_id
                 // no chroma-extended fields for profile 66
        w.ue(0); // log2_max_frame_num_minus4
        w.ue(0); // pic_order_cnt_type
        w.ue(0); // log2_max_pic_order_cnt_lsb_minus4 (since poc_type==0)
        w.ue(1); // max_num_ref_frames
        w.u(1, 0); // gaps_in_frame_num_value_allowed_flag
        w.ue(width_mbs - 1); // pic_width_in_mbs_minus1
        w.ue(height_mbs - 1); // pic_height_in_map_units_minus1
        w.u(1, 1); // frame_mbs_only_flag
        w.u(1, 1); // direct_8x8_inference_flag
        w.u(1, 0); // frame_cropping_flag
        w.u(1, if with_vui { 1 } else { 0 }); // vui_parameters_present_flag
        if !with_vui {
            w.trailing();
        }
        w.into_bytes()
    }

    #[test]
    fn reserved_profile_idc_is_rejected() {
        // §A.1 — profile_idc values not enumerated in §A.2 are
        // reserved. Regression for two fuzz-oracle divergences:
        //   crash-1b2aaf6f54f92df08bf67802c970555c02de3b4e (profile_idc=251)
        //   crash-181e9dea7dfa8fcb2c9721a3f9f044214af6167b (profile_idc=243)
        // common H.264 decoders reject these; we used to accept and emit a
        // mis-decoded frame.
        for bad in [243u8, 251u8, 1u8, 200u8, 0u8] {
            // Build a Baseline-shaped SPS but with the bad profile_idc.
            let mut w = BitWriter::new();
            w.u(8, bad as u32);
            w.u(8, 0); // cs flags + reserved
            w.u(8, 30); // level_idc
            w.ue(0); // seq_parameter_set_id
            w.ue(0); // log2_max_frame_num_minus4
            w.ue(0); // pic_order_cnt_type
            w.ue(0); // log2_max_pic_order_cnt_lsb_minus4
            w.ue(1); // max_num_ref_frames
            w.u(1, 0);
            w.ue(0);
            w.ue(0);
            w.u(1, 1);
            w.u(1, 1);
            w.u(1, 0);
            w.u(1, 0);
            w.trailing();
            let bytes = w.into_bytes();
            let err = Sps::parse(&bytes).unwrap_err();
            assert!(
                matches!(err, SpsError::ProfileIdcReserved(p) if p == bad),
                "profile_idc={bad} → expected ProfileIdcReserved, got {err:?}"
            );
        }
    }

    #[test]
    fn all_annex_a_profile_idcs_accepted() {
        // Smoke-check that every Annex A.2 profile_idc still parses
        // (Baseline-shaped body — the chroma-extended profiles read
        // four extra ue(v)/u(1) fields that we add here for them).
        for good in [
            66u8, 77, 88, 100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134, 135,
        ] {
            let mut w = BitWriter::new();
            w.u(8, good as u32);
            w.u(8, 0);
            w.u(8, 30);
            w.ue(0); // sps_id
                     // Chroma-extended profile gate.
            if matches!(
                good,
                100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
            ) {
                w.ue(1); // chroma_format_idc=1
                w.ue(0); // bit_depth_luma_minus8
                w.ue(0); // bit_depth_chroma_minus8
                w.u(1, 0); // qpprime_y_zero_transform_bypass_flag
                w.u(1, 0); // seq_scaling_matrix_present_flag
            }
            w.ue(0); // log2_max_frame_num_minus4
            w.ue(0); // pic_order_cnt_type
            w.ue(0); // log2_max_pic_order_cnt_lsb_minus4
            w.ue(1); // max_num_ref_frames
            w.u(1, 0);
            w.ue(0);
            w.ue(0);
            w.u(1, 1);
            w.u(1, 1);
            w.u(1, 0);
            w.u(1, 0);
            w.trailing();
            let bytes = w.into_bytes();
            let sps = Sps::parse(&bytes).unwrap_or_else(|e| panic!("profile_idc={good}: {e:?}"));
            assert_eq!(sps.profile_idc, good);
        }
    }

    #[test]
    fn baseline_sps_320x240_level_30() {
        // 320x240 → 20 MBs wide, 15 MBs tall.
        let bytes = build_baseline_sps(30, 20, 15, /*with_vui=*/ false);
        let sps = Sps::parse(&bytes).unwrap();
        assert_eq!(sps.profile_idc, 66);
        assert_eq!(sps.constraint_set_flags, 0);
        assert_eq!(sps.level_idc, 30);
        assert_eq!(sps.seq_parameter_set_id, 0);
        // Profile 66 is not in the chroma-extended set, so these are
        // the §7.4.2.1.1 inferred defaults.
        assert_eq!(sps.chroma_format_idc, 1);
        assert!(!sps.separate_colour_plane_flag);
        assert_eq!(sps.bit_depth_luma_minus8, 0);
        assert_eq!(sps.bit_depth_chroma_minus8, 0);
        assert!(!sps.seq_scaling_matrix_present_flag);
        assert_eq!(sps.log2_max_frame_num_minus4, 0);
        assert_eq!(sps.pic_order_cnt_type, 0);
        assert_eq!(sps.log2_max_pic_order_cnt_lsb_minus4, 0);
        assert_eq!(sps.max_num_ref_frames, 1);
        assert!(!sps.gaps_in_frame_num_value_allowed_flag);
        assert_eq!(sps.pic_width_in_mbs_minus1, 19);
        assert_eq!(sps.pic_height_in_map_units_minus1, 14);
        assert!(sps.frame_mbs_only_flag);
        assert!(!sps.mb_adaptive_frame_field_flag);
        assert!(sps.direct_8x8_inference_flag);
        assert!(sps.frame_cropping.is_none());
        assert!(!sps.vui_parameters_present_flag);

        // Derived helpers.
        assert_eq!(sps.pic_width_in_mbs(), 20);
        assert_eq!(sps.pic_height_in_map_units(), 15);
        assert_eq!(sps.frame_height_in_mbs(), 15);
        assert_eq!(sps.max_frame_num(), 16);
        assert_eq!(sps.chroma_array_type(), 1);
    }

    #[test]
    fn main_profile_sps_poc_type_1() {
        // profile_idc=77 (Main); pic_order_cnt_type=1 with a short cycle.
        let mut w = BitWriter::new();
        w.u(8, 77); // profile_idc
                    // constraint_set0_flag=1, rest=0; reserved_zero_2bits=0.
        w.u(1, 1);
        for _ in 0..5 {
            w.u(1, 0);
        }
        w.u(2, 0);
        w.u(8, 40); // level_idc=40
        w.ue(3); // seq_parameter_set_id=3
        w.ue(4); // log2_max_frame_num_minus4=4
        w.ue(1); // pic_order_cnt_type=1
        w.u(1, 0); // delta_pic_order_always_zero_flag=0
        w.se(-2); // offset_for_non_ref_pic
        w.se(1); // offset_for_top_to_bottom_field
        w.ue(2); // num_ref_frames_in_pic_order_cnt_cycle
        w.se(5);
        w.se(-7);
        w.ue(4); // max_num_ref_frames
        w.u(1, 1); // gaps_in_frame_num_value_allowed_flag
        w.ue(39); // 640px → 40 MBs wide → minus1 = 39
        w.ue(29); // 480px → 30 MBs tall (frame) → minus1 = 29
        w.u(1, 1); // frame_mbs_only_flag
        w.u(1, 0); // direct_8x8_inference_flag
        w.u(1, 0); // frame_cropping_flag
        w.u(1, 0); // vui_parameters_present_flag
        w.trailing();
        let bytes = w.into_bytes();

        let sps = Sps::parse(&bytes).unwrap();
        assert_eq!(sps.profile_idc, 77);
        assert_eq!(sps.constraint_set_flags, 0b0000_0001);
        assert_eq!(sps.level_idc, 40);
        assert_eq!(sps.seq_parameter_set_id, 3);
        // Profile 77 not in chroma-extended set.
        assert_eq!(sps.chroma_format_idc, 1);
        assert_eq!(sps.log2_max_frame_num_minus4, 4);
        assert_eq!(sps.pic_order_cnt_type, 1);
        assert!(!sps.delta_pic_order_always_zero_flag);
        assert_eq!(sps.offset_for_non_ref_pic, -2);
        assert_eq!(sps.offset_for_top_to_bottom_field, 1);
        assert_eq!(sps.num_ref_frames_in_pic_order_cnt_cycle, 2);
        assert_eq!(sps.offset_for_ref_frame, vec![5, -7]);
        assert_eq!(sps.max_num_ref_frames, 4);
        assert!(sps.gaps_in_frame_num_value_allowed_flag);
        assert_eq!(sps.pic_width_in_mbs_minus1, 39);
        assert_eq!(sps.pic_height_in_map_units_minus1, 29);
        assert!(sps.frame_mbs_only_flag);
        assert!(!sps.direct_8x8_inference_flag);
        assert!(sps.frame_cropping.is_none());
        assert!(!sps.vui_parameters_present_flag);
    }

    #[test]
    fn high_profile_sps_includes_chroma_fields() {
        // profile_idc=100 (High) triggers the chroma_format_idc /
        // bit_depth_*_minus8 / qpprime / seq_scaling_matrix_present_flag
        // group. Use 4:2:0 (idc=1), 8-bit, no scaling matrix.
        let mut w = BitWriter::new();
        w.u(8, 100); // profile_idc=High
                     // Baseline had cs* flags 0; here set cs3_flag to 1.
        w.u(1, 0);
        w.u(1, 0);
        w.u(1, 0);
        w.u(1, 1);
        w.u(1, 0);
        w.u(1, 0);
        w.u(2, 0); // reserved
        w.u(8, 41); // level_idc
        w.ue(0); // seq_parameter_set_id
        w.ue(1); // chroma_format_idc=1 (4:2:0)
                 // chroma_format_idc != 3, so no separate_colour_plane_flag.
        w.ue(2); // bit_depth_luma_minus8=2 → 10-bit
        w.ue(2); // bit_depth_chroma_minus8=2
        w.u(1, 0); // qpprime_y_zero_transform_bypass_flag
        w.u(1, 0); // seq_scaling_matrix_present_flag=0
        w.ue(6); // log2_max_frame_num_minus4
        w.ue(2); // pic_order_cnt_type=2 (no extra fields)
        w.ue(5); // max_num_ref_frames
        w.u(1, 0); // gaps_in_frame_num_value_allowed_flag
        w.ue(119); // pic_width_in_mbs_minus1 → 1920px
        w.ue(67); // pic_height_in_map_units_minus1 → 1088px/16=68
        w.u(1, 1); // frame_mbs_only_flag
        w.u(1, 1); // direct_8x8_inference_flag
                   // Frame cropping: crop 0/0/0/8 samples. CropUnitY=2 for 4:2:0 frame_mbs_only=1,
                   // so crop_bottom_offset=4 → 8-sample crop.
        w.u(1, 1); // frame_cropping_flag
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(4);
        w.u(1, 0); // vui_parameters_present_flag
        w.trailing();
        let bytes = w.into_bytes();

        let sps = Sps::parse(&bytes).unwrap();
        assert_eq!(sps.profile_idc, 100);
        assert_eq!(sps.constraint_set_flags, 0b0000_1000);
        assert_eq!(sps.level_idc, 41);
        assert_eq!(sps.chroma_format_idc, 1);
        assert!(!sps.separate_colour_plane_flag);
        assert_eq!(sps.bit_depth_luma_minus8, 2);
        assert_eq!(sps.bit_depth_chroma_minus8, 2);
        assert!(!sps.qpprime_y_zero_transform_bypass_flag);
        assert!(!sps.seq_scaling_matrix_present_flag);
        assert_eq!(sps.log2_max_frame_num_minus4, 6);
        assert_eq!(sps.pic_order_cnt_type, 2);
        // POC type 2 → no offset_for_* arrays.
        assert!(sps.offset_for_ref_frame.is_empty());
        assert_eq!(sps.max_num_ref_frames, 5);
        assert_eq!(sps.pic_width_in_mbs_minus1, 119);
        assert_eq!(sps.pic_height_in_map_units_minus1, 67);
        assert!(sps.direct_8x8_inference_flag);
        let crop = sps.frame_cropping.clone().expect("frame cropping");
        assert_eq!(crop.left, 0);
        assert_eq!(crop.right, 0);
        assert_eq!(crop.top, 0);
        assert_eq!(crop.bottom, 4);
        assert!(!sps.vui_parameters_present_flag);
    }

    #[test]
    fn vui_present_parses_empty_body() {
        // SPS with vui_parameters_present_flag == 1 and an "all zeros"
        // VUI body — every per-section present-flag is 0, so the VUI
        // body fits in 9 bits (§E.1).
        let mut w = BitWriter::new();
        w.u(8, 66);
        w.u(8, 0);
        w.u(8, 30);
        w.ue(0); // sps_id
        w.ue(0); // log2_max_frame_num_minus4
        w.ue(0); // pic_order_cnt_type
        w.ue(0); // log2_max_pic_order_cnt_lsb_minus4
        w.ue(1); // max_num_ref_frames
        w.u(1, 0); // gaps
        w.ue(10); // width
        w.ue(10); // height
        w.u(1, 1); // frame_mbs_only
        w.u(1, 1); // direct_8x8
        w.u(1, 0); // no crop
        w.u(1, 1); // vui_parameters_present_flag = 1
                   // Empty VUI — 9 flags, all 0.
        for _ in 0..9 {
            w.u(1, 0);
        }
        w.trailing();
        let bytes = w.into_bytes();

        let sps = Sps::parse(&bytes).unwrap();
        assert!(sps.vui_parameters_present_flag);
        let vui = sps.vui.as_ref().expect("VUI parsed");
        assert!(vui.aspect_ratio.is_none());
        assert!(vui.timing_info.is_none());
        assert!(vui.bitstream_restriction.is_none());
        assert_eq!(sps.pic_width_in_mbs_minus1, 10);
    }

    #[test]
    fn reserved_zero_2bits_nonzero_is_rejected() {
        let mut w = BitWriter::new();
        w.u(8, 66); // profile_idc
        w.u(6, 0); // constraint_set0..5_flag
        w.u(2, 0b01); // reserved_zero_2bits *not* zero
        w.u(8, 30);
        let bytes = w.into_bytes();
        assert_eq!(
            Sps::parse(&bytes).unwrap_err(),
            SpsError::ReservedNotZero(0b01)
        );
    }

    #[test]
    fn scaling_matrix_present_parses_all_not_present() {
        // seq_scaling_matrix_present_flag=1 but every
        // seq_scaling_list_present_flag[i] is 0 → the parser consumes
        // 8 flag bits (chroma_format_idc != 3) and yields a
        // `SeqScalingLists` of 8 `NotPresent` entries.
        let mut w = BitWriter::new();
        w.u(8, 100); // High profile
        w.u(8, 0);
        w.u(8, 40);
        w.ue(0); // sps_id
        w.ue(1); // chroma_format_idc=1
        w.ue(0); // bit_depth_luma
        w.ue(0); // bit_depth_chroma
        w.u(1, 0); // qpprime_y_zero
        w.u(1, 1); // seq_scaling_matrix_present_flag=1
        for _ in 0..8 {
            w.u(1, 0); // seq_scaling_list_present_flag[i] = 0
        }
        w.ue(0); // log2_max_frame_num_minus4
        w.ue(0); // pic_order_cnt_type
        w.ue(0); // log2_max_poc_lsb_minus4
        w.ue(1); // max_num_ref_frames
        w.u(1, 0); // gaps
        w.ue(19); // pic_width_in_mbs_minus1
        w.ue(14); // pic_height_in_map_units_minus1
        w.u(1, 1); // frame_mbs_only
        w.u(1, 1); // direct_8x8
        w.u(1, 0); // frame_cropping=0
        w.u(1, 0); // vui_parameters_present_flag=0
        w.trailing();
        let bytes = w.into_bytes();

        let sps = Sps::parse(&bytes).unwrap();
        assert!(sps.seq_scaling_matrix_present_flag);
        let lists = sps
            .seq_scaling_lists
            .as_ref()
            .expect("scaling lists parsed");
        assert_eq!(lists.entries.len(), 8);
        for e in &lists.entries {
            assert_eq!(*e, ScalingListEntry::NotPresent);
        }
    }

    #[test]
    fn scaling_matrix_explicit_list_is_parsed() {
        // seq_scaling_matrix_present_flag=1 with entry[0] explicit
        // (all delta_scale = 0 → all 16 entries equal 8, per §7.3.2.1.1.1
        // with lastScale / nextScale seeded at 8 and delta_scale=0 each).
        // Remaining 7 lists NotPresent.
        let mut w = BitWriter::new();
        w.u(8, 100);
        w.u(8, 0);
        w.u(8, 40);
        w.ue(0);
        w.ue(1); // chroma_format_idc
        w.ue(0);
        w.ue(0);
        w.u(1, 0);
        w.u(1, 1); // seq_scaling_matrix_present_flag
        w.u(1, 1); // seq_scaling_list_present_flag[0] = 1
        for _ in 0..16 {
            w.se(0); // delta_scale = 0
        }
        for _ in 0..7 {
            w.u(1, 0); // rest NotPresent
        }
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(1);
        w.u(1, 0);
        w.ue(19);
        w.ue(14);
        w.u(1, 1);
        w.u(1, 1);
        w.u(1, 0);
        w.u(1, 0);
        w.trailing();
        let bytes = w.into_bytes();

        let sps = Sps::parse(&bytes).unwrap();
        let lists = sps.seq_scaling_lists.as_ref().unwrap();
        match &lists.entries[0] {
            ScalingListEntry::Explicit(vals) => {
                assert_eq!(vals.len(), 16);
                for v in vals {
                    assert_eq!(*v, 8);
                }
            }
            other => panic!("expected Explicit, got {:?}", other),
        }
        for i in 1..8 {
            assert_eq!(lists.entries[i], ScalingListEntry::NotPresent);
        }
    }

    #[test]
    fn interlaced_sps_reads_mbaff_flag() {
        let mut w = BitWriter::new();
        w.u(8, 77); // Main
        w.u(8, 0);
        w.u(8, 30);
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(1);
        w.u(1, 0);
        w.ue(10);
        w.ue(10);
        w.u(1, 0); // frame_mbs_only_flag=0
        w.u(1, 1); // mb_adaptive_frame_field_flag=1
        w.u(1, 1); // direct_8x8_inference_flag
        w.u(1, 0); // frame_cropping_flag
        w.u(1, 0); // vui
        w.trailing();
        let bytes = w.into_bytes();

        let sps = Sps::parse(&bytes).unwrap();
        assert!(!sps.frame_mbs_only_flag);
        assert!(sps.mb_adaptive_frame_field_flag);
        // FrameHeightInMbs = 2 * (pic_height_in_map_units_minus1 + 1).
        assert_eq!(sps.frame_height_in_mbs(), 22);

        // §7.4.2.1.1 eq. (7-26) — a field picture is half the frame
        // height in MBs; a frame-coded picture keeps the full height.
        assert_eq!(sps.pic_height_in_mbs(false), 22);
        assert_eq!(sps.pic_height_in_mbs(true), 11);
        // eq. (7-25/7-27) PicSizeInMbs = PicWidthInMbs * PicHeightInMbs.
        // PicWidthInMbs = pic_width_in_mbs_minus1 + 1 = 11.
        assert_eq!(sps.pic_width_in_mbs(), 11);
        assert_eq!(sps.pic_size_in_mbs(false), 11 * 22);
        assert_eq!(sps.pic_size_in_mbs(true), 11 * 11);
    }

    #[test]
    fn pic_height_in_mbs_progressive_equals_frame_height() {
        // frame_mbs_only_flag == 1: field_pic_flag is always 0, so
        // PicHeightInMbs == FrameHeightInMbs regardless of the argument
        // (a conformant stream never sets field_pic_flag here).
        let mut w = BitWriter::new();
        w.u(8, 66);
        w.u(8, 0);
        w.u(8, 30);
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(1);
        w.u(1, 0);
        w.ue(7); // pic_width_in_mbs_minus1 → 8
        w.ue(5); // pic_height_in_map_units_minus1 → 6
        w.u(1, 1); // frame_mbs_only_flag = 1
        w.u(1, 1); // direct_8x8_inference_flag
        w.u(1, 0); // frame_cropping_flag
        w.u(1, 0); // vui
        w.trailing();
        let sps = Sps::parse(&w.into_bytes()).unwrap();
        assert_eq!(sps.frame_height_in_mbs(), 6);
        assert_eq!(sps.pic_height_in_mbs(false), 6);
        assert_eq!(sps.pic_size_in_mbs(false), 8 * 6);
    }

    #[test]
    fn separate_colour_plane_sets_chroma_array_type_zero() {
        let mut w = BitWriter::new();
        w.u(8, 244); // High 4:4:4 Intra — in chroma-extended set
        w.u(8, 0);
        w.u(8, 40);
        w.ue(0);
        w.ue(3); // chroma_format_idc=3 (4:4:4)
        w.u(1, 1); // separate_colour_plane_flag=1
        w.ue(0); // bit_depth_luma_minus8
        w.ue(0); // bit_depth_chroma_minus8
        w.u(1, 0); // qpprime
        w.u(1, 0); // no scaling matrix
        w.ue(0); // log2_max_frame_num_minus4
        w.ue(2); // pic_order_cnt_type=2
        w.ue(1);
        w.u(1, 0);
        w.ue(9);
        w.ue(9);
        w.u(1, 1);
        w.u(1, 1);
        w.u(1, 0);
        w.u(1, 0);
        w.trailing();
        let bytes = w.into_bytes();

        let sps = Sps::parse(&bytes).unwrap();
        assert_eq!(sps.chroma_format_idc, 3);
        assert!(sps.separate_colour_plane_flag);
        assert_eq!(sps.chroma_array_type(), 0);
    }

    #[test]
    fn pic_width_in_mbs_oversize_rejected() {
        // Build an SPS where pic_width_in_mbs_minus1 = 2^31 - 1 (a value
        // an attacker can produce via oversized ue(v) but real streams
        // never come close to). Without the bound check, downstream code
        // multiplies width_in_mbs * 16 and panics with `attempt to
        // multiply with overflow`.
        let mut w = BitWriter::new();
        w.u(8, 66); // profile_idc Baseline
        w.u(8, 0); // constraint_setN + reserved
        w.u(8, 30); // level_idc
        w.ue(0); // sps_id
        w.ue(0); // log2_max_frame_num_minus4
        w.ue(0); // pic_order_cnt_type
        w.ue(0); // log2_max_pic_order_cnt_lsb_minus4
        w.ue(1); // max_num_ref_frames
        w.u(1, 0); // gaps_in_frame_num_value_allowed_flag
        w.ue(MAX_PIC_DIM_IN_MBS_MINUS1 + 1); // pic_width_in_mbs_minus1 (just past cap)
        let err = Sps::parse(&w.into_bytes()).unwrap_err();
        assert_eq!(
            err,
            SpsError::PicWidthInMbsOutOfRange(MAX_PIC_DIM_IN_MBS_MINUS1 + 1)
        );
    }

    #[test]
    fn pic_height_in_map_units_oversize_rejected() {
        let mut w = BitWriter::new();
        w.u(8, 66);
        w.u(8, 0);
        w.u(8, 30);
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(1);
        w.u(1, 0);
        w.ue(0); // pic_width_in_mbs_minus1 OK
        w.ue(MAX_PIC_DIM_IN_MBS_MINUS1 + 17); // pic_height_in_map_units_minus1 oversize
        let err = Sps::parse(&w.into_bytes()).unwrap_err();
        assert_eq!(
            err,
            SpsError::PicHeightInMapUnitsOutOfRange(MAX_PIC_DIM_IN_MBS_MINUS1 + 17)
        );
    }

    /// §7.4.2.1.1 / Annex A.3.1 — `max_num_ref_frames` is bounded by
    /// MaxDpbFrames which is `Min(MaxDpbMbs / PicSizeInMbs, 16)`, so
    /// the absolute upper bound is 16 regardless of level. ffmpeg
    /// rejects with "too many reference frames" for values above 16;
    /// matching this strictness closes a fuzz-oracle divergence
    /// (regression for `crash-f9387b9697e640efbd689a9909ff59deaaf32864`).
    #[test]
    fn max_num_ref_frames_above_16_rejected() {
        let mut w = BitWriter::new();
        w.u(8, 66); // profile_idc Baseline
        w.u(8, 0);
        w.u(8, 30); // level_idc
        w.ue(0); // sps_id
        w.ue(0); // log2_max_frame_num_minus4
        w.ue(0); // pic_order_cnt_type
        w.ue(0); // log2_max_pic_order_cnt_lsb_minus4
        w.ue(17); // max_num_ref_frames = 17 — above MaxDpbFrames cap.
        let err = Sps::parse(&w.into_bytes()).unwrap_err();
        assert_eq!(err, SpsError::MaxNumRefFramesOutOfRange(17));
    }

    #[test]
    fn max_num_ref_frames_at_16_accepted() {
        let mut w = BitWriter::new();
        w.u(8, 66);
        w.u(8, 0);
        w.u(8, 30);
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(16); // exactly 16 — last legal value
        w.u(1, 0); // gaps_in_frame_num_value_allowed_flag
        w.ue(19); // pic_width_in_mbs_minus1 → 20 MBs
        w.ue(14); // pic_height_in_map_units_minus1 → 15 map units
        w.u(1, 1); // frame_mbs_only_flag
        w.u(1, 0); // direct_8x8_inference_flag
        w.u(1, 0); // frame_cropping_flag
        w.u(1, 0); // vui_parameters_present_flag
        w.trailing();
        let sps = Sps::parse(&w.into_bytes()).unwrap();
        assert_eq!(sps.max_num_ref_frames, 16);
    }

    /// §7.4.2.1.1 — a `frame_cropping_flag = 1` SPS whose offsets
    /// would crop more samples than the coded picture contains must
    /// be rejected at SPS parse time. The libfuzzer crash
    /// `8e8b38ae…` (round-91 fuzz oracle) was a 4:2:0 / `frame_mbs_only_flag = 1`
    /// SPS with `pic_width_in_mbs_minus1 = 177` (PicWidthInSamplesL =
    /// 2848), `pic_height_in_map_units_minus1 = 0` (FrameHeightInSamplesL =
    /// 16), and `top_offset = 2148` — CropUnitY = 2 × 1 = 2, so
    /// `2 × (2148 + 2 + 1) = 4302 > 16` overflows the frame height.
    /// common H.264 decoders reject with "crop values invalid"; we mirror.
    #[test]
    fn frame_cropping_offsets_exceeding_picture_rejected() {
        let mut w = BitWriter::new();
        w.u(8, 66); // profile_idc Baseline (no chroma_format_idc parse)
        w.u(8, 0);
        w.u(8, 30); // level_idc
        w.ue(0); // sps_id
        w.ue(0); // log2_max_frame_num_minus4
        w.ue(0); // pic_order_cnt_type
        w.ue(0); // log2_max_pic_order_cnt_lsb_minus4
        w.ue(1); // max_num_ref_frames
        w.u(1, 0); // gaps_in_frame_num_value_allowed_flag
        w.ue(0); // pic_width_in_mbs_minus1 = 0 → PicWidthInSamplesL = 16
        w.ue(0); // pic_height_in_map_units_minus1 = 0 → FrameHeightInSamplesL = 16
        w.u(1, 1); // frame_mbs_only_flag
        w.u(1, 0); // direct_8x8_inference_flag
        w.u(1, 1); // frame_cropping_flag = 1
                   // 4:2:0 (inferred), frame_mbs_only=1 → CropUnitX=2, CropUnitY=2.
                   // top=0, bottom=10 → 2 × (0 + 10 + 1) = 22 > 16.
        w.ue(0); // left
        w.ue(0); // right
        w.ue(0); // top
        w.ue(10); // bottom — overshoots
        let err = Sps::parse(&w.into_bytes()).unwrap_err();
        match err {
            SpsError::FrameCroppingOutOfRange {
                cux,
                cuy,
                left,
                right,
                top,
                bottom,
                width,
                height,
            } => {
                assert_eq!(cux, 2);
                assert_eq!(cuy, 2);
                assert_eq!(left, 0);
                assert_eq!(right, 0);
                assert_eq!(top, 0);
                assert_eq!(bottom, 10);
                assert_eq!(width, 16);
                assert_eq!(height, 16);
            }
            other => panic!("expected FrameCroppingOutOfRange, got {other:?}"),
        }
    }

    /// Boundary case: cropping that exactly fills the picture (cropped
    /// width / height = 1 sample each) must be accepted. The spec
    /// requires `left + right + 1 ≤ PicWidthInSamplesL / CropUnitX`,
    /// so the worst-permitted offsets satisfy the inequality at
    /// equality.
    #[test]
    fn frame_cropping_at_maximal_allowed_offsets_accepted() {
        let mut w = BitWriter::new();
        w.u(8, 66);
        w.u(8, 0);
        w.u(8, 30);
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(0);
        w.ue(1);
        w.u(1, 0);
        w.ue(0); // pic_width_in_mbs_minus1 = 0 → 16 samples wide
        w.ue(0); // pic_height_in_map_units_minus1 = 0 → 16 samples tall
        w.u(1, 1); // frame_mbs_only_flag
        w.u(1, 0); // direct_8x8_inference_flag
        w.u(1, 1); // frame_cropping_flag = 1
                   // 4:2:0 frame_mbs_only=1: CropUnitX=2, CropUnitY=2.
                   // Max bottom = (16/2) - (0 + 1) = 7 → 2 × (0+7+1) = 16 ≤ 16.
        w.ue(0); // left
        w.ue(0); // right
        w.ue(0); // top
        w.ue(7); // bottom = 7 → CropUnitY * (top + bottom + 1) = 16
        w.u(1, 0); // vui_parameters_present_flag
        w.trailing();
        let sps = Sps::parse(&w.into_bytes()).unwrap();
        let c = sps.frame_cropping.unwrap();
        assert_eq!((c.left, c.right, c.top, c.bottom), (0, 0, 0, 7));
    }
}