arcly-stream 0.1.7

An open-extensible live-media streaming kernel: lock-free zero-copy frame fan-out, instant-start GOP cache, a pluggable multi-protocol ingestion layer (RTMP, RTSP, SRT, WHIP/WHEP shipped), and a feature-gated pure-Rust media plane (MPEG-TS/HLS/fMP4) — runtime, config, and metrics free.
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
//! DASH / LL-DASH manifest (`.mpd`) generation and packaging.
//!
//! Reuses the [`Muxer`](super::Muxer) / [`Packager`](super::Packager) contracts:
//! the media segments are ordinary CMAF (fMP4) — produce them with
//! [`Fmp4Muxer`](super::Fmp4Muxer) — and [`DashManifest`] renders a dynamic
//! (live) MPD using a `SegmentTemplate` + `SegmentTimeline`, which describes
//! variable, keyframe-aligned segment durations exactly.
//!
//! Low-latency DASH is enabled with [`DashManifest::low_latency`] /
//! [`DashPackager::low_latency`]: the MPD carries `availabilityTimeOffset` so a
//! player can fetch the in-progress segment as it is produced (chunked CMAF —
//! the chunks are the same `moof`+`mdat` fragments [`Muxer::take_partial`]
//! yields; the actual chunked HTTP transfer is the delivery layer's job).

use std::collections::VecDeque;
use std::fmt::Write as _;
use std::time::{SystemTime, UNIX_EPOCH};

use super::engine::{SegmentEngine, BANDWIDTH_HINT};
use super::{Muxer, Packager};
use crate::traits::StorageBackend;
use crate::{MediaFrame, Result};
use async_trait::async_trait;
use bytes::Bytes;

/// One segment's timing in the MPD `SegmentTimeline` (milliseconds).
#[derive(Debug, Clone, Copy)]
struct TimelineEntry {
    start_ms: u64,
    dur_ms: u64,
}

/// A dynamic (live) DASH media-presentation-description generator.
///
/// Holds a sliding window of segment timings and renders a spec-compliant MPD
/// with a number-addressed `SegmentTemplate` and an explicit `SegmentTimeline`.
#[derive(Debug, Clone)]
pub struct DashManifest {
    window: usize,
    timescale: u64,
    low_latency: bool,
    part_target: f64,
    availability_start: u64,                  // unix seconds
    segments: VecDeque<(u64, TimelineEntry)>, // (seq, timing)
    codecs: Option<String>,
    width: u16,
    height: u16,
    bandwidth: u32,
    init_uri: String,
    media_template: String,
    finished: bool,
}

