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;
#[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
}
#[derive(Debug, Clone)]
pub struct PcrDiscDetector {
last_pcr: BTreeMap<Pid, Clock27>,
limit: Duration,
}
impl PcrDiscDetector {
#[must_use]
pub fn new(limit: Duration) -> Self {
Self {
last_pcr: BTreeMap::new(),
limit,
}
}
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)
}
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)));
}
}