weirdnet-audio-stream 0.2.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
//! Streams over weirdnet-net: a [`Hub`] served on a node, and a [`Subscriber`] to one stream.
use crate::hub::Publisher;
use crate::source::{FrameSource, MemorySource};
use crate::stats::Stats;
use crate::types::{Frame, Start, StreamError, StreamEvent, StreamId, StreamInfo, SubscribeOptions};
use crate::wire::{self, Hello, Msg};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use weirdnet_net::{Limits, Message, Multiaddr, Node, PeerId, Stream};

/// The stream protocol id.
pub const PROTOCOL: &str = "/weirdnet/audio-stream/1";

/// Decides whether `peer` may subscribe to `stream`. A closure works.
pub trait StreamAuth: Send + Sync {
    /// `Err(reason)` refuses the subscription.
    fn authorize(&self, peer: &PeerId, stream: &StreamId) -> Result<(), String>;
}

impl<F: Fn(&PeerId, &StreamId) -> Result<(), String> + Send + Sync> StreamAuth for F {
    fn authorize(&self, peer: &PeerId, stream: &StreamId) -> Result<(), String> {
        self(peer, stream)
    }
}

/// Lets everyone subscribe (tests, or a node whose connections are already gated).
pub struct AllowAll;

impl StreamAuth for AllowAll {
    fn authorize(&self, _: &PeerId, _: &StreamId) -> Result<(), String> {
        Ok(())
    }
}

/// The streams a node offers: live publishers and recorded sources.
#[derive(Default)]
pub struct Hub {
    live: Mutex<HashMap<StreamId, Publisher>>,
    recorded: Mutex<HashMap<StreamId, MemorySource>>,
}

impl Hub {
    /// An empty hub.
    pub fn new() -> Self {
        Self::default()
    }

    /// Offer a live stream (replacing one with the same id).
    pub fn publish(&self, p: &Publisher) {
        self.live.lock().unwrap_or_else(|e| e.into_inner()).insert(p.info().id, p.clone());
    }

    /// Offer a recorded stream.
    pub fn add_recorded(&self, s: MemorySource) {
        self.recorded.lock().unwrap_or_else(|e| e.into_inner()).insert(s.info().id.clone(), s);
    }

    /// Stop offering a stream. Current subscribers of a live stream keep it until it ends.
    pub fn remove(&self, id: &StreamId) {
        self.live.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
        self.recorded.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
    }

    /// The streams offered.
    pub fn streams(&self) -> Vec<StreamInfo> {
        let mut v: Vec<StreamInfo> = self.live.lock().unwrap_or_else(|e| e.into_inner()).values().map(|p| p.info()).collect();
        v.extend(self.recorded.lock().unwrap_or_else(|e| e.into_inner()).values().map(|s| s.info().clone()));
        v.sort_by(|a, b| a.id.cmp(&b.id));
        v
    }

    fn find(&self, id: &StreamId) -> Option<Found> {
        if let Some(p) = self.live.lock().unwrap_or_else(|e| e.into_inner()).get(id) {
            return Some(Found::Live(p.clone()));
        }
        self.recorded.lock().unwrap_or_else(|e| e.into_inner()).get(id).map(|s| Found::Recorded(s.clone()))
    }
}

enum Found {
    Live(Publisher),
    Recorded(MemorySource),
}

/// Serving a hub. Dropping it stops accepting new subscribers.
pub struct Server {
    task: tokio::task::JoinHandle<()>,
}

impl Drop for Server {
    fn drop(&mut self) {
        self.task.abort();
    }
}

/// Serve `hub` on `node` at [`PROTOCOL`], asking `auth` about each subscription. Needs a tokio
/// runtime context.
pub fn serve<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, hub: Arc<Hub>, auth: Arc<dyn StreamAuth>) -> Result<Server, StreamError> {
    let mut incoming = node.accept_streams(PROTOCOL, Limits::default()).map_err(|e| StreamError::Net(e.to_string()))?;
    let task = tokio::spawn(async move {
        while let Some(s) = incoming.next().await {
            let (hub, auth) = (hub.clone(), auth.clone());
            tokio::spawn(async move {
                let _ = handle(s, hub, auth).await;
            });
        }
    });
    Ok(Server { task })
}

