mpeg-ts 0.11.0

MPEG-2 Transport Stream framing (ITU-T H.222.0 / ISO/IEC 13818-1): TS packet, adaptation field, PCR, PSI section reassembly + packetisation, resync. no_std.
Documentation
//! PCR step classification: the per-PID PCR memory and the step predicate
//! behind ETSI TR 101 290 v1.4.1 Table 5.0b indicator 2.3b
//! (`PCR_discontinuity_indicator_error`).
//!
//! The 2.3b clause is a comparison of two successive PCR values on one PID,
//! so it needs no arrival clock: [`pcr_step_exceeds`] is that comparison and
//! [`PcrDiscDetector`] keeps the previous value per PID. `dvb-conformance`
//! (the monitor), `ts-fix` and `ts-remux` all call this one implementation.
//! The threshold is the caller's: TR 101 290 states 100 ms, and the
//! applications that follow the table pass that value.
//!
//! # Spec
//!
//! ETSI TR 101 290 v1.4.1 section 5.2.2 Table 5.0b indicator 2.3b
//! (`private/specs-verified/dvb/dvb-conformance/tr_101_290.md`); ITU-T H.222.0
//! (ISO/IEC 13818-1) clause 2.4.3.5 `discontinuity_indicator` and clause
//! 2.4.2.2 PCR semantics
//! (`private/specs-verified/mpeg/mpeg-ts/tables/h222_0/pcr.md`).

use alloc::collections::BTreeMap;
use core::time::Duration;

use broadcast_common::clock33::{Clock27, PCR_HZ};
use broadcast_core::units::MICROS_PER_SEC;

use crate::pid::Pid;
use crate::ts::TsPacket;

/// Whether the step from `previous` to `current` PCR, in either direction and
/// across the PCR wrap, is wider than `limit`. The caller decides what a
/// signalled `discontinuity_indicator` excuses.
#[must_use]
pub fn pcr_step_exceeds(previous: Clock27, current: Clock27, limit: Duration) -> bool {
    let limit_ticks = (limit.as_micros() as u64).saturating_mul(PCR_HZ) / MICROS_PER_SEC;
    previous.signed_distance_to(current).unsigned_abs() > limit_ticks
}

/// Incremental indicator 2.3b classifier: one previous PCR per PID.
#[derive(Debug, Clone)]
pub struct PcrDiscDetector {
    last_pcr: BTreeMap<Pid, Clock27>,
    limit: Duration,
}

impl PcrDiscDetector {
    /// A detector that flags a step wider than `limit` (TR 101 290 states
    /// 100 ms for indicator 2.3b).
    #[must_use]
    pub fn new(limit: Duration) -> Self {
        Self {
            last_pcr: BTreeMap::new(),
            limit,
        }
    }

    /// Feed one original, unmodified 188-byte TS packet.
    ///
    /// Returns `Some(pid)` when the packet carries a PCR on `pid` that differs
    /// from the previous PCR on that PID by more than the limit with
    /// `discontinuity_indicator == 0` (a genuine, unflagged break; a flagged
    /// one never qualifies). Returns `None` otherwise.
    ///
    /// Call it on every packet in stream order, including those the caller
    /// treats specially, so the per-PID memory follows the true timeline.
    pub fn feed(&mut self, packet: &[u8]) -> Option<Pid> {
        let ts = TsPacket::parse(packet).ok()?;
        let Some(Ok(af)) = ts.adaptation_field() else {
            return None;
        };
        let clock = af.pcr?.to_clock27().ok()?;
        let pid = ts.header.pid;
        let previous = self.last_pcr.insert(pid, clock)?;
        (!af.discontinuity_indicator && pcr_step_exceeds(previous, clock, self.limit))
            .then_some(pid)
    }

    /// Forget the memory of `pid` (an input restart: the next PCR is a first).
    pub fn forget(&mut self, pid: Pid) {
        self.last_pcr.remove(&pid);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use broadcast_common::clock33::PCR_WRAP_27MHZ;

    const TICKS_PER_MS: u64 = PCR_HZ / 1_000;
    const LIMIT: Duration = Duration::from_millis(100);

    fn at(ms: u64) -> Clock27 {
        Clock27::from_27mhz(ms * TICKS_PER_MS).expect("in range")
    }

    #[test]
    fn step_is_symmetric_wrap_safe_and_strict() {
        assert!(!pcr_step_exceeds(at(0), at(100), LIMIT));
        assert!(pcr_step_exceeds(at(0), at(101), LIMIT));
        assert!(!pcr_step_exceeds(at(100), at(0), LIMIT));
        assert!(pcr_step_exceeds(at(101), at(0), LIMIT));
        let before_wrap =
            Clock27::from_27mhz(PCR_WRAP_27MHZ - 10 * TICKS_PER_MS).expect("in range");
        assert!(!pcr_step_exceeds(before_wrap, at(50), LIMIT));
        assert!(pcr_step_exceeds(before_wrap, at(200), LIMIT));
        assert!(pcr_step_exceeds(
            at(0),
            at(1_000),
            Duration::from_millis(500)
        ));
        assert!(!pcr_step_exceeds(at(0), at(1_000), Duration::from_secs(1)));
    }
}