Skip to main content

rtflow_hls/
live.rs

1//! Registry-backed HLS live endpoints for dynamic mounts (notably RTMP
2//! publishers that create their mount after startup).
3use super::{
4    HlsConfig, handler,
5    segment_ring::SegmentRing,
6    segmenter::{Segmenter, SegmenterConfig},
7};
8use rtflow_http::Handler;
9use rtflow_mount::{FrameRecvError, MountHandle, MountRegistry};
10use std::{
11    collections::HashMap,
12    sync::{
13        Arc, Mutex,
14        atomic::{AtomicU64, Ordering},
15    },
16};
17
18struct Channel {
19    ring: Arc<SegmentRing>,
20    /// `Some(generation)` while exactly one segmenter owns this channel.
21    /// Never start a second segmenter for the same mount: two segmenters
22    /// have independent sequence counters and interleave 114/115/116/115
23    /// into one playlist.
24    active: Arc<Mutex<Option<u64>>>,
25    next_generation: AtomicU64,
26    /// Next media sequence. Preserved across segmenter restarts so the
27    /// playlist's EXT-X-MEDIA-SEQUENCE never goes backwards.
28    next_sequence: Arc<AtomicU64>,
29    /// Cache-busting token for init/segments. A server restart or segmenter
30    /// restart must not reuse the previous run's browser-cached init.m4s.
31    generation: Mutex<String>,
32    /// Wall-clock start of the current segmenter generation, used for
33    /// `EXT-X-PROGRAM-DATE-TIME`.
34    started_at: Mutex<std::time::SystemTime>,
35}
36
37/// Per-registry HLS live manager. One segmenter/channel per mount.
38pub struct HlsLiveManager {
39    registry: Arc<MountRegistry>,
40    config: HlsConfig,
41    channels: Mutex<HashMap<String, Arc<Channel>>>,
42}
43
44impl HlsLiveManager {
45    pub fn new(registry: Arc<MountRegistry>, config: HlsConfig) -> Self {
46        Self {
47            registry,
48            config,
49            channels: Mutex::new(HashMap::new()),
50        }
51    }
52
53    fn channel(&self, mount: &MountHandle) -> Arc<Channel> {
54        let key = mount.path().to_owned();
55        self.channels
56            .lock()
57            .unwrap_or_else(std::sync::PoisonError::into_inner)
58            .entry(key)
59            .or_insert_with(|| {
60                Arc::new(Channel {
61                    ring: Arc::new(SegmentRing::with_retention(
62                        self.config.segment_count,
63                        self.config.segment_count.saturating_mul(3),
64                    )),
65                    active: Arc::new(Mutex::new(None)),
66                    next_generation: AtomicU64::new(0),
67                    next_sequence: Arc::new(AtomicU64::new(0)),
68                    generation: Mutex::new(format!(
69                        "{:x}",
70                        std::time::SystemTime::now()
71                            .duration_since(std::time::UNIX_EPOCH)
72                            .unwrap_or_default()
73                            .as_nanos()
74                    )),
75                    started_at: Mutex::new(std::time::SystemTime::now()),
76                })
77            })
78            .clone()
79    }
80
81    fn ensure_started(&self, mount: &MountHandle, channel: &Arc<Channel>) {
82        let mut active = channel
83            .active
84            .lock()
85            .unwrap_or_else(std::sync::PoisonError::into_inner);
86        if active.is_some() {
87            return;
88        }
89        let description = mount.description();
90        if description.tracks.is_empty() {
91            return;
92        }
93        let generation = channel.next_generation.fetch_add(1, Ordering::AcqRel) + 1;
94        *channel
95            .started_at
96            .lock()
97            .unwrap_or_else(std::sync::PoisonError::into_inner) = std::time::SystemTime::now();
98        *active = Some(generation);
99        *channel
100            .generation
101            .lock()
102            .unwrap_or_else(std::sync::PoisonError::into_inner) = format!(
103            "{generation}-{:x}",
104            std::time::SystemTime::now()
105                .duration_since(std::time::UNIX_EPOCH)
106                .unwrap_or_default()
107                .as_nanos()
108        );
109        tracing::info!(
110            mount = %mount.path(),
111            tracks = description.tracks.len(),
112            segment_ms = self.config.segment_duration.as_millis() as u64,
113            window = self.config.segment_count,
114            generation,
115            "HLS live segmenter started"
116        );
117        let ring = channel.ring.clone();
118        let next_sequence = channel.next_sequence.clone();
119        let channel = channel.clone();
120        let mount = mount.clone();
121        let cancel = mount.cancellation_token();
122        let seg_config = SegmenterConfig {
123            segment_duration: self.config.segment_duration,
124            lookback_count: self.config.segment_count,
125        };
126        tokio::spawn(async move {
127            let mut segmenter = Segmenter::new_mpegts(seg_config, &description);
128            segmenter.set_sequence(next_sequence.load(Ordering::Acquire));
129            let mut segments = segmenter.subscribe();
130            let (mut receiver, startup) = mount.subscribe_with_startup();
131            let startup_keys = rtflow_mount::startup_dedup_keys(&startup);
132            let mut startup = std::collections::VecDeque::from(startup);
133            let has_video = description
134                .tracks
135                .iter()
136                .any(|track| track.kind == rtflow_media::MediaKind::Video);
137            let mut awaiting_keyframe = has_video;
138            let mut from_startup = true;
139            loop {
140                let unit = if let Some(unit) = startup.pop_front() {
141                    unit
142                } else {
143                    from_startup = false;
144                    tokio::select! {
145                        _ = cancel.cancelled() => break,
146                        result = receiver.recv() => match result {
147                            Ok(unit) => unit,
148                            Err(FrameRecvError::Lagged(count)) => {
149                                tracing::debug!(count, "HLS live lagged; waiting for a keyframe");
150                                segmenter.reset_after_discontinuity();
151                                awaiting_keyframe = has_video;
152                                continue;
153                            }
154                            Err(FrameRecvError::Closed) => break,
155                        },
156                    }
157                };
158                if awaiting_keyframe {
159                    let video = matches!(
160                        unit.codec,
161                        rtflow_media::Codec::H264 | rtflow_media::Codec::H265
162                    );
163                    if video {
164                        if !unit.is_keyframe {
165                            continue;
166                        }
167                        awaiting_keyframe = false;
168                    } else {
169                        // Do not let audio start a segment before the first
170                        // video IDR: the segment would begin at an audio PTS
171                        // and the video track would join it mid-GOP. hls.js
172                        // then has no decodable video at the segment start.
173                        continue;
174                    }
175                }
176                if from_startup || !startup_keys.contains(&(unit.track_id, unit.rtp_timestamp)) {
177                    segmenter.push((*unit).clone());
178                }
179                while let Ok(segment) = segments.try_recv() {
180                    next_sequence.store(segment.sequence.saturating_add(1), Ordering::Release);
181                    ring.push(segment);
182                }
183            }
184            let mut active = channel
185                .active
186                .lock()
187                .unwrap_or_else(std::sync::PoisonError::into_inner);
188            if *active == Some(generation) {
189                channel.ring.clear();
190                *active = None;
191            }
192        });
193    }
194}
195
196fn mount_path(path: &str) -> Option<(&str, &str)> {
197    let rest = path.strip_prefix("/hls/")?;
198    if let Some(mount) = rest.strip_suffix("/index.m3u8") {
199        return Some((mount, "playlist"));
200    }
201    if let Some(mount) = rest.strip_suffix("/init.m4s") {
202        return Some((mount, "init"));
203    }
204    let (mount, file) = rest.rsplit_once('/')?;
205    if file.ends_with(".m4s") || file.ends_with(".ts") {
206        return Some((mount, "segment"));
207    }
208    None
209}
210
211/// Handler for `/hls/{mount}/index.m3u8`, `/init.m4s`, `/{seq}.m4s`.
212pub fn create_hls_live_handler(manager: Arc<HlsLiveManager>) -> Handler {
213    Arc::new(move |req, mut writer| {
214        let manager = manager.clone();
215        Box::pin(async move {
216            let Some((mount_path, kind)) =
217                mount_path(&req.path).map(|(mount, kind)| (mount.to_owned(), kind))
218            else {
219                writer.write_body(404, "text/plain", b"Not Found").await?;
220                return Ok(writer);
221            };
222            let Some(mount) = manager.registry.get_handle(&format!("/{mount_path}")) else {
223                writer
224                    .write_body(404, "text/plain", b"Mount not found")
225                    .await?;
226                return Ok(writer);
227            };
228            let channel = manager.channel(&mount);
229            manager.ensure_started(&mount, &channel);
230            match kind {
231                "playlist" => {
232                    if mount.description().tracks.is_empty() {
233                        writer
234                            .write_headers(
235                                503,
236                                &[
237                                    ("Retry-After", "2"),
238                                    ("Content-Length", "0"),
239                                    ("Connection", "close"),
240                                ],
241                            )
242                            .await?;
243                        return Ok(writer);
244                    }
245                    // hls.js treats a live playlist without any segment
246                    // (or without EXT-X-MEDIA-SEQUENCE) as a fatal
247                    // internalException. Wait for the first segment after
248                    // starting the segmenter; keep a bounded wait so a
249                    // publisher that never sends data gets 503 + retry.
250                    if channel.ring.is_empty() {
251                        for _ in 0..60 {
252                            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
253                            if !channel.ring.is_empty() {
254                                break;
255                            }
256                        }
257                    }
258                    if channel.ring.is_empty() {
259                        writer
260                            .write_headers(
261                                503,
262                                &[
263                                    ("Retry-After", "1"),
264                                    ("Content-Length", "0"),
265                                    ("Connection", "close"),
266                                ],
267                            )
268                            .await?;
269                        return Ok(writer);
270                    }
271                    let mut req = req;
272                    // LL-HLS blocking playlist reload: hold the request until
273                    // the requested media sequence exists (bounded).
274                    if let Some(msn) = req
275                        .query
276                        .get("_HLS_msn")
277                        .and_then(|value| value.parse::<u64>().ok())
278                    {
279                        let deadline =
280                            tokio::time::Instant::now() + std::time::Duration::from_secs(3);
281                        loop {
282                            if channel
283                                .ring
284                                .latest_sequence()
285                                .is_some_and(|latest| latest >= msn)
286                            {
287                                break;
288                            }
289                            let left =
290                                deadline.saturating_duration_since(tokio::time::Instant::now());
291                            if left.is_zero() {
292                                break;
293                            }
294                            // Register before re-checking so a segment pushed
295                            // between the check and the await is not missed;
296                            // the wait consumes the whole remaining budget
297                            // instead of re-polling every 50 ms (which cloned
298                            // and sorted the whole ring each time).
299                            let notified = channel.ring.notified();
300                            tokio::pin!(notified);
301                            let _ = notified.as_mut().enable();
302                            if channel
303                                .ring
304                                .latest_sequence()
305                                .is_some_and(|latest| latest >= msn)
306                            {
307                                break;
308                            }
309                            let _ = tokio::time::timeout(left, notified).await;
310                        }
311                        req.query.remove("_HLS_msn");
312                        req.query.remove("_HLS_part");
313                    }
314                    let generation = channel
315                        .generation
316                        .lock()
317                        .unwrap_or_else(std::sync::PoisonError::into_inner)
318                        .clone();
319                    req.query.insert("v".to_owned(), generation);
320                    let started_at = *channel
321                        .started_at
322                        .lock()
323                        .unwrap_or_else(std::sync::PoisonError::into_inner);
324                    handler::serve_playlist(
325                        req,
326                        writer,
327                        &channel.ring,
328                        true,
329                        manager.config.segment_duration,
330                        "",
331                        Some(started_at),
332                    )
333                    .await
334                }
335                "init" => handler::serve_init_segment(req, writer, &channel.ring).await,
336                "segment" => {
337                    let sequence = req
338                        .path
339                        .rsplit('/')
340                        .next()
341                        .and_then(|file| {
342                            file.strip_suffix(".m4s")
343                                .or_else(|| file.strip_suffix(".ts"))
344                        })
345                        .and_then(|value| value.parse::<u64>().ok())
346                        .unwrap_or(u64::MAX);
347                    handler::serve_segment(req, writer, &channel.ring, sequence).await
348                }
349                _ => {
350                    writer.write_body(404, "text/plain", b"Not Found").await?;
351                    Ok(writer)
352                }
353            }
354        })
355    })
356}
357
358// Keep the type visible in docs/tests without exposing internals.
359#[allow(dead_code)]
360fn _assert_send_sync() {
361    fn check<T: Send + Sync>() {}
362    check::<HlsLiveManager>();
363}