use crate::types::{Frame, StreamInfo, StreamKind};
pub trait FrameSource: Send {
fn info(&self) -> &StreamInfo;
fn read(&mut self) -> Option<Frame>;
fn seek(&mut self, pts: u64);
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MemorySource {
info: StreamInfo,
frames: Vec<Frame>,
pos: usize,
}
impl MemorySource {
pub fn new(mut info: StreamInfo, mut frames: Vec<Frame>) -> Self {
frames.sort_by_key(|f| f.seq);
let end = frames.iter().map(|f| f.pts + u64::from(f.duration)).max().unwrap_or(0);
let start = frames.first().map_or(0, |f| f.pts);
info.kind = StreamKind::Recorded { duration_ticks: end - start };
MemorySource { info, frames, pos: 0 }
}
pub fn frames(&self) -> &[Frame] {
&self.frames
}
}
impl FrameSource for MemorySource {
fn info(&self) -> &StreamInfo {
&self.info
}
fn read(&mut self) -> Option<Frame> {
let f = self.frames.get(self.pos).cloned();
if f.is_some() {
self.pos += 1;
}
f
}
fn seek(&mut self, pts: u64) {
self.pos = self.frames.iter().rposition(|f| f.key && f.pts <= pts).unwrap_or(0);
}
}
#[derive(Clone, Debug)]
pub struct Recording {
info: StreamInfo,
frames: Vec<Frame>,
}
impl Recording {
pub fn new(info: StreamInfo) -> Self {
Recording { info, frames: Vec::new() }
}
pub fn push(&mut self, frame: Frame) {
self.frames.push(frame);
}
pub fn len(&self) -> usize {
self.frames.len()
}
pub fn is_empty(&self) -> bool {
self.frames.is_empty()
}
pub fn finish(self) -> MemorySource {
MemorySource::new(self.info, self.frames)
}
}