weirdnet-audio-stream 0.3.0

General-purpose audio streaming for Weirdnet: publish and subscribe to live or recorded streams of codec-agnostic frames, many listeners with their own bounded queues, seeking, arrival statistics and per-subscription authorisation.
Documentation
//! The data a stream carries.
use serde::{Deserialize, Serialize};
use std::fmt;

/// A stream's id, unique within its publisher's hub.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct StreamId(String);

impl StreamId {
    /// An id from text.
    pub fn new(s: &str) -> Self {
        StreamId(s.to_string())
    }
    /// The text.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for StreamId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// An opaque codec name, for the decoder; never interpreted here.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CodecId(pub String);

/// Raw PCM, 32-bit float, little endian, interleaved.
pub const PCM_F32LE: &str = "pcm/f32le";
/// Raw PCM, signed 16-bit, little endian, interleaved.
pub const PCM_S16LE: &str = "pcm/s16le";

/// Live (frames as they are produced) or recorded (finite, seekable).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum StreamKind {
    /// Frames as they are produced.
    Live,
    /// A finite stream of this many ticks.
    Recorded {
        /// The length in ticks of the stream's clock.
        duration_ticks: u64,
    },
}

/// What a stream is.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StreamInfo {
    /// The id.
    pub id: StreamId,
    /// A name for people.
    pub name: String,
    /// Live or recorded.
    pub kind: StreamKind,
    /// The codec.
    pub codec: CodecId,
    /// Parameters for the decoder, such as `sample_rate` and `channels`.
    pub params: Vec<(String, String)>,
    /// Ticks per second for frame timestamps.
    pub clock_rate: u32,
    /// Opaque app metadata (for example a stream class such as voice, or a group id).
    pub meta: Option<Vec<u8>>,
}

impl StreamInfo {
    /// A live raw PCM stream: 32-bit float, interleaved, timestamps in samples.
    pub fn pcm_f32(id: &str, name: &str, sample_rate: u32, channels: u16) -> Self {
        StreamInfo {
            id: StreamId::new(id),
            name: name.to_string(),
            kind: StreamKind::Live,
            codec: CodecId(PCM_F32LE.into()),
            params: vec![("sample_rate".into(), sample_rate.to_string()), ("channels".into(), channels.to_string())],
            clock_rate: sample_rate,
            meta: None,
        }
    }

    /// With opaque app metadata.
    pub fn with_meta(mut self, meta: Vec<u8>) -> Self {
        self.meta = Some(meta);
        self
    }

    /// A decoder parameter.
    pub fn param(&self, key: &str) -> Option<&str> {
        self.params.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
    }
}

/// One frame of a stream.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Frame {
    /// Sequence number; a jump shows lost frames.
    pub seq: u64,
    /// Presentation time in ticks.
    pub pts: u64,
    /// Length in ticks.
    pub duration: u32,
    /// A point where a new listener can start decoding.
    pub key: bool,
    /// The encoded bytes.
    pub payload: Vec<u8>,
    /// Opaque app metadata, for example a loop position marker.
    pub meta: Option<Vec<u8>>,
}

impl Frame {
    /// A key frame with no metadata.
    pub fn new(seq: u64, pts: u64, duration: u32, payload: Vec<u8>) -> Self {
        Frame { seq, pts, duration, key: true, payload, meta: None }
    }

    /// A raw PCM f32 frame from interleaved samples; `channels` gives the duration in samples.
    pub fn pcm_f32(seq: u64, pts: u64, channels: u16, samples: &[f32]) -> Self {
        let payload = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
        Frame::new(seq, pts, (samples.len() / channels.max(1) as usize) as u32, payload)
    }

    /// The samples of a raw PCM f32 frame.
    pub fn f32_samples(&self) -> Vec<f32> {
        self.payload.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect()
    }
}

/// What a listener receives.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StreamEvent {
    /// The next frame.
    Frame(Frame),
    /// Frames were lost (dropped by an overflow policy or the network) before the next one.
    Gap {
        /// How many sequence numbers were skipped.
        missed: u64,
    },
    /// The stream's info changed.
    InfoChanged(StreamInfo),
    /// The stream is over.
    Ended,
}

/// What happens when a listener's queue is full.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Overflow {
    /// Drop the oldest queued frame.
    DropOldest,
    /// Drop everything queued and wait for the next key frame.
    SkipToKey,
    /// Disconnect the listener.
    Disconnect,
}

/// How much a listener may queue.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BufferPolicy {
    /// Most frames queued.
    pub max_frames: usize,
    /// What happens when it is full.
    pub overflow: Overflow,
}

impl Default for BufferPolicy {
    fn default() -> Self {
        BufferPolicy { max_frames: 256, overflow: Overflow::DropOldest }
    }
}

/// Where a subscription starts.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Start {
    /// At the live edge (the next key frame). For a recorded stream, the beginning.
    Live,
    /// At this presentation time (recorded streams; the key frame at or before it).
    At(u64),
    /// At the beginning (recorded streams).
    FromStart,
}

/// How to subscribe.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SubscribeOptions {
    /// Where to start.
    pub start: Start,
    /// The queue on the publisher's side for this subscription.
    pub buffer: BufferPolicy,
}

impl Default for SubscribeOptions {
    fn default() -> Self {
        SubscribeOptions { start: Start::Live, buffer: BufferPolicy::default() }
    }
}

/// Why a stream call failed.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum StreamError {
    /// The publisher finished the stream.
    #[error("the stream has ended")]
    Ended,
    /// The publisher refused the subscription.
    #[error("refused: {0}")]
    Refused(String),
    /// No such stream.
    #[error("unknown stream")]
    UnknownStream,
    /// The listener was disconnected by its overflow policy.
    #[error("disconnected: the listener fell too far behind")]
    Overrun,
    /// A network failure.
    #[error("network: {0}")]
    Net(String),
    /// The other side sent something this version does not understand.
    #[error("protocol: {0}")]
    Protocol(String),
}