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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! Disk-backed HLS VOD generation from `VodSource` (recordings or files).
use super::{
    playlist,
    segmenter::{Segment, Segmenter, SegmenterConfig},
};
use rtflow_http::{Handler, Method, ResponseWriter};
use rtflow_media::vod::VodSource;
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    sync::{Arc, RwLock},
    time::Duration,
};
use tokio::sync::Mutex;

/// One VOD source exposed through HLS.
#[derive(Clone)]
pub struct HlsVodEntry {
    pub id: String,
    pub title: String,
    pub duration: Option<Duration>,
    pub source: Arc<dyn VodSource>,
}

/// VOD generation configuration.
#[derive(Clone, Debug)]
pub struct HlsVodConfig {
    pub segment_duration: Duration,
    pub cache_dir: PathBuf,
}

/// Bump when the generated fMP4 layout/codec handling changes so existing
/// on-disk VOD caches are regenerated instead of serving stale corrupt data.
const VOD_CACHE_VERSION: u32 = 4;

/// How long a computed source fingerprint is trusted. Long enough to serve a
/// playlist plus its segments without rescanning, short enough that a growing
/// recording is picked up.
const FINGERPRINT_TTL: Duration = Duration::from_secs(2);

/// Caches generated fMP4 files on disk and serializes generation per id.
pub struct HlsVodManager {
    entries: RwLock<HashMap<String, HlsVodEntry>>,
    config: HlsVodConfig,
    locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
    /// Fingerprint of each source with the time it was computed.
    ///
    /// Walking a recording directory costs one `stat` per segment (a day of
    /// 10 s segments is ~8600), and `ensure` used to do that on every request —
    /// including every segment fetch. The value only changes while a recording
    /// is still growing, so a short TTL keeps it fresh.
    fingerprints: std::sync::Mutex<HashMap<String, (std::time::Instant, Option<String>)>>,
    /// Ids whose cache directory was verified (or generated) recently.
    ///
    /// The verification itself stats `index.m3u8` and reads `.fingerprint`
    /// per request; with a playlist plus N segment fetches that is 2 syscalls
    /// per segment. Entries live for the same TTL as the fingerprint and are
    /// dropped whenever the catalog changes.
    validated: std::sync::Mutex<HashMap<String, std::time::Instant>>,
}

impl HlsVodManager {
    pub fn new(entries: Vec<HlsVodEntry>, config: HlsVodConfig) -> Self {
        Self {
            entries: RwLock::new(
                entries
                    .into_iter()
                    .map(|entry| (entry.id.clone(), entry))
                    .collect(),
            ),
            config,
            locks: Mutex::new(HashMap::new()),
            fingerprints: std::sync::Mutex::new(HashMap::new()),
            validated: std::sync::Mutex::new(HashMap::new()),
        }
    }

    /// Remove a generated cache entry so the next request regenerates it
    /// from the (possibly changed) source.
    pub fn invalidate(&self, id: &str) -> rtflow_core::error::Result<bool> {
        if !self
            .entries
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .contains_key(id)
        {
            return Ok(false);
        }
        self.validated
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(id);
        let directory = self.config.cache_dir.join(id);
        if directory.is_dir() {
            std::fs::remove_dir_all(directory)?;
        }
        Ok(true)
    }

    /// Snapshot of the current catalog, ordered by id.
    pub fn entries(&self) -> Vec<HlsVodEntry> {
        let mut entries: Vec<HlsVodEntry> = self
            .entries
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .values()
            .cloned()
            .collect();
        entries.sort_by(|left, right| left.id.cmp(&right.id));
        entries
    }

    pub fn entry(&self, id: &str) -> Option<HlsVodEntry> {
        self.entries
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(id)
            .cloned()
    }

    /// Add or replace an entry. Used by the recording/VOD catalog when new
    /// recordings finish while the server is running.
    pub fn upsert_entry(&self, entry: HlsVodEntry) {
        self.fingerprints
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(&entry.id);
        self.validated
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(&entry.id);
        self.entries
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(entry.id.clone(), entry);
    }

