dvb-conformance 10.0.0

ETSI TR 101 290 transport-stream conformance monitor (DVB measurement guidelines).
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
use core::time::Duration;

use broadcast_common::Serialize;
use dvb_si::descriptors::any::DescriptorLoop;
use dvb_si::tables::eit::{EitKind, EitSection};
use dvb_si::tables::nit::{NitKind, NitSection};
use dvb_si::tables::pat::{PatEntry, PatSection};
use dvb_si::tables::pmt::{PmtSection, PmtStream};
use dvb_si::tables::rst::RstSection;
use dvb_si::tables::sdt::{SdtKind, SdtSection};
use dvb_si::tables::tdt::TdtSection;
use mpeg_ts::mux::SectionPacketiser;
use mpeg_ts::ts::{TS_PACKET_SIZE, TsHeader};

use crate::{Config, ConformanceMonitor, Indicator};

// ── Helpers ──────────────────────────────────────────────────────────────────

const PID_PAT: u16 = 0x0000;
const PID_CAT: u16 = 0x0001;
const PID_NIT: u16 = 0x0010;
const PID_SDT_BAT: u16 = 0x0011;
const PID_EIT: u16 = 0x0012;
const PID_RST: u16 = 0x0013;
const PID_TDT_TOT: u16 = 0x0014;
const PID_NULL: u16 = 0x1FFF;

fn ms(millis: u64) -> Duration {
    Duration::from_millis(millis)
}

fn secs(seconds: u64) -> Duration {
    Duration::from_secs(seconds)
}

/// Build a single 188-byte TS packet with the given header and payload.
fn make_ts_packet(
    pid: u16,
    cc: u8,
    pusi: bool,
    has_adaptation: bool,
    adaptation: &[u8],
    payload: &[u8],
) -> [u8; TS_PACKET_SIZE] {
    let mut pkt = [0xFFu8; TS_PACKET_SIZE];
    let header = TsHeader {
        tei: false,
        pusi,
        pid,
        scrambling: 0,
        has_adaptation: has_adaptation || !adaptation.is_empty(),
        has_payload: !payload.is_empty(),
        continuity_counter: cc & 0x0F,
    };
    header.serialize_into(&mut pkt[..4]).unwrap();
    let mut pos = 4usize;
    if has_adaptation || !adaptation.is_empty() {
        let af_len = adaptation.len() as u8;
        pkt[pos] = af_len;
        pos += 1;
        if af_len > 0 {
            pkt[pos..pos + adaptation.len()].copy_from_slice(adaptation);
            pos += adaptation.len();
        }
    }
    if !payload.is_empty() {
        pkt[pos..pos + payload.len().min(TS_PACKET_SIZE - pos)]
            .copy_from_slice(&payload[..payload.len().min(TS_PACKET_SIZE - pos)]);
    }
    pkt
}

/// Build a TS packet with TEI bit set.
fn make_ts_packet_with_tei(pid: u16, cc: u8) -> [u8; TS_PACKET_SIZE] {
    let mut pkt = [0xFFu8; TS_PACKET_SIZE];
    let header = TsHeader {
        tei: true,
        pusi: false,
        pid,
        scrambling: 0,
        has_adaptation: false,
        has_payload: false,
        continuity_counter: cc & 0x0F,
    };
    header.serialize_into(&mut pkt[..4]).unwrap();
    pkt
}

/// Build a TS packet with scrambling != 0.
fn make_ts_packet_with_scrambling(pid: u16, cc: u8, scrambling: u8) -> [u8; TS_PACKET_SIZE] {
    let mut pkt = [0xFFu8; TS_PACKET_SIZE];
    let header = TsHeader {
        tei: false,
        pusi: false,
        pid,
        scrambling,
        has_adaptation: false,
        has_payload: true,
        continuity_counter: cc & 0x0F,
    };
    header.serialize_into(&mut pkt[..4]).unwrap();
    pkt[4] = 0xAB; // some payload
    pkt
}

/// Encode a 42-bit PCR value (33-bit base + 9-bit extension) into 6 bytes.
/// ISO/IEC 13818-1 §2.4.3.5 — PCR layout:
///   byte 0-3: base[32:0] (33 bits, MSB first)
///   byte 4: reserved(6) | extension[8:7]
///   byte 5: extension[7:0]
fn encode_pcr(base: u64, extension: u16) -> [u8; 6] {
    let mut out = [0u8; 6];
    out[0] = (base >> 25) as u8;
    out[1] = (base >> 17) as u8;
    out[2] = (base >> 9) as u8;
    out[3] = (base >> 1) as u8;
    out[4] = ((base & 1) << 7) as u8 | 0x7E | ((extension >> 8) & 1) as u8;
    out[5] = (extension & 0xFF) as u8;
    out
}

/// Build adaptation field data (WITHOUT the leading length byte —
/// `make_ts_packet` adds that) carrying a PCR, optionally setting the
/// discontinuity_indicator. When `no_payload` is true the adaptation field
/// fills the rest of the packet (af_length = 183) so the data must be padded
/// to 183 bytes.
fn make_pcr_adaptation(
    pcr_base: u64,
    pcr_extension: u16,
    discontinuity: bool,
    no_payload: bool,
) -> Vec<u8> {
    // Flags byte: discontinuity_indicator(bit7) | random_access(bit6) |
    //   ES_priority(bit5) | PCR_flag(bit4) | OPCR_flag(bit3) |
    //   splicing_point(bit2) | transport_private_data(bit1) | extension(bit0)
    let flags: u8 = 0x10 // PCR flag
        | if discontinuity { 0x80 } else { 0x00 };
    let pcr_bytes = encode_pcr(pcr_base, pcr_extension);
    // adaptation_field_data = flags(1) + pcr(6) = 7 bytes
    let data_len: usize = 7;
    let af_data_len = if no_payload {
        // Fill the rest of the 188-byte packet: 188 - 4(header) - 1(af_len byte) = 183
        183usize
    } else {
        data_len
    };
    let mut af = vec![0xFF; af_data_len];
    af[0] = flags;
    af[1..7].copy_from_slice(&pcr_bytes);
    af
}

/// Build a PAT section's wire bytes.
fn build_pat_section(program_map_pids: &[(u16, u16)]) -> Vec<u8> {
    let pat = PatSection {
        transport_stream_id: 1,
        version_number: 0,
        current_next_indicator: true,
        section_number: 0,
        last_section_number: 0,
        entries: program_map_pids
            .iter()
            .map(|&(pn, pid)| PatEntry {
                program_number: pn,
                pid,
            })
            .collect(),
    };
    let mut buf = vec![0u8; pat.serialized_len()];
    pat.serialize_into(&mut buf).unwrap();
    buf
}

/// Build a PMT section's wire bytes.
fn build_pmt_section(program_number: u16, pcr_pid: u16, es_pids: &[u16]) -> Vec<u8> {
    let pmt = PmtSection::new(
        program_number,
        0,
        true,
        0,
        0,
        pcr_pid,
        Default::default(),
        es_pids
            .iter()
            .map(|&pid| PmtStream {
                stream_type: dvb_si::tables::pmt::StreamType::Mpeg2Video,
                elementary_pid: pid,
                es_info: Default::default(),
            })
            .collect(),
    );
    let mut buf = vec![0u8; pmt.serialized_len()];
    pmt.serialize_into(&mut buf).unwrap();
    buf
}

/// Packetise a section into 188-byte TS packets.
fn packetise_section(pid: u16, section: &[u8]) -> Vec<[u8; TS_PACKET_SIZE]> {
    let mut pktizer = SectionPacketiser::new(pid);
    pktizer.packetise(&[section])
}

/// Feed packets to the monitor and collect all events.
fn feed_all(
    monitor: &mut ConformanceMonitor,
    packets: &[[u8; TS_PACKET_SIZE]],
    base_t: Duration,
    delta: Duration,
) -> Vec<crate::ConformanceEvent> {
    let mut all = Vec::new();
    for (i, pkt) in packets.iter().enumerate() {
        let t = base_t + delta * i as u32;
        let events = monitor.feed(pkt, t);
        all.extend(events.to_vec());
    }
    all
}

fn has_indicator(events: &[crate::ConformanceEvent], indicator: Indicator) -> bool {
    events.iter().any(|e| e.indicator == indicator)
}

/// Acquire sync by feeding 5 good packets.
fn acquire_sync(monitor: &mut ConformanceMonitor) {
    for i in 0u8..5 {
        let pkt = make_ts_packet(0x100, i, false, false, &[], &[]);
        monitor.feed(&pkt, ms(i as u64));
    }
}