impl DashManifest {
    /// A live manifest retaining `window` segments, timed in milliseconds.
    pub fn new(window: usize) -> Self {
        Self {
            window: window.max(1),
            timescale: 1000,
            low_latency: false,
            part_target: 0.0,
            availability_start: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0),
            segments: VecDeque::new(),
            codecs: None,
            width: 0,
            height: 0,
            bandwidth: 0,
            init_uri: "init.m4s".into(),
            media_template: "seg$Number$.m4s".into(),
            finished: false,
        }
    }

    /// Enable LL-DASH: advertise `availabilityTimeOffset` of `part_target`
    /// seconds (one segment minus one part), letting players read the open
    /// segment as its chunks are produced.
    pub fn low_latency(mut self, part_target: f64) -> Self {
        self.low_latency = true;
        self.part_target = part_target.max(0.05);
        self
    }

    /// Set the codec string (`avc1.*` / `hvc1.*`), pixel dimensions, and a
    /// nominal bandwidth (bits/sec) for the `Representation`.
    pub fn set_media_info(
        &mut self,
        codecs: Option<String>,
        width: u16,
        height: u16,
        bandwidth: u32,
    ) {
        self.codecs = codecs;
        self.width = width;
        self.height = height;
        self.bandwidth = bandwidth;
    }

    /// Override the init-segment and media-segment template URIs.
    pub fn set_uris(&mut self, init_uri: impl Into<String>, media_template: impl Into<String>) {
        self.init_uri = init_uri.into();
        self.media_template = media_template.into();
    }

    /// Append a segment timing, evicting the oldest beyond the window.
    pub fn push(&mut self, seq: u64, start_ms: u64, dur_ms: u64) {
        self.segments
            .push_back((seq, TimelineEntry { start_ms, dur_ms }));
        while self.segments.len() > self.window {
            self.segments.pop_front();
        }
    }

    /// Mark the presentation static (VOD) — sets `type="static"` and a final
    /// `minimumUpdatePeriod`-free manifest.
    pub fn finish(&mut self) {
        self.finished = true;
    }

    /// The media sequence number of the first segment in the window (the MPD
    /// `startNumber`).
    fn start_number(&self) -> u64 {
        self.segments.front().map(|(seq, _)| *seq).unwrap_or(0)
    }

    /// Largest segment duration in the window (seconds), for `maxSegmentDuration`.
    fn max_seg_secs(&self) -> f64 {
        self.segments
            .iter()
            .map(|(_, t)| t.dur_ms)
            .max()
            .unwrap_or(0) as f64
            / 1000.0
    }

    /// Render the MPD document.
    pub fn render(&self) -> String {
        let mut s = String::with_capacity(512 + self.segments.len() * 48);
        s.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

        let mpd_type = if self.finished { "static" } else { "dynamic" };
        let profile = "urn:mpeg:dash:profile:isoff-live:2011";
        s.push_str("<MPD xmlns=\"urn:mpeg:dash:schema:mpd:2011\" ");
        // `write!` formats straight into the buffer; `format!` would allocate a
        // throwaway String per line, and this renders on every segment cut.
        let _ = write!(s, "type=\"{mpd_type}\" profiles=\"{profile}\" ");
        s.push_str("minBufferTime=\"PT1.5S\" ");
        if !self.finished {
            let _ = write!(
                s,
                "availabilityStartTime=\"{}\" ",
                unix_to_iso8601(self.availability_start)
            );
            s.push_str("minimumUpdatePeriod=\"PT1S\" ");
        }
        let _ = writeln!(s, "maxSegmentDuration=\"PT{:.3}S\">", self.max_seg_secs());

        s.push_str("  <Period id=\"0\" start=\"PT0S\">\n");
        s.push_str("    <AdaptationSet mimeType=\"video/mp4\" segmentAlignment=\"true\" startWithSAP=\"1\">\n");
        let _ = write!(
            s,
            "      <Representation id=\"v0\" bandwidth=\"{}\"",
            self.bandwidth
        );
        if self.width > 0 && self.height > 0 {
            let _ = write!(s, " width=\"{}\" height=\"{}\"", self.width, self.height);
        }
        if let Some(codecs) = &self.codecs {
            let _ = write!(s, " codecs=\"{codecs}\"");
        }
        s.push_str(">\n");

        let _ = write!(
            s,
            "        <SegmentTemplate timescale=\"{}\" initialization=\"{}\" media=\"{}\" startNumber=\"{}\"",
            self.timescale,
            self.init_uri,
            self.media_template,
            self.start_number()
        );
        if self.low_latency {
            let _ = write!(
                s,
                " availabilityTimeOffset=\"{:.3}\" availabilityTimeComplete=\"false\"",
                (self.max_seg_secs() - self.part_target).max(0.0)
            );
        }
        s.push_str(">\n");
        s.push_str("          <SegmentTimeline>\n");
        // Emit an explicit <S> per segment; `t` only needs restating when the
        // timeline is non-contiguous, but stating it on the first entry anchors
        // the window after eviction.
        for (i, (_, t)) in self.segments.iter().enumerate() {
            if i == 0 {
                let _ = writeln!(
                    s,
                    "            <S t=\"{}\" d=\"{}\"/>",
                    t.start_ms, t.dur_ms
                );
            } else {
                let _ = writeln!(s, "            <S d=\"{}\"/>", t.dur_ms);
            }
        }
        s.push_str("          </SegmentTimeline>\n");
        s.push_str("        </SegmentTemplate>\n");
        s.push_str("      </Representation>\n");
        s.push_str("    </AdaptationSet>\n");
        s.push_str("  </Period>\n");
        s.push_str("</MPD>\n");
        s
    }
}

/// Convert Unix seconds to an ISO-8601 UTC timestamp (`YYYY-MM-DDThh:mm:ssZ`),
/// dependency-free (Howard Hinnant's civil-from-days algorithm).
fn unix_to_iso8601(secs: u64) -> String {
    let days = (secs / 86_400) as i64;
    let rem = secs % 86_400;
    let (h, m, sec) = (rem / 3600, (rem % 3600) / 60, rem % 60);

    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = if month <= 2 { y + 1 } else { y };
    format!("{year:04}-{month:02}-{d:02}T{h:02}:{m:02}:{sec:02}Z")
}

/// Keyframe-boundary DASH packager writing CMAF segments + a live MPD through a
/// [`StorageBackend`]. The DASH counterpart to
/// [`HlsSegmenter`](super::HlsSegmenter).
pub struct DashPackager<M: Muxer, S: StorageBackend> {
    engine: SegmentEngine<M, S>,
    manifest: DashManifest,
    seg_start_ms: u64,
}

impl<M: Muxer, S: StorageBackend> DashPackager<M, S> {
    /// New packager writing under `prefix`, `target_duration`-second segments,
    /// a `window`-segment live MPD.
    pub fn new(
        muxer: M,
        storage: S,
        prefix: impl Into<String>,
        target_duration: u64,
        window: usize,
    ) -> Self {
        Self {
            engine: SegmentEngine::new(muxer, storage, prefix, target_duration),
            manifest: DashManifest::new(window),
            seg_start_ms: 0,
        }
    }

    /// Enable LL-DASH (`availabilityTimeOffset`) with the given part target.
    pub fn low_latency(mut self, part_target: f64) -> Self {
        self.manifest = self.manifest.low_latency(part_target);
        self
    }

    /// The storage key of the MPD.
    pub fn manifest_key(&self) -> String {
        format!("{}/manifest.mpd", self.engine.prefix)
    }

