Skip to main content

ll_hls_runtime/client/
engine.rs

1//! [`LlHlsClient`] — the sans-IO caller-driven engine.
2
3use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
4use alloc::string::{String, ToString};
5use alloc::vec::Vec;
6
7use broadcast_common::Unpackage;
8use transmux::hls::{ByteRange, MapTag, PreloadHintType};
9use transmux::{Fmp4Demux, MediaPlaylist, MediaSegment, OpenSegment, TrackSpec, TsDemux};
10
11use super::action::{Action, BlockingReload, ResourceId};
12use super::error::{Error, Result};
13use super::output::Output;
14use super::url;
15
16/// First byte of every MPEG-2 TS packet (ITU-T H.222.0 / ISO/IEC 13818-1
17/// §2.4.3.2 `sync_byte`). Classic MPEG-TS-segment HLS (HLS v3, RFC 8216 —
18/// the dominant legacy/IPTV form) has no `EXT-X-MAP`/init segment at all:
19/// each `.ts` segment is a self-contained PAT/PMT/PES stream, so this byte
20/// is the only available signal to distinguish one from an fMP4/CMAF
21/// segment (which starts with an ISOBMFF box: `ftyp`/`styp`/`moof`) once the
22/// playlist itself has never advertised a Media Initialization Section.
23const TS_SYNC_BYTE: u8 = 0x47;
24
25/// A driveable, sans-IO Low-Latency HLS (RFC 8216bis) playback client.
26///
27/// `LlHlsClient` never touches a socket or a clock. The caller drives it:
28///
29/// 1. [`LlHlsClient::new`] seeds the first [`Action::FetchPlaylist`]; drain it
30///    with [`LlHlsClient::poll`] and perform the GET.
31/// 2. Feed the response back with [`LlHlsClient::on_playlist`] (playlist) or
32///    [`LlHlsClient::on_resource`] (init/part/segment bytes) —
33///    [`Action::FetchResource`]'s `id` correlates the two.
34/// 3. Drain [`LlHlsClient::poll`] again for the next round of actions (a new
35///    reload, newly discoverable parts, a preload-hint prefetch, ...) and
36///    [`LlHlsClient::next_output`] for newly available [`Output`]s.
37///
38/// # Behaviour
39///
40/// - **Reload scheduling** (issue #717 slice 2): once a playlist advertises
41///   `EXT-X-SERVER-CONTROL`/`EXT-X-PART-INF` **and** the origin's
42///   `CAN-BLOCK-RELOAD` attribute is `YES`
43///   ([`transmux::hls::LowLatencyConfig::can_block_reload`] is `true` —
44///   *not* merely [`transmux::hls::MediaPlaylist::low_latency`] being
45///   `Some`, since an origin may carry parts/PART-INF while still
46///   advertising `CAN-BLOCK-RELOAD=NO`), every reload is a Blocking
47///   Playlist Reload (RFC 8216bis §6.2.5.2) naming the next not-yet-seen
48///   Partial Segment's `_HLS_msn`/`_HLS_part`. Otherwise reloads are plain GETs
49///   paced by an [`Action::WaitMs`] hint derived from `#EXT-X-TARGETDURATION`.
50///   `EXT-X-SKIP`/`CAN-SKIP-UNTIL` Playlist Delta Updates (RFC 8216bis §4.4.5.2)
51///   are requested once a full-playlist baseline exists, and merged back into
52///   a full view before further processing — see `merge_delta` internally.
53/// - **Fetch pipeline** (slice 3): the `EXT-X-PRELOAD-HINT`ed part is fetched
54///   ahead of its own appearance as a numbered `EXT-X-PART`; `BYTERANGE`
55///   parts are supported, including the RFC 8216bis §4.4.4.9 "omitted offset
56///   means immediately after the previous sub-range of the same resource"
57///   rule (tracked per resource URL). The Media Initialization Section
58///   (`EXT-X-MAP`) is fetched once and reused for every following resource
59///   until the map changes.
60/// - **Dedup / coalescing**: once *any* of a segment's parts have been
61///   individually fetched, that segment is never re-fetched whole — when it
62///   later closes (`#EXTINF`+URI), the client only fetches whichever of its
63///   parts (if any) are still missing, and marks the segment "delivered" once
64///   every part is accounted for (fetched, or `GAP=YES`). A playlist whose
65///   segments carry **no** parts at all (a non-LL origin) falls back to
66///   fetching the whole segment resource — the two paths never overlap for a
67///   single segment, so a part's samples are never double-counted against its
68///   parent's.
69/// - **Output adapter** (slice 4): exactly one [`Output::Init`] precedes any
70///   [`Output::Samples`]; parts/segments are demuxed via
71///   [`transmux::Fmp4Demux`] (by concatenating the cached init bytes with the
72///   fetched resource — this crate never re-implements ISOBMFF box parsing,
73///   only reuses transmux's), so `Output::Samples` carries real access units,
74///   not opaque container bytes. `#EXT-X-DISCONTINUITY` on a segment surfaces
75///   as [`Output::Discontinuity`] immediately before that segment's first
76///   samples. **Known limitation**: an in-progress ([`OpenSegment`]) segment
77///   carries no discontinuity flag of its own (only a *closed*
78///   [`MediaSegment`] does) — if every part of a segment was already
79///   delivered while it was still open, a discontinuity revealed only once it
80///   closes is signalled late (after those parts' samples, not before). This
81///   is a gap in the current wire model ([`transmux::hls::OpenSegment`]), not
82///   something this crate can fix locally.
83/// - **Classic MPEG-TS-segment HLS** (issue #760): a playlist that never
84///   advertises an `EXT-X-MAP` (HLS v3, the dominant legacy/IPTV form —
85///   self-contained `.ts` segments carrying their own PAT/PMT/PES, no
86///   separate init resource) routes each fetched Part/Segment through
87///   [`transmux::TsDemux`] instead, content-sniffed by the MPEG-TS sync byte
88///   rather than blocked on an init fetch that will never come. The first
89///   successfully demuxed segment's recovered
90///   [`TrackSpec`]s synthesize the one [`Output::Init`] this crate's contract
91///   requires (via [`transmux::build_init_segment`]) so downstream callers
92///   (e.g. `multimux`'s `HlsPull`, which recovers track specs from
93///   `Output::Init`) need no TS-specific handling of their own. The
94///   fMP4/CMAF plus LL (parts/preload-hint) path above is entirely
95///   unchanged; the two never overlap for a single playlist.
96#[derive(Debug)]
97pub struct LlHlsClient {
98    playlist_url: String,
99
100    pending_actions: VecDeque<Action>,
101    pending_outputs: VecDeque<Output>,
102
103    init_uri: Option<String>,
104    init_bytes: Option<Vec<u8>>,
105    init_emitted: bool,
106    /// Part/Segment resources delivered before the init segment arrived —
107    /// buffered (in arrival order) and replayed once [`Self::init_bytes`] is
108    /// set, so the caller's fetch/response IO can complete in any order
109    /// (a real HTTP client has no reason to serialize on init-first).
110    pending_demux: VecDeque<(ResourceId, Vec<u8>)>,
111
112    requested: BTreeSet<ResourceId>,
113    delivered_parts: BTreeSet<(u64, u64)>,
114    delivered_segments: BTreeSet<u64>,
115    discontinuous_msns: BTreeSet<u64>,
116    discontinuity_emitted: BTreeSet<u64>,
117    byte_range_cursor: BTreeMap<String, u64>,
118
119    outstanding_fetches: u64,
120    saw_endlist: bool,
121    end_emitted: bool,
122    last_full_playlist: Option<MediaPlaylist>,
123}
124
125impl LlHlsClient {
126    /// Create a new client for the Media Playlist at `playlist_url`, seeding
127    /// the first [`Action::FetchPlaylist`] (a plain, non-blocking GET — the
128    /// client does not yet know whether the origin supports blocking reload).
129    pub fn new(playlist_url: impl Into<String>) -> Self {
130        let playlist_url = playlist_url.into();
131        let mut pending_actions = VecDeque::new();
132        pending_actions.push_back(Action::FetchPlaylist {
133            url: playlist_url.clone(),
134            blocking: None,
135            skip: false,
136        });
137        Self {
138            playlist_url,
139            pending_actions,
140            pending_outputs: VecDeque::new(),
141            init_uri: None,
142            init_bytes: None,
143            init_emitted: false,
144            pending_demux: VecDeque::new(),
145            requested: BTreeSet::new(),
146            delivered_parts: BTreeSet::new(),
147            delivered_segments: BTreeSet::new(),
148            discontinuous_msns: BTreeSet::new(),
149            discontinuity_emitted: BTreeSet::new(),
150            byte_range_cursor: BTreeMap::new(),
151            outstanding_fetches: 0,
152            saw_endlist: false,
153            end_emitted: false,
154            last_full_playlist: None,
155        }
156    }
157
158    /// The Media Playlist URL this client is following.
159    pub fn playlist_url(&self) -> &str {
160        &self.playlist_url
161    }
162
163    /// Drain the next IO [`Action`] the caller must perform, if any.
164    pub fn poll(&mut self) -> Option<Action> {
165        self.pending_actions.pop_front()
166    }
167
168    /// Drain the next [`Output`] event, if any.
169    pub fn next_output(&mut self) -> Option<Output> {
170        self.pending_outputs.pop_front()
171    }
172
173    /// Feed a freshly fetched Media Playlist response.
174    ///
175    /// # Errors
176    /// [`Error::PlaylistNotUtf8`] / [`Error::PlaylistParse`] on malformed
177    /// input.
178    pub fn on_playlist(&mut self, bytes: &[u8]) -> Result<()> {
179        let text = core::str::from_utf8(bytes)?;
180        let playlist = MediaPlaylist::parse(text)?;
181        let playlist = self.merge_delta(playlist);
182
183        for (i, seg) in playlist.segments.iter().enumerate() {
184            let msn = playlist.media_sequence + i as u64;
185            self.process_closed_segment(msn, seg)?;
186        }
187
188        let next_msn = playlist.media_sequence + playlist.segments.len() as u64;
189        if let Some(open) = &playlist.open_segment {
190            self.process_open_segment(next_msn, open)?;
191        }
192
193        // Prefer the *open* segment's map when present: it's the most
194        // recent (`#EXT-X-MAP` carries forward, so the open segment's view
195        // is never older than the last closed segment's) and, crucially, is
196        // the only way to learn the init segment's URI at all when NO
197        // segment has closed yet (issue #717 slice 5 fix — previously this
198        // only ever looked at the last *closed* segment's map, so a client
199        // tuning into a stream mid-segment couldn't fetch the init segment,
200        // and therefore couldn't demux any of that segment's parts, until
201        // it closed — needlessly inflating glass-to-glass latency by up to
202        // a full segment duration on every fresh connection).
203        let map = playlist
204            .open_segment
205            .as_ref()
206            .and_then(|o| o.map.as_ref())
207            .or_else(|| playlist.segments.last().and_then(|s| s.map.as_ref()));
208        if let Some(map) = map {
209            self.ensure_init_requested(map)?;
210        }
211
212        if let Some(ll) = &playlist.low_latency {
213            if let Some(hint_uri) = &ll.preload_hint_part {
214                match ll.preload_hint_type {
215                    PreloadHintType::Part => {
216                        let part_idx = playlist
217                            .open_segment
218                            .as_ref()
219                            .map(|o| o.parts.len() as u64)
220                            .unwrap_or(0);
221                        let id = ResourceId::Part {
222                            msn: next_msn,
223                            part: part_idx,
224                        };
225                        let url = url::resolve(&self.playlist_url, hint_uri);
226                        let byte_range = self.resolve_hint_byte_range(&url, ll);
227                        self.request_resource(id, url, byte_range);
228                    }
229                    PreloadHintType::Map => {
230                        let map = MapTag {
231                            uri: hint_uri.clone(),
232                            byte_range: ll.preload_hint_byte_range_length.map(|length| ByteRange {
233                                length,
234                                offset: ll.preload_hint_byte_range_start,
235                            }),
236                        };
237                        self.ensure_init_requested(&map)?;
238                    }
239                }
240            }
241        }
242
243        if playlist.endlist {
244            self.saw_endlist = true;
245        } else {
246            // Issue #717 slice 1 fix: block only when the origin actually
247            // advertises `CAN-BLOCK-RELOAD=YES` — `low_latency.is_some()`
248            // alone is not enough (an origin sending `CAN-BLOCK-RELOAD=NO`
249            // still carries parts/PART-INF, e.g. while ramping up support).
250            let blocking = playlist
251                .low_latency
252                .as_ref()
253                .filter(|ll| ll.can_block_reload)
254                .map(|_| {
255                    let part = playlist
256                        .open_segment
257                        .as_ref()
258                        .map(|o| o.parts.len() as u64)
259                        .unwrap_or(0);
260                    BlockingReload {
261                        msn: next_msn,
262                        part: Some(part),
263                    }
264                });
265            let can_skip = playlist
266                .low_latency
267                .as_ref()
268                .and_then(|ll| ll.can_skip_until)
269                .is_some();
270            let skip = can_skip && self.last_full_playlist.is_some();
271            self.pending_actions.push_back(Action::FetchPlaylist {
272                url: self.playlist_url.clone(),
273                blocking,
274                skip,
275            });
276            if blocking.is_none() {
277                // RFC 8216 §4.3.3.1: a client SHOULD NOT reload more
278                // frequently than once per Target Duration; half that as a
279                // reasonable non-blocking poll cadence.
280                let wait_ms = (u64::from(playlist.target_duration.max(1)) * 1000) / 2;
281                self.pending_actions.push_back(Action::WaitMs(wait_ms));
282            }
283        }
284
285        if playlist.skip.is_none() {
286            self.last_full_playlist = Some(playlist);
287        }
288
289        self.maybe_emit_end_of_stream();
290        Ok(())
291    }
292
293    /// Feed the bytes fetched for a previously requested [`ResourceId`]
294    /// (`init`/part/segment). Part/Segment resources delivered before the
295    /// init segment are buffered internally and demuxed once the init
296    /// arrives — the caller's fetches may complete in any order.
297    ///
298    /// # Errors
299    /// [`Error::UnrequestedResource`] if `id` was never requested (the
300    /// `requested` bookkeeping — or, for `Init`, `init_uri` — has no record
301    /// of it): a caller/driver bug, or a stale/duplicate delivery after the
302    /// client already moved past this id.
303    /// [`Error::Demux`] if `transmux::Fmp4Demux` rejects the concatenation of
304    /// the cached init + `bytes`.
305    pub fn on_resource(&mut self, id: ResourceId, bytes: &[u8]) -> Result<()> {
306        let was_requested = match id {
307            ResourceId::Init => self.init_uri.is_some(),
308            ResourceId::Part { .. } | ResourceId::Segment { .. } => self.requested.contains(&id),
309        };
310        if !was_requested {
311            return Err(Error::UnrequestedResource { id });
312        }
313        self.outstanding_fetches = self.outstanding_fetches.saturating_sub(1);
314        match id {
315            ResourceId::Init => {
316                self.init_bytes = Some(bytes.to_vec());
317                if !self.init_emitted {
318                    self.pending_outputs.push_back(Output::Init(bytes.to_vec()));
319                    self.init_emitted = true;
320                }
321                let buffered: Vec<_> = self.pending_demux.drain(..).collect();
322                for (bid, bbytes) in buffered {
323                    self.finish_media_resource(bid, &bbytes)?;
324                }
325            }
326            ResourceId::Part { .. } | ResourceId::Segment { .. } => {
327                if self.is_ts_segment(bytes) {
328                    // Classic MPEG-TS-segment HLS (issue #760): no init
329                    // resource will ever arrive for this playlist, so demux
330                    // this self-contained TS segment straight away rather
331                    // than buffering it forever waiting for one.
332                    self.finish_ts_resource(id, bytes)?;
333                } else if self.init_bytes.is_none() {
334                    self.pending_demux.push_back((id, bytes.to_vec()));
335                } else {
336                    self.finish_media_resource(id, bytes)?;
337                }
338            }
339        }
340        self.maybe_emit_end_of_stream();
341        Ok(())
342    }
343
344    /// Demux + emit + mark-delivered for a Part/Segment resource, once the
345    /// init segment is known to be available.
346    fn finish_media_resource(&mut self, id: ResourceId, bytes: &[u8]) -> Result<()> {
347        match id {
348            ResourceId::Part { msn, part } => {
349                self.emit_discontinuity_if_needed(msn);
350                self.demux_and_emit(id, bytes)?;
351                self.delivered_parts.insert((msn, part));
352            }
353            ResourceId::Segment { msn } => {
354                self.emit_discontinuity_if_needed(msn);
355                self.demux_and_emit(id, bytes)?;
356                self.delivered_segments.insert(msn);
357            }
358            ResourceId::Init => {}
359        }
360        Ok(())
361    }
362
363    /// The classic-TS-HLS counterpart to [`Self::finish_media_resource`]:
364    /// demux + emit + mark-delivered for a self-contained MPEG-TS Part/
365    /// Segment resource — never buffered pending an init fetch, since
366    /// [`Self::is_ts_segment`] only routes here once this playlist is known
367    /// to advertise no `EXT-X-MAP` at all.
368    fn finish_ts_resource(&mut self, id: ResourceId, bytes: &[u8]) -> Result<()> {
369        match id {
370            ResourceId::Part { msn, part } => {
371                self.emit_discontinuity_if_needed(msn);
372                self.demux_and_emit_ts(id, bytes)?;
373                self.delivered_parts.insert((msn, part));
374            }
375            ResourceId::Segment { msn } => {
376                self.emit_discontinuity_if_needed(msn);
377                self.demux_and_emit_ts(id, bytes)?;
378                self.delivered_segments.insert(msn);
379            }
380            ResourceId::Init => {}
381        }
382        Ok(())
383    }
384
385    /// `true` when `bytes` should be routed to [`Self::finish_ts_resource`]
386    /// (classic MPEG-TS-segment HLS, issue #760) rather than the fMP4/CMAF
387    /// path: this playlist has never advertised an `EXT-X-MAP` (no init
388    /// fetch is outstanding or cached — [`Self::init_uri`] is `None`; by the
389    /// time any Part/Segment fetch response reaches [`Self::on_resource`],
390    /// [`Self::on_playlist`] has already fully processed the playlist that
391    /// requested it, including any map it carries, so this check is never
392    /// stale) **and** `bytes` starts with the MPEG-TS sync byte — an
393    /// fMP4/CMAF resource always starts with an ISOBMFF box
394    /// (`ftyp`/`styp`/`moof`), never [`TS_SYNC_BYTE`].
395    fn is_ts_segment(&self, bytes: &[u8]) -> bool {
396        self.init_uri.is_none() && bytes.first() == Some(&TS_SYNC_BYTE)
397    }
398
399    /// Report that a previously requested [`ResourceId`] (or the playlist
400    /// itself, via [`None`]) failed. Clears the id's "requested" bookkeeping
401    /// so the next [`Self::on_playlist`] call naturally re-requests it (no
402    /// automatic retry timer — the caller drives retry cadence).
403    pub fn on_error(&mut self, id: Option<ResourceId>) {
404        if let Some(id) = id {
405            self.outstanding_fetches = self.outstanding_fetches.saturating_sub(1);
406            match id {
407                ResourceId::Init => self.init_uri = None,
408                other => {
409                    self.requested.remove(&other);
410                }
411            }
412        }
413        self.maybe_emit_end_of_stream();
414    }
415
416    // -- internals ------------------------------------------------------
417
418    /// Reconstruct a full playlist view from an `EXT-X-SKIP` delta update
419    /// (RFC 8216bis §4.4.5.2), by splicing the skipped prefix back in from
420    /// the last full playlist this client observed. Best-effort: if there is
421    /// no cached baseline, or it doesn't cover the skipped range, the delta
422    /// is returned as-is (never an error — "at least don't break").
423    fn merge_delta(&self, playlist: MediaPlaylist) -> MediaPlaylist {
424        let Some(skip) = &playlist.skip else {
425            return playlist;
426        };
427        if skip.skipped_segments == 0 {
428            return playlist;
429        }
430        let Some(prev) = &self.last_full_playlist else {
431            return playlist;
432        };
433        if playlist.media_sequence < prev.media_sequence {
434            return playlist;
435        }
436        let prefix_start = (playlist.media_sequence - prev.media_sequence) as usize;
437        let prefix_end = prefix_start + skip.skipped_segments as usize;
438        let Some(prefix) = prev.segments.get(prefix_start..prefix_end) else {
439            return playlist;
440        };
441        let mut merged = playlist;
442        let mut segments = prefix.to_vec();
443        segments.extend(merged.segments);
444        merged.segments = segments;
445        merged
446    }
447
448    fn process_closed_segment(&mut self, msn: u64, seg: &MediaSegment) -> Result<()> {
449        if seg.discontinuous {
450            self.discontinuous_msns.insert(msn);
451        }
452        if self.delivered_segments.contains(&msn) {
453            return Ok(());
454        }
455        if seg.parts.is_empty() {
456            // Either a genuinely non-LL segment (never had parts), OR an LL
457            // segment whose parts were already fetched individually while it
458            // was still open and whose *closed* rendering simply omits them
459            // — RFC 8216bis does not require a closed segment to keep
460            // listing `#EXT-X-PART` lines, and real origins commonly don't
461            // (e.g. `multimux`'s: `MediaSegment.parts` is always empty for a
462            // closed segment; only the still-open segment carries parts).
463            // Detect the latter via `delivered_parts`: if any part for this
464            // `msn` was ever delivered, every one of its non-`GAP` parts was
465            // already requested while it was open (`process_open_segment`
466            // requests every known part each time it's polled, so by the
467            // time the segment closes none can have been missed) — fetching
468            // the whole segment *as well* would demux and emit its samples a
469            // second time. Caught by `ll-hls-runtime/tests/glass_to_glass.rs`
470            // (issue #717 slice 5): every sample was double-delivered for
471            // the first two segments of a real, live-paced run.
472            let already_have_parts = self
473                .delivered_parts
474                .range((msn, 0)..(msn + 1, 0))
475                .next()
476                .is_some();
477            if already_have_parts {
478                self.delivered_segments.insert(msn);
479                return Ok(());
480            }
481            let id = ResourceId::Segment { msn };
482            if !self.requested.contains(&id) {
483                let url = url::resolve(&self.playlist_url, &seg.uri);
484                let byte_range = self.resolve_byte_range(&url, &seg.byte_range);
485                self.request_resource(id, url, byte_range);
486            }
487            return Ok(());
488        }
489
490        let mut fully_accounted = true;
491        for (i, part) in seg.parts.iter().enumerate() {
492            let i = i as u64;
493            if part.gap || self.delivered_parts.contains(&(msn, i)) {
494                continue;
495            }
496            fully_accounted = false;
497            let id = ResourceId::Part { msn, part: i };
498            if !self.requested.contains(&id) {
499                let url = url::resolve(&self.playlist_url, &part.uri);
500                let byte_range = self.resolve_byte_range(&url, &part.byte_range);
501                self.request_resource(id, url, byte_range);
502            }
503        }
504        if fully_accounted {
505            self.delivered_segments.insert(msn);
506        }
507        Ok(())
508    }
509
510    fn process_open_segment(&mut self, msn: u64, open: &OpenSegment) -> Result<()> {
511        for (i, part) in open.parts.iter().enumerate() {
512            let i = i as u64;
513            if part.gap || self.delivered_parts.contains(&(msn, i)) {
514                continue;
515            }
516            let id = ResourceId::Part { msn, part: i };
517            if !self.requested.contains(&id) {
518                let url = url::resolve(&self.playlist_url, &part.uri);
519                let byte_range = self.resolve_byte_range(&url, &part.byte_range);
520                self.request_resource(id, url, byte_range);
521            }
522        }
523        Ok(())
524    }
525
526    fn ensure_init_requested(&mut self, map: &MapTag) -> Result<()> {
527        let url = url::resolve(&self.playlist_url, &map.uri);
528        if self.init_uri.as_deref() == Some(url.as_str()) {
529            return Ok(());
530        }
531        self.init_uri = Some(url.clone());
532        self.init_bytes = None;
533        self.init_emitted = false;
534        let byte_range = self.resolve_byte_range(&url, &map.byte_range);
535        self.pending_actions.push_back(Action::FetchResource {
536            id: ResourceId::Init,
537            url,
538            byte_range,
539        });
540        self.outstanding_fetches += 1;
541        Ok(())
542    }
543
544    fn request_resource(&mut self, id: ResourceId, url: String, byte_range: Option<(u64, u64)>) {
545        self.requested.insert(id);
546        self.outstanding_fetches += 1;
547        self.pending_actions.push_back(Action::FetchResource {
548            id,
549            url,
550            byte_range,
551        });
552    }
553
554    /// Resolve a `PartSpec`/`MediaSegment`/`MapTag` `BYTERANGE` into an
555    /// absolute `(offset, length)`, honouring the "omitted offset continues
556    /// the previous sub-range of the same resource" rule (tracked per
557    /// resolved URL).
558    fn resolve_byte_range(&mut self, url: &str, br: &Option<ByteRange>) -> Option<(u64, u64)> {
559        let br = br.as_ref()?;
560        let offset = br
561            .offset
562            .unwrap_or_else(|| *self.byte_range_cursor.get(url).unwrap_or(&0));
563        self.byte_range_cursor
564            .insert(url.to_string(), offset + br.length);
565        Some((offset, br.length))
566    }
567
568    fn resolve_hint_byte_range(
569        &mut self,
570        url: &str,
571        ll: &transmux::hls::LowLatencyConfig,
572    ) -> Option<(u64, u64)> {
573        let length = ll.preload_hint_byte_range_length?;
574        let br = ByteRange {
575            length,
576            offset: ll.preload_hint_byte_range_start,
577        };
578        self.resolve_byte_range(url, &Some(br))
579    }
580
581    fn demux_and_emit(&mut self, id: ResourceId, bytes: &[u8]) -> Result<()> {
582        let init = self
583            .init_bytes
584            .as_ref()
585            .ok_or(Error::InitNotYetAvailable { id })?;
586        let mut combined = Vec::with_capacity(init.len() + bytes.len());
587        combined.extend_from_slice(init);
588        combined.extend_from_slice(bytes);
589        let mut demux = Fmp4Demux::new();
590        let media = demux
591            .unpackage(combined.as_slice())
592            .map_err(|source| Error::Demux { id, source })?;
593        for track in media.tracks {
594            if !track.samples.is_empty() {
595                self.pending_outputs.push_back(Output::Samples {
596                    track_id: track.spec.track_id,
597                    samples: track.samples,
598                });
599            }
600        }
601        Ok(())
602    }
603
604    /// The classic-TS-HLS counterpart to [`Self::demux_and_emit`]: demux a
605    /// self-contained MPEG-TS Part/Segment resource via [`TsDemux`] directly
606    /// (no init bytes to concatenate — each `.ts` segment carries its own
607    /// PAT/PMT/PES). On the very first such resource this client demuxes,
608    /// also synthesizes the one [`Output::Init`] the crate's output contract
609    /// requires ("exactly one `Init` precedes any `Samples`") from the
610    /// recovered [`TrackSpec`]s via [`transmux::build_init_segment`] — a real
611    /// `ftyp`+fragmented-`moov`, byte-for-byte demuxable by
612    /// `transmux::Fmp4Demux` like any other init segment, so callers built
613    /// against the fMP4 path (e.g. `multimux`'s `HlsPull`, which recovers
614    /// track specs from `Output::Init`) need no TS-specific handling.
615    fn demux_and_emit_ts(&mut self, id: ResourceId, bytes: &[u8]) -> Result<()> {
616        let mut demux = TsDemux::new();
617        let media = demux
618            .demux(bytes)
619            .map_err(|source| Error::Demux { id, source })?;
620        if !self.init_emitted {
621            let specs: Vec<TrackSpec> = media.tracks.iter().map(|t| t.spec.clone()).collect();
622            let init_bytes = transmux::build_init_segment(&specs, media.movie_timescale)
623                .map_err(|source| Error::Demux { id, source })?;
624            self.pending_outputs.push_back(Output::Init(init_bytes));
625            self.init_emitted = true;
626        }
627        for track in media.tracks {
628            if !track.samples.is_empty() {
629                self.pending_outputs.push_back(Output::Samples {
630                    track_id: track.spec.track_id,
631                    samples: track.samples,
632                });
633            }
634        }
635        Ok(())
636    }
637
638    fn emit_discontinuity_if_needed(&mut self, msn: u64) {
639        if self.discontinuous_msns.contains(&msn) && !self.discontinuity_emitted.contains(&msn) {
640            self.pending_outputs.push_back(Output::Discontinuity);
641            self.discontinuity_emitted.insert(msn);
642        }
643    }
644
645    fn maybe_emit_end_of_stream(&mut self) {
646        if self.saw_endlist && !self.end_emitted && self.outstanding_fetches == 0 {
647            self.pending_outputs.push_back(Output::EndOfStream);
648            self.end_emitted = true;
649        }
650    }
651}
652
653#[cfg(test)]
654mod tests {
655    use super::*;
656
657    // Regression: `on_resource` documents (see `Error::UnrequestedResource`)
658    // that it rejects a `ResourceId` the client never requested, but
659    // previously never actually checked — any bytes for any id (a
660    // caller/driver bug, or a stale/duplicate delivery) were silently
661    // accepted. Must FAIL if that check is ever removed.
662    #[test]
663    fn on_resource_rejects_a_never_requested_id() {
664        let mut client = LlHlsClient::new("http://example.com/playlist.m3u8");
665        let id = ResourceId::Segment { msn: 0 };
666
667        let err = client
668            .on_resource(id, b"some bytes")
669            .expect_err("an id the client never requested must be rejected");
670        assert!(
671            matches!(err, Error::UnrequestedResource { id: got } if got == id),
672            "wrong error variant: {err:?}"
673        );
674
675        // Init is checked too (tracked via `init_uri` rather than
676        // `requested`, since it's never inserted into that set).
677        let err = client
678            .on_resource(ResourceId::Init, b"init bytes")
679            .expect_err("an unrequested Init must be rejected");
680        assert!(
681            matches!(
682                err,
683                Error::UnrequestedResource {
684                    id: ResourceId::Init
685                }
686            ),
687            "wrong error variant: {err:?}"
688        );
689    }
690
691    // The flip side of the regression above: a `ResourceId` the client
692    // actually asked for (via its own internal `request_resource`
693    // bookkeeping, mirroring what a real `poll()`-driven fetch populates)
694    // must still be accepted, not spuriously rejected.
695    #[test]
696    fn on_resource_accepts_a_previously_requested_id() {
697        let mut client = LlHlsClient::new("http://example.com/playlist.m3u8");
698        let id = ResourceId::Segment { msn: 0 };
699        client.request_resource(id, "http://example.com/seg0.m4s".to_string(), None);
700
701        // No init segment cached yet, so this is buffered rather than
702        // demuxed — the point here is only that it is *not* rejected as
703        // unrequested.
704        let result = client.on_resource(id, b"some bytes");
705        assert!(
706            result.is_ok(),
707            "a requested id must be accepted: {result:?}"
708        );
709        assert!(
710            client.pending_demux.iter().any(|(bid, _)| *bid == id),
711            "expected the resource to be buffered pending the init segment"
712        );
713    }
714
715    // Issue #760: classic MPEG-TS-segment HLS routing. `is_ts_segment` must
716    // say yes to a genuine TS resource (sync byte, no map ever seen)...
717    #[test]
718    fn is_ts_segment_true_when_no_map_seen_and_sync_byte_present() {
719        let client = LlHlsClient::new("http://example.com/playlist.m3u8");
720        assert!(client.is_ts_segment(&[TS_SYNC_BYTE, 0x40, 0x11, 0x00]));
721    }
722
723    // ...but say no to an ISOBMFF (fMP4/CMAF) resource even when no map has
724    // been seen yet — the content itself is never TS, so it must fall
725    // through to the ordinary init-buffering path rather than being
726    // misrouted into `TsDemux` (which would reject it as malformed TS).
727    #[test]
728    fn is_ts_segment_false_for_an_isobmff_resource_with_no_map_seen() {
729        let client = LlHlsClient::new("http://example.com/playlist.m3u8");
730        let ftyp_box = b"\x00\x00\x00\x18ftypiso5\x00\x00\x02\x00iso5iso6mp41";
731        assert!(!client.is_ts_segment(ftyp_box));
732    }
733
734    // The playlist signal takes precedence over content-sniffing: once this
735    // playlist is known to advertise an `EXT-X-MAP` (an init fetch has been
736    // requested/cached), even a resource whose first byte happens to be
737    // `0x47` must NOT be misrouted through `TsDemux` -- it is that
738    // playlist's own fMP4/CMAF init + part/segment concatenation the
739    // fetched bytes belong with.
740    #[test]
741    fn is_ts_segment_false_once_a_map_has_been_requested() {
742        let mut client = LlHlsClient::new("http://example.com/playlist.m3u8");
743        client
744            .ensure_init_requested(&MapTag {
745                uri: "init.mp4".to_string(),
746                byte_range: None,
747            })
748            .expect("ensure_init_requested succeeds");
749        assert!(!client.is_ts_segment(&[TS_SYNC_BYTE, 0x40, 0x11, 0x00]));
750    }
751}