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
//! Registry-backed HLS live endpoints for dynamic mounts (notably RTMP
//! publishers that create their mount after startup).
use super::{
HlsConfig, handler,
segment_ring::SegmentRing,
segmenter::{Segmenter, SegmenterConfig},
};
use rtflow_http::Handler;
use rtflow_mount::{FrameRecvError, MountHandle, MountRegistry};
use std::{
collections::HashMap,
sync::{
Arc, Mutex,
atomic::{AtomicU64, Ordering},
},
};
struct Channel {
ring: Arc<SegmentRing>,
/// `Some(generation)` while exactly one segmenter owns this channel.
/// Never start a second segmenter for the same mount: two segmenters
/// have independent sequence counters and interleave 114/115/116/115
/// into one playlist.
active: Arc<Mutex<Option<u64>>>,
next_generation: AtomicU64,
/// Next media sequence. Preserved across segmenter restarts so the
/// playlist's EXT-X-MEDIA-SEQUENCE never goes backwards.
next_sequence: Arc<AtomicU64>,
/// Cache-busting token for init/segments. A server restart or segmenter
/// restart must not reuse the previous run's browser-cached init.m4s.
generation: Mutex<String>,
/// Wall-clock start of the current segmenter generation, used for
/// `EXT-X-PROGRAM-DATE-TIME`.
started_at: Mutex<std::time::SystemTime>,
}
/// Per-registry HLS live manager. One segmenter/channel per mount.
pub struct HlsLiveManager {
registry: Arc<MountRegistry>,
config: HlsConfig,
channels: Mutex<HashMap<String, Arc<Channel>>>,
}
impl HlsLiveManager {
pub fn new(registry: Arc<MountRegistry>, config: HlsConfig) -> Self {
Self {
registry,
config,
channels: Mutex::new(HashMap::new()),
}
}
fn channel(&self, mount: &MountHandle) -> Arc<Channel> {
let key = mount.path().to_owned();
self.channels
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.entry(key)
.or_insert_with(|| {
Arc::new(Channel {
ring: Arc::new(SegmentRing::with_retention(
self.config.segment_count,
self.config.segment_count.saturating_mul(3),
)),
active: Arc::new(Mutex::new(None)),
next_generation: AtomicU64::new(0),
next_sequence: Arc::new(AtomicU64::new(0)),
generation: Mutex::new(format!(
"{:x}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
)),
started_at: Mutex::new(std::time::SystemTime::now()),
})
})
.clone()
}
fn ensure_started(&self, mount: &MountHandle, channel: &Arc<Channel>) {
let mut active = channel
.active
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if active.is_some() {
return;
}
let description = mount.description();
if description.tracks.is_empty() {
return;
}
let generation = channel.next_generation.fetch_add(1, Ordering::AcqRel) + 1;
*channel
.started_at
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = std::time::SystemTime::now();
*active = Some(generation);
*channel
.generation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = format!(
"{generation}-{:x}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
);
tracing::info!(
mount = %mount.path(),
tracks = description.tracks.len(),
segment_ms = self.config.segment_duration.as_millis() as u64,
window = self.config.segment_count,
generation,
"HLS live segmenter started"
);
let ring = channel.ring.clone();
let next_sequence = channel.next_sequence.clone();
let channel = channel.clone();
let mount = mount.clone();
let cancel = mount.cancellation_token();
let seg_config = SegmenterConfig {
segment_duration: self.config.segment_duration,
lookback_count: self.config.segment_count,
};
tokio::spawn(async move {
let mut segmenter = Segmenter::new_mpegts(seg_config, &description);
segmenter.set_sequence(next_sequence.load(Ordering::Acquire));
let mut segments = segmenter.subscribe();
let (mut receiver, startup) = mount.subscribe_with_startup();
let startup_keys = rtflow_mount::startup_dedup_keys(&startup);
let mut startup = std::collections::VecDeque::from(startup);
let has_video = description
.tracks
.iter()
.any(|track| track.kind == rtflow_media::MediaKind::Video);
let mut awaiting_keyframe = has_video;
let mut from_startup = true;
loop {
let unit = if let Some(unit) = startup.pop_front() {
unit
} else {
from_startup = false;
tokio::select! {
_ = cancel.cancelled() => break,
result = receiver.recv() => match result {
Ok(unit) => unit,
Err(FrameRecvError::Lagged(count)) => {
tracing::debug!(count, "HLS live lagged; waiting for a keyframe");
segmenter.reset_after_discontinuity();
awaiting_keyframe = has_video;
continue;
}
Err(FrameRecvError::Closed) => break,
},
}
};
if awaiting_keyframe {
let video = matches!(
unit.codec,
rtflow_media::Codec::H264 | rtflow_media::Codec::H265
);
if video {
if !unit.is_keyframe {
continue;
}
awaiting_keyframe = false;
} else {
// Do not let audio start a segment before the first
// video IDR: the segment would begin at an audio PTS
// and the video track would join it mid-GOP. hls.js
// then has no decodable video at the segment start.
continue;
}
}
if from_startup || !startup_keys.contains(&(unit.track_id, unit.rtp_timestamp)) {
segmenter.push((*unit).clone());
}
while let Ok(segment) = segments.try_recv() {
next_sequence.store(segment.sequence.saturating_add(1), Ordering::Release);
ring.push(segment);
}
}
let mut active = channel
.active
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if *active == Some(generation) {
channel.ring.clear();
*active = None;
}
});
}
}
fn mount_path(path: &str) -> Option<(&str, &str)> {
let rest = path.strip_prefix("/hls/")?;
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.ends_with(".m4s") || file.ends_with(".ts") {
return Some((mount, "segment"));
}
None
}
/// Handler for `/hls/{mount}/index.m3u8`, `/init.m4s`, `/{seq}.m4s`.
pub fn create_hls_live_handler(manager: Arc<HlsLiveManager>) -> 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(|(mount, kind)| (mount.to_owned(), kind))
else {
writer.write_body(404, "text/plain", b"Not Found").await?;
return Ok(writer);
};
let Some(mount) = manager.registry.get_handle(&format!("/{mount_path}")) else {
writer
.write_body(404, "text/plain", b"Mount not found")
.await?;
return Ok(writer);
};
let channel = manager.channel(&mount);
manager.ensure_started(&mount, &channel);
match kind {
"playlist" => {
if mount.description().tracks.is_empty() {
writer
.write_headers(
503,
&[
("Retry-After", "2"),
("Content-Length", "0"),
("Connection", "close"),
],
)
.await?;
return Ok(writer);
}
// hls.js treats a live playlist without any segment
// (or without EXT-X-MEDIA-SEQUENCE) as a fatal
// internalException. Wait for the first segment after
// starting the segmenter; keep a bounded wait so a
// publisher that never sends data gets 503 + retry.
if channel.ring.is_empty() {
for _ in 0..60 {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
if !channel.ring.is_empty() {
break;
}
}
}
if channel.ring.is_empty() {
writer
.write_headers(
503,
&[
("Retry-After", "1"),
("Content-Length", "0"),
("Connection", "close"),
],
)
.await?;
return Ok(writer);
}
let mut req = req;
// LL-HLS blocking playlist reload: hold the request until
// the requested media sequence exists (bounded).
if let Some(msn) = req
.query
.get("_HLS_msn")
.and_then(|value| value.parse::<u64>().ok())
{
let deadline =
tokio::time::Instant::now() + std::time::Duration::from_secs(3);
loop {
if channel
.ring
.latest_sequence()
.is_some_and(|latest| latest >= msn)
{
break;
}
let left =
deadline.saturating_duration_since(tokio::time::Instant::now());
if left.is_zero() {
break;
}
// Register before re-checking so a segment pushed
// between the check and the await is not missed;
// the wait consumes the whole remaining budget
// instead of re-polling every 50 ms (which cloned
// and sorted the whole ring each time).
let notified = channel.ring.notified();
tokio::pin!(notified);
let _ = notified.as_mut().enable();
if channel
.ring
.latest_sequence()
.is_some_and(|latest| latest >= msn)
{
break;
}
let _ = tokio::time::timeout(left, notified).await;
}
req.query.remove("_HLS_msn");
req.query.remove("_HLS_part");
}
let generation = channel
.generation
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
req.query.insert("v".to_owned(), generation);
let started_at = *channel
.started_at
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
handler::serve_playlist(
req,
writer,
&channel.ring,
true,
manager.config.segment_duration,
"",
Some(started_at),
)
.await
}
"init" => handler::serve_init_segment(req, writer, &channel.ring).await,
"segment" => {
let sequence = req
.path
.rsplit('/')
.next()
.and_then(|file| {
file.strip_suffix(".m4s")
.or_else(|| file.strip_suffix(".ts"))
})
.and_then(|value| value.parse::<u64>().ok())
.unwrap_or(u64::MAX);
handler::serve_segment(req, writer, &channel.ring, sequence).await
}
_ => {
writer.write_body(404, "text/plain", b"Not Found").await?;
Ok(writer)
}
}
})
})
}
// Keep the type visible in docs/tests without exposing internals.
#[allow(dead_code)]
fn _assert_send_sync() {
fn check<T: Send + Sync>() {}
check::<HlsLiveManager>();
}