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//! `broadcast-hls/docs/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    pub fn asset_list(id: impl Into<String>, list_uri: impl Into<String>) -> Self {
127        AdBreakDecision {
128            id: id.into(),
129            asset: AssetSource::List(list_uri.into()),
130            resume_offset: None,
131            playout_limit: None,
132            snap: Vec::new(),
133            restrict: Vec::new(),
134        }
135    }
136}
137
138/// Context handed to [`AdDecisionProvider::decide`]: what the SCTE-35 cue
139/// told us about the upcoming break, plus which session is asking.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct BreakContext {
142    /// The session requesting a decision.
143    pub session_id: String,
144    /// `splice_event_id` from the triggering `splice_insert()`, if known.
145    pub splice_event_id: Option<u32>,
146    /// `out_of_network_indicator` — `true` for break start, `false` for
147    /// return-to-network.
148    pub out_of_network: bool,
149    /// `break_duration().duration`, in 90 kHz ticks, if the cue carried one.
150    pub break_duration_ticks: Option<u64>,
151    /// The (conditioned) media-timeline instant this break is scheduled to
152    /// start at, in the caller's clock unit (typically 90 kHz ticks).
153    pub splice_point_pts: u64,
154}
155
156/// Pluggable ad-decision hook (issue #929 design decision): VAST/VMAP or any
157/// other decisioning scheme is entirely the caller's concern. This trait's
158/// only job is to hand back what to render — it performs no I/O itself, and
159/// this crate adds no HTTP client to reach one.
160pub trait AdDecisionProvider {
161    /// Decide what interstitial content to schedule for `ctx`.
162    fn decide(&self, ctx: &BreakContext) -> Result<AdBreakDecision>;
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    struct AlwaysSameAd;
170    impl AdDecisionProvider for AlwaysSameAd {
171        fn decide(&self, ctx: &BreakContext) -> Result<AdBreakDecision> {
172            Ok(AdBreakDecision::single_asset(
173                alloc::format!("break-{}", ctx.splice_event_id.unwrap_or(0)),
174                "https://ads.example.com/creative.m3u8",
175            ))
176        }
177    }
178
179    #[test]
180    fn provider_trait_is_object_safe_and_callable() {
181        let provider: &dyn AdDecisionProvider = &AlwaysSameAd;
182        let ctx = BreakContext {
183            session_id: "s1".into(),
184            splice_event_id: Some(7),
185            out_of_network: true,
186            break_duration_ticks: Some(1_800_000),
187            splice_point_pts: 12_345,
188        };
189        let decision = provider.decide(&ctx).unwrap();
190        assert_eq!(decision.id, "break-7");
191        assert_eq!(
192            decision.asset,
193            AssetSource::Uri("https://ads.example.com/creative.m3u8".into())
194        );
195    }
196
197    #[test]
198    fn single_asset_and_asset_list_builders() {
199        let single = AdBreakDecision::single_asset("a", "https://x/a.m3u8");
200        assert_eq!(single.asset, AssetSource::Uri("https://x/a.m3u8".into()));
201
202        let list = AdBreakDecision::asset_list("b", "https://x/list.json");
203        assert_eq!(list.asset, AssetSource::List("https://x/list.json".into()));
204    }
205
206    #[test]
207    fn label_convention() {
208        assert_eq!(SnapMode::Out.name(), "OUT");
209        assert_eq!(alloc::format!("{}", SnapMode::In), "IN");
210        assert_eq!(RestrictMode::Skip.name(), "SKIP");
211        assert_eq!(alloc::format!("{}", RestrictMode::Jump), "JUMP");
212    }
213}