rtflow-hls 0.7.0

HLS (MPEG-TS live, fMP4 VOD and LL-HLS) endpoints for rtflow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! Low-Latency HLS (LL-HLS) live manager.
//!
//! This is a separate endpoint from the classic MPEG-TS HLS live path so the
//! stable 1 s TS pipeline is untouched. It uses `transmux::LlHlsSegmenter` to
//! emit CMAF parts (`#EXT-X-PART`) as they close, plus the completed segments
//! and a preload hint. Part/segment bytes are served from memory.

use super::segmenter::{pending_limits, track_spec};
use broadcast_core::ids::TrackId;
use bytes::Bytes;
use rtflow_http::Handler;
use rtflow_media::{Codec, MediaKind};
use rtflow_mount::MountRegistry;
use std::{
    collections::{BTreeMap, HashMap},
    sync::{Arc, Mutex},
};
use transmux::Sample;
use transmux::ll_hls::LlHlsSegmenter;

#[derive(Clone, Debug)]
pub struct LlHlsConfig {
    pub segment_duration: f64,
    pub part_target_ms: u32,
    /// Number of completed segments kept in the playlist/state.
    pub segment_window: u32,
}

impl Default for LlHlsConfig {
    fn default() -> Self {
        Self {
            segment_duration: 2.0,
            part_target_ms: 200,
            segment_window: 6,
        }
    }
}

struct Part {
    bytes: Bytes,
    duration: f64,
    independent: bool,
}

struct State {
    init: Bytes,
    parts: BTreeMap<(u32, u32), Part>,
    segments: BTreeMap<u32, (Bytes, f64)>,
}

struct Channel {
    state: Mutex<State>,
    active: Mutex<bool>,
    ready: tokio::sync::Notify,
}

pub struct LlHlsLiveManager {
    registry: Arc<MountRegistry>,
    config: LlHlsConfig,
    channels: Mutex<HashMap<String, Arc<Channel>>>,
}

impl LlHlsLiveManager {
    pub fn new(registry: Arc<MountRegistry>, config: LlHlsConfig) -> Self {
        Self {
            registry,
            config,
            channels: Mutex::new(HashMap::new()),
        }
    }

    fn channel(&self, path: &str) -> Arc<Channel> {
        self.channels
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .entry(path.to_owned())
            .or_insert_with(|| {
                Arc::new(Channel {
                    state: Mutex::new(State {
                        init: Bytes::new(),
                        parts: BTreeMap::new(),
                        segments: BTreeMap::new(),
                    }),
                    active: Mutex::new(false),
                    ready: tokio::sync::Notify::new(),
                })
            })
            .clone()
    }

