transmux 0.29.1

Any-to-any media container muxing hub: demux TS, fMP4/CMAF, MPEG-PS, WebM, FLV, or RTMP into one neutral IR and mux to CMAF/fMP4, progressive MP4, TS, DASH, low-latency DASH, HLS, low-latency HLS, Smooth Streaming, or RTMP. CENC/CBCS encrypt+decrypt, SSAI splice, RTP/RTCP, and an fMP4/CMAF conformance validator; parses codec config headers only, samples stay opaque. no_std + alloc, except the XML manifest paths (DASH/Smooth/PlayReady), which need the std feature.
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
//! Display geometry of a video track: what a player needs to show each
//! picture at its correct shape.
//!
//! Phases 1a and 1b of `docs/display-geometry/DESIGN.md`: the **sample aspect
//! ratio** (SAR) signalled in the SPS VUI, the coded picture size, and the
//! **video signal type / colour description** (video format, full range and
//! the colour primaries / transfer characteristics / matrix coefficients),
//! derived once per track into [`TrackSpec::display`](super::TrackSpec::display).
//! **Phase 2** adds the change model: [`DisplayInfo`] (the displayed state of
//! one access unit), [`DisplayChangeSet`] (which parts of it changed) and
//! [`DisplayInfo::changes_from`], which compares parsed geometry by value,
//! never by the parameter-set bytes it arrived in. Cropping is a later phase
//! (every type here is `#[non_exhaustive]`, so it lands additively).
//!
//! # Spec citations
//!
//! - **H.264**: ITU-T H.264 (V15, 08/2024) §E.1.1 (`vui_parameters()` syntax),
//!   §E.2.1 Table E-1 (meaning of `aspect_ratio_idc`), Table E-2
//!   (`video_format`), Table E-3 (`colour_primaries`), Table E-4
//!   (`transfer_characteristics`) and Table E-5 (`matrix_coefficients`).
//! - **H.265**: ITU-T H.265 (V11, 01/2026) §E.2.1 (syntax) and §E.3.1
//!   Tables E.1 (same values as Table E-1), E.2, E.3, E.4 and E.5.
//!
//! Every table was re-verified row by row against the rendered PDF pages and
//! is transcribed in `docs/codec/vui-colour-tables.md` (see also
//! `docs/display-geometry/SPEC-NOTES.md`), not read from the markdown text,
//! whose Table E-1 rows are merged and whose Tables E-3..E-5 lost their
//! column structure.
//!
//! # Semantics kept exactly
//!
//! - `aspect_ratio_idc` absent (no VUI, or `aspect_ratio_info_present_flag`
//!   0) is inferred 0 (unspecified): [`DisplayGeometry::aspect_ratio`] is
//!   `None`.
//! - "When `aspect_ratio_idc` is equal to 0 or `sar_width` is equal to 0 or
//!   `sar_height` is equal to 0, the sample aspect ratio shall be considered
//!   unspecified": [`AspectRatioIdc::sample_aspect_ratio`] is `None`, never a
//!   `0:0` sentinel.
//! - H.265 §E.3.1: values 17..=254 are reserved and "decoders shall interpret"
//!   them "as equivalent to the value 0". H.264 marks the same range reserved
//!   without that sentence; this crate applies the H.265 rule to both.
//! - Two broadcasters code a 720x576 16:9 picture as `16:11` (idc 4, Table
//!   E-1 NOTE 1: horizontal overscan) and as `64:45` (Extended_SAR). Both are
//!   legitimate and are kept exactly as signalled, never normalised to each
//!   other.

use crate::error::Result;
use crate::ir::CodecConfig;
use core::num::NonZeroU16;

/// `aspect_ratio_idc` value that selects `sar_width` / `sar_height`
/// (H.264 Table E-1 `Extended_SAR`; H.265 Table E.1 `EXTENDED_SAR`).
pub const EXTENDED_SAR_IDC: u8 = 255;

/// First reserved `aspect_ratio_idc` (H.264 Table E-1 / H.265 Table E.1:
/// "17..254 Reserved").
const FIRST_RESERVED_IDC: u8 = 17;

/// H.264 Table E-1 / H.265 Table E.1 `aspect_ratio_idc`, the wire form kept
/// losslessly ([`idc`](Self::idc) returns the wire byte).
///
/// The SAR rows are named for their ratio (`Sar16x11` = `16:11`).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AspectRatioIdc {
    /// 0: unspecified.
    Unspecified,
    /// 1: `1:1` ("square").
    Square,
    /// 2: `12:11`.
    Sar12x11,
    /// 3: `10:11`.
    Sar10x11,
    /// 4: `16:11`.
    Sar16x11,
    /// 5: `40:33`.
    Sar40x33,
    /// 6: `24:11`.
    Sar24x11,
    /// 7: `20:11`.
    Sar20x11,
    /// 8: `32:11`.
    Sar32x11,
    /// 9: `80:33`.
    Sar80x33,
    /// 10: `18:11`.
    Sar18x11,
    /// 11: `15:11`.
    Sar15x11,
    /// 12: `64:33`.
    Sar64x33,
    /// 13: `160:99`.
    Sar160x99,
    /// 14: `4:3`.
    Sar4x3,
    /// 15: `3:2`.
    Sar3x2,
    /// 16: `2:1`.
    Sar2x1,
    /// 17..=254: reserved (wire value kept).
    Reserved(u8),
    /// 255: `Extended_SAR`, with the explicit `sar_width` / `sar_height`
    /// exactly as signalled (either may be 0, which means unspecified).
    ExtendedSar {
        /// `sar_width`, `u(16)`.
        sar_width: u16,
        /// `sar_height`, `u(16)`.
        sar_height: u16,
    },
}

/// (idc, SAR width, SAR height) for the Table E-1 rows 1..=16, in idc order.
/// The single copy of the table: [`AspectRatioIdc::from_wire`],
/// [`AspectRatioIdc::idc`] and [`AspectRatioIdc::sample_aspect_ratio`] all
/// read it, so they cannot disagree.
const TABLE_E1: [(AspectRatioIdc, u16, u16); 16] = [
    (AspectRatioIdc::Square, 1, 1),
    (AspectRatioIdc::Sar12x11, 12, 11),
    (AspectRatioIdc::Sar10x11, 10, 11),
    (AspectRatioIdc::Sar16x11, 16, 11),
    (AspectRatioIdc::Sar40x33, 40, 33),
    (AspectRatioIdc::Sar24x11, 24, 11),
    (AspectRatioIdc::Sar20x11, 20, 11),
    (AspectRatioIdc::Sar32x11, 32, 11),
    (AspectRatioIdc::Sar80x33, 80, 33),
    (AspectRatioIdc::Sar18x11, 18, 11),
    (AspectRatioIdc::Sar15x11, 15, 11),
    (AspectRatioIdc::Sar64x33, 64, 33),
    (AspectRatioIdc::Sar160x99, 160, 99),
    (AspectRatioIdc::Sar4x3, 4, 3),
    (AspectRatioIdc::Sar3x2, 3, 2),
    (AspectRatioIdc::Sar2x1, 2, 1),
];

