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
//! Multiplex bitrate estimated from the PCRs of one PCR PID (ISO/IEC 13818-1
//! §2.4.3.5, PCR PIDs per program §2.4.4.9).
//!
//! Each PCR PID runs its own clock, so samples are tracked per PID and the
//! estimate is taken on a single PID's clock. Values are unwrapped across the
//! ~26.5 h PCR wrap (§2.4.2.2) through [`broadcast_common::clock33`].

use alloc::collections::BTreeMap;
use broadcast_common::clock33::{self, PCR_HZ};

use crate::pid::Pid;
use crate::ts::TS_PACKET_SIZE;

const BITS_PER_PACKET: u64 = (TS_PACKET_SIZE as u64) * 8;

/// First/last `(packet_index, unwrapped 27 MHz value)` seen on one PCR PID.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PcrTrack {
    first: (u64, i128),
    last: (u64, i128),
    samples: u64,
    prev_raw: u64,
}

/// The estimate taken from one PCR PID: the packets carried between its first
/// and last PCR over the time those PCRs span.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PcrBitrate {
    pid: Pid,
    packets: u64,
    ticks: u64,
    samples: u64,
}

impl PcrBitrate {
    /// The PCR PID whose clock the estimate was taken on.
    #[must_use]
    pub fn pid(&self) -> Pid {
        self.pid
    }

    /// PCRs observed on [`pid`](Self::pid).
    #[must_use]
    pub fn samples(&self) -> u64 {
        self.samples
    }

    /// Seconds between the first and last PCR on [`pid`](Self::pid).
    #[must_use]
    pub fn span_seconds(&self) -> f64 {
        self.ticks as f64 / PCR_HZ as f64
    }

    /// Multiplex bits per second: `packets · 188 · 8 · 27 MHz / Δpcr`.
    #[must_use]
    pub fn bits_per_second(&self) -> f64 {
        self.bits_per_second_for(self.packets)
    }

    /// Bits per second carried by `packets` packets over the same span, e.g.
    /// one PID's packet count against the multiplex's PCR clock.
    #[must_use]
    pub fn bits_per_second_for(&self, packets: u64) -> f64 {
        (packets * BITS_PER_PACKET) as f64 * (PCR_HZ as f64) / (self.ticks as f64)
    }
}

/// Folds PCR observations and yields the bitrate of the best PCR PID.
#[derive(Debug, Clone, Default)]
pub struct PcrBitrateEstimator {
    tracks: BTreeMap<Pid, PcrTrack>,
}

impl PcrBitrateEstimator {
    /// An estimator with no samples.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Fold in one PCR (`packet_index`, 27 MHz value) seen on `pid`,
    /// correcting for a single forward wrap since that PID's previous PCR.
    pub fn push(&mut self, pid: Pid, packet_index: u64, pcr_27mhz: u64) {
        match self.tracks.get_mut(&pid) {
            None => {
                self.tracks.insert(
                    pid,
                    PcrTrack {
                        first: (packet_index, i128::from(pcr_27mhz)),
                        last: (packet_index, i128::from(pcr_27mhz)),
                        samples: 1,
                        prev_raw: pcr_27mhz,
                    },
                );
            }
            Some(track) => {
                let unwrapped = track.last.1
                    + i128::from(clock33::pcr_signed_distance(track.prev_raw, pcr_27mhz));
                track.last = (packet_index, unwrapped);
                track.prev_raw = pcr_27mhz;
                track.samples += 1;
            }
        }
    }

    /// The estimate on the PCR PID with the most samples (ties to the lowest
    /// PID), among those whose PCR advanced across more than one packet.
    /// `None` when no PID has two advancing PCRs.
    #[must_use]
    pub fn best(&self) -> Option<PcrBitrate> {
        let mut best: Option<PcrBitrate> = None;
        for (&pid, track) in &self.tracks {
            let advancing = track.last.1 > track.first.1 && track.last.0 > track.first.0;
            if !advancing {
                continue;
            }
            if best.is_some_and(|b| b.samples >= track.samples) {
                continue;
            }
            best = Some(PcrBitrate {
                pid,
                packets: track.last.0 - track.first.0,
                ticks: (track.last.1 - track.first.1) as u64,
                samples: track.samples,
            });
        }
        best
    }
}

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

    fn pid(v: u16) -> Pid {
        Pid::try_from(v).expect("valid pid")
    }

    #[test]
    fn two_pcrs_one_second_apart() {
        let mut e = PcrBitrateEstimator::new();
        e.push(pid(0x100), 10, 0);
        e.push(pid(0x100), 10_010, PCR_HZ);
        let b = e.best().expect("two PCRs");
        assert!((b.bits_per_second() - 15_040_000.0).abs() < 1e-6);
        assert_eq!(b.pid(), pid(0x100));
        assert_eq!(b.samples(), 2);
        assert!((b.span_seconds() - 1.0).abs() < 1e-12);
    }

    #[test]
    fn none_without_two_advancing_pcrs() {
        let mut e = PcrBitrateEstimator::new();
        assert!(e.best().is_none());
        e.push(pid(0x100), 5, 100);
        assert!(e.best().is_none());
        e.push(pid(0x100), 20, 100);
        assert!(e.best().is_none());
        let mut back = PcrBitrateEstimator::new();
        back.push(pid(0x100), 1, 5);
        back.push(pid(0x100), 2, 2);
        assert!(back.best().is_none());
    }

    #[test]
    fn a_forward_wrap_unwraps_to_a_small_step() {
        let mut e = PcrBitrateEstimator::new();
        e.push(pid(0x100), 1, clock33::PCR_WRAP_27MHZ - 3);
        e.push(pid(0x100), 2, 2);
        let b = e.best().expect("wrap is a forward step");
        assert!((b.span_seconds() - 5.0 / PCR_HZ as f64).abs() < 1e-18);
    }

    #[test]
    fn the_pid_with_most_samples_wins_and_clocks_are_not_mixed() {
        let mut e = PcrBitrateEstimator::new();
        e.push(pid(0x200), 0, 0);
        e.push(pid(0x200), 1_000, PCR_HZ);
        e.push(pid(0x100), 0, 0);
        e.push(pid(0x100), 500, PCR_HZ / 2);
        e.push(pid(0x100), 1_000, PCR_HZ);
        let b = e.best().expect("estimate");
        assert_eq!(b.pid(), pid(0x100));
        assert_eq!(b.samples(), 3);
    }

    #[test]
    fn ties_go_to_the_lowest_pid() {
        let mut e = PcrBitrateEstimator::new();
        for p in [0x300, 0x100, 0x200] {
            e.push(pid(p), 0, 0);
            e.push(pid(p), 100, PCR_HZ);
        }
        assert_eq!(e.best().expect("estimate").pid(), pid(0x100));
    }

    #[test]
    fn per_pid_share_uses_the_same_span() {
        let mut e = PcrBitrateEstimator::new();
        e.push(pid(0x100), 0, 0);
        e.push(pid(0x100), 1_000, PCR_HZ);
        let b = e.best().expect("estimate");
        assert!((b.bits_per_second_for(100) - 150_400.0).abs() < 1e-6);
    }
}