/// Build a minimal PES header that signals PTS present (PTS_DTS_flags = 0b10).
/// Layout: 00 00 01 [stream_id] [PES_packet_length_hi] [PES_packet_length_lo]
///         [flags_byte: '10' + scrambling + priority + ...]
///         [PTS_DTS_flags_byte + other flags]
///         [5 bytes PTS placeholder]
fn make_pes_header_with_pts(stream_id: u8, pes_packet_length: u16) -> Vec<u8> {
    vec![
        0x00, // prefix byte 0
        0x00, // prefix byte 1
        0x01, // prefix byte 2
        stream_id,
        (pes_packet_length >> 8) as u8,
        (pes_packet_length & 0xFF) as u8,
        // Byte 6: marker bits '10' + PES_scrambling_control(00) +
        //   PES_priority(0) + data_alignment_indicator(0) + copyright(0) +
        //   original_or_copy(0) = 0b1000_0000 = 0x80
        0x80,
        // Byte 7: PTS_DTS_flags(10) + ESCR_flag(0) + ES_rate_flag(0) +
        //   DSM_trick_mode(0) + additional_copy_info(0) + PES_CRC(0) +
        //   PES_extension(0) = 0b1000_0000 = 0x80
        0x80,
        // Byte 8: PES_header_data_length (5 bytes for PTS only)
        5,
        // 5 bytes of PTS placeholder (33-bit PTS encoded across 5 bytes).
        // Use value 0 for simplicity — we only care about presence, not value.
        0x21, // '0010' + PTS[32:30] + marker '1'
        0x00, // PTS[29:22]
        0x01, // PTS[21:15] + marker '1' (partial)
        0x00, // PTS[14:7]
        0x01, // PTS[6:0] + marker '1'
    ]
}

/// Build a PES header WITHOUT PTS (PTS_DTS_flags = 0b00).
fn make_pes_header_without_pts(stream_id: u8, pes_packet_length: u16) -> Vec<u8> {
    vec![
        0x00,
        0x00,
        0x01,
        stream_id,
        (pes_packet_length >> 8) as u8,
        (pes_packet_length & 0xFF) as u8,
        0x80, // '10' marker
        0x00, // PTS_DTS_flags = 00
        0,    // PES_header_data_length = 0
    ]
}

/// Set up a monitor with sync + PAT + PMT referencing ES PID `es_pid`.
/// Returns the PMT PID.
fn setup_monitor_with_es(monitor: &mut ConformanceMonitor, es_pid: u16) -> u16 {
    let pmt_pid: u16 = 0x0100;
    acquire_sync(monitor);

    let pat_section = build_pat_section(&[(1, pmt_pid)]);
    let pat_packets = packetise_section(PID_PAT, &pat_section);
    feed_all(monitor, &pat_packets, ms(5), ms(1));

    let pmt_section = build_pmt_section(1, 0x1FFF, &[es_pid]);
    let pmt_packets = packetise_section(pmt_pid, &pmt_section);
    feed_all(monitor, &pmt_packets, ms(10), ms(1));

    pmt_pid
}

// ── 1.2 Sync_byte_error ─────────────────────────────────────────────────────

#[test]
fn sync_byte_error_trips_on_bad_sync() {
    let mut monitor = ConformanceMonitor::new();
    let mut pkt = make_ts_packet(PID_PAT, 0, true, false, &[], &[0x00]);
    pkt[0] = 0x00; // bad sync

    let events = monitor.feed(&pkt, ms(0));
    assert!(has_indicator(events, Indicator::SyncByteError));
}

#[test]
fn sync_byte_error_absent_on_good_sync() {
    let mut monitor = ConformanceMonitor::new();
    for i in 0u8..6 {
        let pkt = make_ts_packet(0x100, i, false, false, &[], &[]);
        let events = monitor.feed(&pkt, ms(i as u64));
        assert!(!has_indicator(events, Indicator::SyncByteError));
    }
}

// ── 1.1 TS_sync_loss ────────────────────────────────────────────────────────

#[test]
fn ts_sync_loss_after_bad_run_then_reacquire() {
    let mut monitor = ConformanceMonitor::new();

    for i in 0u8..5 {
        let pkt = make_ts_packet(0x100, i, false, false, &[], &[]);
        monitor.feed(&pkt, ms(i as u64));
    }
    assert!(monitor.stats().in_sync);

    let mut bad = [0u8; TS_PACKET_SIZE];
    bad[0] = 0x00;
    let events1 = monitor.feed(&bad, ms(5));
    assert!(!has_indicator(events1, Indicator::TsSyncLoss));
    let events2 = monitor.feed(&bad, ms(6));
    assert!(has_indicator(events2, Indicator::TsSyncLoss));
    assert!(!monitor.stats().in_sync);

    for i in 0u8..5 {
        let pkt = make_ts_packet(0x100, (5 + i) & 0x0F, false, false, &[], &[]);
        monitor.feed(&pkt, ms(7 + i as u64));
    }
    assert!(monitor.stats().in_sync);
}

#[test]
fn ts_sync_loss_not_emitted_while_in_sync() {
    let mut monitor = ConformanceMonitor::new();
    for i in 0u8..10 {
        let pkt = make_ts_packet(0x100, i, false, false, &[], &[]);
        let events = monitor.feed(&pkt, ms(i as u64));
        assert!(!has_indicator(events, Indicator::TsSyncLoss));
    }
}

// ── 1.4 Continuity_count_error ──────────────────────────────────────────────

#[test]
fn cc_error_trips_on_jump() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Establish a payload-bearing run on a fresh PID with correctly incrementing
    // continuity counters: 0 → 1 must NOT trip (control).
    let init = make_ts_packet(0x200, 0, false, false, &[], &[0xAB]);
    monitor.feed(&init, ms(5));
    let ok = make_ts_packet(0x200, 1, false, false, &[], &[0xAB]);
    assert!(
        !has_indicator(monitor.feed(&ok, ms(6)), Indicator::ContinuityCountError),
        "a correct +1 increment on a payload packet must not trip"
    );

    // Now a genuine jump on a payload packet: last_cc = 1, expected 2, got 5.
    let jump = make_ts_packet(0x200, 5, false, false, &[], &[0xAB]);
    let events = monitor.feed(&jump, ms(7));
    assert!(has_indicator(events, Indicator::ContinuityCountError));
}

#[test]
fn cc_correct_increment_no_error() {
    let mut monitor = ConformanceMonitor::new();
    for i in 0u8..5 {
        let pkt = make_ts_packet(0x100, i, true, false, &[], &[0xAB]);
        monitor.feed(&pkt, ms(i as u64));
    }
    let pkt = make_ts_packet(0x100, 5, true, false, &[], &[0xAB]);
    let events = monitor.feed(&pkt, ms(5));
    assert!(!has_indicator(events, Indicator::ContinuityCountError));
}

// #956: a "duplicate" is legal ONLY when it is byte-identical to its
// predecessor (PCR excepted) — ISO/IEC 13818-1:2023 §2.4.3.3. These three
// tests pin that rule directly (a same-CC repeat with a genuinely different
// payload is a real error, not a duplicate) alongside the still-legal
// byte-identical case and the "at most 2 consecutive duplicates" rule.

#[test]
fn cc_single_duplicate_is_legal() {
    let mut monitor = ConformanceMonitor::new();
    for i in 0u8..5 {
        let pkt = make_ts_packet(0x100, i, true, false, &[], &[0xAB]);
        monitor.feed(&pkt, ms(i as u64));
    }

    // Same CC (4) AND byte-identical payload (0xAB) as the last packet —
    // a genuine legal duplicate per §2.4.3.3.
    let pkt = make_ts_packet(0x100, 4, true, false, &[], &[0xAB]);
    let events = monitor.feed(&pkt, ms(5));
    assert!(!has_indicator(events, Indicator::ContinuityCountError));
}

#[test]
fn cc_same_cc_different_payload_is_error() {
    // #956 regression: repeating the previous CC is legal only when the
    // packet is byte-identical (PCR excepted). A same-CC repeat whose
    // payload has genuinely changed is a real continuity fault, not a
    // duplicate — this used to be silently accepted.
    let mut monitor = ConformanceMonitor::new();
    for i in 0u8..5 {
        let pkt = make_ts_packet(0x100, i, true, false, &[], &[0xAB]);
        monitor.feed(&pkt, ms(i as u64));
    }

    let pkt = make_ts_packet(0x100, 4, true, false, &[], &[0xCD]);
    let events = monitor.feed(&pkt, ms(5));
    assert!(
        has_indicator(events, Indicator::ContinuityCountError),
        "same CC with a genuinely different payload must raise Continuity_count_error"
    );
}

#[test]
fn cc_double_duplicate_is_error() {
    // §2.4.3.3: "duplicate packets may be sent as two, and only two,
    // consecutive transport stream packets of the same PID" — a THIRD
    // repeat of the same (CC, payload) pair is itself an error, even though
    // each individual repeat is byte-identical.
    let mut monitor = ConformanceMonitor::new();
    for i in 0u8..5 {
        let pkt = make_ts_packet(0x100, i, true, false, &[], &[0xAB]);
        monitor.feed(&pkt, ms(i as u64));
    }
    let pkt1 = make_ts_packet(0x100, 4, true, false, &[], &[0xAB]);
    let events1 = monitor.feed(&pkt1, ms(5));
    assert!(
        !has_indicator(events1, Indicator::ContinuityCountError),
        "the first legal duplicate must not raise an error"
    );
    let pkt2 = make_ts_packet(0x100, 4, true, false, &[], &[0xAB]);
    let events2 = monitor.feed(&pkt2, ms(6));
    assert!(
        has_indicator(events2, Indicator::ContinuityCountError),
        "a second consecutive duplicate of the same CC must raise Continuity_count_error"
    );
}

