oxideav-mpegts 0.0.2

Pure-Rust clean-room MPEG-TS (ISO/IEC 13818-1) demuxer — 188-byte TS packet parser, PAT/PMT discovery, PES reassembly. Built to ingest Blu-ray .m2ts bytes for remux pipelines.
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
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
//! Program-Specific Information tables — PAT + PMT.
//!
//! Wire layout (ISO/IEC 13818-1 §2.4.4):
//!
//! When carried in a TS packet whose `payload_unit_start_indicator`
//! is set, the payload begins with a one-byte `pointer_field` that
//! gives the offset (from the byte that follows it) to the start of
//! the first section. Subsequent TS packets with the same PID and
//! `payload_unit_start_indicator == 0` carry continuation bytes for
//! the same section.
//!
//! A PSI section's common header (§2.4.4.10):
//!
//! ```text
//! table_id (8)
//! section_syntax_indicator (1) | '0' (1) | reserved (2) | section_length (12)
//! table_id_extension (16)
//! reserved (2) | version_number (5) | current_next_indicator (1)
//! section_number (8)
//! last_section_number (8)
//! ... body ...
//! CRC_32 (32, MPEG-2 left-shifting, init 0xFFFFFFFF, no reflect, no final XOR)
//! ```
//!
//! `section_length` counts the bytes AFTER the section_length field
//! itself, INCLUDING the CRC trailer.

use crate::descriptor::{iter_descriptors, DescriptorIter};
use crate::TsError;

/// PAT table_id per §2.4.4.3.
pub const PAT_TABLE_ID: u8 = 0x00;
/// CAT table_id per §2.4.4.6 (Table 2-26).
pub const CAT_TABLE_ID: u8 = 0x01;
/// PMT table_id per §2.4.4.8.
pub const PMT_TABLE_ID: u8 = 0x02;
/// TSDT (Transport Stream Description Table) table_id per §2.4.4.12 /
/// Table 2-26.
pub const TSDT_TABLE_ID: u8 = 0x03;
/// SDT (Service Description Table) `table_id` for sections describing the
/// **actual** Transport Stream — the one that carries the SDT (ETSI
/// EN 300 468 §5.2.3 / Table 2, `service_description_section`).
pub const SDT_ACTUAL_TABLE_ID: u8 = 0x42;
/// SDT `table_id` for sections describing **other** Transport Streams
/// (ETSI EN 300 468 §5.2.3 / Table 2).
pub const SDT_OTHER_TABLE_ID: u8 = 0x46;
/// EIT `table_id` for present/following events on the **actual** TS
/// (ETSI EN 300 468 §5.2.4 / Table 2 — `0x4E`).
pub const EIT_ACTUAL_PF_TABLE_ID: u8 = 0x4E;
/// EIT `table_id` for present/following events on **other** TSs
/// (ETSI EN 300 468 §5.2.4 / Table 2 — `0x4F`).
pub const EIT_OTHER_PF_TABLE_ID: u8 = 0x4F;
/// First `table_id` of the EIT **actual**-TS schedule range
/// (ETSI EN 300 468 §5.2.4 / Table 2 — `0x50`–`0x5F` inclusive).
pub const EIT_ACTUAL_SCHEDULE_FIRST: u8 = 0x50;
/// Last `table_id` of the EIT actual-TS schedule range (`0x5F`).
pub const EIT_ACTUAL_SCHEDULE_LAST: u8 = 0x5F;
/// First `table_id` of the EIT **other**-TS schedule range
/// (ETSI EN 300 468 §5.2.4 / Table 2 — `0x60`–`0x6F` inclusive).
pub const EIT_OTHER_SCHEDULE_FIRST: u8 = 0x60;
/// Last `table_id` of the EIT other-TS schedule range (`0x6F`).
pub const EIT_OTHER_SCHEDULE_LAST: u8 = 0x6F;

/// PID reserved for the Program Association Table per §2.4.4.3 / Table 2-3.
pub const PAT_PID: u16 = 0x0000;
/// PID reserved for the Conditional Access Table per §2.4.4.6 / Table 2-3.
pub const CAT_PID: u16 = 0x0001;
/// PID reserved for the Transport Stream Description Table per §2.4.4.12
/// / Table 2-3.
pub const TSDT_PID: u16 = 0x0002;
/// Fixed PID carrying the DVB SDT / BAT / ST sections (ETSI EN 300 468
/// §5.1.3 Table 1 — `0x0011`).
pub const SDT_PID: u16 = 0x0011;
/// Fixed PID carrying the DVB EIT sections (ETSI EN 300 468 §5.1.3
/// Table 1 / §5.2.4 — `0x0012`).
pub const EIT_PID: u16 = 0x0012;

/// Header bytes common to every long-form PSI section (table_id +
/// section_length field through last_section_number).
const SECTION_HEADER_LEN: usize = 8;
/// Length of the CRC-32 trailer.
const SECTION_CRC_LEN: usize = 4;
/// Upper bound on a single PSI section per §2.4.4: 3 header bytes
/// (table_id + section_length wrappers) plus `section_length` ≤ 0x3FD
/// (1021). For private sections this rises to 4096 — kept conservative
/// here since the assembler is sized for ITU-T-defined PSI tables.
pub const MAX_PSI_SECTION_LEN: usize = 3 + 0x3FD;

/// Parsed Program Association Table.
#[derive(Debug, Default, Clone)]
pub struct ProgramAssociationTable {
    /// `transport_stream_id` carried in `table_id_extension`.
    pub transport_stream_id: u16,
    /// 5-bit `version_number`.
    pub version_number: u8,
    /// `current_next_indicator`.
    pub current_next_indicator: bool,
    /// `section_number`.
    pub section_number: u8,
    /// `last_section_number`.
    pub last_section_number: u8,
    /// `(program_number, pmt_pid)` pairs.
    ///
    /// `program_number == 0` denotes the network PID; otherwise the
    /// PID is the PMT for that program.
    pub programs: Vec<(u16, u16)>,
}

impl ProgramAssociationTable {
    /// Parse a single PAT section. The slice must run from
    /// `table_id` through the CRC trailer (i.e. the pointer_field has
    /// already been skipped and the section has been extracted from
    /// the TS payload).
    pub fn parse(section: &[u8]) -> Result<Self, TsError> {
        let (hdr, body) = parse_section_header(section, PAT_TABLE_ID)?;
        let mut programs = Vec::new();
        let mut i = 0;
        while i + 4 <= body.len() {
            let program_number = u16::from_be_bytes([body[i], body[i + 1]]);
            let pid = ((((body[i + 2] & 0b0001_1111) as u16) << 8) | (body[i + 3] as u16)) & 0x1FFF;
            programs.push((program_number, pid));
            i += 4;
        }
        Ok(Self {
            transport_stream_id: hdr.table_id_extension,
            version_number: hdr.version_number,
            current_next_indicator: hdr.current_next_indicator,
            section_number: hdr.section_number,
            last_section_number: hdr.last_section_number,
            programs,
        })
    }
}

/// One elementary-stream descriptor inside a PMT.
#[derive(Debug, Clone)]
pub struct PmtStream {
    /// Per ISO/IEC 13818-1 Table 2-29 (`stream_type`).
    pub stream_type: u8,
    /// 13-bit elementary-stream PID.
    pub elementary_pid: u16,
    /// Raw descriptor bytes — the contents of the
    /// `ES_info_length`-bytes block, copied verbatim.
    pub descriptors: Vec<u8>,
}

impl PmtStream {
    /// Iterate per-elementary-stream descriptors as typed TLV records.
    /// See [`crate::descriptor::iter_descriptors`].
    pub fn iter_descriptors(&self) -> DescriptorIter<'_> {
        iter_descriptors(&self.descriptors)
    }
}

/// Parsed Program Map Table for one program.
#[derive(Debug, Default, Clone)]
pub struct ProgramMapTable {
    /// Program number this PMT serves (from `table_id_extension`).
    pub program_number: u16,
    /// 5-bit `version_number`.
    pub version_number: u8,
    /// `current_next_indicator`.
    pub current_next_indicator: bool,
    /// PID carrying the program's PCR (13 bits).
    pub pcr_pid: u16,
    /// Raw `program_info` descriptor bytes (length given by
    /// `program_info_length`).
    pub program_info: Vec<u8>,
    /// Per-stream descriptors keyed by `elementary_pid`.
    pub streams: Vec<PmtStream>,
}

impl ProgramMapTable {
    /// Iterate the program-wide descriptors carried in `program_info`
    /// as typed TLV records. See
    /// [`crate::descriptor::iter_descriptors`].
    pub fn iter_program_descriptors(&self) -> DescriptorIter<'_> {
        iter_descriptors(&self.program_info)
    }

    /// Parse a single PMT section. The slice must run from
    /// `table_id` through the CRC trailer.
    pub fn parse(section: &[u8]) -> Result<Self, TsError> {
        let (hdr, body) = parse_section_header(section, PMT_TABLE_ID)?;
        if body.len() < 4 {
            return Err(TsError::Truncated {
                what: "PMT body",
                have: body.len(),
                need: 4,
            });
        }
        let pcr_pid = u16::from_be_bytes([body[0] & 0b0001_1111, body[1]]);
        let program_info_length = (u16::from_be_bytes([body[2] & 0b0000_1111, body[3]])) as usize;
        let after_pcr: usize = 4;
        let pi_end =
            after_pcr
                .checked_add(program_info_length)
                .ok_or(TsError::SectionLengthOverrun {
                    claimed: program_info_length,
                    have: body.len() - after_pcr,
                })?;
        if pi_end > body.len() {
            return Err(TsError::SectionLengthOverrun {
                claimed: program_info_length,
                have: body.len() - after_pcr,
            });
        }
        let program_info = body[after_pcr..pi_end].to_vec();

        let mut streams = Vec::new();
        let mut i = pi_end;
        while i + 5 <= body.len() {
            let stream_type = body[i];
            let elementary_pid = u16::from_be_bytes([body[i + 1] & 0b0001_1111, body[i + 2]]);
            let es_info_length =
                (u16::from_be_bytes([body[i + 3] & 0b0000_1111, body[i + 4]])) as usize;
            let descr_start = i + 5;
            let descr_end =
                descr_start
                    .checked_add(es_info_length)
                    .ok_or(TsError::SectionLengthOverrun {
                        claimed: es_info_length,
                        have: body.len() - descr_start,
                    })?;
            if descr_end > body.len() {
                return Err(TsError::SectionLengthOverrun {
                    claimed: es_info_length,
                    have: body.len() - descr_start,
                });
            }
            let descriptors = body[descr_start..descr_end].to_vec();
            streams.push(PmtStream {
                stream_type,
                elementary_pid,
                descriptors,
            });
            i = descr_end;
        }
        Ok(Self {
            program_number: hdr.table_id_extension,
            version_number: hdr.version_number,
            current_next_indicator: hdr.current_next_indicator,
            pcr_pid,
            program_info,
            streams,
        })
    }
}

