arcly-stream 0.1.0

A high-performance live-media streaming kernel: lock-free zero-copy frame fan-out, instant-start GOP cache, pluggable HLS/recording, and trait-driven protocol/storage/auth/observer extension points — runtime, config, and metrics free.
Documentation
//! HLS / LL-HLS media-playlist (`.m3u8`) generation.

use std::collections::VecDeque;

/// One segment entry in a media playlist.
#[derive(Debug, Clone)]
pub struct Segment {
    /// Media sequence number (monotonic, never reused).
    pub seq: u64,
    /// Segment duration in seconds.
    pub duration: f64,
    /// Segment URI (relative path written under the stream's storage prefix).
    pub uri: String,
    /// Whether a discontinuity precedes this segment.
    pub discontinuity: bool,
}

/// A sliding-window HLS media playlist.
///
/// Holds the most recent `window` segments and renders a spec-compliant
/// `#EXTM3U` document. Set `low_latency` to emit `#EXT-X-PART` hints and the
/// LL-HLS preload/blocking tags (the segmenter supplies parts).
#[derive(Debug, Clone)]
pub struct HlsPlaylist {
    target_duration: u64,
    window: usize,
    low_latency: bool,
    part_target: f64,
    media_sequence: u64,
    discontinuity_sequence: u64,
    segments: VecDeque<Segment>,
    map_uri: Option<String>,
    finished: bool,
}

impl HlsPlaylist {
    /// A live playlist holding `window` segments of up to `target_duration` secs.
    pub fn new(target_duration: u64, window: usize) -> Self {
        Self {
            target_duration,
            window: window.max(1),
            low_latency: false,
            part_target: 0.0,
            media_sequence: 0,
            discontinuity_sequence: 0,
            segments: VecDeque::new(),
            map_uri: None,
            finished: false,
        }
    }

    /// Enable LL-HLS output with the given partial-segment target duration.
    pub fn low_latency(mut self, part_target: f64) -> Self {
        self.low_latency = true;
        self.part_target = part_target;
        self
    }

    /// Set the fMP4 initialization-segment URI, emitted as `#EXT-X-MAP`.
    /// Required for fragmented-MP4 renditions (HEVC, AV1, VVC).
    pub fn set_map(&mut self, uri: impl Into<String>) {
        self.map_uri = Some(uri.into());
    }

    /// Append a segment, evicting the oldest if the window is full.
    pub fn push(&mut self, seg: Segment) {
        if self.segments.is_empty() {
            self.media_sequence = seg.seq;
        }
        self.segments.push_back(seg);
        while self.segments.len() > self.window {
            if let Some(old) = self.segments.pop_front() {
                if old.discontinuity {
                    self.discontinuity_sequence += 1;
                }
                self.media_sequence = self.segments.front().map(|s| s.seq).unwrap_or(old.seq + 1);
            }
        }
    }

    /// Mark the stream complete (appends `#EXT-X-ENDLIST`).
    pub fn finish(&mut self) {
        self.finished = true;
    }

    /// Segments currently in the window.
    pub fn segments(&self) -> &VecDeque<Segment> {
        &self.segments
    }

    /// Render the playlist to an `.m3u8` string.
    pub fn render(&self) -> String {
        let mut s = String::with_capacity(256 + self.segments.len() * 64);
        s.push_str("#EXTM3U\n");
        s.push_str("#EXT-X-VERSION:");
        s.push_str(if self.low_latency { "9\n" } else { "3\n" });
        s.push_str(&format!("#EXT-X-TARGETDURATION:{}\n", self.target_duration));
        s.push_str(&format!("#EXT-X-MEDIA-SEQUENCE:{}\n", self.media_sequence));
        if self.discontinuity_sequence > 0 {
            s.push_str(&format!(
                "#EXT-X-DISCONTINUITY-SEQUENCE:{}\n",
                self.discontinuity_sequence
            ));
        }
        if self.low_latency {
            s.push_str(&format!(
                "#EXT-X-PART-INF:PART-TARGET={:.3}\n",
                self.part_target
            ));
            s.push_str("#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES\n");
        }
        if let Some(uri) = &self.map_uri {
            s.push_str(&format!("#EXT-X-MAP:URI=\"{uri}\"\n"));
        }
        for seg in &self.segments {
            if seg.discontinuity {
                s.push_str("#EXT-X-DISCONTINUITY\n");
            }
            s.push_str(&format!("#EXTINF:{:.3},\n", seg.duration));
            s.push_str(&seg.uri);
            s.push('\n');
        }
        if self.finished {
            s.push_str("#EXT-X-ENDLIST\n");
        }
        s
    }
}

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

    fn seg(seq: u64, dur: f64) -> Segment {
        Segment {
            seq,
            duration: dur,
            uri: format!("seg{seq}.m4s"),
            discontinuity: false,
        }
    }

    #[test]
    fn renders_live_playlist_with_sliding_window() {
        let mut pl = HlsPlaylist::new(6, 3);
        for i in 0..5 {
            pl.push(seg(i, 5.0));
        }
        // Window keeps the last 3 segments; media sequence advances to 2.
        assert_eq!(pl.segments().len(), 3);
        let out = pl.render();
        assert!(out.starts_with("#EXTM3U\n"));
        assert!(out.contains("#EXT-X-TARGETDURATION:6\n"));
        assert!(out.contains("#EXT-X-MEDIA-SEQUENCE:2\n"));
        assert!(out.contains("seg4.m4s"));
        assert!(!out.contains("seg1.m4s")); // evicted
        assert!(!out.contains("#EXT-X-ENDLIST"));
    }

    #[test]
    fn finish_appends_endlist() {
        let mut pl = HlsPlaylist::new(6, 5);
        pl.push(seg(0, 4.0));
        pl.finish();
        assert!(pl.render().trim_end().ends_with("#EXT-X-ENDLIST"));
    }

    #[test]
    fn low_latency_emits_part_tags() {
        let pl = HlsPlaylist::new(4, 5).low_latency(0.33);
        let out = pl.render();
        assert!(out.contains("#EXT-X-VERSION:9"));
        assert!(out.contains("PART-TARGET=0.330"));
        assert!(out.contains("CAN-BLOCK-RELOAD=YES"));
    }
}