dvb-si 17.0.0

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
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
//! Section-repetition scheduling of the PSI/SI a DVB transport stream carries.
//!
//! A multiplexer has to put its PAT, PMT and the SI tables on the air at the
//! interval the specification asks for, re-sending each one every so often and
//! keeping each PID's continuity counter continuous across every table it
//! carries. [`SiMux`] is that scheduler: register each complete
//! [`Section`] with its interval, poll it with the caller's clock, and it
//! emits the 188-byte packets due.
//!
//! A DVB table's maximum interval is ETSI TR 101 211 §4.4's
//! (`private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md`); a PSI
//! table's is ETSI TS 101 154 V2.10.1 §4.1.7's
//! (`private/specs-verified/dvb/dvb-si/tables/ts_101_154/417-program-specific-information-psi-repetition-hand-transcribed.md`; [`PAT_MAX_INTERVAL`],
//! [`PMT_MAX_INTERVAL`]). The measurement side of the same intervals is
//! TR 101 290 v1.4.1 Table 5.0c (`dvb_conformance::repetition`).

use alloc::collections::VecDeque;
use alloc::vec::Vec;
use core::num::NonZeroUsize;
use core::time::Duration;

use broadcast_core::Parse;
use broadcast_core::stage::Instant;
use mpeg_ts::mux::{SectionPacketiser, split_sections};
use mpeg_ts::pid::{Pid, well_known};
use mpeg_ts::section::Section;
use mpeg_ts::ts::TS_PACKET_SIZE;

use crate::sub_table::SubTableId;

/// `table_id` of the PAT (ISO/IEC 13818-1 §2.4.4.3).
const PAT_TABLE_ID: u8 = crate::table_id::TableId::Pat as u8;
/// `table_id` of the PMT (ISO/IEC 13818-1 §2.4.4.8).
const PMT_TABLE_ID: u8 = crate::table_id::TableId::Pmt as u8;
/// `table_id` of the NIT actual (ETSI EN 300 468 §5.2.1).
const NIT_ACTUAL_TABLE_ID: u8 = crate::table_id::TableId::NetworkInformationActual as u8;
/// `table_id` of the SDT actual (ETSI EN 300 468 §5.2.3).
const SDT_ACTUAL_TABLE_ID: u8 = crate::table_id::TableId::ServiceDescriptionActual as u8;
/// `table_id` of the TDT (ETSI EN 300 468 §5.2.5).
const TDT_TABLE_ID: u8 = crate::table_id::TableId::TimeAndDate as u8;
/// `table_id` of the TOT (ETSI EN 300 468 §5.2.6).
const TOT_TABLE_ID: u8 = crate::table_id::TableId::TimeOffset as u8;

// ── Interval constants ──────────────────────────────────────────────────────

/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — NIT maximum interval.
pub const NIT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(10));
/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — BAT maximum interval.
pub const BAT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(10));
/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — SDT actual maximum interval.
pub const SDT_ACTUAL_MAX_INTERVAL: SectionInterval =
    SectionInterval::from_const(Duration::from_secs(2));
/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — SDT other maximum interval.
pub const SDT_OTHER_MAX_INTERVAL: SectionInterval =
    SectionInterval::from_const(Duration::from_secs(10));
/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — EIT present/following actual maximum interval.
pub const EIT_PF_ACTUAL_MAX_INTERVAL: SectionInterval =
    SectionInterval::from_const(Duration::from_secs(2));
/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1 — EIT present/following other maximum interval
/// (satellite and cable; §4.4.2 gives 20 s for terrestrial).
pub const EIT_PF_OTHER_MAX_INTERVAL: SectionInterval =
    SectionInterval::from_const(Duration::from_secs(10));
/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1 — EIT schedule (first 8 days) maximum interval.
pub const EIT_SCHED_MAX_INTERVAL: SectionInterval =
    SectionInterval::from_const(Duration::from_secs(10));
/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1 — EIT schedule (further than 8 days ahead) maximum interval.
pub const EIT_SCHED_EXT_MAX_INTERVAL: SectionInterval =
    SectionInterval::from_const(Duration::from_secs(30));
/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — TDT maximum interval.
pub const TDT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(30));
/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — TOT maximum interval.
pub const TOT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(30));

/// The inter-section repetition interval of one table (EN 300 468 §5.1.4.1):
/// a [`Duration`] that is never below [`MIN_SECTION_INTERVAL`].
///
/// The 25 ms floor used to be a `debug_assert!` inside [`SiMux::upsert`], so a
/// release build accepted `Duration::ZERO` (one section every poll) silently.
/// The bound is a property of the interval itself, so it is checked here, once.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct SectionInterval(Duration);

/// A repetition interval below the EN 300 468 §5.1.4.1 floor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("section interval {interval:?} is below the {min:?} minimum (EN 300 468 §5.1.4.1)")]
#[non_exhaustive]
pub struct SectionIntervalTooShort {
    /// The rejected interval.
    pub interval: Duration,
    /// The floor it must reach ([`MIN_SECTION_INTERVAL`]).
    pub min: Duration,
}

impl SectionInterval {
    /// Validate `interval` against the EN 300 468 §5.1.4.1 25 ms floor.
    ///
    /// # Errors
    /// [`SectionIntervalTooShort`] when `interval < MIN_SECTION_INTERVAL`.
    pub const fn try_new(
        interval: Duration,
    ) -> core::result::Result<Self, SectionIntervalTooShort> {
        // A `Duration` comparison is not usable in a `const fn`; compare nanos.
        if interval.as_nanos() < MIN_SECTION_INTERVAL_NANOS {
            Err(SectionIntervalTooShort {
                interval,
                min: MIN_SECTION_INTERVAL,
            })
        } else {
            Ok(Self(interval))
        }
    }

    /// Validate at compile time, for the spec's own named intervals
    /// ([`PAT_MAX_INTERVAL`] and friends): a mistyped interval is then a build
    /// error rather than a run-time `try_new`.
    ///
    /// # Panics
    /// In a `const` context, when `interval < MIN_SECTION_INTERVAL`.
    #[must_use]
    pub const fn from_const(interval: Duration) -> Self {
        assert!(
            interval.as_nanos() >= MIN_SECTION_INTERVAL_NANOS,
            "named section interval is below the 25 ms minimum (EN 300 468 §5.1.4.1)"
        );
        Self(interval)
    }

    /// The interval.
    #[must_use]
    pub const fn duration(self) -> Duration {
        self.0
    }
}

impl TryFrom<Duration> for SectionInterval {
    type Error = SectionIntervalTooShort;
    fn try_from(interval: Duration) -> core::result::Result<Self, Self::Error> {
        Self::try_new(interval)
    }
}

impl From<SectionInterval> for Duration {
    fn from(interval: SectionInterval) -> Self {
        interval.0
    }
}