#[test]
fn cc_no_payload_holds_cc() {
    let mut monitor = ConformanceMonitor::new();
    for i in 0u8..5 {
        let pkt = make_ts_packet(0x100, i, false, false, &[], &[]);
        monitor.feed(&pkt, ms(i as u64));
    }
    let pkt = make_ts_packet(0x100, 4, false, true, &[0x00], &[]);
    let events = monitor.feed(&pkt, ms(5));
    assert!(!has_indicator(events, Indicator::ContinuityCountError));
}

#[test]
fn cc_discontinuity_indicator_skips_check() {
    let mut monitor = ConformanceMonitor::new();
    for i in 0u8..5 {
        let pkt = make_ts_packet(0x100, i, false, false, &[], &[]);
        monitor.feed(&pkt, ms(i as u64));
    }
    let af = [0x80]; // discontinuity_indicator set
    let pkt = make_ts_packet(0x100, 7, false, true, &af, &[]);
    let events = monitor.feed(&pkt, ms(5));
    assert!(!has_indicator(events, Indicator::ContinuityCountError));
}

#[test]
fn cc_null_pid_skipped() {
    let mut monitor = ConformanceMonitor::new();
    for i in 0u8..5 {
        let pkt = make_ts_packet(0x100, i, false, false, &[], &[]);
        monitor.feed(&pkt, ms(i as u64));
    }
    let pkt = make_ts_packet(PID_NULL, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, ms(5));
    assert!(!has_indicator(events, Indicator::ContinuityCountError));
}

// ── 1.3.a PAT_error_2 ───────────────────────────────────────────────────────

#[test]
fn pat_error_wrong_table_id() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let mut section = build_pat_section(&[(1, 0x100)]);
    section[0] = 0x01; // wrong table_id

    let packets = packetise_section(PID_PAT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(has_indicator(&events, Indicator::PatError2));
}

#[test]
fn pat_error_scrambling() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let mut pkt = make_ts_packet(PID_PAT, 0, true, false, &[], &[0x00]);
    pkt[3] = (pkt[3] & !0xC0) | 0x40; // scrambling = 01

    let events = monitor.feed(&pkt, ms(5));
    assert!(has_indicator(events, Indicator::PatError2));
}

#[test]
fn pat_error_timeout() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, ms(600));
    assert!(has_indicator(events, Indicator::PatError2));
}

#[test]
fn pat_compliant_no_error() {
    let mut monitor = ConformanceMonitor::new();

    let section = build_pat_section(&[(1, 0x100)]);
    let packets = packetise_section(PID_PAT, &section);

    acquire_sync(&mut monitor);

    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(!has_indicator(&events, Indicator::PatError2));

    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, ms(20));
    assert!(!has_indicator(events, Indicator::PatError2));
}

// ── 1.5.a PMT_error_2 ───────────────────────────────────────────────────────

#[test]
fn pmt_error_timeout() {
    let mut monitor = ConformanceMonitor::new();

    let section = build_pat_section(&[(1, 0x100)]);
    let packets = packetise_section(PID_PAT, &section);

    acquire_sync(&mut monitor);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, ms(600));
    assert!(has_indicator(events, Indicator::PmtError2));
}

#[test]
fn pmt_error_scrambling() {
    let mut monitor = ConformanceMonitor::new();

    let section = build_pat_section(&[(1, 0x100)]);
    let packets = packetise_section(PID_PAT, &section);
    acquire_sync(&mut monitor);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    let mut pkt = make_ts_packet(0x100, 5, false, false, &[], &[]);
    pkt[3] = (pkt[3] & !0xC0) | 0x40; // scrambling = 01
    let events = monitor.feed(&pkt, ms(10));
    assert!(has_indicator(events, Indicator::PmtError2));
}

#[test]
fn pmt_compliant_no_error() {
    let mut monitor = ConformanceMonitor::new();

    let pat_section = build_pat_section(&[(1, 0x100)]);
    let pat_packets = packetise_section(PID_PAT, &pat_section);

    acquire_sync(&mut monitor);
    feed_all(&mut monitor, &pat_packets, ms(5), ms(1));

    let pmt_section = build_pmt_section(1, 0x1FFF, &[]);
    let pmt_packets = packetise_section(0x100, &pmt_section);
    let events = feed_all(&mut monitor, &pmt_packets, ms(10), ms(1));
    assert!(!has_indicator(&events, Indicator::PmtError2));
}

// ── 1.6 PID_error ────────────────────────────────────────────────────────────

#[test]
fn pid_error_timeout() {
    let config = Config {
        pid_error_period: secs(1),
        ..Config::default()
    };
    let mut monitor = ConformanceMonitor::with_config(config);

    let pat_section = build_pat_section(&[(1, 0x100)]);
    let pat_packets = packetise_section(PID_PAT, &pat_section);

    acquire_sync(&mut monitor);
    feed_all(&mut monitor, &pat_packets, ms(5), ms(1));

    let pmt_section = build_pmt_section(1, 0x1FFF, &[0x200]);
    let pmt_packets = packetise_section(0x100, &pmt_section);
    feed_all(&mut monitor, &pmt_packets, ms(10), ms(1));

    let pkt = make_ts_packet(0x300, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, secs(2));
    assert!(has_indicator(events, Indicator::PidError));
}

#[test]
fn pid_compliant_no_error() {
    let config = Config {
        pid_error_period: secs(5),
        ..Config::default()
    };
    let mut monitor = ConformanceMonitor::with_config(config);

    let pat_section = build_pat_section(&[(1, 0x100)]);
    let pat_packets = packetise_section(PID_PAT, &pat_section);

    acquire_sync(&mut monitor);
    feed_all(&mut monitor, &pat_packets, ms(5), ms(1));

    let pmt_section = build_pmt_section(1, 0x1FFF, &[0x200]);
    let pmt_packets = packetise_section(0x100, &pmt_section);
    feed_all(&mut monitor, &pmt_packets, ms(10), ms(1));

    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, ms(500));
    assert!(!has_indicator(events, Indicator::PidError));
}

// ── Presence-timeout emit-once semantics ─────────────────────────────────────

#[test]
fn pat_timeout_emits_once_not_per_packet() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    let e1 = monitor.feed(&pkt, ms(600)).to_vec();
    let e2 = monitor.feed(&pkt, ms(700)).to_vec();
    let e3 = monitor.feed(&pkt, ms(800)).to_vec();

    assert_eq!(
        e1.iter()
            .filter(|e| e.indicator == Indicator::PatError2)
            .count(),
        1
    );
    assert!(!has_indicator(&e2, Indicator::PatError2));
    assert!(!has_indicator(&e3, Indicator::PatError2));
}

// ── Sync suppression: other indicators suppressed while not in sync ──────────

#[test]
fn other_indicators_suppressed_while_not_in_sync() {
    let mut monitor = ConformanceMonitor::new();

    let bad = [0u8; TS_PACKET_SIZE]; // sync byte = 0x00
    for i in 0u8..10 {
        let events = monitor.feed(&bad, ms(i as u64));
        for e in events {
            assert!(
                e.indicator == Indicator::SyncByteError || e.indicator == Indicator::TsSyncLoss,
                "unexpected indicator {:?} while not in sync",
                e.indicator,
            );
        }
    }
}

// ── Stats ────────────────────────────────────────────────────────────────────

#[test]
fn stats_track_packets_and_events() {
    let mut monitor = ConformanceMonitor::new();
    assert_eq!(monitor.stats().packets, 0);
    assert_eq!(monitor.stats().events, 0);

    let bad = [0u8; TS_PACKET_SIZE];
    monitor.feed(&bad, ms(0));
    assert_eq!(monitor.stats().packets, 1);
    assert!(monitor.stats().events >= 1);
}

// ═══════════════════════════════════════════════════════════════════════════════
// ── Priority 2 tests ─────────────────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════

// ── 2.1 Transport_error ──────────────────────────────────────────────────────

#[test]
fn transport_error_trips_on_tei_set() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let pkt = make_ts_packet_with_tei(0x100, 5);
    let events = monitor.feed(&pkt, ms(5));
    assert!(has_indicator(events, Indicator::TransportError));
}

#[test]
fn transport_error_absent_on_tei_clear() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let pkt = make_ts_packet(0x100, 5, false, false, &[], &[]);
    let events = monitor.feed(&pkt, ms(5));
    assert!(!has_indicator(events, Indicator::TransportError));
}

// ── 2.2 CRC_error ────────────────────────────────────────────────────────────

#[test]
fn crc_error_trips_on_corrupted_pat() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Build a valid PAT section then corrupt a payload byte (not sync/header).
    let mut section = build_pat_section(&[(1, 0x100)]);
    // The section has: header (3) + extension (5) + entries + CRC (4).
    // Corrupt a byte in the entries area (well before the CRC).
    if section.len() > 12 {
        section[10] ^= 0xFF;
    }

    let packets = packetise_section(PID_PAT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(has_indicator(&events, Indicator::CrcError));
}

#[test]
fn crc_error_absent_on_valid_pat() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let section = build_pat_section(&[(1, 0x100)]);
    let packets = packetise_section(PID_PAT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(!has_indicator(&events, Indicator::CrcError));
}

// ── 2.3a PCR_repetition_error ────────────────────────────────────────────────

