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