Skip to main content

timed_metadata/convert/
emsg.rs

1//! SCTE-35 ↔ DASH `emsg` conversion (scheme `urn:scte:scte35:2013:bin`).
2//!
3//! Carriage is **ANSI/SCTE 214-1:2024 §7.7.3**
4//! (`private/specs-verified/scte/dash/scte-214-1-2024.md`): version 1, the
5//! whole `splice_info_section` in `message_data`, and `0xFFFFFFFF` for an
6//! unknown duration. The older 214-3 §8.3.3 transcription only carried the
7//! scheme identity; the rules now live in 214-1 2024. (The MPD `EventStream`
8//! form, `urn:scte:scte35:2014:xml+bin`, is 214-1 2024 §7.7.2.1.)
9use crate::error::{Error, Result};
10use alloc::{string::String, vec::Vec};
11use broadcast_core::timescale::Timescale;
12use isobmff::emsg::{EmsgBox, PresentationTime};
13
14/// The SCTE-35 binary carriage scheme for inband DASH `emsg`
15/// (ANSI/SCTE 214-1:2024 §7.7.3(1)).
16pub const SCTE35_SCHEME: &str = "urn:scte:scte35:2013:bin";
17
18/// The `event_duration` wire value meaning "not known" (214-1 2024 §7.7.3(4)).
19pub const UNKNOWN_EVENT_DURATION: u32 = 0xFFFF_FFFF;
20
21/// The largest expressible known duration, one below [`UNKNOWN_EVENT_DURATION`].
22pub const MAX_KNOWN_EVENT_DURATION: u32 = UNKNOWN_EVENT_DURATION - 1;
23
24/// Parameters for emitting a SCTE-35-carrying `emsg`.
25#[derive(Debug, Clone)]
26#[non_exhaustive]
27pub struct EmsgConfig {
28    /// `timescale` (ticks/second) for the emsg time fields.
29    pub timescale: Timescale,
30    /// `presentation_time` relative to PeriodStart adjusted by
31    /// `@presentationTimeOffset` (214-1 2024 §7.7.3(3)); version 1 only.
32    pub presentation: PresentationTime,
33    /// `event_duration` in `timescale` units (`None` = not known, written as
34    /// [`UNKNOWN_EVENT_DURATION`]; 214-1 2024 §7.7.3(4)).
35    pub event_duration: Option<u32>,
36    /// `value` — the SCTE 35 PID or a URI (214-1 2024 §7.7.3(5)).
37    pub value: String,
38    /// `id` — unique within the Period (214-1 2024 §7.7.3(6)).
39    pub id: u32,
40}
41
42impl EmsgConfig {
43    /// Build the emsg parameters from their required values.
44    #[must_use]
45    pub fn new(
46        timescale: Timescale,
47        presentation: PresentationTime,
48        event_duration: Option<u32>,
49        value: String,
50        id: u32,
51    ) -> Self {
52        Self {
53            timescale,
54            presentation,
55            event_duration,
56            value,
57            id,
58        }
59    }
60}
61
62/// Wrap a verbatim `splice_info_section` as a SCTE-35 `emsg` box (serialized bytes).
63///
64/// The box is version 1: `presentation` is `presentation_time` relative to
65/// PeriodStart adjusted by `@presentationTimeOffset` (214-1 2024 §7.7.3(3));
66/// version 0 shall not be used (§7.7.1(2)).
67pub fn scte35_to_emsg(splice_raw: &[u8], cfg: &EmsgConfig) -> Result<Vec<u8>> {
68    let PresentationTime::Absolute(presentation_time) = cfg.presentation else {
69        return Err(Error::Scte35EmsgVersionZero);
70    };
71    let boxx = EmsgBox {
72        flags: isobmff::emsg::EMSG_FLAGS,
73        scheme_id_uri: SCTE35_SCHEME,
74        value: &cfg.value,
75        timescale: Some(cfg.timescale),
76        presentation_time: PresentationTime::Absolute(presentation_time),
77        event_duration: cfg.event_duration.unwrap_or(UNKNOWN_EVENT_DURATION),
78        id: cfg.id,
79        message_data: splice_raw,
80    };
81    Ok(boxx.to_vec()?)
82}
83
84/// Read a SCTE-35 `emsg`'s `event_duration`: `None` for the "not known" wire
85/// value `0xFFFFFFFF` (214-1 2024 §7.7.3(4)), `Some(ticks)` otherwise.
86pub fn scte35_event_duration(emsg_bytes: &[u8]) -> Result<Option<u32>> {
87    let boxx = EmsgBox::parse(emsg_bytes)?;
88    if !boxx.is_scte35() {
89        return Err(Error::UnsupportedScheme {
90            scheme: String::from(boxx.scheme_id_uri),
91        });
92    }
93    Ok((boxx.event_duration != UNKNOWN_EVENT_DURATION).then_some(boxx.event_duration))
94}
95
96/// Extract the verbatim `splice_info_section` from a SCTE-35 `emsg` box.
97pub fn emsg_to_scte35(emsg_bytes: &[u8]) -> Result<Vec<u8>> {
98    let boxx = EmsgBox::parse(emsg_bytes)?;
99    if !boxx.is_scte35() {
100        return Err(Error::UnsupportedScheme {
101            scheme: String::from(boxx.scheme_id_uri),
102        });
103    }
104    Ok(boxx.message_data.to_vec())
105}
106
107#[cfg(test)]
108mod tests {
109    fn timescale(value: u32) -> Timescale {
110        Timescale::try_new(value).expect("a non-zero timescale")
111    }
112
113    use super::*;
114    use alloc::string::ToString;
115
116    fn splice_2002() -> alloc::vec::Vec<u8> {
117        test_fixtures::read("scte35/splice-insert-2002.bin")
118    }
119
120    #[test]
121    fn scte35_unknown_duration_writes_all_ones_and_reads_back_as_unknown() {
122        let splice = splice_2002();
123        let cfg = EmsgConfig {
124            timescale: timescale(90_000),
125            presentation: PresentationTime::Absolute(90_000),
126            event_duration: None,
127            value: "1".to_string(),
128            id: 1,
129        };
130        let emsg = scte35_to_emsg(&splice, &cfg).unwrap();
131        let parsed = isobmff::emsg::EmsgBox::parse(&emsg).unwrap();
132        assert_eq!(parsed.event_duration, u32::MAX);
133        assert_eq!(scte35_event_duration(&emsg).unwrap(), None);
134    }
135
136    #[test]
137    fn scte35_to_emsg_refuses_a_version_zero_presentation_time() {
138        let splice = splice_2002();
139        let cfg = EmsgConfig {
140            timescale: timescale(90_000),
141            presentation: PresentationTime::Delta(0),
142            event_duration: Some(2_160_000),
143            value: "1".to_string(),
144            id: 1,
145        };
146        assert_eq!(
147            scte35_to_emsg(&splice, &cfg),
148            Err(Error::Scte35EmsgVersionZero)
149        );
150    }
151
152    #[test]
153    fn scte35_to_emsg_emits_version_one() {
154        let splice = splice_2002();
155        let cfg = EmsgConfig {
156            timescale: timescale(90_000),
157            presentation: PresentationTime::Absolute(0),
158            event_duration: Some(2_160_000),
159            value: "1".to_string(),
160            id: 1,
161        };
162        let emsg = scte35_to_emsg(&splice, &cfg).unwrap();
163        assert_eq!(
164            isobmff::emsg::EmsgBox::parse(&emsg)
165                .unwrap()
166                .presentation_time,
167            PresentationTime::Absolute(0)
168        );
169    }
170
171    #[test]
172    fn scte35_to_emsg_embeds_splice_verbatim_then_round_trips() {
173        let splice = splice_2002();
174        let cfg = EmsgConfig {
175            timescale: timescale(90_000),
176            presentation: PresentationTime::Absolute(0),
177            event_duration: Some(2_160_000),
178            value: "1".to_string(),
179            id: 1,
180        };
181        let emsg = scte35_to_emsg(&splice, &cfg).unwrap();
182        // message_data must equal the splice verbatim:
183        let extracted = emsg_to_scte35(&emsg).unwrap();
184        assert_eq!(extracted, splice);
185    }
186}