/// Parsed Conditional Access Table per §2.4.4.6 / Table 2-27.
///
/// The CAT carries the program-wide CA descriptor block — one or more
/// CA_descriptors (§2.6.16) keyed by `CA_system_ID` that point at the
/// EMM PIDs. The CAT is signalled on the fixed PID `CAT_PID` and uses
/// `table_id == CAT_TABLE_ID`. Like PAT and PMT it may be segmented
/// across multiple sections, all of which share `table_id_extension`
/// (reserved; not used to identify a CAT).
#[derive(Debug, Default, Clone)]
pub struct ConditionalAccessTable {
    /// 5-bit `version_number`.
    pub version_number: u8,
    /// `current_next_indicator`.
    pub current_next_indicator: bool,
    /// `section_number`.
    pub section_number: u8,
    /// `last_section_number`.
    pub last_section_number: u8,
    /// Raw bytes of the descriptor() loop carried in the CAT body —
    /// walk with [`Self::iter_descriptors`] to get typed CA entries.
    pub descriptors: Vec<u8>,
}

impl ConditionalAccessTable {
    /// Parse a single CAT section. The slice must run from `table_id`
    /// through the CRC trailer (i.e. the pointer_field has already
    /// been skipped).
    pub fn parse(section: &[u8]) -> Result<Self, TsError> {
        let (hdr, body) = parse_section_header(section, CAT_TABLE_ID)?;
        Ok(Self {
            version_number: hdr.version_number,
            current_next_indicator: hdr.current_next_indicator,
            section_number: hdr.section_number,
            last_section_number: hdr.last_section_number,
            descriptors: body.to_vec(),
        })
    }

    /// Walk the carried descriptor() loop as typed TLV records.
    pub fn iter_descriptors(&self) -> DescriptorIter<'_> {
        iter_descriptors(&self.descriptors)
    }
}

/// Parsed Transport Stream Description Table per §2.4.4.12 /
/// Table 2-30-1.
///
/// The TSDT is optional. When present it is carried on the fixed PID
/// [`TSDT_PID`] (`0x0002`) with `table_id == TSDT_TABLE_ID` (`0x03`)
/// and carries a single `descriptor()` loop (§2.6) that applies to the
/// **entire** Transport Stream rather than to one program or stream.
/// Structurally it mirrors the CAT: the long-form section header
/// (`table_id` … `last_section_number`), then a run of descriptors,
/// then the CRC. The 16 bits at byte offsets 3–4 are reserved per the
/// `reserved (18 bits)` field of Table 2-30-1 and carry no
/// `table_id_extension` meaning; like the CAT they are ignored on
/// parse. Sections may be segmented across the [`TSDT_PID`] stream and
/// reassembled with [`PsiSectionAssembler`] before parsing.
#[derive(Debug, Default, Clone)]
pub struct TransportStreamDescriptionTable {
    /// 5-bit `version_number`.
    pub version_number: u8,
    /// `current_next_indicator`.
    pub current_next_indicator: bool,
    /// `section_number`.
    pub section_number: u8,
    /// `last_section_number`.
    pub last_section_number: u8,
    /// Raw bytes of the descriptor() loop carried in the TSDT body —
    /// walk with [`Self::iter_descriptors`] to get typed records.
    pub descriptors: Vec<u8>,
}

impl TransportStreamDescriptionTable {
    /// Parse a single TSDT section. The slice must run from `table_id`
    /// through the CRC trailer (i.e. the pointer_field has already been
    /// skipped).
    pub fn parse(section: &[u8]) -> Result<Self, TsError> {
        let (hdr, body) = parse_section_header(section, TSDT_TABLE_ID)?;
        Ok(Self {
            version_number: hdr.version_number,
            current_next_indicator: hdr.current_next_indicator,
            section_number: hdr.section_number,
            last_section_number: hdr.last_section_number,
            descriptors: body.to_vec(),
        })
    }

    /// Walk the carried descriptor() loop as typed TLV records.
    pub fn iter_descriptors(&self) -> DescriptorIter<'_> {
        iter_descriptors(&self.descriptors)
    }
}

/// Running status of a service (ETSI EN 300 468 §5.2.3 Table 6).
///
/// A 3-bit field; values 6 and 7 are reserved and surface as
/// [`RunningStatus::Reserved`] preserving the raw value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunningStatus {
    /// `0` — undefined.
    Undefined,
    /// `1` — not running.
    NotRunning,
    /// `2` — starts in a few seconds (e.g. for video recording).
    StartsSoon,
    /// `3` — pausing.
    Pausing,
    /// `4` — running.
    Running,
    /// `5` — service off-air.
    OffAir,
    /// `6`–`7` — reserved for future use; raw value preserved.
    Reserved(u8),
}

impl RunningStatus {
    /// Map the 3-bit wire value to a typed status.
    pub fn from_bits(value: u8) -> Self {
        match value & 0b0000_0111 {
            0 => RunningStatus::Undefined,
            1 => RunningStatus::NotRunning,
            2 => RunningStatus::StartsSoon,
            3 => RunningStatus::Pausing,
            4 => RunningStatus::Running,
            5 => RunningStatus::OffAir,
            other => RunningStatus::Reserved(other),
        }
    }
}

/// One service entry from the SDT service loop (ETSI EN 300 468
/// §5.2.3 Table 5).
#[derive(Debug, Clone)]
pub struct SdtService {
    /// 16-bit `service_id` — equals the corresponding PMT
    /// `program_number` for normal services.
    pub service_id: u16,
    /// `EIT_schedule_flag` — EIT schedule info present in this TS.
    pub eit_schedule_flag: bool,
    /// `EIT_present_following_flag` — EIT present/following info present.
    pub eit_present_following_flag: bool,
    /// 3-bit `running_status` (Table 6).
    pub running_status: RunningStatus,
    /// `free_CA_mode` — when `false` every component stream is
    /// unscrambled; when `true` one or more streams may be CA-controlled.
    pub free_ca_mode: bool,
    /// Raw bytes of this service's `descriptor()` loop — walk with
    /// [`Self::iter_descriptors`]. The DVB `service_descriptor`
    /// (tag `0x48`) carried here decodes the service / provider names.
    pub descriptors: Vec<u8>,
}

impl SdtService {
    /// Walk this service's descriptor loop as typed TLV records.
    pub fn iter_descriptors(&self) -> DescriptorIter<'_> {
        iter_descriptors(&self.descriptors)
    }
}

/// Parsed DVB Service Description Table (ETSI EN 300 468 §5.2.3
/// Table 5).
///
/// The SDT is a DVB Service Information table carried on the fixed PID
/// [`SDT_PID`] (`0x0011`). Sections describing the **actual** TS use
/// `table_id == SDT_ACTUAL_TABLE_ID` (`0x42`); sections describing
/// **other** TSs use `SDT_OTHER_TABLE_ID` (`0x46`). It shares the
/// 8-byte long-form PSI section header (parsed and CRC-verified the
/// same way as PAT/PMT), then carries `original_network_id` (16 bits)
/// plus one reserved byte, then a loop of [`SdtService`] entries, then
/// the CRC.
///
/// `transport_stream_id` is taken from the `table_id_extension` slot
/// per §5.2.3. The service loop's per-service descriptor blocks most
/// commonly carry the DVB `service_descriptor` (tag `0x48`), which the
/// crate's descriptor decoder lifts into
/// [`crate::descriptor::ServiceDescriptor`] — the source of a service's
/// human-readable name and provider.
#[derive(Debug, Default, Clone)]
pub struct ServiceDescriptionTable {
    /// `transport_stream_id` (from `table_id_extension`).
    pub transport_stream_id: u16,
    /// `true` when the section's `table_id` was `0x46` (describes another
    /// TS); `false` for `0x42` (the actual TS carrying the SDT).
    pub other_transport_stream: bool,
    /// 5-bit `version_number`.
    pub version_number: u8,
    /// `current_next_indicator`.
    pub current_next_indicator: bool,
    /// `section_number`.
    pub section_number: u8,
    /// `last_section_number`.
    pub last_section_number: u8,
    /// `original_network_id`.
    pub original_network_id: u16,
    /// Service entries carried in this section.
    pub services: Vec<SdtService>,
}

impl ServiceDescriptionTable {
    /// Parse a single SDT section. The slice must run from `table_id`
    /// through the CRC trailer (i.e. the pointer_field has already been
    /// skipped). Accepts both the actual-TS (`0x42`) and other-TS
    /// (`0x46`) table_ids.
    pub fn parse(section: &[u8]) -> Result<Self, TsError> {
        let table_id = section.first().copied().unwrap_or(0);
        let other_transport_stream = match table_id {
            SDT_ACTUAL_TABLE_ID => false,
            SDT_OTHER_TABLE_ID => true,
            _ => {
                return Err(TsError::Unsupported(
                    "PSI table_id does not match expected value",
                ))
            }
        };
        let (hdr, body) = parse_section_header(section, table_id)?;
        // Body layout (Table 5): original_network_id (16) +
        // reserved_future_use (8) + service loop.
        if body.len() < 3 {
            return Err(TsError::Truncated {
                what: "SDT body",
                have: body.len(),
                need: 3,
            });
        }
        let original_network_id = u16::from_be_bytes([body[0], body[1]]);
        // body[2] is reserved_future_use.
        let mut services = Vec::new();
        let mut i = 3;
        // Each service entry: service_id (16) + flags/running_status/
        // free_CA_mode (8) + descriptors_length (12, top 4 of next byte)
        // + descriptor loop. Fixed head = 5 bytes before descriptors.
        while i + 5 <= body.len() {
            let service_id = u16::from_be_bytes([body[i], body[i + 1]]);
            let b = body[i + 2];
            let eit_schedule_flag = (b & 0b0000_0010) != 0;
            let eit_present_following_flag = (b & 0b0000_0001) != 0;
            let b3 = body[i + 3];
            let running_status = RunningStatus::from_bits(b3 >> 5);
            let free_ca_mode = (b3 & 0b0001_0000) != 0;
            let descriptors_length = (u16::from_be_bytes([b3 & 0b0000_1111, body[i + 4]])) as usize;
            let descr_start = i + 5;
            let descr_end = descr_start.checked_add(descriptors_length).ok_or(
                TsError::SectionLengthOverrun {
                    claimed: descriptors_length,
                    have: body.len() - descr_start,
                },
            )?;
            if descr_end > body.len() {
                return Err(TsError::SectionLengthOverrun {
                    claimed: descriptors_length,
                    have: body.len() - descr_start,
                });
            }
            services.push(SdtService {
                service_id,
                eit_schedule_flag,
                eit_present_following_flag,
                running_status,
                free_ca_mode,
                descriptors: body[descr_start..descr_end].to_vec(),
            });
            i = descr_end;
        }
        Ok(Self {
            transport_stream_id: hdr.table_id_extension,
            other_transport_stream,
            version_number: hdr.version_number,
            current_next_indicator: hdr.current_next_indicator,
            section_number: hdr.section_number,
            last_section_number: hdr.last_section_number,
            original_network_id,
            services,
        })
    }
}

/// A calendar date + wall-clock time decoded from an EIT 40-bit
/// `start_time` field (ETSI EN 300 468 §5.2.4 / annex C).
///
/// On the wire the field is 16 bits of Modified Julian Date (the 16
/// least-significant bits of the MJD) followed by 24 bits of 6-digit
/// 4-bit BCD encoding the UTC hours/minutes/seconds. The date portion
/// is converted to the proleptic Gregorian `(year, month, day)` using
/// the integer formula in annex C; the time portion is the decoded BCD.
///
/// When every bit of the 40-bit field is set (`0xFF_FFFF_FFFF`) the
/// start time is *undefined* (e.g. for an NVOD reference event) and the
/// parser yields `None` rather than a bogus date.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EitDateTime {
    /// Full Gregorian year (e.g. `2003`), reconstructed from the 16-bit
    /// MJD plus the annex-C `Y = year − 1900` intermediate.
    pub year: u16,
    /// Month, 1 (January) through 12 (December).
    pub month: u8,
    /// Day of month, 1 through 31.
    pub day: u8,
    /// UTC hour, 0 through 23 (decoded from BCD; not range-clamped).
    pub hour: u8,
    /// UTC minute, 0 through 59 (decoded from BCD; not range-clamped).
    pub minute: u8,
    /// UTC second, 0 through 59 (decoded from BCD; not range-clamped).
    pub second: u8,
    /// The raw 16-bit MJD value, preserved for callers that prefer to do
    /// their own date arithmetic.
    pub mjd: u16,
}