    /// Generated cache size for an entry: `None` when unknown, `Some(0)` when
    /// the VOD exists but has not been generated yet.
    pub fn cache_size(&self, id: &str) -> Option<u64> {
        if !self
            .entries
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .contains_key(id)
        {
            return None;
        }
        let directory = self.config.cache_dir.join(id);
        if !directory.is_dir() {
            return Some(0);
        }
        let mut total = 0;
        let mut stack = vec![directory];
        while let Some(current) = stack.pop() {
            let Ok(entries) = std::fs::read_dir(current) else {
                continue;
            };
            for entry in entries.flatten() {
                let Ok(metadata) = entry.metadata() else {
                    continue;
                };
                if metadata.is_dir() {
                    stack.push(entry.path());
                } else {
                    total += metadata.len();
                }
            }
        }
        Some(total)
    }

    pub fn remove_entry(&self, id: &str) -> bool {
        self.fingerprints
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(id);
        self.validated
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(id);
        let removed = self
            .entries
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(id)
            .is_some();
        if removed {
            let _ = std::fs::remove_dir_all(self.config.cache_dir.join(id));
        }
        removed
    }

    async fn lock_for(&self, id: &str) -> Arc<Mutex<()>> {
        self.locks
            .lock()
            .await
            .entry(id.to_owned())
            .or_insert_with(|| Arc::new(Mutex::new(())))
            .clone()
    }

    /// Fingerprint of a VOD source, cached for [`FINGERPRINT_TTL`] and
    /// computed on the blocking pool: it stats every segment file in the
    /// recording directory.
    async fn cached_fingerprint(&self, id: &str, source: Arc<dyn VodSource>) -> Option<String> {
        {
            let cached = self
                .fingerprints
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if let Some((at, value)) = cached.get(id)
                && at.elapsed() < FINGERPRINT_TTL
            {
                return value.clone();
            }
        }
        let value = tokio::task::spawn_blocking(move || source.fingerprint())
            .await
            .ok()
            .flatten();
        self.fingerprints
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(id.to_owned(), (std::time::Instant::now(), value.clone()));
        value
    }

    /// True when this id's cache directory was verified within the TTL.
    fn is_validated(&self, id: &str) -> bool {
        self.validated
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(id)
            .is_some_and(|at| at.elapsed() < FINGERPRINT_TTL)
    }

    fn mark_validated(&self, id: &str) {
        self.validated
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(id.to_owned(), std::time::Instant::now());
    }