impl AspectRatioIdc {
    /// Build from the wire `aspect_ratio_idc` and, when it is
    /// [`EXTENDED_SAR_IDC`], the `(sar_width, sar_height)` that follow it.
    /// `extended` is ignored for every other idc.
    ///
    /// An Extended_SAR idc with no `extended` pair is stored as `0:0`
    /// (unspecified), not invented.
    pub fn from_wire(idc: u8, extended: Option<(u16, u16)>) -> Self {
        match idc {
            0 => Self::Unspecified,
            EXTENDED_SAR_IDC => {
                let (sar_width, sar_height) = extended.unwrap_or((0, 0));
                Self::ExtendedSar {
                    sar_width,
                    sar_height,
                }
            }
            FIRST_RESERVED_IDC..=254 => Self::Reserved(idc),
            // 1..=16: `TABLE_E1[idc - 1]`, indexed by construction (the arms
            // above removed 0, 17..=254 and 255).
            _ => TABLE_E1[usize::from(idc) - 1].0,
        }
    }

    /// The wire `aspect_ratio_idc` value (the inverse of
    /// [`from_wire`](Self::from_wire)).
    pub fn idc(&self) -> u8 {
        match self {
            Self::Unspecified => 0,
            Self::Reserved(idc) => *idc,
            Self::ExtendedSar { .. } => EXTENDED_SAR_IDC,
            table_row => TABLE_E1
                .iter()
                .zip(1u8..)
                .find_map(|((row, _, _), idc)| (row == table_row).then_some(idc))
                // Unreachable: every variant not matched above is a table row.
                .unwrap_or(0),
        }
    }

    /// The specified sample aspect ratio, or `None` when it is unspecified:
    /// idc 0, the reserved range 17..=254 (H.265 §E.3.1 "interpret as 0",
    /// applied to both codecs), or Extended_SAR with a zero component.
    pub fn sample_aspect_ratio(&self) -> Option<SampleAspectRatio> {
        match self {
            Self::Unspecified | Self::Reserved(_) => None,
            Self::ExtendedSar {
                sar_width,
                sar_height,
            } => SampleAspectRatio::new(*sar_width, *sar_height),
            table_row => TABLE_E1
                .iter()
                .find(|(row, _, _)| row == table_row)
                .and_then(|(_, w, h)| SampleAspectRatio::new(*w, *h)),
        }
    }

    /// Label: the spec token (`"16:11"`, `"Extended_SAR"`), `"unspecified"` for
    /// idc 0, `"reserved"` for 17..=254.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Unspecified => "unspecified",
            Self::Square => "1:1",
            Self::Sar12x11 => "12:11",
            Self::Sar10x11 => "10:11",
            Self::Sar16x11 => "16:11",
            Self::Sar40x33 => "40:33",
            Self::Sar24x11 => "24:11",
            Self::Sar20x11 => "20:11",
            Self::Sar32x11 => "32:11",
            Self::Sar80x33 => "80:33",
            Self::Sar18x11 => "18:11",
            Self::Sar15x11 => "15:11",
            Self::Sar64x33 => "64:33",
            Self::Sar160x99 => "160:99",
            Self::Sar4x3 => "4:3",
            Self::Sar3x2 => "3:2",
            Self::Sar2x1 => "2:1",
            Self::Reserved(_) => "reserved",
            Self::ExtendedSar { .. } => "Extended_SAR",
        }
    }
}

broadcast_common::impl_spec_display!(AspectRatioIdc, Reserved);

/// A *specified* sample (pixel) aspect ratio: both terms non-zero. Unspecified
/// is `Option::None` at every use site, never a `0:0` sentinel.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SampleAspectRatio {
    width: NonZeroU16,
    height: NonZeroU16,
}

impl SampleAspectRatio {
    /// `None` when either term is 0 (the spec's "unspecified").
    pub fn new(width: u16, height: u16) -> Option<Self> {
        Some(Self {
            width: NonZeroU16::new(width)?,
            height: NonZeroU16::new(height)?,
        })
    }

    /// Horizontal term (`sar_width`).
    pub fn width(&self) -> u16 {
        self.width.get()
    }

    /// Vertical term (`sar_height`).
    pub fn height(&self) -> u16 {
        self.height.get()
    }

    /// `(width, height)`.
    pub fn as_pair(&self) -> (u16, u16) {
        (self.width(), self.height())
    }

    /// Reduced to lowest terms. The spec requires `sar_width` / `sar_height`
    /// to be relatively prime already; a non-reduced wire pair is kept as
    /// signalled in [`AspectRatioIdc::ExtendedSar`] and only reduced here.
    pub fn reduced(&self) -> Self {
        let (mut a, mut b) = (self.width(), self.height());
        while b != 0 {
            (a, b) = (b, a % b);
        }
        // `a` is the gcd of two non-zero values, so non-zero.
        let g = a.max(1);
        Self {
            width: NonZeroU16::new(self.width() / g).unwrap_or(self.width),
            height: NonZeroU16::new(self.height() / g).unwrap_or(self.height),
        }
    }
}

impl From<SampleAspectRatio> for (u16, u16) {
    fn from(sar: SampleAspectRatio) -> Self {
        sar.as_pair()
    }
}

/// A rectangle in luma samples of the decoded picture, top-left origin.
/// `#[non_exhaustive]`: future fields may be added additively.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PictureRect {
    /// Left offset in luma samples.
    pub left: u32,
    /// Top offset in luma samples.
    pub top: u32,
    /// Width in luma samples.
    pub width: u32,
    /// Height in luma samples.
    pub height: u32,
}

impl PictureRect {
    /// Build a rectangle from its four edges.
    pub fn new(left: u32, top: u32, width: u32, height: u32) -> Self {
        Self {
            left,
            top,
            width,
            height,
        }
    }
}

/// The spec's inferred `video_format` when `video_signal_type_present_flag`
/// is 0 (H.264 §E.2.1: "shall be inferred to be equal to 5").
pub const INFERRED_VIDEO_FORMAT: u8 = 5;

/// The spec's inferred `video_full_range_flag` when absent (H.264 §E.2.1: "= 0").
pub const INFERRED_FULL_RANGE: bool = false;

/// The spec's inferred `colour_primaries` / `transfer_characteristics` /
/// `matrix_coefficients` when absent (H.264 §E.2.1: "= 2", unspecified).
pub const INFERRED_COLOUR_CODE: u8 = 2;

/// The MPEG-2 inferred `colour_primaries` / `transfer_characteristics` /
/// `matrix_coefficients` when `sequence_display_extension()` or its
/// `colour_description` is absent: value 1 in all three, i.e. BT.709
/// (ITU-T H.262 §6.3.6, printed pp. 44/47; `docs/codec/mpeg2-video-display.md`).
/// Distinct from [`INFERRED_COLOUR_CODE`]: MPEG-2 never infers "unspecified".
pub const MPEG2_INFERRED_COLOUR_CODE: u8 = 1;

/// H.264 Table E-2 / H.265 Table E.2 `video_format`, the wire form kept
/// losslessly ([`from_wire`](Self::from_wire) / [`code`](Self::code)).
///
/// The rows 0..=5 are identical in both specs. H.264 defines 6 and 7 as
/// `Reserved` with no interpretation; H.265 additionally says decoders "shall
/// interpret the values 6 and 7 ... as equivalent to the value 5". This crate
/// names neither (H.264's label is only "Reserved"), so both are
/// [`Reserved`](Self::Reserved). Unspecified is row 5.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VideoFormat {
    /// 0: component.
    Component,
    /// 1: PAL.
    Pal,
    /// 2: NTSC.
    Ntsc,
    /// 3: SECAM.
    Secam,
    /// 4: MAC.
    Mac,
    /// 5: unspecified video format.
    Unspecified,
    /// 6 or 7: reserved (wire value kept).
    Reserved(u8),
}

