Skip to main content

ssai_runtime/
decision.rs

1//! Ad-break decision types.
2//!
3//! Models the subset of the HLS Interstitials `EXT-X-DATERANGE` attribute
4//! set (`CLASS="com.apple.hls.interstitial"`, draft-pantos-hls-rfc8216bis
5//! Appendix D §D.2, transcribed in full at
6//! `private/specs-verified/hls/ietf/rfc8216bis-interstitials.md`) issue #929 scoped:
7//! `X-ASSET-URI`/`X-ASSET-LIST`, `X-RESUME-OFFSET`, `X-PLAYOUT-LIMIT`,
8//! `X-SNAP`, `X-RESTRICT`. `X-CONTENT-MAY-VARY`, `X-TIMELINE-OCCUPIES`,
9//! `X-TIMELINE-STYLE`, and the §D.3 skip-button-control attributes are not
10//! modeled yet — a later addition, not a correction of what is here.
11//!
12//! The ad-decision server itself (VAST/VMAP, or anything else) is a caller
13//! concern per the issue's design decision: [`AdDecisionProvider`] is the
14//! only extension point this crate defines, and it performs no I/O — this
15//! crate has no HTTP client.
16
17use crate::error::Result;
18use alloc::string::String;
19use alloc::vec::Vec;
20
21/// `X-SNAP` identifier (Appendix D §D.2).
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24#[non_exhaustive]
25pub enum SnapMode {
26    /// `OUT` — the client should locate the primary-content segment
27    /// boundary nearest the interstitial's `START-DATE` and transition
28    /// there.
29    Out,
30    /// `IN` — the client should locate the primary-content segment boundary
31    /// nearest the scheduled resumption point and resume there.
32    In,
33}
34
35impl SnapMode {
36    /// Stable label — the literal `X-SNAP` wire token.
37    pub fn name(&self) -> &'static str {
38        match self {
39            SnapMode::Out => "OUT",
40            SnapMode::In => "IN",
41        }
42    }
43}
44broadcast_common::impl_spec_display!(SnapMode);
45
46/// `X-RESTRICT` identifier (Appendix D §D.2).
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
49#[non_exhaustive]
50pub enum RestrictMode {
51    /// `SKIP` — the client must not allow seeking forward or fast playback
52    /// while the interstitial plays.
53    Skip,
54    /// `JUMP` — the client must not allow seeking across the interstitial's
55    /// `START-DATE` without first playing it.
56    Jump,
57}
58
59impl RestrictMode {
60    /// Stable label — the literal `X-RESTRICT` wire token.
61    pub fn name(&self) -> &'static str {
62        match self {
63            RestrictMode::Skip => "SKIP",
64            RestrictMode::Jump => "JUMP",
65        }
66    }
67}
68broadcast_common::impl_spec_display!(RestrictMode);
69
70/// Which of the mutually-exclusive `X-ASSET-URI` / `X-ASSET-LIST` attributes
71/// identifies the interstitial content. Appendix D §D.2: "An Interstitial
72/// `EXT-X-DATERANGE` tag MUST have either `X-ASSET-URI` or `X-ASSET-LIST`; it
73/// MUST NOT have both."
74#[derive(Debug, Clone, PartialEq, Eq)]
75#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
76#[non_exhaustive]
77pub enum AssetSource {
78    /// `X-ASSET-URI` — a single interstitial asset's absolute URI.
79    Uri(String),
80    /// `X-ASSET-LIST` — URI of a JSON asset-list resource (the §D.2
81    /// `X-ASSET-LIST` JSON schema). This crate carries the URI only; it does
82    /// not fetch or parse that JSON — doing so is HTTP, and this crate is
83    /// sans-IO.
84    List(String),
85}
86
87/// The decision for one ad break: which interstitial content to schedule and
88/// how the client should treat it, per Appendix D §D.2.
89// `resume_offset`/`playout_limit` are `f64`, so this is `PartialEq` only (no
90// `Eq`) — the same reason `broadcast_hls::MediaPlaylist` and
91// `timed_metadata::DateRange` are `PartialEq`-only.
92#[derive(Debug, Clone, PartialEq)]
93#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
94pub struct AdBreakDecision {
95    /// `ID` of the rendered `EXT-X-DATERANGE` tag.
96    pub id: String,
97    /// `X-ASSET-URI` or `X-ASSET-LIST`.
98    pub asset: AssetSource,
99    /// `X-RESUME-OFFSET` in seconds; `None` = attribute omitted (the client
100    /// then treats it as the interstitial's duration, per §D.2).
101    pub resume_offset: Option<f64>,
102    /// `X-PLAYOUT-LIMIT` in seconds; `None` = attribute omitted.
103    pub playout_limit: Option<f64>,
104    /// `X-SNAP` identifiers, in the order they should be rendered.
105    pub snap: Vec<SnapMode>,
106    /// `X-RESTRICT` identifiers, in the order they should be rendered.
107    pub restrict: Vec<RestrictMode>,
108}
109
110impl AdBreakDecision {
111    /// Build a decision for a single-asset (`X-ASSET-URI`) interstitial,
112    /// with no resume offset, playout limit, snap, or restrict attributes —
113    /// set those fields afterwards as needed.
114    pub fn single_asset(id: impl Into<String>, uri: impl Into<String>) -> Self {
115        AdBreakDecision {
116            id: id.into(),
117            asset: AssetSource::Uri(uri.into()),
118            resume_offset: None,
119            playout_limit: None,
120            snap: Vec::new(),
121            restrict: Vec::new(),
122        }
123    }
124
125    /// Build a decision for an asset-list (`X-ASSET-LIST`) interstitial.
126    #[cfg(test)]
127    pub(crate) fn asset_list(id: impl Into<String>, list_uri: impl Into<String>) -> Self {
128        AdBreakDecision {
129            id: id.into(),
130            asset: AssetSource::List(list_uri.into()),
131            resume_offset: None,
132            playout_limit: None,
133            snap: Vec::new(),
134            restrict: Vec::new(),
135        }
136    }
137}
138
139/// Context handed to [`AdDecisionProvider::decide`]: what the SCTE-35 cue
140/// told us about the upcoming break, plus which session is asking.
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct BreakContext {
143    /// The session requesting a decision.
144    pub session_id: String,
145    /// `splice_event_id` from the triggering `splice_insert()`, if known.
146    pub splice_event_id: Option<u32>,
147    /// `out_of_network_indicator` — `true` for break start, `false` for
148    /// return-to-network.
149    pub out_of_network: bool,
150    /// `break_duration().duration`, in 90 kHz ticks, if the cue carried one.
151    pub break_duration_ticks: Option<u64>,
152    /// The (conditioned) media-timeline instant this break is scheduled to
153    /// start at, in the caller's clock unit (typically 90 kHz ticks).
154    pub splice_point_pts: u64,
155}
156
157/// Pluggable ad-decision hook (issue #929 design decision): VAST/VMAP or any
158/// other decisioning scheme is entirely the caller's concern. This trait's
159/// only job is to hand back what to render — it performs no I/O itself, and
160/// this crate adds no HTTP client to reach one.
161pub trait AdDecisionProvider {
162    /// Decide what interstitial content to schedule for `ctx`.
163    fn decide(&self, ctx: &BreakContext) -> Result<AdBreakDecision>;
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    struct AlwaysSameAd;
171    impl AdDecisionProvider for AlwaysSameAd {
172        fn decide(&self, ctx: &BreakContext) -> Result<AdBreakDecision> {
173            Ok(AdBreakDecision::single_asset(
174                alloc::format!("break-{}", ctx.splice_event_id.unwrap_or(0)),
175                "https://ads.example.com/creative.m3u8",
176            ))
177        }
178    }
179
180    #[test]
181    fn provider_trait_is_object_safe_and_callable() {
182        let provider: &dyn AdDecisionProvider = &AlwaysSameAd;
183        let ctx = BreakContext {
184            session_id: "s1".into(),
185            splice_event_id: Some(7),
186            out_of_network: true,
187            break_duration_ticks: Some(1_800_000),
188            splice_point_pts: 12_345,
189        };
190        let decision = provider.decide(&ctx).unwrap();
191        assert_eq!(decision.id, "break-7");
192        assert_eq!(
193            decision.asset,
194            AssetSource::Uri("https://ads.example.com/creative.m3u8".into())
195        );
196    }
197
198    #[test]
199    fn single_asset_and_asset_list_builders() {
200        let single = AdBreakDecision::single_asset("a", "https://x/a.m3u8");
201        assert_eq!(single.asset, AssetSource::Uri("https://x/a.m3u8".into()));
202
203        let list = AdBreakDecision::asset_list("b", "https://x/list.json");
204        assert_eq!(list.asset, AssetSource::List("https://x/list.json".into()));
205    }
206
207    #[test]
208    fn label_convention() {
209        assert_eq!(SnapMode::Out.name(), "OUT");
210        assert_eq!(alloc::format!("{}", SnapMode::In), "IN");
211        assert_eq!(RestrictMode::Skip.name(), "SKIP");
212        assert_eq!(alloc::format!("{}", RestrictMode::Jump), "JUMP");
213    }
214}