Skip to main content

ssai_runtime/
playlist.rs

1//! Per-session HLS Interstitial playlist rendering.
2//!
3//! `EXT-X-DATERANGE CLASS="com.apple.hls.interstitial"` — Appendix D §D.2 of
4//! draft-pantos-hls-rfc8216bis, transcribed in full at
5//! `private/specs-verified/hls/ietf/rfc8216bis-interstitials.md` (§D.2, examples §D.6/§D.7). Renders
6//! over `broadcast-hls`: [`render_session_playlist`] clones the primary
7//! [`MediaPlaylist`] and appends this session's interstitial tag line to
8//! [`MediaPlaylist::extra_tags`] — the injection point `broadcast-hls`
9//! documents for exactly this purpose ("Extra tag lines emitted verbatim
10//! before segment entries (e.g. `#EXT-X-DATERANGE:...`)").
11//!
12//! Implements the attribute set issue #929 scoped: `X-ASSET-URI`/
13//! `X-ASSET-LIST`, `X-RESUME-OFFSET`, `X-PLAYOUT-LIMIT`, `X-SNAP`,
14//! `X-RESTRICT`. `X-CONTENT-MAY-VARY`, `X-TIMELINE-OCCUPIES`,
15//! `X-TIMELINE-STYLE`, and the §D.3 skip-button-control attributes are not
16//! modeled.
17//!
18//! This crate does not do wall-clock math: [`InterstitialDateRange::start_date`]
19//! is a caller-supplied, already-formatted ISO-8601/RFC3339 string.
20//!
21//! The tag itself is `broadcast_hls::DateRange`, the workspace's one
22//! `EXT-X-DATERANGE` model: [`InterstitialDateRange::to_tag_line`] builds one
23//! through its typed setters and [`InterstitialDateRange::parse_tag_line`]
24//! reads one back, so this crate renders no attribute text and owns no parser.
25
26use crate::decision::{AdBreakDecision, AssetSource, RestrictMode, SnapMode};
27use crate::error::{Error, Result};
28use alloc::format;
29use alloc::string::{String, ToString};
30use alloc::vec::Vec;
31use broadcast_hls::{
32    DateRange, DecimalSeconds, INTERSTITIAL_ASSET_LIST, INTERSTITIAL_ASSET_URI,
33    INTERSTITIAL_PLAYOUT_LIMIT, INTERSTITIAL_RESTRICT, INTERSTITIAL_RESUME_OFFSET,
34    INTERSTITIAL_SNAP, MediaPlaylist,
35};
36
37/// The `DURATION` attribute (§4.4.5.1) this crate's errors name.
38const DURATION_ATTRIBUTE: &str = "DURATION";
39
40/// `CLASS` value for an Interstitial `EXT-X-DATERANGE` (Appendix D §D.2).
41pub const INTERSTITIAL_CLASS: &str = broadcast_hls::INTERSTITIAL_CLASS;
42
43/// A rendered Interstitial `EXT-X-DATERANGE` tag: an [`AdBreakDecision`]
44/// plus the base-tag scheduling fields (`START-DATE`, `DURATION`, RFC 8216bis
45/// §4.4.5.1) the decision itself does not carry.
46#[derive(Debug, Clone, PartialEq)]
47pub struct InterstitialDateRange {
48    /// `ID` (quoted).
49    pub id: String,
50    /// `START-DATE` (quoted, ISO-8601/RFC3339) — caller-supplied; this
51    /// module does no wall-clock math.
52    pub start_date: String,
53    /// `DURATION` in seconds, if known.
54    pub duration: Option<f64>,
55    /// `X-ASSET-URI` or `X-ASSET-LIST`.
56    pub asset: AssetSource,
57    /// `X-RESUME-OFFSET` in seconds.
58    pub resume_offset: Option<f64>,
59    /// `X-PLAYOUT-LIMIT` in seconds.
60    pub playout_limit: Option<f64>,
61    /// `X-SNAP` identifiers.
62    pub snap: Vec<SnapMode>,
63    /// `X-RESTRICT` identifiers.
64    pub restrict: Vec<RestrictMode>,
65}
66
67impl InterstitialDateRange {
68    /// Build from an [`AdBreakDecision`] plus the two base-tag fields it
69    /// doesn't carry.
70    pub fn from_decision(
71        decision: &AdBreakDecision,
72        start_date: impl Into<String>,
73        duration: Option<f64>,
74    ) -> Self {
75        InterstitialDateRange {
76            id: decision.id.clone(),
77            start_date: start_date.into(),
78            duration,
79            asset: decision.asset.clone(),
80            resume_offset: decision.resume_offset,
81            playout_limit: decision.playout_limit,
82            snap: decision.snap.clone(),
83            restrict: decision.restrict.clone(),
84        }
85    }
86
87    /// Render one `#EXT-X-DATERANGE:` line through
88    /// [`broadcast_hls::DateRange`], whose new-tag attribute order (`ID`,
89    /// `CLASS`, `START-DATE`, `DURATION`, `X-ASSET-URI`/`X-ASSET-LIST`,
90    /// `X-RESUME-OFFSET`, `X-PLAYOUT-LIMIT`, `X-SNAP`, `X-RESTRICT`) is the
91    /// one [`Self::parse_tag_line`] round-trips.
92    ///
93    /// Every attribute goes through that typed setter, so `id`, `start_date`
94    /// and the asset URI/list — frequently supplied (directly or indirectly)
95    /// by an [`crate::decision::AdDecisionProvider`], a third-party
96    /// ad-decision service — can never terminate the attribute list and
97    /// inject a tag line, whatever they carry. Every failure is therefore
98    /// [`Error::HlsAttrValue`], as it always has been.
99    ///
100    /// A `duration` or `playout_limit` that is not finite and non-negative,
101    /// and a `resume_offset` that is not finite, is
102    /// [`Error::InvalidDuration`] (RFC 8216bis Appendix D; audit
103    /// r14-SSAI-W4).
104    pub fn to_tag_line(&self) -> Result<String> {
105        if let Some(duration) = self.duration
106            && !(duration.is_finite() && duration >= 0.0)
107        {
108            return Err(Error::InvalidDuration {
109                what: DURATION_ATTRIBUTE,
110                value: duration,
111            });
112        }
113        if let Some(offset) = self.resume_offset
114            && !offset.is_finite()
115        {
116            return Err(Error::InvalidDuration {
117                what: INTERSTITIAL_RESUME_OFFSET,
118                value: offset,
119            });
120        }
121        if let Some(limit) = self.playout_limit
122            && !(limit.is_finite() && limit >= 0.0)
123        {
124            return Err(Error::InvalidDuration {
125                what: INTERSTITIAL_PLAYOUT_LIMIT,
126                value: limit,
127            });
128        }
129        self.tag_line().map_err(Error::HlsAttrValue)
130    }
131
132    fn tag_line(&self) -> core::result::Result<String, broadcast_hls::Error> {
133        let mut range = DateRange::from_parts(
134            self.id.as_str(),
135            Some(INTERSTITIAL_CLASS),
136            self.start_date.as_str(),
137            self.duration.map(DecimalSeconds::new).transpose()?,
138            None,
139            None,
140        )?;
141
142        let uri = match &self.asset {
143            AssetSource::Uri(uri) => (INTERSTITIAL_ASSET_URI, uri),
144            AssetSource::List(uri) => (INTERSTITIAL_ASSET_LIST, uri),
145        };
146        range.set_quoted_client_attr(uri.0, Some(uri.1.clone()))?;
147        if let Some(offset) = self.resume_offset {
148            range.set_float_client_attr_text(
149                INTERSTITIAL_RESUME_OFFSET,
150                Some(seconds_text(offset)),
151            )?;
152        }
153        if let Some(limit) = self.playout_limit {
154            range.set_float_client_attr_text(
155                INTERSTITIAL_PLAYOUT_LIMIT,
156                Some(seconds_text(limit)),
157            )?;
158        }
159        let snap: Vec<&str> = self.snap.iter().map(SnapMode::token).collect();
160        range.set_identifier_list(INTERSTITIAL_SNAP, Some(&snap))?;
161        let restrict: Vec<&str> = self.restrict.iter().map(RestrictMode::token).collect();
162        range.set_identifier_list(INTERSTITIAL_RESTRICT, Some(&restrict))?;
163        range.to_tag_line()
164    }
165
166    /// Parse one `#EXT-X-DATERANGE:` line with
167    /// `CLASS="com.apple.hls.interstitial"`, read through
168    /// [`broadcast_hls::DateRange::parse_tag_line`]. Errors with
169    /// [`Error::TagParse`] if the `CLASS` doesn't match (or is missing)
170    /// or `START-DATE` is absent, and [`Error::InvalidAssetSource`] if
171    /// neither or both of `X-ASSET-URI`/`X-ASSET-LIST` are present; any
172    /// malformed attribute the tag model refuses is [`Error::HlsAttrValue`].
173    /// A negative `X-PLAYOUT-LIMIT`, which this crate's `playout_limit` never
174    /// carries, reads as absent.
175    pub fn parse_tag_line(s: &str) -> Result<Self> {
176        let range = DateRange::parse_tag_line(s)?;
177        if range.class() != Some(INTERSTITIAL_CLASS) {
178            return Err(Error::TagParse(
179                "not an Interstitial EXT-X-DATERANGE (CLASS missing or mismatched)".to_string(),
180            ));
181        }
182        let asset = match (
183            range.client_attr_str(INTERSTITIAL_ASSET_URI),
184            range.client_attr_str(INTERSTITIAL_ASSET_LIST),
185        ) {
186            (Some(uri), None) => AssetSource::Uri(uri.to_string()),
187            (None, Some(list)) => AssetSource::List(list.to_string()),
188            _ => return Err(Error::InvalidAssetSource),
189        };
190        let start_date = range
191            .start()
192            .ok_or_else(|| Error::TagParse("missing START-DATE".to_string()))?
193            .render()
194            .to_string();
195        Ok(InterstitialDateRange {
196            id: range.id().to_string(),
197            start_date,
198            duration: range.duration().map(DecimalSeconds::get),
199            asset,
200            resume_offset: range.float_client_attr(INTERSTITIAL_RESUME_OFFSET),
201            playout_limit: non_negative(range.float_client_attr(INTERSTITIAL_PLAYOUT_LIMIT)),
202            snap: range
203                .identifier_list(INTERSTITIAL_SNAP)
204                .into_iter()
205                .map(|token| match token {
206                    "OUT" => SnapMode::Out,
207                    "IN" => SnapMode::In,
208                    other => SnapMode::Other(other.to_string()),
209                })
210                .collect(),
211            restrict: range
212                .identifier_list(INTERSTITIAL_RESTRICT)
213                .into_iter()
214                .map(|token| match token {
215                    "SKIP" => RestrictMode::Skip,
216                    "JUMP" => RestrictMode::Jump,
217                    other => RestrictMode::Other(other.to_string()),
218                })
219                .collect(),
220        })
221    }
222}
223
224/// A `PLAYOUT-LIMIT` the tag model stores but this crate's own contract
225/// cannot hold: a negative §D.2 exit point is not one.
226fn non_negative(value: Option<f64>) -> Option<f64> {
227    value.filter(|v| *v >= 0.0)
228}
229
230/// Integers up to 2^53 are exactly representable in an `f64`; beyond it the
231/// saturating `as i64` cast no longer round-trips.
232const EXACT_INT_LIMIT: f64 = 9_007_199_254_740_992.0;
233
234/// A finite seconds value without a trailing `.0`, matching the spec
235/// examples (`X-RESUME-OFFSET=0`). Avoids `f64::fract()` (a std-only
236/// intrinsic, and this crate is `no_std`); past [`EXACT_INT_LIMIT`] the
237/// shortest exact spelling is used instead of a saturated integer.
238fn seconds_text(v: f64) -> String {
239    if v.abs() < EXACT_INT_LIMIT {
240        let trunc = v as i64;
241        if v == trunc as f64 {
242            return format!("{trunc}");
243        }
244    }
245    format!("{v}")
246}
247
248/// `#EXT-X-PROGRAM-DATE-TIME` (RFC 8216bis §4.4.4.6) — the tag an
249/// `EXT-X-DATERANGE` playlist must contain at least one of (§4.4.5.1).
250const PDT_TAG: &str = "#EXT-X-PROGRAM-DATE-TIME:";
251
252/// Whether `base` carries an `EXT-X-PROGRAM-DATE-TIME` (a segment's
253/// `pre_tags`, where [`MediaPlaylist::parse`] files it, or the
254/// playlist-level `extra_tags`).
255fn has_program_date_time(base: &MediaPlaylist) -> bool {
256    base.extra_tags.iter().any(|t| t.starts_with(PDT_TAG))
257        || base.segments.iter().any(|s| {
258            s.program_date_time.is_some() || s.pre_tags.iter().any(|t| t.starts_with(PDT_TAG))
259        })
260}
261
262/// Clone `base` and append `active`'s rendered tag line (if any) to
263/// [`MediaPlaylist::extra_tags`] — the per-session playlist for one viewer.
264/// `base` is otherwise untouched: SSAI needs no per-viewer copy of the media
265/// itself (issue #929 design decision), only of this one tag line.
266///
267/// Fallible (issue #1140 / audit r14-SSAI-W1): an ad-decision-supplied value
268/// that fails [`InterstitialDateRange::to_tag_line`]'s validation is an
269/// error from this entry point, not a line silently dropped or injected.
270/// Also [`Error::MissingProgramDateTime`] when `active` is `Some` but
271/// `base` has no `EXT-X-PROGRAM-DATE-TIME` (RFC 8216bis §4.4.5.1; audit
272/// r14-SSAI-W3, issue #1125).
273///
274/// This deep-clones every segment per call; a per-viewer hot path should
275/// build one [`SessionPlaylistBase`] per base-playlist reload instead.
276pub fn render_session_playlist(
277    base: &MediaPlaylist,
278    active: Option<&InterstitialDateRange>,
279) -> Result<MediaPlaylist> {
280    let mut out = base.clone();
281    if let Some(dr) = active {
282        if !has_program_date_time(base) {
283            return Err(Error::MissingProgramDateTime);
284        }
285        out.extra_tags.push(dr.to_tag_line()?);
286    }
287    Ok(out)
288}
289
290/// A base playlist rendered **once**, so each viewer's per-session playlist
291/// costs one tag line plus a copy of the text — not a deep clone of every
292/// segment and a full re-serialisation per viewer per reload (audit
293/// r14-SSAI-O1, issue #1125).
294///
295/// The tag line is spliced in immediately before the first `#EXT-X-PART:` or
296/// `#EXTINF:` line, whichever comes first — i.e. before the first segment's
297/// part/`EXTINF` group, never between a segment's parts and its `EXTINF` (an
298/// `EXT-X-DATERANGE` is not positional within the playlist, RFC 8216bis
299/// §4.4.5.1) — or before `#EXT-X-ENDLIST` / at the end when the base has
300/// neither.
301#[derive(Debug, Clone)]
302pub struct SessionPlaylistBase {
303    head: String,
304    tail: String,
305    has_pdt: bool,
306}
307
308impl SessionPlaylistBase {
309    /// Render `base` once. Errors as [`MediaPlaylist::to_m3u8`].
310    pub fn new(base: &MediaPlaylist) -> Result<Self> {
311        let text = base.to_m3u8()?;
312        // `#EXT-X-PART:` (not `#EXT-X-PART-INF:`) or `#EXTINF:`, first of either.
313        let first_group = ["\n#EXT-X-PART:", "\n#EXTINF:"]
314            .iter()
315            .filter_map(|tag| text.find(tag))
316            .min();
317        let at = first_group
318            .or_else(|| text.rfind("\n#EXT-X-ENDLIST"))
319            .map_or(text.len(), |i| i + 1);
320        let (head, tail) = text.split_at(at);
321        Ok(SessionPlaylistBase {
322            head: head.to_string(),
323            tail: tail.to_string(),
324            has_pdt: has_program_date_time(base),
325        })
326    }
327
328    /// The viewer-independent playlist text (no break).
329    #[cfg(test)]
330    pub(crate) fn render_plain(&self) -> String {
331        let mut out = String::with_capacity(self.head.len() + self.tail.len());
332        out.push_str(&self.head);
333        out.push_str(&self.tail);
334        out
335    }
336
337    /// Append one viewer's playlist to `out`: the base text, with
338    /// `active`'s tag line spliced in. Errors as [`render_session_playlist`];
339    /// on error nothing is appended.
340    pub fn render_into(
341        &self,
342        out: &mut String,
343        active: Option<&InterstitialDateRange>,
344    ) -> Result<()> {
345        let line = match active {
346            Some(dr) => {
347                if !self.has_pdt {
348                    return Err(Error::MissingProgramDateTime);
349                }
350                Some(dr.to_tag_line()?)
351            }
352            None => None,
353        };
354        out.push_str(&self.head);
355        if let Some(line) = line {
356            out.push_str(&line);
357            out.push('\n');
358        }
359        out.push_str(&self.tail);
360        Ok(())
361    }
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367    use crate::error::Error;
368    use alloc::format;
369
370    fn test_limits() -> broadcast_hls::limits::Limits {
371        broadcast_hls::limits::Limits {
372            max_playlist_bytes: 4 << 20,
373            max_segments: 1_000_000,
374            max_segment_bytes: 64 << 20,
375        }
376    }
377
378    const TAG: &str = "#EXT-X-DATERANGE:";
379    use alloc::vec;
380    use broadcast_hls::{DecimalSeconds, MediaSegment};
381
382    fn sample() -> InterstitialDateRange {
383        InterstitialDateRange {
384            id: "ad1".to_string(),
385            start_date: "2020-01-02T21:55:44.000Z".to_string(),
386            duration: Some(15.0),
387            asset: AssetSource::Uri("http://example.com/ad1.m3u8".to_string()),
388            resume_offset: Some(0.0),
389            playout_limit: None,
390            snap: Vec::new(),
391            restrict: vec![RestrictMode::Skip, RestrictMode::Jump],
392        }
393    }
394
395    #[test]
396    fn tag_line_matches_the_spec_example_shape() {
397        // Appendix D §D.6 example, reproduced with this crate's own types.
398        let line = sample().to_tag_line().unwrap();
399        assert!(line.starts_with(TAG));
400        assert!(line.contains(r#"CLASS="com.apple.hls.interstitial""#));
401        assert!(line.contains(r#"X-ASSET-URI="http://example.com/ad1.m3u8""#));
402        assert!(line.contains("X-RESUME-OFFSET=0"));
403        assert!(line.contains(r#"X-RESTRICT="SKIP,JUMP""#));
404    }
405
406    #[test]
407    fn tag_line_round_trips() {
408        let dr = sample();
409        let line = dr.to_tag_line().unwrap();
410        let back = InterstitialDateRange::parse_tag_line(&line).unwrap();
411        assert_eq!(back, dr);
412    }
413
414    #[test]
415    fn asset_list_variant_round_trips() {
416        let dr = InterstitialDateRange {
417            id: "ad2".to_string(),
418            start_date: "2020-01-02T21:55:44.000Z".to_string(),
419            duration: Some(30.0),
420            asset: AssetSource::List("http://example.com/adv.json".to_string()),
421            resume_offset: None,
422            playout_limit: Some(20.0),
423            snap: vec![SnapMode::Out, SnapMode::In],
424            restrict: Vec::new(),
425        };
426        let line = dr.to_tag_line().unwrap();
427        assert!(line.contains(r#"X-ASSET-LIST="http://example.com/adv.json""#));
428        assert!(line.contains(r#"X-SNAP="OUT,IN""#));
429        let back = InterstitialDateRange::parse_tag_line(&line).unwrap();
430        assert_eq!(back, dr);
431    }
432
433    /// Mutating any field must change the rendered output — the anti-cheat
434    /// property a raw-passthrough (source-span-echoing) serializer cannot
435    /// satisfy, since an echo can't reflect a mutation it didn't store.
436    #[test]
437    fn mutating_a_field_changes_the_output() {
438        let base = sample();
439        let base_line = base.to_tag_line().unwrap();
440
441        let mut mutated = base.clone();
442        mutated.id = "different-id".to_string();
443        assert_ne!(mutated.to_tag_line().unwrap(), base_line);
444
445        let mut mutated = base.clone();
446        mutated.resume_offset = Some(5.0);
447        assert_ne!(mutated.to_tag_line().unwrap(), base_line);
448
449        let mut mutated = base.clone();
450        mutated.restrict = vec![RestrictMode::Skip];
451        assert_ne!(mutated.to_tag_line().unwrap(), base_line);
452
453        let mut mutated = base;
454        mutated.asset = AssetSource::Uri("http://example.com/different.m3u8".to_string());
455        assert_ne!(mutated.to_tag_line().unwrap(), base_line);
456    }
457
458    /// Audit r14-SSAI-W1: a `"`, CR or LF in an ad-decision-supplied value
459    /// (here `X-ASSET-URI`) must be rejected, not injected into the
460    /// playlist as a broken attribute list or an extra tag line.
461    #[test]
462    fn to_tag_line_rejects_injection_in_asset_uri() {
463        let mut dr = sample();
464        dr.asset = AssetSource::Uri("http://example.com/ad1.m3u8\"\r\n#EXT-X-ENDLIST".to_string());
465        assert!(matches!(
466            dr.to_tag_line().unwrap_err(),
467            Error::HlsAttrValue(_)
468        ));
469    }
470
471    #[test]
472    fn to_tag_line_rejects_injection_in_id() {
473        let mut dr = sample();
474        dr.id = "ad\"1".to_string();
475        assert!(matches!(
476            dr.to_tag_line().unwrap_err(),
477            Error::HlsAttrValue(_)
478        ));
479    }
480
481    /// Audit r14-SSAI-W4: NaN/infinite/negative durations must be rejected,
482    /// never rendered as the bare token `NaN`/`inf`/a negative number.
483    #[test]
484    fn to_tag_line_rejects_non_finite_and_negative_durations() {
485        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0] {
486            let mut dr = sample();
487            dr.duration = Some(bad);
488            let err = dr.to_tag_line().unwrap_err();
489            assert!(
490                matches!(err, Error::HlsAttrValue(_) | Error::InvalidDuration { .. }),
491                "duration {bad} should be rejected, got {err:?}"
492            );
493
494            if bad != -1.0 {
495                let mut dr = sample();
496                dr.resume_offset = Some(bad);
497                assert!(matches!(
498                    dr.to_tag_line().unwrap_err(),
499                    Error::InvalidDuration { .. }
500                ));
501            }
502
503            let mut dr = sample();
504            dr.playout_limit = Some(bad);
505            assert!(matches!(
506                dr.to_tag_line().unwrap_err(),
507                Error::InvalidDuration { .. }
508            ));
509        }
510    }
511
512    #[test]
513    fn to_tag_line_rejects_unsafe_other_list_tokens() {
514        for bad in ["a\"b", "a,b", "a\rb", "a\nb"] {
515            let mut dr = sample();
516            dr.snap = vec![SnapMode::Other(bad.to_string())];
517            assert!(
518                matches!(
519                    dr.to_tag_line().unwrap_err(),
520                    Error::HlsAttrValue(_) | Error::TagParse(_)
521                ),
522                "snap {bad:?}"
523            );
524            let mut dr = sample();
525            dr.restrict = vec![RestrictMode::Other(bad.to_string())];
526            assert!(
527                matches!(
528                    dr.to_tag_line().unwrap_err(),
529                    Error::HlsAttrValue(_) | Error::TagParse(_)
530                ),
531                "restrict {bad:?}"
532            );
533        }
534        let mut dr = sample();
535        dr.snap = vec![SnapMode::Other("X-CUSTOM".to_string())];
536        assert!(dr.to_tag_line().is_ok());
537    }
538
539    #[test]
540    fn snap_and_restrict_lists_trim_tokens_and_drop_empty_ones() {
541        let line = sample().to_tag_line().unwrap();
542        let with = |attr: &str| {
543            let base = line.replace(",X-RESTRICT=\"SKIP,JUMP\"", "");
544            format!("{base},{attr}")
545        };
546        let dr = InterstitialDateRange::parse_tag_line(&with("X-SNAP=\" OUT , IN \"")).unwrap();
547        assert_eq!(dr.snap, vec![SnapMode::Out, SnapMode::In]);
548        let dr = InterstitialDateRange::parse_tag_line(&with("X-SNAP=\"OUT,\"")).unwrap();
549        assert_eq!(dr.snap, vec![SnapMode::Out]);
550        let dr =
551            InterstitialDateRange::parse_tag_line(&with("X-RESTRICT=\" SKIP , JUMP \"")).unwrap();
552        assert_eq!(dr.restrict, vec![RestrictMode::Skip, RestrictMode::Jump]);
553        let dr = InterstitialDateRange::parse_tag_line(&with("X-RESTRICT=\"SKIP,\"")).unwrap();
554        assert_eq!(dr.restrict, vec![RestrictMode::Skip]);
555    }
556
557    #[test]
558    fn negative_resume_offset_round_trips() {
559        let mut dr = sample();
560        dr.resume_offset = Some(-5.0);
561        let line = dr.to_tag_line().unwrap();
562        assert!(line.contains("X-RESUME-OFFSET=-5"), "{line}");
563        let back = InterstitialDateRange::parse_tag_line(&line).unwrap();
564        assert_eq!(back.resume_offset, Some(-5.0));
565    }
566
567    #[test]
568    fn parse_accepts_negative_resume_offset() {
569        let s = "#EXT-X-DATERANGE:ID=\"a\",CLASS=\"com.apple.hls.interstitial\",\
570                 START-DATE=\"2020-01-02T21:55:44.000Z\",X-ASSET-URI=\"http://x/a\",\
571                 X-RESUME-OFFSET=-3";
572        let parsed = InterstitialDateRange::parse_tag_line(s).unwrap();
573        assert_eq!(parsed.resume_offset, Some(-3.0));
574    }
575
576    #[test]
577    fn negative_playout_limit_is_still_rejected() {
578        let mut dr = sample();
579        dr.playout_limit = Some(-1.0);
580        assert!(matches!(
581            dr.to_tag_line().unwrap_err(),
582            Error::InvalidDuration { .. }
583        ));
584    }
585
586    #[test]
587    fn duration_beyond_exact_integer_range_renders_exactly() {
588        let mut dr = sample();
589        dr.duration = Some(9_223_372_036_854_775_808.0);
590        let line = dr.to_tag_line().unwrap();
591        assert!(!line.contains("DURATION=9223372036854775807"), "{line}");
592        let back = InterstitialDateRange::parse_tag_line(&line).unwrap();
593        assert_eq!(back.duration, Some(9_223_372_036_854_775_808.0));
594    }
595
596    #[test]
597    fn parse_rejects_non_finite_duration() {
598        let line = "#EXT-X-DATERANGE:ID=\"x\",CLASS=\"com.apple.hls.interstitial\",\
599                     START-DATE=\"2020-01-01T00:00:00Z\",X-ASSET-URI=\"http://x/a.m3u8\",\
600                     DURATION=nan";
601        assert!(matches!(
602            InterstitialDateRange::parse_tag_line(line).unwrap_err(),
603            Error::HlsAttrValue(
604                broadcast_hls::Error::InvalidDateRange {
605                    reason: broadcast_hls::DateRangeError::InvalidDurationValue,
606                    ..
607                } | broadcast_hls::Error::InvalidDecimalSeconds(_)
608            )
609        ));
610    }
611
612    #[test]
613    fn parse_rejects_wrong_or_missing_class() {
614        let line = "#EXT-X-DATERANGE:ID=\"x\",START-DATE=\"2020-01-01T00:00:00Z\",\
615                     X-ASSET-URI=\"http://x/a.m3u8\"";
616        let err = InterstitialDateRange::parse_tag_line(line).unwrap_err();
617        assert!(matches!(err, Error::TagParse(_)));
618    }
619
620    #[test]
621    fn parse_rejects_both_or_neither_asset_source() {
622        let both = "#EXT-X-DATERANGE:ID=\"x\",CLASS=\"com.apple.hls.interstitial\",\
623                     START-DATE=\"2020-01-01T00:00:00Z\",X-ASSET-URI=\"http://x/a.m3u8\",\
624                     X-ASSET-LIST=\"http://x/list.json\"";
625        assert!(matches!(
626            InterstitialDateRange::parse_tag_line(both).unwrap_err(),
627            Error::InvalidAssetSource
628        ));
629
630        let neither = "#EXT-X-DATERANGE:ID=\"x\",CLASS=\"com.apple.hls.interstitial\",\
631                        START-DATE=\"2020-01-01T00:00:00Z\"";
632        assert!(matches!(
633            InterstitialDateRange::parse_tag_line(neither).unwrap_err(),
634            Error::InvalidAssetSource
635        ));
636    }
637
638    #[test]
639    fn render_session_playlist_appends_only_for_the_active_session() {
640        let mut base = MediaPlaylist {
641            target_duration: 6,
642            ..Default::default()
643        };
644        base.segments.push(MediaSegment {
645            duration: DecimalSeconds::new(6.0).unwrap(),
646            uri: "main.ts".to_string(),
647            ..Default::default()
648        });
649
650        base.segments[0].pre_tags = vec![PDT_LINE.to_string()];
651
652        let dr = sample();
653        let with_break = render_session_playlist(&base, Some(&dr)).unwrap();
654        let without_break = render_session_playlist(&base, None).unwrap();
655
656        assert!(with_break.to_m3u8().unwrap().contains("X-ASSET-URI"));
657        assert!(!without_break.to_m3u8().unwrap().contains("X-ASSET-URI"));
658        // The base playlist itself (what every other viewer renders from)
659        // is untouched.
660        assert!(base.extra_tags.is_empty());
661        // Only the tag line differs; the segment list is byte-identical.
662        assert_eq!(with_break.segments, without_break.segments);
663    }
664
665    const PDT_LINE: &str = "#EXT-X-PROGRAM-DATE-TIME:2020-01-02T21:55:40.000Z";
666
667    fn base_with_segments(n: usize, pdt: bool) -> MediaPlaylist {
668        let mut base = MediaPlaylist {
669            target_duration: 6,
670            ..Default::default()
671        };
672        for i in 0..n {
673            base.segments.push(MediaSegment {
674                duration: DecimalSeconds::new(6.0).unwrap(),
675                uri: format!("main{i}.ts"),
676                pre_tags: if pdt && i == 0 {
677                    vec![PDT_LINE.to_string()]
678                } else {
679                    Vec::new()
680                },
681                ..Default::default()
682            });
683        }
684        base
685    }
686
687    /// Audit r14-SSAI-W3: a DATERANGE needs a PDT in the playlist
688    /// (RFC 8216bis §4.4.5.1); both render paths refuse without one, and
689    /// accept the PDT wherever the base carries it.
690    #[test]
691    fn daterange_without_pdt_is_an_error_on_both_paths() {
692        let dr = sample();
693        let no_pdt = base_with_segments(2, false);
694        assert!(matches!(
695            render_session_playlist(&no_pdt, Some(&dr)).unwrap_err(),
696            Error::MissingProgramDateTime
697        ));
698        let b = SessionPlaylistBase::new(&no_pdt).unwrap();
699        let mut out = String::new();
700        assert!(matches!(
701            b.render_into(&mut out, Some(&dr)).unwrap_err(),
702            Error::MissingProgramDateTime
703        ));
704        assert!(out.is_empty(), "nothing appended on error");
705        // No break requested: no DATERANGE emitted, so no PDT needed.
706        assert!(render_session_playlist(&no_pdt, None).is_ok());
707        b.render_into(&mut out, None).unwrap();
708        assert_eq!(out, no_pdt.to_m3u8().unwrap());
709
710        // PDT as a playlist-level extra tag also satisfies the rule.
711        let mut extra = base_with_segments(1, false);
712        extra.extra_tags.push(PDT_LINE.to_string());
713        assert!(render_session_playlist(&extra, Some(&dr)).is_ok());
714        assert!(
715            SessionPlaylistBase::new(&extra)
716                .unwrap()
717                .render_into(&mut String::new(), Some(&dr))
718                .is_ok()
719        );
720    }
721
722    /// The spliced render must contain exactly the base text plus one tag
723    /// line, placed before the first EXTINF, and the result must reparse.
724    #[test]
725    fn session_playlist_base_splices_one_line_before_the_first_extinf() {
726        let base = base_with_segments(3, true);
727        let dr = sample();
728        let plain = base.to_m3u8().unwrap();
729        let b = SessionPlaylistBase::new(&base).unwrap();
730        assert_eq!(b.render_plain(), plain);
731
732        let mut out = String::new();
733        b.render_into(&mut out, Some(&dr)).unwrap();
734        let line = dr.to_tag_line().unwrap();
735        let expected = plain.replacen("#EXTINF:", &format!("{line}\n#EXTINF:"), 1);
736        assert_eq!(out, expected);
737        assert_eq!(out.lines().filter(|l| l.starts_with(TAG)).count(), 1);
738        let reparsed = MediaPlaylist::parse(&out, &test_limits()).unwrap();
739        assert_eq!(reparsed.segments.len(), 3);
740
741        // An injection attempt errors and appends nothing.
742        let mut bad = sample();
743        bad.asset = AssetSource::Uri("x\"\n#EXT-X-ENDLIST".to_string());
744        let mut out2 = String::from("keep");
745        assert!(b.render_into(&mut out2, Some(&bad)).is_err());
746        assert_eq!(out2, "keep");
747    }
748
749    /// A segment-less base with `#EXT-X-ENDLIST` must get the tag before it.
750    #[test]
751    fn session_playlist_base_without_segments_inserts_before_endlist() {
752        let mut base = MediaPlaylist {
753            target_duration: 6,
754            endlist: true,
755            ..Default::default()
756        };
757        base.extra_tags.push(PDT_LINE.to_string());
758        let b = SessionPlaylistBase::new(&base).unwrap();
759        let mut out = String::new();
760        b.render_into(&mut out, Some(&sample())).unwrap();
761        let lines: Vec<&str> = out.lines().collect();
762        let n = lines.len();
763        assert_eq!(lines[n - 1], "#EXT-X-ENDLIST");
764        assert!(lines[n - 2].starts_with(TAG));
765    }
766
767    /// An LL-HLS base: the first segment's `EXT-X-PART` lines precede its
768    /// `EXTINF`, so the DATERANGE must land before the first PART, not between
769    /// a segment's parts and its `EXTINF`.
770    #[test]
771    fn low_latency_base_gets_the_tag_before_the_first_part() {
772        use broadcast_hls::{LowLatencyConfig, PartSpec};
773        let mut base = base_with_segments(2, true);
774        for seg in &mut base.segments {
775            seg.parts = vec![
776                PartSpec::new(
777                    format!("{}.0.m4s", seg.uri),
778                    DecimalSeconds::new(3.0).unwrap(),
779                ),
780                PartSpec::new(
781                    format!("{}.1.m4s", seg.uri),
782                    DecimalSeconds::new(3.0).unwrap(),
783                ),
784            ];
785        }
786        base.low_latency =
787            Some(LowLatencyConfig::default().with_part_target(DecimalSeconds::new(3.0).unwrap()));
788        let plain = base.to_m3u8().unwrap();
789        let first_part = plain.find("#EXT-X-PART:").expect("the base has parts");
790        let first_extinf = plain.find("#EXTINF:").unwrap();
791        assert!(
792            first_part < first_extinf,
793            "premise: parts precede EXTINF\n{plain}"
794        );
795
796        let mut out = String::new();
797        SessionPlaylistBase::new(&base)
798            .unwrap()
799            .render_into(&mut out, Some(&sample()))
800            .unwrap();
801        let tag = out.find(TAG).expect("tag present");
802        let part = out.find("#EXT-X-PART:").unwrap();
803        let extinf = out.find("#EXTINF:").unwrap();
804        assert!(tag < part && part < extinf, "{out}");
805        assert_eq!(out.matches(TAG).count(), 1);
806        // The PART-INF header line is not mistaken for a part.
807        assert!(out.find("#EXT-X-PART-INF").is_none_or(|i| i < tag), "{out}");
808        MediaPlaylist::parse(&out, &test_limits()).expect("the spliced LL playlist parses");
809    }
810
811    #[test]
812    fn parse_tag_line_rejects_malformed_attribute_list_unterminated_quote() {
813        let line = "#EXT-X-DATERANGE:ID=\"x";
814        assert!(matches!(
815            InterstitialDateRange::parse_tag_line(line).unwrap_err(),
816            Error::HlsAttrValue(
817                broadcast_hls::Error::UnterminatedQuotedString { .. }
818                    | broadcast_hls::Error::InvalidAttributeList {
819                        reason: broadcast_hls::AttributeListError::UnterminatedQuote,
820                        ..
821                    }
822            )
823        ));
824    }
825
826    #[test]
827    fn parse_tag_line_rejects_malformed_attribute_list_duplicate_key() {
828        let line = "#EXT-X-DATERANGE:ID=\"x\",ID=\"y\",CLASS=\"com.apple.hls.interstitial\",START-DATE=\"2020-01-01T00:00:00Z\",X-ASSET-URI=\"http://x/a.m3u8\"";
829        assert!(matches!(
830            InterstitialDateRange::parse_tag_line(line).unwrap_err(),
831            Error::HlsAttrValue(broadcast_hls::Error::DuplicateAttribute { name, .. }) if name == "ID"
832        ));
833    }
834
835    const LINE_PREFIX: &str = "#EXT-X-DATERANGE:CLASS=\"com.apple.hls.interstitial\",START-DATE=\"2020-01-02T21:55:44.000Z\",X-ASSET-URI=\"https://x/a.m3u8\"";
836
837    #[test]
838    fn parse_rejects_an_unquoted_id_and_a_quoted_duration() {
839        for extra in [",ID=ad1", ",ID=\"ad1\",DURATION=\"15\""] {
840            let line = alloc::format!("{LINE_PREFIX}{extra}");
841            assert!(
842                matches!(
843                    InterstitialDateRange::parse_tag_line(&line),
844                    Err(Error::HlsAttrValue(
845                        broadcast_hls::Error::InvalidDateRange {
846                            reason: broadcast_hls::DateRangeError::WrongAttributeKind
847                                | broadcast_hls::DateRangeError::InvalidDurationValue,
848                            ..
849                        }
850                    ))
851                ),
852                "{line}"
853            );
854        }
855        let ok = alloc::format!("{LINE_PREFIX},ID=\"ad1\",DURATION=15");
856        assert!(InterstitialDateRange::parse_tag_line(&ok).is_ok());
857    }
858
859    #[test]
860    fn unknown_snap_and_restrict_identifiers_round_trip_byte_identical() {
861        let line = alloc::format!(
862            "{LINE_PREFIX},ID=\"ad1\",X-SNAP=\"OUT,SIDEWAYS\",X-RESTRICT=\"SKIP,TELEPORT\""
863        );
864        let parsed = InterstitialDateRange::parse_tag_line(&line).unwrap();
865        assert_eq!(parsed.snap[1], SnapMode::Other("SIDEWAYS".to_string()));
866        let again = parsed.to_tag_line().unwrap();
867        let reparsed = InterstitialDateRange::parse_tag_line(&again).unwrap();
868        assert_eq!(reparsed, parsed);
869        assert!(again.contains("X-SNAP=\"OUT,SIDEWAYS\""), "{again}");
870        assert!(again.contains("X-RESTRICT=\"SKIP,TELEPORT\""), "{again}");
871    }
872}