    async fn ensure(&self, id: &str) -> rtflow_core::error::Result<PathBuf> {
        let entry = self
            .entry(id)
            .ok_or_else(|| rtflow_core::error::Error::Rtsp("VOD id not found".into()))?;
        let valid = id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '@'));
        if !valid || id == "." || id == ".." || id.starts_with('.') {
            return Err(rtflow_core::error::Error::InvalidConfig(
                "invalid VOD id".into(),
            ));
        }
        let directory = self.config.cache_dir.join(id);
        if self.is_validated(id) {
            return Ok(directory);
        }
        let fingerprint = self.cached_fingerprint(id, entry.source.clone()).await;
        let cache_valid = |directory: &Path| {
            if !directory.join("index.m3u8").is_file() {
                return false;
            }
            match fingerprint.as_deref() {
                Some(expected) => std::fs::read_to_string(directory.join(".fingerprint"))
                    .is_ok_and(|stored| stored == format!("{VOD_CACHE_VERSION}:{expected}")),
                None => true,
            }
        };
        if cache_valid(&directory) {
            self.mark_validated(id);
            return Ok(directory);
        }
        let lock = self.lock_for(id).await;
        let _guard = lock.lock().await;
        if cache_valid(&directory) {
            self.mark_validated(id);
            return Ok(directory);
        }
        let cleanup = directory.clone();
        tokio::task::spawn_blocking(move || match std::fs::remove_dir_all(&cleanup) {
            Ok(()) => Ok(()),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(error) => Err(error),
        })
        .await
        .map_err(|error| {
            rtflow_core::error::Error::Media(format!("VOD cleanup worker failed: {error}"))
        })??;
        let temporary = self.config.cache_dir.join(format!(".tmp-{id}"));
        let source = entry.source.clone();
        let config = self.config.clone();
        let label = entry.title.clone();
        let target = directory.clone();
        let temporary_for_cleanup = temporary.clone();
        tokio::task::spawn_blocking(move || {
            let _ = std::fs::remove_dir_all(&temporary_for_cleanup);
            if let Err(error) = generate(source, &label, &config, &temporary_for_cleanup) {
                let _ = std::fs::remove_dir_all(&temporary_for_cleanup);
                return Err(error);
            }
            if let Some(fingerprint) = fingerprint {
                let _ = std::fs::write(
                    temporary_for_cleanup.join(".fingerprint"),
                    format!("{VOD_CACHE_VERSION}:{fingerprint}"),
                );
            }
            if let Err(error) = std::fs::rename(&temporary_for_cleanup, &target) {
                let _ = std::fs::remove_dir_all(&temporary_for_cleanup);
                return Err(error.into());
            }
            Ok::<(), rtflow_core::error::Error>(())
        })
        .await
        .map_err(|error| {
            rtflow_core::error::Error::Media(format!("VOD worker failed: {error}"))
        })??;
        self.mark_validated(id);
        Ok(directory)
    }

    async fn playlist(&self, id: &str) -> rtflow_core::error::Result<String> {
        let directory = self.ensure(id).await?;
        Ok(tokio::fs::read_to_string(directory.join("index.m3u8")).await?)
    }

    async fn file(&self, id: &str, name: &str) -> rtflow_core::error::Result<Option<Vec<u8>>> {
        let directory = self.ensure(id).await?;
        let path = directory.join(name);
        if !path.is_file() {
            return Ok(None);
        }
        Ok(Some(tokio::fs::read(path).await?))
    }
}