/// An event duration decoded from an EIT 24-bit `duration` field
/// (ETSI EN 300 468 §5.2.4) — 6 digits of 4-bit BCD giving hours,
/// minutes, and seconds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct EitDuration {
    /// Hours component (BCD-decoded; may exceed 24 for long events).
    pub hours: u8,
    /// Minutes component (BCD-decoded, 0–59).
    pub minutes: u8,
    /// Seconds component (BCD-decoded, 0–59).
    pub seconds: u8,
}

impl EitDuration {
    /// Total duration expressed in whole seconds.
    pub fn as_seconds(&self) -> u32 {
        (self.hours as u32) * 3600 + (self.minutes as u32) * 60 + (self.seconds as u32)
    }
}

/// Decode one 4-bit-BCD byte into its 0–99 integer value.
fn bcd_byte(b: u8) -> u8 {
    (b >> 4) * 10 + (b & 0x0F)
}

/// Decode the 40-bit EIT `start_time` (16-bit MJD + 24-bit BCD time).
///
/// Returns `None` when the field is the all-ones "undefined" sentinel.
/// The MJD→(Y,M,D) conversion follows the integer formula in
/// ETSI EN 300 468 annex C:
///
/// ```text
/// Y' = int((MJD − 15078,2) / 365,25)
/// M' = int((MJD − 14956,1 − int(Y' × 365,25)) / 30,6001)
/// D  = MJD − 14956 − int(Y' × 365,25) − int(M' × 30,6001)
/// K  = 1 if M' == 14 or M' == 15 else 0
/// Y  = Y' + K                 (years since 1900)
/// M  = M' − 1 − K × 12
/// ```
fn decode_eit_start_time(bytes: [u8; 5]) -> Option<EitDateTime> {
    if bytes == [0xFF, 0xFF, 0xFF, 0xFF, 0xFF] {
        return None;
    }
    let mjd = u16::from_be_bytes([bytes[0], bytes[1]]);
    // Annex C integer arithmetic. The constants 365,25 and 30,6001 are
    // applied via scaled integer multiplication to avoid floating point:
    // int(Y' × 365,25) == (Y' × 36525) / 100, etc.
    let mjd_i = mjd as i64;
    let yp = ((mjd_i - 15078) * 100 - 20) / 36525; // int((MJD − 15078,2)/365,25)
    let yp_days = (yp * 36525) / 100; // int(Y' × 365,25)
                                      // int((MJD − 14956,1 − yp_days)/30,6001)
    let mp = ((mjd_i - 14956 - yp_days) * 10000 - 1) / 306001;
    let mp_days = (mp * 306001) / 10000; // int(M' × 30,6001)
    let d = mjd_i - 14956 - yp_days - mp_days;
    let k: i64 = if mp == 14 || mp == 15 { 1 } else { 0 };
    let y = yp + k;
    let m = mp - 1 - k * 12;
    let year = (1900 + y) as u16;
    let month = m as u8;
    let day = d as u8;
    let hour = bcd_byte(bytes[2]);
    let minute = bcd_byte(bytes[3]);
    let second = bcd_byte(bytes[4]);
    Some(EitDateTime {
        year,
        month,
        day,
        hour,
        minute,
        second,
        mjd,
    })
}

/// One event entry from the EIT event loop (ETSI EN 300 468 §5.2.4
/// Table 7).
#[derive(Debug, Clone)]
pub struct EitEvent {
    /// 16-bit `event_id`, unique within a service.
    pub event_id: u16,
    /// Decoded `start_time` — `None` when the field was the all-ones
    /// "undefined" sentinel (e.g. for an NVOD reference event).
    pub start_time: Option<EitDateTime>,
    /// Decoded `duration` (BCD hours/minutes/seconds).
    pub duration: EitDuration,
    /// 3-bit `running_status` (Table 6).
    pub running_status: RunningStatus,
    /// `free_CA_mode` — `false` when every component stream of the event
    /// is unscrambled; `true` when one or more may be CA-controlled.
    pub free_ca_mode: bool,
    /// Raw bytes of this event's `descriptor()` loop — walk with
    /// [`Self::iter_descriptors`]. The DVB `short_event_descriptor`
    /// (tag `0x4D`) carried here decodes the event name + short text.
    pub descriptors: Vec<u8>,
}

impl EitEvent {
    /// Walk this event's descriptor loop as typed TLV records.
    pub fn iter_descriptors(&self) -> DescriptorIter<'_> {
        iter_descriptors(&self.descriptors)
    }
}

/// Parsed DVB Event Information Table (ETSI EN 300 468 §5.2.4 Table 7).
///
/// The EIT carries chronological per-event metadata (start time,
/// duration, running status, descriptors) for the services in a
/// multiplex. It is carried on the fixed PID [`EIT_PID`] (`0x0012`) and
/// distinguished from other tables by `table_id`:
///
/// * `0x4E` — present/following events on the **actual** TS.
/// * `0x4F` — present/following events on **other** TSs.
/// * `0x50`–`0x5F` — event schedule on the actual TS.
/// * `0x60`–`0x6F` — event schedule on other TSs.
///
/// The section shares the 8-byte long-form PSI header (CRC-verified the
/// same way as PAT/PMT/SDT) where `service_id` lives in the
/// `table_id_extension` slot. After the header the body carries
/// `transport_stream_id` (16) + `original_network_id` (16) +
/// `segment_last_section_number` (8) + `last_table_id` (8), then a loop
/// of [`EitEvent`] entries, then the CRC.
///
/// The `service_id` equals the corresponding PMT `program_number` for
/// normal services, so an EIT lets the `oxideav remux bluray://` path
/// attach human-readable event names (via the per-event
/// `short_event_descriptor`) and time ranges to each program.
#[derive(Debug, Default, Clone)]
pub struct EventInformationTable {
    /// `service_id` (from `table_id_extension`).
    pub service_id: u16,
    /// `true` when the section describes other TSs (`table_id` `0x4F`
    /// or `0x60`–`0x6F`); `false` for the actual TS (`0x4E` /
    /// `0x50`–`0x5F`).
    pub other_transport_stream: bool,
    /// `true` when the section is event-schedule information
    /// (`0x50`–`0x6F`); `false` for present/following (`0x4E` / `0x4F`).
    pub schedule: bool,
    /// Raw `table_id` of the parsed section.
    pub table_id: u8,
    /// 5-bit `version_number`.
    pub version_number: u8,
    /// `current_next_indicator`.
    pub current_next_indicator: bool,
    /// `section_number`.
    pub section_number: u8,
    /// `last_section_number`.
    pub last_section_number: u8,
    /// `transport_stream_id`.
    pub transport_stream_id: u16,
    /// `original_network_id`.
    pub original_network_id: u16,
    /// `segment_last_section_number` — last section of this segment of
    /// the sub_table (equals `last_section_number` for unsegmented
    /// sub_tables).
    pub segment_last_section_number: u8,
    /// `last_table_id` — the largest `table_id` used by this service's
    /// sub_table (per §5.2.4 may differ per service).
    pub last_table_id: u8,
    /// Event entries carried in this section, in chronological order.
    pub events: Vec<EitEvent>,
}

impl EventInformationTable {
    /// `true` when `table_id` is any of the four EIT classifications
    /// (`0x4E`, `0x4F`, `0x50`–`0x5F`, `0x60`–`0x6F`).
    pub fn is_eit_table_id(table_id: u8) -> bool {
        matches!(table_id, EIT_ACTUAL_PF_TABLE_ID | EIT_OTHER_PF_TABLE_ID)
            || (EIT_ACTUAL_SCHEDULE_FIRST..=EIT_ACTUAL_SCHEDULE_LAST).contains(&table_id)
            || (EIT_OTHER_SCHEDULE_FIRST..=EIT_OTHER_SCHEDULE_LAST).contains(&table_id)
    }

    /// Parse a single EIT section. The slice must run from `table_id`
    /// through the CRC trailer (i.e. the pointer_field has already been
    /// skipped). Accepts any of the four EIT `table_id` classifications.
    pub fn parse(section: &[u8]) -> Result<Self, TsError> {
        let table_id = section.first().copied().unwrap_or(0);
        if !Self::is_eit_table_id(table_id) {
            return Err(TsError::Unsupported(
                "PSI table_id does not match expected value",
            ));
        }
        let other_transport_stream = table_id == EIT_OTHER_PF_TABLE_ID
            || (EIT_OTHER_SCHEDULE_FIRST..=EIT_OTHER_SCHEDULE_LAST).contains(&table_id);
        let schedule = (EIT_ACTUAL_SCHEDULE_FIRST..=EIT_OTHER_SCHEDULE_LAST).contains(&table_id);
        let (hdr, body) = parse_section_header(section, table_id)?;
        // Body layout (Table 7): transport_stream_id (16) +
        // original_network_id (16) + segment_last_section_number (8) +
        // last_table_id (8), then the event loop.
        if body.len() < 6 {
            return Err(TsError::Truncated {
                what: "EIT body",
                have: body.len(),
                need: 6,
            });
        }
        let transport_stream_id = u16::from_be_bytes([body[0], body[1]]);
        let original_network_id = u16::from_be_bytes([body[2], body[3]]);
        let segment_last_section_number = body[4];
        let last_table_id = body[5];
        let mut events = Vec::new();
        let mut i = 6;
        // Each event entry: event_id (16) + start_time (40) +
        // duration (24) + running_status (3) / free_CA_mode (1) /
        // descriptors_length (12). Fixed head = 12 bytes before the
        // descriptor loop.
        while i + 12 <= body.len() {
            let event_id = u16::from_be_bytes([body[i], body[i + 1]]);
            let start_time = decode_eit_start_time([
                body[i + 2],
                body[i + 3],
                body[i + 4],
                body[i + 5],
                body[i + 6],
            ]);
            let duration = EitDuration {
                hours: bcd_byte(body[i + 7]),
                minutes: bcd_byte(body[i + 8]),
                seconds: bcd_byte(body[i + 9]),
            };
            let b10 = body[i + 10];
            let running_status = RunningStatus::from_bits(b10 >> 5);
            let free_ca_mode = (b10 & 0b0001_0000) != 0;
            let descriptors_length =
                (u16::from_be_bytes([b10 & 0b0000_1111, body[i + 11]])) as usize;
            let descr_start = i + 12;
            let descr_end = descr_start.checked_add(descriptors_length).ok_or(
                TsError::SectionLengthOverrun {
                    claimed: descriptors_length,
                    have: body.len() - descr_start,
                },
            )?;
            if descr_end > body.len() {
                return Err(TsError::SectionLengthOverrun {
                    claimed: descriptors_length,
                    have: body.len() - descr_start,
                });
            }
            events.push(EitEvent {
                event_id,
                start_time,
                duration,
                running_status,
                free_ca_mode,
                descriptors: body[descr_start..descr_end].to_vec(),
            });
            i = descr_end;
        }
        Ok(Self {
            service_id: hdr.table_id_extension,
            other_transport_stream,
            schedule,
            table_id,
            version_number: hdr.version_number,
            current_next_indicator: hdr.current_next_indicator,
            section_number: hdr.section_number,
            last_section_number: hdr.last_section_number,
            transport_stream_id,
            original_network_id,
            segment_last_section_number,
            last_table_id,
            events,
        })
    }
}