#[test]
fn pcr_repetition_error_trips_on_large_gap() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let pcr_pid: u16 = 0x0200;
    // PCR base values are in 90kHz units; as_27mhz() = base * 300.
    // 1s = 90000 base units, 2s = 180000.
    let af1 = make_pcr_adaptation(90000, 0, false, true);
    let pkt1 = make_ts_packet(pcr_pid, 0, false, true, &af1, &[]);
    let af2 = make_pcr_adaptation(180000, 0, false, true);
    let pkt2 = make_ts_packet(pcr_pid, 1, false, true, &af2, &[]);

    monitor.feed(&pkt1, ms(0));
    // Second PCR at t=150ms — gap of 150ms exceeds 100ms default limit.
    let events = monitor.feed(&pkt2, ms(150));
    assert!(has_indicator(events, Indicator::PcrRepetitionError));
}

#[test]
fn pcr_repetition_error_absent_within_limit() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let pcr_pid: u16 = 0x0200;
    let af1 = make_pcr_adaptation(90000, 0, false, true);
    let pkt1 = make_ts_packet(pcr_pid, 0, false, true, &af1, &[]);
    let af2 = make_pcr_adaptation(180000, 0, false, true);
    let pkt2 = make_ts_packet(pcr_pid, 1, false, true, &af2, &[]);

    monitor.feed(&pkt1, ms(0));
    // Second PCR at t=50ms — gap of 50ms within 100ms limit.
    let events = monitor.feed(&pkt2, ms(50));
    assert!(!has_indicator(events, Indicator::PcrRepetitionError));
}

// ── 2.3b PCR_discontinuity_indicator_error ───────────────────────────────────

#[test]
fn pcr_discontinuity_error_trips_on_large_delta_without_indicator() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let pcr_pid: u16 = 0x0200;
    // First PCR (1s on 90kHz = base 90000, as_27mhz = 27000000).
    let af1 = make_pcr_adaptation(90000, 0, false, true);
    let pkt1 = make_ts_packet(pcr_pid, 0, false, true, &af1, &[]);
    // Second PCR (4s on 90kHz = base 360000, as_27mhz = 108000000).
    // Delta on 27MHz = 81000000 = 3000ms >> 100ms, no discontinuity.
    let af2 = make_pcr_adaptation(360000, 0, false, true);
    let pkt2 = make_ts_packet(pcr_pid, 1, false, true, &af2, &[]);

    monitor.feed(&pkt1, ms(0));
    let events = monitor.feed(&pkt2, ms(50));
    assert!(has_indicator(events, Indicator::PcrDiscontinuityError));
}

#[test]
fn pcr_discontinuity_error_suppressed_with_indicator() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let pcr_pid: u16 = 0x0200;
    // Same large PCR delta but WITH discontinuity_indicator set — legal.
    let af1 = make_pcr_adaptation(90000, 0, false, true);
    let pkt1 = make_ts_packet(pcr_pid, 0, false, true, &af1, &[]);
    let af2 = make_pcr_adaptation(360000, 0, true, true); // discontinuity
    let pkt2 = make_ts_packet(pcr_pid, 1, false, true, &af2, &[]);

    monitor.feed(&pkt1, ms(0));
    let events = monitor.feed(&pkt2, ms(50));
    assert!(!has_indicator(events, Indicator::PcrDiscontinuityError));
}

#[test]
fn pcr_discontinuity_error_absent_within_range() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    let pcr_pid: u16 = 0x0200;
    // PCR delta of 50ms: base diff = 4500 (90kHz), as_27mhz diff = 1350000.
    let af1 = make_pcr_adaptation(90000, 0, false, true);
    let pkt1 = make_ts_packet(pcr_pid, 0, false, true, &af1, &[]);
    let af2 = make_pcr_adaptation(90000 + 4500, 0, false, true);
    let pkt2 = make_ts_packet(pcr_pid, 1, false, true, &af2, &[]);

    monitor.feed(&pkt1, ms(0));
    let events = monitor.feed(&pkt2, ms(50));
    assert!(!has_indicator(events, Indicator::PcrDiscontinuityError));
}

// ── 2.5 PTS_error ────────────────────────────────────────────────────────────

#[test]
fn pts_error_trips_on_large_gap() {
    let mut monitor = ConformanceMonitor::new();

    let es_pid: u16 = 0x0200;
    setup_monitor_with_es(&mut monitor, es_pid);

    // First PES with PTS at t=20ms.
    let pes1 = make_pes_header_with_pts(0xE0, 10);
    let pkt1 = make_ts_packet(es_pid, 0, true, false, &[], &pes1);
    let events1 = monitor.feed(&pkt1, ms(20));
    // First PTS should not produce an error (arm only).
    assert!(!has_indicator(events1, Indicator::PtsError));

    // Second PES with PTS at t=800ms — gap of 780ms exceeds 700ms limit.
    let pes2 = make_pes_header_with_pts(0xE0, 10);
    let pkt2 = make_ts_packet(es_pid, 1, true, false, &[], &pes2);
    let events2 = monitor.feed(&pkt2, ms(800));
    assert!(has_indicator(events2, Indicator::PtsError));
}

#[test]
fn pts_error_absent_within_limit() {
    let mut monitor = ConformanceMonitor::new();

    let es_pid: u16 = 0x0200;
    setup_monitor_with_es(&mut monitor, es_pid);

    // First PES with PTS.
    let pes1 = make_pes_header_with_pts(0xE0, 10);
    let pkt1 = make_ts_packet(es_pid, 0, true, false, &[], &pes1);
    monitor.feed(&pkt1, ms(20));

    // Second PES with PTS at t=500ms — gap of 480ms within 700ms limit.
    let pes2 = make_pes_header_with_pts(0xE0, 10);
    let pkt2 = make_ts_packet(es_pid, 1, true, false, &[], &pes2);
    let events = monitor.feed(&pkt2, ms(500));
    assert!(!has_indicator(events, Indicator::PtsError));
}

#[test]
fn pts_error_not_armed_without_first_pts() {
    let mut monitor = ConformanceMonitor::new();

    let es_pid: u16 = 0x0200;
    setup_monitor_with_es(&mut monitor, es_pid);

    // Feed a PES packet WITHOUT PTS — should not arm the check.
    let pes_no_pts = make_pes_header_without_pts(0xE0, 10);
    let pkt1 = make_ts_packet(es_pid, 0, true, false, &[], &pes_no_pts);
    monitor.feed(&pkt1, ms(20));

    // Feed another PES WITH PTS at t=800ms — first PTS, so just arms.
    let pes2 = make_pes_header_with_pts(0xE0, 10);
    let pkt2 = make_ts_packet(es_pid, 1, true, false, &[], &pes2);
    let events = monitor.feed(&pkt2, ms(800));
    assert!(!has_indicator(events, Indicator::PtsError));
}

// ── 2.6 CAT_error ────────────────────────────────────────────────────────────

#[test]
fn cat_error_wrong_table_id_on_pid_cat() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Build a section with table_id 0x02 (PMT) on PID 0x0001 (CAT PID).
    // Take a PAT section and change the PID to CAT PID.
    let mut section = build_pat_section(&[(1, 0x100)]);
    section[0] = 0x02; // table_id = PMT (not CAT)

    let packets = packetise_section(PID_CAT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(has_indicator(&events, Indicator::CatError));
}

#[test]
fn cat_error_scrambled_without_cat() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Feed a scrambled packet when no CAT has been seen.
    let pkt = make_ts_packet_with_scrambling(0x0100, 0, 0x03);
    let events = monitor.feed(&pkt, ms(10));
    assert!(has_indicator(events, Indicator::CatError));
}

/// Build a CRC-valid minimal CAT section (table_id 0x01, empty descriptor
/// loop). Long-form: 3-byte header + table_id_extension(2) + version/cni(1) +
/// section_number(1) + last_section_number(1) + CRC-32/MPEG-2(4) = 12 bytes.
fn build_valid_cat_section() -> Vec<u8> {
    let mut cat = vec![
        0x01, // table_id = CAT
        0xB0, 0x09, // ssi=1, '0', reserved=11, section_length=9
        0xFF, 0xFF, // table_id_extension (reserved for CAT)
        0xC1, // reserved=11, version=0, current_next_indicator=1
        0x00, // section_number
        0x00, // last_section_number
    ];
    let crc = broadcast_common::crc32_mpeg2::compute(&cat);
    cat.extend_from_slice(&crc.to_be_bytes());
    cat
}

