timed-metadata 0.13.0

Convert DPI / timed-metadata signalling between SCTE-35, HLS EXT-X-DATERANGE and DASH emsg. no_std.
Documentation
//! The inband `emsg` set a fMP4 segment carries for a run of timed events
//! (ANSI/SCTE 214-1:2024 §7.7.3, `private/specs-verified/scte/dash/scte-214-1-2024.md`;
//! ISO/IEC 23009-1 §5.10.3.3).
//!
//! A live segment's events are stamped on the trunk's 90 kHz event clock,
//! already wrap-unrolled. Turning them into boxes is three steps, all here
//! so a caller writes none of them:
//!
//! 1. only a SCTE-35-sourced event with a resolved presentation time becomes
//!    an `emsg`, through [`Timeline::to_emsg`] over the same
//!    [`EmsgConfig`] the v0 conversion uses;
//! 2. DASH clients de-duplicate by `(scheme_id_uri, value, id)`
//!    (ISO/IEC 23009-1 §5.10.3.3), so every box in one segment must carry a
//!    distinct [`unique_id`] — a SCTE-35 `splice_insert`'s own
//!    `splice_event_id` verbatim, else one derived from the presentation
//!    time;
//! 3. the boxes are spliced in immediately after the segment's `styp`, which
//!    is where CMAF places event boxes (`[styp][emsg*][moof][mdat]`).

use alloc::vec::Vec;

use broadcast_core::timescale::Timescale;
use isobmff::emsg::PresentationTime;

use crate::convert::{EmsgConfig, scte35_to_emsg};
use crate::event::{MediaDuration, MediaTime};

/// The `timescale` an event's media time is expressed in: the trunk's 90 kHz
/// event clock ([`broadcast_common::clock33::PTS_TIMESCALE`]).
#[must_use]
pub fn event_timescale() -> Timescale {
    broadcast_common::clock33::PTS_TIMESCALE
}

/// A `(scheme, value, id)`-unique `emsg` id, walking past every id `used`
/// already holds.
///
/// A declared id — a SCTE-35 `splice_insert`'s `splice_event_id` — is kept
/// verbatim: it is the operator's own identity, and a client keyed on it must
/// see the same value, even when two events of one segment genuinely share
/// it (that is the upstream's data, not something to rewrite). Only an
/// undeclared id — a `time_signal` carries none — is derived from the
/// presentation time, so two such events cannot both fall on the same id and
/// have the second silently dropped by a deduplicating client.
pub fn unique_id(declared: Option<u32>, media_time_90k: u64, used: &mut Vec<u32>) -> u32 {
    if let Some(id) = declared {
        if !used.contains(&id) {
            used.push(id);
        }
        return id;
    }
    // The id space is 32-bit and a 33-bit 90 kHz time exceeds it after about
    // 13.2 hours, so fold rather than truncate silently.
    let mut id = u32::try_from(media_time_90k % u64::from(u32::MAX)).unwrap_or(u32::MAX);
    while used.contains(&id) {
        id = id.wrapping_add(1);
    }
    used.push(id);
    id
}