/// Per-PID PSI section reassembler — joins TS payloads carrying the
/// same `table_id` across multiple 188-byte TS packets per §2.4.4.
///
/// Real PMTs that carry many ES_descriptors (e.g. an HEVC + multi-
/// language audio + multi-language PGS Blu-ray title) routinely run
/// past one TS packet's ~184-byte payload budget. The spec carries
/// the overflow into the next same-PID packet whose
/// `payload_unit_start_indicator == 0`; the assembler concatenates
/// those continuation payloads onto the in-flight section until
/// `3 + section_length` bytes have been collected, then yields the
/// completed section as a borrow over the internal buffer.
///
/// Wire rules enforced (§2.4.4 / §2.4.4.1):
///
/// * A PUSI=1 TS payload starts with a `pointer_field`. The bytes
///   from the byte immediately following `pointer_field` for
///   `pointer_field` bytes complete the previous in-flight section,
///   then the next section begins. A `pointer_field == 0` means the
///   first section starts immediately after the pointer.
/// * A PUSI=0 TS payload contains continuation bytes for the section
///   in flight at the end of the previous same-PID packet.
/// * `0xFF` table_id terminates section iteration inside a single TS
///   payload (stuffing bytes after a section).
/// * The 4-bit `continuity_counter` advances by +1 (mod 16) between
///   payload-carrying same-PID packets. A skipped count (per
///   §2.4.3.3) discards the in-flight buffer rather than blindly
///   concatenating misordered bytes — the next PUSI=1 packet rebuilds
///   from scratch.
///
/// The assembler is `table_id`-agnostic — it yields raw section bytes
/// and leaves CRC verification + table parsing to the caller (the
/// `Parse::parse` methods on [`ProgramAssociationTable`],
/// [`ProgramMapTable`], and [`ConditionalAccessTable`] each verify
/// CRC-32/MPEG-2 themselves). Sections that exceed
/// [`MAX_PSI_SECTION_LEN`] are dropped with [`TsError::SectionLengthOverrun`].
#[derive(Debug, Default)]
pub struct PsiSectionAssembler {
    /// Bytes of the section being assembled, including the 3-byte
    /// length-bearing header (table_id + 12-bit section_length).
    in_flight: Vec<u8>,
    /// Total length of `in_flight` once complete (= 3 + section_length).
    /// `None` until the first 3 bytes have been collected.
    target_len: Option<usize>,
    /// Last `continuity_counter` observed for the assembler's PID.
    /// `None` until the first TS packet has been fed. Used to detect a
    /// CC skip that invalidates the in-flight buffer.
    last_cc: Option<u8>,
}

impl PsiSectionAssembler {
    /// Create an empty assembler.
    pub fn new() -> Self {
        Self::default()
    }

    /// Drop any in-flight section bytes — used when the caller knows
    /// the underlying PID just signalled a `discontinuity_indicator`
    /// (§2.4.3.5) or the input stream restarted.
    pub fn reset(&mut self) {
        self.in_flight.clear();
        self.target_len = None;
        self.last_cc = None;
    }

    /// Feed one TS-packet payload to the assembler.
    ///
    /// * `payload` is the TS packet's payload bytes (after the
    ///   adaptation field has been stripped) — the same byte slice
    ///   `iter_sections` would consume on a single-payload section.
    /// * `pusi` is the value of the TS packet's
    ///   `payload_unit_start_indicator`.
    /// * `continuity_counter` is the 4-bit field from the TS packet's
    ///   byte-3 low nibble — used to detect a dropped same-PID packet
    ///   that would corrupt the in-flight section if blindly
    ///   concatenated.
    ///
    /// Returns every complete section gathered by this call (a single
    /// payload can carry many short sections, or finish off one
    /// section and start another). Each yielded `Vec<u8>` runs from
    /// `table_id` through the CRC trailer — exactly what
    /// [`ProgramAssociationTable::parse`] /
    /// [`ProgramMapTable::parse`] / [`ConditionalAccessTable::parse`]
    /// expect.
    pub fn feed(
        &mut self,
        payload: &[u8],
        pusi: bool,
        continuity_counter: u8,
    ) -> Result<Vec<Vec<u8>>, TsError> {
        // CC continuity check — the 4-bit field wraps mod 16. A skip
        // means we missed a same-PID payload; the in-flight section
        // is no longer trustable, so drop it and resume on the next
        // PUSI=1 packet.
        let cc = continuity_counter & 0x0F;
        if let Some(prev) = self.last_cc {
            let expected = (prev + 1) & 0x0F;
            if cc != expected {
                // CC skip — discard buffer.
                self.in_flight.clear();
                self.target_len = None;
            }
        }
        self.last_cc = Some(cc);

        let mut out = Vec::new();
        let mut rest: &[u8] = payload;

        if pusi {
            // pointer_field = first byte of the payload (§2.4.4.1).
            if rest.is_empty() {
                return Ok(out);
            }
            let ptr = rest[0] as usize;
            rest = &rest[1..];
            if ptr > rest.len() {
                // Pointer overruns the payload — corrupt header, drop
                // whatever was in flight and stop.
                self.in_flight.clear();
                self.target_len = None;
                return Ok(out);
            }
            let (tail_of_prev, after_ptr) = rest.split_at(ptr);
            // `tail_of_prev` finishes the previous in-flight section
            // (when there was one). It may be padded with 0xFF
            // stuffing if no continuation was due — both cases share
            // the same "extend then check completion" path.
            if !self.in_flight.is_empty() || self.target_len.is_some() {
                if let Some(section) = self.extend_in_flight(tail_of_prev)? {
                    out.push(section);
                }
                // If the in-flight section isn't done after consuming
                // `tail_of_prev`, drop it: a PUSI=1 packet promises a
                // fresh section is about to begin, so the previous
                // section can't be straddled further into this
                // packet.
                self.in_flight.clear();
                self.target_len = None;
            }
            rest = after_ptr;
        } else if self.target_len.is_none() {
            // PUSI=0 with nothing in flight — payload bytes belong to
            // a section that started before we attached. Skip.
            return Ok(out);
        } else {
            // PUSI=0 continuation — every payload byte feeds the
            // in-flight section.
            if let Some(section) = self.extend_in_flight(rest)? {
                out.push(section);
            }
            return Ok(out);
        }

        // After pointer_field handling, `rest` points at one-or-more
        // freshly-starting sections. Each begins with a 3-byte
        // length-bearing header; 0xFF is a stuffing terminator.
        while !rest.is_empty() {
            if rest[0] == 0xFF {
                // Stuffing — rest of payload is filler.
                break;
            }
            if rest.len() < 3 {
                // Header straddles into the next TS packet — buffer
                // what we have and wait for the continuation.
                self.in_flight.extend_from_slice(rest);
                self.target_len = None;
                break;
            }
            let section_length =
                ((((rest[1] & 0b0000_1111) as usize) << 8) | (rest[2] as usize)) & 0x0FFF;
            let total = 3 + section_length;
            if total > MAX_PSI_SECTION_LEN {
                self.in_flight.clear();
                self.target_len = None;
                return Err(TsError::SectionLengthOverrun {
                    claimed: section_length,
                    have: rest.len() - 3,
                });
            }
            if rest.len() >= total {
                // Section fits entirely within this payload — emit
                // and advance.
                out.push(rest[..total].to_vec());
                rest = &rest[total..];
            } else {
                // Section straddles into next TS packet — buffer.
                self.in_flight.clear();
                self.in_flight.extend_from_slice(rest);
                self.target_len = Some(total);
                break;
            }
        }

        Ok(out)
    }

    /// Extend the in-flight section with `bytes`. If the section
    /// completes, return it (and clear the buffer). Returns `Ok(None)`
    /// when more bytes are still needed.
    fn extend_in_flight(&mut self, bytes: &[u8]) -> Result<Option<Vec<u8>>, TsError> {
        if bytes.is_empty() {
            return Ok(None);
        }
        // If we don't yet have a target_len, we're still gathering the
        // 3-byte length-bearing header.
        if self.target_len.is_none() {
            let want = 3usize.saturating_sub(self.in_flight.len());
            let take = want.min(bytes.len());
            self.in_flight.extend_from_slice(&bytes[..take]);
            if self.in_flight.len() < 3 {
                return Ok(None);
            }
            let section_length = ((((self.in_flight[1] & 0b0000_1111) as usize) << 8)
                | (self.in_flight[2] as usize))
                & 0x0FFF;
            let total = 3 + section_length;
            if total > MAX_PSI_SECTION_LEN {
                self.in_flight.clear();
                self.target_len = None;
                return Err(TsError::SectionLengthOverrun {
                    claimed: section_length,
                    have: bytes.len() - take,
                });
            }
            self.target_len = Some(total);
            // Recurse on the remainder past the header bytes.
            return self.extend_in_flight(&bytes[take..]);
        }
        let target = self.target_len.expect("checked above");
        let want = target.saturating_sub(self.in_flight.len());
        let take = want.min(bytes.len());
        self.in_flight.extend_from_slice(&bytes[..take]);
        if self.in_flight.len() < target {
            return Ok(None);
        }
        // Section complete.
        let done = std::mem::take(&mut self.in_flight);
        self.target_len = None;
        Ok(Some(done))
    }
}

/// Shared header parse — verifies sync, length, CRC.
struct SectionHeader {
    table_id_extension: u16,
    version_number: u8,
    current_next_indicator: bool,
    section_number: u8,
    last_section_number: u8,
}

fn parse_section_header(
    section: &[u8],
    expected_table_id: u8,
) -> Result<(SectionHeader, &[u8]), TsError> {
    if section.len() < SECTION_HEADER_LEN + SECTION_CRC_LEN {
        return Err(TsError::Truncated {
            what: "PSI section header",
            have: section.len(),
            need: SECTION_HEADER_LEN + SECTION_CRC_LEN,
        });
    }
    let table_id = section[0];
    if table_id != expected_table_id {
        return Err(TsError::Unsupported(
            "PSI table_id does not match expected value",
        ));
    }
    let b1 = section[1];
    let b2 = section[2];
    // section_length is 12 bits across the bottom 4 of b1 + b2.
    let section_length = ((((b1 & 0b0000_1111) as usize) << 8) | (b2 as usize)) & 0x0FFF;

    // section_length counts bytes after itself — i.e. from `section[3]`
    // through the CRC. So total section size = 3 + section_length.
    let total = 3 + section_length;
    if total > section.len() {
        return Err(TsError::SectionLengthOverrun {
            claimed: section_length,
            have: section.len() - 3,
        });
    }
    let section = &section[..total];

    // Verify the MPEG-2 CRC over [section_start .. section_end - 4].
    let crc_pos = total - SECTION_CRC_LEN;
    let computed = mpeg2_crc32(&section[..crc_pos]);
    let header_crc = u32::from_be_bytes([
        section[crc_pos],
        section[crc_pos + 1],
        section[crc_pos + 2],
        section[crc_pos + 3],
    ]);
    if computed != header_crc {
        return Err(TsError::PsiCrcMismatch {
            header: header_crc,
            computed,
        });
    }

    let table_id_extension = u16::from_be_bytes([section[3], section[4]]);
    let b5 = section[5];
    let version_number = (b5 >> 1) & 0b0001_1111;
    let current_next_indicator = (b5 & 0b0000_0001) != 0;
    let section_number = section[6];
    let last_section_number = section[7];

    let body = &section[SECTION_HEADER_LEN..crc_pos];
    Ok((
        SectionHeader {
            table_id_extension,
            version_number,
            current_next_indicator,
            section_number,
            last_section_number,
        },
        body,
    ))
}