#[test]
fn cat_error_absent_when_cat_seen_then_scrambled() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed a CRC-VALID CAT section on PID 0x0001 — this must mark the CAT as
    // seen (and must NOT itself raise a CRC error).
    let packets = packetise_section(PID_CAT, &build_valid_cat_section());
    let cat_events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(
        !has_indicator(&cat_events, Indicator::CrcError),
        "a CRC-valid CAT must not raise CRC_error"
    );
    assert!(
        !has_indicator(&cat_events, Indicator::CatError),
        "a valid CAT on PID 0x0001 must not raise CAT_error"
    );

    // Now a scrambled packet arrives — because a CAT has been seen, the
    // "scrambled packet but no CAT" condition (2.6) must NOT fire.
    let pkt = make_ts_packet_with_scrambling(0x0100, 0, 0x03);
    let events = monitor.feed(&pkt, ms(10));
    assert!(
        !has_indicator(events, Indicator::CatError),
        "CAT_error must not fire for a scrambled packet once a CAT has been seen"
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// ── Priority 3 tests — SI_repetition_error (3.2) ────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════

/// Build an SDT_actual section's wire bytes.
fn build_sdt_actual_section() -> Vec<u8> {
    let sdt = SdtSection {
        kind: SdtKind::Actual,
        transport_stream_id: 1,
        version_number: 0,
        current_next_indicator: true,
        section_number: 0,
        last_section_number: 0,
        original_network_id: 1,
        services: vec![],
    };
    let mut buf = vec![0u8; sdt.serialized_len()];
    sdt.serialize_into(&mut buf).unwrap();
    buf
}

/// Build a NIT_actual section's wire bytes.
fn build_nit_actual_section() -> Vec<u8> {
    let nit = NitSection {
        kind: NitKind::Actual,
        network_id: 1,
        version_number: 0,
        current_next_indicator: true,
        section_number: 0,
        last_section_number: 0,
        network_descriptors: DescriptorLoop::new(&[]),
        transport_streams: vec![],
    };
    let mut buf = vec![0u8; nit.serialized_len()];
    nit.serialize_into(&mut buf).unwrap();
    buf
}

/// Build an EIT P/F actual section's wire bytes.
fn build_eit_pf_actual_section() -> Vec<u8> {
    let eit = EitSection {
        kind: EitKind::PresentFollowingActual,
        table_id: dvb_si::tables::eit::TABLE_ID_PF_ACTUAL,
        service_id: 1,
        version_number: 0,
        current_next_indicator: true,
        section_number: 0,
        last_section_number: 0,
        transport_stream_id: 1,
        original_network_id: 1,
        segment_last_section_number: 0,
        last_table_id: dvb_si::tables::eit::TABLE_ID_PF_ACTUAL,
        events: vec![],
    };
    let mut buf = vec![0u8; eit.serialized_len()];
    eit.serialize_into(&mut buf).unwrap();
    buf
}

/// Build a TDT section's wire bytes.
fn build_tdt_section() -> Vec<u8> {
    let tdt = TdtSection::new([0x00, 0x00, 0x00, 0x00, 0x00]);
    let mut buf = vec![0u8; tdt.serialized_len()];
    tdt.serialize_into(&mut buf).unwrap();
    buf
}

/// Build an (empty) RST section's wire bytes — short-form, no CRC.
fn build_rst_section() -> Vec<u8> {
    let rst = RstSection { entries: vec![] };
    let mut buf = vec![0u8; rst.serialized_len()];
    rst.serialize_into(&mut buf).unwrap();
    buf
}

// ── 3.2 SDT_actual repetition ────────────────────────────────────────────────

#[test]
fn si_repetition_sdt_trips_on_timeout() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Feed an SDT_actual section.
    let section = build_sdt_actual_section();
    let packets = packetise_section(PID_SDT_BAT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed a packet on another PID past the 2 s SDT interval.
    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, secs(3));
    assert!(has_indicator(events, Indicator::SiRepetitionError));
    let si_events: Vec<_> = events
        .iter()
        .filter(|e| e.indicator == Indicator::SiRepetitionError)
        .collect();
    assert_eq!(si_events.len(), 1);
    assert_eq!(si_events[0].pid, Some(PID_SDT_BAT));
    assert!(si_events[0].detail.contains("SDT_actual"));
}

#[test]
fn si_repetition_sdt_compliant_within_interval() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Feed an SDT_actual section.
    let section = build_sdt_actual_section();
    let packets = packetise_section(PID_SDT_BAT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed another SDT_actual within 2 s.
    let packets2 = packetise_section(PID_SDT_BAT, &section);
    let events = feed_all(&mut monitor, &packets2, ms(1000), ms(1));
    assert!(!has_indicator(&events, Indicator::SiRepetitionError));
}

// ── 3.2 TDT repetition ──────────────────────────────────────────────────────

#[test]
fn si_repetition_tdt_trips_on_timeout() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Feed a TDT section.
    let section = build_tdt_section();
    let packets = packetise_section(PID_TDT_TOT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed a packet past the 30 s TDT interval.
    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, secs(35));
    assert!(has_indicator(events, Indicator::SiRepetitionError));
    let si_events: Vec<_> = events
        .iter()
        .filter(|e| e.indicator == Indicator::SiRepetitionError)
        .collect();
    assert_eq!(si_events.len(), 1);
    assert_eq!(si_events[0].pid, Some(PID_TDT_TOT));
    assert!(si_events[0].detail.contains("TDT"));
}

#[test]
fn si_repetition_tdt_compliant_within_interval() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Feed a TDT section.
    let section = build_tdt_section();
    let packets = packetise_section(PID_TDT_TOT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed another TDT within 30 s.
    let packets2 = packetise_section(PID_TDT_TOT, &section);
    let events = feed_all(&mut monitor, &packets2, secs(20), ms(1));
    assert!(!has_indicator(&events, Indicator::SiRepetitionError));
}

// ── 3.2 NIT_actual repetition ────────────────────────────────────────────────

#[test]
fn si_repetition_nit_trips_on_timeout() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Feed a NIT_actual section.
    let section = build_nit_actual_section();
    let packets = packetise_section(PID_NIT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed a packet past the 10 s NIT interval.
    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, secs(12));
    assert!(has_indicator(events, Indicator::SiRepetitionError));
    let si_events: Vec<_> = events
        .iter()
        .filter(|e| e.indicator == Indicator::SiRepetitionError)
        .collect();
    assert_eq!(si_events.len(), 1);
    assert_eq!(si_events[0].pid, Some(PID_NIT));
    assert!(si_events[0].detail.contains("NIT_actual"));
}

#[test]
fn si_repetition_nit_compliant_within_interval() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Feed a NIT_actual section.
    let section = build_nit_actual_section();
    let packets = packetise_section(PID_NIT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed another NIT within 10 s.
    let packets2 = packetise_section(PID_NIT, &section);
    let events = feed_all(&mut monitor, &packets2, secs(5), ms(1));
    assert!(!has_indicator(&events, Indicator::SiRepetitionError));
}

// ── 3.2 EIT P/F actual repetition ───────────────────────────────────────────

#[test]
fn si_repetition_eit_pf_trips_on_timeout() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Feed an EIT P/F actual section.
    let section = build_eit_pf_actual_section();
    let packets = packetise_section(PID_EIT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed a packet past the 2 s EIT interval.
    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, secs(3));
    assert!(has_indicator(events, Indicator::SiRepetitionError));
    let si_events: Vec<_> = events
        .iter()
        .filter(|e| e.indicator == Indicator::SiRepetitionError)
        .collect();
    assert_eq!(si_events.len(), 1);
    assert_eq!(si_events[0].pid, Some(PID_EIT));
    assert!(si_events[0].detail.contains("EIT_P/F_actual"));
}

#[test]
fn si_repetition_eit_pf_compliant_within_interval() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Feed an EIT P/F actual section.
    let section = build_eit_pf_actual_section();
    let packets = packetise_section(PID_EIT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed another EIT within 2 s.
    let packets2 = packetise_section(PID_EIT, &section);
    let events = feed_all(&mut monitor, &packets2, secs(1), ms(1));
    assert!(!has_indicator(&events, Indicator::SiRepetitionError));
}

// ── 3.2 Lazy arming — absent table not flagged ───────────────────────────────

#[test]
fn si_repetition_not_armed_before_first_section() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Feed packets on unrelated PIDs well past all SI intervals.
    // No SI table has been seen, so no timer is armed.
    for i in 0..5u8 {
        let pkt = make_ts_packet(0x200, i, false, false, &[], &[]);
        let events = monitor.feed(&pkt, secs(60 + i as u64));
        assert!(
            !has_indicator(events, Indicator::SiRepetitionError),
            "SiRepetitionError should not fire before any SI section is seen"
        );
    }
}

// ── 3.2 Emit-once semantics ──────────────────────────────────────────────────

