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