/// The `emsg` box for one event at `presentation_time` (90 kHz ticks) whose
/// raw payload is `raw` and whose declared id is `declared`.
///
/// `duration` is the event's declared length on the same clock, if any; an
/// over-long one saturates below `u32::MAX` (the "not known" value, 214-1
/// 2024 §7.7.3(4)) rather than wrapping. The `value` field is empty, as a
/// SCTE-35 splice payload names its own type.
pub fn event_emsg(
    raw: &[u8],
    declared: Option<u32>,
    presentation_time: MediaTime,
    duration: Option<MediaDuration>,
    used_ids: &mut Vec<u32>,
) -> crate::Result<Vec<u8>> {
    let config = EmsgConfig::new(
        event_timescale(),
        PresentationTime::Absolute(presentation_time.ticks_90khz()),
        duration.map(|d| {
            u32::try_from(d.ticks_90khz()).unwrap_or(crate::convert::MAX_KNOWN_EVENT_DURATION)
        }),
        alloc::string::String::new(),
        unique_id(declared, presentation_time.ticks_90khz(), used_ids),
    );
    scte35_to_emsg(raw, &config)
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    #[test]
    fn a_declared_id_is_kept_verbatim_even_when_another_event_shares_it() {
        let mut used = Vec::new();
        assert_eq!(unique_id(Some(2002), 0, &mut used), 2002);
        assert_eq!(unique_id(Some(2002), 90_000, &mut used), 2002);
        assert_eq!(used, vec![2002]);
    }

    #[test]
    fn an_undeclared_id_is_derived_and_walks_past_an_id_already_emitted() {
        let mut used = Vec::new();
        assert_eq!(unique_id(None, 7, &mut used), 7);
        assert_eq!(unique_id(None, 7, &mut used), 8);
        assert_eq!(unique_id(Some(9), 0, &mut used), 9);
        assert_eq!(unique_id(None, 9, &mut used), 10);
        assert_eq!(unique_id(None, 7, &mut used), 11);
    }

    #[test]
    fn a_thirty_three_bit_time_derives_an_id_rather_than_wrapping_to_zero() {
        let mut used = Vec::new();
        let id = unique_id(None, broadcast_common::clock33::WRAP_33BIT - 1, &mut used);
        assert_ne!(id, 0);
        assert!(used.contains(&id));
    }

    #[test]
    fn an_over_32_bit_media_time_folds_into_the_id_space() {
        let mut used = Vec::new();
        let media_time = u64::from(u32::MAX) * 2;
        assert_eq!(unique_id(None, media_time, &mut used), 0);
        assert_eq!(
            unique_id(None, media_time, &mut used),
            1,
            "the walk moves past an id already emitted"
        );
    }

    #[test]
    fn cues_past_the_32_bit_boundary_get_distinct_ids_in_one_window() {
        let boundary = u64::from(u32::MAX);
        let mut used = Vec::new();
        let ids: Vec<u32> = [
            boundary - 1,
            boundary + 1,
            boundary + 1000,
            boundary * 3 + 7,
        ]
        .iter()
        .map(|time| unique_id(None, *time, &mut used))
        .collect();
        let mut distinct = ids.clone();
        distinct.sort_unstable();
        distinct.dedup();
        assert_eq!(distinct.len(), ids.len(), "{ids:?}");
        assert!(ids.iter().all(|id| *id != u32::MAX), "{ids:?}");
    }

    #[test]
    fn two_segments_past_the_boundary_do_not_share_an_id() {
        let boundary = u64::from(u32::MAX);
        let first = unique_id(None, boundary + 10, &mut Vec::new());
        let second = unique_id(None, boundary + 20_000, &mut Vec::new());
        assert_ne!(first, second);
    }

    #[test]
    fn an_event_emsg_carries_its_payload_timescale_and_id() {
        let raw = test_fixtures::read("scte35/splice-insert-2002.bin");
        let mut used = Vec::new();
        let bytes = event_emsg(
            &raw,
            Some(2002),
            MediaTime::from_90khz_ticks(90_000),
            Some(MediaDuration::from_90khz_ticks(45_000)),
            &mut used,
        )
        .expect("emsg serialized");
        let parsed = isobmff::emsg::EmsgBox::parse(&bytes).expect("parses back");
        assert_eq!(parsed.scheme_id_uri, crate::convert::SCTE35_SCHEME);
        assert_eq!(parsed.value, "");
        assert_eq!(parsed.timescale, Some(event_timescale()));
        assert_eq!(parsed.presentation_time, PresentationTime::Absolute(90_000));
        assert_eq!(parsed.event_duration, 45_000);
        assert_eq!(parsed.id, 2002);
        assert_eq!(parsed.message_data, raw.as_slice());
    }

    #[test]
    fn an_over_long_duration_saturates_below_unknown_and_an_absent_one_is_unknown() {
        let raw = test_fixtures::read("scte35/splice-insert-2002.bin");
        let mut used = Vec::new();
        let long = event_emsg(
            &raw,
            None,
            MediaTime::from_90khz_ticks(0),
            Some(MediaDuration::from_90khz_ticks(u64::from(u32::MAX) + 1)),
            &mut used,
        )
        .expect("emsg serialized");
        assert_eq!(
            isobmff::emsg::EmsgBox::parse(&long)
                .expect("parses back")
                .event_duration,
            crate::convert::MAX_KNOWN_EVENT_DURATION
        );
        let none = event_emsg(&raw, None, MediaTime::from_90khz_ticks(0), None, &mut used)
            .expect("emsg serialized");
        assert_eq!(
            crate::convert::scte35_event_duration(&none).expect("parses back"),
            None
        );
    }
}