    fn start(&self, mount: rtflow_mount::MountHandle, channel: Arc<Channel>) {
        let mut active = channel
            .active
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if *active {
            return;
        }
        // 与经典 HLS(create_hls_handlers)一致:把 mount 公布的 fmtp 补进轨道描述,
        // 否则 track_spec() 拿不到 sprop-parameter-sets,H.264 轨道会被整条跳过,
        // 切片器起不来(播放列表永远为空)。
        let mut description = (*mount.description()).clone();
        let announced_fmtp = mount.announce_fmtp();
        for track in &mut description.tracks {
            if let Some(fmtp) = announced_fmtp.get(&track.id) {
                track.fmtp = Some(fmtp.clone());
            }
        }
        if description.tracks.is_empty() {
            tracing::warn!(mount = %mount.path(), "LL-HLS:挂载点没有轨道描述,切片器不启动");
            return;
        }
        let mut specs = Vec::new();
        let mut timescales = HashMap::new();
        let mut durations = HashMap::new();
        for track in &description.tracks {
            if let Some(spec) = track_spec(track) {
                timescales.insert(track.id, track.clock_rate);
                let duration = match track.kind {
                    MediaKind::Video => track
                        .frame_rate
                        .map(|(n, d)| {
                            (u64::from(track.clock_rate) * u64::from(d) / u64::from(n).max(1))
                                as u32
                        })
                        .unwrap_or(3_000),
                    MediaKind::Audio => 1024,
                };
                durations.insert(track.id, duration.max(1));
                specs.push(spec);
            }
        }
        if specs.is_empty() {
            tracing::warn!(mount = %mount.path(), tracks = description.tracks.len(),
                "LL-HLS:轨道无法转成 transmux 规格(缺 codec/fmtp?),切片器不启动");
            return;
        }
        let track_count = specs.len();
        let Ok(mut segmenter) = LlHlsSegmenter::with_part_target(
            specs,
            broadcast_core::timescale!(90_000),
            std::time::Duration::from_secs_f64(self.config.segment_duration.max(0.001)),
            std::time::Duration::from_millis(u64::from(self.config.part_target_ms.max(1))),
            pending_limits(),
        ) else {
            return;
        };
        tracing::info!(
            mount = %mount.path(),
            tracks = track_count,
            segment_ms = (self.config.segment_duration * 1000.0) as u64,
            part_ms = self.config.part_target_ms,
            "LL-HLS segmenter started"
        );
        let init = segmenter.init_segment().unwrap_or_default();
        if init.is_empty() {
            tracing::warn!(mount = %mount.path(), "LL-HLS:init 段为空(SPS/PPS 还没到?)");
        }
        if let Ok(mut state) = channel.state.lock() {
            state.init = Bytes::from(init);
        }
        let cancel = mount.cancellation_token();
        let segment_window = self.config.segment_window.max(1);
        *active = true;
        drop(active);
        tokio::spawn(async move {
            let (mut receiver, startup) = mount.subscribe_with_startup();
            let mut startup = std::collections::VecDeque::from(startup);
            let mut awaiting_keyframe = true;
            loop {
                let unit = if let Some(unit) = startup.pop_front() {
                    unit
                } else {
                    tokio::select! {
                        _ = cancel.cancelled() => break,
                        result = receiver.recv() => match result {
                            Ok(unit) => unit,
                            Err(rtflow_mount::FrameRecvError::Lagged(_)) => { awaiting_keyframe = true; continue; }
                            Err(_) => break,
                        },
                    }
                };
                if awaiting_keyframe {
                    if !matches!(
                        unit.codec,
                        Codec::H264 | Codec::H265 | Codec::Vp9 | Codec::Av1
                    ) || !unit.is_keyframe
                    {
                        continue;
                    }
                    awaiting_keyframe = false;
                }
                let Some(&track_id) = timescales.get(&unit.track_id).map(|_| &unit.track_id) else {
                    continue;
                };
                let Some(timescale) = timescales.get(&track_id).copied() else {
                    continue;
                };
                let ticks = |d: std::time::Duration| {
                    (d.as_secs() * u64::from(timescale)
                        + u64::from(d.subsec_nanos()) * u64::from(timescale) / 1_000_000_000)
                        as i64
                };
                let duration = durations.get(&track_id).copied();
                let sample = if matches!(unit.codec, Codec::Aac | Codec::Pcma | Codec::Pcmu) {
                    Sample::from_raw(
                        unit.data.clone(),
                        Some(ticks(unit.dts.unwrap_or(unit.pts))),
                        Some(ticks(unit.pts)),
                        duration,
                    )
                } else {
                    Sample::from_annexb(
                        &unit.data,
                        Some(ticks(unit.dts.unwrap_or(unit.pts))),
                        Some(ticks(unit.pts)),
                        duration,
                        unit.is_keyframe,
                    )
                };
                let Ok(sample) = sample else {
                    continue;
                };
                if segmenter
                    .push(TrackId::new(u32::from(track_id) + 1), sample)
                    .is_err()
                {
                    continue;
                }
                let mut state = channel
                    .state
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                let mut produced = false;
                let parts_ready = segmenter.take_ready_parts();
                for part in parts_ready {
                    produced = true;
                    state.parts.insert(
                        (part.segment_seq, part.part_index.into()),
                        Part {
                            bytes: Bytes::from(part.bytes),
                            duration: part.duration.as_secs_f64(),
                            independent: part.independent,
                        },
                    );
                }
                for segment in segmenter.take_ready_segments() {
                    produced = true;
                    state.segments.insert(
                        segment.segment_seq,
                        (Bytes::from(segment.bytes), segment.duration.as_secs_f64()),
                    );
                    state.parts.retain(|(msn, _), _| *msn > segment.segment_seq);
                    let keep_from = segment.segment_seq.saturating_sub(segment_window);
                    state.segments.retain(|seq, _| *seq >= keep_from);
                }
                drop(state);
                // Parts close every `part_target_ms`, not on every frame:
                // waking blocking reloads per frame was 5-10x more wakeups
                // than there were results to deliver.
                if produced {
                    channel.ready.notify_waiters();
                }
            }
            let mut state = channel
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let _ = segmenter.flush();
            let mut produced = false;
            for part in segmenter.take_ready_parts() {
                produced = true;
                state.parts.insert(
                    (part.segment_seq, part.part_index.into()),
                    Part {
                        bytes: Bytes::from(part.bytes),
                        duration: part.duration.as_secs_f64(),
                        independent: part.independent,
                    },
                );
            }
            for segment in segmenter.take_ready_segments() {
                produced = true;
                state.segments.insert(
                    segment.segment_seq,
                    (Bytes::from(segment.bytes), segment.duration.as_secs_f64()),
                );
            }
            drop(state);
            if produced {
                channel.ready.notify_waiters();
            }
        });
    }

