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