/// MPEG-2 CRC-32 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB-first, no
/// reflect, no final XOR).
pub fn mpeg2_crc32(bytes: &[u8]) -> u32 {
    let mut crc: u32 = 0xFFFF_FFFF;
    for &b in bytes {
        crc ^= (b as u32) << 24;
        for _ in 0..8 {
            if (crc & 0x8000_0000) != 0 {
                crc = (crc << 1) ^ 0x04C1_1DB7;
            } else {
                crc <<= 1;
            }
        }
    }
    crc
}

/// Iterate the long-form PSI sections carried in one TS-packet payload.
///
/// `ts_payload` is the TS payload bytes (after AF stripping) of a TS
/// packet whose `payload_unit_start_indicator` was set. The first
/// byte is treated as the `pointer_field`. Each successive section is
/// located by reading its `section_length`. Stuffing bytes (`0xFF`
/// table_id) terminate iteration.
///
/// Each yielded slice runs from `table_id` through the CRC trailer.
pub fn iter_sections(ts_payload: &[u8]) -> SectionIter<'_> {
    if ts_payload.is_empty() {
        return SectionIter { rest: &[][..] };
    }
    let ptr = ts_payload[0] as usize;
    let start = 1 + ptr;
    if start > ts_payload.len() {
        return SectionIter { rest: &[][..] };
    }
    SectionIter {
        rest: &ts_payload[start..],
    }
}

/// Iterator returned by [`iter_sections`].
#[derive(Debug)]
pub struct SectionIter<'a> {
    rest: &'a [u8],
}

