Skip to main content

dvb_conformance/
lib.rs

1//! ETSI TR 101 290 v1.4.1 transport-stream conformance monitor.
2//!
3//! Implements the **first-priority** (Table 5.0a, indicators 1.1–1.6),
4//! **second-priority** (Table 5.0b, indicators 2.1–2.3b, 2.5–2.6), and
5//! **SI-repetition** (Table 5.0c, indicator 3.2 — maximum interval) indicator
6//! sets. Indicator 2.4 (PCR_accuracy_error) is intentionally excluded — it
7//! requires hardware arrival timestamps not available under the caller-supplied-
8//! time model. Indicator 3.2's minimum-gap (25 ms) dimension is deferred —
9//! it needs per-`(table_id, section_number)` tracking to avoid false positives
10//! on dense multi-section tables.
11//!
12//! # Caller-supplied time
13//!
14//! [`ConformanceMonitor::feed`] takes a [`core::time::Duration`] timestamp
15//! alongside each TS packet. All presence/absence timeout checks (1.3.a, 1.5.a,
16//! 1.6, 2.3a, 2.3b, 2.5, 3.2) are evaluated against this clock. The caller
17//! must ensure that timestamps are **monotonic non-decreasing** across calls;
18//! the monitor does not enforce this but non-monotonic timestamps will produce
19//! spurious events.
20//!
21//! # References
22//!
23//! - ETSI TR 101 290 v1.4.1 (2023-05), §5.2.1, Table 5.0a
24//! - ETSI TR 101 290 v1.4.1 (2023-05), §5.2.2, Table 5.0b
25//! - ETSI TR 101 290 v1.4.1 (2023-05), §5.2.3, Table 5.0c
26//! - ISO/IEC 13818-1 (MPEG-2 Systems)
27
28#![cfg_attr(not(feature = "std"), no_std)]
29#![cfg_attr(docsrs, feature(doc_cfg))]
30// Runnable examples, embedded so they render on docs.rs and stay in sync with
31// the actual `examples/*.rs` files (shown, not compiled).
32#![doc = "\n# Examples\n"]
33#![doc = "Two runnable examples ship with this crate (`cargo run -p dvb-conformance --example <name>`).\n"]
34#![doc = "\n## `monitor_stream`\n\n```rust,ignore"]
35#![doc = include_str!("../examples/monitor_stream.rs")]
36#![doc = "```\n\n## `priority_breakdown`\n\n```rust,ignore"]
37#![doc = include_str!("../examples/priority_breakdown.rs")]
38#![doc = "```"]
39extern crate alloc;
40
41use alloc::collections::BTreeMap;
42use alloc::format;
43use alloc::string::String;
44use alloc::vec::Vec;
45use core::time::Duration;
46
47use broadcast_common::Parse;
48use dvb_si::tables::pat::{PatSection, TABLE_ID as PAT_TABLE_ID};
49use dvb_si::tables::pmt::PmtSection;
50use mpeg_ts::section::Section;
51use mpeg_ts::ts::{SectionReassembler, TsPacket};
52
53// ── Named PID constants ─────────────────────────────────────────────────────
54
55/// PID 0x0000 — Program Association Table (ISO/IEC 13818-1 §2.4.4.3).
56const PID_PAT: u16 = 0x0000;
57/// PID 0x0001 — Conditional Access Table (ISO/IEC 13818-1 §2.4.4.5).
58const PID_CAT: u16 = 0x0001;
59/// PID 0x0010 — Network Information Table (EN 300 468 §5.2.1).
60const PID_NIT: u16 = 0x0010;
61/// PID 0x0011 — SDT/BAT (EN 300 468 §5.2.2 / §5.2.3).
62const PID_SDT_BAT: u16 = 0x0011;
63/// PID 0x0012 — Event Information Table (EN 300 468 §5.2.4).
64const PID_EIT: u16 = 0x0012;
65/// PID 0x0014 — TDT/TOT (EN 300 468 §5.2.5 / §5.2.6).
66const PID_TDT_TOT: u16 = 0x0014;
67/// PID 0x1FFF — Null/padding packets (ISO/IEC 13818-1 §2.4.3.3).
68const PID_NULL: u16 = 0x1FFF;
69
70/// Sync byte value (ISO/IEC 13818-1 §2.4.3.3).
71const SYNC_BYTE: u8 = 0x47;
72
73/// Well-known SI/PSI PIDs on which CRC-checked long-form sections appear.
74const SI_PIDS: [u16; 6] = [PID_PAT, PID_CAT, PID_NIT, PID_SDT_BAT, PID_EIT, PID_TDT_TOT];
75
76// ── Default timing constants ────────────────────────────────────────────────
77
78/// TR 101 290 v1.4.1 Table 5.0a note 3 / TS 101 154 §4.1.7 — PAT maximum
79/// interval (0.5 s per Table 5.0a row 1.3.a; TS 101 154 recommends ≤ 100 ms).
80const DEFAULT_PAT_MAX_INTERVAL_MS: u64 = 500;
81
82/// TR 101 290 v1.4.1 Table 5.0a row 1.5.a / note 3 — PMT maximum interval.
83const DEFAULT_PMT_MAX_INTERVAL_MS: u64 = 500;
84
85/// TR 101 290 v1.4.1 §5.2.1 accompanying text (1.6) — PID_error period.
86const DEFAULT_PID_ERROR_PERIOD_SECS: u64 = 5;
87
88/// TR 101 290 v1.4.1 §5.2.1 accompanying text (1.1) — sync acquisition
89/// threshold: five consecutive correct sync bytes.
90const DEFAULT_SYNC_ACQUIRE_PACKETS: u8 = 5;
91
92/// TR 101 290 v1.4.1 §5.2.1 accompanying text (1.1) — sync loss threshold:
93/// two or more consecutive corrupted sync bytes.
94const DEFAULT_SYNC_LOSS_PACKETS: u8 = 2;
95
96/// TR 101 290 v1.4.1 Table 5.0b indicator 2.3a / note 2 — PCR maximum
97/// repetition interval (100 ms; note 2 removed the 40 ms limit).
98const DEFAULT_PCR_REPETITION_LIMIT_MS: u64 = 100;
99
100/// TR 101 290 v1.4.1 Table 5.0b indicator 2.3b — PCR discontinuity indicator
101/// maximum interval (100 ms).
102const DEFAULT_PCR_DISCONTINUITY_LIMIT_MS: u64 = 100;
103
104/// TR 101 290 v1.4.1 Table 5.0b indicator 2.5 / note 3 — PTS maximum
105/// repetition interval (700 ms; not applied to still pictures).
106const DEFAULT_PTS_REPETITION_LIMIT_MS: u64 = 700;
107
108/// TR 101 290 v1.4.1 Table 5.0c indicator 3.2 — NIT_actual maximum repetition
109/// interval (10 s; EN 300 468 §5.2.1).
110const DEFAULT_SI_NIT_INTERVAL_SECS: u64 = 10;
111
112/// TR 101 290 v1.4.1 Table 5.0c indicator 3.2 — SDT_actual maximum repetition
113/// interval (2 s; EN 300 468 §5.2.2).
114const DEFAULT_SI_SDT_INTERVAL_SECS: u64 = 2;
115
116/// TR 101 290 v1.4.1 Table 5.0c indicator 3.2 — EIT P/F actual maximum
117/// repetition interval (2 s; EN 300 468 §5.2.4).
118const DEFAULT_SI_EIT_PF_INTERVAL_SECS: u64 = 2;
119
120/// TR 101 290 v1.4.1 Table 5.0c indicator 3.2 — TDT maximum repetition
121/// interval (30 s; EN 300 468 §5.2.5).
122const DEFAULT_SI_TDT_INTERVAL_SECS: u64 = 30;
123
124// ── PCR / PES constants ─────────────────────────────────────────────────────
125
126/// PCR modulus on the 27 MHz clock: `2^33 × 300` (33-bit base × 300 ticks).
127/// ISO/IEC 13818-1 §2.4.3.5 — PCR wraps modulo this value.
128const PCR_MODULUS_27MHZ: u64 = (1u64 << 33) * 300;
129
130/// 27 MHz clock rate (ticks per second).
131const CLOCK_27MHZ: u64 = 27_000_000;
132
133/// PES start-code prefix byte 0 (ISO/IEC 13818-1 §2.4.3.7 Table 2-18).
134const PES_PREFIX_0: u8 = 0x00;
135/// PES start-code prefix byte 1.
136const PES_PREFIX_1: u8 = 0x00;
137/// PES start-code prefix byte 2.
138const PES_PREFIX_2: u8 = 0x01;
139
140/// Offset of the PES header `marker_bits + flags` byte relative to the PES
141/// packet start (byte 6: `'10' + PES_scrambling_control + …`).
142const PES_FLAGS_OFFSET: usize = 6;
143
144/// Mask for the `PTS_DTS_flags` field within the PES header byte at offset 7
145/// (bits `[7:6]` — `0b10` means PTS present, `0b11` means PTS+DTS).
146const PES_PTS_DTS_FLAGS_MASK: u8 = 0b1100_0000;
147
148/// Value indicating PTS is present in `PTS_DTS_flags` (bit 7 set).
149const PES_PTS_PRESENT: u8 = 0b1000_0000;
150
151/// CAT `table_id` value (ISO/IEC 13818-1 §2.4.4.5).
152const CAT_TABLE_ID: u8 = dvb_si::table_id::TableId::Cat as u8;
153
154/// NIT_actual `table_id` (EN 300 468 §5.2.1, table_id 0x40).
155const NIT_ACTUAL_TABLE_ID: u8 = dvb_si::table_id::TableId::NetworkInformationActual as u8;
156
157/// SDT_actual `table_id` (EN 300 468 §5.2.2, table_id 0x42).
158const SDT_ACTUAL_TABLE_ID: u8 = dvb_si::table_id::TableId::ServiceDescriptionActual as u8;
159
160/// EIT P/F actual `table_id` (EN 300 468 §5.2.4, table_id 0x4E).
161const EIT_PF_ACTUAL_TABLE_ID: u8 = dvb_si::table_id::TableId::EventInformationPfActual as u8;
162
163/// TDT `table_id` (EN 300 468 §5.2.5, table_id 0x70).
164const TDT_TABLE_ID: u8 = dvb_si::table_id::TableId::TimeAndDate as u8;
165
166// ── Public types ─────────────────────────────────────────────────────────────
167
168/// Severity tier per TR 101 290 §5.2 (Tables 5.0a/5.0b/5.0c).
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170#[cfg_attr(feature = "serde", derive(serde::Serialize))]
171#[non_exhaustive]
172pub enum Priority {
173    /// Table 5.0a — necessary for de-codability.
174    First,
175    /// Table 5.0b — recommended for continuous or periodic monitoring.
176    Second,
177    /// Table 5.0c — application-dependant monitoring.
178    Third,
179}
180
181impl Priority {
182    /// Human-readable spec label (TR 101 290 §5.2, Tables 5.0a/5.0b/5.0c).
183    #[must_use]
184    pub fn name(&self) -> &'static str {
185        match self {
186            Self::First => "first priority",
187            Self::Second => "second priority",
188            Self::Third => "third priority",
189        }
190    }
191}
192broadcast_common::impl_spec_display!(Priority);
193
194/// A TR 101 290 measurement indicator.
195///
196/// `#[non_exhaustive]` — additional Priority-3 variants may be added later.
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
198#[cfg_attr(feature = "serde", derive(serde::Serialize))]
199#[non_exhaustive]
200pub enum Indicator {
201    // ── Priority 1 (Table 5.0a) ──────────────────────────────────────────
202    /// TR 101 290 v1.4.1 Table 5.0a indicator 1.1 — loss of synchronisation
203    /// with hysteresis.
204    TsSyncLoss,
205    /// TR 101 290 v1.4.1 Table 5.0a indicator 1.2 — sync_byte not equal 0x47.
206    SyncByteError,
207    /// TR 101 290 v1.4.1 Table 5.0a indicator 1.3.a — PAT_error_2.
208    PatError2,
209    /// TR 101 290 v1.4.1 Table 5.0a indicator 1.4 — Continuity_count_error.
210    ContinuityCountError,
211    /// TR 101 290 v1.4.1 Table 5.0a indicator 1.5.a — PMT_error_2.
212    PmtError2,
213    /// TR 101 290 v1.4.1 Table 5.0a indicator 1.6 — PID_error.
214    PidError,
215
216    // ── Priority 2 (Table 5.0b) ──────────────────────────────────────────
217    /// TR 101 290 v1.4.1 Table 5.0b indicator 2.1 — Transport_error.
218    TransportError,
219    /// TR 101 290 v1.4.1 Table 5.0b indicator 2.2 — CRC_error.
220    CrcError,
221    /// TR 101 290 v1.4.1 Table 5.0b indicator 2.3a — PCR_repetition_error.
222    PcrRepetitionError,
223    /// TR 101 290 v1.4.1 Table 5.0b indicator 2.3b —
224    /// PCR_discontinuity_indicator_error.
225    PcrDiscontinuityError,
226    /// TR 101 290 v1.4.1 Table 5.0b indicator 2.5 — PTS_error.
227    PtsError,
228    /// TR 101 290 v1.4.1 Table 5.0b indicator 2.6 — CAT_error.
229    CatError,
230
231    // ── Priority 3 (Table 5.0c) ──────────────────────────────────────────
232    /// TR 101 290 v1.4.1 Table 5.0c indicator 3.2 — SI_repetition_error
233    /// (maximum interval dimension; minimum-gap deferred).
234    SiRepetitionError,
235}
236
237impl Indicator {
238    /// The priority tier this indicator belongs to.
239    #[must_use]
240    pub fn priority(self) -> Priority {
241        match self {
242            Self::TsSyncLoss
243            | Self::SyncByteError
244            | Self::PatError2
245            | Self::ContinuityCountError
246            | Self::PmtError2
247            | Self::PidError => Priority::First,
248            Self::TransportError
249            | Self::CrcError
250            | Self::PcrRepetitionError
251            | Self::PcrDiscontinuityError
252            | Self::PtsError
253            | Self::CatError => Priority::Second,
254            Self::SiRepetitionError => Priority::Third,
255        }
256    }
257
258    /// Verbatim indicator name from the TR 101 290 tables.
259    #[must_use]
260    pub fn name(self) -> &'static str {
261        match self {
262            Self::TsSyncLoss => "TS_sync_loss",
263            Self::SyncByteError => "Sync_byte_error",
264            Self::PatError2 => "PAT_error_2",
265            Self::ContinuityCountError => "Continuity_count_error",
266            Self::PmtError2 => "PMT_error_2",
267            Self::PidError => "PID_error",
268            Self::TransportError => "Transport_error",
269            Self::CrcError => "CRC_error",
270            Self::PcrRepetitionError => "PCR_repetition_error",
271            Self::PcrDiscontinuityError => "PCR_discontinuity_indicator_error",
272            Self::PtsError => "PTS_error",
273            Self::CatError => "CAT_error",
274            Self::SiRepetitionError => "SI_repetition_error",
275        }
276    }
277
278    /// Clause citation from the spec.
279    #[must_use]
280    pub fn clause(self) -> &'static str {
281        match self {
282            Self::TsSyncLoss => "TR 101 290 v1.4.1 Table 5.0a indicator 1.1",
283            Self::SyncByteError => "TR 101 290 v1.4.1 Table 5.0a indicator 1.2",
284            Self::PatError2 => "TR 101 290 v1.4.1 Table 5.0a indicator 1.3.a",
285            Self::ContinuityCountError => "TR 101 290 v1.4.1 Table 5.0a indicator 1.4",
286            Self::PmtError2 => "TR 101 290 v1.4.1 Table 5.0a indicator 1.5.a",
287            Self::PidError => "TR 101 290 v1.4.1 Table 5.0a indicator 1.6",
288            Self::TransportError => "TR 101 290 v1.4.1 Table 5.0b indicator 2.1",
289            Self::CrcError => "TR 101 290 v1.4.1 Table 5.0b indicator 2.2",
290            Self::PcrRepetitionError => "TR 101 290 v1.4.1 Table 5.0b indicator 2.3a",
291            Self::PcrDiscontinuityError => "TR 101 290 v1.4.1 Table 5.0b indicator 2.3b",
292            Self::PtsError => "TR 101 290 v1.4.1 Table 5.0b indicator 2.5",
293            Self::CatError => "TR 101 290 v1.4.1 Table 5.0b indicator 2.6",
294            Self::SiRepetitionError => "TR 101 290 v1.4.1 Table 5.0c indicator 3.2",
295        }
296    }
297}
298broadcast_common::impl_spec_display!(Indicator);
299
300/// One raised conformance error.
301#[derive(Debug, Clone, PartialEq, Eq)]
302#[cfg_attr(feature = "serde", derive(serde::Serialize))]
303#[non_exhaustive]
304pub struct ConformanceEvent {
305    /// The indicator that was raised.
306    pub indicator: Indicator,
307    /// Priority tier of the indicator.
308    pub priority: Priority,
309    /// PID the error concerns, when applicable.
310    pub pid: Option<u16>,
311    /// Caller timestamp of the packet that raised it.
312    pub at: Duration,
313    /// Human-readable specifics (e.g. "expected cc=5, got 7").
314    pub detail: String,
315}
316
317/// Diagnostic counters.
318#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
319#[cfg_attr(feature = "serde", derive(serde::Serialize))]
320#[non_exhaustive]
321pub struct Stats {
322    /// Total TS packets fed.
323    pub packets: u64,
324    /// Total conformance events raised.
325    pub events: u64,
326    /// Whether the monitor is currently in sync.
327    pub in_sync: bool,
328}
329
330/// Configurable hysteresis and timeout parameters.
331#[derive(Debug, Clone)]
332#[non_exhaustive]
333pub struct Config {
334    /// Maximum interval between PAT sections (Table 5.0a 1.3.a / note 3).
335    /// Default: 500 ms.
336    pub pat_max_interval: Duration,
337    /// Maximum interval between PMT sections per program_map_PID (1.5.a).
338    /// Default: 500 ms.
339    pub pmt_max_interval: Duration,
340    /// Period after which a referenced PID is considered absent (1.6).
341    /// Default: 5 s.
342    pub pid_error_period: Duration,
343    /// Consecutive good sync bytes to acquire sync (1.1).
344    /// Default: 5.
345    pub sync_acquire_packets: u8,
346    /// Consecutive bad sync bytes to declare sync loss (1.1).
347    /// Default: 2.
348    pub sync_loss_packets: u8,
349    /// Maximum interval between consecutive PCR values on a single PID
350    /// (Table 5.0b 2.3a / note 2). Default: 100 ms.
351    pub pcr_repetition_limit: Duration,
352    /// Maximum legal PCR delta (in time) without a signalled discontinuity
353    /// (Table 5.0b 2.3b). Default: 100 ms.
354    pub pcr_discontinuity_limit: Duration,
355    /// Maximum interval between consecutive PTS values on an elementary-stream
356    /// PID (Table 5.0b 2.5 / note 3). Default: 700 ms.
357    pub pts_repetition_limit: Duration,
358    /// Maximum repetition interval for NIT_actual sections (Table 5.0c 3.2 /
359    /// EN 300 468 §5.2.1). Default: 10 s.
360    pub si_nit_interval: Duration,
361    /// Maximum repetition interval for SDT_actual sections (Table 5.0c 3.2 /
362    /// EN 300 468 §5.2.2). Default: 2 s.
363    pub si_sdt_interval: Duration,
364    /// Maximum repetition interval for EIT P/F actual sections (Table 5.0c
365    /// 3.2 / EN 300 468 §5.2.4). Default: 2 s.
366    pub si_eit_pf_interval: Duration,
367    /// Maximum repetition interval for TDT sections (Table 5.0c 3.2 /
368    /// EN 300 468 §5.2.5). Default: 30 s.
369    pub si_tdt_interval: Duration,
370}
371
372impl Default for Config {
373    fn default() -> Self {
374        Self {
375            pat_max_interval: Duration::from_millis(DEFAULT_PAT_MAX_INTERVAL_MS),
376            pmt_max_interval: Duration::from_millis(DEFAULT_PMT_MAX_INTERVAL_MS),
377            pid_error_period: Duration::from_secs(DEFAULT_PID_ERROR_PERIOD_SECS),
378            sync_acquire_packets: DEFAULT_SYNC_ACQUIRE_PACKETS,
379            sync_loss_packets: DEFAULT_SYNC_LOSS_PACKETS,
380            pcr_repetition_limit: Duration::from_millis(DEFAULT_PCR_REPETITION_LIMIT_MS),
381            pcr_discontinuity_limit: Duration::from_millis(DEFAULT_PCR_DISCONTINUITY_LIMIT_MS),
382            pts_repetition_limit: Duration::from_millis(DEFAULT_PTS_REPETITION_LIMIT_MS),
383            si_nit_interval: Duration::from_secs(DEFAULT_SI_NIT_INTERVAL_SECS),
384            si_sdt_interval: Duration::from_secs(DEFAULT_SI_SDT_INTERVAL_SECS),
385            si_eit_pf_interval: Duration::from_secs(DEFAULT_SI_EIT_PF_INTERVAL_SECS),
386            si_tdt_interval: Duration::from_secs(DEFAULT_SI_TDT_INTERVAL_SECS),
387        }
388    }
389}
390
391// ── Internal per-PID state ───────────────────────────────────────────────────
392
393/// Per-PID continuity-counter tracking state.
394struct CcState {
395    last_cc: u8,
396    had_payload: bool,
397    dup_used: bool,
398    initialised: bool,
399}
400
401/// Timer state for a presence/absence check (shared by 1.3.a, 1.5.a, 1.6).
402struct PresenceTimer {
403    last_seen: Duration,
404    reported: bool,
405}
406
407/// State tracked for each program_map_PID signalled by the PAT.
408struct PmtTracking {
409    timer: PresenceTimer,
410    reassembler: SectionReassembler,
411}
412
413/// State tracked for each elementary-stream PID referenced by a PMT.
414struct EsTracking {
415    timer: PresenceTimer,
416}
417
418/// Per-PID PCR tracking state (indicators 2.3a, 2.3b).
419struct PcrState {
420    last_pcr_27mhz: u64,
421    last_pcr_time: Duration,
422    initialised: bool,
423}
424
425/// Per-PID PTS tracking state (indicator 2.5).
426struct PtsState {
427    last_pts_time: Duration,
428    armed: bool,
429}
430
431/// Per-PID section reassembly state for the well-known SI/PSI PIDs.
432struct SiReassembly {
433    reassembler: SectionReassembler,
434}
435
436/// Timer state for an SI table repetition-interval check (indicator 3.2).
437/// Lazily armed — only starts checking after the first section of that
438/// table_id is seen.
439struct SiRepetitionTimer {
440    last_seen: Duration,
441    reported: bool,
442    armed: bool,
443}
444
445// ── ConformanceMonitor ───────────────────────────────────────────────────────
446
447/// ETSI TR 101 290 transport-stream conformance monitor.
448///
449/// Feed one TS packet at a time via [`feed`](Self::feed); each call returns
450/// the events raised by that packet. The monitor is synchronous and
451/// single-threaded — no interior mutability, no async.
452pub struct ConformanceMonitor {
453    config: Config,
454    events: Vec<ConformanceEvent>,
455    stats: Stats,
456
457    // Sync hysteresis state machine (1.1)
458    in_sync: bool,
459    good_run: u8,
460    bad_run: u8,
461
462    // Per-PID continuity counter (1.4)
463    cc_states: BTreeMap<u16, CcState>,
464
465    // PAT section reassembly + timing (1.3.a)
466    pat_reassembler: SectionReassembler,
467    pat_timer: PresenceTimer,
468
469    // PMT section reassembly + timing per program_map_PID (1.5.a)
470    pmt_trackings: BTreeMap<u16, PmtTracking>,
471
472    // Referenced ES PID timing (1.6)
473    es_trackings: BTreeMap<u16, EsTracking>,
474
475    // Well-known SI/PSI section reassembly + CRC checking (2.2)
476    si_reassemblies: BTreeMap<u16, SiReassembly>,
477
478    // Per-PID PCR tracking (2.3a, 2.3b)
479    pcr_states: BTreeMap<u16, PcrState>,
480
481    // Per-PID PTS tracking (2.5)
482    pts_states: BTreeMap<u16, PtsState>,
483
484    // CAT tracking (2.6)
485    cat_seen: bool,
486    scrambled_without_cat_reported: bool,
487
488    // SI repetition-interval timers keyed by table_id (3.2)
489    si_timers: BTreeMap<u8, SiRepetitionTimer>,
490}
491
492impl ConformanceMonitor {
493    /// Create a monitor with default configuration.
494    pub fn new() -> Self {
495        Self::with_config(Config::default())
496    }
497
498    /// Create a monitor with the given configuration.
499    pub fn with_config(config: Config) -> Self {
500        let mut si_reassemblies = BTreeMap::new();
501        for &pid in &SI_PIDS {
502            si_reassemblies.insert(
503                pid,
504                SiReassembly {
505                    reassembler: SectionReassembler::default(),
506                },
507            );
508        }
509        Self {
510            config,
511            events: Vec::new(),
512            stats: Stats {
513                packets: 0,
514                events: 0,
515                in_sync: false,
516            },
517            in_sync: false,
518            good_run: 0,
519            bad_run: 0,
520            cc_states: BTreeMap::new(),
521            pat_reassembler: SectionReassembler::default(),
522            pat_timer: PresenceTimer {
523                last_seen: Duration::ZERO,
524                reported: false,
525            },
526            pmt_trackings: BTreeMap::new(),
527            es_trackings: BTreeMap::new(),
528            si_reassemblies,
529            pcr_states: BTreeMap::new(),
530            pts_states: BTreeMap::new(),
531            cat_seen: false,
532            scrambled_without_cat_reported: false,
533            si_timers: BTreeMap::new(),
534        }
535    }
536
537    /// Feed ONE TS packet (any length; 188 expected) with its caller-supplied
538    /// arrival time `t`.
539    ///
540    /// `t` must be monotonic non-decreasing across calls (documented but not
541    /// enforced). Returns the events raised by this packet.
542    pub fn feed(&mut self, ts_packet: &[u8], t: Duration) -> &[ConformanceEvent] {
543        self.events.clear();
544        self.stats.packets += 1;
545
546        // ── Step 2: Sync byte check (1.2) ─────────────────────────────────
547        let sync_ok = !ts_packet.is_empty() && ts_packet[0] == SYNC_BYTE;
548        if !sync_ok {
549            self.emit(Indicator::SyncByteError, None, t, "sync_byte != 0x47");
550        }
551
552        // ── Step 3: Sync hysteresis state machine (1.1) ──────────────────
553        if sync_ok {
554            self.good_run = self.good_run.saturating_add(1);
555            self.bad_run = 0;
556            if !self.in_sync && self.good_run >= self.config.sync_acquire_packets {
557                self.in_sync = true;
558            }
559        } else {
560            self.bad_run = self.bad_run.saturating_add(1);
561            self.good_run = 0;
562            if self.in_sync && self.bad_run >= self.config.sync_loss_packets {
563                self.in_sync = false;
564                self.emit(
565                    Indicator::TsSyncLoss,
566                    None,
567                    t,
568                    "sync lost after hysteresis threshold",
569                );
570            }
571        }
572
573        // Per the doc: "If indicator 1.1 is activated then all other
574        // indicators are invalid." While not in sync, suppress all other
575        // indicators.
576        if !self.in_sync {
577            return &self.events;
578        }
579
580        // ── Step 4: Parse TS packet ───────────────────────────────────────
581        let packet = match TsPacket::parse(ts_packet) {
582            Ok(p) => p,
583            Err(_) => return &self.events,
584        };
585        let header = &packet.header;
586        let pid = header.pid;
587
588        // ── 2.1 Transport_error (Table 5.0b indicator 2.1) ──────────────
589        if header.tei {
590            self.emit(
591                Indicator::TransportError,
592                Some(pid),
593                t,
594                format!("transport_error_indicator set on PID 0x{pid:04X}"),
595            );
596        }
597
598        // ── Step 5: Continuity_count_error (1.4) ─────────────────────────
599        if pid != PID_NULL {
600            self.check_cc(
601                pid,
602                header.continuity_counter,
603                header.has_payload,
604                t,
605                ts_packet,
606            );
607        }
608
609        // ── Step 7: PAT_error_2 — scrambling check (1.3.a) ──────────────
610        if pid == PID_PAT && header.scrambling != 0 {
611            self.emit(
612                Indicator::PatError2,
613                Some(PID_PAT),
614                t,
615                format!(
616                    "scrambling_control_field != 00 on PID 0x0000 (got {})",
617                    header.scrambling
618                ),
619            );
620        }
621
622        // ── Step 8: PMT_error_2 — scrambling check (1.5.a) ──────────────
623        if self.pmt_trackings.contains_key(&pid) && header.scrambling != 0 {
624            self.emit(
625                Indicator::PmtError2,
626                Some(pid),
627                t,
628                format!("scrambling_control_field != 00 on program_map_PID 0x{pid:04X}"),
629            );
630        }
631
632        // ── 2.6 CAT_error — scrambled packet with no CAT (Table 5.0b 2.6)
633        //
634        // At stream start, scrambled packets may arrive before a CAT section
635        // has been acquired; this check fires once in that case. It re-arms
636        // (see `check_cat_table_id`) when a CAT later appears, so the error is
637        // re-detectable after a CAT section is seen.
638        if header.scrambling != 0 && !self.cat_seen && !self.scrambled_without_cat_reported {
639            self.scrambled_without_cat_reported = true;
640            self.emit(
641                Indicator::CatError,
642                Some(pid),
643                t,
644                format!("scrambled packet on PID 0x{pid:04X} but no CAT seen on PID 0x0001"),
645            );
646        }
647
648        // ── Step 6: Section reassembly — PAT ─────────────────────────────
649        if pid == PID_PAT && header.has_payload {
650            if let Some(payload) = packet.payload {
651                self.pat_reassembler.feed(payload, header.pusi);
652            }
653            self.pat_timer.last_seen = t;
654            self.pat_timer.reported = false;
655            while let Some(section_bytes) = self.pat_reassembler.pop_section() {
656                self.check_crc_and_process_pat(&section_bytes, pid, t);
657            }
658        }
659
660        // ── Step 6b: Section reassembly — PMT PIDs ───────────────────────
661        if self.pmt_trackings.contains_key(&pid) && header.has_payload {
662            if let Some(payload) = packet.payload {
663                if let Some(tracking) = self.pmt_trackings.get_mut(&pid) {
664                    tracking.reassembler.feed(payload, header.pusi);
665                }
666            }
667            let sections: Vec<_> = if let Some(tracking) = self.pmt_trackings.get_mut(&pid) {
668                tracking.timer.last_seen = t;
669                tracking.timer.reported = false;
670                core::iter::from_fn(|| tracking.reassembler.pop_section()).collect()
671            } else {
672                Vec::new()
673            };
674            for section_bytes in &sections {
675                self.check_crc_and_process_pmt(section_bytes, pid, t);
676            }
677        }
678
679        // ── Step 6c: Section reassembly — well-known SI/PSI PIDs (2.2) ───
680        // PAT and PMT PIDs are handled above (they have separate reassembly
681        // for P1 logic). Only process the non-PAT, non-PMT SI PIDs here.
682        if pid != PID_PAT
683            && !self.pmt_trackings.contains_key(&pid)
684            && self.si_reassemblies.contains_key(&pid)
685            && header.has_payload
686        {
687            if let Some(payload) = packet.payload {
688                if let Some(si_ra) = self.si_reassemblies.get_mut(&pid) {
689                    si_ra.reassembler.feed(payload, header.pusi);
690                }
691            }
692            let sections: Vec<_> = if let Some(si_ra) = self.si_reassemblies.get_mut(&pid) {
693                core::iter::from_fn(|| si_ra.reassembler.pop_section()).collect()
694            } else {
695                Vec::new()
696            };
697            for section_bytes in &sections {
698                self.check_crc_for_si(section_bytes, pid, t);
699                self.check_cat_table_id(section_bytes, pid, t);
700                self.update_si_repetition(section_bytes, pid, t);
701            }
702        }
703        // Also CRC-check completed PAT/PMT sections via the si_reassemblies
704        // map (these share the same PID). PAT and PMT already have their own
705        // reassemblers above — the si_reassemblies entries for those PIDs are
706        // not fed again. CRC checking for PAT/PMT is done inside
707        // check_crc_and_process_pat / check_crc_and_process_pmt.
708
709        // ── Step 9: PID_error — update last_seen for referenced PIDs ─────
710        if let Some(tracking) = self.es_trackings.get_mut(&pid) {
711            tracking.timer.last_seen = t;
712            tracking.timer.reported = false;
713        }
714
715        // ── 2.3a / 2.3b: PCR checks (Table 5.0b indicators 2.3a, 2.3b) ──
716        if let Some(Ok(af)) = packet.adaptation_field() {
717            if let Some(pcr) = af.pcr {
718                self.check_pcr(pid, pcr.as_27mhz(), af.discontinuity_indicator, t);
719            }
720        }
721
722        // ── 2.5: PTS check (Table 5.0b indicator 2.5) ───────────────────
723        if header.pusi
724            && header.scrambling == 0
725            && self.es_trackings.contains_key(&pid)
726            && header.has_payload
727        {
728            if let Some(payload) = packet.payload {
729                self.check_pts(pid, payload, t);
730            }
731        }
732
733        // ── Presence-timeout evaluation (1.3.a, 1.5.a, 1.6) ────────────
734        self.check_presence_timeouts(t);
735
736        &self.events
737    }
738
739    /// Diagnostic counters.
740    pub fn stats(&self) -> Stats {
741        Stats {
742            in_sync: self.in_sync,
743            ..self.stats
744        }
745    }
746
747    // ── Internal helpers ──────────────────────────────────────────────────
748
749    fn emit(
750        &mut self,
751        indicator: Indicator,
752        pid: Option<u16>,
753        at: Duration,
754        detail: impl Into<String>,
755    ) {
756        let event = ConformanceEvent {
757            indicator,
758            priority: indicator.priority(),
759            pid,
760            at,
761            detail: detail.into(),
762        };
763        self.stats.events += 1;
764        self.events.push(event);
765    }
766
767    /// Continuity_count_error (1.4) check.
768    fn check_cc(&mut self, pid: u16, cc: u8, has_payload: bool, t: Duration, raw: &[u8]) {
769        // Check for discontinuity_indicator in the adaptation field BEFORE
770        // mutating cc_states (avoids holding the entry borrow across self.emit).
771        let discontinuity = if raw.len() >= 5 {
772            let b3 = raw[3];
773            let has_adaptation = (b3 & 0x20) != 0;
774            if has_adaptation {
775                let af_len = raw[4] as usize;
776                if af_len > 0 && raw.len() > 5 {
777                    (raw[5] & 0x80) != 0
778                } else {
779                    false
780                }
781            } else {
782                false
783            }
784        } else {
785            false
786        };
787
788        // Compute what we need from the existing state, then decide.
789        let (expected, is_duplicate, should_emit_dup, should_emit_cc) = {
790            let state = self.cc_states.entry(pid).or_insert_with(|| CcState {
791                last_cc: cc,
792                had_payload: has_payload,
793                dup_used: false,
794                initialised: false,
795            });
796
797            if !state.initialised {
798                state.last_cc = cc;
799                state.had_payload = has_payload;
800                state.dup_used = false;
801                state.initialised = true;
802                return;
803            }
804
805            if discontinuity {
806                // Will update state below — just signal no emit.
807                (0u8, false, false, false)
808            } else {
809                let is_duplicate = cc == state.last_cc && has_payload;
810                let mut should_emit_dup = false;
811                let mut should_emit_cc = false;
812
813                if is_duplicate {
814                    if state.dup_used {
815                        should_emit_dup = true;
816                    }
817                } else {
818                    state.dup_used = false;
819                    let expected = if has_payload {
820                        (state.last_cc.wrapping_add(1)) & 0x0F
821                    } else {
822                        state.last_cc
823                    };
824                    if cc != expected {
825                        should_emit_cc = true;
826                    }
827                }
828
829                (
830                    if has_payload {
831                        (state.last_cc.wrapping_add(1)) & 0x0F
832                    } else {
833                        state.last_cc
834                    },
835                    is_duplicate,
836                    should_emit_dup,
837                    should_emit_cc,
838                )
839            }
840        };
841
842        // Now emit events without holding a borrow on cc_states.
843        if should_emit_dup {
844            self.emit(
845                Indicator::ContinuityCountError,
846                Some(pid),
847                t,
848                format!("second consecutive duplicate on PID 0x{pid:04X} (cc={cc})"),
849            );
850        }
851        if should_emit_cc {
852            self.emit(
853                Indicator::ContinuityCountError,
854                Some(pid),
855                t,
856                format!("expected cc={expected}, got {cc} on PID 0x{pid:04X}"),
857            );
858        }
859
860        // Finally, update state.
861        let state = self.cc_states.get_mut(&pid).unwrap();
862        if discontinuity {
863            state.last_cc = cc;
864            state.had_payload = has_payload;
865            state.dup_used = false;
866        } else if is_duplicate {
867            // First duplicate is legal; mark dup_used but do NOT update last_cc.
868            state.dup_used = true;
869        } else {
870            state.dup_used = false;
871            state.last_cc = cc;
872            state.had_payload = has_payload;
873        }
874    }
875
876    /// CRC-check a completed section and, if on PID_PAT, process it.
877    fn check_crc_and_process_pat(&mut self, section_bytes: &[u8], pid: u16, t: Duration) {
878        // 2.2: CRC check on PAT section.
879        self.check_crc_for_section(section_bytes, pid, t);
880
881        self.process_pat_section(section_bytes, t);
882    }
883
884    /// CRC-check a completed section and, if on a PMT PID, process it.
885    fn check_crc_and_process_pmt(&mut self, section_bytes: &[u8], pid: u16, t: Duration) {
886        // 2.2: CRC check on PMT section.
887        self.check_crc_for_section(section_bytes, pid, t);
888
889        self.process_pmt_section(section_bytes, pid, t);
890    }
891
892    /// TR 101 290 v1.4.1 Table 5.0b indicator 2.2 — CRC_error.
893    ///
894    /// On any tracked PID, if a completed long-form section has a CRC
895    /// mismatch, emit `CrcError`.
896    fn check_crc_for_section(&mut self, section_bytes: &[u8], pid: u16, t: Duration) {
897        let section = match Section::parse(section_bytes) {
898            Ok(s) => s,
899            Err(_) => return,
900        };
901
902        // validate_crc returns Ok for short-form sections (no CRC to check).
903        if let Err(mpeg_ts::error::Error::CrcMismatch { .. }) = section.validate_crc(section_bytes)
904        {
905            self.emit(
906                Indicator::CrcError,
907                Some(pid),
908                t,
909                format!(
910                    "CRC-32 mismatch on PID 0x{:04X} (table_id 0x{:02X})",
911                    pid, section.table_id
912                ),
913            );
914        }
915    }
916
917    /// CRC-check for SI PIDs that are not PAT/PMT (handled via si_reassemblies).
918    fn check_crc_for_si(&mut self, section_bytes: &[u8], pid: u16, t: Duration) {
919        self.check_crc_for_section(section_bytes, pid, t);
920    }
921
922    /// TR 101 290 v1.4.1 Table 5.0b indicator 2.6 — CAT_error, condition 1:
923    /// section with `table_id != 0x01` on PID_CAT.
924    fn check_cat_table_id(&mut self, section_bytes: &[u8], pid: u16, t: Duration) {
925        if pid != PID_CAT {
926            return;
927        }
928        let section = match Section::parse(section_bytes) {
929            Ok(s) => s,
930            Err(_) => return,
931        };
932        if section.table_id == CAT_TABLE_ID {
933            // Valid CAT section — mark as seen.
934            self.cat_seen = true;
935            // Re-arm the "scrambled without CAT" check so that if a CAT was
936            // previously absent and then appears, the check resets.
937            self.scrambled_without_cat_reported = false;
938        } else {
939            self.emit(
940                Indicator::CatError,
941                Some(PID_CAT),
942                t,
943                format!(
944                    "section with table_id 0x{:02X} on PID 0x0001 (expected 0x01 for CAT)",
945                    section.table_id
946                ),
947            );
948        }
949    }
950
951    /// Process a completed section on PID_PAT.
952    fn process_pat_section(&mut self, section_bytes: &[u8], t: Duration) {
953        let section = match Section::parse(section_bytes) {
954            Ok(s) => s,
955            Err(_) => return,
956        };
957
958        // 1.3.a: section with table_id other than 0x00 found on PID 0x0000.
959        if section.table_id != PAT_TABLE_ID {
960            self.emit(
961                Indicator::PatError2,
962                Some(PID_PAT),
963                t,
964                format!(
965                    "section with table_id 0x{:02X} on PID 0x0000 (expected 0x00)",
966                    section.table_id
967                ),
968            );
969            return;
970        }
971
972        // Parse the PAT proper.
973        let pat = match PatSection::parse(section_bytes) {
974            Ok(p) => p,
975            Err(_) => return,
976        };
977
978        // Discover program_map_PIDs and start tracking them.
979        for entry in pat.programmes() {
980            let pmt_pid = entry.pid;
981            self.pmt_trackings
982                .entry(pmt_pid)
983                .or_insert_with(|| PmtTracking {
984                    timer: PresenceTimer {
985                        last_seen: t,
986                        reported: false,
987                    },
988                    reassembler: SectionReassembler::default(),
989                });
990        }
991    }
992
993    /// Process a completed section on a program_map_PID.
994    fn process_pmt_section(&mut self, section_bytes: &[u8], _pid: u16, t: Duration) {
995        let section = match Section::parse(section_bytes) {
996            Ok(s) => s,
997            Err(_) => return,
998        };
999
1000        // 1.5.a only checks presence and scrambling of table_id 0x02 sections.
1001        // If table_id is not 0x02, skip — we don't emit PMT_error_2 for a
1002        // wrong table_id on a program_map_PID (that's not in the spec for
1003        // 1.5.a).
1004        let pmt_table_id: u8 = dvb_si::tables::pmt::TABLE_ID;
1005        if section.table_id != pmt_table_id {
1006            return;
1007        }
1008
1009        // Parse the PMT proper.
1010        let pmt = match PmtSection::parse(section_bytes) {
1011            Ok(p) => p,
1012            Err(_) => return,
1013        };
1014
1015        // Collect new ES PIDs to add.
1016        let mut new_es_pids: Vec<u16> = Vec::new();
1017        if pmt.pcr_pid != PID_NULL && !self.es_trackings.contains_key(&pmt.pcr_pid) {
1018            new_es_pids.push(pmt.pcr_pid);
1019        }
1020        for stream in &pmt.streams {
1021            let es_pid = stream.elementary_pid;
1022            if !self.es_trackings.contains_key(&es_pid) {
1023                new_es_pids.push(es_pid);
1024            }
1025        }
1026
1027        for es_pid in new_es_pids {
1028            self.es_trackings.insert(
1029                es_pid,
1030                EsTracking {
1031                    timer: PresenceTimer {
1032                        last_seen: t,
1033                        reported: false,
1034                    },
1035                },
1036            );
1037        }
1038    }
1039
1040    /// TR 101 290 v1.4.1 Table 5.0b indicators 2.3a / 2.3b — PCR checks.
1041    fn check_pcr(&mut self, pid: u16, pcr_27mhz: u64, discontinuity: bool, t: Duration) {
1042        let state = self.pcr_states.entry(pid).or_insert_with(|| PcrState {
1043            last_pcr_27mhz: 0,
1044            last_pcr_time: Duration::ZERO,
1045            initialised: false,
1046        });
1047
1048        if !state.initialised {
1049            state.last_pcr_27mhz = pcr_27mhz;
1050            state.last_pcr_time = t;
1051            state.initialised = true;
1052            return;
1053        }
1054
1055        // Snapshot state for decision-making before any emit.
1056        let last_pcr_time = state.last_pcr_time;
1057        let last_pcr_27mhz = state.last_pcr_27mhz;
1058
1059        // 2.3a: PCR_repetition_error — interval between consecutive PCR
1060        // values exceeds the configured limit.
1061        let rep_interval = t.saturating_sub(last_pcr_time);
1062        let should_emit_rep = rep_interval > self.config.pcr_repetition_limit;
1063
1064        // 2.3b: PCR_discontinuity_indicator_error — PCR delta exceeds 100 ms
1065        // without a signalled discontinuity.
1066        let delta =
1067            (pcr_27mhz.wrapping_add(PCR_MODULUS_27MHZ) - last_pcr_27mhz) % PCR_MODULUS_27MHZ;
1068        let delta_ms = delta * 1000 / CLOCK_27MHZ;
1069        let limit_ms = self.config.pcr_discontinuity_limit.as_millis() as u64;
1070        let should_emit_disc = delta_ms > limit_ms && !discontinuity;
1071
1072        // Emit outside the HashMap borrow.
1073        if should_emit_rep {
1074            self.emit(
1075                Indicator::PcrRepetitionError,
1076                Some(pid),
1077                t,
1078                format!(
1079                    "PCR interval {} ms exceeds limit {} ms on PID 0x{:04X}",
1080                    rep_interval.as_millis(),
1081                    self.config.pcr_repetition_limit.as_millis(),
1082                    pid
1083                ),
1084            );
1085        }
1086        if should_emit_disc {
1087            self.emit(
1088                Indicator::PcrDiscontinuityError,
1089                Some(pid),
1090                t,
1091                format!(
1092                    "PCR delta {delta_ms} ms exceeds limit {limit_ms} ms on PID 0x{pid:04X} without discontinuity_indicator"
1093                ),
1094            );
1095        }
1096
1097        // Update state.
1098        let state = self.pcr_states.get_mut(&pid).unwrap();
1099        state.last_pcr_27mhz = pcr_27mhz;
1100        state.last_pcr_time = t;
1101    }
1102
1103    /// TR 101 290 v1.4.1 Table 5.0b indicator 2.5 — PTS_error.
1104    ///
1105    /// Peeks the PES header on an elementary-stream PID for PTS_DTS_flags.
1106    /// Only checks PIDs that have been "armed" by seeing at least one PTS.
1107    fn check_pts(&mut self, pid: u16, payload: &[u8], t: Duration) {
1108        // PES start-code prefix: 00 00 01.
1109        if payload.len() < PES_FLAGS_OFFSET + 2 {
1110            return;
1111        }
1112        if payload[0] != PES_PREFIX_0 || payload[1] != PES_PREFIX_1 || payload[2] != PES_PREFIX_2 {
1113            return;
1114        }
1115
1116        // Byte 6: `'10' + flags` — the top two bits must be `10`.
1117        let flags_byte = payload[PES_FLAGS_OFFSET];
1118        if (flags_byte >> 6) != 0b10 {
1119            return;
1120        }
1121
1122        // Byte 7: PTS_DTS_flags in bits `[7:6]`.
1123        let pts_dts_flags = payload[PES_FLAGS_OFFSET + 1] & PES_PTS_DTS_FLAGS_MASK;
1124        let pts_present = (pts_dts_flags & PES_PTS_PRESENT) != 0;
1125        if !pts_present {
1126            return;
1127        }
1128
1129        let state = self.pts_states.entry(pid).or_insert_with(|| PtsState {
1130            last_pts_time: Duration::ZERO,
1131            armed: false,
1132        });
1133
1134        if !state.armed {
1135            // First PTS on this PID — arm the check, no error yet.
1136            state.last_pts_time = t;
1137            state.armed = true;
1138            return;
1139        }
1140
1141        // Snapshot state for decision-making before any emit.
1142        let last_pts_time = state.last_pts_time;
1143        let pts_interval = t.saturating_sub(last_pts_time);
1144        let should_emit = pts_interval > self.config.pts_repetition_limit;
1145
1146        if should_emit {
1147            self.emit(
1148                Indicator::PtsError,
1149                Some(pid),
1150                t,
1151                format!(
1152                    "PTS interval {} ms exceeds limit {} ms on PID 0x{:04X}",
1153                    pts_interval.as_millis(),
1154                    self.config.pts_repetition_limit.as_millis(),
1155                    pid
1156                ),
1157            );
1158        }
1159
1160        // Update state.
1161        let state = self.pts_states.get_mut(&pid).unwrap();
1162        state.last_pts_time = t;
1163    }
1164
1165    /// TR 101 290 v1.4.1 Table 5.0c indicator 3.2 — update SI repetition timer
1166    /// when a completed section on a well-known SI PID matches one of the four
1167    /// tracked table_ids.
1168    fn update_si_repetition(&mut self, section_bytes: &[u8], _pid: u16, t: Duration) {
1169        let table_id = match Section::parse(section_bytes) {
1170            Ok(s) => s.table_id,
1171            Err(_) => return,
1172        };
1173
1174        let is_tracked = table_id == NIT_ACTUAL_TABLE_ID
1175            || table_id == SDT_ACTUAL_TABLE_ID
1176            || table_id == EIT_PF_ACTUAL_TABLE_ID
1177            || table_id == TDT_TABLE_ID;
1178
1179        if !is_tracked {
1180            return;
1181        }
1182
1183        let timer = self
1184            .si_timers
1185            .entry(table_id)
1186            .or_insert_with(|| SiRepetitionTimer {
1187                last_seen: Duration::ZERO,
1188                reported: false,
1189                armed: false,
1190            });
1191
1192        timer.last_seen = t;
1193        timer.reported = false;
1194        timer.armed = true;
1195    }
1196
1197    /// Evaluate all presence/absence timeouts against the current time `t`.
1198    fn check_presence_timeouts(&mut self, t: Duration) {
1199        // 1.3.a: PAT presence timeout
1200        if t.saturating_sub(self.pat_timer.last_seen) > self.config.pat_max_interval
1201            && !self.pat_timer.reported
1202        {
1203            self.pat_timer.reported = true;
1204            self.emit(
1205                Indicator::PatError2,
1206                Some(PID_PAT),
1207                t,
1208                format!(
1209                    "no PAT section within {} ms",
1210                    self.config.pat_max_interval.as_millis()
1211                ),
1212            );
1213        }
1214
1215        // 1.5.a: PMT presence timeout per program_map_PID
1216        // Collect PIDs that need events, then emit outside the iteration.
1217        let pmt_timeouts: Vec<(u16, u64)> = self
1218            .pmt_trackings
1219            .iter()
1220            .filter_map(|(&pid, tracking)| {
1221                if t.saturating_sub(tracking.timer.last_seen) > self.config.pmt_max_interval
1222                    && !tracking.timer.reported
1223                {
1224                    Some((pid, self.config.pmt_max_interval.as_millis() as u64))
1225                } else {
1226                    None
1227                }
1228            })
1229            .collect();
1230        for (pid, interval_ms) in pmt_timeouts {
1231            if let Some(tracking) = self.pmt_trackings.get_mut(&pid) {
1232                tracking.timer.reported = true;
1233            }
1234            self.emit(
1235                Indicator::PmtError2,
1236                Some(pid),
1237                t,
1238                format!("no PMT section on program_map_PID 0x{pid:04X} within {interval_ms} ms"),
1239            );
1240        }
1241
1242        // 1.6: PID_error — referenced PID absence
1243        let pid_timeouts: Vec<(u16, u64)> = self
1244            .es_trackings
1245            .iter()
1246            .filter_map(|(&pid, tracking)| {
1247                if t.saturating_sub(tracking.timer.last_seen) > self.config.pid_error_period
1248                    && !tracking.timer.reported
1249                {
1250                    Some((pid, self.config.pid_error_period.as_secs()))
1251                } else {
1252                    None
1253                }
1254            })
1255            .collect();
1256        for (pid, period_secs) in pid_timeouts {
1257            if let Some(tracking) = self.es_trackings.get_mut(&pid) {
1258                tracking.timer.reported = true;
1259            }
1260            self.emit(
1261                Indicator::PidError,
1262                Some(pid),
1263                t,
1264                format!("referenced PID 0x{pid:04X} absent for > {period_secs} s"),
1265            );
1266        }
1267
1268        // 3.2: SI_repetition_error — maximum interval for tracked SI tables.
1269        // Collect table_ids that need events, then emit outside the iteration.
1270        let si_timeouts: Vec<(u8, u64, u16, u64)> = self
1271            .si_timers
1272            .iter()
1273            .filter_map(|(&table_id, timer)| {
1274                if !timer.armed || timer.reported {
1275                    return None;
1276                }
1277                let (limit, pid) = match table_id {
1278                    NIT_ACTUAL_TABLE_ID => (self.config.si_nit_interval, PID_NIT),
1279                    SDT_ACTUAL_TABLE_ID => (self.config.si_sdt_interval, PID_SDT_BAT),
1280                    EIT_PF_ACTUAL_TABLE_ID => (self.config.si_eit_pf_interval, PID_EIT),
1281                    TDT_TABLE_ID => (self.config.si_tdt_interval, PID_TDT_TOT),
1282                    _ => return None,
1283                };
1284                let interval = t.saturating_sub(timer.last_seen);
1285                if interval > limit {
1286                    Some((
1287                        table_id,
1288                        interval.as_millis() as u64,
1289                        pid,
1290                        limit.as_millis() as u64,
1291                    ))
1292                } else {
1293                    None
1294                }
1295            })
1296            .collect();
1297        for (table_id, interval_ms, pid, limit_ms) in si_timeouts {
1298            if let Some(timer) = self.si_timers.get_mut(&table_id) {
1299                timer.reported = true;
1300            }
1301            let table_name = match table_id {
1302                NIT_ACTUAL_TABLE_ID => "NIT_actual",
1303                SDT_ACTUAL_TABLE_ID => "SDT_actual",
1304                EIT_PF_ACTUAL_TABLE_ID => "EIT_P/F_actual",
1305                TDT_TABLE_ID => "TDT",
1306                _ => "unknown",
1307            };
1308            self.emit(
1309                Indicator::SiRepetitionError,
1310                Some(pid),
1311                t,
1312                format!("{table_name} repetition interval {interval_ms} ms exceeds {limit_ms} ms"),
1313            );
1314        }
1315    }
1316}
1317
1318impl Default for ConformanceMonitor {
1319    fn default() -> Self {
1320        Self::new()
1321    }
1322}
1323
1324#[cfg(test)]
1325mod tests;