    fn playlist(&self, channel: &Channel, query: &str) -> String {
        let state = channel
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut out = String::from("#EXTM3U\n#EXT-X-VERSION:9\n#EXT-X-INDEPENDENT-SEGMENTS\n");
        // 别名端点(/live/main.m3u8)下,分片 URI 需要带上流名前缀,
        // 播放器才会请求 /live/main/<name>;/llhls 端点保持空前缀。
        let prefix = query
            .split('&')
            .find_map(|kv| kv.strip_prefix("_PREFIX="))
            .unwrap_or("")
            .to_string();
        out.push_str(&format!(
            "#EXT-X-TARGETDURATION:{}\n",
            self.config.segment_duration.ceil().max(1.0) as u64
        ));
        out.push_str(&format!(
            "#EXT-X-PART-INF:PART-TARGET={:.3}\n",
            f64::from(self.config.part_target_ms) / 1000.0
        ));
        out.push_str(&format!(
            "#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK={:.3}\n",
            f64::from(self.config.part_target_ms) * 3.0 / 1000.0
        ));
        let first_sequence = state
            .segments
            .keys()
            .next()
            .copied()
            .or_else(|| state.parts.keys().next().map(|(msn, _)| *msn))
            .unwrap_or(0);
        out.push_str(&format!("#EXT-X-MEDIA-SEQUENCE:{first_sequence}\n"));
        out.push_str(&format!(
            "#EXT-X-MAP:URI=\"{prefix}init.m4s{}\"\n",
            query_suffix(query)
        ));
        let last_segment = state.segments.keys().next_back().copied().unwrap_or(0);
        for (&seq, (_, duration)) in &state.segments {
            out.push_str(&format!(
                "#EXTINF:{duration:.3},\n{prefix}{seq}.m4s{}\n",
                query_suffix(query)
            ));
        }
        for (&(msn, idx), part) in state.parts.range((last_segment + 1, 0)..) {
            out.push_str(&format!(
                "#EXT-X-PART:DURATION={:.3},URI=\"{prefix}part-{msn}-{idx}.m4s{}\",INDEPENDENT={}\n",
                part.duration,
                query_suffix(query),
                if part.independent { "YES" } else { "NO" }
            ));
        }
        if let Some(&(msn, _)) = state.parts.keys().next_back() {
            out.push_str(&format!(
                "#EXT-X-PRELOAD-HINT:TYPE=PART,URI=\"{prefix}part-{}-0.m4s{}\"\n",
                msn + 1,
                query_suffix(query)
            ));
        }
        out
    }
}