#[test]
fn si_repetition_emits_once_not_per_packet() {
    let mut monitor = ConformanceMonitor::new();

    acquire_sync(&mut monitor);

    // Feed an SDT_actual section.
    let section = build_sdt_actual_section();
    let packets = packetise_section(PID_SDT_BAT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed packets past the 2 s interval — only the FIRST should emit.
    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    let e1 = monitor.feed(&pkt, secs(3)).to_vec();
    let e2 = monitor.feed(&pkt, secs(4)).to_vec();
    let e3 = monitor.feed(&pkt, secs(5)).to_vec();

    assert_eq!(
        e1.iter()
            .filter(|e| e.indicator == Indicator::SiRepetitionError)
            .count(),
        1
    );
    assert!(!has_indicator(&e2, Indicator::SiRepetitionError));
    assert!(!has_indicator(&e3, Indicator::SiRepetitionError));
}

// ═══════════════════════════════════════════════════════════════════════════════
// ── 3.1 NIT_error ────────────────────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn nit_error_trips_on_wrong_table_id() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // A PMT (table_id 0x02) is not an allowed table_id on PID 0x0010.
    let mut section = build_nit_actual_section();
    section[0] = 0x02;

    let packets = packetise_section(PID_NIT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(has_indicator(&events, Indicator::NitError));
}

#[test]
fn nit_error_trips_on_actual_absence_timeout() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let section = build_nit_actual_section();
    let packets = packetise_section(PID_NIT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Past the 10 s NIT_actual repetition interval, with no further NIT.
    let pkt = make_ts_packet(0x0500, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, secs(12));
    assert!(has_indicator(events, Indicator::NitError));
}

#[test]
fn nit_error_absent_on_compliant_stream() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let section = build_nit_actual_section();
    let packets = packetise_section(PID_NIT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(!has_indicator(&events, Indicator::NitError));

    // A second NIT_actual well within the 10 s interval — no error either.
    let packets2 = packetise_section(PID_NIT, &section);
    let events2 = feed_all(&mut monitor, &packets2, secs(5), ms(1));
    assert!(!has_indicator(&events2, Indicator::NitError));
}

// ═══════════════════════════════════════════════════════════════════════════════
// ── 3.4 Unreferenced_PID ─────────────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn unreferenced_pid_trips_after_persistence_threshold() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let stray_pid: u16 = 0x0500;
    let pkt1 = make_ts_packet(stray_pid, 0, false, false, &[], &[]);
    monitor.feed(&pkt1, ms(5));

    // No PAT/PMT ever references `stray_pid`. Past the 500 ms threshold, a
    // further sighting must trip Unreferenced_PID.
    let pkt2 = make_ts_packet(stray_pid, 1, false, false, &[], &[]);
    let events = monitor.feed(&pkt2, ms(600));
    let unref: Vec<_> = events
        .iter()
        .filter(|e| e.indicator == Indicator::UnreferencedPid && e.pid == Some(stray_pid))
        .collect();
    assert_eq!(unref.len(), 1);
}

#[test]
fn unreferenced_pid_absent_within_persistence_threshold() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let stray_pid: u16 = 0x0500;
    let pkt1 = make_ts_packet(stray_pid, 0, false, false, &[], &[]);
    monitor.feed(&pkt1, ms(5));

    // Still within the 500 ms transition allowance — must not trip yet.
    let pkt2 = make_ts_packet(stray_pid, 1, false, false, &[], &[]);
    let events = monitor.feed(&pkt2, ms(200));
    let unref: Vec<_> = events
        .iter()
        .filter(|e| e.indicator == Indicator::UnreferencedPid && e.pid == Some(stray_pid))
        .collect();
    assert!(unref.is_empty());
}

#[test]
fn unreferenced_pid_absent_when_referenced_by_pmt() {
    let mut monitor = ConformanceMonitor::new();
    let es_pid: u16 = 0x0500;
    setup_monitor_with_es(&mut monitor, es_pid);

    // The ES PID is now referenced by the PMT (before ever transmitting its
    // own packets). Even long after the 500 ms threshold, it must not trip.
    let pkt = make_ts_packet(es_pid, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, secs(2));
    assert!(!has_indicator(events, Indicator::UnreferencedPid));
}

#[test]
fn unreferenced_pid_absent_for_well_known_si_pids() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // NOTE: `acquire_sync`'s own helper PID (0x0100) is itself a legitimate
    // Unreferenced_PID candidate here (no PAT/PMT ever references it in this
    // test) and correctly fires past the threshold — filter events down to
    // the PID under test so that unrelated noise doesn't fail the assertion.
    for &pid in &[PID_NIT, PID_SDT_BAT, PID_EIT, PID_RST, PID_TDT_TOT] {
        let pkt1 = make_ts_packet(pid, 0, false, false, &[], &[]);
        monitor.feed(&pkt1, ms(5));
        let pkt2 = make_ts_packet(pid, 1, false, false, &[], &[]);
        let events = monitor.feed(&pkt2, secs(2));
        let flagged = events
            .iter()
            .any(|e| e.indicator == Indicator::UnreferencedPid && e.pid == Some(pid));
        assert!(
            !flagged,
            "well-known SI PID 0x{pid:04X} must never be flagged Unreferenced_PID"
        );
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ── 3.5 SDT_error ────────────────────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn sdt_error_trips_on_wrong_table_id() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let mut section = build_sdt_actual_section();
    section[0] = 0x02; // PMT table_id, not allowed on PID 0x0011.

    let packets = packetise_section(PID_SDT_BAT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(has_indicator(&events, Indicator::SdtError));
}

#[test]
fn sdt_error_trips_on_actual_absence_timeout() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let section = build_sdt_actual_section();
    let packets = packetise_section(PID_SDT_BAT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    let pkt = make_ts_packet(0x0500, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, secs(3));
    assert!(has_indicator(events, Indicator::SdtError));
}

#[test]
fn sdt_error_absent_on_compliant_stream() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let section = build_sdt_actual_section();
    let packets = packetise_section(PID_SDT_BAT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(!has_indicator(&events, Indicator::SdtError));

    let packets2 = packetise_section(PID_SDT_BAT, &section);
    let events2 = feed_all(&mut monitor, &packets2, ms(1000), ms(1));
    assert!(!has_indicator(&events2, Indicator::SdtError));
}

// ═══════════════════════════════════════════════════════════════════════════════
// ── 3.6 EIT_error ────────────────────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn eit_error_trips_on_wrong_table_id() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let mut section = build_eit_pf_actual_section();
    section[0] = 0x02; // PMT table_id, not allowed on PID 0x0012.

    let packets = packetise_section(PID_EIT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(has_indicator(&events, Indicator::EitError));
}

#[test]
fn eit_error_schedule_table_id_is_allowed() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // 0x55 is within the EIT-schedule-actual range (0x50..=0x5F) — allowed.
    let mut section = build_eit_pf_actual_section();
    section[0] = 0x55;

    let packets = packetise_section(PID_EIT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(!has_indicator(&events, Indicator::EitError));
}

#[test]
fn eit_error_trips_on_pf_actual_absence_timeout() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let section = build_eit_pf_actual_section();
    let packets = packetise_section(PID_EIT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    let pkt = make_ts_packet(0x0500, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, secs(3));
    assert!(has_indicator(events, Indicator::EitError));
}

#[test]
fn eit_error_absent_on_compliant_stream() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let section = build_eit_pf_actual_section();
    let packets = packetise_section(PID_EIT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(!has_indicator(&events, Indicator::EitError));

    let packets2 = packetise_section(PID_EIT, &section);
    let events2 = feed_all(&mut monitor, &packets2, secs(1), ms(1));
    assert!(!has_indicator(&events2, Indicator::EitError));
}

// ═══════════════════════════════════════════════════════════════════════════════
// ── 3.7 RST_error ────────────────────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn rst_error_trips_on_wrong_table_id() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let mut section = build_rst_section();
    section[0] = 0x40; // NIT_actual table_id, not allowed on PID 0x0013.

    let packets = packetise_section(PID_RST, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(has_indicator(&events, Indicator::RstError));
}

#[test]
fn rst_error_absent_on_valid_rst() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let section = build_rst_section();
    let packets = packetise_section(PID_RST, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(!has_indicator(&events, Indicator::RstError));
}

#[test]
fn rst_error_absent_on_stuffing_table_id() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let mut section = build_rst_section();
    section[0] = 0x72; // Stuffing/ST — explicitly allowed.

    let packets = packetise_section(PID_RST, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(!has_indicator(&events, Indicator::RstError));
}

// ═══════════════════════════════════════════════════════════════════════════════
// ── 3.8 TDT_error ────────────────────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn tdt_error_trips_on_wrong_table_id() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let mut section = build_tdt_section();
    section[0] = 0x02; // PMT table_id, not allowed on PID 0x0014.

    let packets = packetise_section(PID_TDT_TOT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(has_indicator(&events, Indicator::TdtError));
}

#[test]
fn tdt_error_trips_on_absence_timeout() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let section = build_tdt_section();
    let packets = packetise_section(PID_TDT_TOT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    let pkt = make_ts_packet(0x0500, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, secs(35));
    assert!(has_indicator(events, Indicator::TdtError));
}

#[test]
fn tdt_error_absent_on_compliant_stream() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let section = build_tdt_section();
    let packets = packetise_section(PID_TDT_TOT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(!has_indicator(&events, Indicator::TdtError));

    let packets2 = packetise_section(PID_TDT_TOT, &section);
    let events2 = feed_all(&mut monitor, &packets2, secs(20), ms(1));
    assert!(!has_indicator(&events2, Indicator::TdtError));
}

// ═══════════════════════════════════════════════════════════════════════════════
// ── 3.3 Buffer_error (TBsys overflow) ────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════

/// Build a large PSI section (~900 bytes) that exceeds TBsys capacity (512
/// bytes). When fed in rapid succession without giving TBsys time to drain
/// (1 Mbit/s = 125 KB/s), the buffer overflows.
fn build_large_pat_section() -> Vec<u8> {
    // A PAT with many entries to push section size above 512 bytes.
    // Each PAT entry is 4 bytes; 120 entries ≈ 480 bytes, plus header ≈ 8
    // bytes, total ≈ 488 bytes. We need >512 to overflow in one shot.
    // Actually the PAT is packetized across TS packets, so the section bytes
    // arrive in ~184-byte chunks. TBsys must drain between them.
    // For a 900-byte section, 5 packets @ 184 bytes = 920 bytes total.
    // At 125 KB/s drain and 40 µs spacing, drain per packet = 5 bytes.
    // After 5 packets: 920 - 5*5 = 895 bytes > 512 → overflow.
    let mut entries = Vec::new();
    for i in 0u16..200 {
        entries.push(PatEntry {
            program_number: i,
            pid: 0x0100 + i,
        });
    }
    let pat = PatSection {
        transport_stream_id: 1,
        version_number: 0,
        current_next_indicator: true,
        section_number: 0,
        last_section_number: 0,
        entries,
    };
    let mut buf = vec![0u8; pat.serialized_len()];
    pat.serialize_into(&mut buf).unwrap();
    buf
}

#[test]
fn buffer_error_trips_on_tbsys_overflow() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed a PAT section that is large enough to overflow TBsys when
    // packetized at rapid rate (minimal drain time between packets).
    let section = build_large_pat_section();
    let section_len = section.len();
    assert!(
        section_len > 512,
        "test precondition: section {section_len} bytes > TBsys 512 bytes"
    );

    // Packetize with minimal inter-packet timing (1 ms each → TBsys
    // drains only 125 bytes between packets at 125 KB/s).
    let packets = packetise_section(PID_PAT, &section);
    let events = feed_all(&mut monitor, &packets, ms(1), ms(1));
    assert!(
        has_indicator(&events, Indicator::BufferError),
        "TBsys overflow should fire for a >512 byte section with minimal drain"
    );
}