impl VideoFormat {
    /// Decode a 3-bit `video_format` value. `None` for a value the `u(3)`
    /// field cannot carry (so [`code`](Self::code) round-trips every value the
    /// wire can produce). 6 and 7 are [`Reserved`](Self::Reserved).
    pub fn from_wire(code: u8) -> Option<Self> {
        match code {
            0 => Some(Self::Component),
            1 => Some(Self::Pal),
            2 => Some(Self::Ntsc),
            3 => Some(Self::Secam),
            4 => Some(Self::Mac),
            5 => Some(Self::Unspecified),
            6 | 7 => Some(Self::Reserved(code)),
            _ => None,
        }
    }

    /// The wire `video_format` value.
    pub fn code(&self) -> u8 {
        match self {
            Self::Component => 0,
            Self::Pal => 1,
            Self::Ntsc => 2,
            Self::Secam => 3,
            Self::Mac => 4,
            Self::Unspecified => 5,
            Self::Reserved(code) => *code,
        }
    }

    /// Label: the spec's Table E-2 meaning, `"reserved"` for 6/7.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Component => "Component",
            Self::Pal => "PAL",
            Self::Ntsc => "NTSC",
            Self::Secam => "SECAM",
            Self::Mac => "MAC",
            Self::Unspecified => "Unspecified video format",
            Self::Reserved(_) => "reserved",
        }
    }

    /// `video_format` when the VUI omits the field (inferred 5).
    pub fn inferred() -> Self {
        Self::from_wire(INFERRED_VIDEO_FORMAT).unwrap_or(Self::Unspecified)
    }
}

broadcast_common::impl_spec_display!(VideoFormat, Reserved);

/// H.264 Table E-3 / H.265 Table E.3 `colour_primaries` (identical rows in
/// both specs), the wire form kept losslessly.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColourPrimaries {
    /// 0: reserved for future use by ITU-T | ISO/IEC.
    Reserved(u8),
    /// 1: Rec. ITU-R BT.709-6 (also BT.1361-0 conventional gamut, sRGB/sYCC).
    Bt709,
    /// 2: unspecified (image characteristics unknown or determined by the
    /// application).
    Unspecified,
    /// 4: Rec. ITU-R BT.470-7 System M (historical; NTSC 1953).
    Bt470SystemM,
    /// 5: Rec. ITU-R BT.470-7 System B, G (historical; BT.601-7 625).
    Bt470SystemBg,
    /// 6: Rec. ITU-R BT.601-7 525 (functionally the same as row 7).
    Bt601_525,
    /// 7: SMPTE 240M (1999, historical) (functionally the same as row 6).
    Smpte240M,
    /// 8: generic film (colour filters using Illuminant C).
    GenericFilm,
    /// 9: Rec. ITU-R BT.2020-2.
    Bt2020,
    /// 10: SMPTE ST 428-1 (2006) (CIE 1931 XYZ as in ISO 11664-1).
    Xyz,
    /// 11: SMPTE RP 431-2 (2011) (SMPTE ST 2113 (2018) "P3DCI").
    SmpteRp431_2,
    /// 12: SMPTE EG 432-1 (2010) (SMPTE ST 2113 (2018) "P3D65").
    SmpteEg432_1,
    /// 22: EBU Tech. 3213-E (1975).
    EbuTech3213E,
}

impl ColourPrimaries {
    /// Decode a `colour_primaries` value; unnamed rows are reserved.
    pub fn from_wire(code: u8) -> Self {
        match code {
            1 => Self::Bt709,
            2 => Self::Unspecified,
            4 => Self::Bt470SystemM,
            5 => Self::Bt470SystemBg,
            6 => Self::Bt601_525,
            7 => Self::Smpte240M,
            8 => Self::GenericFilm,
            9 => Self::Bt2020,
            10 => Self::Xyz,
            11 => Self::SmpteRp431_2,
            12 => Self::SmpteEg432_1,
            22 => Self::EbuTech3213E,
            other => Self::Reserved(other),
        }
    }

    /// The wire `colour_primaries` value (inverse of
    /// [`from_wire`](Self::from_wire)).
    pub fn code(&self) -> u8 {
        match self {
            Self::Reserved(code) => *code,
            Self::Bt709 => 1,
            Self::Unspecified => 2,
            Self::Bt470SystemM => 4,
            Self::Bt470SystemBg => 5,
            Self::Bt601_525 => 6,
            Self::Smpte240M => 7,
            Self::GenericFilm => 8,
            Self::Bt2020 => 9,
            Self::Xyz => 10,
            Self::SmpteRp431_2 => 11,
            Self::SmpteEg432_1 => 12,
            Self::EbuTech3213E => 22,
        }
    }

    /// Label: the Table E-3 primaries text (without the informative remark),
    /// `"reserved"` for reserved rows.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Reserved(_) => "reserved",
            Self::Bt709 => "Rec. ITU-R BT.709-6",
            Self::Unspecified => "Unspecified",
            Self::Bt470SystemM => "Rec. ITU-R BT.470-7 System M (historical)",
            Self::Bt470SystemBg => "Rec. ITU-R BT.470-7 System B, G (historical)",
            Self::Bt601_525 => "Rec. ITU-R BT.601-7 525",
            Self::Smpte240M => "SMPTE 240M (1999, historical)",
            Self::GenericFilm => "Generic film (colour filters using Illuminant C)",
            Self::Bt2020 => "Rec. ITU-R BT.2020-2",
            Self::Xyz => "SMPTE ST 428-1 (2006)",
            Self::SmpteRp431_2 => "SMPTE RP 431-2 (2011)",
            Self::SmpteEg432_1 => "SMPTE EG 432-1 (2010)",
            Self::EbuTech3213E => "EBU Tech. 3213-E (1975)",
        }
    }

    /// `colour_primaries` when the VUI omits the field (inferred 2).
    pub fn inferred() -> Self {
        Self::Unspecified
    }
}

broadcast_common::impl_spec_display!(ColourPrimaries, Reserved);

/// H.264 Table E-4 / H.265 Table E.4 `transfer_characteristics` (identical
/// rows in both specs), the wire form kept losslessly.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TransferCharacteristics {
    /// 0: reserved for future use by ITU-T | ISO/IEC.
    Reserved(u8),
    /// 1: Rec. ITU-R BT.709-6 (also BT.1361-0 conventional gamut).
    Bt709,
    /// 2: unspecified.
    Unspecified,
    /// 4: assumed display gamma 2.2 (BT.470-7 System M, historical).
    Gamma22,
    /// 5: assumed display gamma 2.8 (BT.470-7 System B, G, historical).
    Gamma28,
    /// 6: Rec. ITU-R BT.601-7 (525 or 625).
    Bt601,
    /// 7: SMPTE 240M (1999, historical).
    Smpte240M,
    /// 8: linear transfer characteristics.
    Linear,
    /// 9: logarithmic transfer characteristic (100:1 range).
    Log100,
    /// 10: logarithmic transfer characteristic (100 * Sqrt(10) : 1 range).
    Log316,
    /// 11: IEC 61966-2-4.
    Iec61966_2_4,
    /// 12: Rec. ITU-R BT.1361-0 extended colour gamut system (historical).
    Bt1361Extended,
    /// 13: IEC 61966-2-1 sRGB / sYCC.
    Iec61966_2_1,
    /// 14: Rec. ITU-R BT.2020-2 (10 bit system).
    Bt2020_10Bit,
    /// 15: Rec. ITU-R BT.2020-2 (12 bit system).
    Bt2020_12Bit,
    /// 16: SMPTE ST 2084 (2014) / Rec. ITU-R BT.2100-2 PQ system.
    SmpteSt2084,
    /// 17: SMPTE ST 428-1 (2006).
    SmpteSt428_1,
    /// 18: ARIB STD-B67 / Rec. ITU-R BT.2100-2 HLG system.
    AribStdB67,
}

