timed_metadata/convert/
emsg.rs1use crate::error::{Error, Result};
12use alloc::{string::String, vec::Vec};
13use broadcast_common::timescale::Timescale;
14use mp4_emsg::{EmsgBox, PresentationTime};
15
16pub const SCTE35_SCHEME: &str = "urn:scte:scte35:2013:bin";
19
20#[derive(Debug, Clone)]
22#[non_exhaustive]
23pub struct EmsgConfig {
24 pub timescale: Timescale,
26 pub presentation: PresentationTime,
28 pub event_duration: u32,
30 pub value: String,
32 pub id: u32,
34}
35
36impl EmsgConfig {
37 #[must_use]
39 pub fn new(
40 timescale: Timescale,
41 presentation: PresentationTime,
42 event_duration: u32,
43 value: String,
44 id: u32,
45 ) -> Self {
46 Self {
47 timescale,
48 presentation,
49 event_duration,
50 value,
51 id,
52 }
53 }
54}
55
56pub fn scte35_to_emsg(splice_raw: &[u8], cfg: &EmsgConfig) -> Result<Vec<u8>> {
58 let boxx = EmsgBox {
59 flags: mp4_emsg::EMSG_FLAGS,
60 scheme_id_uri: SCTE35_SCHEME,
61 value: &cfg.value,
62 timescale: cfg.timescale,
63 presentation_time: cfg.presentation,
64 event_duration: cfg.event_duration,
65 id: cfg.id,
66 message_data: splice_raw,
67 };
68 Ok(boxx.to_vec()?)
69}
70
71pub fn emsg_to_scte35(emsg_bytes: &[u8]) -> Result<Vec<u8>> {
73 let boxx = EmsgBox::parse(emsg_bytes)?;
74 if !boxx.is_scte35() {
75 return Err(Error::UnsupportedScheme {
76 scheme: String::from(boxx.scheme_id_uri),
77 });
78 }
79 Ok(boxx.message_data.to_vec())
80}
81
82#[cfg(test)]
83mod tests {
84 fn timescale(value: u32) -> Timescale {
85 Timescale::try_new(value).expect("a non-zero timescale")
86 }
87
88 use super::*;
89 use alloc::string::ToString;
90
91 fn splice_2002() -> alloc::vec::Vec<u8> {
92 test_fixtures::read("scte35/splice-insert-2002.bin")
93 }
94
95 #[test]
96 fn scte35_to_emsg_embeds_splice_verbatim_then_round_trips() {
97 let splice = splice_2002();
98 let cfg = EmsgConfig {
99 timescale: timescale(90_000),
100 presentation: PresentationTime::Delta(0),
101 event_duration: 2_160_000,
102 value: "1".to_string(),
103 id: 1,
104 };
105 let emsg = scte35_to_emsg(&splice, &cfg).unwrap();
106 let extracted = emsg_to_scte35(&emsg).unwrap();
108 assert_eq!(extracted, splice);
109 }
110}