playout_runtime/scte35.rs
1//! SCTE-35 emission points a transition implies (issue
2//! [#748](https://github.com/fishloa/rust-broadcast/issues/748)):
3//! `splice_insert()` — ANSI/SCTE 35 2023r1 §9.7.3, Table 10 — built and
4//! serialized with `scte35-splice`'s own
5//! [`Serialize`](broadcast_common::Serialize), not hand-assembled bytes.
6//!
7//! This module decides *what* cue to emit and *where* (after conditioning);
8//! it does not decide *how the splice lands* against real segment/keyframe
9//! boundaries — that is [`ssai_runtime::splice::condition_splice_point_wrapping`],
10//! reused here rather than re-implemented, per the crate-root docs. Two
11//! implementations of boundary conditioning could disagree about the same
12//! boundary, which is exactly the bug class this workspace keeps finding.
13
14use crate::error::Result;
15use alloc::vec::Vec;
16use scte35_splice::SpliceInfoSection;
17use scte35_splice::commands::AnyCommand;
18use scte35_splice::commands::SpliceInsert;
19use scte35_splice::time::{BreakDuration, SpliceTime};
20pub use ssai_runtime::splice::ConditionedSplicePoint;
21use ssai_runtime::splice::PTS_MODULUS_33;
22
23/// Which edge of an ad break a transition represents.
24///
25/// A [`crate::schedule::Schedule`] alone (Programme/Ad/Slate) does not
26/// disambiguate "ad -> ad" within a multi-spot break from "ad -> programme"
27/// return, so the caller supplies this explicitly rather than this crate
28/// guessing it from entry kinds.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum BreakEdge {
32 /// Entering a break — `out_of_network_indicator = true` (§9.7.3).
33 Enter,
34 /// Returning from a break — `out_of_network_indicator = false`.
35 Return,
36}
37
38impl BreakEdge {
39 /// Stable label.
40 pub fn name(&self) -> &'static str {
41 match self {
42 BreakEdge::Enter => "enter",
43 BreakEdge::Return => "return",
44 }
45 }
46}
47broadcast_common::impl_spec_display!(BreakEdge);
48
49/// Build a `splice_insert()` command for a transition, snapping its target
50/// instant onto the nearest of `candidates` (real segment or keyframe
51/// boundaries) within `max_delta_ticks` of `requested_pts` — see
52/// [`ssai_runtime::splice::condition_splice_point_wrapping`], which this delegates to
53/// rather than duplicating. Errors (via [`crate::Error::SpliceConditioning`])
54/// if no candidate is close enough, or none are supplied: this crate never
55/// emits a cue for a splice point nothing is actually close to.
56///
57/// Distances are measured modulo 2^33 (the width of the SCTE-35 `pts_time`):
58/// `delta_ticks`/`direction` are circular (a cue at `2^33 - 100` snapping to a
59/// boundary at `50` is 150 ticks `After`). The returned
60/// [`ConditionedSplicePoint`] reports `requested_pts` and `snapped_pts` in the
61/// caller's own units (an unwrapped channel clock stays unwrapped).
62///
63/// `break_duration_ticks`, if given, sets `break_duration().duration` with
64/// `auto_return = true` (the splicer returns to the network feed on its own
65/// once the duration elapses — §9.7.3).
66///
67/// # Units (mandatory — PLAY-W1, #1126)
68///
69/// `requested_pts`, every entry of `candidates`, `max_delta_ticks` and
70/// `break_duration_ticks` **must** already be counts of 90 kHz ticks:
71/// `splice_time()`/`break_duration()` are fixed 90 kHz fields (ANSI/SCTE 35
72/// 2023r1 §9.8.1/§9.8.2), and this function passes every one of these values
73/// straight through to [`SpliceTime::with_pts`]/[`BreakDuration`] with no
74/// unit conversion or validation. Passing a channel clock in any other unit
75/// (27 MHz, milliseconds, nanoseconds, …) produces a structurally valid cue
76/// that is silently wrong by that unit's fixed conversion factor. Convert
77/// with `scte35_splice::time::duration_to_ticks` first if the channel clock
78/// isn't already 90 kHz.
79pub fn build_splice_insert(
80 edge: BreakEdge,
81 splice_event_id: u32,
82 requested_pts: u64,
83 candidates: &[u64],
84 max_delta_ticks: u64,
85 break_duration_ticks: Option<u64>,
86) -> Result<(ConditionedSplicePoint, SpliceInsert)> {
87 // `splice_time().pts_time` is a 33-bit field (ANSI/SCTE 35 §9.8.1;
88 // `SpliceTime::with_pts` masks to it), so the instant a cue names — and the
89 // boundary it snaps to — live on the circle of 2^33 ticks, wrapping about
90 // every 26.5 h on a 24/7 channel: a cue just before the wrap whose nearest
91 // real boundary is just after it is 150 ticks away, not ~8.6e9. Reduce
92 // every input onto that circle and measure the circular distance
93 // (ssai-runtime audit r14-SSAI-W2).
94 let reduced: Vec<u64> = candidates.iter().map(|c| c % PTS_MODULUS_33).collect();
95 let mut conditioned = ssai_runtime::splice::condition_splice_point_wrapping(
96 requested_pts % PTS_MODULUS_33,
97 &reduced,
98 max_delta_ticks,
99 PTS_MODULUS_33,
100 )?;
101 // Report in the caller's units: the instant they asked for and the
102 // candidate they supplied (an unwrapped channel clock stays unwrapped),
103 // with the circular delta/direction measured above.
104 if let Some(original) = candidates
105 .iter()
106 .zip(&reduced)
107 .find_map(|(orig, red)| (*red == conditioned.snapped_pts).then_some(*orig))
108 {
109 conditioned.snapped_pts = original;
110 }
111 conditioned.requested_pts = requested_pts;
112 let insert = SpliceInsert {
113 splice_event_id,
114 splice_event_cancel_indicator: false,
115 out_of_network_indicator: matches!(edge, BreakEdge::Enter),
116 program_splice_flag: true,
117 splice_immediate_flag: false,
118 event_id_compliance_flag: true,
119 splice_time: Some(SpliceTime::with_pts(conditioned.snapped_pts)),
120 components: Vec::new(),
121 break_duration: break_duration_ticks.map(|duration| BreakDuration {
122 auto_return: true,
123 duration,
124 }),
125 unique_program_id: 0,
126 avail_num: 0,
127 avails_expected: 0,
128 };
129 Ok((conditioned, insert))
130}
131
132/// Wrap a built [`SpliceInsert`] into a clear (unencrypted)
133/// `splice_info_section()`, ready to serialize
134/// (`broadcast_common::Serialize::to_bytes`) onto the SCTE-35 elementary
135/// stream/PID.
136#[must_use]
137pub fn to_section<'a>(insert: SpliceInsert) -> SpliceInfoSection<'a> {
138 SpliceInfoSection::new_clear(AnyCommand::SpliceInsert(insert), &[])
139}
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144 use broadcast_common::{Parse, Serialize};
145 use ssai_runtime::Error as SsaiError;
146
147 #[test]
148 fn builds_an_enter_break_cue_snapped_to_the_conditioned_point() {
149 let (conditioned, insert) = build_splice_insert(
150 BreakEdge::Enter,
151 7,
152 1_000,
153 &[1_050, 2_000],
154 100,
155 Some(1_800_000),
156 )
157 .unwrap();
158 assert_eq!(conditioned.snapped_pts, 1_050);
159 assert_eq!(insert.splice_event_id, 7);
160 assert!(insert.out_of_network_indicator);
161 assert_eq!(insert.splice_time.unwrap().pts_time, Some(1_050));
162 assert_eq!(insert.break_duration.unwrap().duration, 1_800_000);
163 assert!(insert.break_duration.unwrap().auto_return);
164
165 // The cue must reflect the *conditioned* point, not the raw request
166 // — proves this isn't a passthrough of `requested_pts`.
167 assert_ne!(insert.splice_time.unwrap().pts_time, Some(1_000));
168 }
169
170 #[test]
171 fn builds_a_return_break_cue_with_no_duration() {
172 let (_, insert) =
173 build_splice_insert(BreakEdge::Return, 8, 1_000, &[1_000], 0, None).unwrap();
174 assert!(!insert.out_of_network_indicator);
175 assert!(insert.break_duration.is_none());
176 }
177
178 #[test]
179 fn rejects_a_cue_with_no_boundary_within_tolerance() {
180 let err = build_splice_insert(BreakEdge::Enter, 1, 1_000, &[5_000], 10, None).unwrap_err();
181 match err {
182 crate::Error::SpliceConditioning(SsaiError::NoAlignedBoundary {
183 requested_pts,
184 tolerance_ticks,
185 nearest_delta_ticks,
186 }) => {
187 assert_eq!(requested_pts, 1_000);
188 assert_eq!(tolerance_ticks, 10);
189 assert_eq!(nearest_delta_ticks, 4_000);
190 }
191 other => panic!("expected SpliceConditioning(NoAlignedBoundary), got {other:?}"),
192 }
193 }
194
195 #[test]
196 fn section_round_trips_through_scte35_splices_own_serialize() {
197 let (_, insert) =
198 build_splice_insert(BreakEdge::Enter, 42, 1_000, &[1_000], 0, Some(900_000)).unwrap();
199 let section = to_section(insert);
200 let bytes = section.try_to_bytes().unwrap();
201 assert_eq!(bytes[0], scte35_splice::section::TABLE_ID);
202
203 let parsed = SpliceInfoSection::parse(&bytes).unwrap();
204 match parsed.clear.unwrap().command {
205 AnyCommand::SpliceInsert(reparsed) => {
206 assert_eq!(reparsed.splice_event_id, 42);
207 assert_eq!(reparsed.splice_time.unwrap().pts_time, Some(1_000));
208 assert_eq!(reparsed.break_duration.unwrap().duration, 900_000);
209 }
210 other => panic!("expected SpliceInsert, got {other:?}"),
211 }
212 }
213
214 #[test]
215 fn label_convention() {
216 assert_eq!(BreakEdge::Enter.name(), "enter");
217 assert_eq!(alloc::format!("{}", BreakEdge::Return), "return");
218 }
219
220 /// PLAY-W1 follow-up: the cue's `pts_time` is 33-bit, so a requested
221 /// instant just before the wrap whose nearest real boundary is just after
222 /// it is a 150-tick `After` snap, not an out-of-tolerance miss.
223 #[test]
224 fn a_cue_before_the_33_bit_wrap_snaps_to_a_boundary_after_it() {
225 let requested = PTS_MODULUS_33 - 100;
226 let (conditioned, insert) =
227 build_splice_insert(BreakEdge::Enter, 9, requested, &[50], 1_000, None).unwrap();
228 assert_eq!(conditioned.snapped_pts, 50);
229 assert_eq!(conditioned.delta_ticks, 150);
230 assert_eq!(conditioned.direction, ssai_runtime::SnapDirection::After);
231 assert_eq!(insert.splice_time.unwrap().pts_time, Some(50));
232 // Too tight a tolerance is still refused (circularly measured).
233 assert!(matches!(
234 build_splice_insert(BreakEdge::Enter, 9, requested, &[50], 149, None),
235 Err(crate::Error::SpliceConditioning(
236 SsaiError::NoAlignedBoundary {
237 nearest_delta_ticks: 150,
238 ..
239 }
240 ))
241 ));
242 }
243
244 /// A channel clock already unrolled past 2^33 is reduced onto the
245 /// SCTE-35 circle before conditioning: boundary just before the wrap,
246 /// request just after it, in unwrapped terms.
247 #[test]
248 fn an_unwrapped_channel_clock_is_reduced_to_the_33_bit_circle() {
249 let requested = PTS_MODULUS_33 + 10;
250 let (conditioned, _) = build_splice_insert(
251 BreakEdge::Return,
252 1,
253 requested,
254 &[PTS_MODULUS_33 - 5],
255 1_000,
256 None,
257 )
258 .unwrap();
259 // Reported in the caller's (unwrapped) units.
260 assert_eq!(conditioned.requested_pts, requested);
261 assert_eq!(conditioned.snapped_pts, PTS_MODULUS_33 - 5);
262 assert_eq!(conditioned.delta_ticks, 15);
263 assert_eq!(conditioned.direction, ssai_runtime::SnapDirection::Before);
264 }
265}