Skip to main content

ssai_runtime/
splice.rs

1//! Splice-point conditioning: aligning a SCTE-35 cue's target presentation
2//! time (`splice_time().pts_time`, ANSI/SCTE 35 2023r1 §9.8.1, or a DASH
3//! `emsg`'s `presentation_time`) against the primary content's actual
4//! segment/keyframe boundaries.
5//!
6//! Real cues are frequently **not** IDR-aligned. `fixtures/scte35/PROVENANCE.md`
7//! documents a genuine DASH-IF `livesim2` capture whose nearest video
8//! keyframe lands 6000 ticks (67 ms) *after* the cue's nominal presentation
9//! time at the shared 90 kHz clock — see `ssai-runtime/examples/condition_real_cue.rs`,
10//! which reproduces that exact measurement through this module rather than
11//! asserting it. [`condition_splice_point`] measures that offset instead of
12//! assuming it away, so a caller (the playlist renderer, or a transmux-side
13//! splicer) can make an informed choice: snap to the actual boundary and
14//! accept the drift, or reject the cue as un-splice-able when nothing is
15//! close enough.
16//!
17//! Every instant here is a [`Clock33`] — a validated 90 kHz PTS/`pts_time`
18//! sample on the 33-bit circle (ISO/IEC 13818-1 §2.4.3.7 `PTS[32..0]`,
19//! ANSI/SCTE 35 2023r1 §9.8.1), which wraps about every 26.5 h — and the
20//! arithmetic goes through `broadcast_common::clock33`, so there is exactly
21//! one conditioning algorithm and it measures across the wrap. A linear twin
22//! beside it was tried and dropped (audit 19, issue #2726): a caller picking
23//! it measured a cue just before the wrap against a boundary just after it
24//! as ~8.6 × 10⁹ ticks away and dropped the break. This module does not
25//! decode SCTE-35 or emsg (that's `scte35-splice` / `mp4-emsg`'s job).
26
27use broadcast_common::clock33::{Clock33, WRAP_33BIT};
28use broadcast_common::timescale::{self, Rounding, Timescale};
29use core::time::Duration;
30
31use crate::error::{Error, Result};
32
33/// The 90 kHz clock PTS/DTS and a SCTE-35 `pts_time` are sampled into
34/// (ISO/IEC 13818-1 §2.4.3.7; ANSI/SCTE 35 2023r1 §9.8.1): the unit of every
35/// [`Clock33`] in this module's API and of a tolerance [`Duration`].
36const PTS_TIMESCALE: Timescale = broadcast_common::clock33::PTS_TIMESCALE;
37
38/// Where the chosen boundary landed relative to the requested instant.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum SnapDirection {
42    /// The candidate matches the requested instant exactly.
43    Exact,
44    /// The candidate is before the requested instant.
45    Before,
46    /// The candidate is after the requested instant — the common case for a
47    /// real, non-IDR-aligned cue (see the module docs).
48    After,
49}
50
51impl SnapDirection {
52    /// Stable label.
53    pub fn name(&self) -> &'static str {
54        match self {
55            SnapDirection::Exact => "exact",
56            SnapDirection::Before => "before",
57            SnapDirection::After => "after",
58        }
59    }
60}
61broadcast_common::impl_spec_display!(SnapDirection);
62
63/// The result of conditioning one splice point against a set of candidate
64/// boundaries (segment starts, or sync-sample/IDR timestamps).
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct ConditionedSplicePoint {
67    /// The cue's nominal target.
68    pub requested_pts: Clock33,
69    /// The nearest candidate boundary actually chosen.
70    pub snapped_pts: Clock33,
71    /// The circular distance from `requested_pts` to `snapped_pts`, in 90 kHz
72    /// ticks — at most `2^32` (half the circle).
73    pub delta_ticks: u64,
74    /// Whether the snap landed before, after, or exactly on the request.
75    pub direction: SnapDirection,
76}
77
78impl ConditionedSplicePoint {
79    /// Whether the snap was exact (no drift at all).
80    pub fn is_exact(&self) -> bool {
81        self.delta_ticks == 0
82    }
83}
84
85/// The tolerance `max_delta` in 90 kHz ticks, rounded up: a tolerance the
86/// caller expressed `Floor`-ed down could reject a boundary that is exactly
87/// at their stated drift.
88fn tolerance_ticks(max_delta: Duration) -> u64 {
89    let nanos = i128::try_from(max_delta.as_nanos()).unwrap_or(i128::MAX);
90    let ticks = timescale::rescale(nanos, Timescale::NANOS, PTS_TIMESCALE, Rounding::Ceil);
91    u64::try_from(ticks).unwrap_or(u64::MAX)
92}
93
94/// Find the candidate boundary nearest `requested_pts`, and error out if the
95/// nearest one is farther than `max_delta` away — the caller decides how
96/// much drift is tolerable (a live low-latency splice may need a tight
97/// bound; a VOD ad break can tolerate a full GOP).
98///
99/// Every instant is a 90 kHz 33-bit PTS/`pts_time`, and distances and the
100/// snap direction are measured on that circle (issue #1125 / audit
101/// r14-SSAI-W2): a cue at `2^33 - 100` whose nearest real boundary is at
102/// `50` (just after the wrap, about every 26.5 h on a 24/7 channel) is 150
103/// ticks [`SnapDirection::After`], where a linear measure finds ~8.6 × 10⁹
104/// ticks and drops the break. The shorter way round wins; on an exact
105/// half-circle tie the forward ([`SnapDirection::After`]) way is taken.
106/// [`ConditionedSplicePoint::delta_ticks`] is that circular distance.
107///
108/// `candidates` need not be sorted; every entry is checked, and the result
109/// does not depend on slice order. The candidate sets this crate is used
110/// with (segment or sync-sample boundaries within one GOP of the cue) are
111/// small enough that a linear scan is the right tool: no allocation, no
112/// requirement that the caller maintain sorted order.
113///
114/// Returns [`Error::NoCandidates`] if `candidates` is empty, and
115/// [`Error::NoAlignedBoundary`] if the nearest candidate exceeds
116/// `max_delta` — conditioning never silently accepts a splice point nothing
117/// is actually close to.
118pub fn condition_splice_point(
119    requested_pts: Clock33,
120    candidates: &[Clock33],
121    max_delta: Duration,
122) -> Result<ConditionedSplicePoint> {
123    let r = u128::from(requested_pts.ticks());
124    let modulus = u128::from(WRAP_33BIT);
125    let tolerance_ticks = tolerance_ticks(max_delta);
126    // (candidate, circular delta, forward?)
127    let mut nearest: Option<(Clock33, u64, bool)> = None;
128    for &candidate in candidates {
129        let c = u128::from(candidate.ticks());
130        let forward = (c + modulus - r) % modulus;
131        let backward = (r + modulus - c) % modulus;
132        let (delta, is_forward) = if forward <= backward {
133            (forward, true)
134        } else {
135            (backward, false)
136        };
137        // Both are below the modulus, so the shorter leg fits a u64.
138        let delta = u64::try_from(delta).unwrap_or(u64::MAX);
139        // Equidistant candidates: prefer the one after the request (a splice
140        // is cut at or after the cue, never before it, when there is a
141        // choice) — so the result does not depend on slice order.
142        if nearest.is_none_or(|(_, best, best_forward)| {
143            delta < best || (delta == best && is_forward && !best_forward)
144        }) {
145            nearest = Some((candidate, delta, is_forward));
146        }
147    }
148    let (snapped_pts, delta_ticks, is_forward) = nearest.ok_or(Error::NoCandidates)?;
149    if delta_ticks > tolerance_ticks {
150        return Err(Error::NoAlignedBoundary {
151            requested_pts: requested_pts.ticks(),
152            tolerance_ticks,
153            nearest_delta_ticks: delta_ticks,
154        });
155    }
156    let direction = if delta_ticks == 0 {
157        SnapDirection::Exact
158    } else if is_forward {
159        SnapDirection::After
160    } else {
161        SnapDirection::Before
162    };
163    Ok(ConditionedSplicePoint {
164        requested_pts,
165        snapped_pts,
166        delta_ticks,
167        direction,
168    })
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    const fn pts(ticks: u64) -> Clock33 {
176        match Clock33::try_new(ticks) {
177            Ok(c) => c,
178            Err(_) => Clock33::ZERO,
179        }
180    }
181
182    /// A tolerance of `ticks` 90 kHz ticks. Exact: `ticks * 10^9` is divisible
183    /// by 90 000 for every `ticks` the tests use.
184    fn ticks(n: u64) -> Duration {
185        Duration::from_nanos(n * 1_000_000_000 / 90_000)
186    }
187
188    /// The 33-bit modulus, for expressing "just before the wrap".
189    const WRAP: u64 = broadcast_common::clock33::WRAP_33BIT;
190
191    #[test]
192    fn snaps_to_nearest_candidate() {
193        let result =
194            condition_splice_point(pts(1_000), &[pts(500), pts(1_050), pts(2_000)], ticks(100))
195                .unwrap();
196        assert_eq!(result.snapped_pts, pts(1_050));
197        assert_eq!(result.delta_ticks, 50);
198        assert_eq!(result.direction, SnapDirection::After);
199        assert!(!result.is_exact());
200    }
201
202    #[test]
203    fn exact_match_reports_zero_delta() {
204        let result = condition_splice_point(pts(1_000), &[pts(1_000)], Duration::ZERO).unwrap();
205        assert_eq!(result.delta_ticks, 0);
206        assert_eq!(result.direction, SnapDirection::Exact);
207        assert!(result.is_exact());
208    }
209
210    #[test]
211    fn before_direction_when_candidate_precedes_request() {
212        let result = condition_splice_point(pts(1_000), &[pts(900)], ticks(200)).unwrap();
213        assert_eq!(result.snapped_pts, pts(900));
214        assert_eq!(result.direction, SnapDirection::Before);
215    }
216
217    #[test]
218    fn rejects_a_candidate_outside_tolerance() {
219        let err = condition_splice_point(pts(1_000), &[pts(2_000)], ticks(500)).unwrap_err();
220        match err {
221            Error::NoAlignedBoundary {
222                requested_pts,
223                tolerance_ticks,
224                nearest_delta_ticks,
225            } => {
226                assert_eq!(requested_pts, 1_000);
227                assert_eq!(tolerance_ticks, 500);
228                assert_eq!(nearest_delta_ticks, 1_000);
229            }
230            other => panic!("expected NoAlignedBoundary, got {other:?}"),
231        }
232    }
233
234    #[test]
235    fn rejects_empty_candidates() {
236        let err = condition_splice_point(pts(1_000), &[], ticks(500)).unwrap_err();
237        assert!(matches!(err, Error::NoCandidates));
238    }
239
240    /// Audit r14-SSAI-W2: cue just before the 33-bit wrap, boundary just after
241    /// it. There is one conditioning algorithm and it reports the true 150-tick
242    /// forward distance rather than dropping the break (audit 19, issue #2726:
243    /// the linear twin that used to sit beside it failed exactly here).
244    #[test]
245    fn snaps_across_the_33_bit_boundary() {
246        let cue = pts(WRAP - 100);
247        let r = condition_splice_point(cue, &[pts(50)], ticks(1_000)).unwrap();
248        assert_eq!(r.snapped_pts, pts(50));
249        assert_eq!(r.delta_ticks, 150);
250        assert_eq!(r.direction, SnapDirection::After);
251    }
252
253    #[test]
254    fn direction_before_across_the_wrap() {
255        let r = condition_splice_point(pts(50), &[pts(WRAP - 100)], ticks(1_000)).unwrap();
256        assert_eq!(r.delta_ticks, 150);
257        assert_eq!(r.direction, SnapDirection::Before);
258    }
259
260    #[test]
261    fn picks_nearest_among_both_sides_of_the_wrap() {
262        let cue = pts(WRAP - 100);
263        let r = condition_splice_point(cue, &[pts(WRAP - 500), pts(90), pts(4_000)], ticks(10_000))
264            .unwrap();
265        assert_eq!(r.snapped_pts, pts(90));
266        assert_eq!(r.delta_ticks, 190);
267        let r = condition_splice_point(cue, &[pts(WRAP - 150), pts(90)], ticks(10_000)).unwrap();
268        assert_eq!(r.snapped_pts, pts(WRAP - 150));
269        assert_eq!(r.delta_ticks, 50);
270        assert_eq!(r.direction, SnapDirection::Before);
271    }
272
273    #[test]
274    fn exact_and_tolerance_and_tie() {
275        let r = condition_splice_point(pts(7), &[pts(7)], Duration::ZERO).unwrap();
276        assert_eq!(r.direction, SnapDirection::Exact);
277        assert!(r.is_exact());
278        let err = condition_splice_point(pts(WRAP - 100), &[pts(50)], ticks(149)).unwrap_err();
279        assert!(matches!(
280            err,
281            Error::NoAlignedBoundary {
282                nearest_delta_ticks: 150,
283                tolerance_ticks: 149,
284                ..
285            }
286        ));
287        let r = condition_splice_point(Clock33::ZERO, &[pts(5)], ticks(5)).unwrap();
288        assert_eq!((r.delta_ticks, r.direction), (5, SnapDirection::After));
289    }
290
291    /// A tolerance is a `Duration` on the 90 kHz clock, rounded up: a fraction of
292    /// a tick is still a tick of tolerance, and a value too large for the clock
293    /// simply accepts any candidate.
294    #[test]
295    fn a_duration_tolerance_is_converted_to_ticks() {
296        // One nanosecond is ~10^-5 of a 90 kHz tick: rounded up, it is one tick
297        // of tolerance, and rounded down it would be zero (and reject a 1-tick
298        // drift).
299        let r = condition_splice_point(pts(1_000), &[pts(1_001)], Duration::from_nanos(1)).unwrap();
300        assert_eq!(r.delta_ticks, 1);
301        // The shorter way round the circle from 1000 to just before the wrap
302        // is backwards, 1100 ticks.
303        let r = condition_splice_point(pts(1_000), &[pts(WRAP - 100)], Duration::MAX).unwrap();
304        assert_eq!(r.delta_ticks, 1_100);
305        assert_eq!(r.direction, SnapDirection::Before);
306    }
307
308    /// Two candidates equally far either side of the cue: `After` wins, in
309    /// either slice order.
310    #[test]
311    fn an_equidistant_tie_prefers_after_regardless_of_order() {
312        for candidates in [[pts(900), pts(1_100)], [pts(1_100), pts(900)]] {
313            let r = condition_splice_point(pts(1_000), &candidates, ticks(200)).unwrap();
314            assert_eq!(
315                (r.snapped_pts, r.direction),
316                (pts(1_100), SnapDirection::After)
317            );
318        }
319        // Across the wrap: 100 ticks either side of 0.
320        for candidates in [[pts(WRAP - 100), pts(100)], [pts(100), pts(WRAP - 100)]] {
321            let r = condition_splice_point(Clock33::ZERO, &candidates, ticks(200)).unwrap();
322            assert_eq!(
323                (r.snapped_pts, r.direction),
324                (pts(100), SnapDirection::After)
325            );
326        }
327    }
328
329    #[test]
330    fn direction_labels() {
331        assert_eq!(SnapDirection::Exact.name(), "exact");
332        assert_eq!(alloc::format!("{}", SnapDirection::After), "after");
333    }
334}