timed-metadata 0.13.1

Convert DPI / timed-metadata signalling between SCTE-35, HLS EXT-X-DATERANGE and DASH emsg. no_std.
Documentation
//! SCTE-35 ↔ DASH `emsg` conversion (scheme `urn:scte:scte35:2013:bin`).
//!
//! Carriage is **ANSI/SCTE 214-1:2024 §7.7.3**
//! (`private/specs-verified/scte/dash/scte-214-1-2024.md`): version 1, the
//! whole `splice_info_section` in `message_data`, and `0xFFFFFFFF` for an
//! unknown duration. The older 214-3 §8.3.3 transcription only carried the
//! scheme identity; the rules now live in 214-1 2024. (The MPD `EventStream`
//! form, `urn:scte:scte35:2014:xml+bin`, is 214-1 2024 §7.7.2.1.)
use crate::error::{Error, Result};
use alloc::{string::String, vec::Vec};
use broadcast_core::timescale::Timescale;
use isobmff::emsg::{EmsgBox, PresentationTime};

/// The SCTE-35 binary carriage scheme for inband DASH `emsg`
/// (ANSI/SCTE 214-1:2024 §7.7.3(1)).
pub const SCTE35_SCHEME: &str = "urn:scte:scte35:2013:bin";

/// The `event_duration` wire value meaning "not known" (214-1 2024 §7.7.3(4)).
pub const UNKNOWN_EVENT_DURATION: u32 = 0xFFFF_FFFF;

/// The largest expressible known duration, one below [`UNKNOWN_EVENT_DURATION`].
pub const MAX_KNOWN_EVENT_DURATION: u32 = UNKNOWN_EVENT_DURATION - 1;

/// Parameters for emitting a SCTE-35-carrying `emsg`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct EmsgConfig {
    /// `timescale` (ticks/second) for the emsg time fields.
    pub timescale: Timescale,
    /// `presentation_time` relative to PeriodStart adjusted by
    /// `@presentationTimeOffset` (214-1 2024 §7.7.3(3)); version 1 only.
    pub presentation: PresentationTime,
    /// `event_duration` in `timescale` units (`None` = not known, written as
    /// [`UNKNOWN_EVENT_DURATION`]; 214-1 2024 §7.7.3(4)).
    pub event_duration: Option<u32>,
    /// `value` — the SCTE 35 PID or a URI (214-1 2024 §7.7.3(5)).
    pub value: String,
    /// `id` — unique within the Period (214-1 2024 §7.7.3(6)).
    pub id: u32,
}

impl EmsgConfig {
    /// Build the emsg parameters from their required values.
    #[must_use]
    pub fn new(
        timescale: Timescale,
        presentation: PresentationTime,
        event_duration: Option<u32>,
        value: String,
        id: u32,
    ) -> Self {
        Self {
            timescale,
            presentation,
            event_duration,
            value,
            id,
        }
    }
}

/// Wrap a verbatim `splice_info_section` as a SCTE-35 `emsg` box (serialized bytes).
///
/// The box is version 1: `presentation` is `presentation_time` relative to
/// PeriodStart adjusted by `@presentationTimeOffset` (214-1 2024 §7.7.3(3));
/// version 0 shall not be used (§7.7.1(2)).
pub fn scte35_to_emsg(splice_raw: &[u8], cfg: &EmsgConfig) -> Result<Vec<u8>> {
    let PresentationTime::Absolute(presentation_time) = cfg.presentation else {
        return Err(Error::Scte35EmsgVersionZero);
    };
    let boxx = EmsgBox {
        flags: isobmff::emsg::EMSG_FLAGS,
        scheme_id_uri: SCTE35_SCHEME,
        value: &cfg.value,
        timescale: Some(cfg.timescale),
        presentation_time: PresentationTime::Absolute(presentation_time),
        event_duration: cfg.event_duration.unwrap_or(UNKNOWN_EVENT_DURATION),
        id: cfg.id,
        message_data: splice_raw,
    };
    Ok(boxx.to_vec()?)
}

/// Read a SCTE-35 `emsg`'s `event_duration`: `None` for the "not known" wire
/// value `0xFFFFFFFF` (214-1 2024 §7.7.3(4)), `Some(ticks)` otherwise.
pub fn scte35_event_duration(emsg_bytes: &[u8]) -> Result<Option<u32>> {
    let boxx = EmsgBox::parse(emsg_bytes)?;
    if !boxx.is_scte35() {
        return Err(Error::UnsupportedScheme {
            scheme: String::from(boxx.scheme_id_uri),
        });
    }
    Ok((boxx.event_duration != UNKNOWN_EVENT_DURATION).then_some(boxx.event_duration))
}

/// Extract the verbatim `splice_info_section` from a SCTE-35 `emsg` box.
pub fn emsg_to_scte35(emsg_bytes: &[u8]) -> Result<Vec<u8>> {
    let boxx = EmsgBox::parse(emsg_bytes)?;
    if !boxx.is_scte35() {
        return Err(Error::UnsupportedScheme {
            scheme: String::from(boxx.scheme_id_uri),
        });
    }
    Ok(boxx.message_data.to_vec())
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;
    use test_harness::values::timescale;

    fn splice_2002() -> alloc::vec::Vec<u8> {
        test_fixtures::read("scte35/splice-insert-2002.bin")
    }

    #[test]
    fn scte35_unknown_duration_writes_all_ones_and_reads_back_as_unknown() {
        let splice = splice_2002();
        let cfg = EmsgConfig {
            timescale: timescale(90_000),
            presentation: PresentationTime::Absolute(90_000),
            event_duration: None,
            value: "1".to_string(),
            id: 1,
        };
        let emsg = scte35_to_emsg(&splice, &cfg).unwrap();
        let parsed = isobmff::emsg::EmsgBox::parse(&emsg).unwrap();
        assert_eq!(parsed.event_duration, u32::MAX);
        assert_eq!(scte35_event_duration(&emsg).unwrap(), None);
    }

    #[test]
    fn scte35_to_emsg_refuses_a_version_zero_presentation_time() {
        let splice = splice_2002();
        let cfg = EmsgConfig {
            timescale: timescale(90_000),
            presentation: PresentationTime::Delta(0),
            event_duration: Some(2_160_000),
            value: "1".to_string(),
            id: 1,
        };
        assert_eq!(
            scte35_to_emsg(&splice, &cfg),
            Err(Error::Scte35EmsgVersionZero)
        );
    }

    #[test]
    fn scte35_to_emsg_emits_version_one() {
        let splice = splice_2002();
        let cfg = EmsgConfig {
            timescale: timescale(90_000),
            presentation: PresentationTime::Absolute(0),
            event_duration: Some(2_160_000),
            value: "1".to_string(),
            id: 1,
        };
        let emsg = scte35_to_emsg(&splice, &cfg).unwrap();
        assert_eq!(
            isobmff::emsg::EmsgBox::parse(&emsg)
                .unwrap()
                .presentation_time,
            PresentationTime::Absolute(0)
        );
    }

    #[test]
    fn scte35_to_emsg_embeds_splice_verbatim_then_round_trips() {
        let splice = splice_2002();
        let cfg = EmsgConfig {
            timescale: timescale(90_000),
            presentation: PresentationTime::Absolute(0),
            event_duration: Some(2_160_000),
            value: "1".to_string(),
            id: 1,
        };
        let emsg = scte35_to_emsg(&splice, &cfg).unwrap();
        // message_data must equal the splice verbatim:
        let extracted = emsg_to_scte35(&emsg).unwrap();
        assert_eq!(extracted, splice);
    }
}