/// private/specs-verified/dvb/dvb-si/tables/en_300_468/514-repetition-rates-and-random-access-hand-transcribed.md
/// §5.1.4.1 — minimum inter-section interval floor (≤100 Mbit/s TSs).
pub const MIN_SECTION_INTERVAL: Duration = Duration::from_millis(25);
/// [`MIN_SECTION_INTERVAL`] in nanoseconds, for the `const` comparisons.
const MIN_SECTION_INTERVAL_NANOS: u128 = 25_000_000;

/// ETSI TS 101 154 V2.10.1 §4.1.7 — PAT maximum interval (100 ms; a `shall` in distribution applications).
pub const PAT_MAX_INTERVAL: SectionInterval =
    SectionInterval::from_const(Duration::from_millis(100));
/// ETSI TS 101 154 V2.10.1 §4.1.7 — PMT maximum interval (100 ms; a `shall` in distribution applications).
pub const PMT_MAX_INTERVAL: SectionInterval =
    SectionInterval::from_const(Duration::from_millis(100));

// ── SiMux ────────────────────────────────────────────────────────────────────

/// The key one scheduled section is stored under: the PID it is carried on,
/// its `table_id`, its `section_number` and, for a long-form section, the
/// sub_table it belongs to (ISO/IEC 13818-1 §2.4.4 / EN 300 468 §5.2): the
/// `table_id_extension`, `current_next_indicator` and, for the SDT and EIT,
/// the identifying fields after the header (see [`crate::sub_table`]).
/// Several distinct tables share a PID by spec (TDT/TOT both on `0x0014`,
/// SDT/BAT both on `0x0011`, the present/following EIT of every service on
/// `0x0012`, several program_map_sections on one PMT PID), so neither PID
/// plus `table_id` nor PID plus `section_number` names a section.
///
/// [`SectionKey::new`] names no sub_table: [`SiMux::remove`] takes it to mean
/// every sub_table's section `section_number` of that `table_id` on the PID.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct SectionKey {
    /// The PID the section is carried on.
    pub pid: Pid,
    /// `table_id` (ISO/IEC 13818-1 §2.4.4.1).
    pub table_id: u8,
    /// `section_number`: the section's position in its table.
    pub section_number: u8,
    /// The sub_table of a long-form section; `None` for a short-form one.
    pub sub_table: Option<SubTableId>,
}

impl SectionKey {
    /// The key of the section `section_number` of table `table_id` on `pid`,
    /// naming no sub_table.
    #[must_use]
    pub const fn new(pid: Pid, table_id: u8, section_number: u8) -> Self {
        Self {
            pid,
            table_id,
            section_number,
            sub_table: None,
        }
    }

    /// This key within `sub_table`.
    #[must_use]
    pub const fn in_sub_table(mut self, sub_table: SubTableId) -> Self {
        self.sub_table = Some(sub_table);
        self
    }

    fn covers(&self, stored: &Self) -> bool {
        self.pid == stored.pid
            && self.table_id == stored.table_id
            && self.section_number == stored.section_number
            && self.sub_table.is_none_or(|s| Some(s) == stored.sub_table)
    }
}

/// A section [`SiMux::upsert`] could not schedule, kept so the caller can
/// see what was refused rather than having it dropped without a word.
///
/// The section itself is not retained: the bytes are the caller's, and a
/// rejection names only where they were registered and why they cannot be
/// emitted.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct RejectedSection {
    /// The PID the section was registered on.
    pub pid: Pid,
    /// Why it was rejected.
    pub reason: SectionRejection,
}

/// Why [`SiMux::upsert`] could not put a section into the emission
/// schedule.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum SectionRejection {
    /// The input held no complete section (an empty slice, or a header that
    /// declares more bytes than were given), so there is nothing to parse.
    /// An empty input used to register a whole `(pid, table_id 0)` entry and
    /// emit the PAT interval's worth of nothing.
    NotASection,
    /// Two or more sections were given for one PID. A `SectionKey` names one
    /// section, so a batch is ambiguous; register each on its own call.
    MoreThanOneSection,
    /// Several sections on one PID carried the same `(table_id,
    /// section_number)` and sub_table: the second would silently replace the first.
    DuplicateSection,
    /// The section bytes did not parse as a section header.
    Malformed,
    /// A convenience registration received a section of another table: a
    /// `table_id` other than the one that registration is for.
    WrongTableId {
        /// The `table_id` the registration is for.
        expected: u8,
        /// The `table_id` the section carries, if its header fit.
        found: Option<u8>,
    },
}

impl SectionRejection {
    /// A label for the rejection.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            SectionRejection::NotASection => "not_a_section",
            SectionRejection::MoreThanOneSection => "more_than_one_section",
            SectionRejection::DuplicateSection => "duplicate_section",
            SectionRejection::Malformed => "malformed",
            SectionRejection::WrongTableId { .. } => "wrong_table_id",
        }
    }
}

broadcast_core::impl_spec_display!(SectionRejection);

/// Section-repetition scheduler that builds TS packets on a caller-supplied clock.
///
/// Each entry is one complete [section](mpeg_ts::section::Section) — its
/// `table_id` and `section_number` identify it, its PID + interval say where
/// and how often it goes out. Call [`poll_into`](Self::poll_into) with
/// monotonically-increasing `now` values to get 188-byte TS packets for every
/// entry whose interval has elapsed since its last emission.
///
/// Entries are keyed by [`SectionKey`]: the PID, `table_id`, `section_number` and sub_table.
/// A section is given as a single `Section`: the length and CRC are derived
/// from the section's own fields when it is packetised, so a caller cannot
/// hand the scheduler bytes that are not a section, sections of mixed tables,
/// or a trailing truncated section that used to be dropped without a word.
/// Input that cannot be scheduled is kept and reported by
/// [`rejected`](Self::rejected) ([`RejectedSection`]).
///
/// All entries on the same PID share one [`SectionPacketiser`] (and so one
/// continuity counter), created lazily the first time that PID emits — this
/// is what keeps the continuity counter continuous per PID across table
/// kinds, not just within one kind.
///
/// # 25 ms floor
///
/// [`MIN_SECTION_INTERVAL`] is the minimum valid interval (EN 300 468 §5.1.4.1),
/// enforced by [`SectionInterval::try_new`]: an interval below it cannot reach
/// [`upsert`](Self::upsert) at all.
pub struct SiMux {
    entries: Vec<Entry>,
    rejected: VecDeque<RejectedSection>,
    max_rejected: usize,
    rejected_dropped: u64,
    /// One packetiser per distinct PID, shared across every table_id on it.
    packetisers: Vec<SectionPacketiser>,
}

struct Entry {
    key: SectionKey,
    section: Vec<u8>,
    interval: SectionInterval,
    last_emit: Option<Instant>,
}

