Skip to main content

rtflow_hls/
ll.rs

1//! Low-Latency HLS (LL-HLS) live manager.
2//!
3//! This is a separate endpoint from the classic MPEG-TS HLS live path so the
4//! stable 1 s TS pipeline is untouched. It uses `transmux::LlHlsSegmenter` to
5//! emit CMAF parts (`#EXT-X-PART`) as they close, plus the completed segments
6//! and a preload hint. Part/segment bytes are served from memory.
7
8use super::segmenter::{pending_limits, track_spec};
9use broadcast_core::ids::TrackId;
10use bytes::Bytes;
11use rtflow_http::Handler;
12use rtflow_media::{Codec, MediaKind};
13use rtflow_mount::MountRegistry;
14use std::{
15    collections::{BTreeMap, HashMap},
16    sync::{Arc, Mutex},
17};
18use transmux::Sample;
19use transmux::ll_hls::LlHlsSegmenter;
20
21#[derive(Clone, Debug)]
22pub struct LlHlsConfig {
23    pub segment_duration: f64,
24    pub part_target_ms: u32,
25    /// Number of completed segments kept in the playlist/state.
26    pub segment_window: u32,
27}
28
29impl Default for LlHlsConfig {
30    fn default() -> Self {
31        Self {
32            segment_duration: 2.0,
33            part_target_ms: 200,
34            segment_window: 6,
35        }
36    }
37}
38
39struct Part {
40    bytes: Bytes,
41    duration: f64,
42    independent: bool,
43}
44
45struct State {
46    init: Bytes,
47    parts: BTreeMap<(u32, u32), Part>,
48    segments: BTreeMap<u32, (Bytes, f64)>,
49}
50
51struct Channel {
52    state: Mutex<State>,
53    active: Mutex<bool>,
54    ready: tokio::sync::Notify,
55}
56
57pub struct LlHlsLiveManager {
58    registry: Arc<MountRegistry>,
59    config: LlHlsConfig,
60    channels: Mutex<HashMap<String, Arc<Channel>>>,
61}
62
63impl LlHlsLiveManager {
64    pub fn new(registry: Arc<MountRegistry>, config: LlHlsConfig) -> Self {
65        Self {
66            registry,
67            config,
68            channels: Mutex::new(HashMap::new()),
69        }
70    }
71
72    fn channel(&self, path: &str) -> Arc<Channel> {
73        self.channels
74            .lock()
75            .unwrap_or_else(std::sync::PoisonError::into_inner)
76            .entry(path.to_owned())
77            .or_insert_with(|| {
78                Arc::new(Channel {
79                    state: Mutex::new(State {
80                        init: Bytes::new(),
81                        parts: BTreeMap::new(),
82                        segments: BTreeMap::new(),
83                    }),
84                    active: Mutex::new(false),
85                    ready: tokio::sync::Notify::new(),
86                })
87            })
88            .clone()
89    }
90
91    fn start(&self, mount: rtflow_mount::MountHandle, channel: Arc<Channel>) {
92        let mut active = channel
93            .active
94            .lock()
95            .unwrap_or_else(std::sync::PoisonError::into_inner);
96        if *active {
97            return;
98        }
99        // 与经典 HLS(create_hls_handlers)一致:把 mount 公布的 fmtp 补进轨道描述,
100        // 否则 track_spec() 拿不到 sprop-parameter-sets,H.264 轨道会被整条跳过,
101        // 切片器起不来(播放列表永远为空)。
102        let mut description = (*mount.description()).clone();
103        let announced_fmtp = mount.announce_fmtp();
104        for track in &mut description.tracks {
105            if let Some(fmtp) = announced_fmtp.get(&track.id) {
106                track.fmtp = Some(fmtp.clone());
107            }
108        }
109        if description.tracks.is_empty() {
110            tracing::warn!(mount = %mount.path(), "LL-HLS:挂载点没有轨道描述,切片器不启动");
111            return;
112        }
113        let mut specs = Vec::new();
114        let mut timescales = HashMap::new();
115        let mut durations = HashMap::new();
116        for track in &description.tracks {
117            if let Some(spec) = track_spec(track) {
118                timescales.insert(track.id, track.clock_rate);
119                let duration = match track.kind {
120                    MediaKind::Video => track
121                        .frame_rate
122                        .map(|(n, d)| {
123                            (u64::from(track.clock_rate) * u64::from(d) / u64::from(n).max(1))
124                                as u32
125                        })
126                        .unwrap_or(3_000),
127                    MediaKind::Audio => 1024,
128                };
129                durations.insert(track.id, duration.max(1));
130                specs.push(spec);
131            }
132        }
133        if specs.is_empty() {
134            tracing::warn!(mount = %mount.path(), tracks = description.tracks.len(),
135                "LL-HLS:轨道无法转成 transmux 规格(缺 codec/fmtp?),切片器不启动");
136            return;
137        }
138        let track_count = specs.len();
139        let Ok(mut segmenter) = LlHlsSegmenter::with_part_target(
140            specs,
141            broadcast_core::timescale!(90_000),
142            std::time::Duration::from_secs_f64(self.config.segment_duration.max(0.001)),
143            std::time::Duration::from_millis(u64::from(self.config.part_target_ms.max(1))),
144            pending_limits(),
145        ) else {
146            return;
147        };
148        tracing::info!(
149            mount = %mount.path(),
150            tracks = track_count,
151            segment_ms = (self.config.segment_duration * 1000.0) as u64,
152            part_ms = self.config.part_target_ms,
153            "LL-HLS segmenter started"
154        );
155        let init = segmenter.init_segment().unwrap_or_default();
156        if init.is_empty() {
157            tracing::warn!(mount = %mount.path(), "LL-HLS:init 段为空(SPS/PPS 还没到?)");
158        }
159        if let Ok(mut state) = channel.state.lock() {
160            state.init = Bytes::from(init);
161        }
162        let cancel = mount.cancellation_token();
163        let segment_window = self.config.segment_window.max(1);
164        *active = true;
165        drop(active);
166        tokio::spawn(async move {
167            let (mut receiver, startup) = mount.subscribe_with_startup();
168            let mut startup = std::collections::VecDeque::from(startup);
169            let mut awaiting_keyframe = true;
170            loop {
171                let unit = if let Some(unit) = startup.pop_front() {
172                    unit
173                } else {
174                    tokio::select! {
175                        _ = cancel.cancelled() => break,
176                        result = receiver.recv() => match result {
177                            Ok(unit) => unit,
178                            Err(rtflow_mount::FrameRecvError::Lagged(_)) => { awaiting_keyframe = true; continue; }
179                            Err(_) => break,
180                        },
181                    }
182                };
183                if awaiting_keyframe {
184                    if !matches!(
185                        unit.codec,
186                        Codec::H264 | Codec::H265 | Codec::Vp9 | Codec::Av1
187                    ) || !unit.is_keyframe
188                    {
189                        continue;
190                    }
191                    awaiting_keyframe = false;
192                }
193                let Some(&track_id) = timescales.get(&unit.track_id).map(|_| &unit.track_id) else {
194                    continue;
195                };
196                let Some(timescale) = timescales.get(&track_id).copied() else {
197                    continue;
198                };
199                let ticks = |d: std::time::Duration| {
200                    (d.as_secs() * u64::from(timescale)
201                        + u64::from(d.subsec_nanos()) * u64::from(timescale) / 1_000_000_000)
202                        as i64
203                };
204                let duration = durations.get(&track_id).copied();
205                let sample = if matches!(unit.codec, Codec::Aac | Codec::Pcma | Codec::Pcmu) {
206                    Sample::from_raw(
207                        unit.data.clone(),
208                        Some(ticks(unit.dts.unwrap_or(unit.pts))),
209                        Some(ticks(unit.pts)),
210                        duration,
211                    )
212                } else {
213                    Sample::from_annexb(
214                        &unit.data,
215                        Some(ticks(unit.dts.unwrap_or(unit.pts))),
216                        Some(ticks(unit.pts)),
217                        duration,
218                        unit.is_keyframe,
219                    )
220                };
221                let Ok(sample) = sample else {
222                    continue;
223                };
224                if segmenter
225                    .push(TrackId::new(u32::from(track_id) + 1), sample)
226                    .is_err()
227                {
228                    continue;
229                }
230                let mut state = channel
231                    .state
232                    .lock()
233                    .unwrap_or_else(std::sync::PoisonError::into_inner);
234                let mut produced = false;
235                let parts_ready = segmenter.take_ready_parts();
236                for part in parts_ready {
237                    produced = true;
238                    state.parts.insert(
239                        (part.segment_seq, part.part_index.into()),
240                        Part {
241                            bytes: Bytes::from(part.bytes),
242                            duration: part.duration.as_secs_f64(),
243                            independent: part.independent,
244                        },
245                    );
246                }
247                for segment in segmenter.take_ready_segments() {
248                    produced = true;
249                    state.segments.insert(
250                        segment.segment_seq,
251                        (Bytes::from(segment.bytes), segment.duration.as_secs_f64()),
252                    );
253                    state.parts.retain(|(msn, _), _| *msn > segment.segment_seq);
254                    let keep_from = segment.segment_seq.saturating_sub(segment_window);
255                    state.segments.retain(|seq, _| *seq >= keep_from);
256                }
257                drop(state);
258                // Parts close every `part_target_ms`, not on every frame:
259                // waking blocking reloads per frame was 5-10x more wakeups
260                // than there were results to deliver.
261                if produced {
262                    channel.ready.notify_waiters();
263                }
264            }
265            let mut state = channel
266                .state
267                .lock()
268                .unwrap_or_else(std::sync::PoisonError::into_inner);
269            let _ = segmenter.flush();
270            let mut produced = false;
271            for part in segmenter.take_ready_parts() {
272                produced = true;
273                state.parts.insert(
274                    (part.segment_seq, part.part_index.into()),
275                    Part {
276                        bytes: Bytes::from(part.bytes),
277                        duration: part.duration.as_secs_f64(),
278                        independent: part.independent,
279                    },
280                );
281            }
282            for segment in segmenter.take_ready_segments() {
283                produced = true;
284                state.segments.insert(
285                    segment.segment_seq,
286                    (Bytes::from(segment.bytes), segment.duration.as_secs_f64()),
287                );
288            }
289            drop(state);
290            if produced {
291                channel.ready.notify_waiters();
292            }
293        });
294    }
295
296    fn playlist(&self, channel: &Channel, query: &str) -> String {
297        let state = channel
298            .state
299            .lock()
300            .unwrap_or_else(std::sync::PoisonError::into_inner);
301        let mut out = String::from("#EXTM3U\n#EXT-X-VERSION:9\n#EXT-X-INDEPENDENT-SEGMENTS\n");
302        // 别名端点(/live/main.m3u8)下,分片 URI 需要带上流名前缀,
303        // 播放器才会请求 /live/main/<name>;/llhls 端点保持空前缀。
304        let prefix = query
305            .split('&')
306            .find_map(|kv| kv.strip_prefix("_PREFIX="))
307            .unwrap_or("")
308            .to_string();
309        out.push_str(&format!(
310            "#EXT-X-TARGETDURATION:{}\n",
311            self.config.segment_duration.ceil().max(1.0) as u64
312        ));
313        out.push_str(&format!(
314            "#EXT-X-PART-INF:PART-TARGET={:.3}\n",
315            f64::from(self.config.part_target_ms) / 1000.0
316        ));
317        out.push_str(&format!(
318            "#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK={:.3}\n",
319            f64::from(self.config.part_target_ms) * 3.0 / 1000.0
320        ));
321        let first_sequence = state
322            .segments
323            .keys()
324            .next()
325            .copied()
326            .or_else(|| state.parts.keys().next().map(|(msn, _)| *msn))
327            .unwrap_or(0);
328        out.push_str(&format!("#EXT-X-MEDIA-SEQUENCE:{first_sequence}\n"));
329        out.push_str(&format!(
330            "#EXT-X-MAP:URI=\"{prefix}init.m4s{}\"\n",
331            query_suffix(query)
332        ));
333        let last_segment = state.segments.keys().next_back().copied().unwrap_or(0);
334        for (&seq, (_, duration)) in &state.segments {
335            out.push_str(&format!(
336                "#EXTINF:{duration:.3},\n{prefix}{seq}.m4s{}\n",
337                query_suffix(query)
338            ));
339        }
340        for (&(msn, idx), part) in state.parts.range((last_segment + 1, 0)..) {
341            out.push_str(&format!(
342                "#EXT-X-PART:DURATION={:.3},URI=\"{prefix}part-{msn}-{idx}.m4s{}\",INDEPENDENT={}\n",
343                part.duration,
344                query_suffix(query),
345                if part.independent { "YES" } else { "NO" }
346            ));
347        }
348        if let Some(&(msn, _)) = state.parts.keys().next_back() {
349            out.push_str(&format!(
350                "#EXT-X-PRELOAD-HINT:TYPE=PART,URI=\"{prefix}part-{}-0.m4s{}\"\n",
351                msn + 1,
352                query_suffix(query)
353            ));
354        }
355        out
356    }
357}
358
359fn query_suffix(query: &str) -> String {
360    // HLS blocking-reload parameters belong to the playlist request only.
361    // Never append them to media/part URIs (hls.js would request them as media).
362    let filtered = query
363        .split('&')
364        .filter(|pair| {
365            let key = pair.split_once('=').map(|(key, _)| key).unwrap_or(pair);
366            !key.starts_with("_HLS_") && !key.starts_with("_PREFIX")
367        })
368        .collect::<Vec<_>>()
369        .join("&");
370    if filtered.is_empty() {
371        String::new()
372    } else {
373        format!("?{filtered}")
374    }
375}
376
377fn mount_path(path: &str) -> Option<(&str, &str)> {
378    let rest = path.strip_prefix("/llhls/")?;
379    if let Some(mount) = rest.strip_suffix("/index.m3u8") {
380        return Some((mount, "playlist"));
381    }
382    if let Some(mount) = rest.strip_suffix("/init.m4s") {
383        return Some((mount, "init"));
384    }
385    let (mount, file) = rest.rsplit_once('/')?;
386    if file.starts_with("part-") && file.ends_with(".m4s") {
387        return Some((mount, "part"));
388    }
389    if file.ends_with(".m4s") {
390        return Some((mount, "segment"));
391    }
392    None
393}
394
395pub fn create_ll_hls_handler(manager: Arc<LlHlsLiveManager>) -> Handler {
396    Arc::new(move |req, mut writer| {
397        let manager = manager.clone();
398        Box::pin(async move {
399            let Some((mount_path, kind)) = mount_path(&req.path).map(|(m, k)| (m.to_owned(), k))
400            else {
401                writer.write_body(404, "text/plain", b"Not Found").await?;
402                return Ok(writer);
403            };
404            let registry_path = format!("/{mount_path}");
405            let Some(mount) = manager.registry.get_handle(&registry_path) else {
406                writer
407                    .write_body(404, "text/plain", b"Mount not found")
408                    .await?;
409                return Ok(writer);
410            };
411            let channel = manager.channel(&registry_path);
412            manager.start(mount, channel.clone());
413            match kind {
414                "playlist" => {
415                    // 这里**不能**用 tokio::time::timeout 等切片器就绪:实测在该运行
416                    // 上下文里定时器不推进,handler 会一直挂着(客户端 0 字节直到超时)。
417                    // 没数据就立刻 503,让播放器按自己的节奏重试(与 C 版行为一致)。
418                    // LL-HLS 阻塞重载:_HLS_msn=<分片号>&_HLS_part=<part 序号>。
419                    // 客户端请求"下一块",服务端等它产出再回(最多 2 s),减少空轮询。
420                    {
421                        let want_msn = req
422                            .query
423                            .iter()
424                            .find(|(k, _)| k.as_str() == "_HLS_msn")
425                            .and_then(|(_, v)| v.parse::<u32>().ok());
426                        let want_part = req
427                            .query
428                            .iter()
429                            .find(|(k, _)| k.as_str() == "_HLS_part")
430                            .and_then(|(_, v)| v.parse::<u32>().ok());
431                        if let Some(msn) = want_msn {
432                            let deadline = tokio::time::Instant::now()
433                                + std::time::Duration::from_millis(2000);
434                            let is_ready = || {
435                                let state = channel
436                                    .state
437                                    .lock()
438                                    .unwrap_or_else(std::sync::PoisonError::into_inner);
439                                state.segments.contains_key(&msn)
440                                    || match want_part {
441                                        Some(idx) => state.parts.contains_key(&(msn, idx)),
442                                        None => state.parts.keys().any(|(m, _)| *m == msn),
443                                    }
444                                    || state
445                                        .segments
446                                        .keys()
447                                        .next_back()
448                                        .is_some_and(|last| msn < *last)
449                            };
450                            loop {
451                                if is_ready() {
452                                    break;
453                                }
454                                let left =
455                                    deadline.saturating_duration_since(tokio::time::Instant::now());
456                                if left.is_zero() {
457                                    break;
458                                }
459                                // Enable the waiter before re-checking so a part
460                                // produced between the check and the await cannot
461                                // be missed; wait for the whole remaining budget
462                                // instead of re-polling every 100 ms.
463                                let notified = channel.ready.notified();
464                                tokio::pin!(notified);
465                                let _ = notified.as_mut().enable();
466                                if is_ready() {
467                                    break;
468                                }
469                                let _ = tokio::time::timeout(left, notified).await;
470                            }
471                        }
472                    }
473                    let query = req
474                        .query
475                        .iter()
476                        .map(|(k, v)| format!("{k}={v}"))
477                        .collect::<Vec<_>>()
478                        .join("&");
479                    let body = manager.playlist(&channel, &query);
480                    writer
481                        .write_headers(
482                            200,
483                            &[
484                                ("Content-Type", "application/vnd.apple.mpegurl"),
485                                ("Content-Length", &body.len().to_string()),
486                                ("Cache-Control", "no-cache"),
487                                ("Access-Control-Allow-Origin", "*"),
488                                ("Connection", "keep-alive"),
489                            ],
490                        )
491                        .await?;
492                    writer.write_raw(body.as_bytes()).await?;
493                }
494                "init" => {
495                    let init = {
496                        channel
497                            .state
498                            .lock()
499                            .unwrap_or_else(std::sync::PoisonError::into_inner)
500                            .init
501                            .clone()
502                    };
503                    if init.is_empty() {
504                        writer.write_body(404, "text/plain", b"No init").await?;
505                        return Ok(writer);
506                    }
507                    writer
508                        .write_headers(
509                            200,
510                            &[
511                                ("Content-Type", "video/mp4"),
512                                ("Content-Length", &init.len().to_string()),
513                                ("Cache-Control", "no-store"),
514                                ("Access-Control-Allow-Origin", "*"),
515                            ],
516                        )
517                        .await?;
518                    writer.write_raw(&init).await?;
519                }
520                "part" => {
521                    let file = req.path.rsplit('/').next().unwrap_or("");
522                    let mut it = file.trim_end_matches(".m4s").split('-');
523                    let _ = it.next();
524                    let msn = it
525                        .next()
526                        .and_then(|v| v.parse::<u32>().ok())
527                        .unwrap_or(u32::MAX);
528                    let idx = it
529                        .next()
530                        .and_then(|v| v.parse::<u32>().ok())
531                        .unwrap_or(u32::MAX);
532                    let bytes = {
533                        channel
534                            .state
535                            .lock()
536                            .unwrap_or_else(std::sync::PoisonError::into_inner)
537                            .parts
538                            .get(&(msn, idx))
539                            .map(|part| part.bytes.clone())
540                    };
541                    let Some(bytes) = bytes else {
542                        writer
543                            .write_body(404, "text/plain", b"Part not found")
544                            .await?;
545                        return Ok(writer);
546                    };
547                    writer
548                        .write_headers(
549                            200,
550                            &[
551                                ("Content-Type", "video/iso.segment"),
552                                ("Content-Length", &bytes.len().to_string()),
553                                ("Cache-Control", "no-store"),
554                                ("Access-Control-Allow-Origin", "*"),
555                            ],
556                        )
557                        .await?;
558                    writer.write_raw(&bytes).await?;
559                }
560                "segment" => {
561                    let seq = req
562                        .path
563                        .rsplit('/')
564                        .next()
565                        .and_then(|f| f.strip_suffix(".m4s"))
566                        .and_then(|v| v.parse::<u32>().ok())
567                        .unwrap_or(u32::MAX);
568                    let bytes = {
569                        channel
570                            .state
571                            .lock()
572                            .unwrap_or_else(std::sync::PoisonError::into_inner)
573                            .segments
574                            .get(&seq)
575                            .map(|(bytes, _)| bytes.clone())
576                    };
577                    let Some(bytes) = bytes else {
578                        writer
579                            .write_body(404, "text/plain", b"Segment not found")
580                            .await?;
581                        return Ok(writer);
582                    };
583                    writer
584                        .write_headers(
585                            200,
586                            &[
587                                ("Content-Type", "video/iso.segment"),
588                                ("Content-Length", &bytes.len().to_string()),
589                                ("Cache-Control", "no-store"),
590                                ("Access-Control-Allow-Origin", "*"),
591                            ],
592                        )
593                        .await?;
594                    writer.write_raw(&bytes).await?;
595                }
596                _ => {
597                    writer.write_body(404, "text/plain", b"Not Found").await?;
598                }
599            }
600            Ok(writer)
601        })
602    })
603}
604
605#[cfg(test)]
606mod tests {
607    use super::query_suffix;
608
609    #[test]
610    fn blocking_reload_query_is_not_propagated_to_media_uris() {
611        assert_eq!(query_suffix("_HLS_msn=21&_HLS_part=9"), "");
612        assert_eq!(query_suffix("token=abc&_HLS_msn=21"), "?token=abc");
613        assert_eq!(query_suffix("_HLS_skip=YES&key=x"), "?key=x");
614        assert_eq!(query_suffix("token=abc"), "?token=abc");
615    }
616}