impl TransferCharacteristics {
    /// Decode a `transfer_characteristics` value; unnamed rows are reserved.
    pub fn from_wire(code: u8) -> Self {
        match code {
            1 => Self::Bt709,
            2 => Self::Unspecified,
            4 => Self::Gamma22,
            5 => Self::Gamma28,
            6 => Self::Bt601,
            7 => Self::Smpte240M,
            8 => Self::Linear,
            9 => Self::Log100,
            10 => Self::Log316,
            11 => Self::Iec61966_2_4,
            12 => Self::Bt1361Extended,
            13 => Self::Iec61966_2_1,
            14 => Self::Bt2020_10Bit,
            15 => Self::Bt2020_12Bit,
            16 => Self::SmpteSt2084,
            17 => Self::SmpteSt428_1,
            18 => Self::AribStdB67,
            other => Self::Reserved(other),
        }
    }

    /// The wire `transfer_characteristics` value.
    pub fn code(&self) -> u8 {
        match self {
            Self::Reserved(code) => *code,
            Self::Bt709 => 1,
            Self::Unspecified => 2,
            Self::Gamma22 => 4,
            Self::Gamma28 => 5,
            Self::Bt601 => 6,
            Self::Smpte240M => 7,
            Self::Linear => 8,
            Self::Log100 => 9,
            Self::Log316 => 10,
            Self::Iec61966_2_4 => 11,
            Self::Bt1361Extended => 12,
            Self::Iec61966_2_1 => 13,
            Self::Bt2020_10Bit => 14,
            Self::Bt2020_12Bit => 15,
            Self::SmpteSt2084 => 16,
            Self::SmpteSt428_1 => 17,
            Self::AribStdB67 => 18,
        }
    }

    /// Label: the Table E-4 transfer characteristic / informative remark
    /// (without the transfer-function equation), `"reserved"` for reserved
    /// rows. HLG (18) is an H.265-defined row that H.264 also defines.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Reserved(_) => "reserved",
            Self::Bt709 => "Rec. ITU-R BT.709-6",
            Self::Unspecified => "Unspecified",
            Self::Gamma22 => "Assumed display gamma 2.2",
            Self::Gamma28 => "Assumed display gamma 2.8",
            Self::Bt601 => "Rec. ITU-R BT.601-7 525 or 625",
            Self::Smpte240M => "SMPTE 240M (1999, historical)",
            Self::Linear => "Linear transfer characteristics",
            Self::Log100 => "Logarithmic transfer characteristic (100:1 range)",
            Self::Log316 => "Logarithmic transfer characteristic (100 * Sqrt(10) : 1 range)",
            Self::Iec61966_2_4 => "IEC 61966-2-4",
            Self::Bt1361Extended => {
                "Rec. ITU-R BT.1361-0 extended colour gamut system (historical)"
            }
            Self::Iec61966_2_1 => {
                "IEC 61966-2-1 sRGB (with matrix_coefficients equal to 0) \
                 / IEC 61966-2-1 sYCC (with matrix_coefficients equal to 5)"
            }
            Self::Bt2020_10Bit => "Rec. ITU-R BT.2020-2 (10 bit system)",
            Self::Bt2020_12Bit => "Rec. ITU-R BT.2020-2 (12 bit system)",
            Self::SmpteSt2084 => "SMPTE ST 2084 (2014) / Rec. ITU-R BT.2100-2 PQ system",
            Self::SmpteSt428_1 => "SMPTE ST 428-1 (2006)",
            Self::AribStdB67 => "ARIB STD-B67 / Rec. ITU-R BT.2100-2 HLG system",
        }
    }

    /// `transfer_characteristics` when the VUI omits the field (inferred 2).
    pub fn inferred() -> Self {
        Self::Unspecified
    }
}

broadcast_common::impl_spec_display!(TransferCharacteristics, Reserved);

/// H.264 Table E-5 / H.265 Table E.5 `matrix_coefficients` (identical rows in
/// both specs), the wire form kept losslessly.
///
/// The broadcaster-facing rows are [`Bt709`](Self::Bt709),
/// [`Bt470SystemB`](Self::Bt470SystemB) (BT.601 625) and
/// [`Bt470SystemM`](Self::Bt470SystemM) (BT.601 525), plus
/// [`Bt2020NonConstant`](Self::Bt2020NonConstant) for UHD.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatrixCoefficients {
    /// 0: GBR (H.264) / Identity (H.265): the identity matrix (RGB / YZX).
    Gbr,
    /// 1: KR = 0.2126; KB = 0.0722 (Rec. ITU-R BT.709-6).
    Bt709,
    /// 2: unspecified.
    Unspecified,
    /// 3: reserved for future use by ITU-T | ISO/IEC.
    Reserved(u8),
    /// 4: KR = 0.30; KB = 0.11 (FCC Title 47 CFR 73.682).
    Fcc,
    /// 5: KR = 0.299; KB = 0.114 (BT.470-7 System B, G / BT.601-7 625 / sYCC).
    Bt470SystemB,
    /// 6: KR = 0.299; KB = 0.114 (BT.601-7 525 / SMPTE 170M).
    Bt470SystemM,
    /// 7: KR = 0.212; KB = 0.087 (SMPTE 240M, 1999, historical).
    Smpte240M,
    /// 8: YCgCo or YCgCo-R.
    YCgCo,
    /// 9: KR = 0.2627; KB = 0.0593 (BT.2020-2 non-constant luminance).
    Bt2020NonConstant,
    /// 10: KR = 0.2627; KB = 0.0593 (BT.2020-2 constant luminance).
    Bt2020Constant,
    /// 11: Y'D'ZD'X (SMPTE ST 2085 (2015)).
    SmpteSt2085,
    /// 12: chromaticity-derived non-constant luminance system.
    ChromaticityDerivedNonConstant,
    /// 13: chromaticity-derived constant luminance system.
    ChromaticityDerivedConstant,
    /// 14: ICtCp (BT.2100-2).
    ICtCp,
    /// 15: IPT-C2.
    IptC2,
    /// 16: YCgCo-Re.
    YCgCoRe,
    /// 17: YCgCo-Ro.
    YCgCoRo,
}

impl MatrixCoefficients {
    /// Decode a `matrix_coefficients` value; unnamed rows are reserved.
    pub fn from_wire(code: u8) -> Self {
        match code {
            0 => Self::Gbr,
            1 => Self::Bt709,
            2 => Self::Unspecified,
            4 => Self::Fcc,
            5 => Self::Bt470SystemB,
            6 => Self::Bt470SystemM,
            7 => Self::Smpte240M,
            8 => Self::YCgCo,
            9 => Self::Bt2020NonConstant,
            10 => Self::Bt2020Constant,
            11 => Self::SmpteSt2085,
            12 => Self::ChromaticityDerivedNonConstant,
            13 => Self::ChromaticityDerivedConstant,
            14 => Self::ICtCp,
            15 => Self::IptC2,
            16 => Self::YCgCoRe,
            17 => Self::YCgCoRo,
            other => Self::Reserved(other),
        }
    }

