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