Skip to main content

rtflow_hls/
lib.rs

1pub mod handler;
2pub mod live;
3pub mod ll;
4pub mod playlist;
5pub mod segment_ring;
6pub mod segmenter;
7pub mod vod;
8
9use rtflow_http::Handler;
10use segment_ring::SegmentRing;
11use segmenter::{Segmenter, SegmenterConfig};
12use std::time::Duration;
13use std::{collections::VecDeque, sync::Arc};
14
15/// HLS configuration.
16#[derive(Clone, Debug)]
17pub struct HlsConfig {
18    /// Target segment duration.
19    pub segment_duration: Duration,
20    /// Number of segments to keep in the sliding window.
21    pub segment_count: usize,
22    /// Whether this is a live or VOD stream.
23    pub live: bool,
24}
25
26impl HlsConfig {
27    /// Reject degenerate segment duration; `segment_count` is clamped by
28    /// [`segment_ring::SegmentRing`].
29    pub fn validate(&self) -> rtflow_core::error::Result<()> {
30        if self.segment_duration.is_zero() {
31            return Err(rtflow_core::error::Error::Limit("HLS segment duration"));
32        }
33        Ok(())
34    }
35}
36
37impl Default for HlsConfig {
38    fn default() -> Self {
39        Self {
40            // 1 s segments: with a 1 s GOP this is the theoretical minimum
41            // server-side cut latency (average GOP/2 = 0.5 s to the next
42            // segment). The 3-segment window still satisfies the HLS
43            // spec's 3×TARGETDURATION lookback requirement.
44            segment_duration: Duration::from_secs(1),
45            // Embedded budget: lookback segments are retained in RAM
46            // after finalization (1s×bitrate×count peak).
47            segment_count: 3,
48            live: true,
49        }
50    }
51}
52
53/// Named HLS handler set. Prefer this over positional tuples.
54pub struct HlsHandlers {
55    pub playlist: Handler,
56    pub segment: Handler,
57    pub init: Handler,
58}
59
60/// Named-constructor variant of [`create_hls_handlers`].
61pub fn create_hls_router(config: HlsConfig, mount: &rtflow_mount::MountHandle) -> HlsHandlers {
62    let (playlist, segment, init) = create_hls_handlers(config, mount);
63    HlsHandlers {
64        playlist,
65        segment,
66        init,
67    }
68}
69
70/// Create HLS HTTP handlers backed by a mount startup snapshot and tied to its lifetime.
71pub fn create_hls_handlers(
72    config: HlsConfig,
73    mount: &rtflow_mount::MountHandle,
74) -> (Handler, Handler, Handler) {
75    let ring = Arc::new(SegmentRing::with_retention(
76        config.segment_count,
77        config.segment_count.saturating_mul(3),
78    ));
79    let target_duration = config.segment_duration;
80    let is_live = config.live;
81    let mut description = (*mount.description()).clone();
82    let announced_fmtp = mount.announce_fmtp();
83    for track in &mut description.tracks {
84        if let Some(fmtp) = announced_fmtp.get(&track.id) {
85            track.fmtp = Some(fmtp.clone());
86        }
87    }
88    let (mut receiver, startup) = mount.subscribe_with_startup();
89    let cancel = mount.cancellation_token();
90    let asset_prefix: Arc<str> = Arc::from(mount.path());
91
92    // Mirror served-segment counts into the global metrics registry when
93    // the mount's event sink is a MetricsEventSink.
94    #[cfg(feature = "metrics")]
95    let metrics = rtflow_core::metrics::registry_from_sink(&mount.mount().event_sink);
96
97    let ring_clone = ring.clone();
98    let seg_config = SegmenterConfig {
99        segment_duration: config.segment_duration,
100        lookback_count: config.segment_count,
101    };
102    tracing::info!(
103        mount = %mount.path(),
104        tracks = description.tracks.len(),
105        segment_ms = seg_config.segment_duration.as_millis() as u64,
106        "HLS segmenter started"
107    );
108    tokio::spawn(async move {
109        let mut segmenter = Segmenter::new(seg_config, &description);
110        let mut segments = segmenter.subscribe();
111        // Skip broadcast replays of frames the startup snapshot already
112        // delivered (duplicate keyframes would corrupt segment timing).
113        let startup_keys = rtflow_mount::startup_dedup_keys(&startup);
114        let mut startup = VecDeque::from(startup);
115        let has_video = description
116            .tracks
117            .iter()
118            .any(|track| track.kind == rtflow_media::MediaKind::Video);
119        let mut awaiting_keyframe = has_video;
120        let mut from_startup = true;
121        loop {
122            let unit = if let Some(unit) = startup.pop_front() {
123                unit
124            } else {
125                from_startup = false;
126                tokio::select! {
127                    _ = cancel.cancelled() => break,
128                    result = receiver.recv() => match result {
129                        Ok(unit) => unit,
130                        Err(rtflow_mount::FrameRecvError::Lagged(count)) => {
131                            tracing::debug!(count, "HLS input lagged; waiting for a keyframe");
132                            segmenter.reset_after_discontinuity();
133                            awaiting_keyframe = has_video;
134                            continue;
135                        }
136                        Err(rtflow_mount::FrameRecvError::Closed) => break,
137                    },
138                }
139            };
140            if awaiting_keyframe {
141                let video = matches!(
142                    unit.codec,
143                    rtflow_media::Codec::H264 | rtflow_media::Codec::H265
144                );
145                if video {
146                    if !unit.is_keyframe {
147                        continue;
148                    }
149                    awaiting_keyframe = false;
150                } else {
151                    continue;
152                }
153            }
154            // Skip broadcast replays of frames the startup snapshot already
155            // delivered (duplicate keyframes would corrupt segment timing).
156            if !from_startup && startup_keys.contains(&(unit.track_id, unit.rtp_timestamp)) {
157                continue;
158            }
159            segmenter.push((*unit).clone());
160            while let Ok(segment) = segments.try_recv() {
161                ring_clone.push(segment);
162            }
163        }
164        segmenter.flush();
165        while let Ok(segment) = segments.try_recv() {
166            ring_clone.push(segment);
167        }
168    });
169
170    if !is_live {
171        // HlsConfig.live=false promises a VOD playlist, but segments are
172        // still served from the sliding window ring and get evicted (404).
173        // Refuse honestly instead of advertising an unusable VOD mode.
174        tracing::warn!(
175            "HLS VOD mode (HlsConfig.live=false) is not implemented; segments would be evicted from the sliding window. Use live mode (default)."
176        );
177        let reject: Handler = Arc::new(|_req, mut writer| {
178            Box::pin(async move {
179                writer
180                    .write_body(
181                        501,
182                        "text/plain",
183                        b"HLS VOD mode is not implemented; use live mode",
184                    )
185                    .await?;
186                Ok(writer)
187            })
188        });
189        return (reject.clone(), reject.clone(), reject);
190    }
191
192    let ring_p = ring.clone();
193    let playlist_asset_prefix = asset_prefix.clone();
194    let playlist_handler: Handler = Arc::new(move |_req, writer| {
195        let r = ring_p.clone();
196        let asset_prefix = playlist_asset_prefix.clone();
197        Box::pin(async move {
198            handler::serve_playlist(
199                _req,
200                writer,
201                &r,
202                is_live,
203                target_duration,
204                &asset_prefix,
205                None,
206            )
207            .await
208        })
209    });
210
211    let ring_s = ring.clone();
212    let segment_handler: Handler = Arc::new(move |_req, writer| {
213        #[cfg(feature = "metrics")]
214        let metrics = metrics.clone();
215        let r = ring_s.clone();
216        Box::pin(async move {
217            let seq = _req
218                .path
219                .rsplit('/')
220                .next()
221                .and_then(|value| value.trim_end_matches(".m4s").parse::<u64>().ok())
222                .unwrap_or(u64::MAX);
223            #[cfg(feature = "metrics")]
224            if let Some(metrics) = &metrics {
225                use std::sync::atomic::Ordering;
226                metrics.hls_segments_served.fetch_add(1, Ordering::Relaxed);
227            }
228            handler::serve_segment(_req, writer, &r, seq).await
229        })
230    });
231
232    let ring_i = ring.clone();
233    let init_handler: Handler = Arc::new(move |_req, writer| {
234        let r = ring_i.clone();
235        Box::pin(async move { handler::serve_init_segment(_req, writer, &r).await })
236    });
237
238    (playlist_handler, segment_handler, init_handler)
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn zero_segment_duration_is_rejected() {
247        let config = HlsConfig {
248            segment_duration: Duration::ZERO,
249            ..HlsConfig::default()
250        };
251        assert!(config.validate().is_err());
252    }
253}