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#[derive(Clone, Debug)]
17pub struct HlsConfig {
18 pub segment_duration: Duration,
20 pub segment_count: usize,
22 pub live: bool,
24}
25
26impl HlsConfig {
27 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 segment_duration: Duration::from_secs(1),
45 segment_count: 3,
48 live: true,
49 }
50 }
51}
52
53pub struct HlsHandlers {
55 pub playlist: Handler,
56 pub segment: Handler,
57 pub init: Handler,
58}
59
60pub 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
70pub 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 #[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 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 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 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}