impl<'a> Iterator for SectionIter<'a> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        // Need at least the 3-byte length-bearing header.
        if self.rest.len() < 3 {
            return None;
        }
        // `0xFF` is the stuffing byte that fills out a section-bearing
        // TS payload.
        if self.rest[0] == 0xFF {
            return None;
        }
        let section_length =
            ((((self.rest[1] & 0b0000_1111) as usize) << 8) | (self.rest[2] as usize)) & 0x0FFF;
        let total = 3 + section_length;
        if total > self.rest.len() {
            return None;
        }
        let (head, tail) = self.rest.split_at(total);
        self.rest = tail;
        Some(head)
    }
}

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

    /// Build a PAT section for a single (program_number, pmt_pid)
    /// pair. Section bytes run from table_id through CRC.
    fn build_pat_section(tsid: u16, version: u8, programs: &[(u16, u16)]) -> Vec<u8> {
        // Body = 4 bytes per program.
        // Section total after section_length = 5 (rest of header) + body + 4 (CRC).
        let body_len = programs.len() * 4;
        let section_length = 5 + body_len + 4;
        let mut s = Vec::with_capacity(3 + section_length);
        s.push(PAT_TABLE_ID);
        // section_syntax_indicator=1, '0', reserved=0b11, then 12-bit
        // length.
        let len_hi = 0b1011_0000 | ((section_length >> 8) & 0x0F) as u8;
        s.push(len_hi);
        s.push((section_length & 0xFF) as u8);
        s.extend_from_slice(&tsid.to_be_bytes());
        // reserved=0b11, version (5), current_next=1.
        s.push(0b1100_0001 | ((version & 0b1_1111) << 1));
        s.push(0); // section_number
        s.push(0); // last_section_number
        for (prog, pid) in programs {
            s.extend_from_slice(&prog.to_be_bytes());
            // reserved=0b111, then 13-bit PID.
            s.push(0b1110_0000 | ((pid >> 8) & 0x1F) as u8);
            s.push((pid & 0xFF) as u8);
        }
        let crc = mpeg2_crc32(&s);
        s.extend_from_slice(&crc.to_be_bytes());
        s
    }

    fn build_pmt_section(
        program_number: u16,
        version: u8,
        pcr_pid: u16,
        program_info: &[u8],
        streams: &[(u8, u16, &[u8])],
    ) -> Vec<u8> {
        // Body = 4 bytes (pcr/program_info_length) + program_info + Σ(5+es_info).
        let body_len: usize =
            4 + program_info.len() + streams.iter().map(|(_, _, d)| 5 + d.len()).sum::<usize>();
        let section_length = 5 + body_len + 4;
        let mut s = Vec::with_capacity(3 + section_length);
        s.push(PMT_TABLE_ID);
        let len_hi = 0b1011_0000 | ((section_length >> 8) & 0x0F) as u8;
        s.push(len_hi);
        s.push((section_length & 0xFF) as u8);
        s.extend_from_slice(&program_number.to_be_bytes());
        s.push(0b1100_0001 | ((version & 0b1_1111) << 1));
        s.push(0);
        s.push(0);
        // PCR_PID
        s.push(0b1110_0000 | ((pcr_pid >> 8) & 0x1F) as u8);
        s.push((pcr_pid & 0xFF) as u8);
        // program_info_length
        let pil = program_info.len() as u16;
        s.push(0b1111_0000 | ((pil >> 8) & 0x0F) as u8);
        s.push((pil & 0xFF) as u8);
        s.extend_from_slice(program_info);
        for (stype, epid, descr) in streams {
            s.push(*stype);
            s.push(0b1110_0000 | ((*epid >> 8) & 0x1F) as u8);
            s.push((*epid & 0xFF) as u8);
            let el = descr.len() as u16;
            s.push(0b1111_0000 | ((el >> 8) & 0x0F) as u8);
            s.push((el & 0xFF) as u8);
            s.extend_from_slice(descr);
        }
        let crc = mpeg2_crc32(&s);
        s.extend_from_slice(&crc.to_be_bytes());
        s
    }

    #[test]
    fn mpeg2_crc32_known_vector() {
        // CRC of the byte "1": MPEG-2 CRC of the ASCII string "1"
        // is 0xA6B15CD4 — easy to confirm with any spec-matching
        // implementation. We assert internal consistency via the
        // round-trip below; this anchors the polynomial wiring.
        let crc = mpeg2_crc32(b"123456789");
        // The classic check value for CRC-32/MPEG-2 over "123456789"
        // is 0x0376E6E7 (see CRC-Catalogue / Greg Cook).
        assert_eq!(crc, 0x0376_E6E7);
    }

    #[test]
    fn pat_one_program_round_trip() {
        let section = build_pat_section(1, 3, &[(1, 0x100)]);
        let pat = ProgramAssociationTable::parse(&section).unwrap();
        assert_eq!(pat.transport_stream_id, 1);
        assert_eq!(pat.version_number, 3);
        assert!(pat.current_next_indicator);
        assert_eq!(pat.programs, vec![(1, 0x100)]);
    }

    #[test]
    fn pmt_avc_ac3_pgs_round_trip() {
        // Stream descriptors: one AVC (0x1B), one AC-3 (0x81), one
        // PGS (0x90), each with a tiny descriptor blob to prove the
        // length/bytes survive.
        let avc_descr: &[u8] = &[0x52, 0x01, 0x00]; // dummy stream_identifier
        let ac3_descr: &[u8] = &[0x6A, 0x01, 0x80];
        let pgs_descr: &[u8] = &[];
        let section = build_pmt_section(
            1,
            5,
            0x100,
            &[],
            &[
                (0x1B, 0x1011, avc_descr),
                (0x81, 0x1100, ac3_descr),
                (0x90, 0x1200, pgs_descr),
            ],
        );
        let pmt = ProgramMapTable::parse(&section).unwrap();
        assert_eq!(pmt.program_number, 1);
        assert_eq!(pmt.version_number, 5);
        assert!(pmt.current_next_indicator);
        assert_eq!(pmt.pcr_pid, 0x100);
        assert!(pmt.program_info.is_empty());
        assert_eq!(pmt.streams.len(), 3);
        assert_eq!(pmt.streams[0].stream_type, 0x1B);
        assert_eq!(pmt.streams[0].elementary_pid, 0x1011);
        assert_eq!(pmt.streams[0].descriptors, avc_descr);
        assert_eq!(pmt.streams[1].stream_type, 0x81);
        assert_eq!(pmt.streams[1].elementary_pid, 0x1100);
        assert_eq!(pmt.streams[1].descriptors, ac3_descr);
        assert_eq!(pmt.streams[2].stream_type, 0x90);
        assert_eq!(pmt.streams[2].elementary_pid, 0x1200);
        assert!(pmt.streams[2].descriptors.is_empty());
    }

    #[test]
    fn psi_crc_corruption_is_rejected() {
        let mut section = build_pat_section(7, 0, &[(1, 0x100)]);
        // Flip a payload bit.
        section[3] ^= 0x01;
        let err = ProgramAssociationTable::parse(&section).unwrap_err();
        match err {
            TsError::PsiCrcMismatch { .. } => {}
            other => panic!("expected PsiCrcMismatch, got {other:?}"),
        }
    }

    #[test]
    fn iter_sections_skips_pointer_field_and_stuffing() {
        let section = build_pat_section(1, 0, &[(1, 0x100)]);
        // Simulate a TS payload: pointer_field=0, then the section,
        // then stuffing.
        let mut payload = Vec::new();
        payload.push(0u8); // pointer_field
        payload.extend_from_slice(&section);
        payload.extend(std::iter::repeat(0xFF).take(10));
        let mut it = iter_sections(&payload);
        let s = it.next().expect("section");
        assert_eq!(s, section);
        assert!(it.next().is_none());
    }

    #[test]
    fn iter_sections_with_nonzero_pointer_field() {
        let section = build_pat_section(1, 0, &[(1, 0x100)]);
        let mut payload = Vec::new();
        payload.push(3u8); // pointer_field = 3
        payload.extend_from_slice(&[0xAA, 0xBB, 0xCC]); // 3 stuffing-ish bytes
        payload.extend_from_slice(&section);
        let s = iter_sections(&payload).next().expect("section");
        assert_eq!(s, section);
    }

    #[test]
    fn pmt_per_stream_descriptors_decode_iso639() {
        // ES descriptor block: an ISO-639 language descriptor with two
        // entries — eng/0, jpn/2.
        let es_descr: &[u8] = &[0x0A, 0x08, b'e', b'n', b'g', 0x00, b'j', b'p', b'n', 0x02];
        let section = build_pmt_section(1, 0, 0x100, &[], &[(0x81, 0x1100, es_descr)]);
        let pmt = ProgramMapTable::parse(&section).unwrap();
        assert_eq!(pmt.streams.len(), 1);
        let descriptors: Vec<_> = pmt.streams[0]
            .iter_descriptors()
            .collect::<Result<_, _>>()
            .unwrap();
        assert_eq!(descriptors.len(), 1);
        assert_eq!(descriptors[0].tag, 0x0A);
        match &descriptors[0].body {
            crate::descriptor::DescriptorBody::Iso639Language(langs) => {
                assert_eq!(langs.len(), 2);
                assert_eq!(&langs[0].language, b"eng");
                assert_eq!(&langs[1].language, b"jpn");
                assert_eq!(langs[1].audio_type, 2);
            }
            other => panic!("expected Iso639Language, got {other:?}"),
        }
    }

    #[test]
    fn pmt_program_info_descriptors_decode_registration() {
        // program_info: registration descriptor with format_identifier=HDMV.
        let program_info: &[u8] = &[0x05, 0x04, b'H', b'D', b'M', b'V'];
        let section = build_pmt_section(1, 0, 0x100, program_info, &[(0x1B, 0x1011, &[])]);
        let pmt = ProgramMapTable::parse(&section).unwrap();
        let descriptors: Vec<_> = pmt
            .iter_program_descriptors()
            .collect::<Result<_, _>>()
            .unwrap();
        assert_eq!(descriptors.len(), 1);
        match &descriptors[0].body {
            crate::descriptor::DescriptorBody::Registration {
                format_identifier, ..
            } => {
                assert_eq!(format_identifier, b"HDMV");
            }
            other => panic!("expected Registration, got {other:?}"),
        }
    }

    #[test]
    fn pat_network_pid_program_zero() {
        let section = build_pat_section(2, 0, &[(0, 0x10), (1, 0x100)]);
        let pat = ProgramAssociationTable::parse(&section).unwrap();
        assert_eq!(pat.programs[0], (0, 0x10));
        assert_eq!(pat.programs[1], (1, 0x100));
    }

    /// Build a CAT section carrying `descriptors` as its body.
    /// Section bytes run from table_id through CRC.
    fn build_cat_section(version: u8, descriptors: &[u8]) -> Vec<u8> {
        let section_length = 5 + descriptors.len() + 4;
        let mut s = Vec::with_capacity(3 + section_length);
        s.push(CAT_TABLE_ID);
        let len_hi = 0b1011_0000 | ((section_length >> 8) & 0x0F) as u8;
        s.push(len_hi);
        s.push((section_length & 0xFF) as u8);
        // reserved (18 bits high padding) -> for CAT, table_id_extension
        // is the 16 reserved bits of bytes 3..5 — encode as 0xFFFF.
        s.push(0xFF);
        s.push(0xFF);
        // reserved | version | current_next.
        s.push(0b1100_0001 | ((version & 0b1_1111) << 1));
        s.push(0);
        s.push(0);
        s.extend_from_slice(descriptors);
        let crc = mpeg2_crc32(&s);
        s.extend_from_slice(&crc.to_be_bytes());
        s
    }

    #[test]
    fn cat_round_trip_single_ca_descriptor() {
        // CA_descriptor (tag 0x09): CA_system_ID=0x0500, CA_PID=0x0123,
        // private_data=0xCA 0xFE.
        let ca_descr: &[u8] = &[0x09, 0x06, 0x05, 0x00, 0xE1, 0x23, 0xCA, 0xFE];
        let section = build_cat_section(3, ca_descr);
        let cat = ConditionalAccessTable::parse(&section).unwrap();
        assert_eq!(cat.version_number, 3);
        assert!(cat.current_next_indicator);
        let descrs: Vec<_> = cat.iter_descriptors().collect::<Result<_, _>>().unwrap();
        assert_eq!(descrs.len(), 1);
        match &descrs[0].body {
            crate::descriptor::DescriptorBody::Ca(ca) => {
                assert_eq!(ca.ca_system_id, 0x0500);
                assert_eq!(ca.ca_pid, 0x0123);
                assert_eq!(ca.private_data, &[0xCA, 0xFE]);
            }
            other => panic!("expected CA, got {other:?}"),
        }
    }

    #[test]
    fn cat_rejects_wrong_table_id() {
        // Build a PAT-shaped section and parse it as CAT — table_id
        // mismatch must surface as an error.
        let section = build_pat_section(1, 0, &[(1, 0x100)]);
        let err = ConditionalAccessTable::parse(&section).unwrap_err();
        match err {
            TsError::Unsupported(_) => {}
            other => panic!("expected Unsupported, got {other:?}"),
        }
    }

    /// Build a TSDT section (table_id 0x03) carrying `descriptors` as
    /// its body. Section bytes run from table_id through CRC. The TSDT
    /// shares the CAT's wire layout: a long-form header whose bytes 3–4
    /// are reserved, then a descriptor() loop, then CRC.
    fn build_tsdt_section(version: u8, section_number: u8, descriptors: &[u8]) -> Vec<u8> {
        let section_length = 5 + descriptors.len() + 4;
        let mut s = Vec::with_capacity(3 + section_length);
        s.push(TSDT_TABLE_ID);
        let len_hi = 0b1011_0000 | ((section_length >> 8) & 0x0F) as u8;
        s.push(len_hi);
        s.push((section_length & 0xFF) as u8);
        // reserved 16 bits at bytes 3–4 (no table_id_extension meaning).
        s.push(0xFF);
        s.push(0xFF);
        // reserved | version | current_next.
        s.push(0b1100_0001 | ((version & 0b1_1111) << 1));
        s.push(section_number);
        s.push(section_number); // last_section_number = section_number
        s.extend_from_slice(descriptors);
        let crc = mpeg2_crc32(&s);
        s.extend_from_slice(&crc.to_be_bytes());
        s
    }

    #[test]
    fn tsdt_round_trip_registration_descriptor() {
        // Table 2-39 restricts the TSDT to 2.6 descriptors; a
        // registration_descriptor (tag 0x05) is one such — carry
        // format_identifier "HDMV" + a private byte.
        let reg_descr: &[u8] = &[0x05, 0x05, b'H', b'D', b'M', b'V', 0xAB];
        let section = build_tsdt_section(9, 0, reg_descr);
        let tsdt = TransportStreamDescriptionTable::parse(&section).unwrap();
        assert_eq!(tsdt.version_number, 9);
        assert!(tsdt.current_next_indicator);
        assert_eq!(tsdt.section_number, 0);
        assert_eq!(tsdt.last_section_number, 0);
        let descrs: Vec<_> = tsdt.iter_descriptors().collect::<Result<_, _>>().unwrap();
        assert_eq!(descrs.len(), 1);
        match &descrs[0].body {
            crate::descriptor::DescriptorBody::Registration {
                format_identifier, ..
            } => assert_eq!(format_identifier, b"HDMV"),
            other => panic!("expected Registration, got {other:?}"),
        }
    }

    #[test]
    fn tsdt_empty_descriptor_loop() {
        // A TSDT with no descriptors is well-formed: header + CRC only.
        let section = build_tsdt_section(0, 0, &[]);
        let tsdt = TransportStreamDescriptionTable::parse(&section).unwrap();
        assert_eq!(tsdt.version_number, 0);
        assert!(tsdt.descriptors.is_empty());
        assert_eq!(tsdt.iter_descriptors().count(), 0);
    }

    #[test]
    fn tsdt_rejects_wrong_table_id() {
        // A CAT-shaped section (table_id 0x01) must not parse as TSDT.
        let section = build_cat_section(1, &[0x09, 0x04, 0x05, 0x00, 0xE1, 0x23]);
        let err = TransportStreamDescriptionTable::parse(&section).unwrap_err();
        match err {
            TsError::Unsupported(_) => {}
            other => panic!("expected Unsupported, got {other:?}"),
        }
    }

    #[test]
    fn tsdt_reassembles_via_psi_assembler() {
        // The TSDT shares the PSI section envelope, so the generic
        // assembler must reassemble + hand it to TSDT::parse. Drive a
        // single-payload feed (pointer_field = 0).
        let reg_descr: &[u8] = &[0x05, 0x04, b'A', b'V', b'0', b'1'];
        let section = build_tsdt_section(2, 0, reg_descr);
        let mut payload = vec![0u8]; // pointer_field = 0
        payload.extend_from_slice(&section);
        payload.resize(184, 0xFF);
        let mut asm = PsiSectionAssembler::new();
        let out = asm.feed(&payload, true, 0).unwrap();
        assert_eq!(out.len(), 1);
        let tsdt = TransportStreamDescriptionTable::parse(&out[0]).unwrap();
        assert_eq!(tsdt.version_number, 2);
        assert_eq!(tsdt.iter_descriptors().count(), 1);
    }

    /// Build a synthetic TS packet carrying `payload` with the given
    /// PUSI bit and continuity counter. Used to drive
    /// `PsiSectionAssembler` without going through the full
    /// `TsPacket::parse` path.
    fn fake_ts_payload(payload: &[u8], _pusi: bool, _cc: u8) -> Vec<u8> {
        // The assembler receives the already-extracted TS payload,
        // not the wire bytes — so this helper just hands back the
        // payload as-is. Kept for symmetry with the test layout.
        payload.to_vec()
    }

    #[test]
    fn assembler_single_packet_section() {
        // A short PAT fits in one TS payload — the assembler must
        // emit it on a single feed() call.
        let section = build_pat_section(7, 0, &[(1, 0x100)]);
        let mut payload = vec![0u8]; // pointer_field = 0
        payload.extend_from_slice(&section);
        // Pad with stuffing so the payload looks like a real 184-byte
        // TS data area.
        payload.resize(184, 0xFF);
        let mut asm = PsiSectionAssembler::new();
        let out = asm
            .feed(&fake_ts_payload(&payload, true, 0), true, 0)
            .unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0], section);
        let pat = ProgramAssociationTable::parse(&out[0]).unwrap();
        assert_eq!(pat.programs, vec![(1, 0x100)]);
    }

    #[test]
    fn assembler_section_spans_two_ts_packets() {
        // Build a PMT large enough to overflow one TS payload — use
        // many ES_descriptors per stream entry to inflate ES_info.
        let stuff_descr = vec![0u8; 100]; // raw 100-byte descriptor blob
        let mut descr_block = vec![];
        descr_block.push(0xC0); // user-private tag → DescriptorBody::Raw
        descr_block.push(stuff_descr.len() as u8);
        descr_block.extend_from_slice(&stuff_descr);
        let section = build_pmt_section(
            1,
            0,
            0x100,
            &[],
            &[(0x1B, 0x1011, &descr_block), (0x81, 0x1100, &descr_block)],
        );
        assert!(
            section.len() > 184,
            "section ({} bytes) must exceed a single TS payload to exercise the assembler",
            section.len()
        );

        // First TS payload: pointer_field=0, then first 183 bytes of
        // section. The TS packet has a 184-byte payload (no
        // adaptation_field), pointer_field eats one byte, leaving 183
        // bytes of section.
        let mut p0 = vec![0u8]; // pointer_field
        p0.extend_from_slice(&section[..183]);
        // Second TS payload: continuation = rest of section, plus
        // stuffing to fill 184 bytes.
        let mut p1 = Vec::new();
        p1.extend_from_slice(&section[183..]);
        p1.resize(184, 0xFF);

        let mut asm = PsiSectionAssembler::new();
        let out0 = asm.feed(&p0, true, 5).unwrap();
        assert!(
            out0.is_empty(),
            "section straddles two TS packets — first feed must not yield"
        );
        let out1 = asm.feed(&p1, false, 6).unwrap();
        assert_eq!(out1.len(), 1, "second feed must complete the section");
        assert_eq!(out1[0], section);
        let pmt = ProgramMapTable::parse(&out1[0]).unwrap();
        assert_eq!(pmt.streams.len(), 2);
    }

    #[test]
    fn assembler_section_spans_three_ts_packets() {
        // Stuff a single PMT so it needs three TS payloads. Pad the
        // program_info area with two ~250-byte raw descriptor blobs;
        // each TLV uses an 8-bit length so the upper bound per blob
        // is 255 + 2 header bytes.
        let payload_chunk = vec![0xABu8; 250];
        let mut descr_block: Vec<u8> = Vec::new();
        for tag in [0xC0u8, 0xC1] {
            descr_block.push(tag);
            descr_block.push(payload_chunk.len() as u8);
            descr_block.extend_from_slice(&payload_chunk);
        }
        let section = build_pmt_section(1, 0, 0x100, &descr_block, &[(0x1B, 0x1011, &[])]);
        assert!(
            section.len() > 2 * 184,
            "need >2 TS payloads worth, got {} bytes",
            section.len()
        );

        // Slice into three chunks. First payload carries 183 section
        // bytes (after pointer_field=0); the next two carry up to 184
        // continuation bytes each.
        let mut p0 = vec![0u8];
        p0.extend_from_slice(&section[..183]);
        let p1 = section[183..183 + 184].to_vec();
        let mut p2 = section[183 + 184..].to_vec();
        p2.resize(184, 0xFF);

        let mut asm = PsiSectionAssembler::new();
        assert!(asm.feed(&p0, true, 0).unwrap().is_empty());
        assert!(asm.feed(&p1, false, 1).unwrap().is_empty());
        let out = asm.feed(&p2, false, 2).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0], section);
    }

    #[test]
    fn assembler_cc_skip_discards_in_flight_section() {
        // Begin a section in packet A (CC=4), then jump to CC=8 in
        // packet B. The assembler must discard the in-flight bytes
        // rather than concatenate them blindly.
        let section = build_pat_section(1, 0, &[(1, 0x100), (2, 0x200), (3, 0x300)]);
        // Make sure the section doesn't fit in one payload, so the
        // CC skip actually matters.
        let mut padded = Vec::new();
        for _ in 0..200 {
            padded.extend_from_slice(&section);
        }
        let big_section = build_pmt_section(
            1,
            0,
            0x100,
            &[0u8; 200],
            &[(0x1B, 0x1011, &[]), (0x81, 0x1100, &[])],
        );
        let mut p0 = vec![0u8];
        p0.extend_from_slice(&big_section[..183]);

        let mut asm = PsiSectionAssembler::new();
        assert!(asm.feed(&p0, true, 0).unwrap().is_empty());
        // Skip CC from 0 → 2 (expected was 1). Assembler drops the
        // in-flight buffer.
        let p1 = vec![0xFFu8; 184];
        let out = asm.feed(&p1, false, 2).unwrap();
        assert!(out.is_empty());
        // Confirm the buffer was actually dropped: feeding the rest
        // of `big_section` as a continuation now produces no section.
        let mut p2 = big_section[183..].to_vec();
        p2.resize(184, 0xFF);
        let out2 = asm.feed(&p2, false, 3).unwrap();
        assert!(out2.is_empty(), "CC-skip must have dropped in-flight bytes");

        let _ = padded;
    }

    #[test]
    fn assembler_stuffing_terminates_payload() {
        // A single short section followed by stuffing — assembler
        // must yield the section and stop at the first 0xFF.
        let section = build_pat_section(9, 0, &[(1, 0x100)]);
        let mut payload = vec![0u8]; // pointer_field
        payload.extend_from_slice(&section);
        payload.extend_from_slice(&[0xFFu8; 64]);
        let mut asm = PsiSectionAssembler::new();
        let out = asm.feed(&payload, true, 0).unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0], section);
    }

    #[test]
    fn assembler_two_sections_same_payload() {
        // Two short PAT sections packed back-to-back in one PUSI
        // payload — pointer_field=0 puts the first section
        // immediately after the pointer.
        let s0 = build_pat_section(1, 0, &[(1, 0x100)]);
        let s1 = build_pat_section(2, 0, &[(2, 0x200)]);
        let mut payload = vec![0u8];
        payload.extend_from_slice(&s0);
        payload.extend_from_slice(&s1);
        payload.resize(184, 0xFF);
        let mut asm = PsiSectionAssembler::new();
        let out = asm.feed(&payload, true, 0).unwrap();
        assert_eq!(out.len(), 2);
        assert_eq!(out[0], s0);
        assert_eq!(out[1], s1);
    }

    #[test]
    fn assembler_pointer_field_finishes_prev_section() {
        // First TS payload starts a section that runs past the
        // 184-byte data area. Second TS payload has PUSI=1 with
        // pointer_field = N where N is the remaining bytes of the
        // previous section; after those N bytes, a new section
        // begins.
        //
        // s0 must overflow one TS payload — build it with a stuffed
        // PMT body. s1 is the trailing short section.
        let big_descr = vec![0u8; 200];
        let s0 = build_pmt_section(1, 0, 0x100, &big_descr, &[(0x1B, 0x1011, &[])]);
        let s1 = build_pat_section(7, 0, &[(3, 0x300)]);
        assert!(s0.len() > 184, "s0 must straddle a TS packet boundary");
        let mut p0 = vec![0u8]; // pointer_field = 0
        p0.extend_from_slice(&s0[..183]);
        // p1: pointer_field = remaining s0 bytes, then s1.
        let remaining = s0.len() - 183;
        let mut p1 = vec![remaining as u8];
        p1.extend_from_slice(&s0[183..]);
        p1.extend_from_slice(&s1);
        p1.resize(184, 0xFF);

        let mut asm = PsiSectionAssembler::new();
        let out0 = asm.feed(&p0, true, 0).unwrap();
        assert!(out0.is_empty());
        let out1 = asm.feed(&p1, true, 1).unwrap();
        assert_eq!(out1.len(), 2);
        assert_eq!(out1[0], s0);
        assert_eq!(out1[1], s1);
    }

    #[test]
    fn assembler_reset_drops_buffer() {
        let section = build_pmt_section(1, 0, 0x100, &[0u8; 200], &[(0x1B, 0x1011, &[])]);
        let mut p0 = vec![0u8];
        p0.extend_from_slice(&section[..183]);
        let mut asm = PsiSectionAssembler::new();
        assert!(asm.feed(&p0, true, 0).unwrap().is_empty());
        asm.reset();
        // Feeding the continuation now does nothing — the buffer
        // was wiped.
        let mut p1 = section[183..].to_vec();
        p1.resize(184, 0xFF);
        let out = asm.feed(&p1, false, 1).unwrap();
        assert!(out.is_empty());
    }

    /// Build one service-loop entry for an SDT section.
    fn build_sdt_service(
        service_id: u16,
        eit_sched: bool,
        eit_pf: bool,
        running_status: u8,
        free_ca: bool,
        descriptors: &[u8],
    ) -> Vec<u8> {
        let mut s = Vec::new();
        s.extend_from_slice(&service_id.to_be_bytes());
        // reserved_future_use (6) | EIT_schedule_flag | EIT_present_following.
        let mut b = 0b1111_1100u8;
        if eit_sched {
            b |= 0b10;
        }
        if eit_pf {
            b |= 0b01;
        }
        s.push(b);
        // running_status (3) | free_CA_mode (1) | descriptors_length (12).
        let dlen = descriptors.len() as u16;
        let b3 = ((running_status & 0b111) << 5)
            | (if free_ca { 0b0001_0000 } else { 0 })
            | ((dlen >> 8) & 0x0F) as u8;
        s.push(b3);
        s.push((dlen & 0xFF) as u8);
        s.extend_from_slice(descriptors);
        s
    }

    /// Build a full SDT section (table_id through CRC).
    fn build_sdt_section(
        table_id: u8,
        tsid: u16,
        version: u8,
        original_network_id: u16,
        services: &[Vec<u8>],
    ) -> Vec<u8> {
        // body = onid(2) + reserved(1) + Σ service entries.
        let body_len: usize = 3 + services.iter().map(|s| s.len()).sum::<usize>();
        let section_length = 5 + body_len + 4;
        let mut s = Vec::with_capacity(3 + section_length);
        s.push(table_id);
        let len_hi = 0b1011_0000 | ((section_length >> 8) & 0x0F) as u8;
        s.push(len_hi);
        s.push((section_length & 0xFF) as u8);
        s.extend_from_slice(&tsid.to_be_bytes());
        s.push(0b1100_0001 | ((version & 0b1_1111) << 1));
        s.push(0); // section_number
        s.push(0); // last_section_number
        s.extend_from_slice(&original_network_id.to_be_bytes());
        s.push(0xFF); // reserved_future_use
        for svc in services {
            s.extend_from_slice(svc);
        }
        let crc = mpeg2_crc32(&s);
        s.extend_from_slice(&crc.to_be_bytes());
        s
    }

    /// Build a service_descriptor (tag 0x48) TLV.
    fn build_service_descriptor(service_type: u8, provider: &[u8], name: &[u8]) -> Vec<u8> {
        let mut body = vec![service_type, provider.len() as u8];
        body.extend_from_slice(provider);
        body.push(name.len() as u8);
        body.extend_from_slice(name);
        let mut v = vec![0x48u8, body.len() as u8];
        v.extend_from_slice(&body);
        v
    }

    #[test]
    fn sdt_actual_single_service_round_trip() {
        let sd = build_service_descriptor(0x01, b"Provider", b"Channel One");
        let svc = build_sdt_service(0x0064, true, true, 4, false, &sd);
        let section = build_sdt_section(SDT_ACTUAL_TABLE_ID, 0x0001, 7, 0x2024, &[svc]);
        let sdt = ServiceDescriptionTable::parse(&section).unwrap();
        assert!(!sdt.other_transport_stream);
        assert_eq!(sdt.transport_stream_id, 0x0001);
        assert_eq!(sdt.version_number, 7);
        assert!(sdt.current_next_indicator);
        assert_eq!(sdt.original_network_id, 0x2024);
        assert_eq!(sdt.services.len(), 1);
        let s = &sdt.services[0];
        assert_eq!(s.service_id, 0x0064);
        assert!(s.eit_schedule_flag);
        assert!(s.eit_present_following_flag);
        assert_eq!(s.running_status, RunningStatus::Running);
        assert!(!s.free_ca_mode);
        let d = s.iter_descriptors().next().unwrap().unwrap();
        match d.body {
            crate::descriptor::DescriptorBody::Service(svc) => {
                assert_eq!(svc.service_type, 0x01);
                assert_eq!(svc.service_provider_name, b"Provider");
                assert_eq!(svc.service_name, b"Channel One");
            }
            other => panic!("expected Service, got {other:?}"),
        }
    }

    #[test]
    fn sdt_other_table_id_sets_flag() {
        let svc = build_sdt_service(0x0001, false, false, 1, true, &[]);
        let section = build_sdt_section(SDT_OTHER_TABLE_ID, 0x0009, 0, 0x0001, &[svc]);
        let sdt = ServiceDescriptionTable::parse(&section).unwrap();
        assert!(sdt.other_transport_stream);
        assert_eq!(sdt.services.len(), 1);
        let s = &sdt.services[0];
        assert_eq!(s.running_status, RunningStatus::NotRunning);
        assert!(s.free_ca_mode);
        assert!(!s.eit_schedule_flag);
        assert!(!s.eit_present_following_flag);
    }

    #[test]
    fn sdt_multiple_services() {
        let svc0 = build_sdt_service(0x0064, true, true, 4, false, &[]);
        let svc1 = build_sdt_service(0x0065, false, true, 5, true, &[]);
        let section = build_sdt_section(SDT_ACTUAL_TABLE_ID, 0x0002, 1, 0x1000, &[svc0, svc1]);
        let sdt = ServiceDescriptionTable::parse(&section).unwrap();
        assert_eq!(sdt.services.len(), 2);
        assert_eq!(sdt.services[0].service_id, 0x0064);
        assert_eq!(sdt.services[1].service_id, 0x0065);
        assert_eq!(sdt.services[1].running_status, RunningStatus::OffAir);
    }

    #[test]
    fn sdt_rejects_wrong_table_id() {
        // A PMT section fed to the SDT parser must be rejected.
        let section = build_pmt_section(1, 0, 0x100, &[], &[(0x1B, 0x1011, &[])]);
        assert!(ServiceDescriptionTable::parse(&section).is_err());
    }

    #[test]
    fn sdt_crc_mismatch_rejected() {
        let svc = build_sdt_service(0x0064, true, true, 4, false, &[]);
        let mut section = build_sdt_section(SDT_ACTUAL_TABLE_ID, 0x0001, 7, 0x2024, &[svc]);
        let last = section.len() - 1;
        section[last] ^= 0xFF;
        assert!(matches!(
            ServiceDescriptionTable::parse(&section),
            Err(TsError::PsiCrcMismatch { .. })
        ));
    }

    #[test]
    fn running_status_reserved_values() {
        assert_eq!(RunningStatus::from_bits(6), RunningStatus::Reserved(6));
        assert_eq!(RunningStatus::from_bits(7), RunningStatus::Reserved(7));
        assert_eq!(RunningStatus::from_bits(0), RunningStatus::Undefined);
        assert_eq!(RunningStatus::from_bits(2), RunningStatus::StartsSoon);
        assert_eq!(RunningStatus::from_bits(3), RunningStatus::Pausing);
    }

    /// Build a short_event_descriptor (tag 0x4D) TLV.
    fn build_short_event_descriptor(lang: &[u8; 3], name: &[u8], text: &[u8]) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(lang);
        body.push(name.len() as u8);
        body.extend_from_slice(name);
        body.push(text.len() as u8);
        body.extend_from_slice(text);
        let mut v = vec![0x4Du8, body.len() as u8];
        v.extend_from_slice(&body);
        v
    }

    /// Build one EIT event entry (event loop element, no CRC).
    #[allow(clippy::too_many_arguments)]
    fn build_eit_event(
        event_id: u16,
        start_time: [u8; 5],
        duration_bcd: [u8; 3],
        running_status: u8,
        free_ca: bool,
        descriptors: &[u8],
    ) -> Vec<u8> {
        let mut s = Vec::new();
        s.extend_from_slice(&event_id.to_be_bytes());
        s.extend_from_slice(&start_time);
        s.extend_from_slice(&duration_bcd);
        let dlen = descriptors.len() as u16;
        let b = ((running_status & 0b111) << 5)
            | (if free_ca { 0b0001_0000 } else { 0 })
            | ((dlen >> 8) & 0x0F) as u8;
        s.push(b);
        s.push((dlen & 0xFF) as u8);
        s.extend_from_slice(descriptors);
        s
    }

    /// Build a full EIT section (table_id through CRC).
    #[allow(clippy::too_many_arguments)]
    fn build_eit_section(
        table_id: u8,
        service_id: u16,
        version: u8,
        tsid: u16,
        onid: u16,
        segment_last: u8,
        last_table_id: u8,
        events: &[Vec<u8>],
    ) -> Vec<u8> {
        // body = tsid(2) + onid(2) + segment_last(1) + last_table_id(1)
        //        + Σ events.
        let body_len: usize = 6 + events.iter().map(|e| e.len()).sum::<usize>();
        let section_length = 5 + body_len + 4;
        let mut s = Vec::with_capacity(3 + section_length);
        s.push(table_id);
        let len_hi = 0b1011_0000 | ((section_length >> 8) & 0x0F) as u8;
        s.push(len_hi);
        s.push((section_length & 0xFF) as u8);
        s.extend_from_slice(&service_id.to_be_bytes());
        s.push(0b1100_0001 | ((version & 0b1_1111) << 1));
        s.push(0); // section_number
        s.push(0); // last_section_number
        s.extend_from_slice(&tsid.to_be_bytes());
        s.extend_from_slice(&onid.to_be_bytes());
        s.push(segment_last);
        s.push(last_table_id);
        for e in events {
            s.extend_from_slice(e);
        }
        let crc = mpeg2_crc32(&s);
        s.extend_from_slice(&crc.to_be_bytes());
        s
    }

    #[test]
    fn eit_start_time_spec_example() {
        // EN 300 468 §5.2.4 example 2: 93/10/13 12:45:00 is coded as
        // 0xC0 7912 4500 (MJD 0xC079 = 49273, then 12 45 00 in BCD).
        let dt = decode_eit_start_time([0xC0, 0x79, 0x12, 0x45, 0x00]).unwrap();
        assert_eq!(dt.mjd, 0xC079);
        assert_eq!(dt.year, 1993);
        assert_eq!(dt.month, 10);
        assert_eq!(dt.day, 13);
        assert_eq!(dt.hour, 12);
        assert_eq!(dt.minute, 45);
        assert_eq!(dt.second, 0);
    }

    #[test]
    fn eit_start_time_undefined_sentinel() {
        assert!(decode_eit_start_time([0xFF, 0xFF, 0xFF, 0xFF, 0xFF]).is_none());
    }

    #[test]
    fn eit_duration_spec_example() {
        // EN 300 468 §5.2.4 example 3: 01:45:30 is coded as 0x01 4530.
        let d = EitDuration {
            hours: bcd_byte(0x01),
            minutes: bcd_byte(0x45),
            seconds: bcd_byte(0x30),
        };
        assert_eq!(d.hours, 1);
        assert_eq!(d.minutes, 45);
        assert_eq!(d.seconds, 30);
        assert_eq!(d.as_seconds(), 3600 + 45 * 60 + 30);
    }

    #[test]
    fn eit_actual_pf_single_event_round_trip() {
        let sed = build_short_event_descriptor(b"eng", b"The Event", b"A short description");
        let ev = build_eit_event(
            0x1234,
            [0xC0, 0x79, 0x12, 0x45, 0x00],
            [0x01, 0x45, 0x30],
            4, // running
            false,
            &sed,
        );
        let section = build_eit_section(
            EIT_ACTUAL_PF_TABLE_ID,
            0x0064, // service_id
            5,
            0x0001, // tsid
            0x2024, // onid
            0,
            EIT_ACTUAL_PF_TABLE_ID,
            &[ev],
        );
        let eit = EventInformationTable::parse(&section).unwrap();
        assert!(!eit.other_transport_stream);
        assert!(!eit.schedule);
        assert_eq!(eit.table_id, EIT_ACTUAL_PF_TABLE_ID);
        assert_eq!(eit.service_id, 0x0064);
        assert_eq!(eit.version_number, 5);
        assert!(eit.current_next_indicator);
        assert_eq!(eit.transport_stream_id, 0x0001);
        assert_eq!(eit.original_network_id, 0x2024);
        assert_eq!(eit.last_table_id, EIT_ACTUAL_PF_TABLE_ID);
        assert_eq!(eit.events.len(), 1);
        let e = &eit.events[0];
        assert_eq!(e.event_id, 0x1234);
        let st = e.start_time.unwrap();
        assert_eq!((st.year, st.month, st.day), (1993, 10, 13));
        assert_eq!((st.hour, st.minute, st.second), (12, 45, 0));
        assert_eq!(e.duration.as_seconds(), 6330);
        assert_eq!(e.running_status, RunningStatus::Running);
        assert!(!e.free_ca_mode);
        // The short_event_descriptor decodes to the event name + text.
        let d = e.iter_descriptors().next().unwrap().unwrap();
        match d.body {
            DescriptorBody::ShortEvent(se) => {
                assert_eq!(&se.language_code, b"eng");
                assert_eq!(se.event_name, b"The Event");
                assert_eq!(se.text, b"A short description");
            }
            other => panic!("expected ShortEvent, got {other:?}"),
        }
    }

    #[test]
    fn eit_schedule_and_other_flags() {
        // 0x60 = other-TS schedule.
        let ev = build_eit_event(1, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF], [0, 0, 0], 0, true, &[]);
        let section = build_eit_section(0x60, 0x0001, 0, 0x0001, 0x0001, 0, 0x62, &[ev]);
        let eit = EventInformationTable::parse(&section).unwrap();
        assert!(eit.other_transport_stream);
        assert!(eit.schedule);
        assert_eq!(eit.last_table_id, 0x62);
        // Undefined start time surfaces as None; free_CA_mode set.
        assert!(eit.events[0].start_time.is_none());
        assert!(eit.events[0].free_ca_mode);
    }

    #[test]
    fn eit_multiple_events() {
        let e0 = build_eit_event(
            10,
            [0xC0, 0x79, 0x12, 0x00, 0x00],
            [0, 0x30, 0],
            4,
            false,
            &[],
        );
        let e1 = build_eit_event(
            11,
            [0xC0, 0x79, 0x12, 0x30, 0x00],
            [0x01, 0, 0],
            1,
            false,
            &[],
        );
        let section = build_eit_section(
            EIT_ACTUAL_PF_TABLE_ID,
            0x0064,
            0,
            0x0001,
            0x0001,
            0,
            0x4E,
            &[e0, e1],
        );
        let eit = EventInformationTable::parse(&section).unwrap();
        assert_eq!(eit.events.len(), 2);
        assert_eq!(eit.events[0].event_id, 10);
        assert_eq!(eit.events[1].event_id, 11);
        assert_eq!(eit.events[0].duration.minutes, 30);
        assert_eq!(eit.events[1].duration.hours, 1);
    }

    #[test]
    fn eit_table_id_classification() {
        assert!(EventInformationTable::is_eit_table_id(0x4E));
        assert!(EventInformationTable::is_eit_table_id(0x4F));
        assert!(EventInformationTable::is_eit_table_id(0x50));
        assert!(EventInformationTable::is_eit_table_id(0x5F));
        assert!(EventInformationTable::is_eit_table_id(0x60));
        assert!(EventInformationTable::is_eit_table_id(0x6F));
        assert!(!EventInformationTable::is_eit_table_id(0x4D));
        assert!(!EventInformationTable::is_eit_table_id(0x70));
        assert!(!EventInformationTable::is_eit_table_id(0x42));
    }

    #[test]
    fn eit_rejects_wrong_table_id() {
        let ev = build_eit_event(1, [0xFF; 5], [0, 0, 0], 0, false, &[]);
        // Build with a valid EIT id, then corrupt the table_id byte so
        // the CRC still matches the original — parse must reject on id.
        let mut section = build_eit_section(0x70, 0, 0, 0, 0, 0, 0, &[ev]);
        section[0] = 0x70;
        assert!(matches!(
            EventInformationTable::parse(&section),
            Err(TsError::Unsupported(_))
        ));
    }

    #[test]
    fn eit_crc_mismatch_rejected() {
        let ev = build_eit_event(1, [0xC0, 0x79, 0x12, 0x45, 0x00], [0, 0, 0], 4, false, &[]);
        let mut section = build_eit_section(
            EIT_ACTUAL_PF_TABLE_ID,
            0x0064,
            0,
            0x0001,
            0x0001,
            0,
            0x4E,
            &[ev],
        );
        let last = section.len() - 1;
        section[last] ^= 0xFF;
        assert!(matches!(
            EventInformationTable::parse(&section),
            Err(TsError::PsiCrcMismatch { .. })
        ));
    }
}