Skip to main content

mpeg_ts/
mux.rs

1//! Section → TS packetiser (the byte-exact inverse of
2//! [`SectionReassembler::feed`](crate::ts::SectionReassembler::feed)).
3//!
4//! Per the PSI carriage rules of ITU-T H.222.0 §2.4.4 (= ISO/IEC 13818-1:2007 §2.4.4)
5//! (`private/specs-verified/mpeg/mpeg-ts/tables/h222_0/psi_section.md`): sections are packed into 188-byte packets
6//! with a `pointer_field` where sections begin, concatenated contiguously, and
7//! 0xFF-stuffed at the batch tail.
8
9use alloc::vec::Vec;
10use core::time::Duration;
11
12use broadcast_common::Parse;
13use broadcast_common::stage::Timestamp;
14
15use crate::pid::{Pid, well_known};
16use crate::section::Section;
17use crate::ts::{
18    AdaptationFieldControl, ContinuityCounter, ScramblingControl, TS_PACKET_SIZE, TsHeader,
19};
20
21/// `table_id` of the PAT (ISO/IEC 13818-1 §2.4.4.3).
22pub const TABLE_ID_PAT: u8 = 0x00;
23/// `table_id` of the PMT (ISO/IEC 13818-1 §2.4.4.8).
24pub const TABLE_ID_PMT: u8 = 0x02;
25/// `table_id` of the NIT actual (ETSI EN 300 468 §5.2.1).
26pub const TABLE_ID_NIT_ACTUAL: u8 = 0x40;
27/// `table_id` of the SDT actual (ETSI EN 300 468 §5.2.3).
28pub const TABLE_ID_SDT_ACTUAL: u8 = 0x42;
29/// `table_id` of the TDT (ETSI EN 300 468 §5.2.5).
30pub const TABLE_ID_TDT: u8 = 0x70;
31/// `table_id` of the TOT (ETSI EN 300 468 §5.2.6).
32pub const TABLE_ID_TOT: u8 = 0x73;
33
34/// Maximum data bytes in a PUSI=1 packet (188 − 4 header − 1 pointer_field). §2.4.4.
35const PUSI_PAYLOAD_CAP: usize = 183;
36/// Maximum data bytes in a continuation packet (188 − 4 header). §2.4.4.
37const PAYLOAD_CAP: usize = 184;
38use crate::ts::STUFFING_BYTE;
39
40/// Packetises PSI/SI sections into 188-byte TS packets.
41///
42/// This is the byte-exact inverse of
43/// [`SectionReassembler::feed`](crate::ts::SectionReassembler::feed): packets
44/// produced here, when fed back through the reassembler, yield the same
45/// sections in order.
46///
47/// ISO/IEC 13818-1:2007 §2.4.4 (`private/specs-verified/mpeg/mpeg-ts/tables/h222_0/psi_section.md`).
48pub struct SectionPacketiser {
49    pid: Pid,
50    continuity_counter: ContinuityCounter,
51}
52
53impl SectionPacketiser {
54    /// Start a packetiser for `pid` with continuity_counter = 0.
55    pub fn new(pid: Pid) -> Self {
56        Self {
57            pid,
58            continuity_counter: ContinuityCounter::ZERO,
59        }
60    }
61
62    /// Start at a specific continuity_counter — for resuming a stream.
63    pub fn with_continuity(pid: Pid, cc: ContinuityCounter) -> Self {
64        Self {
65            pid,
66            continuity_counter: cc,
67        }
68    }
69
70    /// The PID this packetiser emits packets for.
71    pub fn pid(&self) -> Pid {
72        self.pid
73    }
74
75    /// The continuity_counter for the next emitted packet.
76    pub fn continuity_counter(&self) -> ContinuityCounter {
77        self.continuity_counter
78    }
79
80    /// Packetise a batch of complete sections into 188-byte TS packets,
81    /// appended to `out` (cleared first).
82    ///
83    /// Returns the number of packets appended.
84    pub fn packetise_into(
85        &mut self,
86        sections: &[&[u8]],
87        out: &mut Vec<[u8; TS_PACKET_SIZE]>,
88    ) -> usize {
89        out.clear();
90
91        if sections.is_empty() {
92            return 0;
93        }
94
95        // Concatenate all sections and record section-start byte offsets.
96        let total_len: usize = sections.iter().map(|s| s.len()).sum();
97        if total_len == 0 {
98            return 0;
99        }
100        let mut data = Vec::with_capacity(total_len);
101        let mut starts = Vec::with_capacity(sections.len());
102        for s in sections {
103            starts.push(data.len());
104            data.extend_from_slice(s);
105        }
106
107        let count_before = out.len();
108        let mut pos = 0usize;
109        // `starts` is ascending and `pos` only advances, so a forward-only
110        // cursor finds the smallest section-start offset >= pos in amortised
111        // O(1) per packet instead of rescanning from the front (audit
112        // r01-O1: O(packets x sections)).
113        let mut next_idx = 0usize;
114
115        while pos < data.len() {
116            while starts.get(next_idx).is_some_and(|&s| s < pos) {
117                next_idx += 1;
118            }
119            let next_start = starts.get(next_idx).copied();
120
121            let pusi: bool;
122            let pointer_field: u8;
123            let cap: usize;
124
125            if let Some(ns) = next_start {
126                let diff = ns.saturating_sub(pos);
127                // W1 (#1074): `diff == PUSI_PAYLOAD_CAP` (183) must NOT take the
128                // PUSI branch — a pointer_field of 183 would claim a section
129                // starts after all 183 payload bytes, i.e. not within this
130                // packet at all (H.222.0 §2.4.4 requires PUSI=1 to mean a
131                // section genuinely starts here). The non-PUSI branch's cap
132                // must in turn be bounded by `diff`, not just the fixed
133                // 184-byte payload size, or a continuation packet at this same
134                // boundary copies one byte past the next section's start —
135                // the reassembler then silently drops it (it only takes what
136                // completes the in-progress section), corrupting the next one.
137                if diff < PUSI_PAYLOAD_CAP {
138                    pusi = true;
139                    pointer_field = diff as u8;
140                    cap = PUSI_PAYLOAD_CAP;
141                } else {
142                    pusi = false;
143                    pointer_field = 0;
144                    cap = PAYLOAD_CAP.min(diff);
145                }
146            } else {
147                pusi = false;
148                pointer_field = 0;
149                cap = PAYLOAD_CAP;
150            }
151
152            let mut pkt = [0u8; TS_PACKET_SIZE];
153
154            let header = TsHeader {
155                tei: false,
156                pusi,
157                pid: self.pid,
158                scrambling: ScramblingControl::NotScrambled,
159                adaptation_field_control: AdaptationFieldControl::PayloadOnly,
160                continuity_counter: self.continuity_counter,
161            };
162            pkt[..4].copy_from_slice(&header.to_bytes());
163
164            self.continuity_counter = self.continuity_counter.next();
165
166            let mut write_pos = 4usize;
167
168            if pusi {
169                pkt[write_pos] = pointer_field;
170                write_pos += 1;
171            }
172
173            let remaining = data.len() - pos;
174            let to_copy = remaining.min(cap);
175            pkt[write_pos..write_pos + to_copy].copy_from_slice(&data[pos..pos + to_copy]);
176            pos += to_copy;
177            write_pos += to_copy;
178
179            // 0xFF-stuff remaining payload bytes.
180            for b in &mut pkt[write_pos..] {
181                *b = STUFFING_BYTE;
182            }
183
184            out.push(pkt);
185        }
186
187        out.len() - count_before
188    }
189
190    /// Allocating convenience wrapper over [`packetise_into`](Self::packetise_into).
191    pub fn packetise(&mut self, sections: &[&[u8]]) -> Vec<[u8; TS_PACKET_SIZE]> {
192        let mut out = Vec::new();
193        self.packetise_into(sections, &mut out);
194        out
195    }
196}
197
198// ── Default interval constants ────────────────────────────────────────────────
199
200/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — NIT maximum interval.
201pub const NIT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(10));
202/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — BAT maximum interval.
203pub const BAT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(10));
204/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — SDT actual maximum interval.
205pub const SDT_ACTUAL_MAX_INTERVAL: SectionInterval =
206    SectionInterval::from_const(Duration::from_secs(2));
207/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — SDT other maximum interval.
208pub const SDT_OTHER_MAX_INTERVAL: SectionInterval =
209    SectionInterval::from_const(Duration::from_secs(10));
210/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — EIT present/following actual maximum interval.
211pub const EIT_PF_ACTUAL_MAX_INTERVAL: SectionInterval =
212    SectionInterval::from_const(Duration::from_secs(2));
213/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1 — EIT present/following other maximum interval
214/// (satellite and cable; §4.4.2 gives 20 s for terrestrial).
215pub const EIT_PF_OTHER_MAX_INTERVAL: SectionInterval =
216    SectionInterval::from_const(Duration::from_secs(10));
217/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1 — EIT schedule (first 8 days) maximum interval.
218pub const EIT_SCHED_MAX_INTERVAL: SectionInterval =
219    SectionInterval::from_const(Duration::from_secs(10));
220/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1 — EIT schedule (further than 8 days ahead) maximum interval.
221pub const EIT_SCHED_EXT_MAX_INTERVAL: SectionInterval =
222    SectionInterval::from_const(Duration::from_secs(30));
223/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — TDT maximum interval.
224pub const TDT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(30));
225/// private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2 — TOT maximum interval.
226pub const TOT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(30));
227
228/// The inter-section repetition interval of one table (EN 300 468 §5.1.4.1):
229/// a [`Duration`] that is never below [`MIN_SECTION_INTERVAL`].
230///
231/// The 25 ms floor used to be a `debug_assert!` inside [`SiMux::upsert`], so a
232/// release build accepted `Duration::ZERO` (one section every poll) silently.
233/// The bound is a property of the interval itself, so it is checked here, once.
234#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
235#[cfg_attr(feature = "serde", derive(serde::Serialize))]
236#[cfg_attr(feature = "serde", serde(transparent))]
237pub struct SectionInterval(Duration);
238
239/// A repetition interval below the EN 300 468 §5.1.4.1 floor.
240#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
241#[error("section interval {interval:?} is below the {min:?} minimum (EN 300 468 §5.1.4.1)")]
242#[non_exhaustive]
243pub struct SectionIntervalTooShort {
244    /// The rejected interval.
245    pub interval: Duration,
246    /// The floor it must reach ([`MIN_SECTION_INTERVAL`]).
247    pub min: Duration,
248}
249
250impl SectionInterval {
251    /// Validate `interval` against the EN 300 468 §5.1.4.1 25 ms floor.
252    ///
253    /// # Errors
254    /// [`SectionIntervalTooShort`] when `interval < MIN_SECTION_INTERVAL`.
255    pub const fn try_new(
256        interval: Duration,
257    ) -> core::result::Result<Self, SectionIntervalTooShort> {
258        // A `Duration` comparison is not usable in a `const fn`; compare nanos.
259        if interval.as_nanos() < MIN_SECTION_INTERVAL_NANOS {
260            Err(SectionIntervalTooShort {
261                interval,
262                min: MIN_SECTION_INTERVAL,
263            })
264        } else {
265            Ok(Self(interval))
266        }
267    }
268
269    /// Validate at compile time, for the spec's own named intervals
270    /// ([`PAT_MAX_INTERVAL`] and friends): a mistyped interval is then a build
271    /// error rather than a run-time `try_new`.
272    ///
273    /// # Panics
274    /// In a `const` context, when `interval < MIN_SECTION_INTERVAL`.
275    #[must_use]
276    pub const fn from_const(interval: Duration) -> Self {
277        assert!(
278            interval.as_nanos() >= MIN_SECTION_INTERVAL_NANOS,
279            "named section interval is below the 25 ms minimum (EN 300 468 §5.1.4.1)"
280        );
281        Self(interval)
282    }
283
284    /// The interval.
285    #[must_use]
286    pub const fn duration(self) -> Duration {
287        self.0
288    }
289}
290
291impl TryFrom<Duration> for SectionInterval {
292    type Error = SectionIntervalTooShort;
293    fn try_from(interval: Duration) -> core::result::Result<Self, Self::Error> {
294        Self::try_new(interval)
295    }
296}
297
298impl From<SectionInterval> for Duration {
299    fn from(interval: SectionInterval) -> Self {
300        interval.0
301    }
302}
303
304/// private/specs-verified/dvb/dvb-si/tables/en_300_468/514-repetition-rates-and-random-access-hand-transcribed.md
305/// §5.1.4.1 — minimum inter-section interval floor (≤100 Mbit/s TSs).
306pub const MIN_SECTION_INTERVAL: Duration = Duration::from_millis(25);
307/// [`MIN_SECTION_INTERVAL`] in nanoseconds, for the `const` comparisons.
308const MIN_SECTION_INTERVAL_NANOS: u128 = 25_000_000;
309
310/// private/specs-verified/dvb/dvb-si/ §4.1.7 — PAT maximum interval (shall ≤ 100 ms).
311pub const PAT_MAX_INTERVAL: SectionInterval =
312    SectionInterval::from_const(Duration::from_millis(100));
313/// private/specs-verified/dvb/dvb-si/ §4.1.7 — PMT maximum interval (shall ≤ 100 ms).
314pub const PMT_MAX_INTERVAL: SectionInterval =
315    SectionInterval::from_const(Duration::from_millis(100));
316
317// ── SiMux ────────────────────────────────────────────────────────────────────
318
319/// The key one scheduled section is stored under: the PID it is carried on
320/// and its identity inside that PID — `table_id` plus `section_number`
321/// (ISO/IEC 13818-1 §2.4.4.4 / EN 300 468 §5.2). Several distinct tables
322/// share a PID by spec (TDT/TOT both on `0x0014`, SDT/BAT both on `0x0011`,
323/// EIT present/following vs. schedule sub-tables on `0x0012`), and a long
324/// table spans several sections told apart by `section_number`, so neither
325/// PID alone nor PID plus `table_id` names a section.
326#[non_exhaustive]
327#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
328#[cfg_attr(feature = "serde", derive(serde::Serialize))]
329pub struct SectionKey {
330    /// The PID the section is carried on.
331    pub pid: Pid,
332    /// `table_id` (ISO/IEC 13818-1 §2.4.4.1).
333    pub table_id: u8,
334    /// `section_number`: the section's position in its table.
335    pub section_number: u8,
336}
337
338/// A section [`SiMux::upsert`] could not schedule, kept so the caller can
339/// see what was refused rather than having it dropped without a word.
340///
341/// The section itself is not retained: the bytes are the caller's, and a
342/// rejection names only where they were registered and why they cannot be
343/// emitted.
344#[non_exhaustive]
345#[derive(Debug, Clone, PartialEq, Eq)]
346#[cfg_attr(feature = "serde", derive(serde::Serialize))]
347pub struct RejectedSection {
348    /// The PID the section was registered on.
349    pub pid: Pid,
350    /// Why it was rejected.
351    pub reason: SectionRejection,
352}
353
354/// Why [`SiMux::upsert`] could not put a section into the emission
355/// schedule.
356#[non_exhaustive]
357#[derive(Debug, Clone, Copy, PartialEq, Eq)]
358#[cfg_attr(feature = "serde", derive(serde::Serialize))]
359pub enum SectionRejection {
360    /// The input held no complete section (an empty slice, or a header that
361    /// declares more bytes than were given), so there is nothing to parse.
362    /// An empty input used to register a whole `(pid, table_id 0)` entry and
363    /// emit the PAT interval's worth of nothing.
364    NotASection,
365    /// Two or more sections were given for one PID. A `SectionKey` names one
366    /// section, so a batch is ambiguous; register each on its own call.
367    MoreThanOneSection,
368    /// Several sections on one PID carried the same `(table_id,
369    /// section_number)`: the second would silently replace the first.
370    DuplicateSection,
371    /// The section bytes did not parse as a section header.
372    Malformed,
373    /// A convenience registration received a section of another table: a
374    /// `table_id` other than the one that registration is for.
375    WrongTableId {
376        /// The `table_id` the registration is for.
377        expected: u8,
378        /// The `table_id` the section carries, if its header fit.
379        found: Option<u8>,
380    },
381}
382
383impl SectionRejection {
384    /// A label for the rejection.
385    #[must_use]
386    pub fn name(&self) -> &'static str {
387        match self {
388            SectionRejection::NotASection => "not_a_section",
389            SectionRejection::MoreThanOneSection => "more_than_one_section",
390            SectionRejection::DuplicateSection => "duplicate_section",
391            SectionRejection::Malformed => "malformed",
392            SectionRejection::WrongTableId { .. } => "wrong_table_id",
393        }
394    }
395}
396
397broadcast_common::impl_spec_display!(SectionRejection);
398
399/// Section-repetition scheduler that builds TS packets on a caller-supplied clock.
400///
401/// Each entry is one complete [section](crate::section::Section) — its
402/// `table_id` and `section_number` identify it, its PID + interval say where
403/// and how often it goes out. Call [`poll_into`](Self::poll_into) with
404/// monotonically-increasing `now` values to get 188-byte TS packets for every
405/// entry whose interval has elapsed since its last emission.
406///
407/// Entries are keyed by [`SectionKey`]: `(pid, table_id, section_number)`.
408/// A section is given as a single `Section`: the length and CRC are derived
409/// from the section's own fields when it is packetised, so a caller cannot
410/// hand the scheduler bytes that are not a section, sections of mixed tables,
411/// or a trailing truncated section that used to be dropped without a word.
412/// Input that cannot be scheduled is kept and reported by
413/// [`rejected`](Self::rejected) ([`RejectedSection`]).
414///
415/// All entries on the same PID share one [`SectionPacketiser`] (and so one
416/// continuity counter), created lazily the first time that PID emits — this
417/// is what keeps the continuity counter continuous per PID across table
418/// kinds, not just within one kind.
419///
420/// # 25 ms floor
421///
422/// [`MIN_SECTION_INTERVAL`] is the minimum valid interval (EN 300 468 §5.1.4.1),
423/// enforced by [`SectionInterval::try_new`]: an interval below it cannot reach
424/// [`upsert`](Self::upsert) at all.
425pub struct SiMux {
426    entries: Vec<Entry>,
427    rejected: Vec<RejectedSection>,
428    /// One packetiser per distinct PID, shared across every table_id on it.
429    packetisers: Vec<SectionPacketiser>,
430}
431
432struct Entry {
433    key: SectionKey,
434    section: Section<'static>,
435    interval: SectionInterval,
436    last_emit: Option<Timestamp>,
437}
438
439/// Find the packetiser for `pid`, creating one (fresh continuity counter) if
440/// this is the first entry ever registered on that PID. A free function, not
441/// a method, so callers can hold `&mut entries` and this borrow concurrently.
442fn packetiser_for(packetisers: &mut Vec<SectionPacketiser>, pid: Pid) -> &mut SectionPacketiser {
443    if let Some(idx) = packetisers.iter().position(|p| p.pid() == pid) {
444        &mut packetisers[idx]
445    } else {
446        packetisers.push(SectionPacketiser::new(pid));
447        let last = packetisers.len() - 1;
448        &mut packetisers[last]
449    }
450}
451
452impl SiMux {
453    /// Create an empty scheduler (no entries, no pending emissions).
454    pub fn new() -> Self {
455        Self {
456            entries: Vec::new(),
457            rejected: Vec::new(),
458            packetisers: Vec::new(),
459        }
460    }
461
462    /// Register or replace one section carried on `pid` at `interval` (a
463    /// validated [`SectionInterval`]: EN 300 468 §5.1.4.1's 25 ms floor).
464    ///
465    /// The section is stored under its own [`SectionKey`], so re-calling for
466    /// the same `(pid, table_id, section_number)` updates that one section
467    /// and its interval while preserving the PID's shared continuity counter;
468    /// any other section becomes a second, independent entry.
469    ///
470    /// # Errors
471    ///
472    /// Returns the [`SectionRejection`] for a section that cannot be
473    /// scheduled: [`NotASection`](SectionRejection::NotASection) (the input
474    /// held no complete section, so the key would not be its own),
475    /// [`MoreThanOneSection`](SectionRejection::MoreThanOneSection) (a
476    /// [`SectionKey`] names one section, so a batch is ambiguous),
477    /// [`DuplicateSection`](SectionRejection::DuplicateSection) or
478    /// [`Malformed`](SectionRejection::Malformed) or
479    /// [`WrongTableId`](SectionRejection::WrongTableId). Every rejection is
480    /// kept in [`rejected`](Self::rejected).
481    pub fn upsert(
482        &mut self,
483        pid: Pid,
484        section: Vec<u8>,
485        interval: SectionInterval,
486    ) -> core::result::Result<(), SectionRejection> {
487        let rejection = self.register(pid, section, interval);
488        match rejection {
489            Some(reason) => {
490                self.rejected.push(RejectedSection { pid, reason });
491                Err(reason)
492            }
493            None => Ok(()),
494        }
495    }
496
497    /// Register one complete section, replacing the entry already stored
498    /// under its key.
499    fn register(
500        &mut self,
501        pid: Pid,
502        section: Vec<u8>,
503        interval: SectionInterval,
504    ) -> Option<SectionRejection> {
505        let batch = split_sections(&section);
506        let owned = match batch.len() {
507            0 => return Some(SectionRejection::NotASection),
508            1 => match Section::parse(batch[0]) {
509                Ok(parsed) => parsed,
510                Err(_) => return Some(SectionRejection::Malformed),
511            },
512            _ => {
513                if !sections_are_distinct(&batch) {
514                    return Some(SectionRejection::DuplicateSection);
515                }
516                return Some(SectionRejection::MoreThanOneSection);
517            }
518        };
519        let key = SectionKey {
520            pid,
521            table_id: owned.table_id,
522            section_number: owned.section_number,
523        };
524        let stored = Section::into_owned(owned);
525        if let Some(entry) = self.entries.iter_mut().find(|e| e.key == key) {
526            entry.section = stored;
527            entry.interval = interval;
528        } else {
529            self.entries.push(Entry {
530                key,
531                section: stored,
532                interval,
533                last_emit: None,
534            });
535        }
536        None
537    }
538
539    /// The sections that could not be scheduled, with why, in the order they
540    /// were refused. Never silently dropped: read it after
541    /// [`upsert`](Self::upsert) to surface a bad input instead of trusting the
542    /// scheduler to have taken everything.
543    #[must_use]
544    pub fn rejected(&self) -> &[RejectedSection] {
545        &self.rejected
546    }
547
548    /// PAT at [`PAT_MAX_INTERVAL`] on PID 0x0000.
549    ///
550    /// # Errors
551    ///
552    /// As [`upsert`](Self::upsert); only a PAT section is accepted.
553    pub fn upsert_pat(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
554        upsert_checked(
555            self,
556            well_known::PAT,
557            section,
558            PAT_MAX_INTERVAL,
559            TABLE_ID_PAT,
560        )
561    }
562
563    /// PMT at [`PMT_MAX_INTERVAL`] on the caller-supplied `pid`.
564    ///
565    /// Interval cites private/specs-verified/dvb/dvb-si/ §4.1.7.
566    ///
567    /// # Errors
568    ///
569    /// As [`upsert`](Self::upsert); the PAT interval used to apply to whatever
570    /// was stored under `table_id 0`, so only a PMT section is accepted.
571    pub fn upsert_pmt(
572        &mut self,
573        pid: Pid,
574        section: Vec<u8>,
575    ) -> core::result::Result<(), SectionRejection> {
576        upsert_checked(self, pid, section, PMT_MAX_INTERVAL, TABLE_ID_PMT)
577    }
578
579    /// SDT actual at [`SDT_ACTUAL_MAX_INTERVAL`] on PID 0x0011.
580    ///
581    /// Interval cites private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2.
582    ///
583    /// # Errors
584    ///
585    /// As [`upsert`](Self::upsert); only an SDT actual section is accepted.
586    pub fn upsert_sdt_actual(
587        &mut self,
588        section: Vec<u8>,
589    ) -> core::result::Result<(), SectionRejection> {
590        upsert_checked(
591            self,
592            well_known::SDT_BAT,
593            section,
594            SDT_ACTUAL_MAX_INTERVAL,
595            TABLE_ID_SDT_ACTUAL,
596        )
597    }
598
599    /// NIT at [`NIT_MAX_INTERVAL`] on PID 0x0010.
600    ///
601    /// # Errors
602    ///
603    /// As [`upsert`](Self::upsert); only a NIT section is accepted.
604    pub fn upsert_nit(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
605        upsert_checked(
606            self,
607            well_known::NIT,
608            section,
609            NIT_MAX_INTERVAL,
610            TABLE_ID_NIT_ACTUAL,
611        )
612    }
613
614    /// TDT at [`TDT_MAX_INTERVAL`] on PID 0x0014.
615    ///
616    /// Interval cites private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2.
617    ///
618    /// # Errors
619    ///
620    /// As [`upsert`](Self::upsert); only a TDT section is accepted.
621    pub fn upsert_tdt(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
622        upsert_checked(
623            self,
624            well_known::TDT_TOT,
625            section,
626            TDT_MAX_INTERVAL,
627            TABLE_ID_TDT,
628        )
629    }
630
631    /// TOT at [`TOT_MAX_INTERVAL`] on PID 0x0014.
632    ///
633    /// Interval cites private/specs-verified/dvb/dvb-si/text/tr_101_211/README.md §4.4.1/§4.4.2.
634    ///
635    /// # Errors
636    ///
637    /// As [`upsert`](Self::upsert); only a TOT section is accepted.
638    pub fn upsert_tot(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
639        upsert_checked(
640            self,
641            well_known::TDT_TOT,
642            section,
643            TOT_MAX_INTERVAL,
644            TABLE_ID_TOT,
645        )
646    }
647
648    /// Emit every entry due at `now` (i.e. `now - last_emit >= interval`, and
649    /// first call always due), packetising via [`SectionPacketiser`], appended
650    /// to `out` (cleared first).
651    ///
652    /// Updates each emitted entry's `last_emit = now`. Deterministic given the
653    /// fed `now` sequence. Returns the packet count appended.
654    pub fn poll_into(&mut self, now: Timestamp, out: &mut Vec<[u8; TS_PACKET_SIZE]>) -> usize {
655        out.clear();
656        let before = out.len();
657
658        let packetisers = &mut self.packetisers;
659        for entry in &mut self.entries {
660            let due = match entry.last_emit {
661                None => true,
662                Some(last) => now.saturating_sub(last) >= entry.interval.duration(),
663            };
664            if due {
665                let mut tmp = Vec::new();
666                if let Ok(bytes) = entry.section.serialize() {
667                    let refs: [&[u8]; 1] = [&bytes];
668                    let packetiser = packetiser_for(packetisers, entry.key.pid);
669                    packetiser.packetise_into(&refs, &mut tmp);
670                }
671                out.append(&mut tmp);
672                entry.last_emit = Some(now);
673            }
674        }
675
676        out.len() - before
677    }
678
679    /// Allocating convenience wrapper over [`poll_into`](Self::poll_into).
680    pub fn poll(&mut self, now: Timestamp) -> Vec<[u8; TS_PACKET_SIZE]> {
681        let mut out = Vec::new();
682        self.poll_into(now, &mut out);
683        out
684    }
685}
686
687fn sections_are_distinct(sections: &[&[u8]]) -> bool {
688    let mut keys: Vec<(u8, u8)> = Vec::with_capacity(sections.len());
689    for bytes in sections {
690        let Ok(section) = Section::parse(bytes) else {
691            return true;
692        };
693        let key = (section.table_id, section.section_number);
694        if keys.contains(&key) {
695            return false;
696        }
697        keys.push(key);
698    }
699    true
700}
701
702/// The scheduler accepts only this `table_id` for a convenience registration
703/// and otherwise keeps the section as rejected.
704fn upsert_checked(
705    mux: &mut SiMux,
706    pid: Pid,
707    section: Vec<u8>,
708    interval: SectionInterval,
709    table_id: u8,
710) -> core::result::Result<(), SectionRejection> {
711    if split_sections(&section)
712        .first()
713        .is_some_and(|s| s.first().copied() != Some(table_id))
714    {
715        let reason = SectionRejection::WrongTableId {
716            expected: table_id,
717            found: section.first().copied(),
718        };
719        mux.rejected.push(RejectedSection { pid, reason });
720        return Err(reason);
721    }
722    mux.upsert(pid, section, interval)
723}
724
725impl Default for SiMux {
726    fn default() -> Self {
727        Self::new()
728    }
729}
730
731/// Split concatenated complete-section bytes into individual `&[u8]` slices.
732///
733/// Walks the PSI/SI section headers: byte 0 = table_id, bytes 1-2 =
734/// section_length (12 bits). Each slice is 3 + section_length bytes long.
735/// Trailing bytes that don't form a complete section header are discarded.
736fn split_sections(data: &[u8]) -> Vec<&[u8]> {
737    let mut result = Vec::new();
738    let mut pos = 0;
739    while let Some(end) = crate::ts::section_total_len(&data[pos..]).map(|len| pos + len) {
740        if end > data.len() {
741            break;
742        }
743        result.push(&data[pos..end]);
744        pos = end;
745    }
746    result
747}
748
749#[cfg(test)]
750mod tests {
751    use super::*;
752    use crate::ts::{SectionReassembler, TsPacket};
753    use alloc::vec;
754    use alloc::vec::Vec;
755
756    // ── helpers ──────────────────────────────────────────────────────────────
757
758    fn concat_sections(sections: &[Vec<u8>]) -> Vec<u8> {
759        let total: usize = sections.iter().map(|s| s.len()).sum();
760        let mut out = Vec::with_capacity(total);
761        for s in sections {
762            out.extend_from_slice(s);
763        }
764        out
765    }
766
767    /// Round-trip `sections` through packetise → reassembler, asserting
768    /// byte-identical output in order and no leftovers.
769    fn assert_round_trip(sections: &[Vec<u8>]) {
770        let mut packetiser = SectionPacketiser::new(Pid::from_const(0x0100));
771        let refs: Vec<&[u8]> = sections.iter().map(|s| s.as_slice()).collect();
772        let packets = packetiser.packetise(&refs);
773
774        let mut reasm = SectionReassembler::default();
775        for pkt_raw in &packets {
776            let pkt = TsPacket::parse(pkt_raw).expect("parse generated packet");
777            let payload = pkt.payload.expect("payload present");
778            let pusi = pkt.header.pusi;
779            reasm.feed(payload, pusi);
780        }
781
782        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
783        assert_eq!(
784            got.len(),
785            sections.len(),
786            "section count mismatch: expected {}, got {}",
787            sections.len(),
788            got.len()
789        );
790        for (i, (orig, round)) in sections.iter().zip(got.iter()).enumerate() {
791            assert_eq!(
792                round.as_ref(),
793                orig.as_slice(),
794                "section {i} round-trip mismatch"
795            );
796        }
797        assert!(reasm.is_empty(), "reassembler should be empty after drain");
798    }
799
800    /// 400 sections whose sizes sweep 0..=399 body bytes (so section starts
801    /// land on every offset around the 183/184-byte packet boundaries)
802    /// round-trip byte-identically through packetise -> reassemble (audit
803    /// r01-O1: the section-start lookup is now a forward cursor; this is the
804    /// independent oracle that the rewrite chose the same boundaries).
805    #[test]
806    fn many_sections_with_boundary_straddling_sizes_round_trip() {
807        let sections: Vec<Vec<u8>> = (0..400usize)
808            .map(|n| {
809                let body: Vec<u8> = (0..n).map(|i| (i % 251) as u8).collect();
810                test_fixtures::psi::short_section((n % 200) as u8, &body)
811            })
812            .collect();
813        assert_round_trip(&sections);
814    }
815
816    // ── split_sections ──────────────────────────────────────────────────────
817
818    #[test]
819    fn split_single_section() {
820        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
821        let refs = split_sections(&s);
822        assert_eq!(refs.len(), 1);
823        assert_eq!(refs[0], s.as_slice());
824    }
825
826    #[test]
827    fn split_two_sections() {
828        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01, 0x02]);
829        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x03, 0x04, 0x05]);
830        let both = concat_sections(&[s1.clone(), s2.clone()]);
831        let refs = split_sections(&both);
832        assert_eq!(refs.len(), 2);
833        assert_eq!(refs[0], s1.as_slice());
834        assert_eq!(refs[1], s2.as_slice());
835    }
836
837    #[test]
838    fn split_empty_input() {
839        let refs = split_sections(&[]);
840        assert!(refs.is_empty());
841    }
842
843    #[test]
844    fn split_trailing_garbage_ignored() {
845        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 3]);
846        let mut data = s.clone();
847        data.push(0xFF); // trailing byte that doesn't complete a header
848        let refs = split_sections(&data);
849        assert_eq!(refs.len(), 1);
850        assert_eq!(refs[0], s.as_slice());
851    }
852
853    fn cc(v: u8) -> ContinuityCounter {
854        ContinuityCounter::try_new(v).expect("4-bit counter")
855    }
856
857    // ── interval constants pinned to spec ────────────────────────────────────
858
859    #[test]
860    fn interval_constants_match_spec() {
861        // TR 101 211 §4.4.1/§4.4.2
862        assert_eq!(NIT_MAX_INTERVAL.duration(), Duration::from_secs(10));
863        assert_eq!(BAT_MAX_INTERVAL.duration(), Duration::from_secs(10));
864        assert_eq!(SDT_ACTUAL_MAX_INTERVAL.duration(), Duration::from_secs(2));
865        assert_eq!(SDT_OTHER_MAX_INTERVAL.duration(), Duration::from_secs(10));
866        assert_eq!(
867            EIT_PF_ACTUAL_MAX_INTERVAL.duration(),
868            Duration::from_secs(2)
869        );
870        assert_eq!(
871            EIT_PF_OTHER_MAX_INTERVAL.duration(),
872            Duration::from_secs(10)
873        );
874        assert_eq!(EIT_SCHED_MAX_INTERVAL.duration(), Duration::from_secs(10));
875        assert_eq!(
876            EIT_SCHED_EXT_MAX_INTERVAL.duration(),
877            Duration::from_secs(30)
878        );
879        assert_eq!(TDT_MAX_INTERVAL.duration(), Duration::from_secs(30));
880        assert_eq!(TOT_MAX_INTERVAL.duration(), Duration::from_secs(30));
881
882        // TS 101 154 §4.1.7
883        assert_eq!(PAT_MAX_INTERVAL.duration(), Duration::from_millis(100));
884        assert_eq!(PMT_MAX_INTERVAL.duration(), Duration::from_millis(100));
885
886        // EN 300 468 §5.1.4.1
887        assert_eq!(MIN_SECTION_INTERVAL, Duration::from_millis(25));
888    }
889
890    // ── SiMux: basic behaviour ───────────────────────────────────────────────
891
892    #[test]
893    fn new_and_default_simux_are_empty() {
894        for mut mux in [SiMux::new(), SiMux::default()] {
895            let pkts = mux.poll(Timestamp::ZERO);
896            assert!(pkts.is_empty());
897        }
898    }
899
900    #[test]
901    fn first_poll_always_emits() {
902        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
903        let mut mux = SiMux::new();
904        mux.upsert(
905            Pid::from_const(0x0100),
906            s.clone(),
907            SectionInterval::from_const(Duration::from_millis(100)),
908        )
909        .expect("scheduled section");
910        let pkts = mux.poll(Timestamp::ZERO);
911        assert!(!pkts.is_empty(), "first poll must emit");
912    }
913
914    #[test]
915    fn first_poll_emits_all_entries() {
916        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01; 5]);
917        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x02; 5]);
918        let mut mux = SiMux::new();
919        mux.upsert(
920            Pid::from_const(0x0100),
921            s1.clone(),
922            SectionInterval::from_const(Duration::from_millis(100)),
923        )
924        .expect("scheduled section");
925        mux.upsert(
926            Pid::from_const(0x0200),
927            s2.clone(),
928            SectionInterval::from_const(Duration::from_millis(200)),
929        )
930        .expect("scheduled section");
931        let pkts = mux.poll(Timestamp::ZERO);
932        // Both entries should emit — we count PID occurrences
933        let pids: Vec<Pid> = pkts
934            .iter()
935            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
936            .collect();
937        assert!(pids.contains(&Pid::from_const(0x0100)));
938        assert!(pids.contains(&Pid::from_const(0x0200)));
939    }
940
941    // ── deterministic schedule ───────────────────────────────────────────────
942
943    #[test]
944    fn entry_emits_only_when_due() {
945        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
946        let mut mux = SiMux::new();
947        mux.upsert(
948            Pid::from_const(0x0100),
949            s.clone(),
950            SectionInterval::from_const(Duration::from_millis(100)),
951        )
952        .expect("scheduled section");
953
954        // First poll at t=0: emits
955        let pkts0 = mux.poll(Timestamp::ZERO);
956        assert!(!pkts0.is_empty());
957
958        // t=50: not yet due
959        let pkts50 = mux.poll(Timestamp::from_millis(50));
960        assert!(pkts50.is_empty(), "should not emit at t=50");
961
962        // t=99: still not due
963        let pkts99 = mux.poll(Timestamp::from_millis(99));
964        assert!(pkts99.is_empty(), "should not emit at t=99");
965
966        // t=100: due again
967        let pkts100 = mux.poll(Timestamp::from_millis(100));
968        assert!(!pkts100.is_empty(), "should emit at t=100");
969    }
970
971    #[test]
972    fn two_entries_different_cadence() {
973        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01; 5]);
974        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x02; 5]);
975        let mut mux = SiMux::new();
976        mux.upsert(
977            Pid::from_const(0x0100),
978            concat_sections(&[s1]),
979            SectionInterval::from_const(Duration::from_millis(100)),
980        )
981        .expect("scheduled section");
982        mux.upsert(
983            Pid::from_const(0x0200),
984            concat_sections(&[s2]),
985            SectionInterval::from_const(Duration::from_millis(200)),
986        )
987        .expect("scheduled section");
988
989        // t=0: both emit
990        let pkts = mux.poll(Timestamp::ZERO);
991        assert!(!pkts.is_empty());
992
993        // t=100: only 0x0100 emits (due at 100)
994        let pkts100 = mux.poll(Timestamp::from_millis(100));
995        assert!(!pkts100.is_empty());
996        let pids100: Vec<Pid> = pkts100
997            .iter()
998            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
999            .collect();
1000        assert!(
1001            pids100.contains(&Pid::from_const(0x0100)),
1002            "PID 0x0100 should emit at t=100"
1003        );
1004        assert!(
1005            !pids100.contains(&Pid::from_const(0x0200)),
1006            "PID 0x0200 should NOT emit at t=100"
1007        );
1008
1009        // t=150: neither emits
1010        let pkts150 = mux.poll(Timestamp::from_millis(150));
1011        assert!(pkts150.is_empty(), "neither should emit at t=150");
1012
1013        // t=200: both emit again
1014        let pkts200 = mux.poll(Timestamp::from_millis(200));
1015        let pids200: Vec<Pid> = pkts200
1016            .iter()
1017            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1018            .collect();
1019        assert!(
1020            pids200.contains(&Pid::from_const(0x0100)),
1021            "PID 0x0100 should emit at t=200"
1022        );
1023        assert!(
1024            pids200.contains(&Pid::from_const(0x0200)),
1025            "PID 0x0200 should emit at t=200"
1026        );
1027    }
1028
1029    #[test]
1030    fn entry_emits_again_after_full_interval() {
1031        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 20]);
1032        let mut mux = SiMux::new();
1033        mux.upsert(
1034            Pid::from_const(0x0100),
1035            s,
1036            SectionInterval::from_const(Duration::from_secs(1)),
1037        )
1038        .expect("scheduled section");
1039
1040        // t=0
1041        let n0 = mux.poll_into(Timestamp::ZERO, &mut Vec::new());
1042        assert!(n0 > 0);
1043
1044        // t=999ms: not due
1045        let mut buf = Vec::new();
1046        let n999 = mux.poll_into(Timestamp::from_millis(999), &mut buf);
1047        assert_eq!(n999, 0);
1048
1049        // t=1s: due
1050        let mut buf2 = Vec::new();
1051        let n1000 = mux.poll_into(Timestamp::from_millis(1000), &mut buf2);
1052        assert!(n1000 > 0);
1053    }
1054
1055    // ── upsert replaces existing entry (same pid + table_id only) ───────────
1056
1057    #[test]
1058    fn upsert_updates_existing_entry() {
1059        // Same table_id (0x42, SDT actual) both times: this is a genuine
1060        // update of the same logical table, so it must replace, not add.
1061        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1062        let s2 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xBB; 10]);
1063        let mut mux = SiMux::new();
1064
1065        mux.upsert(
1066            Pid::from_const(0x0100),
1067            s1,
1068            SectionInterval::from_const(Duration::from_millis(100)),
1069        )
1070        .expect("scheduled section");
1071        mux.upsert(
1072            Pid::from_const(0x0100),
1073            s2.clone(),
1074            SectionInterval::from_const(Duration::from_millis(200)),
1075        )
1076        .expect("scheduled section");
1077
1078        let pkts = mux.poll(Timestamp::ZERO);
1079
1080        // Round-trip the output to verify the updated sections
1081        let mut reasm = SectionReassembler::default();
1082        for raw in &pkts {
1083            let pkt = TsPacket::parse(raw).unwrap();
1084            if pkt.header.pid == Pid::from_const(0x0100) {
1085                reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1086            }
1087        }
1088        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1089        assert_eq!(got.len(), 1);
1090        assert_eq!(got[0].as_ref(), s2.as_slice());
1091    }
1092
1093    // ── issue #1000: distinct table_ids sharing a PID must NOT collide ──────
1094
1095    /// Regression: `upsert_tdt` then `upsert_tot` (both PID 0x0014) used to
1096    /// collide because entries were keyed by PID alone — the second call
1097    /// silently replaced the first. Both table_ids must now come out, with a
1098    /// continuous continuity counter across the shared PID.
1099    #[test]
1100    fn upsert_tdt_then_tot_both_emitted_with_continuous_cc() {
1101        let tdt = test_fixtures::psi::long_section(0x70, 1, 0, 0, &[0xAA; 5]); // TDT
1102        let tot = test_fixtures::psi::long_section(0x73, 1, 0, 0, &[0xBB; 8]); // TOT
1103        let mut mux = SiMux::new();
1104
1105        mux.upsert_tdt(tdt.clone()).expect("scheduled section");
1106        mux.upsert_tot(tot.clone()).expect("scheduled section");
1107
1108        let pkts = mux.poll(Timestamp::ZERO);
1109        assert!(!pkts.is_empty());
1110
1111        let mut table_ids_seen = Vec::new();
1112        let mut reasm = SectionReassembler::default();
1113        let mut prev_cc: Option<ContinuityCounter> = None;
1114        for raw in &pkts {
1115            let pkt = TsPacket::parse(raw).unwrap();
1116            assert_eq!(pkt.header.pid, well_known::TDT_TOT);
1117            if let Some(prev) = prev_cc {
1118                assert_eq!(
1119                    pkt.header.continuity_counter.forward_distance_from(prev),
1120                    1,
1121                    "continuity counter must be continuous across table kinds on one PID"
1122                );
1123            }
1124            prev_cc = Some(pkt.header.continuity_counter);
1125            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1126        }
1127        while let Some(section) = reasm.pop_section() {
1128            table_ids_seen.push(section.as_ref()[0]);
1129        }
1130
1131        assert!(table_ids_seen.contains(&0x70), "TDT missing from output");
1132        assert!(table_ids_seen.contains(&0x73), "TOT missing from output");
1133    }
1134
1135    /// Same collision class for SDT actual (0x42) vs. BAT (0x4A), both on
1136    /// PID 0x0011.
1137    #[test]
1138    fn upsert_sdt_and_bat_both_emitted() {
1139        let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xCC; 5]);
1140        let bat = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0xDD; 6]);
1141        let mut mux = SiMux::new();
1142
1143        mux.upsert_sdt_actual(sdt.clone())
1144            .expect("scheduled section");
1145        mux.upsert(
1146            well_known::SDT_BAT,
1147            bat.clone(),
1148            SectionInterval::from_const(Duration::from_millis(1000)),
1149        )
1150        .expect("scheduled section");
1151
1152        let pkts = mux.poll(Timestamp::ZERO);
1153        let mut table_ids_seen = Vec::new();
1154        let mut reasm = SectionReassembler::default();
1155        for raw in &pkts {
1156            let pkt = TsPacket::parse(raw).unwrap();
1157            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1158        }
1159        while let Some(section) = reasm.pop_section() {
1160            table_ids_seen.push(section.as_ref()[0]);
1161        }
1162
1163        assert!(table_ids_seen.contains(&0x42), "SDT actual missing");
1164        assert!(table_ids_seen.contains(&0x4A), "BAT missing");
1165    }
1166
1167    // ── convenience constructors ─────────────────────────────────────────────
1168
1169    #[test]
1170    fn upsert_sdt_actual_uses_correct_pid() {
1171        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1172        let mut mux = SiMux::new();
1173        mux.upsert_sdt_actual(s).expect("scheduled section");
1174        let pkts = mux.poll(Timestamp::ZERO);
1175        let pids: Vec<Pid> = pkts
1176            .iter()
1177            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1178            .collect();
1179        assert!(pids.iter().all(|&p| p == well_known::SDT_BAT));
1180    }
1181
1182    #[test]
1183    fn upsert_pat_uses_correct_pid() {
1184        let s = test_fixtures::psi::long_section(0x00, 1, 0, 0, &[0x01, 0x02]);
1185        let mut mux = SiMux::new();
1186        mux.upsert_pat(s).expect("scheduled section");
1187        let pkts = mux.poll(Timestamp::ZERO);
1188        assert!(!pkts.is_empty());
1189        let pids: Vec<Pid> = pkts
1190            .iter()
1191            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1192            .collect();
1193        assert!(pids.iter().all(|&p| p == well_known::PAT));
1194        assert!(
1195            mux.poll(Timestamp::from_nanos(
1196                (PAT_MAX_INTERVAL.duration() / 2).as_nanos() as u64
1197            ))
1198            .is_empty()
1199        );
1200        assert!(
1201            !mux.poll(Timestamp::from_nanos(
1202                PAT_MAX_INTERVAL.duration().as_nanos() as u64
1203            ))
1204            .is_empty()
1205        );
1206    }
1207
1208    #[test]
1209    fn upsert_nit_uses_correct_pid() {
1210        let s = test_fixtures::psi::long_section(0x40, 1, 0, 0, &[0x01]);
1211        let mut mux = SiMux::new();
1212        mux.upsert_nit(s).expect("scheduled section");
1213        let pkts = mux.poll(Timestamp::ZERO);
1214        assert!(!pkts.is_empty());
1215        let pids: Vec<Pid> = pkts
1216            .iter()
1217            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1218            .collect();
1219        assert!(pids.iter().all(|&p| p == well_known::NIT));
1220        assert!(
1221            mux.poll(Timestamp::from_nanos(
1222                (NIT_MAX_INTERVAL.duration() / 2).as_nanos() as u64
1223            ))
1224            .is_empty()
1225        );
1226        assert!(
1227            !mux.poll(Timestamp::from_nanos(
1228                NIT_MAX_INTERVAL.duration().as_nanos() as u64
1229            ))
1230            .is_empty()
1231        );
1232    }
1233
1234    #[test]
1235    fn upsert_tdt_uses_correct_pid() {
1236        let s = test_fixtures::psi::long_section(0x70, 1, 0, 0, &[0x01]);
1237        let mut mux = SiMux::new();
1238        mux.upsert_tdt(s).expect("scheduled section");
1239        let pkts = mux.poll(Timestamp::ZERO);
1240        let pids: Vec<Pid> = pkts
1241            .iter()
1242            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1243            .collect();
1244        assert!(pids.iter().all(|&p| p == well_known::TDT_TOT));
1245    }
1246
1247    #[test]
1248    fn upsert_tot_uses_correct_pid() {
1249        let s = test_fixtures::psi::long_section(0x73, 1, 0, 0, &[0x01]);
1250        let mut mux = SiMux::new();
1251        mux.upsert_tot(s).expect("scheduled section");
1252        let pkts = mux.poll(Timestamp::ZERO);
1253        let pids: Vec<Pid> = pkts
1254            .iter()
1255            .map(|raw| TsPacket::parse(raw).unwrap().header.pid)
1256            .collect();
1257        assert!(pids.iter().all(|&p| p == well_known::TDT_TOT));
1258    }
1259
1260    // ── typed input: empty, mixed-table and trailing-garbage registrations ──
1261
1262    #[test]
1263    fn upsert_rejects_an_empty_input() {
1264        // `table_id_of(&[])` used to return 0, so an empty registration
1265        // collided with the PAT entry on PID 0 and re-armed its interval.
1266        let mut mux = SiMux::new();
1267        let pat = test_fixtures::psi::pat_section(1, 0, &[(1, 0x1000)]);
1268        mux.upsert_pat(pat.clone()).expect("PAT is schedulable");
1269        assert_eq!(
1270            mux.upsert(well_known::PAT, Vec::new(), PAT_MAX_INTERVAL),
1271            Err(SectionRejection::NotASection)
1272        );
1273        assert_eq!(mux.rejected().len(), 1);
1274        assert_eq!(mux.rejected()[0].pid, well_known::PAT);
1275        let pkts = mux.poll(Timestamp::ZERO);
1276        let mut reasm = SectionReassembler::default();
1277        for raw in &pkts {
1278            let pkt = TsPacket::parse(raw).unwrap();
1279            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1280        }
1281        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1282        assert_eq!(got.len(), 1);
1283        assert_eq!(got[0].as_ref(), pat.as_slice());
1284    }
1285
1286    #[test]
1287    fn upsert_rejects_two_sections_that_share_a_key() {
1288        let a = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1289        let b = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x02]);
1290        let mut mux = SiMux::new();
1291        assert_eq!(
1292            mux.upsert(
1293                well_known::SDT_BAT,
1294                concat_sections(&[a, b]),
1295                SDT_ACTUAL_MAX_INTERVAL
1296            ),
1297            Err(SectionRejection::DuplicateSection)
1298        );
1299    }
1300
1301    #[test]
1302    fn upsert_rejects_a_second_section_of_another_table() {
1303        let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1304        let bat = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0x02]);
1305        let mut mux = SiMux::new();
1306        assert_eq!(
1307            mux.upsert(
1308                well_known::SDT_BAT,
1309                concat_sections(&[sdt, bat]),
1310                SDT_ACTUAL_MAX_INTERVAL
1311            ),
1312            Err(SectionRejection::MoreThanOneSection)
1313        );
1314    }
1315
1316    #[test]
1317    fn upsert_keeps_a_complete_section_and_rejects_a_trailing_fragment() {
1318        // A truncated final section used to be dropped without a word, and
1319        // the caller could not tell it never went out.
1320        let whole = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1321        let mut with_tail = whole.clone();
1322        with_tail.extend_from_slice(&[0x4A, 0x00]);
1323        let mut mux = SiMux::new();
1324        mux.upsert(well_known::SDT_BAT, with_tail, SDT_ACTUAL_MAX_INTERVAL)
1325            .expect("the complete section is schedulable");
1326        let pkts = mux.poll(Timestamp::ZERO);
1327        let mut reasm = SectionReassembler::default();
1328        for raw in &pkts {
1329            let pkt = TsPacket::parse(raw).unwrap();
1330            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1331        }
1332        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1333        assert_eq!(got.len(), 1);
1334        assert_eq!(got[0].as_ref(), whole.as_slice());
1335    }
1336
1337    #[test]
1338    fn sections_of_one_table_are_keyed_by_their_section_number() {
1339        let first = test_fixtures::psi::long_section(0x4E, 1, 0, 0, &[0x01]);
1340        let second = test_fixtures::psi::long_section(0x4E, 1, 0, 1, &[0x02]);
1341        let mut mux = SiMux::new();
1342        let pid = Pid::from_const(0x0012);
1343        mux.upsert(pid, first.clone(), EIT_SCHED_MAX_INTERVAL)
1344            .expect("first section");
1345        mux.upsert(pid, second.clone(), EIT_SCHED_MAX_INTERVAL)
1346            .expect("second section");
1347        let pkts = mux.poll(Timestamp::ZERO);
1348        let mut reasm = SectionReassembler::default();
1349        for raw in &pkts {
1350            let pkt = TsPacket::parse(raw).unwrap();
1351            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1352        }
1353        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1354        assert_eq!(got.len(), 2, "both sections of the table must go out");
1355    }
1356
1357    #[test]
1358    fn upsert_pat_rejects_a_section_of_another_table() {
1359        let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01]);
1360        let mut mux = SiMux::new();
1361        assert_eq!(
1362            mux.upsert_pat(sdt),
1363            Err(SectionRejection::WrongTableId {
1364                expected: TABLE_ID_PAT,
1365                found: Some(0x42),
1366            })
1367        );
1368        assert!(mux.poll(Timestamp::ZERO).is_empty());
1369    }
1370
1371    // ── round-trip through reassembler ───────────────────────────────────────
1372
1373    #[test]
1374    fn simux_round_trip_single_entry() {
1375        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 20]);
1376        let interval = SectionInterval::from_const(Duration::from_millis(100));
1377        let mut mux = SiMux::new();
1378        mux.upsert(Pid::from_const(0x0100), s1.clone(), interval)
1379            .expect("scheduled section");
1380
1381        let pkts = mux.poll(Timestamp::ZERO);
1382
1383        let mut reasm = SectionReassembler::default();
1384        for raw in &pkts {
1385            let pkt = TsPacket::parse(raw).unwrap();
1386            if pkt.header.pid == Pid::from_const(0x0100) {
1387                reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1388            }
1389        }
1390        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1391        assert_eq!(got.len(), 1, "round-trip must recover the section");
1392        assert_eq!(got[0].as_ref(), s1.as_slice());
1393    }
1394
1395    #[test]
1396    fn simux_round_trip_multi_pid() {
1397        let s_a = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xA0; 10]);
1398        let s_b = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xB0; 10]);
1399        let mut mux = SiMux::new();
1400        mux.upsert(
1401            Pid::from_const(0x0100),
1402            s_a.clone(),
1403            SectionInterval::from_const(Duration::from_millis(100)),
1404        )
1405        .expect("scheduled section");
1406        mux.upsert(
1407            Pid::from_const(0x0200),
1408            s_b.clone(),
1409            SectionInterval::from_const(Duration::from_millis(100)),
1410        )
1411        .expect("scheduled section");
1412
1413        let pkts = mux.poll(Timestamp::ZERO);
1414
1415        let mut reasm_a = SectionReassembler::default();
1416        let mut reasm_b = SectionReassembler::default();
1417        for raw in &pkts {
1418            let pkt = TsPacket::parse(raw).unwrap();
1419            match pkt.header.pid.value() {
1420                0x0100 => reasm_a.feed(pkt.payload.unwrap(), pkt.header.pusi),
1421                0x0200 => reasm_b.feed(pkt.payload.unwrap(), pkt.header.pusi),
1422                _ => {}
1423            }
1424        }
1425        let got_a: Vec<_> = core::iter::from_fn(|| reasm_a.pop_section()).collect();
1426        let got_b: Vec<_> = core::iter::from_fn(|| reasm_b.pop_section()).collect();
1427        assert_eq!(got_a.len(), 1);
1428        assert_eq!(got_b.len(), 1);
1429        assert_eq!(got_a[0].as_ref(), s_a.as_slice());
1430        assert_eq!(got_b[0].as_ref(), s_b.as_slice());
1431    }
1432
1433    // ── CC continuity across polls ───────────────────────────────────────────
1434
1435    #[test]
1436    fn continuity_counter_continuous_across_polls() {
1437        // Section large enough to span at least 2 packets.
1438        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 250]);
1439        let mut mux = SiMux::new();
1440        mux.upsert(
1441            Pid::from_const(0x0100),
1442            s,
1443            SectionInterval::from_const(Duration::from_millis(100)),
1444        )
1445        .expect("scheduled section");
1446
1447        let pkts1 = mux.poll(Timestamp::ZERO);
1448        assert!(pkts1.len() >= 2, "need ≥2 packets to test CC continuity");
1449
1450        let last_cc_pkts1 = TsPacket::parse(&pkts1[pkts1.len() - 1])
1451            .unwrap()
1452            .header
1453            .continuity_counter;
1454
1455        let pkts2 = mux.poll(Timestamp::from_millis(100));
1456        assert!(!pkts2.is_empty(), "second poll must emit");
1457
1458        let first_cc_pkts2 = TsPacket::parse(&pkts2[0])
1459            .unwrap()
1460            .header
1461            .continuity_counter;
1462
1463        assert_eq!(
1464            first_cc_pkts2.forward_distance_from(last_cc_pkts1),
1465            1,
1466            "CC must continue across poll cycles"
1467        );
1468    }
1469
1470    // ── poll_into clears output ──────────────────────────────────────────────
1471
1472    #[test]
1473    fn poll_into_clears_out_before_appending() {
1474        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1475        let mut mux = SiMux::new();
1476        mux.upsert(
1477            Pid::from_const(0x0100),
1478            s,
1479            SectionInterval::from_const(Duration::from_millis(100)),
1480        )
1481        .expect("scheduled section");
1482
1483        let mut out = vec![[0u8; TS_PACKET_SIZE]; 42];
1484        let n = mux.poll_into(Timestamp::ZERO, &mut out);
1485        assert_eq!(n, out.len(), "out must contain only new packets");
1486    }
1487
1488    // ── the 25 ms interval floor ─────────────────────────────────────────────
1489
1490    /// The 25 ms floor is a `const` check on the spec's own named intervals, so
1491    /// a sub-floor one is a build error (verified by `from_const` panicking in
1492    /// a `const` context, which the `should_panic` surfaces here).
1493    #[test]
1494    #[should_panic(expected = "25 ms")]
1495    fn named_interval_const_rejects_sub_25ms_interval() {
1496        let _ = SectionInterval::from_const(Duration::from_millis(10));
1497    }
1498
1499    /// EN 300 468 §5.1.4.1's 25 ms floor is enforced at construction, so a
1500    /// zero or sub-floor interval cannot reach the scheduler (it used to be a
1501    /// `debug_assert!` that release builds compiled out).
1502    #[test]
1503    fn section_interval_rejects_below_the_25ms_floor() {
1504        for bad in [
1505            Duration::ZERO,
1506            Duration::from_millis(1),
1507            Duration::from_millis(24),
1508            MIN_SECTION_INTERVAL - Duration::from_nanos(1),
1509        ] {
1510            let err = SectionInterval::try_new(bad).unwrap_err();
1511            assert_eq!(err.interval, bad);
1512            assert_eq!(err.min, MIN_SECTION_INTERVAL);
1513            assert!(SectionInterval::try_from(bad).is_err());
1514        }
1515        assert_eq!(
1516            SectionInterval::try_new(MIN_SECTION_INTERVAL)
1517                .expect("the floor itself is valid")
1518                .duration(),
1519            MIN_SECTION_INTERVAL
1520        );
1521        assert_eq!(
1522            Duration::from(SectionInterval::from_const(Duration::from_secs(2))),
1523            Duration::from_secs(2)
1524        );
1525    }
1526
1527    #[test]
1528    fn upsert_accepts_25ms_interval() {
1529        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1530        let mut mux = SiMux::new();
1531        mux.upsert(
1532            Pid::from_const(0x0100),
1533            s,
1534            SectionInterval::from_const(MIN_SECTION_INTERVAL),
1535        )
1536        .expect("scheduled section");
1537        let pkts = mux.poll(Timestamp::ZERO);
1538        assert!(!pkts.is_empty());
1539    }
1540
1541    // ── round-trip property (the mandatory acceptance oracle) ────────────────
1542
1543    #[test]
1544    fn round_trip_single_short_section() {
1545        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
1546        assert_round_trip(&[s]);
1547    }
1548
1549    #[test]
1550    fn round_trip_one_byte_body() {
1551        let s = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xBB]); // 4 bytes total
1552        assert_round_trip(&[s]);
1553    }
1554
1555    #[test]
1556    fn round_trip_section_exactly_pusi_cap_boundary() {
1557        // A section whose total length is exactly PUSI_PAYLOAD_CAP (183).
1558        let body = vec![0xCC; PUSI_PAYLOAD_CAP - 3];
1559        let s = test_fixtures::psi::short_section(0x50, &body);
1560        assert_eq!(s.len(), PUSI_PAYLOAD_CAP);
1561        assert_round_trip(&[s]);
1562    }
1563
1564    #[test]
1565    fn round_trip_section_just_over_pusi_cap() {
1566        // One byte more than fits in a PUSI packet → must span to continuation.
1567        let body = vec![0xDD; PUSI_PAYLOAD_CAP - 3 + 1];
1568        let s = test_fixtures::psi::short_section(0x52, &body);
1569        assert_eq!(s.len(), PUSI_PAYLOAD_CAP + 1);
1570        assert_round_trip(&[s]);
1571    }
1572
1573    #[test]
1574    fn round_trip_section_spans_many_packets() {
1575        // A 2000-byte section spans ~11 packets.
1576        let body = vec![0xEE; 2000 - 3];
1577        let s = test_fixtures::psi::short_section(0x60, &body);
1578        assert_round_trip(&[s]);
1579    }
1580
1581    #[test]
1582    fn round_trip_section_at_max_size() {
1583        // The maximum section (4096 total, the long-form ceiling), whose final
1584        // continuation packet carries the tail followed by 0xFF stuffing. Since
1585        // #148 the reassembler ignores that trailing stuffing instead of
1586        // counting it toward MAX_SECTION_SIZE, so a full-size section round-trips.
1587        let body = vec![0x11; 4096 - 3];
1588        let s = test_fixtures::psi::short_section(0x80, &body);
1589        assert_eq!(s.len(), 4096);
1590        assert_round_trip(&[s]);
1591    }
1592
1593    #[test]
1594    fn round_trip_multiple_short_sections_in_one_batch() {
1595        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01, 0x02]); // 5 bytes
1596        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x03]); // 4 bytes
1597        let s3 = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0x04, 0x05, 0x06]); // 6 bytes
1598        assert_round_trip(&[s1, s2, s3]);
1599    }
1600
1601    #[test]
1602    fn round_trip_section_ends_exactly_at_boundary() {
1603        // First section is exactly PUSI_PAYLOAD_CAP bytes — ends at packet
1604        // boundary.  Second section starts fresh in the next packet with
1605        // PUSI=1, pointer_field=0.
1606        let body1 = vec![0xA1; PUSI_PAYLOAD_CAP - 3];
1607        let s1 = test_fixtures::psi::short_section(0x50, &body1);
1608        assert_eq!(s1.len(), PUSI_PAYLOAD_CAP);
1609
1610        let s2 = test_fixtures::psi::long_section(0x52, 1, 0, 0, &[0xB1, 0xB2]);
1611        assert_round_trip(&[s1, s2]);
1612    }
1613
1614    #[test]
1615    fn continuation_packet_never_overshoots_next_section_start() {
1616        // First section is 366 bytes total: it fills the first (PUSI) packet's
1617        // 183-byte payload exactly, then the *second* packet (a continuation,
1618        // starting at pos=183) is exactly 183 bytes short of the next
1619        // section's start (183 + 183 = 366) — the mid-stream analogue of
1620        // `round_trip_section_ends_exactly_at_boundary` above, which only
1621        // exercises the boundary at pos=0.
1622        let body1 = vec![0xA5; 366 - 3];
1623        let s1 = test_fixtures::psi::short_section(0x50, &body1);
1624        assert_eq!(s1.len(), 366);
1625        let s2 = test_fixtures::psi::long_section(0x52, 1, 0, 0, &[0xB1, 0xB2, 0xB3]);
1626
1627        let mut packetiser = SectionPacketiser::new(Pid::from_const(0x0100));
1628        let packets = packetiser.packetise(&[s1.as_slice(), s2.as_slice()]);
1629
1630        for pkt_raw in &packets {
1631            let pkt = TsPacket::parse(pkt_raw).expect("parse generated packet");
1632            let payload = pkt.payload.expect("payload present");
1633            if pkt.header.pusi {
1634                let pointer = payload[0] as usize;
1635                // W1 (#1074): pre-fix this was 183 — a pointer_field pointing
1636                // past the packet's own payload, so no section byte actually
1637                // starts within it.
1638                assert!(
1639                    pointer < PUSI_PAYLOAD_CAP,
1640                    "pointer_field {pointer} leaves no room for a section to \
1641                     start within this packet (H.222.0 §2.4.4)"
1642                );
1643            }
1644        }
1645
1646        assert_round_trip(&[s1, s2]);
1647    }
1648
1649    #[test]
1650    fn round_trip_mix_small_large_sections() {
1651        // Mix of small and spanning sections that stress pointer_field and
1652        // concatenation.
1653        let s1 = test_fixtures::psi::long_section(0x10, 1, 0, 0, &[0xAA; 5]);
1654        let body2 = vec![0xBB; 200];
1655        let s2 = test_fixtures::psi::short_section(0x20, &body2);
1656        let s3 = test_fixtures::psi::long_section(0x30, 1, 0, 0, &[0xCC; 50]);
1657        let body4 = vec![0xDD; 800];
1658        let s4 = test_fixtures::psi::short_section(0x40, &body4);
1659        let s5 = test_fixtures::psi::long_section(0x50, 1, 0, 0, &[0xEE]); // 1-byte body
1660        assert_round_trip(&[s1, s2, s3, s4, s5]);
1661    }
1662
1663    // ── continuity counter ───────────────────────────────────────────────────
1664
1665    #[test]
1666    fn continuity_counter_increments_per_packet() {
1667        // Use a section large enough to span several packets.
1668        let body = vec![0xAA; 500];
1669        let section = test_fixtures::psi::short_section(0x42, &body);
1670        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1671
1672        let packets = p.packetise(&[&section]);
1673        assert!(packets.len() >= 3, "need multiple packets to test CC");
1674
1675        let mut last_cc: Option<ContinuityCounter> = None;
1676        for pkt_raw in &packets {
1677            let pkt = TsPacket::parse(pkt_raw).unwrap();
1678            let cc = pkt.header.continuity_counter;
1679            if let Some(last) = last_cc {
1680                assert_eq!(
1681                    cc.forward_distance_from(last),
1682                    1,
1683                    "CC must increment per packet"
1684                );
1685            }
1686            last_cc = Some(cc);
1687        }
1688    }
1689
1690    #[test]
1691    fn continuity_counter_wraps_and_continues_across_calls() {
1692        let mut p = SectionPacketiser::with_continuity(Pid::from_const(0x0100), cc(14));
1693        // Section large enough to span at least 3 packets.
1694        let body = vec![0xBB; 500];
1695        let s = test_fixtures::psi::short_section(0x42, &body);
1696
1697        // First call: CC 14, 15, 0, …
1698        let pkts1 = p.packetise(&[&s]);
1699        assert!(pkts1.len() >= 3, "section must span ≥3 packets");
1700        let ccs1: Vec<u8> = pkts1
1701            .iter()
1702            .map(|b| {
1703                TsPacket::parse(b)
1704                    .unwrap()
1705                    .header
1706                    .continuity_counter
1707                    .value()
1708            })
1709            .collect();
1710        assert_eq!(ccs1[0], 14);
1711        assert_eq!(ccs1[1], 15);
1712        assert_eq!(ccs1[2], 0);
1713
1714        // Second call: CC continues from where first left off.
1715        let previous = ContinuityCounter::try_new(ccs1.last().copied().unwrap_or(0))
1716            .expect("the last emitted counter is 4-bit");
1717        let pkts2 = p.packetise(&[&s]);
1718        let cc_first_pkt2 = TsPacket::parse(&pkts2[0])
1719            .unwrap()
1720            .header
1721            .continuity_counter;
1722        assert_eq!(cc_first_pkt2.forward_distance_from(previous), 1);
1723    }
1724
1725    // ── PUSI placement ──────────────────────────────────────────────────────
1726
1727    #[test]
1728    fn pusi_set_when_section_starts() {
1729        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
1730        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1731        let packets = p.packetise(&[&s]);
1732        assert!(!packets.is_empty());
1733        let pkt = TsPacket::parse(&packets[0]).unwrap();
1734        assert!(pkt.header.pusi, "first packet must have PUSI=1");
1735    }
1736
1737    #[test]
1738    fn pusi_not_set_on_mid_section_continuation() {
1739        let body = vec![0xAA; 500];
1740        let s = test_fixtures::psi::short_section(0x42, &body);
1741        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1742        let packets = p.packetise(&[&s]);
1743        assert!(packets.len() >= 2);
1744        let pkt1 = TsPacket::parse(&packets[0]).unwrap();
1745        let pkt2 = TsPacket::parse(&packets[1]).unwrap();
1746        assert!(pkt1.header.pusi, "first packet must have PUSI=1");
1747        assert!(
1748            !pkt2.header.pusi,
1749            "second packet is continuation, must have PUSI=0"
1750        );
1751    }
1752
1753    #[test]
1754    fn pointer_field_equals_tail_length_before_new_section() {
1755        // Section1 = 200 bytes.  Section2 = 50 bytes.
1756        // Packet 1: PUSI=1, pointer=0, section1 head.
1757        // Packet 2: PUSI=1, pointer > 0 (tail of section1 before section2).
1758        let body1 = vec![0xA1; 197]; // 200-byte section
1759        let s1 = test_fixtures::psi::short_section(0x52, &body1);
1760        assert_eq!(s1.len(), 200);
1761        let s2 = test_fixtures::psi::long_section(0x54, 1, 0, 0, &[0xB1; 38]); // 50-byte section
1762        assert_eq!(s2.len(), 50);
1763
1764        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1765        let packets = p.packetise(&[&s1, &s2]);
1766
1767        // Find the packet where PUSI=1 and pointer>0.
1768        let pkt_with_pointer = packets
1769            .iter()
1770            .map(|raw| TsPacket::parse(raw).unwrap())
1771            .find(|pkt| pkt.header.pusi && pkt.payload.is_some_and(|pl| pl.first() != Some(&0)))
1772            .expect("must have a PUSI packet with non-zero pointer");
1773
1774        let payload = pkt_with_pointer.payload.unwrap();
1775        let pointer = payload[0] as usize;
1776        assert!(pointer > 0, "pointer must be non-zero");
1777        // The tail bytes should be from the end of section1.
1778        let tail_start = s1.len() - pointer;
1779        assert_eq!(&payload[1..1 + pointer], &s1[tail_start..]);
1780    }
1781
1782    // ── stuffing ─────────────────────────────────────────────────────────────
1783
1784    #[test]
1785    fn final_packet_unused_tail_is_stuffing() {
1786        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]); // 8 bytes total
1787        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1788        let packets = p.packetise(&[&s]);
1789
1790        let pkt = TsPacket::parse(&packets[0]).unwrap();
1791        let payload = pkt.payload.unwrap();
1792        assert_eq!(payload[0], 0, "pointer_field should be 0");
1793
1794        let section_end = 1 + s.len(); // after pointer + section
1795        assert!(
1796            section_end < payload.len(),
1797            "must have stuffing after section"
1798        );
1799        for &b in &payload[section_end..] {
1800            assert_eq!(b, STUFFING_BYTE, "all trailing bytes must be 0xFF");
1801        }
1802    }
1803
1804    #[test]
1805    fn reassembler_discards_stuffing() {
1806        let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
1807        let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xBB; 5]);
1808
1809        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1810        let packets = p.packetise(&[&s1, &s2]);
1811
1812        let mut reasm = SectionReassembler::default();
1813        for pkt_raw in &packets {
1814            let pkt = TsPacket::parse(pkt_raw).unwrap();
1815            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1816        }
1817
1818        let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
1819        assert_eq!(got.len(), 2);
1820        assert!(
1821            reasm.is_empty(),
1822            "stuffing tail must be discarded, not buffered"
1823        );
1824    }
1825
1826    // ── misc ─────────────────────────────────────────────────────────────────
1827
1828    #[test]
1829    fn empty_batch_produces_no_packets() {
1830        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1831        let packets: Vec<[u8; TS_PACKET_SIZE]> = p.packetise(&[]);
1832        assert!(packets.is_empty());
1833    }
1834
1835    #[test]
1836    fn packetise_into_clears_out_first() {
1837        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 5]);
1838        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1839
1840        let mut out = vec![[0u8; TS_PACKET_SIZE]; 99]; // pre-existing junk
1841        let n = p.packetise_into(&[&s], &mut out);
1842        assert_eq!(n, out.len(), "out must contain only the new packets");
1843        // Verify the output is correct (round-trip).
1844        let mut reasm = SectionReassembler::default();
1845        for pkt_raw in &out {
1846            let pkt = TsPacket::parse(pkt_raw).unwrap();
1847            reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
1848        }
1849        let got = reasm.pop_section().unwrap();
1850        assert_eq!(got.as_ref(), s.as_slice());
1851    }
1852
1853    #[test]
1854    fn pid_is_correct() {
1855        let p = SectionPacketiser::new(Pid::from_const(0x1234));
1856        assert_eq!(p.pid(), Pid::from_const(0x1234));
1857    }
1858
1859    #[test]
1860    fn with_continuity_masks_to_4_bits() {
1861        let expected = ContinuityCounter::try_new(0x0E).expect("4-bit counter");
1862        let p = SectionPacketiser::with_continuity(Pid::from_const(0x0100), expected);
1863        assert_eq!(p.continuity_counter(), expected);
1864    }
1865
1866    #[test]
1867    fn has_payload_always_true_no_adaptation() {
1868        let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 50]);
1869        let mut p = SectionPacketiser::new(Pid::from_const(0x0100));
1870        let packets = p.packetise(&[&s]);
1871        for pkt_raw in &packets {
1872            let pkt = TsPacket::parse(pkt_raw).unwrap();
1873            assert!(pkt.header.has_payload(), "every packet must carry payload");
1874            assert!(
1875                !pkt.header.has_adaptation(),
1876                "no adaptation field is emitted"
1877            );
1878            assert!(!pkt.header.tei, "TEI must be false");
1879            assert_eq!(
1880                pkt.header.scrambling,
1881                ScramblingControl::NotScrambled,
1882                "scrambling must be 0"
1883            );
1884        }
1885    }
1886}