Skip to main content

timed_metadata/
timeline.rs

1//! Stateful conversion session: holds the wall-clock anchor and unrolls 33-bit
2//! PTS wrap across a stream of events.
3use crate::anchor::TimeAnchor;
4use crate::convert::{EmsgConfig, scte35_to_daterange, scte35_to_emsg};
5use crate::daterange::DateRange;
6use crate::error::{Error, Result};
7use crate::event::{MediaTime, TimedEvent};
8use alloc::vec::Vec;
9use broadcast_common::traits::Parse;
10use scte35_splice::SpliceInfoSection;
11
12/// The 33-bit PTS modulus.
13pub const PTS_WRAP: u64 = broadcast_common::clock33::WRAP_33BIT;
14
15/// A stateful conversion session.
16#[derive(Debug, Default)]
17pub struct Timeline {
18    anchor: Option<TimeAnchor>,
19    unroller: PtsUnroller,
20}
21
22impl Timeline {
23    /// New session with no anchor.
24    pub fn new() -> Self {
25        Self::default()
26    }
27    /// New session with a wall-clock anchor.
28    pub fn with_anchor(anchor: TimeAnchor) -> Self {
29        Timeline {
30            anchor: Some(anchor),
31            unroller: PtsUnroller::seeded(anchor.pts_90k),
32        }
33    }
34
35    /// Set or replace the wall-clock anchor, keeping the PTS unroll state of the
36    /// events already pushed.
37    pub fn set_anchor(&mut self, anchor: TimeAnchor) {
38        if self.unroller.state.is_none() {
39            self.unroller = PtsUnroller::seeded(anchor.pts_90k);
40        }
41        self.anchor = Some(anchor);
42    }
43
44    /// Parse a SCTE-35 section; unroll its PTS into an absolute [`MediaTime`].
45    pub fn push_scte35(&mut self, bytes: &[u8]) -> Result<TimedEvent> {
46        let section = SpliceInfoSection::parse(bytes)?;
47        let mut ev = TimedEvent::from_scte35(&section, bytes)?;
48        if let Some(MediaTime(pts33)) = ev.at {
49            let abs = self.unroller.unroll(pts33);
50            ev.at = Some(MediaTime(abs));
51        }
52        Ok(ev)
53    }
54
55    /// Convert to a DATERANGE (requires an anchor).
56    pub fn to_daterange(&self, ev: &TimedEvent) -> Result<DateRange> {
57        let anchor = self.anchor.as_ref().ok_or(Error::MissingAnchor)?;
58        scte35_to_daterange(ev, anchor)
59    }
60
61    /// Convert to a serialized SCTE-35 `emsg` box.
62    pub fn to_emsg(&self, ev: &TimedEvent, cfg: &EmsgConfig) -> Result<Vec<u8>> {
63        match &ev.source {
64            crate::event::SourcePayload::Scte35 { raw } => scte35_to_emsg(raw, cfg),
65            crate::event::SourcePayload::Emsg { .. } => Err(Error::AttrParse(
66                alloc::string::String::from("event is not SCTE-35-sourced"),
67            )),
68        }
69    }
70}
71
72/// Per-signal 33-bit PTS unroller: turns a repeating 90 kHz wire counter into
73/// an absolute, ever-growing tick value.
74///
75/// Thin stateful wrapper around
76/// [`broadcast_common::clock33::unwrap_delta`] — the actual wrap-correction
77/// math lives there (shared with `transmux`'s demux-edge unroller and
78/// `media-doctor`/`compliance-probe`'s wrap-aware comparisons), so a fix
79/// there reaches every 33-bit clock consumer in the workspace instead of
80/// just this one. Used both by [`Timeline`] and by the caption diff-based
81/// boundary tracker (`crate::webvtt::cue::DiffState`) — a second reason not
82/// to hand-roll the (raw, epoch) bookkeeping a third time.
83///
84/// SCTE-35 cues and caption commit events never legitimately reorder across
85/// the 33-bit origin before any sample has been observed (there is no prior
86/// sample to wrap from), so `unroll` never sees a negative accumulator in
87/// practice; the `max(0)` below is a defensive clamp against malformed input
88/// rather than a real code path.
89#[derive(Debug, Default)]
90pub(crate) struct PtsUnroller {
91    /// `(previous raw 33-bit value, previous unwrapped accumulator)`.
92    state: Option<(u64, i128)>,
93}
94
95impl PtsUnroller {
96    pub(crate) fn seeded(origin: u64) -> Self {
97        PtsUnroller {
98            state: Some((origin % PTS_WRAP, i128::from(origin))),
99        }
100    }
101
102    pub(crate) fn unroll(&mut self, raw33: u64) -> u64 {
103        let unwrapped = match self.state {
104            Some((prev_raw, prev_unwrapped)) => {
105                broadcast_common::clock33::unwrap_delta(prev_unwrapped, prev_raw, raw33)
106            }
107            None => raw33 as i128,
108        };
109        self.state = Some((raw33, unwrapped));
110        unwrapped.max(0) as u64
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn a_cue_just_before_the_origin_clamps_to_the_origin() {
120        let mut u = PtsUnroller::seeded(0);
121        assert_eq!(u.unroll(PTS_WRAP - 90_000), 0);
122    }
123
124    fn splice_2002() -> alloc::vec::Vec<u8> {
125        test_fixtures::read("scte35/splice-insert-2002.bin")
126    }
127
128    #[test]
129    fn push_scte35_returns_event() {
130        let mut tl = Timeline::new();
131        let ev = tl.push_scte35(&splice_2002()).unwrap();
132        assert_eq!(ev.id, Some(2002));
133    }
134
135    #[test]
136    fn to_daterange_without_anchor_errors() {
137        let tl = Timeline::new();
138        let ev = Timeline::new().push_scte35(&splice_2002()).unwrap();
139        assert!(matches!(
140            tl.to_daterange(&ev),
141            Err(crate::Error::MissingAnchor)
142        ));
143    }
144
145    #[test]
146    fn set_anchor_adds_and_replaces_the_anchor_like_with_anchor() {
147        let first = TimeAnchor {
148            pts_90k: 0,
149            utc_epoch_ms: 1_700_000_000_000,
150        };
151        let second = TimeAnchor {
152            pts_90k: 0,
153            utc_epoch_ms: 1_800_000_000_000,
154        };
155        let mut tl = Timeline::new();
156        let ev = tl.push_scte35(&splice_2002()).unwrap();
157        assert!(matches!(
158            tl.to_daterange(&ev),
159            Err(crate::Error::MissingAnchor)
160        ));
161
162        tl.set_anchor(first);
163        let anchored = tl.to_daterange(&ev).unwrap();
164        let expected = Timeline::with_anchor(first).to_daterange(&ev).unwrap();
165        assert_eq!(anchored.start_date, expected.start_date);
166
167        tl.set_anchor(second);
168        let replaced = tl.to_daterange(&ev).unwrap();
169        assert_eq!(
170            replaced.start_date,
171            Timeline::with_anchor(second)
172                .to_daterange(&ev)
173                .unwrap()
174                .start_date
175        );
176        assert_ne!(replaced.start_date, anchored.start_date);
177    }
178
179    #[test]
180    fn wrap_unroll_adds_one_epoch() {
181        // A near-max previous value then a small next value crosses one wrap.
182        let mut u = PtsUnroller {
183            state: Some(((1u64 << 33) - 10, ((1u64 << 33) - 10) as i128)),
184        };
185        assert_eq!(u.unroll(5), 5 + (1u64 << 33));
186    }
187
188    #[test]
189    fn wrap_unroll_forward_delta_keeps_epoch() {
190        // A normal forward delta within range must NOT bump the epoch.
191        let mut u = PtsUnroller {
192            state: Some((1_000, 1_000)),
193        };
194        assert_eq!(u.unroll(2_000), 2_000);
195        // First call (no prior pts) returns the raw value.
196        let mut u2 = PtsUnroller::default();
197        assert_eq!(u2.unroll(42), 42);
198    }
199
200    /// MUTATION VERIFIED: the previous `unroll_pts` (a forward-only epoch
201    /// counter) could not distinguish a small backward reorder that
202    /// straddles the wrap origin from a huge forward jump — see
203    /// `broadcast_common::clock33::unwrap_delta`'s doc comment for the exact
204    /// case. Reproduced here at the `PtsUnroller` level: a splice/caption
205    /// event at raw tick `2`, then one at raw tick `2^33 - 3` (a legitimate
206    /// 5-tick backward step across the origin), must unroll to a small
207    /// value, not to `~2^33`.
208    #[test]
209    fn wrap_unroll_backward_reorder_across_origin_does_not_leap_forward() {
210        let mut u = PtsUnroller::default();
211        assert_eq!(u.unroll(2), 2);
212        let second = u.unroll((1u64 << 33) - 3);
213        assert!(
214            second < 1000,
215            "expected a small value from a 5-tick backward reorder, got {second}"
216        );
217    }
218}