/// Find the packetiser for `pid`, creating one (fresh continuity counter) if
/// this is the first entry ever registered on that PID. A free function, not
/// a method, so callers can hold `&mut entries` and this borrow concurrently.
fn packetiser_for(packetisers: &mut Vec<SectionPacketiser>, pid: Pid) -> &mut SectionPacketiser {
    if let Some(idx) = packetisers.iter().position(|p| p.pid() == pid) {
        &mut packetisers[idx]
    } else {
        packetisers.push(SectionPacketiser::new(pid));
        let last = packetisers.len() - 1;
        &mut packetisers[last]
    }
}

/// The caller's bound on what a [`SiMux`] keeps.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SiMuxLimits {
    /// How many [`RejectedSection`]s [`SiMux::rejected`] holds; past it the
    /// oldest is dropped and counted in [`SiMux::rejected_dropped`].
    pub max_rejected: NonZeroUsize,
}

impl SiMux {
    /// Create an empty scheduler (no entries, no pending emissions).
    #[must_use]
    pub fn new(limits: SiMuxLimits) -> Self {
        Self {
            entries: Vec::new(),
            rejected: VecDeque::new(),
            max_rejected: limits.max_rejected.get(),
            rejected_dropped: 0,
            packetisers: Vec::new(),
        }
    }

    fn reject(&mut self, pid: Pid, reason: SectionRejection) {
        if self.rejected.len() >= self.max_rejected {
            self.rejected.pop_front();
            self.rejected_dropped = self.rejected_dropped.saturating_add(1);
        }
        self.rejected.push_back(RejectedSection { pid, reason });
    }

    /// Register or replace one section carried on `pid` at `interval` (a
    /// validated [`SectionInterval`]: EN 300 468 §5.1.4.1's 25 ms floor).
    ///
    /// The section is stored under its own [`SectionKey`], so re-calling for
    /// the same key (`pid`, `table_id`, `section_number` and sub_table) updates that one section
    /// and its interval while preserving the PID's shared continuity counter;
    /// any other section becomes a second, independent entry.
    ///
    /// # Errors
    ///
    /// Returns the [`SectionRejection`] for a section that cannot be
    /// scheduled: [`NotASection`](SectionRejection::NotASection) (the input
    /// held no complete section, so the key would not be its own),
    /// [`MoreThanOneSection`](SectionRejection::MoreThanOneSection) (a
    /// [`SectionKey`] names one section, so a batch is ambiguous),
    /// [`DuplicateSection`](SectionRejection::DuplicateSection) or
    /// [`Malformed`](SectionRejection::Malformed) or
    /// [`WrongTableId`](SectionRejection::WrongTableId). Every rejection is
    /// kept in [`rejected`](Self::rejected).
    pub fn upsert(
        &mut self,
        pid: Pid,
        section: Vec<u8>,
        interval: SectionInterval,
    ) -> core::result::Result<(), SectionRejection> {
        let rejection = self.register(pid, section, interval);
        match rejection {
            Some(reason) => {
                self.reject(pid, reason);
                Err(reason)
            }
            None => Ok(()),
        }
    }

    /// Register one complete section, replacing the entry already stored
    /// under its key.
    fn register(
        &mut self,
        pid: Pid,
        section: Vec<u8>,
        interval: SectionInterval,
    ) -> Option<SectionRejection> {
        let batch = split_sections(&section);
        let owned = match batch.len() {
            0 => return Some(SectionRejection::NotASection),
            1 => match Section::parse(batch[0]) {
                Ok(parsed) => parsed,
                Err(_) => return Some(SectionRejection::Malformed),
            },
            _ => {
                if !sections_are_distinct(&batch) {
                    return Some(SectionRejection::DuplicateSection);
                }
                return Some(SectionRejection::MoreThanOneSection);
            }
        };
        let sub_table = if owned.section_syntax_indicator {
            Some(SubTableId::of_section(&owned))
        } else {
            None
        };
        let key = SectionKey {
            pid,
            table_id: owned.table_id,
            section_number: owned.section_number,
            sub_table,
        };
        let Ok(stored) = owned.serialize() else {
            return Some(SectionRejection::Malformed);
        };
        if let Some(entry) = self.entries.iter_mut().find(|e| e.key == key) {
            if entry.section != stored {
                entry.last_emit = None;
            }
            entry.section = stored;
            entry.interval = interval;
        } else {
            self.entries.push(Entry {
                key,
                section: stored,
                interval,
                last_emit: None,
            });
        }
        None
    }

    /// Stop sending the section stored under `key` (every sub_table's, when
    /// the key names none). Returns whether any was scheduled. The PID's shared continuity counter is kept, so a later
    /// section on that PID continues the count.
    pub fn remove(&mut self, key: SectionKey) -> bool {
        let before = self.entries.len();
        self.entries.retain(|e| !key.covers(&e.key));
        self.entries.len() != before
    }