    /// The wire `matrix_coefficients` value.
    pub fn code(&self) -> u8 {
        match self {
            Self::Gbr => 0,
            Self::Bt709 => 1,
            Self::Unspecified => 2,
            Self::Reserved(code) => *code,
            Self::Fcc => 4,
            Self::Bt470SystemB => 5,
            Self::Bt470SystemM => 6,
            Self::Smpte240M => 7,
            Self::YCgCo => 8,
            Self::Bt2020NonConstant => 9,
            Self::Bt2020Constant => 10,
            Self::SmpteSt2085 => 11,
            Self::ChromaticityDerivedNonConstant => 12,
            Self::ChromaticityDerivedConstant => 13,
            Self::ICtCp => 14,
            Self::IptC2 => 15,
            Self::YCgCoRe => 16,
            Self::YCgCoRo => 17,
        }
    }

    /// Label: the Table E-5 matrix / informative remark (without the
    /// equations), `"reserved"` for reserved rows. Row 0 uses H.264's `GBR`.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Gbr => "GBR",
            Self::Bt709 => "Rec. ITU-R BT.709-6",
            Self::Unspecified => "Unspecified",
            Self::Reserved(_) => "reserved",
            Self::Fcc => "FCC Title 47 CFR 73.682 (a) (20)",
            Self::Bt470SystemB => {
                "Rec. ITU-R BT.470-7 System B, G (historical) / Rec. ITU-R BT.601-7 625"
            }
            Self::Bt470SystemM => "Rec. ITU-R BT.601-7 525 / SMPTE 170M (2004)",
            Self::Smpte240M => "SMPTE 240M (1999, historical)",
            Self::YCgCo => "YCgCo or YCgCo-R",
            Self::Bt2020NonConstant => {
                "Rec. ITU-R BT.2020-2 non-constant luminance system / Rec. ITU-R BT.2100-2 Y'CbCr"
            }
            Self::Bt2020Constant => "Rec. ITU-R BT.2020-2 constant luminance system",
            Self::SmpteSt2085 => "Y'D'ZD'X (SMPTE ST 2085 (2015))",
            Self::ChromaticityDerivedNonConstant => {
                "Chromaticity-derived non-constant luminance system"
            }
            Self::ChromaticityDerivedConstant => "Chromaticity-derived constant luminance system",
            Self::ICtCp => "ICtCp (Rec. ITU-R BT.2100-2)",
            Self::IptC2 => "IPT-C2 (IPT-PQ-C2)",
            Self::YCgCoRe => "YCgCo-Re",
            Self::YCgCoRo => "YCgCo-Ro",
        }
    }

    /// `matrix_coefficients` when the VUI omits the field (inferred 2).
    pub fn inferred() -> Self {
        Self::Unspecified
    }
}

broadcast_common::impl_spec_display!(MatrixCoefficients, Reserved);

/// `colour_description_present_flag == 1`: H.264 §E.2.1 Tables E-3..E-5 /
/// H.265 §E.3.1 Tables E.3..E.5.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ColourDescription {
    /// `colour_primaries`.
    pub primaries: ColourPrimaries,
    /// `transfer_characteristics`.
    pub transfer: TransferCharacteristics,
    /// `matrix_coefficients` (H.265: `matrix_coeffs`).
    pub matrix: MatrixCoefficients,
}

impl ColourDescription {
    /// Build from the three wire values (`u(8)` each), keeping every code
    /// point losslessly.
    pub fn from_wire(primaries: u8, transfer: u8, matrix: u8) -> Self {
        Self {
            primaries: ColourPrimaries::from_wire(primaries),
            transfer: TransferCharacteristics::from_wire(transfer),
            matrix: MatrixCoefficients::from_wire(matrix),
        }
    }
}

/// `video_signal_type_present_flag == 1`: H.264 §E.2.1 / H.265 §E.3.1.
///
/// Only what was signalled is recorded, except that `video_format` has no
/// `None` state on the wire (the field is always the full `u(3)` when the
/// block is present). The spec's inferred values when the whole block is
/// absent live on [`DisplayGeometry::video_format`](DisplayGeometry::video_format)
/// and friends, never in here.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VideoSignalType {
    /// `video_format`.
    pub video_format: VideoFormat,
    /// `video_full_range_flag` (1 = full range).
    pub full_range: bool,
    /// `None` when `colour_description_present_flag` is 0 (the spec then
    /// infers primaries/transfer/matrix 2, available via
    /// [`DisplayGeometry::colour_description`](DisplayGeometry::colour_description)).
    pub colour: Option<ColourDescription>,
}

impl VideoSignalType {
    /// Build from the field values as read.
    pub fn new(
        video_format: VideoFormat,
        full_range: bool,
        colour: Option<ColourDescription>,
    ) -> Self {
        Self {
            video_format,
            full_range,
            colour,
        }
    }
}

/// Sequence-level display geometry of a video track: everything derived from
/// the active SPS (in a conforming stream it changes only at an IDR / IRAP,
/// H.264 §7.4.1.2.1 / H.265 §7.4.3.2). Lives on
/// [`TrackSpec::display`](super::TrackSpec::display).
///
/// Phases 1a/1b carry the coded size, the VUI aspect ratio, the overscan
/// flag and the video signal type (format, full range, colour description);
/// cropping and the H.265 default display window are additive follow-ups.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DisplayGeometry {
    /// Decoded picture width before cropping, in luma samples (H.264
    /// `PicWidthInSamplesL`; H.265 `pic_width_in_luma_samples`). `u32`, wider
    /// than the `u16` [`CodecConfig`] carries; unlike `CodecConfig`'s width it
    /// is **not** cropped.
    pub coded_width: u32,
    /// Decoded picture height before cropping, in luma samples (H.264
    /// `16 * FrameHeightInMbs`; H.265 `pic_height_in_luma_samples`).
    pub coded_height: u32,
    /// What the decoder outputs: H.264 frame-cropping rectangle / H.265
    /// conformance window. Equals the full picture when there is no cropping.
    pub output_rect: PictureRect,
    /// H.265 default display window (absolute, i.e. conformance offsets
    /// already added per E-78..E-81). Always `None` for H.264. A suggestion,
    /// never applied to `output_rect`.
    pub default_display_rect: Option<PictureRect>,
    /// The VUI `aspect_ratio_idc` as signalled. `None` when the SPS has no VUI,
    /// `aspect_ratio_info_present_flag` is 0, or the VUI was truncated before
    /// the field was complete (all inferred idc 0, "unspecified"). `Some` does
    /// **not** imply a specified ratio: see
    /// [`sample_aspect_ratio`](Self::sample_aspect_ratio).
    pub aspect_ratio: Option<AspectRatioIdc>,
    /// `overscan_appropriate_flag` as signalled. `None` when
    /// `overscan_info_present_flag` is 0 or the VUI was truncated before it.
    pub overscan_appropriate: Option<bool>,
    /// `video_signal_type()` as signalled. `None` when
    /// `video_signal_type_present_flag` is 0 (or there is no VUI). The spec's
    /// inferred defaults (format 5, limited range, colour 2/2/2) are then
    /// available through [`video_format`](Self::video_format),
    /// [`full_range`](Self::full_range) and
    /// [`colour_description`](Self::colour_description); the struct itself
    /// records only what was signalled.
    pub video_signal: Option<VideoSignalType>,
    /// This geometry came from MPEG-2 video (H.262) syntax, whose inferred
    /// colour defaults differ from H.264/H.265: BT.709 (1/1/1) rather than
    /// unspecified (2/2/2, H.262 §6.3.6 vs H.264 §E.2.1). `false` for every
    /// other source; [`colour_description`](Self::colour_description) reads it
    /// when nothing was signalled.
    pub mpeg2: bool,
}