#[test]
fn buffer_error_absent_on_small_sections() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // A normal PAT section (~16 bytes) should not overflow TBsys
    let section = build_pat_section(&[(0x0001, 0x0100)]);
    let packets = packetise_section(PID_PAT, &section);
    let events = feed_all(&mut monitor, &packets, ms(1), ms(1));
    assert!(
        !has_indicator(&events, Indicator::BufferError),
        "normal PAT section should not overflow TBsys"
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// ── 3.9 Empty_buffer_error ───────────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn empty_buffer_error_trips_when_tbsys_never_empties_for_1s() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // TBsys drains at 125 000 bytes/s (1 Mbit/s). A single large section
    // (~900 bytes) drains in ~7.2 ms. To keep TBsys non-empty for >1 s
    // across the second empty-interval window (the first window always
    // passes because `empty_since_check` starts true from the initial
    // feed), we flood large PAT sections continuously: each 5 ms section
    // feeds ~900 bytes while only ~625 bytes drain between completions,
    // so occupancy never hits 0.
    //
    // Timeline: first `check_empty_interval` at ~1 s drains the initial
    // `empty_since_check = true` (no error). Second call at ~2 s finds
    // `empty_since_check = false` (buffer never emptied) → error.
    // TR 101 290 v1.4.1 Table 5.0c indicator 3.9.
    let section = build_large_pat_section();
    let section_packets = packetise_section(PID_PAT, &section);

    let section_interval_ms = 5u64;
    let mut events = Vec::new();
    // 450 sections ≈ 2250 ms, enough for two 1 s check windows.
    for section_idx in 0..450u64 {
        for (pkt_idx, pkt) in section_packets.iter().enumerate() {
            let t = Duration::from_millis(section_idx * section_interval_ms + pkt_idx as u64);
            let evts = monitor.feed(pkt, t);
            let evts_slice = evts.to_vec();
            if !evts_slice.is_empty() {
                events.extend(evts_slice);
            }
        }
    }

    assert!(
        has_indicator(&events, Indicator::EmptyBufferError),
        "EmptyBufferError should fire when TBsys never empties for >1 s"
    );
}

#[test]
fn empty_buffer_error_absent_when_buffer_empties_normally() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed a small PAT section — TBsys drains at 125 KB/s, so a 20-byte
    // section empties in ~0.16 ms. Any subsequent check within 1 s
    // will find the buffer was empty.
    let section = build_pat_section(&[(0x0001, 0x0100)]);
    let packets = packetise_section(PID_PAT, &section);
    let _events = feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Now advance 500 ms and feed another section — the buffer
    // was emptied well within 1 s.
    let packets2 = packetise_section(PID_PAT, &section);
    let events2 = feed_all(&mut monitor, &packets2, ms(600), ms(1));
    assert!(
        !has_indicator(&events2, Indicator::EmptyBufferError),
        "EmptyBufferError should not fire when buffer empties normally"
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// ── 3.10 Data_delay_error ───────────────────────────────────────────────────
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn data_delay_error_trips_when_data_lingers_over_1s() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // TBsys drains at 125 000 bytes/s. With continuous large-section
    // feeding at 5 ms per section, the buffer stays non-empty and
    // `first_byte_arrival` stays at the first section's completion
    // time (~5 ms). At t > 1.005 s, delay exceeds 1 s → error.
    // TR 101 290 v1.4.1 Table 5.0c indicator 3.10.
    let section = build_large_pat_section();
    let section_packets = packetise_section(PID_PAT, &section);

    let section_interval_ms = 5u64;
    let mut events = Vec::new();
    for section_idx in 0..250u64 {
        for (pkt_idx, pkt) in section_packets.iter().enumerate() {
            let t = Duration::from_millis(section_idx * section_interval_ms + pkt_idx as u64);
            let evts = monitor.feed(pkt, t);
            let evts_slice = evts.to_vec();
            if !evts_slice.is_empty() {
                events.extend(evts_slice);
            }
        }
    }

    assert!(
        has_indicator(&events, Indicator::DataDelayError),
        "DataDelayError should fire when data stays in TBsys for >1 s"
    );
}

#[test]
fn data_delay_error_absent_with_rapid_drain() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Normal PAT section: feeds TBsys, drains at 125 KB/s.
    // For a ~20-byte section, drain time ≈ 0.16 ms, well < 1 s.
    let section = build_pat_section(&[(0x0001, 0x0100)]);
    let packets = packetise_section(PID_PAT, &section);
    let events = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(
        !has_indicator(&events, Indicator::DataDelayError),
        "no delay on normal section"
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// New #736 indicators: min-gap, _other repetition, EIT P/F pairing
// ═══════════════════════════════════════════════════════════════════════════════

/// Build a NIT_actual section with a specific section_number.
fn build_nit_actual_section_numbered(section_number: u8) -> Vec<u8> {
    let nit = NitSection {
        kind: NitKind::Actual,
        network_id: 1,
        version_number: 0,
        current_next_indicator: true,
        section_number,
        last_section_number: 0,
        network_descriptors: DescriptorLoop::new(&[]),
        transport_streams: vec![],
    };
    let mut buf = vec![0u8; nit.serialized_len()];
    nit.serialize_into(&mut buf).unwrap();
    buf
}

/// Build an SDT_actual section with a specific section_number.
fn build_sdt_actual_section_numbered(section_number: u8) -> Vec<u8> {
    let sdt = SdtSection {
        kind: SdtKind::Actual,
        transport_stream_id: 1,
        version_number: 0,
        current_next_indicator: true,
        section_number,
        last_section_number: 0,
        original_network_id: 1,
        services: vec![],
    };
    let mut buf = vec![0u8; sdt.serialized_len()];
    sdt.serialize_into(&mut buf).unwrap();
    buf
}

/// Build an EIT P/F actual section with specific section_number and sub-table key.
fn build_eit_pf_actual_section_keyed(
    section_number: u8,
    service_id: u16,
    ts_id: u16,
    onw_id: u16,
) -> Vec<u8> {
    let eit = EitSection {
        kind: EitKind::PresentFollowingActual,
        table_id: dvb_si::tables::eit::TABLE_ID_PF_ACTUAL,
        service_id,
        version_number: 0,
        current_next_indicator: true,
        section_number,
        last_section_number: 0,
        transport_stream_id: ts_id,
        original_network_id: onw_id,
        segment_last_section_number: 0,
        last_table_id: dvb_si::tables::eit::TABLE_ID_PF_ACTUAL,
        events: vec![],
    };
    let mut buf = vec![0u8; eit.serialized_len()];
    eit.serialize_into(&mut buf).unwrap();
    buf
}

/// Build an NIT_other section (table_id 0x41) with specific section_number.
fn build_nit_other_section(section_number: u8) -> Vec<u8> {
    let nit = NitSection {
        kind: NitKind::Other,
        network_id: 1,
        version_number: 0,
        current_next_indicator: true,
        section_number,
        last_section_number: 0,
        network_descriptors: DescriptorLoop::new(&[]),
        transport_streams: vec![],
    };
    let mut buf = vec![0u8; nit.serialized_len()];
    nit.serialize_into(&mut buf).unwrap();
    buf
}

/// Build an SDT_other section (table_id 0x46) with specific section_number.
fn build_sdt_other_section(section_number: u8) -> Vec<u8> {
    let sdt = SdtSection {
        kind: SdtKind::Other,
        transport_stream_id: 1,
        version_number: 0,
        current_next_indicator: true,
        section_number,
        last_section_number: 0,
        original_network_id: 1,
        services: vec![],
    };
    let mut buf = vec![0u8; sdt.serialized_len()];
    sdt.serialize_into(&mut buf).unwrap();
    buf
}

/// Build an EIT P/F other section (table_id 0x4F) with specific section_number.
fn build_eit_other_section(section_number: u8) -> Vec<u8> {
    let eit = EitSection {
        kind: EitKind::PresentFollowingOther,
        table_id: dvb_si::tables::eit::TABLE_ID_PF_OTHER,
        service_id: 1,
        version_number: 0,
        current_next_indicator: true,
        section_number,
        last_section_number: 0,
        transport_stream_id: 1,
        original_network_id: 1,
        segment_last_section_number: 0,
        last_table_id: dvb_si::tables::eit::TABLE_ID_PF_OTHER,
        events: vec![],
    };
    let mut buf = vec![0u8; eit.serialized_len()];
    eit.serialize_into(&mut buf).unwrap();
    buf
}

// ── SiMinGapError (25 ms min-gap) ─────────────────────────────────────────

#[test]
fn si_min_gap_trips_when_same_section_number_too_close() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed an SDT_actual section at t=5ms
    let section = build_sdt_actual_section_numbered(0);
    let packets = packetise_section(PID_SDT_BAT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed the SAME section again only 5ms later (gap < 25ms)
    let packets2 = packetise_section(PID_SDT_BAT, &section);
    let events = feed_all(&mut monitor, &packets2, ms(10), ms(1));
    assert!(has_indicator(&events, Indicator::SiMinGapError));
}

#[test]
fn si_min_gap_absent_when_25ms_or_more() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed an SDT_actual section at t=5ms
    let section = build_sdt_actual_section_numbered(0);
    let packets = packetise_section(PID_SDT_BAT, &section);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed same section again 25ms later (exactly the threshold)
    let packets2 = packetise_section(PID_SDT_BAT, &section);
    let events = feed_all(&mut monitor, &packets2, ms(30), ms(1));
    assert!(!has_indicator(&events, Indicator::SiMinGapError));
}

