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