fn generate(
    source: Arc<dyn VodSource>,
    title: &str,
    config: &HlsVodConfig,
    directory: &Path,
) -> rtflow_core::error::Result<()> {
    std::fs::create_dir_all(directory)?;
    let description = source.description().clone();
    tracing::info!(
        title,
        tracks = description.tracks.len(),
        segment_ms = config.segment_duration.as_millis() as u64,
        "HLS VOD generation started"
    );
    let mut demuxer = source.open()?;
    // MPEG-TS is the most interoperable HLS container (Firefox MSE rejects
    // this project's fMP4 init/sample layout). Fall back to fMP4 when the
    // description has no codec configuration for the TS pipeline.
    let mut segmenter = Segmenter::new_mpegts(
        SegmenterConfig {
            segment_duration: config.segment_duration,
            lookback_count: 1,
        },
        &description,
    );
    let mut segments = segmenter.subscribe();
    let mut completed = Vec::new();
    while let Some(sample) = demuxer.next_sample()? {
        segmenter.push(sample.unit);
        while let Ok(segment) = segments.try_recv() {
            completed.push(segment);
        }
    }
    segmenter.flush();
    while let Ok(segment) = segments.try_recv() {
        completed.push(segment);
    }
    tracing::info!(
        title,
        segments = completed.len(),
        "HLS VOD generation finished"
    );
    if completed.is_empty() {
        return Err(rtflow_core::error::Error::Media(format!(
            "VOD {title} produced no segments"
        )));
    }
    let mpeg_ts = completed
        .first()
        .is_some_and(|segment| segment.format == crate::segmenter::SegmentFormat::MpegTs);
    if !mpeg_ts {
        let init = completed
            .first()
            .map(|segment| segment.init.clone())
            .unwrap_or_default();
        std::fs::write(directory.join("init.m4s"), &init)?;
    }
    let extension = if mpeg_ts { "ts" } else { "m4s" };
    for segment in &completed {
        std::fs::write(
            directory.join(format!("{}.{extension}", segment.sequence)),
            &segment.data,
        )?;
    }
    let playlist_segments: Vec<Segment> = completed
        .into_iter()
        .map(|mut segment| {
            segment.data = bytes::Bytes::new();
            segment
        })
        .collect();
    // Give every regeneration a new URI token: a browser that cached an old
    // (possibly corrupt) init/segment under the same name must fetch the new
    // files instead of reusing them.
    let token = format!(
        "v={VOD_CACHE_VERSION}-{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    );
    let body = playlist::write_vod_playlist_at_q(&playlist_segments, "", &token);
    std::fs::write(directory.join("index.m3u8"), body)?;
    Ok(())
}

fn parse(path: &str) -> Option<(&str, &str)> {
    let rest = path.strip_prefix("/vod/")?;
    if let Some(id) = rest.strip_suffix("/index.m3u8") {
        return Some((id, "playlist"));
    }
    if let Some(id) = rest.strip_suffix("/init.m4s") {
        return Some((id, "init"));
    }
    let (id, file) = rest.rsplit_once('/')?;
    if file.ends_with(".m4s") || file.ends_with(".ts") {
        return Some((id, "segment"));
    }
    None
}

fn byte_range(header: Option<&str>, length: usize) -> Option<(usize, usize)> {
    let value = header?.strip_prefix("bytes=")?;
    let (start, end) = value.split_once('-')?;
    if start.is_empty() {
        // Suffix form: bytes=-N asks for the last N bytes.
        let suffix = end.parse::<usize>().ok()?.min(length);
        let start = length.checked_sub(suffix)?;
        return (suffix > 0).then_some((start, length - 1));
    }
    let start = start.parse::<usize>().ok()?;
    let end = if end.is_empty() {
        length.checked_sub(1)?
    } else {
        end.parse::<usize>().ok()?.min(length.checked_sub(1)?)
    };
    (start <= end && start < length).then_some((start, end))
}

/// Handler for `/vod/{id}/index.m3u8`, `/init.m4s`, `/{seq}.m4s`.
pub fn create_hls_vod_handler(manager: Arc<HlsVodManager>) -> Handler {
    Arc::new(move |req, mut writer| {
        let manager = manager.clone();
        Box::pin(async move {
            let Some((id, kind)) = parse(&req.path).map(|(id, kind)| (id.to_owned(), kind)) else {
                writer.write_body(404, "text/plain", b"Not Found").await?;
                return Ok(writer);
            };
            if manager.entry(&id).is_none() {
                writer
                    .write_body(404, "text/plain", b"VOD not found")
                    .await?;
                return Ok(writer);
            }
            let head = req.method == Method::Head;
            match kind {
                "playlist" => match manager.playlist(&id).await {
                    Ok(body) => {
                        let length = body.len().to_string();
                        writer
                            .write_headers(
                                200,
                                &[
                                    ("Content-Type", "application/vnd.apple.mpegurl"),
                                    ("Content-Length", length.as_str()),
                                    ("Cache-Control", "no-store"),
                                    ("Access-Control-Allow-Origin", "*"),
                                    ("Connection", "close"),
                                ],
                            )
                            .await?;
                        if !head {
                            writer.write_raw(body.as_bytes()).await?;
                            writer.flush().await?;
                        }
                        Ok(writer)
                    }
                    Err(error) => {
                        tracing::warn!(%error, %id, "HLS VOD generation failed");
                        writer
                            .write_body(500, "text/plain", b"VOD generation failed")
                            .await?;
                        Ok(writer)
                    }
                },
                "init" | "segment" => {
                    let name = if kind == "init" {
                        "init.m4s".to_owned()
                    } else {
                        req.path.rsplit('/').next().unwrap_or("").to_owned()
                    };
                    match manager.file(&id, &name).await {
                        Ok(Some(body)) => {
                            let content_type = if kind == "init" {
                                "video/mp4"
                            } else if name.ends_with(".ts") {
                                "video/mp2t"
                            } else {
                                "video/iso.segment"
                            };
                            let range = byte_range(req.header("range"), body.len());
                            let (status, slice_start, slice_end) = match range {
                                Some((start, end)) => (206, start, end + 1),
                                None => (200, 0, body.len()),
                            };
                            let length = (slice_end - slice_start).to_string();
                            let content_range = format!(
                                "bytes {slice_start}-{}/{body_len}",
                                slice_end - 1,
                                body_len = body.len()
                            );
                            let mut headers = vec![
                                ("Content-Type", content_type),
                                ("Content-Length", length.as_str()),
                                ("Cache-Control", "no-store"),
                                ("Access-Control-Allow-Origin", "*"),
                                ("Accept-Ranges", "bytes"),
                                ("Connection", "close"),
                            ];
                            if status == 206 {
                                headers.push(("Content-Range", content_range.as_str()));
                            }
                            writer.write_headers(status, &headers).await?;
                            if !head {
                                writer.write_raw(&body[slice_start..slice_end]).await?;
                            }
                            writer.flush().await?;
                            Ok(writer)
                        }
                        Ok(None) => {
                            writer.write_body(404, "text/plain", b"Not Found").await?;
                            Ok(writer)
                        }
                        Err(error) => {
                            tracing::warn!(%error, %id, "HLS VOD file failed");
                            writer.write_body(500, "text/plain", b"VOD failed").await?;
                            Ok(writer)
                        }
                    }
                }
                _ => {
                    writer.write_body(404, "text/plain", b"Not Found").await?;
                    Ok(writer)
                }
            }
        })
    })
}

#[allow(dead_code)]
fn _keep_handler_import(_: ResponseWriter<tokio::net::tcp::OwnedWriteHalf>) {}

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

    #[test]
    fn byte_range_supports_suffix_and_open_ended() {
        assert_eq!(byte_range(Some("bytes=-10"), 100), Some((90, 99)));
        assert_eq!(byte_range(Some("bytes=10-"), 100), Some((10, 99)));
        assert_eq!(byte_range(Some("bytes=10-19"), 100), Some((10, 19)));
        assert_eq!(byte_range(Some("bytes=-0"), 100), None);
        assert_eq!(byte_range(Some("bytes=200-"), 100), None);
    }

    /// The source fingerprint (one `stat` per segment) must not be recomputed
    /// for every playlist/segment request.
    #[tokio::test]
    async fn fingerprint_is_cached_between_requests() {
        use rtflow_media::MediaDescription;
        use rtflow_media::demux::Demuxer;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct CountingSource {
            scans: Arc<AtomicUsize>,
            description: MediaDescription,
        }

        impl VodSource for CountingSource {
            fn description(&self) -> &MediaDescription {
                &self.description
            }

            fn open(&self) -> rtflow_core::error::Result<Box<dyn Demuxer>> {
                Err(rtflow_core::error::Error::Unsupported("test".into()))
            }

            fn fingerprint(&self) -> Option<String> {
                self.scans.fetch_add(1, Ordering::Relaxed);
                Some("test-fingerprint".to_owned())
            }
        }

        let scans = Arc::new(AtomicUsize::new(0));
        let source: Arc<dyn VodSource> = Arc::new(CountingSource {
            scans: scans.clone(),
            description: MediaDescription::new("test", Vec::new()),
        });
        let manager = HlsVodManager::new(
            Vec::new(),
            HlsVodConfig {
                segment_duration: Duration::from_secs(1),
                cache_dir: std::env::temp_dir(),
            },
        );
        let first = manager.cached_fingerprint("vod", source.clone()).await;
        let second = manager.cached_fingerprint("vod", source).await;
        assert_eq!(first, second);
        assert_eq!(
            scans.load(Ordering::Relaxed),
            1,
            "the second lookup within the TTL must not rescan the source"
        );
    }
}