    async fn ensure_init(&mut self, frame: &MediaFrame) -> Result<()> {
        if let Some(uri) = self.engine.ensure_init(frame).await? {
            self.manifest.set_uris(
                uri,
                format!("seg$Number$.{}", self.engine.muxer.extension()),
            );
            // Media info for the Representation, once the muxer can report it.
            self.manifest
                .set_media_info(self.engine.muxer.codec_string(), 0, 0, BANDWIDTH_HINT);
        }
        Ok(())
    }

    async fn cut(&mut self, duration: f64) -> Result<()> {
        let bytes = self.engine.muxer.finish_segment()?;
        if bytes.is_empty() {
            return Ok(());
        }
        let uri = self.engine.segment_uri(self.engine.seq);
        let key = self.engine.key(&uri);
        self.engine.storage.put(&key, bytes).await?;
        let dur_ms = (duration * 1000.0) as u64;
        self.manifest
            .push(self.engine.seq, self.seg_start_ms, dur_ms);
        self.seg_start_ms += dur_ms;
        self.write_manifest().await?;
        self.engine.seq += 1;
        Ok(())
    }

    async fn write_manifest(&mut self) -> Result<()> {
        let body = self.manifest.render();
        self.engine
            .storage
            .put(
                &self.engine.key("manifest.mpd"),
                Bytes::from(body.into_bytes()),
            )
            .await
    }
}

#[async_trait]
impl<M: Muxer, S: StorageBackend> Packager for DashPackager<M, S> {
    async fn push(&mut self, frame: &MediaFrame) -> Result<()> {
        self.ensure_init(frame).await?;
        let decision = self.engine.observe(frame);
        if decision.skip {
            return Ok(());
        }
        if let Some(duration) = decision.cut_previous {
            self.cut(duration).await?;
        }
        if decision.open_new {
            self.engine.muxer.start_segment()?;
        }
        self.engine.muxer.write(frame)?;
        Ok(())
    }

    async fn finish(&mut self) -> Result<()> {
        if let Some(duration) = self.engine.flush() {
            self.cut(duration).await?;
        }
        self.manifest.finish();
        self.write_manifest().await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::packager::PassthroughMuxer;
    use crate::testing::{video_frame, InMemoryStorage};

    #[test]
    fn iso8601_known_vector() {
        // 2026-06-15T11:35:43Z → seconds since epoch.
        assert_eq!(unix_to_iso8601(0), "1970-01-01T00:00:00Z");
        assert_eq!(unix_to_iso8601(1_609_459_200), "2021-01-01T00:00:00Z");
        assert_eq!(
            unix_to_iso8601(1_609_459_200 + 3661),
            "2021-01-01T01:01:01Z"
        );
    }

    #[test]
    fn manifest_renders_dynamic_mpd_with_timeline() {
        let mut m = DashManifest::new(3);
        m.set_media_info(Some("avc1.42001f".into()), 1280, 720, 2_000_000);
        m.push(0, 0, 2000);
        m.push(1, 2000, 1980);
        let out = m.render();
        assert!(out.contains("type=\"dynamic\""));
        assert!(out.contains("availabilityStartTime="));
        assert!(out.contains("<SegmentTimeline>"));
        assert!(out.contains("<S t=\"0\" d=\"2000\"/>"));
        assert!(out.contains("<S d=\"1980\"/>"));
        assert!(out.contains("codecs=\"avc1.42001f\""));
        assert!(out.contains("width=\"1280\" height=\"720\""));
    }

    #[test]
    fn low_latency_emits_availability_time_offset() {
        let mut m = DashManifest::new(3).low_latency(0.5);
        m.push(0, 0, 2000);
        let out = m.render();
        assert!(out.contains("availabilityTimeOffset="));
        assert!(out.contains("availabilityTimeComplete=\"false\""));
    }

    #[test]
    fn finish_marks_static() {
        let mut m = DashManifest::new(3);
        m.push(0, 0, 2000);
        m.finish();
        let out = m.render();
        assert!(out.contains("type=\"static\""));
        assert!(!out.contains("minimumUpdatePeriod"));
    }

    #[tokio::test]
    async fn packager_writes_segments_and_mpd() {
        let store = InMemoryStorage::new();
        let mut dash = DashPackager::new(
            PassthroughMuxer::new("m4s"),
            store.clone(),
            "live/dash",
            2,
            5,
        );

        for i in 0..4 {
            let pts = i * 1000;
            dash.push(&video_frame(pts, true)).await.unwrap();
            dash.push(&video_frame(pts + 500, false)).await.unwrap();
        }
        dash.finish().await.unwrap();

        let mpd =
            String::from_utf8(store.get("live/dash/manifest.mpd").await.unwrap().to_vec()).unwrap();
        assert!(mpd.contains("<MPD"));
        assert!(mpd.contains("type=\"static\"")); // finished
        assert!(mpd.contains("<SegmentTimeline>"));
        assert!(store.get("live/dash/seg0.m4s").await.is_ok());
    }
}