Skip to main content

mpeg_ts/
bitrate.rs

1//! Multiplex bitrate estimated from the PCRs of one PCR PID (ISO/IEC 13818-1
2//! §2.4.3.5, PCR PIDs per program §2.4.4.9).
3//!
4//! Each PCR PID runs its own clock, so samples are tracked per PID and the
5//! estimate is taken on a single PID's clock. Values are unwrapped across the
6//! ~26.5 h PCR wrap (§2.4.2.2) through [`broadcast_common::clock33`].
7
8use alloc::collections::BTreeMap;
9use broadcast_common::clock33::{self, PCR_HZ};
10
11use crate::pid::Pid;
12use crate::ts::TS_PACKET_SIZE;
13
14const BITS_PER_PACKET: u64 = (TS_PACKET_SIZE as u64) * 8;
15
16/// First/last `(packet_index, unwrapped 27 MHz value)` seen on one PCR PID.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18struct PcrTrack {
19    first: (u64, i128),
20    last: (u64, i128),
21    samples: u64,
22    prev_raw: u64,
23}
24
25/// The estimate taken from one PCR PID: the packets carried between its first
26/// and last PCR over the time those PCRs span.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct PcrBitrate {
29    pid: Pid,
30    packets: u64,
31    ticks: u64,
32    samples: u64,
33}
34
35impl PcrBitrate {
36    /// The PCR PID whose clock the estimate was taken on.
37    #[must_use]
38    pub fn pid(&self) -> Pid {
39        self.pid
40    }
41
42    /// PCRs observed on [`pid`](Self::pid).
43    #[must_use]
44    pub fn samples(&self) -> u64 {
45        self.samples
46    }
47
48    /// Seconds between the first and last PCR on [`pid`](Self::pid).
49    #[must_use]
50    pub fn span_seconds(&self) -> f64 {
51        self.ticks as f64 / PCR_HZ as f64
52    }
53
54    /// Multiplex bits per second: `packets · 188 · 8 · 27 MHz / Δpcr`.
55    #[must_use]
56    pub fn bits_per_second(&self) -> f64 {
57        self.bits_per_second_for(self.packets)
58    }
59
60    /// Bits per second carried by `packets` packets over the same span, e.g.
61    /// one PID's packet count against the multiplex's PCR clock.
62    #[must_use]
63    pub fn bits_per_second_for(&self, packets: u64) -> f64 {
64        (packets * BITS_PER_PACKET) as f64 * (PCR_HZ as f64) / (self.ticks as f64)
65    }
66}
67
68/// Folds PCR observations and yields the bitrate of the best PCR PID.
69#[derive(Debug, Clone, Default)]
70pub struct PcrBitrateEstimator {
71    tracks: BTreeMap<Pid, PcrTrack>,
72}
73
74impl PcrBitrateEstimator {
75    /// An estimator with no samples.
76    #[must_use]
77    pub fn new() -> Self {
78        Self::default()
79    }
80
81    /// Fold in one PCR (`packet_index`, 27 MHz value) seen on `pid`,
82    /// correcting for a single forward wrap since that PID's previous PCR.
83    pub fn push(&mut self, pid: Pid, packet_index: u64, pcr_27mhz: u64) {
84        match self.tracks.get_mut(&pid) {
85            None => {
86                self.tracks.insert(
87                    pid,
88                    PcrTrack {
89                        first: (packet_index, i128::from(pcr_27mhz)),
90                        last: (packet_index, i128::from(pcr_27mhz)),
91                        samples: 1,
92                        prev_raw: pcr_27mhz,
93                    },
94                );
95            }
96            Some(track) => {
97                let unwrapped = track.last.1
98                    + i128::from(clock33::pcr_signed_distance(track.prev_raw, pcr_27mhz));
99                track.last = (packet_index, unwrapped);
100                track.prev_raw = pcr_27mhz;
101                track.samples += 1;
102            }
103        }
104    }
105
106    /// The estimate on the PCR PID with the most samples (ties to the lowest
107    /// PID), among those whose PCR advanced across more than one packet.
108    /// `None` when no PID has two advancing PCRs.
109    #[must_use]
110    pub fn best(&self) -> Option<PcrBitrate> {
111        let mut best: Option<PcrBitrate> = None;
112        for (&pid, track) in &self.tracks {
113            let advancing = track.last.1 > track.first.1 && track.last.0 > track.first.0;
114            if !advancing {
115                continue;
116            }
117            if best.is_some_and(|b| b.samples >= track.samples) {
118                continue;
119            }
120            best = Some(PcrBitrate {
121                pid,
122                packets: track.last.0 - track.first.0,
123                ticks: (track.last.1 - track.first.1) as u64,
124                samples: track.samples,
125            });
126        }
127        best
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    fn pid(v: u16) -> Pid {
136        Pid::try_from(v).expect("valid pid")
137    }
138
139    #[test]
140    fn two_pcrs_one_second_apart() {
141        let mut e = PcrBitrateEstimator::new();
142        e.push(pid(0x100), 10, 0);
143        e.push(pid(0x100), 10_010, PCR_HZ);
144        let b = e.best().expect("two PCRs");
145        assert!((b.bits_per_second() - 15_040_000.0).abs() < 1e-6);
146        assert_eq!(b.pid(), pid(0x100));
147        assert_eq!(b.samples(), 2);
148        assert!((b.span_seconds() - 1.0).abs() < 1e-12);
149    }
150
151    #[test]
152    fn none_without_two_advancing_pcrs() {
153        let mut e = PcrBitrateEstimator::new();
154        assert!(e.best().is_none());
155        e.push(pid(0x100), 5, 100);
156        assert!(e.best().is_none());
157        e.push(pid(0x100), 20, 100);
158        assert!(e.best().is_none());
159        let mut back = PcrBitrateEstimator::new();
160        back.push(pid(0x100), 1, 5);
161        back.push(pid(0x100), 2, 2);
162        assert!(back.best().is_none());
163    }
164
165    #[test]
166    fn a_forward_wrap_unwraps_to_a_small_step() {
167        let mut e = PcrBitrateEstimator::new();
168        e.push(pid(0x100), 1, clock33::PCR_WRAP_27MHZ - 3);
169        e.push(pid(0x100), 2, 2);
170        let b = e.best().expect("wrap is a forward step");
171        assert!((b.span_seconds() - 5.0 / PCR_HZ as f64).abs() < 1e-18);
172    }
173
174    #[test]
175    fn the_pid_with_most_samples_wins_and_clocks_are_not_mixed() {
176        let mut e = PcrBitrateEstimator::new();
177        e.push(pid(0x200), 0, 0);
178        e.push(pid(0x200), 1_000, PCR_HZ);
179        e.push(pid(0x100), 0, 0);
180        e.push(pid(0x100), 500, PCR_HZ / 2);
181        e.push(pid(0x100), 1_000, PCR_HZ);
182        let b = e.best().expect("estimate");
183        assert_eq!(b.pid(), pid(0x100));
184        assert_eq!(b.samples(), 3);
185    }
186
187    #[test]
188    fn ties_go_to_the_lowest_pid() {
189        let mut e = PcrBitrateEstimator::new();
190        for p in [0x300, 0x100, 0x200] {
191            e.push(pid(p), 0, 0);
192            e.push(pid(p), 100, PCR_HZ);
193        }
194        assert_eq!(e.best().expect("estimate").pid(), pid(0x100));
195    }
196
197    #[test]
198    fn per_pid_share_uses_the_same_span() {
199        let mut e = PcrBitrateEstimator::new();
200        e.push(pid(0x100), 0, 0);
201        e.push(pid(0x100), 1_000, PCR_HZ);
202        let b = e.best().expect("estimate");
203        assert!((b.bits_per_second_for(100) - 150_400.0).abs() < 1e-6);
204    }
205}