Skip to main content

timed_metadata/
event.rs

1//! Canonical timed-metadata event (the hub of the hub-and-spoke model).
2use crate::error::Result;
3use alloc::{string::String, vec::Vec};
4use scte35_splice::{
5    SpliceInfoSection,
6    commands::{AnyCommand, ProgramSplice, SpliceMode},
7    descriptors::{AnySpliceDescriptor, SegmentationTypeId},
8};
9
10/// A media-timeline instant in 90 kHz ticks, wrap-unrolled.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13pub struct MediaTime(pub u64);
14
15/// A duration in 90 kHz ticks.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct MediaDuration(pub u64);
19
20impl MediaDuration {
21    /// The duration in seconds.
22    pub fn as_seconds_f64(self) -> f64 {
23        self.0 as f64 / crate::PTS_HZ as f64
24    }
25}
26
27/// The abstracted meaning of an event, independent of carriage format.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30#[non_exhaustive]
31pub enum EventKind {
32    /// Start of an ad/break opportunity (SCTE-35 out-of-network).
33    BreakStart,
34    /// Return to network (SCTE-35 in-to-network).
35    BreakEnd,
36    /// Chapter / program boundary.
37    Chapter,
38    /// Meaning not determined from the source.
39    Unspecified,
40}
41
42impl EventKind {
43    /// Stable label for this variant.
44    pub fn name(&self) -> &'static str {
45        match self {
46            EventKind::BreakStart => "break_start",
47            EventKind::BreakEnd => "break_end",
48            EventKind::Chapter => "chapter",
49            EventKind::Unspecified => "unspecified",
50        }
51    }
52}
53broadcast_common::impl_spec_display!(EventKind);
54
55/// The lossless original payload, carried verbatim.
56#[derive(Debug, Clone, PartialEq, Eq)]
57#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
58#[non_exhaustive]
59pub enum SourcePayload {
60    /// A SCTE-35 `splice_info_section`, verbatim.
61    Scte35 { raw: Vec<u8> },
62    /// A DASH `emsg`: its scheme/value plus the verbatim `message_data`.
63    Emsg {
64        scheme_id_uri: String,
65        value: String,
66        raw: Vec<u8>,
67    },
68}
69
70/// The canonical event passed between format adapters.
71#[derive(Debug, Clone, PartialEq, Eq)]
72#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
73#[non_exhaustive]
74pub struct TimedEvent {
75    /// Event id (`splice_event_id` / emsg `id`).
76    pub id: Option<u32>,
77    /// Abstract meaning.
78    pub kind: EventKind,
79    /// Media-timeline instant; `None` = immediate / determined by insertion point.
80    pub at: Option<MediaTime>,
81    /// Event duration, if known.
82    pub duration: Option<MediaDuration>,
83    /// Lossless original.
84    pub source: SourcePayload,
85}
86
87impl TimedEvent {
88    /// Build a canonical event from its required meaning and source, leaving
89    /// `id`/`at`/`duration` unset (set them with [`Self::with_id`] /
90    /// [`Self::with_at`] / [`Self::with_duration`] as applicable).
91    #[must_use]
92    pub fn new(kind: EventKind, source: SourcePayload) -> Self {
93        Self {
94            id: None,
95            kind,
96            at: None,
97            duration: None,
98            source,
99        }
100    }
101
102    /// Attach the event id (`splice_event_id` / emsg `id`).
103    #[must_use]
104    pub fn with_id(mut self, id: u32) -> Self {
105        self.id = Some(id);
106        self
107    }
108
109    /// Attach the media-timeline instant.
110    #[must_use]
111    pub fn with_at(mut self, at: MediaTime) -> Self {
112        self.at = Some(at);
113        self
114    }
115
116    /// Attach the event duration.
117    #[must_use]
118    pub fn with_duration(mut self, duration: MediaDuration) -> Self {
119        self.duration = Some(duration);
120        self
121    }
122
123    /// Build from a parsed SCTE-35 section, retaining `raw` verbatim.
124    ///
125    /// Every `pts_time` is shifted by the section's `pts_adjustment` (SCTE 35
126    /// §9.6.1: "the value of `pts_adjustment` shall be added to the
127    /// `pts_time`... modulo 2^33") via [`broadcast_common::clock33::add`]
128    /// before it becomes [`TimedEvent::at`] — the section itself is not
129    /// mutated, only the value this crate derives from it.
130    pub fn from_scte35(section: &SpliceInfoSection, raw: &[u8]) -> Result<Self> {
131        let mut id = None;
132        let mut kind = EventKind::Unspecified;
133        let mut at = None;
134        let mut duration = None;
135
136        let adjust = |pts: broadcast_common::clock33::Clock33| {
137            MediaTime(broadcast_common::clock33::add(
138                pts.ticks(),
139                section.pts_adjustment,
140            ))
141        };
142
143        if let Some(clear) = &section.clear {
144            match &clear.command {
145                AnyCommand::SpliceInsert(si) => {
146                    id = Some(si.splice_event_id);
147                    kind = if si.cancel.is_some() {
148                        // A cancel carries no out_of_network_indicator (§9.7.3);
149                        // it is neither a break start nor a break end.
150                        EventKind::Unspecified
151                    } else if si.out_of_network_indicator {
152                        EventKind::BreakStart
153                    } else {
154                        EventKind::BreakEnd
155                    };
156                    if let SpliceMode::Program(ProgramSplice::At(st)) = &si.mode {
157                        at = st.pts_time.map(adjust);
158                    }
159                    if let Some(bd) = &si.break_duration {
160                        duration = Some(MediaDuration(bd.duration));
161                    }
162                }
163                AnyCommand::TimeSignal(ts) => {
164                    at = ts.splice_time.pts_time.map(adjust);
165                    // time_signal() carries no id/kind/duration of its own
166                    // (§9.7.4): those ride in the descriptor loop, almost
167                    // always a segmentation_descriptor (§10.3.3). Take the
168                    // first one, per this crate's documented lossy-collapse
169                    // policy for multi-descriptor loops.
170                    for d in section.descriptors() {
171                        if let Ok(AnySpliceDescriptor::Segmentation(seg)) = d {
172                            if seg.segmentation_event_cancel_indicator {
173                                continue;
174                            }
175                            id = Some(seg.segmentation_event_id);
176                            kind = segmentation_kind(seg.segmentation_type_id);
177                            duration = seg.segmentation_duration.map(MediaDuration);
178                            break;
179                        }
180                    }
181                }
182                _ => {}
183            }
184        }
185
186        Ok(TimedEvent {
187            id,
188            kind,
189            at,
190            duration,
191            source: SourcePayload::Scte35 { raw: raw.to_vec() },
192        })
193    }
194}
195
196/// Classify a `time_signal()` segmentation descriptor's `segmentation_type_id`
197/// (SCTE 35 Table 23) into this crate's abstract [`EventKind`]. Program- and
198/// chapter-boundary types map to [`EventKind::Chapter`]. Only the types that
199/// actually leave (or return to) network programming for ad insertion map to
200/// `BreakStart`/`BreakEnd`: `Break`, Provider/Distributor `Advertisement`,
201/// Provider/Distributor `PlacementOpportunity` (**not** the `Overlay` variants
202/// — an overlay is composited over the network feed, not a break away from
203/// it), and Provider/Distributor `AdBlock`. Everything else — credits, promos,
204/// unscheduled events, alternate content, and every `Overlay` placement
205/// opportunity — is deliberately `Unspecified` rather than `BreakStart`/`End`:
206/// a consumer that splices ads on `BreakStart` must not replace credits/promos
207/// with an ad (`id`/`at`/`duration` are still populated; only `kind` is
208/// unspecified for these). `NetworkStart`/`NetworkEnd` (Table 23 `0x50`/`0x51`)
209/// have the *reversed* sense (a `NetworkStart` marks the return to network
210/// programming, i.e. the end of a break) and are also left `Unspecified`
211/// rather than guessed at; every other/reserved value is `Unspecified` too.
212fn segmentation_kind(type_id: SegmentationTypeId) -> EventKind {
213    use SegmentationTypeId as T;
214    match type_id {
215        T::ProgramStart | T::ProgramEnd | T::ChapterStart | T::ChapterEnd => EventKind::Chapter,
216        T::BreakStart
217        | T::ProviderAdvertisementStart
218        | T::DistributorAdvertisementStart
219        | T::ProviderPlacementOpportunityStart
220        | T::DistributorPlacementOpportunityStart
221        | T::ProviderAdBlockStart
222        | T::DistributorAdBlockStart => EventKind::BreakStart,
223        T::BreakEnd
224        | T::ProviderAdvertisementEnd
225        | T::DistributorAdvertisementEnd
226        | T::ProviderPlacementOpportunityEnd
227        | T::DistributorPlacementOpportunityEnd
228        | T::ProviderAdBlockEnd
229        | T::DistributorAdBlockEnd => EventKind::BreakEnd,
230        _ => EventKind::Unspecified,
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237    use alloc::vec::Vec;
238    use broadcast_common::traits::Parse;
239    use scte35_splice::SpliceInfoSection;
240
241    // Real Unified Streaming splice (ID 2002): out-of-network, break_duration 2160000 (24s).
242    fn splice_2002() -> Vec<u8> {
243        test_fixtures::read("scte35/splice-insert-2002.bin")
244    }
245
246    #[test]
247    fn from_scte35_extracts_break_start_and_duration() {
248        let raw = splice_2002();
249        let section = SpliceInfoSection::parse(&raw).unwrap();
250        let ev = TimedEvent::from_scte35(&section, &raw).unwrap();
251        assert_eq!(ev.id, Some(2002));
252        assert_eq!(ev.kind, EventKind::BreakStart); // out_of_network = true
253        assert_eq!(ev.at, None); // pts_time None (program splice)
254        assert_eq!(ev.duration, Some(MediaDuration(2_160_000)));
255        assert!((ev.duration.unwrap().as_seconds_f64() - 24.0).abs() < 1e-9);
256        match &ev.source {
257            SourcePayload::Scte35 { raw: r } => assert_eq!(r, &raw), // verbatim, lossless
258            _ => panic!("expected Scte35 payload"),
259        }
260    }
261
262    #[test]
263    fn event_kind_labels() {
264        assert_eq!(EventKind::BreakStart.name(), "break_start");
265        assert_eq!(alloc::format!("{}", EventKind::BreakEnd), "break_end");
266    }
267
268    /// Issue #1040: only the segmentation types that actually leave/return to
269    /// network programming for ad insertion (Table 23's `Break`,
270    /// `*Advertisement`, `*PlacementOpportunity` (non-overlay), `*AdBlock`)
271    /// map to `BreakStart`/`BreakEnd`. Program/Chapter map to `Chapter`.
272    /// Everything else -- including credits, promos, unscheduled/alternate
273    /// content, and the `Overlay` placement-opportunity variants (an overlay
274    /// is composited over the network feed, not a break away from it) -- is
275    /// `Unspecified`, so a consumer that splices ads only on `BreakStart`
276    /// cannot mistake a credit/promo boundary for an ad avail.
277    #[test]
278    fn segmentation_kind_classifies_by_group() {
279        use SegmentationTypeId as T;
280        let cases: &[(SegmentationTypeId, EventKind)] = &[
281            // Program / Chapter -> Chapter.
282            (T::ProgramStart, EventKind::Chapter),
283            (T::ProgramEnd, EventKind::Chapter),
284            (T::ChapterStart, EventKind::Chapter),
285            (T::ChapterEnd, EventKind::Chapter),
286            // The actual "leaves the network" break group -> BreakStart/End.
287            (T::BreakStart, EventKind::BreakStart),
288            (T::BreakEnd, EventKind::BreakEnd),
289            (T::ProviderAdvertisementStart, EventKind::BreakStart),
290            (T::DistributorAdvertisementEnd, EventKind::BreakEnd),
291            (T::ProviderPlacementOpportunityStart, EventKind::BreakStart),
292            (T::DistributorPlacementOpportunityEnd, EventKind::BreakEnd),
293            (T::ProviderAdBlockStart, EventKind::BreakStart),
294            (T::DistributorAdBlockEnd, EventKind::BreakEnd),
295            // Everything else: Unspecified, NOT BreakStart/BreakEnd.
296            (T::OpeningCreditStart, EventKind::Unspecified),
297            (T::ClosingCreditEnd, EventKind::Unspecified),
298            (T::ProviderPromoStart, EventKind::Unspecified),
299            (T::DistributorPromoEnd, EventKind::Unspecified),
300            (T::UnscheduledEventStart, EventKind::Unspecified),
301            (T::AlternateContentOpportunityEnd, EventKind::Unspecified),
302            // Overlay placement opportunities: composited OVER the network
303            // feed, not a break away from it -- must not become BreakStart.
304            (
305                T::ProviderOverlayPlacementOpportunityStart,
306                EventKind::Unspecified,
307            ),
308            (
309                T::DistributorOverlayPlacementOpportunityEnd,
310                EventKind::Unspecified,
311            ),
312            // NetworkStart/End have the reversed sense; also Unspecified.
313            (T::NetworkStart, EventKind::Unspecified),
314            (T::NetworkEnd, EventKind::Unspecified),
315            (T::Reserved(0x60), EventKind::Unspecified),
316        ];
317        for (type_id, want) in cases {
318            assert_eq!(
319                segmentation_kind(*type_id),
320                *want,
321                "segmentation_type_id {type_id:?} ({}) must classify as {want:?}",
322                type_id.name()
323            );
324        }
325    }
326}