timed_metadata/convert/
emsg.rs1use crate::error::{Error, Result};
12use alloc::{string::String, vec::Vec};
13use mp4_emsg::{EmsgBox, PresentationTime};
14
15pub const SCTE35_SCHEME: &str = "urn:scte:scte35:2013:bin";
18
19#[derive(Debug, Clone)]
21pub struct EmsgConfig {
22 pub timescale: u32,
24 pub presentation: PresentationTime,
26 pub event_duration: u32,
28 pub value: String,
30 pub id: u32,
32}
33
34pub fn scte35_to_emsg(splice_raw: &[u8], cfg: &EmsgConfig) -> Result<Vec<u8>> {
36 let boxx = EmsgBox {
37 flags: mp4_emsg::EMSG_FLAGS,
38 scheme_id_uri: SCTE35_SCHEME,
39 value: &cfg.value,
40 timescale: cfg.timescale,
41 presentation_time: cfg.presentation,
42 event_duration: cfg.event_duration,
43 id: cfg.id,
44 message_data: splice_raw,
45 };
46 Ok(boxx.to_vec()?)
47}
48
49pub fn emsg_to_scte35(emsg_bytes: &[u8]) -> Result<Vec<u8>> {
51 let boxx = EmsgBox::parse(emsg_bytes)?;
52 if !boxx.is_scte35() {
53 return Err(Error::UnsupportedScheme {
54 scheme: String::from(boxx.scheme_id_uri),
55 });
56 }
57 Ok(boxx.message_data.to_vec())
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63 use alloc::string::ToString;
64
65 fn splice_2002() -> alloc::vec::Vec<u8> {
66 let hex = "FC302100000000000000FFF01005000007D27FEF7F7E0020F580C0000000000088B9661D";
67 (0..hex.len())
68 .step_by(2)
69 .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
70 .collect()
71 }
72
73 #[test]
74 fn scte35_to_emsg_embeds_splice_verbatim_then_round_trips() {
75 let splice = splice_2002();
76 let cfg = EmsgConfig {
77 timescale: 90_000,
78 presentation: PresentationTime::Delta(0),
79 event_duration: 2_160_000,
80 value: "1".to_string(),
81 id: 1,
82 };
83 let emsg = scte35_to_emsg(&splice, &cfg).unwrap();
84 let extracted = emsg_to_scte35(&emsg).unwrap();
86 assert_eq!(extracted, splice);
87 }
88}