#[test]
fn si_min_gap_multi_section_no_false_positive() {
    // TEST 3 from the brief: a dense legitimate multi-section table must NOT
    // trigger min-gap. Different section_numbers on the same table_id are ok.
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed NIT_actual section_number=0 at t=5ms
    let sec0 = build_nit_actual_section_numbered(0);
    let p0 = packetise_section(PID_NIT, &sec0);
    feed_all(&mut monitor, &p0, ms(5), ms(1));

    // Feed NIT_actual section_number=1 at t=6ms (different section_number, gap < 25ms)
    let sec1 = build_nit_actual_section_numbered(1);
    let p1 = packetise_section(PID_NIT, &sec1);
    let events = feed_all(&mut monitor, &p1, ms(6), ms(1));

    // Different section_numbers → no min-gap error.
    assert!(!has_indicator(&events, Indicator::SiMinGapError));
}

// ── NIT_other / SDT_other / EIT_other repetition ──────────────────────────

#[test]
fn other_repetition_trips_on_interval_exceeded() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed SDT_other section_number=0 at t=5ms (first occurrence — arms but does not fire)
    let sec = build_sdt_other_section(0);
    let packets = packetise_section(PID_SDT_BAT, &sec);
    let events1 = feed_all(&mut monitor, &packets, ms(5), ms(1));
    assert!(!has_indicator(&events1, Indicator::SdtOtherError));

    // Feed same section at t=15s (interval 15s > 10s limit; second occurrence triggers check)
    let packets2 = packetise_section(PID_SDT_BAT, &sec);
    let events2 = feed_all(&mut monitor, &packets2, secs(15), ms(1));
    assert!(has_indicator(&events2, Indicator::SdtOtherError));
}

#[test]
fn other_repetition_silent_when_within_interval() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed NIT_other at t=5ms
    let sec = build_nit_other_section(0);
    let packets = packetise_section(PID_NIT, &sec);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Feed same section at t=5s (within 10s limit)
    let packets2 = packetise_section(PID_NIT, &sec);
    let events = feed_all(&mut monitor, &packets2, secs(5), ms(1));
    assert!(!has_indicator(&events, Indicator::NitOtherError));
}

#[test]
fn other_repetition_no_false_positive_if_table_absent() {
    // If a stream carries no NIT_other (0x41) at all, NitOtherError must NOT fire.
    // A legitimate non-_other stream should be clean.
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed only NIT_actual sections — no _other ever seen.
    let sec = build_nit_actual_section_numbered(0);
    for i in 0..3 {
        let packets = packetise_section(PID_NIT, &sec);
        let events = feed_all(&mut monitor, &packets, secs(i as u64), ms(1));
        assert!(!has_indicator(&events, Indicator::NitOtherError));
    }
}

// ── EIT_PF_error (3.6.c) ──────────────────────────────────────────────────

#[test]
fn eit_pf_error_trips_when_only_section_0_present() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed only EIT P/F section 0 for service 0x42
    let sec0 = build_eit_pf_actual_section_keyed(0, 0x42, 1, 1);
    let packets = packetise_section(PID_EIT, &sec0);
    let mut all_events = feed_all(&mut monitor, &packets, ms(5), ms(1));

    // EitPfError fires only after > 2 s delay (EIT P/F repetition interval).
    // Advance time past 2 s so the timer triggers.
    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    all_events.extend(monitor.feed(&pkt, secs(3)).to_vec());
    assert!(
        has_indicator(&all_events, Indicator::EitPfError),
        "events: {all_events:#?}"
    );
}

#[test]
fn eit_pf_error_trips_when_only_section_1_present() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed only EIT P/F section 1 for service 0x99
    let sec1 = build_eit_pf_actual_section_keyed(1, 0x99, 1, 1);
    let packets = packetise_section(PID_EIT, &sec1);
    let mut all_events = feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Advance past 2 s interval.
    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    all_events.extend(monitor.feed(&pkt, secs(3)).to_vec());
    assert!(has_indicator(&all_events, Indicator::EitPfError));
}

#[test]
fn eit_pf_error_absent_when_both_sections_present() {
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed EIT P/F section 0 for service 1
    let sec0 = build_eit_pf_actual_section_keyed(0, 1, 1, 1);
    let packets0 = packetise_section(PID_EIT, &sec0);
    feed_all(&mut monitor, &packets0, ms(5), ms(1));

    // Feed EIT P/F section 1 for service 1 (same sub-table)
    let sec1 = build_eit_pf_actual_section_keyed(1, 1, 1, 1);
    let packets1 = packetise_section(PID_EIT, &sec1);
    feed_all(&mut monitor, &packets1, ms(10), ms(1));

    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    let events = monitor.feed(&pkt, ms(15));
    assert!(!has_indicator(events, Indicator::EitPfError));
}

#[test]
fn eit_pf_error_per_sub_table_not_global() {
    // Service 0x10 has only section 0 → error.
    // Service 0x20 has both sections → no error.
    // If the check were global, both services would look fine.
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    let mut all_events = Vec::new();

    // Section 0 for service 0x10 (incomplete — first_incomplete_at = t=5ms)
    let sec0_a = build_eit_pf_actual_section_keyed(0, 0x10, 1, 1);
    let p0_a = packetise_section(PID_EIT, &sec0_a);
    all_events.extend(feed_all(&mut monitor, &p0_a, ms(5), ms(1)));

    // Both sections for service 0x20 (complete — both arrive, error clears)
    let sec0_b = build_eit_pf_actual_section_keyed(0, 0x20, 1, 1);
    let p0_b = packetise_section(PID_EIT, &sec0_b);
    all_events.extend(feed_all(&mut monitor, &p0_b, ms(10), ms(1)));
    let sec1_b = build_eit_pf_actual_section_keyed(1, 0x20, 1, 1);
    let p1_b = packetise_section(PID_EIT, &sec1_b);
    all_events.extend(feed_all(&mut monitor, &p1_b, ms(15), ms(1)));

    // Advance past 2 s — only service 0x10 should fire EitPfError.
    let pkt = make_ts_packet(0x200, 0, false, false, &[], &[]);
    all_events.extend(monitor.feed(&pkt, secs(3)).to_vec());

    assert!(has_indicator(&all_events, Indicator::EitPfError));
    let pf_events: Vec<_> = all_events
        .iter()
        .filter(|e| e.indicator == Indicator::EitPfError)
        .collect();
    assert_eq!(
        pf_events.len(),
        1,
        "expected exactly 1 EitPfError (service 0x10 only), got {}: {pf_events:?}",
        pf_events.len()
    );
    assert!(pf_events[0].detail.contains("0x0010"));
}

#[test]
fn nit_other_on_eit_pid_no_error() {
    // EIT_other on PID 0x0010 is valid — NIT_other goes on PID_NIT.
    // Verify that EitOtherError fires on PID_EIT, not PID_NIT.
    let mut monitor = ConformanceMonitor::new();
    acquire_sync(&mut monitor);

    // Feed EIT_other section on PID_EIT at t=5ms
    let sec = build_eit_other_section(0);
    let packets = packetise_section(PID_EIT, &sec);
    feed_all(&mut monitor, &packets, ms(5), ms(1));

    // Second occurrence at t=15s (exceeds 10s limit)
    let packets2 = packetise_section(PID_EIT, &sec);
    let events = feed_all(&mut monitor, &packets2, secs(15), ms(1));
    assert!(has_indicator(&events, Indicator::EitOtherError));
}