    /// The key of every scheduled section, in registration order.
    pub fn keys(&self) -> impl Iterator<Item = SectionKey> + '_ {
        self.entries.iter().map(|e| e.key)
    }

    /// The sections that could not be scheduled, with why, in the order they
    /// were refused, oldest first; at most [`SiMuxLimits::max_rejected`] are
    /// held, and a dropped one is counted by
    /// [`rejected_dropped`](Self::rejected_dropped). Read it after
    /// [`upsert`](Self::upsert) to surface a bad input instead of trusting the
    /// scheduler to have taken everything.
    pub fn rejected(&self) -> impl ExactSizeIterator<Item = &RejectedSection> + '_ {
        self.rejected.iter()
    }

    /// Take every held rejection, oldest first, leaving none.
    pub fn take_rejected(&mut self) -> Vec<RejectedSection> {
        self.rejected.drain(..).collect()
    }

    /// How many rejections were dropped to stay within
    /// [`SiMuxLimits::max_rejected`].
    #[must_use]
    pub fn rejected_dropped(&self) -> u64 {
        self.rejected_dropped
    }

    /// PAT at [`PAT_MAX_INTERVAL`] on PID 0x0000.
    ///
    /// # Errors
    ///
    /// As [`upsert`](Self::upsert); only a PAT section is accepted.
    pub fn upsert_pat(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
        upsert_checked(
            self,
            well_known::PAT,
            section,
            PAT_MAX_INTERVAL,
            PAT_TABLE_ID,
        )
    }

    /// PMT at [`PMT_MAX_INTERVAL`] on the caller-supplied `pid`.
    ///
    /// Interval cites private/specs-verified/dvb/dvb-si/ §4.1.7.
    ///
    /// # Errors
    ///
    /// As [`upsert`](Self::upsert); the PAT interval used to apply to whatever
    /// was stored under `table_id 0`, so only a PMT section is accepted.
    pub fn upsert_pmt(
        &mut self,
        pid: Pid,
        section: Vec<u8>,
    ) -> core::result::Result<(), SectionRejection> {
        upsert_checked(self, pid, section, PMT_MAX_INTERVAL, PMT_TABLE_ID)
    }

    /// SDT actual at [`SDT_ACTUAL_MAX_INTERVAL`] on PID 0x0011.
    ///
    /// Interval cites private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2.
    ///
    /// # Errors
    ///
    /// As [`upsert`](Self::upsert); only an SDT actual section is accepted.
    pub fn upsert_sdt_actual(
        &mut self,
        section: Vec<u8>,
    ) -> core::result::Result<(), SectionRejection> {
        upsert_checked(
            self,
            well_known::SDT_BAT,
            section,
            SDT_ACTUAL_MAX_INTERVAL,
            SDT_ACTUAL_TABLE_ID,
        )
    }

    /// NIT at [`NIT_MAX_INTERVAL`] on PID 0x0010.
    ///
    /// # Errors
    ///
    /// As [`upsert`](Self::upsert); only a NIT section is accepted.
    pub fn upsert_nit(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
        upsert_checked(
            self,
            well_known::NIT,
            section,
            NIT_MAX_INTERVAL,
            NIT_ACTUAL_TABLE_ID,
        )
    }

    /// TDT at [`TDT_MAX_INTERVAL`] on PID 0x0014.
    ///
    /// Interval cites private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2.
    ///
    /// # Errors
    ///
    /// As [`upsert`](Self::upsert); only a TDT section is accepted.
    pub fn upsert_tdt(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
        upsert_checked(
            self,
            well_known::TDT_TOT,
            section,
            TDT_MAX_INTERVAL,
            TDT_TABLE_ID,
        )
    }

    /// TOT at [`TOT_MAX_INTERVAL`] on PID 0x0014.
    ///
    /// Interval cites private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2.
    ///
    /// # Errors
    ///
    /// As [`upsert`](Self::upsert); only a TOT section is accepted.
    pub fn upsert_tot(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
        upsert_checked(
            self,
            well_known::TDT_TOT,
            section,
            TOT_MAX_INTERVAL,
            TOT_TABLE_ID,
        )
    }

    /// Emit every entry due at `now` (i.e. `now - last_emit >= interval`, and
    /// first call always due), packetising via [`SectionPacketiser`], appended
    /// to `out` (cleared first).
    ///
    /// Updates each emitted entry's `last_emit = now`. Deterministic given the
    /// fed `now` sequence. Returns the packet count appended.
    pub fn poll_into(&mut self, now: Instant, out: &mut Vec<[u8; TS_PACKET_SIZE]>) -> usize {
        out.clear();
        let before = out.len();

        let packetisers = &mut self.packetisers;
        for entry in &mut self.entries {
            let due = match entry.last_emit {
                None => true,
                Some(last) => now.saturating_duration_since(last) >= entry.interval.duration(),
            };
            if due {
                let mut tmp = Vec::new();
                let refs: [&[u8]; 1] = [&entry.section];
                let packetiser = packetiser_for(packetisers, entry.key.pid);
                packetiser.packetise_into(&refs, &mut tmp);
                out.append(&mut tmp);
                entry.last_emit = Some(now);
            }
        }

        out.len() - before
    }

    /// Allocating convenience wrapper over [`poll_into`](Self::poll_into).
    pub fn poll(&mut self, now: Instant) -> Vec<[u8; TS_PACKET_SIZE]> {
        let mut out = Vec::new();
        self.poll_into(now, &mut out);
        out
    }
}

fn sections_are_distinct(sections: &[&[u8]]) -> bool {
    let mut keys: Vec<(u8, u8, Option<SubTableId>)> = Vec::with_capacity(sections.len());
    for bytes in sections {
        let Ok(section) = Section::parse(bytes) else {
            return true;
        };
        let sub_table = if section.section_syntax_indicator {
            Some(SubTableId::of_section(&section))
        } else {
            None
        };
        let key = (section.table_id, section.section_number, sub_table);
        if keys.contains(&key) {
            return false;
        }
        keys.push(key);
    }
    true
}

