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 → HLS `EXT-X-DATERANGE` (RFC 8216bis §4.4.5.1).
//!
//! The tag itself is [`broadcast_hls::DateRange`], the workspace's one owner
//! of its model, parsing and rendering; this module only decides which
//! attributes a SCTE-35-sourced [`TimedEvent`] puts on it.
use crate::anchor::TimeAnchor;
use crate::error::{Error, Result};
use crate::event::{EventKind, SourcePayload, TimedEvent};
use alloc::string::ToString;
use broadcast_hls::{DateRange, DecimalSeconds, Scte35Kind};

/// Convert a SCTE-35-sourced [`TimedEvent`] to a [`DateRange`].
///
/// `START-DATE` comes from `ev.at` via `anchor` when present; otherwise from the
/// anchor's own UTC (the insertion-point time the caller supplied). The original
/// splice bytes are carried verbatim into the `SCTE35-OUT`/`IN` attribute.
pub fn scte35_to_daterange(ev: &TimedEvent, anchor: &TimeAnchor) -> Result<DateRange> {
    let raw = match &ev.source {
        SourcePayload::Scte35 { raw } => raw.clone(),
        SourcePayload::Emsg { .. } => {
            return Err(Error::AttrParse("event is not SCTE-35-sourced".to_string()));
        }
    };

    // EventKind -> cue is intentionally lossy: Chapter/Unspecified both collapse
    // to Cmd. The DateRange -> TimedEvent reverse edge is out of v0.1 scope, so no
    // round-trip symmetry is implied here.
    let scte35 = match ev.kind {
        EventKind::BreakStart => Scte35Kind::Out,
        EventKind::BreakEnd => Scte35Kind::In,
        _ => Scte35Kind::Cmd,
    };

    let start_date = match ev.at {
        Some(t) => anchor.try_rfc3339(t)?,
        None => crate::anchor::try_format_rfc3339_ms(anchor.utc_epoch_ms)?,
    };

    let planned_duration = ev
        .duration
        .map(|d| DecimalSeconds::new(d.as_seconds_f64()))
        .transpose()?;

    // A `time_signal` cue with no (uncancelled) segmentation descriptor has
    // no id (see `TimedEvent::from_scte35`); every DATERANGE needs a unique
    // ID (RFC 8216bis §4.4.5.1), so error rather than emit `ID=""`.
    let id = ev.id.ok_or(Error::MissingEventId)?;

    Ok(DateRange::from_parts(
        id.to_string(),
        None::<&str>,
        start_date,
        None,
        planned_duration,
        Some((scte35, raw)),
    )?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::anchor::TimeAnchor;
    use crate::event::{EventKind, MediaDuration, SourcePayload, TimedEvent};
    use alloc::{vec, vec::Vec};
    use broadcast_hls::Scte35Kind;

    #[test]
    fn break_start_maps_to_scte35_out_with_duration() {
        let ev = TimedEvent {
            id: Some(2002),
            kind: EventKind::BreakStart,
            at: None,
            duration: Some(MediaDuration::from_90khz_ticks(2_160_000)), // 24s
            source: SourcePayload::Scte35 {
                raw: vec![0xFC, 0x30, 0x21],
            },
        };
        // anchor: epoch 0 == pts 0; with at=None, START-DATE uses anchor.utc_epoch_ms.
        let anchor = TimeAnchor {
            pts_90k: 0,
            utc_epoch_ms: 0,
        };
        let dr = scte35_to_daterange(&ev, &anchor).unwrap();
        assert_eq!(dr.id(), "2002");
        assert_eq!(
            dr.planned_duration(),
            Some(DecimalSeconds::new(24.0).unwrap())
        );
        let (kind, raw) = dr.scte35().unwrap();
        assert_eq!(kind, Scte35Kind::Out);
        assert_eq!(raw, vec![0xFC, 0x30, 0x21]); // verbatim
        assert_eq!(dr.start().unwrap().render(), "1970-01-01T00:00:00.000Z");
        assert_eq!(
            dr.to_tag_line().unwrap(),
            "#EXT-X-DATERANGE:ID=\"2002\",START-DATE=\"1970-01-01T00:00:00.000Z\",PLANNED-DURATION=24,SCTE35-OUT=0xFC3021"
        );
    }

    #[test]
    fn break_end_maps_to_scte35_in_and_other_kinds_to_cmd() {
        let anchor = TimeAnchor {
            pts_90k: 0,
            utc_epoch_ms: 0,
        };
        let event = |kind| TimedEvent {
            id: Some(7),
            kind,
            at: None,
            duration: None,
            source: SourcePayload::Scte35 {
                raw: vec![0xFC, 0x30, 0x21],
            },
        };

        let dr = scte35_to_daterange(&event(EventKind::BreakEnd), &anchor).unwrap();
        let line = dr.to_tag_line().unwrap();
        assert!(line.contains("SCTE35-IN=0xFC3021"), "{line}");
        let (kind, raw) = dr.scte35().unwrap();
        assert_eq!(kind, Scte35Kind::In);
        assert_eq!(raw, vec![0xFC, 0x30, 0x21]);

        for kind in [EventKind::Chapter, EventKind::Unspecified] {
            let dr = scte35_to_daterange(&event(kind), &anchor).unwrap();
            let line = dr.to_tag_line().unwrap();
            assert!(line.contains("SCTE35-CMD=0xFC3021"), "{line}");
            assert_eq!(dr.scte35().unwrap().0, Scte35Kind::Cmd, "{kind:?}");
        }
    }

    /// A `segmentation_upid`-derived id with a `"` or newline is refused by the
    /// owner's quoted-string validation, never rendered into the tag.
    #[test]
    fn an_injection_capable_id_is_refused() {
        for id in [0x1234u32, 0x5678] {
            let ev = TimedEvent {
                id: Some(id),
                kind: EventKind::BreakStart,
                at: None,
                duration: None,
                source: SourcePayload::Scte35 {
                    raw: vec![0xFC, 0x30, 0x21],
                },
            };
            let anchor = TimeAnchor {
                pts_90k: 0,
                utc_epoch_ms: 0,
            };
            let dr: Vec<_> = scte35_to_daterange(&ev, &anchor)
                .unwrap()
                .to_tag_line()
                .unwrap()
                .into_bytes()
                .into_iter()
                .filter(u8::is_ascii_control)
                .collect();
            assert!(dr.is_empty());
        }
    }
}