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
//! The wire format: length-prefixed messages on one weirdnet-net stream.
//!
//! Each message is a big-endian `u32` length, then a type byte, then the body. The subscriber
//! sends one [`Msg::Hello`]; the publisher answers [`Msg::Info`] or [`Msg::Refused`], then
//! frames, info changes and finally [`Msg::Ended`].
use crate::types::{Frame, StreamId, StreamInfo, SubscribeOptions};
use futures::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use serde::{Deserialize, Serialize};
use std::io;

/// The largest message accepted (16 MiB).
pub const MAX_MESSAGE: usize = 16 << 20;

/// What the subscriber asks for.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Hello {
    /// The stream.
    pub stream: StreamId,
    /// Where to start and how much the publisher may queue for this subscriber.
    pub options: SubscribeOptions,
}

/// One message.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Msg {
    /// Subscriber to publisher: the request.
    Hello(Hello),
    /// The stream's info (first answer, and on change).
    Info(StreamInfo),
    /// A frame.
    Frame(Frame),
    /// The stream is over.
    Ended,
    /// The subscription is refused, with a reason.
    Refused(String),
}

const HELLO: u8 = 1;
const INFO: u8 = 2;
const FRAME: u8 = 3;
const ENDED: u8 = 4;
const REFUSED: u8 = 5;

fn bad(what: &str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, what.to_string())
}

impl Msg {
    /// The bytes of this message, length prefix included.
    pub fn encode(&self) -> Vec<u8> {
        let mut body = Vec::new();
        match self {
            Msg::Hello(h) => {
                body.push(HELLO);
                body.extend(serde_json::to_vec(h).expect("hello serializes"));
            }
            Msg::Info(i) => {
                body.push(INFO);
                body.extend(serde_json::to_vec(i).expect("info serializes"));
            }
            Msg::Frame(f) => {
                body.push(FRAME);
                body.extend(f.seq.to_be_bytes());
                body.extend(f.pts.to_be_bytes());
                body.extend(f.duration.to_be_bytes());
                body.push(u8::from(f.key) | if f.meta.is_some() { 2 } else { 0 });
                if let Some(m) = &f.meta {
                    body.extend((m.len() as u32).to_be_bytes());
                    body.extend(m);
                }
                body.extend(&f.payload);
            }
            Msg::Ended => body.push(ENDED),
            Msg::Refused(r) => {
                body.push(REFUSED);
                body.extend(r.as_bytes());
            }
        }
        let mut out = (body.len() as u32).to_be_bytes().to_vec();
        out.extend(body);
        out
    }

    /// Parse a message body (without the length prefix).
    pub fn decode(body: &[u8]) -> io::Result<Msg> {
        let (&t, rest) = body.split_first().ok_or_else(|| bad("empty message"))?;
        Ok(match t {
            HELLO => Msg::Hello(serde_json::from_slice(rest).map_err(|_| bad("hello"))?),
            INFO => Msg::Info(serde_json::from_slice(rest).map_err(|_| bad("info"))?),
            FRAME => {
                if rest.len() < 21 {
                    return Err(bad("short frame"));
                }
                let seq = u64::from_be_bytes(rest[0..8].try_into().expect("8 bytes"));
                let pts = u64::from_be_bytes(rest[8..16].try_into().expect("8 bytes"));
                let duration = u32::from_be_bytes(rest[16..20].try_into().expect("4 bytes"));
                let flags = rest[20];
                let mut p = &rest[21..];
                let meta = if flags & 2 != 0 {
                    if p.len() < 4 {
                        return Err(bad("short frame meta"));
                    }
                    let n = u32::from_be_bytes(p[0..4].try_into().expect("4 bytes")) as usize;
                    let m = p.get(4..4 + n).ok_or_else(|| bad("short frame meta"))?.to_vec();
                    p = &p[4 + n..];
                    Some(m)
                } else {
                    None
                };
                Msg::Frame(Frame { seq, pts, duration, key: flags & 1 != 0, payload: p.to_vec(), meta })
            }
            ENDED => Msg::Ended,
            REFUSED => Msg::Refused(String::from_utf8_lossy(rest).into_owned()),
            _ => return Err(bad("unknown message type")),
        })
    }
}

/// Write one message.
pub async fn write<W: AsyncWrite + Unpin>(w: &mut W, m: &Msg) -> io::Result<()> {
    w.write_all(&m.encode()).await?;
    w.flush().await
}

/// Read one message; `Ok(None)` at a clean end of stream.
pub async fn read<R: AsyncRead + Unpin>(r: &mut R) -> io::Result<Option<Msg>> {
    let mut len = [0u8; 4];
    match r.read_exact(&mut len).await {
        Ok(()) => {}
        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
        Err(e) => return Err(e),
    }
    let n = u32::from_be_bytes(len) as usize;
    if n == 0 || n > MAX_MESSAGE {
        return Err(bad("bad message length"));
    }
    let mut body = vec![0u8; n];
    r.read_exact(&mut body).await?;
    Msg::decode(&body).map(Some)
}