wavegraph-remote 0.1.0

MIDI control and live graph discovery for WaveGraph
Documentation
//! Bounded, allocation-free graph discovery over complete MIDI SysEx messages.
//!
//! A query receives `Begin`, node records, contiguous bytecode chunks, then `End`.
//! Every reply echoes the request ID. A complete snapshot belongs to one revision.
//! Each record is its own SysEx message so ordinary MIDI can run between records.
//! The development namespace is `F0 7D 57 47`, followed by version, message kind,
//! five little-endian seven-bit request-ID digits, packed payload, and `F7`.
//! Payload groups contain a high-bit mask followed by up to seven low-bit bytes.
//! This protocol does not serialize Rust memory layouts or private message enums.

use core::{fmt, str};

/// Maximum decoded payload size for one record.
pub const MAX_PAYLOAD: usize = 80;
/// Storage sufficient for any encoded record, including its MIDI framing.
pub const MAX_FRAME: usize = 112;
/// Current remote protocol version, independent of the signal bytecode version.
pub const VERSION: u8 = 1;
const PREFIX: [u8; 4] = [0xf0, 0x7d, b'W', b'G'];
const HEADER: usize = 11;

/// Why a received record or an encoding request was invalid.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ProtocolError {
    /// Malformed MIDI framing, packing, message length, or message kind.
    Frame,
    /// The peer uses a different protocol version.
    Version,
    /// The record exceeds a bounded buffer.
    Capacity,
    /// A field contains an invalid value.
    Value,
}

impl fmt::Display for ProtocolError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Frame => "malformed WaveGraph remote record",
            Self::Version => "unsupported WaveGraph remote protocol version",
            Self::Capacity => "WaveGraph remote record exceeds its capacity",
            Self::Value => "invalid WaveGraph remote field",
        })
    }
}

impl core::error::Error for ProtocolError {}

/// Target-side failure for a graph query.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ErrorCode {
    /// The endpoint is already sending another snapshot; retry later.
    Busy,
    /// No audio block has been accepted yet.
    NotReady,
    /// This operation is not supported.
    Unsupported,
}

/// Metadata captured together with the applied graph.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SnapshotMeta {
    /// Connection epoch supplied by the endpoint; not a persistent device UUID.
    pub session: u32,
    /// Topology revision within the running engine session.
    pub revision: u32,
    /// First frame of an accepted block using this captured configuration.
    pub first_frame: u64,
    /// Number of node records that follow.
    pub nodes: u8,
    /// Total number of signal bytecode bytes that follow.
    pub code_len: u16,
}

/// Borrowed description of one native process instance.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NodeRef<'a> {
    /// Object-table ID used by this snapshot's signal bytecode.
    pub id: u8,
    /// Assignment generation; replacing an instrument changes this value.
    pub generation: u32,
    /// Unique ASCII alphanumeric alias, beginning with a letter, within this snapshot.
    pub alias: &'a str,
    /// Printable ASCII type name, for example `wavegraph-303`.
    pub kind: &'a str,
    /// Zero-based MIDI input channel, or none for an unbound process.
    pub midi_channel: Option<u8>,
    /// Local inlet kinds in order: zero for signal, one for message.
    pub inlets: &'a [u8],
    /// Local outlet kinds in order: zero for signal, one for message.
    pub outlets: &'a [u8],
}

/// One query or response record. No variant owns or allocates storage.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Message<'a> {
    /// Request a coherent snapshot of the currently applied graph.
    Query,
    /// Start a snapshot and identify the signal buses bound to physical outputs.
    Begin {
        /// Captured revision, timeline, and record counts.
        meta: SnapshotMeta,
        /// Signal bus IDs, in physical-output order.
        outputs: &'a [u8],
    },
    /// Describe one of the native process objects in the snapshot.
    Node(NodeRef<'a>),
    /// Append contiguous signal bytecode to the snapshot.
    Code {
        /// Byte offset of this chunk in the complete program.
        offset: u16,
        /// Program bytes, including the bytecode version in the first chunk.
        bytes: &'a [u8],
    },
    /// Finish the snapshot. The client validates all counts and connections.
    End,
    /// Reject a query without changing the running graph.
    Error(ErrorCode),
}

/// Whether a complete or partial message starts with the remote namespace.
#[must_use]
pub fn is_remote(bytes: &[u8]) -> bool {
    bytes.starts_with(&PREFIX)
}