fn query_suffix(query: &str) -> String {
    // HLS blocking-reload parameters belong to the playlist request only.
    // Never append them to media/part URIs (hls.js would request them as media).
    let filtered = query
        .split('&')
        .filter(|pair| {
            let key = pair.split_once('=').map(|(key, _)| key).unwrap_or(pair);
            !key.starts_with("_HLS_") && !key.starts_with("_PREFIX")
        })
        .collect::<Vec<_>>()
        .join("&");
    if filtered.is_empty() {
        String::new()
    } else {
        format!("?{filtered}")
    }
}

fn mount_path(path: &str) -> Option<(&str, &str)> {
    let rest = path.strip_prefix("/llhls/")?;
    if let Some(mount) = rest.strip_suffix("/index.m3u8") {
        return Some((mount, "playlist"));
    }
    if let Some(mount) = rest.strip_suffix("/init.m4s") {
        return Some((mount, "init"));
    }
    let (mount, file) = rest.rsplit_once('/')?;
    if file.starts_with("part-") && file.ends_with(".m4s") {
        return Some((mount, "part"));
    }
    if file.ends_with(".m4s") {
        return Some((mount, "segment"));
    }
    None
}

pub fn create_ll_hls_handler(manager: Arc<LlHlsLiveManager>) -> Handler {
    Arc::new(move |req, mut writer| {
        let manager = manager.clone();
        Box::pin(async move {
            let Some((mount_path, kind)) = mount_path(&req.path).map(|(m, k)| (m.to_owned(), k))
            else {
                writer.write_body(404, "text/plain", b"Not Found").await?;
                return Ok(writer);
            };
            let registry_path = format!("/{mount_path}");
            let Some(mount) = manager.registry.get_handle(&registry_path) else {
                writer
                    .write_body(404, "text/plain", b"Mount not found")
                    .await?;
                return Ok(writer);
            };
            let channel = manager.channel(&registry_path);
            manager.start(mount, channel.clone());
            match kind {
                "playlist" => {
                    // 这里**不能**用 tokio::time::timeout 等切片器就绪:实测在该运行
                    // 上下文里定时器不推进,handler 会一直挂着(客户端 0 字节直到超时)。
                    // 没数据就立刻 503,让播放器按自己的节奏重试(与 C 版行为一致)。
                    // LL-HLS 阻塞重载:_HLS_msn=<分片号>&_HLS_part=<part 序号>。
                    // 客户端请求"下一块",服务端等它产出再回(最多 2 s),减少空轮询。
                    {
                        let want_msn = req
                            .query
                            .iter()
                            .find(|(k, _)| k.as_str() == "_HLS_msn")
                            .and_then(|(_, v)| v.parse::<u32>().ok());
                        let want_part = req
                            .query
                            .iter()
                            .find(|(k, _)| k.as_str() == "_HLS_part")
                            .and_then(|(_, v)| v.parse::<u32>().ok());
                        if let Some(msn) = want_msn {
                            let deadline = tokio::time::Instant::now()
                                + std::time::Duration::from_millis(2000);
                            let is_ready = || {
                                let state = channel
                                    .state
                                    .lock()
                                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                                state.segments.contains_key(&msn)
                                    || match want_part {
                                        Some(idx) => state.parts.contains_key(&(msn, idx)),
                                        None => state.parts.keys().any(|(m, _)| *m == msn),
                                    }
                                    || state
                                        .segments
                                        .keys()
                                        .next_back()
                                        .is_some_and(|last| msn < *last)
                            };
                            loop {
                                if is_ready() {
                                    break;
                                }
                                let left =
                                    deadline.saturating_duration_since(tokio::time::Instant::now());
                                if left.is_zero() {
                                    break;
                                }
                                // Enable the waiter before re-checking so a part
                                // produced between the check and the await cannot
                                // be missed; wait for the whole remaining budget
                                // instead of re-polling every 100 ms.
                                let notified = channel.ready.notified();
                                tokio::pin!(notified);
                                let _ = notified.as_mut().enable();
                                if is_ready() {
                                    break;
                                }
                                let _ = tokio::time::timeout(left, notified).await;
                            }
                        }
                    }
                    let query = req
                        .query
                        .iter()
                        .map(|(k, v)| format!("{k}={v}"))
                        .collect::<Vec<_>>()
                        .join("&");
                    let body = manager.playlist(&channel, &query);
                    writer
                        .write_headers(
                            200,
                            &[
                                ("Content-Type", "application/vnd.apple.mpegurl"),
                                ("Content-Length", &body.len().to_string()),
                                ("Cache-Control", "no-cache"),
                                ("Access-Control-Allow-Origin", "*"),
                                ("Connection", "keep-alive"),
                            ],
                        )
                        .await?;
                    writer.write_raw(body.as_bytes()).await?;
                }
                "init" => {
                    let init = {
                        channel
                            .state
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)
                            .init
                            .clone()
                    };
                    if init.is_empty() {
                        writer.write_body(404, "text/plain", b"No init").await?;
                        return Ok(writer);
                    }
                    writer
                        .write_headers(
                            200,
                            &[
                                ("Content-Type", "video/mp4"),
                                ("Content-Length", &init.len().to_string()),
                                ("Cache-Control", "no-store"),
                                ("Access-Control-Allow-Origin", "*"),
                            ],
                        )
                        .await?;
                    writer.write_raw(&init).await?;
                }
                "part" => {
                    let file = req.path.rsplit('/').next().unwrap_or("");
                    let mut it = file.trim_end_matches(".m4s").split('-');
                    let _ = it.next();
                    let msn = it
                        .next()
                        .and_then(|v| v.parse::<u32>().ok())
                        .unwrap_or(u32::MAX);
                    let idx = it
                        .next()
                        .and_then(|v| v.parse::<u32>().ok())
                        .unwrap_or(u32::MAX);
                    let bytes = {
                        channel
                            .state
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)
                            .parts
                            .get(&(msn, idx))
                            .map(|part| part.bytes.clone())
                    };
                    let Some(bytes) = bytes else {
                        writer
                            .write_body(404, "text/plain", b"Part not found")
                            .await?;
                        return Ok(writer);
                    };
                    writer
                        .write_headers(
                            200,
                            &[
                                ("Content-Type", "video/iso.segment"),
                                ("Content-Length", &bytes.len().to_string()),
                                ("Cache-Control", "no-store"),
                                ("Access-Control-Allow-Origin", "*"),
                            ],
                        )
                        .await?;
                    writer.write_raw(&bytes).await?;
                }
                "segment" => {
                    let seq = req
                        .path
                        .rsplit('/')
                        .next()
                        .and_then(|f| f.strip_suffix(".m4s"))
                        .and_then(|v| v.parse::<u32>().ok())
                        .unwrap_or(u32::MAX);
                    let bytes = {
                        channel
                            .state
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)
                            .segments
                            .get(&seq)
                            .map(|(bytes, _)| bytes.clone())
                    };
                    let Some(bytes) = bytes else {
                        writer
                            .write_body(404, "text/plain", b"Segment not found")
                            .await?;
                        return Ok(writer);
                    };
                    writer
                        .write_headers(
                            200,
                            &[
                                ("Content-Type", "video/iso.segment"),
                                ("Content-Length", &bytes.len().to_string()),
                                ("Cache-Control", "no-store"),
                                ("Access-Control-Allow-Origin", "*"),
                            ],
                        )
                        .await?;
                    writer.write_raw(&bytes).await?;
                }
                _ => {
                    writer.write_body(404, "text/plain", b"Not Found").await?;
                }
            }
            Ok(writer)
        })
    })
}

#[cfg(test)]
mod tests {
    use super::query_suffix;

    #[test]
    fn blocking_reload_query_is_not_propagated_to_media_uris() {
        assert_eq!(query_suffix("_HLS_msn=21&_HLS_part=9"), "");
        assert_eq!(query_suffix("token=abc&_HLS_msn=21"), "?token=abc");
        assert_eq!(query_suffix("_HLS_skip=YES&key=x"), "?key=x");
        assert_eq!(query_suffix("token=abc"), "?token=abc");
    }
}