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,
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))]
73pub struct TimedEvent {
74    /// Event id (`splice_event_id` / emsg `id`).
75    pub id: Option<u32>,
76    /// Abstract meaning.
77    pub kind: EventKind,
78    /// Media-timeline instant; `None` = immediate / determined by insertion point.
79    pub at: Option<MediaTime>,
80    /// Event duration, if known.
81    pub duration: Option<MediaDuration>,
82    /// Lossless original.
83    pub source: SourcePayload,
84}
85
86impl TimedEvent {
87    /// Build from a parsed SCTE-35 section, retaining `raw` verbatim.
88    ///
89    /// Every `pts_time` is shifted by the section's `pts_adjustment` (SCTE 35
90    /// §9.6.1: "the value of `pts_adjustment` shall be added to the
91    /// `pts_time`... modulo 2^33") via [`broadcast_common::clock33::add`]
92    /// before it becomes [`TimedEvent::at`] — the section itself is not
93    /// mutated, only the value this crate derives from it.
94    pub fn from_scte35(section: &SpliceInfoSection, raw: &[u8]) -> Result<Self> {
95        let mut id = None;
96        let mut kind = EventKind::Unspecified;
97        let mut at = None;
98        let mut duration = None;
99
100        let adjust =
101            |pts: u64| MediaTime(broadcast_common::clock33::add(pts, section.pts_adjustment));
102
103        if let Some(clear) = &section.clear {
104            match &clear.command {
105                AnyCommand::SpliceInsert(si) => {
106                    id = Some(si.splice_event_id);
107                    kind = if si.splice_event_cancel_indicator {
108                        // A cancel carries no out_of_network_indicator (§9.7.3);
109                        // it is neither a break start nor a break end.
110                        EventKind::Unspecified
111                    } else if si.out_of_network_indicator {
112                        EventKind::BreakStart
113                    } else {
114                        EventKind::BreakEnd
115                    };
116                    if let Some(st) = &si.splice_time {
117                        at = st.pts_time.map(adjust);
118                    }
119                    if let Some(bd) = &si.break_duration {
120                        duration = Some(MediaDuration(bd.duration));
121                    }
122                }
123                AnyCommand::TimeSignal(ts) => {
124                    at = ts.splice_time.pts_time.map(adjust);
125                    // time_signal() carries no id/kind/duration of its own
126                    // (§9.7.4): those ride in the descriptor loop, almost
127                    // always a segmentation_descriptor (§10.3.3). Take the
128                    // first one, per this crate's documented lossy-collapse
129                    // policy for multi-descriptor loops.
130                    for d in section.descriptors() {
131                        if let Ok(AnySpliceDescriptor::Segmentation(seg)) = d {
132                            if seg.segmentation_event_cancel_indicator {
133                                continue;
134                            }
135                            id = Some(seg.segmentation_event_id);
136                            kind = segmentation_kind(seg.segmentation_type_id);
137                            duration = seg.segmentation_duration.map(MediaDuration);
138                            break;
139                        }
140                    }
141                }
142                _ => {}
143            }
144        }
145
146        Ok(TimedEvent {
147            id,
148            kind,
149            at,
150            duration,
151            source: SourcePayload::Scte35 { raw: raw.to_vec() },
152        })
153    }
154}
155
156/// Classify a `time_signal()` segmentation descriptor's `segmentation_type_id`
157/// (SCTE 35 Table 23) into this crate's abstract [`EventKind`]. Program- and
158/// chapter-boundary types map to [`EventKind::Chapter`]. Only the types that
159/// actually leave (or return to) network programming for ad insertion map to
160/// `BreakStart`/`BreakEnd`: `Break`, Provider/Distributor `Advertisement`,
161/// Provider/Distributor `PlacementOpportunity` (**not** the `Overlay` variants
162/// — an overlay is composited over the network feed, not a break away from
163/// it), and Provider/Distributor `AdBlock`. Everything else — credits, promos,
164/// unscheduled events, alternate content, and every `Overlay` placement
165/// opportunity — is deliberately `Unspecified` rather than `BreakStart`/`End`:
166/// a consumer that splices ads on `BreakStart` must not replace credits/promos
167/// with an ad (`id`/`at`/`duration` are still populated; only `kind` is
168/// unspecified for these). `NetworkStart`/`NetworkEnd` (Table 23 `0x50`/`0x51`)
169/// have the *reversed* sense (a `NetworkStart` marks the return to network
170/// programming, i.e. the end of a break) and are also left `Unspecified`
171/// rather than guessed at; every other/reserved value is `Unspecified` too.
172fn segmentation_kind(type_id: SegmentationTypeId) -> EventKind {
173    use SegmentationTypeId as T;
174    match type_id {
175        T::ProgramStart | T::ProgramEnd | T::ChapterStart | T::ChapterEnd => EventKind::Chapter,
176        T::BreakStart
177        | T::ProviderAdvertisementStart
178        | T::DistributorAdvertisementStart
179        | T::ProviderPlacementOpportunityStart
180        | T::DistributorPlacementOpportunityStart
181        | T::ProviderAdBlockStart
182        | T::DistributorAdBlockStart => EventKind::BreakStart,
183        T::BreakEnd
184        | T::ProviderAdvertisementEnd
185        | T::DistributorAdvertisementEnd
186        | T::ProviderPlacementOpportunityEnd
187        | T::DistributorPlacementOpportunityEnd
188        | T::ProviderAdBlockEnd
189        | T::DistributorAdBlockEnd => EventKind::BreakEnd,
190        _ => EventKind::Unspecified,
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197    use alloc::vec::Vec;
198    use broadcast_common::traits::Parse;
199    use scte35_splice::SpliceInfoSection;
200
201    // Real Unified Streaming splice (ID 2002): out-of-network, break_duration 2160000 (24s).
202    fn splice_2002() -> Vec<u8> {
203        let hex = "FC302100000000000000FFF01005000007D27FEF7F7E0020F580C0000000000088B9661D";
204        (0..hex.len())
205            .step_by(2)
206            .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
207            .collect()
208    }
209
210    #[test]
211    fn from_scte35_extracts_break_start_and_duration() {
212        let raw = splice_2002();
213        let section = SpliceInfoSection::parse(&raw).unwrap();
214        let ev = TimedEvent::from_scte35(&section, &raw).unwrap();
215        assert_eq!(ev.id, Some(2002));
216        assert_eq!(ev.kind, EventKind::BreakStart); // out_of_network = true
217        assert_eq!(ev.at, None); // pts_time None (program splice)
218        assert_eq!(ev.duration, Some(MediaDuration(2_160_000)));
219        assert!((ev.duration.unwrap().as_seconds_f64() - 24.0).abs() < 1e-9);
220        match &ev.source {
221            SourcePayload::Scte35 { raw: r } => assert_eq!(r, &raw), // verbatim, lossless
222            _ => panic!("expected Scte35 payload"),
223        }
224    }
225
226    #[test]
227    fn event_kind_labels() {
228        assert_eq!(EventKind::BreakStart.name(), "break_start");
229        assert_eq!(alloc::format!("{}", EventKind::BreakEnd), "break_end");
230    }
231
232    /// Issue #1040: only the segmentation types that actually leave/return to
233    /// network programming for ad insertion (Table 23's `Break`,
234    /// `*Advertisement`, `*PlacementOpportunity` (non-overlay), `*AdBlock`)
235    /// map to `BreakStart`/`BreakEnd`. Program/Chapter map to `Chapter`.
236    /// Everything else -- including credits, promos, unscheduled/alternate
237    /// content, and the `Overlay` placement-opportunity variants (an overlay
238    /// is composited over the network feed, not a break away from it) -- is
239    /// `Unspecified`, so a consumer that splices ads only on `BreakStart`
240    /// cannot mistake a credit/promo boundary for an ad avail.
241    #[test]
242    fn segmentation_kind_classifies_by_group() {
243        use SegmentationTypeId as T;
244        let cases: &[(SegmentationTypeId, EventKind)] = &[
245            // Program / Chapter -> Chapter.
246            (T::ProgramStart, EventKind::Chapter),
247            (T::ProgramEnd, EventKind::Chapter),
248            (T::ChapterStart, EventKind::Chapter),
249            (T::ChapterEnd, EventKind::Chapter),
250            // The actual "leaves the network" break group -> BreakStart/End.
251            (T::BreakStart, EventKind::BreakStart),
252            (T::BreakEnd, EventKind::BreakEnd),
253            (T::ProviderAdvertisementStart, EventKind::BreakStart),
254            (T::DistributorAdvertisementEnd, EventKind::BreakEnd),
255            (T::ProviderPlacementOpportunityStart, EventKind::BreakStart),
256            (T::DistributorPlacementOpportunityEnd, EventKind::BreakEnd),
257            (T::ProviderAdBlockStart, EventKind::BreakStart),
258            (T::DistributorAdBlockEnd, EventKind::BreakEnd),
259            // Everything else: Unspecified, NOT BreakStart/BreakEnd.
260            (T::OpeningCreditStart, EventKind::Unspecified),
261            (T::ClosingCreditEnd, EventKind::Unspecified),
262            (T::ProviderPromoStart, EventKind::Unspecified),
263            (T::DistributorPromoEnd, EventKind::Unspecified),
264            (T::UnscheduledEventStart, EventKind::Unspecified),
265            (T::AlternateContentOpportunityEnd, EventKind::Unspecified),
266            // Overlay placement opportunities: composited OVER the network
267            // feed, not a break away from it -- must not become BreakStart.
268            (
269                T::ProviderOverlayPlacementOpportunityStart,
270                EventKind::Unspecified,
271            ),
272            (
273                T::DistributorOverlayPlacementOpportunityEnd,
274                EventKind::Unspecified,
275            ),
276            // NetworkStart/End have the reversed sense; also Unspecified.
277            (T::NetworkStart, EventKind::Unspecified),
278            (T::NetworkEnd, EventKind::Unspecified),
279            (T::Reserved(0x60), EventKind::Unspecified),
280        ];
281        for (type_id, want) in cases {
282            assert_eq!(
283                segmentation_kind(*type_id),
284                *want,
285                "segmentation_type_id {type_id:?} ({}) must classify as {want:?}",
286                type_id.name()
287            );
288        }
289    }
290}