/// Read the correlation ID from a framed message without decoding its payload.
///
/// This envelope is shared across protocol versions. Clients can discard a
/// different request's reply before interpreting its version or payload.
///
/// # Errors
/// Rejects incomplete framing, a different namespace, or invalid request digits.
pub fn request_id(bytes: &[u8]) -> Result<u32, ProtocolError> {
    if bytes.len() < HEADER + 1 || !is_remote(bytes) || bytes.last() != Some(&0xf7) {
        return Err(ProtocolError::Frame);
    }
    if bytes[6..HEADER].iter().any(|digit| *digit >= 128) || bytes[10] > 15 {
        return Err(ProtocolError::Value);
    }
    let mut request = 0;
    for (digit, shift) in bytes[6..HEADER].iter().zip([0, 7, 14, 21, 28]) {
        request |= u32::from(*digit) << shift;
    }
    Ok(request)
}

/// Encode one complete SysEx record into caller-owned storage.
///
/// # Errors
/// Returns an error for invalid fields or insufficient output capacity.
pub fn encode(
    request: u32,
    message: Message<'_>,
    output: &mut [u8],
) -> Result<usize, ProtocolError> {
    let mut payload = [0; MAX_PAYLOAD];
    let mut writer = Writer::new(&mut payload);
    let kind = match message {
        Message::Query => 1,
        Message::Begin { meta, outputs } => {
            writer.bytes(&meta.session.to_le_bytes())?;
            writer.bytes(&meta.revision.to_le_bytes())?;
            writer.bytes(&meta.first_frame.to_le_bytes())?;
            writer.byte(meta.nodes)?;
            writer.bytes(&meta.code_len.to_le_bytes())?;
            writer.byte(length(outputs)?)?;
            writer.bytes(outputs)?;
            2
        }
        Message::Node(node) => {
            validate_node(node)?;
            writer.byte(node.id)?;
            writer.bytes(&node.generation.to_le_bytes())?;
            writer.byte(node.midi_channel.unwrap_or(255))?;
            writer.byte(length(node.inlets)?)?;
            writer.byte(length(node.outlets)?)?;
            writer.byte(length(node.alias.as_bytes())?)?;
            writer.byte(length(node.kind.as_bytes())?)?;
            writer.bytes(node.inlets)?;
            writer.bytes(node.outlets)?;
            writer.bytes(node.alias.as_bytes())?;
            writer.bytes(node.kind.as_bytes())?;
            3
        }
        Message::Code { offset, bytes } => {
            if bytes.is_empty() {
                return Err(ProtocolError::Value);
            }
            writer.bytes(&offset.to_le_bytes())?;
            writer.bytes(bytes)?;
            4
        }
        Message::End => 5,
        Message::Error(code) => {
            writer.byte(match code {
                ErrorCode::Busy => 1,
                ErrorCode::NotReady => 2,
                ErrorCode::Unsupported => 3,
            })?;
            6
        }
    };
    let payload_len = writer.len;
    let mut writer = Writer::new(output);
    writer.bytes(&PREFIX)?;
    writer.byte(VERSION)?;
    writer.byte(kind)?;
    for shift in [0, 7, 14, 21, 28] {
        writer.byte(u8::try_from((request >> shift) & 0x7f).map_err(|_| ProtocolError::Value)?)?;
    }
    for chunk in payload[..payload_len].chunks(7) {
        let mask = chunk
            .iter()
            .enumerate()
            .fold(0u8, |mask, (bit, byte)| mask | ((byte >> 7) << bit));
        writer.byte(mask)?;
        for byte in chunk {
            writer.byte(byte & 0x7f)?;
        }
    }
    writer.byte(0xf7)?;
    Ok(writer.len)
}