impl DisplayGeometry {
    /// Build from explicit values (for muxers and tests; demuxed tracks get
    /// theirs from the SPS).
    pub fn new(coded_width: u32, coded_height: u32, aspect_ratio: Option<AspectRatioIdc>) -> Self {
        Self {
            coded_width,
            coded_height,
            output_rect: PictureRect::new(0, 0, coded_width, coded_height),
            default_display_rect: None,
            aspect_ratio,
            overscan_appropriate: None,
            video_signal: None,
            mpeg2: false,
        }
    }

    /// Geometry of an H.264 SPS NAL unit (1-byte NAL header included; the same
    /// input as [`decode_avc_sps`](crate::decode_avc_sps), and the same VUI
    /// walk).
    pub fn from_avc_sps(sps_nal: &[u8]) -> Result<Self> {
        crate::sps::decode_avc_display_facts(sps_nal).map(Self::from_facts)
    }

    /// Geometry of an H.265 SPS NAL unit (2-byte NAL header included; the same
    /// input as [`decode_hevc_sps`](crate::decode_hevc_sps)).
    pub fn from_hevc_sps(sps_nal: &[u8]) -> Result<Self> {
        crate::sps::decode_hevc_display_facts(sps_nal).map(Self::from_facts)
    }

    /// Geometry derived from the first SPS of an `avcC` / `hvcC` record, or
    /// from the `sequence_header()` an MPEG-2 video `esds`
    /// DecoderSpecificInfo carries. `None` for other codecs, for a record with
    /// no SPS / no sequence header (a placeholder config), or when that header
    /// does not decode; never a fabricated value.
    pub fn from_codec_config(config: &CodecConfig) -> Option<Self> {
        match config {
            CodecConfig::Avc { config, .. } => {
                let sps = config.config.sps.first()?;
                Self::from_avc_sps(&sps.0).ok()
            }
            CodecConfig::Hevc { config, .. } => {
                let sps = config
                    .config
                    .arrays
                    .iter()
                    .filter(|a| a.nal_unit_type == crate::nalu_types::HEVC_SPS_NUT)
                    .flat_map(|a| a.nalus.iter())
                    .next()?;
                Self::from_hevc_sps(&sps.0).ok()
            }
            CodecConfig::Mpeg2Video { esds, .. } => {
                let es = esds
                    .es_descriptor
                    .decoder_config
                    .as_ref()?
                    .decoder_specific_info
                    .as_ref()?;
                Self::from_mpeg2_es(&es.data).ok()
            }
            _ => None,
        }
    }

    fn from_facts(f: crate::sps::DisplayFacts) -> Self {
        Self {
            coded_width: f.coded_width,
            coded_height: f.coded_height,
            output_rect: f.output_rect,
            default_display_rect: f.default_display_rect,
            aspect_ratio: f.aspect_ratio,
            overscan_appropriate: f.overscan_appropriate,
            video_signal: f.video_signal,
            mpeg2: false,
        }
    }

    /// Whether this geometry came from an MPEG-2 (H.262) sequence.
    pub fn is_mpeg2(&self) -> bool {
        self.mpeg2
    }

    /// The specified sample aspect ratio as `(width, height)`, or `None` when
    /// it is unspecified (no VUI / flag clear, idc 0, reserved idc, or an
    /// Extended_SAR with a zero component). Exactly as signalled, not reduced:
    /// see [`SampleAspectRatio::reduced`].
    pub fn sample_aspect_ratio(&self) -> Option<(u16, u16)> {
        self.typed_sample_aspect_ratio().map(Into::into)
    }

    /// [`sample_aspect_ratio`](Self::sample_aspect_ratio) as the typed
    /// [`SampleAspectRatio`].
    pub fn typed_sample_aspect_ratio(&self) -> Option<SampleAspectRatio> {
        self.aspect_ratio?.sample_aspect_ratio()
    }

    /// `video_full_range_flag`: `true` only when the VUI signalled full range;
    /// the spec's inferred value when the video signal type is absent is 0
    /// (limited range), so this returns `false` then.
    pub fn full_range(&self) -> bool {
        self.video_signal.is_some_and(|vst| vst.full_range)
    }

    /// `video_format`, the signalled value or the inferred 5 when the video
    /// signal type is absent (H.264 §E.2.1).
    pub fn video_format(&self) -> VideoFormat {
        self.video_signal
            .map_or_else(VideoFormat::inferred, |vst| vst.video_format)
    }

    /// The colour description, the signalled triple or, when
    /// `colour_description_present_flag` is 0 (or the whole video signal type
    /// is absent), the spec's inferred primaries / transfer / matrix: 2/2/2
    /// (unspecified) for H.264/H.265, but 1/1/1 (BT.709) for MPEG-2
    /// ([`MPEG2_INFERRED_COLOUR_CODE`], H.262 §6.3.6). A player wanting to
    /// know whether the stream really said BT.709 reads
    /// [`video_signal`](Self::video_signal) instead.
    pub fn colour_description(&self) -> ColourDescription {
        self.video_signal
            .and_then(|vst| vst.colour)
            .unwrap_or(if self.mpeg2 {
                ColourDescription::from_wire(
                    MPEG2_INFERRED_COLOUR_CODE,
                    MPEG2_INFERRED_COLOUR_CODE,
                    MPEG2_INFERRED_COLOUR_CODE,
                )
            } else {
                ColourDescription {
                    primaries: ColourPrimaries::inferred(),
                    transfer: TransferCharacteristics::inferred(),
                    matrix: MatrixCoefficients::inferred(),
                }
            })
    }
}

/// Everything that determines how one access unit is shown
/// (`docs/display-geometry/DESIGN.md` §4, Phase 2).
///
/// ETSI TS 101 154 Table B.5 / SMPTE ST 2016-1 Table 1 (SN §5), wire form
/// kept losslessly.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ActiveFormatDescription {
    /// 0000: AFD unknown.
    Unknown,
    /// 0010: box 16:9 (top).
    Box16x9Top,
    /// 0011: box 14:9 (top).
    Box14x9Top,
    /// 0100: box > 16:9 (centre).
    BoxWiderThan16x9Centre,
    /// 1000: active format is the same as the coded frame.
    SameAsCodedFrame,
    /// 1001: 4:3 (centre).
    Centre4x3,
    /// 1010: 16:9 (centre).
    Centre16x9,
    /// 1011: 14:9 (centre).
    Centre14x9,
    /// 1101: 4:3 (with shoot and protect 14:9 centre).
    Centre4x3ShootProtect14x9,
    /// 1110: 16:9 (with shoot and protect 14:9 centre).
    Centre16x9ShootProtect14x9,
    /// 1111: 16:9 (with shoot and protect 4:3 centre).
    Centre16x9ShootProtect4x3,
    /// 0001, 0101..0111, 1100: reserved (wire value kept).
    Reserved(u8),
}

