weirdnet-streaming 0.1.0

Streaming for Weirdnet: live and recorded audio streams over weirdnet-net with per-listener queues, clocks and remote routing, a follow-transport protocol (start, stop, locate, tempo, beacon), and loop-positioned streams with alignment for record-along.
Documentation
//! Recorded streams: a finite source of frames that can seek.
use crate::types::{Frame, StreamInfo, StreamKind};

/// A recorded stream a server can play to subscribers.
pub trait FrameSource: Send {
    /// What the stream is.
    fn info(&self) -> &StreamInfo;
    /// The next frame, or `None` at the end.
    fn read(&mut self) -> Option<Frame>;
    /// Move to the key frame at or before `pts` (the first frame if there is none).
    fn seek(&mut self, pts: u64);
}

/// A recorded stream held in memory.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MemorySource {
    info: StreamInfo,
    frames: Vec<Frame>,
    pos: usize,
}

impl MemorySource {
    /// A recorded stream from frames in order; the info's kind becomes Recorded with the
    /// frames' total length.
    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 }
    }

    /// The frames.
    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);
    }
}

/// Collects a live stream's frames into a [`MemorySource`].
#[derive(Clone, Debug)]
pub struct Recording {
    info: StreamInfo,
    frames: Vec<Frame>,
}

impl Recording {
    /// Start recording a stream with this info.
    pub fn new(info: StreamInfo) -> Self {
        Recording { info, frames: Vec::new() }
    }

    /// Add a frame.
    pub fn push(&mut self, frame: Frame) {
        self.frames.push(frame);
    }

    /// Frames so far.
    pub fn len(&self) -> usize {
        self.frames.len()
    }

    /// No frames yet.
    pub fn is_empty(&self) -> bool {
        self.frames.is_empty()
    }

    /// The finished recording.
    pub fn finish(self) -> MemorySource {
        MemorySource::new(self.info, self.frames)
    }
}