/// Decode one complete SysEx record into the supplied payload buffer.
///
/// Returned strings and slices borrow `scratch`, which must remain unchanged
/// while the returned message is used. A record is never partially accepted.
///
/// # Errors
/// Rejects malformed, noncanonical, oversized, and unsupported records.
pub fn decode<'a>(
    bytes: &[u8],
    scratch: &'a mut [u8],
) -> Result<(u32, Message<'a>), ProtocolError> {
    let request = request_id(bytes)?;
    if bytes.len() > MAX_FRAME {
        return Err(ProtocolError::Frame);
    }
    let body = bytes.strip_suffix(&[0xf7]).ok_or(ProtocolError::Frame)?;
    if body[1..].iter().any(|b| *b >= 128) {
        return Err(ProtocolError::Frame);
    }
    if bytes[4] != VERSION {
        return Err(ProtocolError::Version);
    }
    let mut writer = Writer::new(scratch);
    for chunk in body[HEADER..].chunks(8) {
        let (&mask, data) = chunk.split_first().ok_or(ProtocolError::Frame)?;
        if data.is_empty() || (mask >> data.len()) != 0 {
            return Err(ProtocolError::Frame);
        }
        for (bit, byte) in data.iter().enumerate() {
            writer.byte(byte | (((mask >> bit) & 1) << 7))?;
        }
    }
    let len = writer.len;
    if len > MAX_PAYLOAD {
        return Err(ProtocolError::Capacity);
    }
    let mut reader = Reader(&scratch[..len]);
    let message = match bytes[5] {
        1 => Message::Query,
        2 => {
            let meta = SnapshotMeta {
                session: u32::from_le_bytes(reader.array()?),
                revision: u32::from_le_bytes(reader.array()?),
                first_frame: u64::from_le_bytes(reader.array()?),
                nodes: reader.byte()?,
                code_len: u16::from_le_bytes(reader.array()?),
            };
            let count = reader.byte()?;
            Message::Begin {
                meta,
                outputs: reader.take(usize::from(count))?,
            }
        }
        3 => {
            let id = reader.byte()?;
            let generation = u32::from_le_bytes(reader.array()?);
            let channel = reader.byte()?;
            let inputs = reader.byte()?;
            let outputs = reader.byte()?;
            let alias_len = reader.byte()?;
            let kind_len = reader.byte()?;
            let node = NodeRef {
                id,
                generation,
                midi_channel: (channel != 255).then_some(channel),
                inlets: reader.take(usize::from(inputs))?,
                outlets: reader.take(usize::from(outputs))?,
                alias: str::from_utf8(reader.take(usize::from(alias_len))?)
                    .map_err(|_| ProtocolError::Value)?,
                kind: str::from_utf8(reader.take(usize::from(kind_len))?)
                    .map_err(|_| ProtocolError::Value)?,
            };
            validate_node(node)?;
            Message::Node(node)
        }
        4 => {
            let offset = u16::from_le_bytes(reader.array()?);
            let bytes = reader.take(reader.0.len())?;
            if bytes.is_empty() {
                return Err(ProtocolError::Value);
            }
            Message::Code { offset, bytes }
        }
        5 => Message::End,
        6 => Message::Error(match reader.byte()? {
            1 => ErrorCode::Busy,
            2 => ErrorCode::NotReady,
            3 => ErrorCode::Unsupported,
            _ => return Err(ProtocolError::Value),
        }),
        _ => return Err(ProtocolError::Frame),
    };
    if !reader.0.is_empty() {
        return Err(ProtocolError::Frame);
    }
    Ok((request, message))
}

fn validate_node(node: NodeRef<'_>) -> Result<(), ProtocolError> {
    if node.alias.is_empty()
        || node.alias.len() > 32
        || !node
            .alias
            .as_bytes()
            .first()
            .is_some_and(u8::is_ascii_alphabetic)
        || !node.alias.bytes().all(|b| b.is_ascii_alphanumeric())
        || node.kind.is_empty()
        || node.kind.len() > 32
        || !node.kind.bytes().all(|b| (0x20..=0x7e).contains(&b))
        || node.midi_channel.is_some_and(|channel| channel >= 16)
        || node.inlets.iter().chain(node.outlets).any(|kind| *kind > 1)
    {
        return Err(ProtocolError::Value);
    }
    Ok(())
}

fn length(bytes: &[u8]) -> Result<u8, ProtocolError> {
    u8::try_from(bytes.len()).map_err(|_| ProtocolError::Capacity)
}

struct Writer<'a> {
    bytes: &'a mut [u8],
    len: usize,
}

impl<'a> Writer<'a> {
    fn new(bytes: &'a mut [u8]) -> Self {
        Self { bytes, len: 0 }
    }
    fn byte(&mut self, byte: u8) -> Result<(), ProtocolError> {
        self.bytes(&[byte])
    }
    fn bytes(&mut self, bytes: &[u8]) -> Result<(), ProtocolError> {
        let end = self
            .len
            .checked_add(bytes.len())
            .ok_or(ProtocolError::Capacity)?;
        self.bytes
            .get_mut(self.len..end)
            .ok_or(ProtocolError::Capacity)?
            .copy_from_slice(bytes);
        self.len = end;
        Ok(())
    }
}

struct Reader<'a>(&'a [u8]);

impl<'a> Reader<'a> {
    fn byte(&mut self) -> Result<u8, ProtocolError> {
        Ok(self.array::<1>()?[0])
    }
    fn array<const N: usize>(&mut self) -> Result<[u8; N], ProtocolError> {
        self.take(N)?.try_into().map_err(|_| ProtocolError::Frame)
    }
    fn take(&mut self, len: usize) -> Result<&'a [u8], ProtocolError> {
        let (value, rest) = self.0.split_at_checked(len).ok_or(ProtocolError::Frame)?;
        self.0 = rest;
        Ok(value)
    }
}