/// The scheduler accepts only this `table_id` for a convenience registration
/// and otherwise keeps the section as rejected.
fn upsert_checked(
    mux: &mut SiMux,
    pid: Pid,
    section: Vec<u8>,
    interval: SectionInterval,
    table_id: u8,
) -> core::result::Result<(), SectionRejection> {
    if split_sections(&section)
        .first()
        .is_some_and(|s| s.first().copied() != Some(table_id))
    {
        let reason = SectionRejection::WrongTableId {
            expected: table_id,
            found: section.first().copied(),
        };
        mux.reject(pid, reason);
        return Err(reason);
    }
    mux.upsert(pid, section, interval)
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;
    use alloc::vec::Vec;
    use mpeg_ts::ts::{ContinuityCounter, SectionReassembler, TsPacket};

    fn test_mux() -> SiMux {
        SiMux::new(SiMuxLimits {
            max_rejected: NonZeroUsize::new(8).expect("non-zero"),
        })
    }

    fn concat_sections(sections: &[Vec<u8>]) -> Vec<u8> {
        let total: usize = sections.iter().map(|s| s.len()).sum();
        let mut out = Vec::with_capacity(total);
        for s in sections {
            out.extend_from_slice(s);
        }
        out
    }

    // ── interval constants pinned to spec ────────────────────────────────────

    #[test]
    fn interval_constants_match_spec() {
        // TR 101 211 §4.4.1/§4.4.2
        assert_eq!(NIT_MAX_INTERVAL.duration(), Duration::from_secs(10));
        assert_eq!(BAT_MAX_INTERVAL.duration(), Duration::from_secs(10));
        assert_eq!(SDT_ACTUAL_MAX_INTERVAL.duration(), Duration::from_secs(2));
        assert_eq!(SDT_OTHER_MAX_INTERVAL.duration(), Duration::from_secs(10));
        assert_eq!(
            EIT_PF_ACTUAL_MAX_INTERVAL.duration(),
            Duration::from_secs(2)
        );
        assert_eq!(
            EIT_PF_OTHER_MAX_INTERVAL.duration(),
            Duration::from_secs(10)
        );
        assert_eq!(EIT_SCHED_MAX_INTERVAL.duration(), Duration::from_secs(10));
        assert_eq!(
            EIT_SCHED_EXT_MAX_INTERVAL.duration(),
            Duration::from_secs(30)
        );
        assert_eq!(TDT_MAX_INTERVAL.duration(), Duration::from_secs(30));
        assert_eq!(TOT_MAX_INTERVAL.duration(), Duration::from_secs(30));

        // TS 101 154 V2.10.1 §4.1.7
        assert_eq!(PAT_MAX_INTERVAL.duration(), Duration::from_millis(100));
        assert_eq!(PMT_MAX_INTERVAL.duration(), Duration::from_millis(100));

        // EN 300 468 §5.1.4.1
        assert_eq!(MIN_SECTION_INTERVAL, Duration::from_millis(25));
    }

    // ── SiMux: basic behaviour ───────────────────────────────────────────────

    #[test]
    fn new_and_default_simux_are_empty() {
        let mut mux = test_mux();
        let pkts = mux.poll(Instant::ZERO);
        assert!(pkts.is_empty());
    }

    #[test]
    fn first_poll_always_emits() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
        let mut mux = test_mux();
        mux.upsert(
            Pid::from_const(0x0100),
            s.clone(),
            SectionInterval::from_const(Duration::from_millis(100)),
        )
        .expect("scheduled section");
        let pkts = mux.poll(Instant::ZERO);
        assert!(!pkts.is_empty(), "first poll must emit");
    }

    #[test]
    fn first_poll_emits_all_entries() {
        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01; 5]);
        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x02; 5]);
        let mut mux = test_mux();
        mux.upsert(
            Pid::from_const(0x0100),
            s1.clone(),
            SectionInterval::from_const(Duration::from_millis(100)),
        )
        .expect("scheduled section");
        mux.upsert(
            Pid::from_const(0x0200),
            s2.clone(),
            SectionInterval::from_const(Duration::from_millis(200)),
        )
        .expect("scheduled section");
        let pkts = mux.poll(Instant::ZERO);
        // Both entries should emit — we count PID occurrences
        let pids: Vec<Pid> = pkts
            .iter()
            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
            .collect();
        assert!(pids.contains(&Pid::from_const(0x0100)));
        assert!(pids.contains(&Pid::from_const(0x0200)));
    }

    // ── deterministic schedule ───────────────────────────────────────────────

    #[test]
    fn entry_emits_only_when_due() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
        let mut mux = test_mux();
        mux.upsert(
            Pid::from_const(0x0100),
            s.clone(),
            SectionInterval::from_const(Duration::from_millis(100)),
        )
        .expect("scheduled section");

        // First poll at t=0: emits
        let pkts0 = mux.poll(Instant::ZERO);
        assert!(!pkts0.is_empty());

        // t=50: not yet due
        let pkts50 = mux.poll(Instant::from_millis(50));
        assert!(pkts50.is_empty(), "should not emit at t=50");

        // t=99: still not due
        let pkts99 = mux.poll(Instant::from_millis(99));
        assert!(pkts99.is_empty(), "should not emit at t=99");

        // t=100: due again
        let pkts100 = mux.poll(Instant::from_millis(100));
        assert!(!pkts100.is_empty(), "should emit at t=100");
    }

    #[test]
    fn two_entries_different_cadence() {
        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01; 5]);
        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x02; 5]);
        let mut mux = test_mux();
        mux.upsert(
            Pid::from_const(0x0100),
            concat_sections(&[s1]),
            SectionInterval::from_const(Duration::from_millis(100)),
        )
        .expect("scheduled section");
        mux.upsert(
            Pid::from_const(0x0200),
            concat_sections(&[s2]),
            SectionInterval::from_const(Duration::from_millis(200)),
        )
        .expect("scheduled section");

        // t=0: both emit
        let pkts = mux.poll(Instant::ZERO);
        assert!(!pkts.is_empty());

        // t=100: only 0x0100 emits (due at 100)
        let pkts100 = mux.poll(Instant::from_millis(100));
        assert!(!pkts100.is_empty());
        let pids100: Vec<Pid> = pkts100
            .iter()
            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
            .collect();
        assert!(
            pids100.contains(&Pid::from_const(0x0100)),
            "PID 0x0100 should emit at t=100"
        );
        assert!(
            !pids100.contains(&Pid::from_const(0x0200)),
            "PID 0x0200 should NOT emit at t=100"
        );

        // t=150: neither emits
        let pkts150 = mux.poll(Instant::from_millis(150));
        assert!(pkts150.is_empty(), "neither should emit at t=150");

        // t=200: both emit again
        let pkts200 = mux.poll(Instant::from_millis(200));
        let pids200: Vec<Pid> = pkts200
            .iter()
            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
            .collect();
        assert!(
            pids200.contains(&Pid::from_const(0x0100)),
            "PID 0x0100 should emit at t=200"
        );
        assert!(
            pids200.contains(&Pid::from_const(0x0200)),
            "PID 0x0200 should emit at t=200"
        );
    }

    #[test]
    fn entry_emits_again_after_full_interval() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 20]);
        let mut mux = test_mux();
        mux.upsert(
            Pid::from_const(0x0100),
            s,
            SectionInterval::from_const(Duration::from_secs(1)),
        )
        .expect("scheduled section");

        // t=0
        let n0 = mux.poll_into(Instant::ZERO, &mut Vec::new());
        assert!(n0 > 0);

        // t=999ms: not due
        let mut buf = Vec::new();
        let n999 = mux.poll_into(Instant::from_millis(999), &mut buf);
        assert_eq!(n999, 0);

        // t=1s: due
        let mut buf2 = Vec::new();
        let n1000 = mux.poll_into(Instant::from_millis(1000), &mut buf2);
        assert!(n1000 > 0);
    }

    // ── upsert replaces existing entry (same pid + table_id only) ───────────

    #[test]
    fn upsert_updates_existing_entry() {
        // Same table_id (0x42, SDT actual) both times: this is a genuine
        // update of the same logical table, so it must replace, not add.
        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0xAA, 0xAA]);
        let s2 =
            test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0xBB, 0xBB, 0xBB]);
        let mut mux = test_mux();

        mux.upsert(
            Pid::from_const(0x0100),
            s1,
            SectionInterval::from_const(Duration::from_millis(100)),
        )
        .expect("scheduled section");
        mux.upsert(
            Pid::from_const(0x0100),
            s2.clone(),
            SectionInterval::from_const(Duration::from_millis(200)),
        )
        .expect("scheduled section");

        let pkts = mux.poll(Instant::ZERO);

        // Round-trip the output to verify the updated sections
        let mut reasm = SectionReassembler::default();
        for raw in &pkts {
            let pkt = TsPacket::parse(raw).unwrap();
            if pkt.header.pid == Pid::from_const(0x0100) {
                reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
            }
        }
        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
        assert_eq!(got.len(), 1);
        assert_eq!(got[0].as_ref(), s2.as_slice());
    }

    // ── issue #1000: distinct table_ids sharing a PID must NOT collide ──────

    /// Regression: `upsert_tdt` then `upsert_tot` (both PID 0x0014) used to
    /// collide because entries were keyed by PID alone — the second call
    /// silently replaced the first. Both table_ids must now come out, with a
    /// continuous continuity counter across the shared PID.
    #[test]
    fn upsert_tdt_then_tot_both_emitted_with_continuous_cc() {
        let tdt = test_fixtures::psi::long_section(0x70, 1, 0, 0, &[0xAA; 5]); // TDT
        let tot = test_fixtures::psi::long_section(0x73, 1, 0, 0, &[0xBB; 8]); // TOT
        let mut mux = test_mux();

        mux.upsert_tdt(tdt.clone()).expect("scheduled section");
        mux.upsert_tot(tot.clone()).expect("scheduled section");

        let pkts = mux.poll(Instant::ZERO);
        assert!(!pkts.is_empty());

        let mut table_ids_seen = Vec::new();
        let mut reasm = SectionReassembler::default();
        let mut prev_cc: Option<ContinuityCounter> = None;
        for raw in &pkts {
            let pkt = TsPacket::parse(raw).unwrap();
            assert_eq!(pkt.header.pid, well_known::TDT_TOT);
            if let Some(prev) = prev_cc {
                assert_eq!(
                    pkt.header.continuity_counter.forward_distance_from(prev),
                    1,
                    "continuity counter must be continuous across table kinds on one PID"
                );
            }
            prev_cc = Some(pkt.header.continuity_counter);
            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
        }
        while let Some(section) = reasm.pop_section() {
            table_ids_seen.push(section.as_ref()[0]);
        }

        assert!(table_ids_seen.contains(&0x70), "TDT missing from output");
        assert!(table_ids_seen.contains(&0x73), "TOT missing from output");
    }

    /// Same collision class for SDT actual (0x42) vs. BAT (0x4A), both on
    /// PID 0x0011.
    #[test]
    fn upsert_sdt_and_bat_both_emitted() {
        let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xCC; 5]);
        let bat = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0xDD; 6]);
        let mut mux = test_mux();

        mux.upsert_sdt_actual(sdt.clone())
            .expect("scheduled section");
        mux.upsert(
            well_known::SDT_BAT,
            bat.clone(),
            SectionInterval::from_const(Duration::from_millis(1000)),
        )
        .expect("scheduled section");

        let pkts = mux.poll(Instant::ZERO);
        let mut table_ids_seen = Vec::new();
        let mut reasm = SectionReassembler::default();
        for raw in &pkts {
            let pkt = TsPacket::parse(raw).unwrap();
            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
        }
        while let Some(section) = reasm.pop_section() {
            table_ids_seen.push(section.as_ref()[0]);
        }

        assert!(table_ids_seen.contains(&0x42), "SDT actual missing");
        assert!(table_ids_seen.contains(&0x4A), "BAT missing");
    }

    fn emitted_sections(mux: &mut SiMux) -> Vec<Vec<u8>> {
        let mut reasm = SectionReassembler::default();
        for raw in &mux.poll(Instant::ZERO) {
            let pkt = TsPacket::parse(raw).unwrap();
            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
        }
        core::iter::from_fn(|| reasm.pop_section())
            .map(|s| s.as_ref().to_vec())
            .collect()
    }

    fn eit_pf(service_id: u16, tsid: u16, onid: u16, tag: u8) -> Vec<u8> {
        let mut payload = Vec::new();
        payload.extend_from_slice(&tsid.to_be_bytes());
        payload.extend_from_slice(&onid.to_be_bytes());
        payload.extend_from_slice(&[0x00, 0x4E, tag]);
        test_fixtures::psi::long_section(0x4E, service_id, 0, 0, &payload)
    }

    fn sdt(tsid: u16, onid: u16, tag: u8) -> Vec<u8> {
        let mut payload = Vec::new();
        payload.extend_from_slice(&onid.to_be_bytes());
        payload.extend_from_slice(&[0xFF, tag]);
        test_fixtures::psi::long_section(0x46, tsid, 0, 0, &payload)
    }

    /// R11-c (#4711): the present/following EIT of several services shares
    /// one PID, table_id and section_number; each is its own sub_table.
    #[test]
    fn every_services_eit_present_following_is_scheduled() {
        let mut mux = test_mux();
        let sections: Vec<Vec<u8>> = (1..=3u16)
            .map(|svc| eit_pf(svc, 1000, 1, svc as u8))
            .collect();
        for section in &sections {
            mux.upsert(
                Pid::from_const(0x0012),
                section.clone(),
                EIT_PF_ACTUAL_MAX_INTERVAL,
            )
            .expect("scheduled");
        }
        assert_eq!(mux.keys().count(), 3);
        let mut got = emitted_sections(&mut mux);
        got.sort();
        let mut want = sections;
        want.sort();
        assert_eq!(got, want);
    }

    #[test]
    fn two_networks_sdt_other_with_one_transport_stream_id_are_both_scheduled() {
        let mut mux = test_mux();
        let (a, b) = (sdt(1000, 1, 0xA1), sdt(1000, 2, 0xB2));
        for section in [&a, &b] {
            mux.upsert(well_known::SDT_BAT, section.clone(), SDT_OTHER_MAX_INTERVAL)
                .expect("scheduled");
        }
        let mut got = emitted_sections(&mut mux);
        got.sort();
        let mut want = vec![a, b];
        want.sort();
        assert_eq!(got, want);
    }

    #[test]
    fn two_programmes_pmt_on_one_pid_are_both_scheduled() {
        let mut mux = test_mux();
        let (a, b) = (
            test_fixtures::psi::long_section(0x02, 1, 0, 0, &[0xE1, 0x00, 0xF0, 0x00]),
            test_fixtures::psi::long_section(0x02, 2, 0, 0, &[0xE1, 0x00, 0xF0, 0x00]),
        );
        for section in [&a, &b] {
            mux.upsert(Pid::from_const(0x0100), section.clone(), PMT_MAX_INTERVAL)
                .expect("scheduled");
        }
        assert_eq!(emitted_sections(&mut mux).len(), 2);
    }

    #[test]
    fn a_newer_section_of_the_same_sub_table_replaces_only_its_own() {
        let mut mux = test_mux();
        let pid = Pid::from_const(0x0012);
        for svc in [1u16, 2] {
            mux.upsert(pid, eit_pf(svc, 1000, 1, 0x10), EIT_PF_ACTUAL_MAX_INTERVAL)
                .expect("scheduled");
        }
        let newer = eit_pf(2, 1000, 1, 0x20);
        mux.upsert(pid, newer.clone(), EIT_PF_ACTUAL_MAX_INTERVAL)
            .expect("replaced");
        assert_eq!(mux.keys().count(), 2);
        let got = emitted_sections(&mut mux);
        assert!(got.contains(&newer));
        assert!(got.contains(&eit_pf(1, 1000, 1, 0x10)));
    }

    #[test]
    fn removing_a_key_without_a_sub_table_removes_every_sub_table_section() {
        let mut mux = test_mux();
        let pid = Pid::from_const(0x0012);
        for svc in [1u16, 2] {
            mux.upsert(pid, eit_pf(svc, 1000, 1, 0x10), EIT_PF_ACTUAL_MAX_INTERVAL)
                .expect("scheduled");
        }
        let one = mux.keys().next().expect("a key");
        assert!(mux.remove(one));
        assert_eq!(mux.keys().count(), 1);
        assert!(mux.remove(SectionKey::new(pid, 0x4E, 0)));
        assert_eq!(mux.keys().count(), 0);
    }

    #[test]
    fn the_rejection_log_is_bounded_and_counts_what_it_drops() {
        let mut mux = SiMux::new(SiMuxLimits {
            max_rejected: NonZeroUsize::new(2).expect("non-zero"),
        });
        for _ in 0..5 {
            mux.upsert(well_known::PAT, Vec::new(), PAT_MAX_INTERVAL)
                .expect_err("empty input is no section");
        }
        assert_eq!(mux.rejected().len(), 2);
        assert_eq!(mux.rejected_dropped(), 3);
        assert_eq!(mux.take_rejected().len(), 2);
        assert_eq!(mux.rejected().len(), 0);
    }

    // ── convenience constructors ─────────────────────────────────────────────

    #[test]
    fn upsert_sdt_actual_uses_correct_pid() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x01]);
        let mut mux = test_mux();
        mux.upsert_sdt_actual(s).expect("scheduled section");
        let pkts = mux.poll(Instant::ZERO);
        let pids: Vec<Pid> = pkts
            .iter()
            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
            .collect();
        assert!(pids.iter().all(|&p| p == well_known::SDT_BAT));
    }

    #[test]
    fn upsert_pat_uses_correct_pid() {
        let s = test_fixtures::psi::long_section(0x00, 1, 0, 0, &[0x01, 0x02]);
        let mut mux = test_mux();
        mux.upsert_pat(s).expect("scheduled section");
        let pkts = mux.poll(Instant::ZERO);
        assert!(!pkts.is_empty());
        let pids: Vec<Pid> = pkts
            .iter()
            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
            .collect();
        assert!(pids.iter().all(|&p| p == well_known::PAT));
        assert!(
            mux.poll(Instant::from_nanos(
                (PAT_MAX_INTERVAL.duration() / 2).as_nanos() as u64
            ))
            .is_empty()
        );
        assert!(
            !mux.poll(Instant::from_nanos(
                PAT_MAX_INTERVAL.duration().as_nanos() as u64
            ))
            .is_empty()
        );
    }

    #[test]
    fn upsert_nit_uses_correct_pid() {
        let s = test_fixtures::psi::long_section(0x40, 1, 0, 0, &[0x01]);
        let mut mux = test_mux();
        mux.upsert_nit(s).expect("scheduled section");
        let pkts = mux.poll(Instant::ZERO);
        assert!(!pkts.is_empty());
        let pids: Vec<Pid> = pkts
            .iter()
            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
            .collect();
        assert!(pids.iter().all(|&p| p == well_known::NIT));
        assert!(
            mux.poll(Instant::from_nanos(
                (NIT_MAX_INTERVAL.duration() / 2).as_nanos() as u64
            ))
            .is_empty()
        );
        assert!(
            !mux.poll(Instant::from_nanos(
                NIT_MAX_INTERVAL.duration().as_nanos() as u64
            ))
            .is_empty()
        );
    }

    #[test]
    fn upsert_tdt_uses_correct_pid() {
        let s = test_fixtures::psi::long_section(0x70, 1, 0, 0, &[0x01]);
        let mut mux = test_mux();
        mux.upsert_tdt(s).expect("scheduled section");
        let pkts = mux.poll(Instant::ZERO);
        let pids: Vec<Pid> = pkts
            .iter()
            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
            .collect();
        assert!(pids.iter().all(|&p| p == well_known::TDT_TOT));
    }

    #[test]
    fn upsert_tot_uses_correct_pid() {
        let s = test_fixtures::psi::long_section(0x73, 1, 0, 0, &[0x01]);
        let mut mux = test_mux();
        mux.upsert_tot(s).expect("scheduled section");
        let pkts = mux.poll(Instant::ZERO);
        let pids: Vec<Pid> = pkts
            .iter()
            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
            .collect();
        assert!(pids.iter().all(|&p| p == well_known::TDT_TOT));
    }

    // ── typed input: empty, mixed-table and trailing-garbage registrations ──

    #[test]
    fn upsert_rejects_an_empty_input() {
        // `table_id_of(&[])` used to return 0, so an empty registration
        // collided with the PAT entry on PID 0 and re-armed its interval.
        let mut mux = test_mux();
        let pat = test_fixtures::psi::pat_section(1, 0, &[(1, 0x1000)]);
        mux.upsert_pat(pat.clone()).expect("PAT is schedulable");
        assert_eq!(
            mux.upsert(well_known::PAT, Vec::new(), PAT_MAX_INTERVAL),
            Err(SectionRejection::NotASection)
        );
        assert_eq!(mux.rejected().len(), 1);
        assert_eq!(mux.rejected().next().expect("one").pid, well_known::PAT);
        let pkts = mux.poll(Instant::ZERO);
        let mut reasm = SectionReassembler::default();
        for raw in &pkts {
            let pkt = TsPacket::parse(raw).unwrap();
            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
        }
        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
        assert_eq!(got.len(), 1);
        assert_eq!(got[0].as_ref(), pat.as_slice());
    }

    #[test]
    fn upsert_rejects_two_sections_that_share_a_key() {
        let a = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x01]);
        let b = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x02]);
        let mut mux = test_mux();
        assert_eq!(
            mux.upsert(
                well_known::SDT_BAT,
                concat_sections(&[a, b]),
                SDT_ACTUAL_MAX_INTERVAL
            ),
            Err(SectionRejection::DuplicateSection)
        );
    }

    #[test]
    fn upsert_rejects_a_second_section_of_another_table() {
        let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x01]);
        let bat = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0x02]);
        let mut mux = test_mux();
        assert_eq!(
            mux.upsert(
                well_known::SDT_BAT,
                concat_sections(&[sdt, bat]),
                SDT_ACTUAL_MAX_INTERVAL
            ),
            Err(SectionRejection::MoreThanOneSection)
        );
    }

    #[test]
    fn upsert_keeps_a_complete_section_and_rejects_a_trailing_fragment() {
        // A truncated final section used to be dropped without a word, and
        // the caller could not tell it never went out.
        let whole = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x01]);
        let mut with_tail = whole.clone();
        with_tail.extend_from_slice(&[0x4A, 0x00]);
        let mut mux = test_mux();
        mux.upsert(well_known::SDT_BAT, with_tail, SDT_ACTUAL_MAX_INTERVAL)
            .expect("the complete section is schedulable");
        let pkts = mux.poll(Instant::ZERO);
        let mut reasm = SectionReassembler::default();
        for raw in &pkts {
            let pkt = TsPacket::parse(raw).unwrap();
            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
        }
        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
        assert_eq!(got.len(), 1);
        assert_eq!(got[0].as_ref(), whole.as_slice());
    }

    #[test]
    fn sections_of_one_table_are_keyed_by_their_section_number() {
        let first = test_fixtures::psi::long_section(
            0x4E,
            1,
            0,
            0,
            &[0x00, 0x01, 0x00, 0x01, 0x00, 0x4E, 0x01],
        );
        let second = test_fixtures::psi::long_section(
            0x4E,
            1,
            0,
            1,
            &[0x00, 0x01, 0x00, 0x01, 0x00, 0x4E, 0x02],
        );
        let mut mux = test_mux();
        let pid = Pid::from_const(0x0012);
        mux.upsert(pid, first.clone(), EIT_SCHED_MAX_INTERVAL)
            .expect("first section");
        mux.upsert(pid, second.clone(), EIT_SCHED_MAX_INTERVAL)
            .expect("second section");
        let pkts = mux.poll(Instant::ZERO);
        let mut reasm = SectionReassembler::default();
        for raw in &pkts {
            let pkt = TsPacket::parse(raw).unwrap();
            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
        }
        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
        assert_eq!(got.len(), 2, "both sections of the table must go out");
    }

    #[test]
    fn upsert_pat_rejects_a_section_of_another_table() {
        let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x01]);
        let mut mux = test_mux();
        assert_eq!(
            mux.upsert_pat(sdt),
            Err(SectionRejection::WrongTableId {
                expected: PAT_TABLE_ID,
                found: Some(0x42),
            })
        );
        assert!(mux.poll(Instant::ZERO).is_empty());
    }

    // ── round-trip through reassembler ───────────────────────────────────────

    #[test]
    fn simux_round_trip_single_entry() {
        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 20]);
        let interval = SectionInterval::from_const(Duration::from_millis(100));
        let mut mux = test_mux();
        mux.upsert(Pid::from_const(0x0100), s1.clone(), interval)
            .expect("scheduled section");

        let pkts = mux.poll(Instant::ZERO);

        let mut reasm = SectionReassembler::default();
        for raw in &pkts {
            let pkt = TsPacket::parse(raw).unwrap();
            if pkt.header.pid == Pid::from_const(0x0100) {
                reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
            }
        }
        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
        assert_eq!(got.len(), 1, "round-trip must recover the section");
        assert_eq!(got[0].as_ref(), s1.as_slice());
    }

    #[test]
    fn simux_round_trip_multi_pid() {
        let s_a = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xA0; 10]);
        let s_b = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xB0; 10]);
        let mut mux = test_mux();
        mux.upsert(
            Pid::from_const(0x0100),
            s_a.clone(),
            SectionInterval::from_const(Duration::from_millis(100)),
        )
        .expect("scheduled section");
        mux.upsert(
            Pid::from_const(0x0200),
            s_b.clone(),
            SectionInterval::from_const(Duration::from_millis(100)),
        )
        .expect("scheduled section");

        let pkts = mux.poll(Instant::ZERO);

        let mut reasm_a = SectionReassembler::default();
        let mut reasm_b = SectionReassembler::default();
        for raw in &pkts {
            let pkt = TsPacket::parse(raw).unwrap();
            match pkt.header.pid.value() {
                0x0100 => reasm_a.feed(pkt.payload.unwrap(), pkt.header.pusi),
                0x0200 => reasm_b.feed(pkt.payload.unwrap(), pkt.header.pusi),
                _ => {}
            }
        }
        let got_a: Vec<_> = core::iter::from_fn(|| reasm_a.pop_section()).collect();
        let got_b: Vec<_> = core::iter::from_fn(|| reasm_b.pop_section()).collect();
        assert_eq!(got_a.len(), 1);
        assert_eq!(got_b.len(), 1);
        assert_eq!(got_a[0].as_ref(), s_a.as_slice());
        assert_eq!(got_b[0].as_ref(), s_b.as_slice());
    }

    // ── CC continuity across polls ───────────────────────────────────────────

    #[test]
    fn continuity_counter_continuous_across_polls() {
        // Section large enough to span at least 2 packets.
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 250]);
        let mut mux = test_mux();
        mux.upsert(
            Pid::from_const(0x0100),
            s,
            SectionInterval::from_const(Duration::from_millis(100)),
        )
        .expect("scheduled section");

        let pkts1 = mux.poll(Instant::ZERO);
        assert!(pkts1.len() >= 2, "need ≥2 packets to test CC continuity");

        let last_cc_pkts1 = TsPacket::parse(&pkts1[pkts1.len() - 1])
            .unwrap()
            .header
            .continuity_counter;

        let pkts2 = mux.poll(Instant::from_millis(100));
        assert!(!pkts2.is_empty(), "second poll must emit");

        let first_cc_pkts2 = TsPacket::parse(&pkts2[0])
            .unwrap()
            .header
            .continuity_counter;

        assert_eq!(
            first_cc_pkts2.forward_distance_from(last_cc_pkts1),
            1,
            "CC must continue across poll cycles"
        );
    }

    // ── poll_into clears output ──────────────────────────────────────────────

    #[test]
    fn poll_into_clears_out_before_appending() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0xAA, 0xAA]);
        let mut mux = test_mux();
        mux.upsert(
            Pid::from_const(0x0100),
            s,
            SectionInterval::from_const(Duration::from_millis(100)),
        )
        .expect("scheduled section");

        let mut out = vec![[0u8; TS_PACKET_SIZE]; 42];
        let n = mux.poll_into(Instant::ZERO, &mut out);
        assert_eq!(n, out.len(), "out must contain only new packets");
    }

    // ── the 25 ms interval floor ─────────────────────────────────────────────

    /// The 25 ms floor is a `const` check on the spec's own named intervals, so
    /// a sub-floor one is a build error (verified by `from_const` panicking in
    /// a `const` context, which the `should_panic` surfaces here).
    #[test]
    #[should_panic(expected = "25 ms")]
    fn named_interval_const_rejects_sub_25ms_interval() {
        let _ = SectionInterval::from_const(Duration::from_millis(10));
    }

    /// EN 300 468 §5.1.4.1's 25 ms floor is enforced at construction, so a
    /// zero or sub-floor interval cannot reach the scheduler (it used to be a
    /// `debug_assert!` that release builds compiled out).
    #[test]
    fn section_interval_rejects_below_the_25ms_floor() {
        for bad in [
            Duration::ZERO,
            Duration::from_millis(1),
            Duration::from_millis(24),
            MIN_SECTION_INTERVAL - Duration::from_nanos(1),
        ] {
            let err = SectionInterval::try_new(bad).unwrap_err();
            assert_eq!(err.interval, bad);
            assert_eq!(err.min, MIN_SECTION_INTERVAL);
            assert!(SectionInterval::try_from(bad).is_err());
        }
        assert_eq!(
            SectionInterval::try_new(MIN_SECTION_INTERVAL)
                .expect("the floor itself is valid")
                .duration(),
            MIN_SECTION_INTERVAL
        );
        assert_eq!(
            Duration::from(SectionInterval::from_const(Duration::from_secs(2))),
            Duration::from_secs(2)
        );
    }

    #[test]
    fn upsert_accepts_25ms_interval() {
        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0xAA, 0xAA]);
        let mut mux = test_mux();
        mux.upsert(
            Pid::from_const(0x0100),
            s,
            SectionInterval::from_const(MIN_SECTION_INTERVAL),
        )
        .expect("scheduled section");
        let pkts = mux.poll(Instant::ZERO);
        assert!(!pkts.is_empty());
    }
}