impl ActiveFormatDescription {
    /// The 4-bit wire code (lossless).
    pub fn code(&self) -> u8 {
        match self {
            Self::Unknown => 0b0000,
            Self::Box16x9Top => 0b0010,
            Self::Box14x9Top => 0b0011,
            Self::BoxWiderThan16x9Centre => 0b0100,
            Self::SameAsCodedFrame => 0b1000,
            Self::Centre4x3 => 0b1001,
            Self::Centre16x9 => 0b1010,
            Self::Centre14x9 => 0b1011,
            Self::Centre4x3ShootProtect14x9 => 0b1101,
            Self::Centre16x9ShootProtect14x9 => 0b1110,
            Self::Centre16x9ShootProtect4x3 => 0b1111,
            Self::Reserved(v) => *v,
        }
    }

    /// Build from the 4-bit wire code (lossless, every value maps).
    pub fn from_code(code: u8) -> Self {
        match code & 0x0F {
            0b0000 => Self::Unknown,
            0b0010 => Self::Box16x9Top,
            0b0011 => Self::Box14x9Top,
            0b0100 => Self::BoxWiderThan16x9Centre,
            0b1000 => Self::SameAsCodedFrame,
            0b1001 => Self::Centre4x3,
            0b1010 => Self::Centre16x9,
            0b1011 => Self::Centre14x9,
            0b1101 => Self::Centre4x3ShootProtect14x9,
            0b1110 => Self::Centre16x9ShootProtect14x9,
            0b1111 => Self::Centre16x9ShootProtect4x3,
            other => Self::Reserved(other),
        }
    }

    pub fn name(&self) -> &'static str {
        match self {
            Self::Unknown => "AFD unknown",
            Self::Box16x9Top => "box 16:9 (top)",
            Self::Box14x9Top => "box 14:9 (top)",
            Self::BoxWiderThan16x9Centre => "box > 16:9 (centre)",
            Self::SameAsCodedFrame => "same as coded frame",
            Self::Centre4x3 => "4:3 (centre)",
            Self::Centre16x9 => "16:9 (centre)",
            Self::Centre14x9 => "14:9 (centre)",
            Self::Centre4x3ShootProtect14x9 => "4:3 (with shoot and protect 14:9 centre)",
            Self::Centre16x9ShootProtect14x9 => "16:9 (with shoot and protect 14:9 centre)",
            Self::Centre16x9ShootProtect4x3 => "16:9 (with shoot and protect 4:3 centre)",
            Self::Reserved(_) => "reserved",
        }
    }
}
broadcast_common::impl_spec_display!(ActiveFormatDescription, Reserved);

/// TS 101 154 Table B.7. Only the signalled pair is `Some`; the 14-bit values
/// are kept as wire values.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BarData {
    pub top_bar_end_line: Option<u16>,
    pub bottom_bar_start_line: Option<u16>,
    pub left_bar_end_pixel: Option<u16>,
    pub right_bar_start_pixel: Option<u16>,
}

/// Which wrapper carried the AFD/bar data.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UserDataCarriage {
    AvcSei,
    HevcPrefixSei,
    Mpeg2PictureUserData,
}

impl UserDataCarriage {
    pub fn name(&self) -> &'static str {
        match self {
            Self::AvcSei => "AVC SEI",
            Self::HevcPrefixSei => "HEVC prefix SEI",
            Self::Mpeg2PictureUserData => "MPEG-2 picture user data",
        }
    }
}
broadcast_common::impl_spec_display!(UserDataCarriage);

/// Picture-level "area of interest" state in force for an access unit.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ActiveFormat {
    /// `None` when the last afd_data() had active_format_flag == 0, or no AFD
    /// has been seen.
    pub afd: Option<ActiveFormatDescription>,
    pub bar_data: Option<BarData>,
    pub carriage: UserDataCarriage,
}

impl ActiveFormat {
    /// Construct a picture-level state (additive Phase 3 constructor).
    pub fn new(
        afd: Option<ActiveFormatDescription>,
        bar_data: Option<BarData>,
        carriage: UserDataCarriage,
    ) -> Self {
        Self {
            afd,
            bar_data,
            carriage,
        }
    }
}

/// Persistence policy for AFD / bar data in H.264/H.265 (design §6.4).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum AfdPersistence {
    /// Sticky until a new AFD message replaces it (default).
    #[default]
    UntilReplaced,
    /// Reset at a random-access (IDR/IRAP) AU that carries no AFD: afd becomes
    /// `Some(SameAsCodedFrame)` and bar data becomes `None` (ANSI/SCTE 128-1
    /// §8.2.3-8.2.4).
    ResetAtRandomAccess,
}

impl AfdPersistence {
    pub fn name(&self) -> &'static str {
        match self {
            Self::UntilReplaced => "until replaced",
            Self::ResetAtRandomAccess => "reset at random access",
        }
    }
}
broadcast_common::impl_spec_display!(AfdPersistence);

/// Carried twice, always behind `alloc::sync::Arc` because it is shared by
/// every picture of a configuration and never copied per sample:
/// [`Sample::display`](super::Sample::display) for the state in force at one
/// access unit, and [`DemuxEvent::DisplayChanged`](super::DemuxEvent::DisplayChanged)
/// announcing a new state before the first access unit it applies to.
///
/// Phase 2 populates [`geometry`](Self::geometry) only; picture-level AFD and
/// bar data are Phase 3 and land as additive fields.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DisplayInfo {
    /// The sequence-level geometry of the SPS active at this access unit.
    /// `None` for a track with no parseable SPS.
    pub geometry: Option<DisplayGeometry>,
    /// Picture-level active format (AFD) and bar data in force at this access
    /// unit, or `None` when none has been signalled.
    pub active_format: Option<ActiveFormat>,
}

impl DisplayInfo {
    /// A state carrying only a sequence-level geometry.
    pub fn new(geometry: Option<DisplayGeometry>) -> Self {
        Self {
            geometry,
            active_format: None,
        }
    }

    /// Attach an [`ActiveFormat`] to this state (additive Phase 3 constructor).
    pub fn with_active_format(mut self, active_format: Option<ActiveFormat>) -> Self {
        self.active_format = active_format;
        self
    }

    /// The state of a [`TrackSpec`](super::TrackSpec)'s static
    /// [`display`](super::TrackSpec::display) geometry, or `None` when that
    /// spec has none (nothing to announce, so no per-AU state either).
    pub fn from_geometry(geometry: Option<DisplayGeometry>) -> Option<Self> {
        geometry.map(|g| Self::new(Some(g)))
    }

    /// The sample aspect ratio in force, if any.
    pub fn sample_aspect_ratio(&self) -> Option<SampleAspectRatio> {
        self.geometry.as_ref()?.typed_sample_aspect_ratio()
    }