async fn handle(mut s: Stream, hub: Arc<Hub>, auth: Arc<dyn StreamAuth>) -> std::io::Result<()> {
    let hello = match tokio::time::timeout(std::time::Duration::from_secs(30), wire::read(&mut s)).await {
        Ok(Ok(Some(Msg::Hello(h)))) => h,
        _ => return Ok(()),
    };
    let peer = s.peer();
    if let Err(reason) = auth.authorize(&peer, &hello.stream) {
        return wire::write(&mut s, &Msg::Refused(reason)).await;
    }
    match hub.find(&hello.stream) {
        None => wire::write(&mut s, &Msg::Refused("unknown stream".into())).await,
        Some(Found::Live(p)) => {
            let mut l = p.listen_as(&peer.to_string(), hello.options.buffer);
            wire::write(&mut s, &Msg::Info(p.info())).await?;
            while let Some(ev) = l.next().await {
                let m = match ev {
                    StreamEvent::Frame(f) => Msg::Frame(f),
                    StreamEvent::InfoChanged(i) => Msg::Info(i),
                    StreamEvent::Ended => Msg::Ended,
                    StreamEvent::Gap { .. } => continue,
                };
                wire::write(&mut s, &m).await?;
            }
            if l.overrun() {
                wire::write(&mut s, &Msg::Refused("fell too far behind".into())).await?;
            }
            Ok(())
        }
        Some(Found::Recorded(mut src)) => {
            wire::write(&mut s, &Msg::Info(src.info().clone())).await?;
            match hello.options.start {
                Start::At(pts) => src.seek(pts),
                Start::Live | Start::FromStart => {}
            }
            while let Some(f) = src.read() {
                wire::write(&mut s, &Msg::Frame(f)).await?;
            }
            wire::write(&mut s, &Msg::Ended).await
        }
    }
}

/// One subscription to a stream on another node.
pub struct Subscriber {
    s: Stream,
    info: StreamInfo,
    stats: Stats,
    held: Option<Frame>,
    epoch: Instant,
    done: bool,
}

impl Subscriber {
    /// Subscribe to `stream` on `peer` (reached through `addrs` if not connected).
    pub async fn connect<Q: Message, R: Message>(
        node: &Node<Q, R>,
        peer: PeerId,
        addrs: &[Multiaddr],
        stream: &StreamId,
        options: SubscribeOptions,
    ) -> Result<Subscriber, StreamError> {
        let mut s = node.open_stream_async(peer, addrs, PROTOCOL, Limits::default()).await.map_err(|e| StreamError::Net(e.to_string()))?;
        let net = |e: std::io::Error| StreamError::Net(e.to_string());
        wire::write(&mut s, &Msg::Hello(Hello { stream: stream.clone(), options })).await.map_err(net)?;
        match wire::read(&mut s).await.map_err(net)? {
            Some(Msg::Info(info)) => Ok(Subscriber { s, info, stats: Stats::default(), held: None, epoch: Instant::now(), done: false }),
            Some(Msg::Refused(r)) if r == "unknown stream" => Err(StreamError::UnknownStream),
            Some(Msg::Refused(r)) => Err(StreamError::Refused(r)),
            Some(_) => Err(StreamError::Protocol("expected the stream info".into())),
            None => Err(StreamError::Net("closed before answering".into())),
        }
    }

    /// The stream's info (updated by [`StreamEvent::InfoChanged`]).
    pub fn info(&self) -> &StreamInfo {
        &self.info
    }

    /// Arrival statistics so far.
    pub fn stats(&self) -> &Stats {
        &self.stats
    }

    /// The next event; `None` after [`StreamEvent::Ended`] or when the connection fails.
    pub async fn next(&mut self) -> Option<StreamEvent> {
        if let Some(f) = self.held.take() {
            return Some(StreamEvent::Frame(f));
        }
        if self.done {
            return None;
        }
        match wire::read(&mut self.s).await {
            Ok(Some(Msg::Frame(f))) => {
                let at = self.epoch.elapsed().as_secs_f64() * 1000.0;
                let missed = self.stats.observe(f.seq, f.pts, f.payload.len(), self.info.clock_rate, at);
                if missed > 0 {
                    self.held = Some(f);
                    return Some(StreamEvent::Gap { missed });
                }
                Some(StreamEvent::Frame(f))
            }
            Ok(Some(Msg::Info(i))) => {
                self.info = i.clone();
                Some(StreamEvent::InfoChanged(i))
            }
            Ok(Some(Msg::Ended)) => {
                self.done = true;
                Some(StreamEvent::Ended)
            }
            _ => {
                self.done = true;
                None
            }
        }
    }
}