Skip to main content

weirdnet_streaming/
source.rs

1//! Recorded streams: a finite source of frames that can seek.
2use crate::types::{Frame, StreamInfo, StreamKind};
3
4/// A recorded stream a server can play to subscribers.
5pub trait FrameSource: Send {
6    /// What the stream is.
7    fn info(&self) -> &StreamInfo;
8    /// The next frame, or `None` at the end.
9    fn read(&mut self) -> Option<Frame>;
10    /// Move to the key frame at or before `pts` (the first frame if there is none).
11    fn seek(&mut self, pts: u64);
12}
13
14/// A recorded stream held in memory.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct MemorySource {
17    info: StreamInfo,
18    frames: Vec<Frame>,
19    pos: usize,
20}
21
22impl MemorySource {
23    /// A recorded stream from frames in order; the info's kind becomes Recorded with the
24    /// frames' total length.
25    pub fn new(mut info: StreamInfo, mut frames: Vec<Frame>) -> Self {
26        frames.sort_by_key(|f| f.seq);
27        let end = frames.iter().map(|f| f.pts + u64::from(f.duration)).max().unwrap_or(0);
28        let start = frames.first().map_or(0, |f| f.pts);
29        info.kind = StreamKind::Recorded { duration_ticks: end - start };
30        MemorySource { info, frames, pos: 0 }
31    }
32
33    /// The frames.
34    pub fn frames(&self) -> &[Frame] {
35        &self.frames
36    }
37}
38
39impl FrameSource for MemorySource {
40    fn info(&self) -> &StreamInfo {
41        &self.info
42    }
43
44    fn read(&mut self) -> Option<Frame> {
45        let f = self.frames.get(self.pos).cloned();
46        if f.is_some() {
47            self.pos += 1;
48        }
49        f
50    }
51
52    fn seek(&mut self, pts: u64) {
53        self.pos = self.frames.iter().rposition(|f| f.key && f.pts <= pts).unwrap_or(0);
54    }
55}
56
57/// Collects a live stream's frames into a [`MemorySource`].
58#[derive(Clone, Debug)]
59pub struct Recording {
60    info: StreamInfo,
61    frames: Vec<Frame>,
62}
63
64impl Recording {
65    /// Start recording a stream with this info.
66    pub fn new(info: StreamInfo) -> Self {
67        Recording { info, frames: Vec::new() }
68    }
69
70    /// Add a frame.
71    pub fn push(&mut self, frame: Frame) {
72        self.frames.push(frame);
73    }
74
75    /// Frames so far.
76    pub fn len(&self) -> usize {
77        self.frames.len()
78    }
79
80    /// No frames yet.
81    pub fn is_empty(&self) -> bool {
82        self.frames.is_empty()
83    }
84
85    /// The finished recording.
86    pub fn finish(self) -> MemorySource {
87        MemorySource::new(self.info, self.frames)
88    }
89}