    /// Which parts of `self` differ from `previous`.
    ///
    /// Comparison is by **parsed value** ([`PartialEq`]), never by the bytes
    /// a parameter set arrived in (design §6.1): an SPS re-sent with a level
    /// or HRD edit but identical geometry yields an all-false set, while a
    /// wire-form change of the SAR (e.g. idc 4 `16:11` to Extended_SAR
    /// `64:45`) always sets [`DisplayChangeSet::aspect_ratio`] even when the
    /// resulting display aspect ratio is unchanged.
    pub fn changes_from(&self, previous: Option<&Self>) -> DisplayChangeSet {
        let Some(previous) = previous else {
            return DisplayChangeSet {
                initial: true,
                ..DisplayChangeSet::default()
            };
        };
        if previous == self {
            return DisplayChangeSet::default();
        }
        let previous_display = previous;
        let (current, previous) = (self.geometry.as_ref(), previous_display.geometry.as_ref());
        DisplayChangeSet {
            initial: false,
            aspect_ratio: aspect_ratio_of(current) != aspect_ratio_of(previous),
            output_rect: output_rect_of(current) != output_rect_of(previous),
            video_signal: current.and_then(|g| g.video_signal)
                != previous.and_then(|g| g.video_signal),
            overscan: current.and_then(|g| g.overscan_appropriate)
                != previous.and_then(|g| g.overscan_appropriate),
            default_display_rect: default_display_rect_of(current)
                != default_display_rect_of(previous),
            afd: self.active_format.as_ref().map(|a| a.afd)
                != previous_display.active_format.as_ref().map(|a| a.afd),
            bar_data: self.active_format.as_ref().and_then(|a| a.bar_data.clone())
                != previous_display
                    .active_format
                    .as_ref()
                    .and_then(|a| a.bar_data.clone()),
        }
    }
}

/// The wire aspect ratio (idc and, for Extended_SAR, both terms) in force.
fn aspect_ratio_of(g: Option<&DisplayGeometry>) -> Option<AspectRatioIdc> {
    g.and_then(|g| g.aspect_ratio)
}

/// The displayed rectangle (output crop) of a geometry, or `None` when the
/// geometry itself is absent.
fn output_rect_of(g: Option<&DisplayGeometry>) -> Option<PictureRect> {
    g.map(|g| g.output_rect)
}

/// The (never-applied) H.265 default display window of a geometry.
fn default_display_rect_of(g: Option<&DisplayGeometry>) -> Option<Option<PictureRect>> {
    g.map(|g| g.default_display_rect)
}

/// Which parts of a [`DisplayInfo`] differ from the previous state for a
/// track (design §4, §6.1). Every field is an exact comparison of that part.
///
/// A field is set by any wire-form difference of the part, so a SAR change
/// that leaves the display aspect ratio identical (16:11 -> 64:45) still sets
/// [`aspect_ratio`](Self::aspect_ratio), and an SPS whose bytes changed but
/// whose parsed geometry did not sets nothing.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DisplayChangeSet {
    /// The first state for this track (level-triggered start, design §5.2).
    pub initial: bool,
    /// [`AspectRatioIdc`] changed (idc, or the Extended_SAR terms).
    pub aspect_ratio: bool,
    /// The output rectangle changed (Phase 2: the coded size; cropping is a
    /// later phase).
    pub output_rect: bool,
    /// The (never-applied) H.265 default display window changed. Always
    /// `false` in Phase 2.
    pub default_display_rect: bool,
    /// The [`VideoSignalType`] changed (video format, full range, colour).
    pub video_signal: bool,
    /// [`DisplayGeometry::overscan_appropriate`] changed.
    pub overscan: bool,
    pub afd: bool,
    pub bar_data: bool,
}

impl DisplayChangeSet {
    /// The change set of a track's first state.
    pub fn initial() -> Self {
        Self {
            initial: true,
            ..Self::default()
        }
    }

    /// Whether any field changed at all.
    pub fn any(&self) -> bool {
        *self != Self::default()
    }

    /// A short, stable label of the changed parts, in field order
    /// (`"initial aspect_ratio"`), used by tests and logs.
    pub fn names(&self) -> alloc::string::String {
        let mut out = alloc::string::String::new();
        let mut push = |set: bool, name: &str| {
            if set {
                if !out.is_empty() {
                    out.push(' ');
                }
                out.push_str(name);
            }
        };
        push(self.initial, "initial");
        push(self.aspect_ratio, "aspect_ratio");
        push(self.output_rect, "output_rect");
        push(self.default_display_rect, "default_display_rect");
        push(self.video_signal, "video_signal");
        push(self.overscan, "overscan");
        push(self.afd, "afd");
        push(self.bar_data, "bar_data");
        out
    }
}

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

    #[test]
    fn idc_round_trips_for_every_wire_value() {
        for idc in 0..=u8::MAX {
            let v = AspectRatioIdc::from_wire(idc, Some((3, 4)));
            assert_eq!(v.idc(), idc, "idc {idc}");
        }
    }

    #[test]
    fn variants_land_on_their_table_e1_rows() {
        assert_eq!(
            AspectRatioIdc::from_wire(0, None),
            AspectRatioIdc::Unspecified
        );
        assert_eq!(AspectRatioIdc::from_wire(1, None), AspectRatioIdc::Square);
        assert_eq!(AspectRatioIdc::from_wire(4, None), AspectRatioIdc::Sar16x11);
        assert_eq!(AspectRatioIdc::from_wire(14, None), AspectRatioIdc::Sar4x3);
        assert_eq!(AspectRatioIdc::from_wire(16, None), AspectRatioIdc::Sar2x1);
        assert_eq!(
            AspectRatioIdc::from_wire(17, None),
            AspectRatioIdc::Reserved(17)
        );
        assert_eq!(
            AspectRatioIdc::from_wire(255, Some((64, 45))),
            AspectRatioIdc::ExtendedSar {
                sar_width: 64,
                sar_height: 45
            }
        );
        // `extended` is ignored for a non-255 idc, and a missing pair for 255
        // is unspecified rather than invented.
        assert_eq!(
            AspectRatioIdc::from_wire(4, Some((9, 9))),
            AspectRatioIdc::Sar16x11
        );
        assert_eq!(
            AspectRatioIdc::from_wire(255, None).sample_aspect_ratio(),
            None
        );
    }

    #[test]
    fn labels_follow_the_spec_tokens() {
        assert_eq!(AspectRatioIdc::Square.to_string(), "1:1");
        assert_eq!(AspectRatioIdc::Sar160x99.to_string(), "160:99");
        assert_eq!(AspectRatioIdc::Unspecified.to_string(), "unspecified");
        assert_eq!(AspectRatioIdc::Reserved(0x11).to_string(), "reserved(0x11)");
        let ext = AspectRatioIdc::from_wire(255, Some((64, 45)));
        assert_eq!(ext.to_string(), "Extended_SAR");
    }

    #[test]
    fn sample_aspect_ratio_rejects_a_zero_term() {
        assert!(SampleAspectRatio::new(0, 1).is_none());
        assert!(SampleAspectRatio::new(1, 0).is_none());
        let r = SampleAspectRatio::new(64, 45).unwrap();
        assert_eq!((r.width(), r.height()), (64, 45));
        assert_eq!(r.reduced(), r);
        let r = SampleAspectRatio::new(10, 4).unwrap();
        assert_eq!(r.reduced().as_pair(), (5, 2));
    }

    #[test]
    fn codecs_without_an_sps_have_no_geometry() {
        let data = CodecConfig::Data {
            stream_type: 0x06,
            descriptors: alloc::vec::Vec::new(),
            carriage: crate::ir::DataCarriage::Pes,
        };
        assert_eq!(DisplayGeometry::from_codec_config(&data), None);
    }
}