Skip to main content

wavegraph_remote/
protocol.rs

1//! Bounded, allocation-free graph discovery over complete MIDI SysEx messages.
2//!
3//! A query receives `Begin`, node records, contiguous bytecode chunks, then `End`.
4//! Every reply echoes the request ID. A complete snapshot belongs to one revision.
5//! Each record is its own SysEx message so ordinary MIDI can run between records.
6//! The development namespace is `F0 7D 57 47`, followed by version, message kind,
7//! five little-endian seven-bit request-ID digits, packed payload, and `F7`.
8//! Payload groups contain a high-bit mask followed by up to seven low-bit bytes.
9//! This protocol does not serialize Rust memory layouts or private message enums.
10
11use core::{fmt, str};
12
13/// Maximum decoded payload size for one record.
14pub const MAX_PAYLOAD: usize = 80;
15/// Storage sufficient for any encoded record, including its MIDI framing.
16pub const MAX_FRAME: usize = 112;
17/// Current remote protocol version, independent of the signal bytecode version.
18pub const VERSION: u8 = 1;
19const PREFIX: [u8; 4] = [0xf0, 0x7d, b'W', b'G'];
20const HEADER: usize = 11;
21
22/// Why a received record or an encoding request was invalid.
23#[derive(Clone, Copy, Debug, Eq, PartialEq)]
24pub enum ProtocolError {
25    /// Malformed MIDI framing, packing, message length, or message kind.
26    Frame,
27    /// The peer uses a different protocol version.
28    Version,
29    /// The record exceeds a bounded buffer.
30    Capacity,
31    /// A field contains an invalid value.
32    Value,
33}
34
35impl fmt::Display for ProtocolError {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.write_str(match self {
38            Self::Frame => "malformed WaveGraph remote record",
39            Self::Version => "unsupported WaveGraph remote protocol version",
40            Self::Capacity => "WaveGraph remote record exceeds its capacity",
41            Self::Value => "invalid WaveGraph remote field",
42        })
43    }
44}
45
46impl core::error::Error for ProtocolError {}
47
48/// Target-side failure for a graph query.
49#[derive(Clone, Copy, Debug, Eq, PartialEq)]
50pub enum ErrorCode {
51    /// The endpoint is already sending another snapshot; retry later.
52    Busy,
53    /// No audio block has been accepted yet.
54    NotReady,
55    /// This operation is not supported.
56    Unsupported,
57}
58
59/// Metadata captured together with the applied graph.
60#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61pub struct SnapshotMeta {
62    /// Connection epoch supplied by the endpoint; not a persistent device UUID.
63    pub session: u32,
64    /// Topology revision within the running engine session.
65    pub revision: u32,
66    /// First frame of an accepted block using this captured configuration.
67    pub first_frame: u64,
68    /// Number of node records that follow.
69    pub nodes: u8,
70    /// Total number of signal bytecode bytes that follow.
71    pub code_len: u16,
72}
73
74/// Borrowed description of one native process instance.
75#[derive(Clone, Copy, Debug, Eq, PartialEq)]
76pub struct NodeRef<'a> {
77    /// Object-table ID used by this snapshot's signal bytecode.
78    pub id: u8,
79    /// Assignment generation; replacing an instrument changes this value.
80    pub generation: u32,
81    /// Unique ASCII alphanumeric alias, beginning with a letter, within this snapshot.
82    pub alias: &'a str,
83    /// Printable ASCII type name, for example `wavegraph-303`.
84    pub kind: &'a str,
85    /// Zero-based MIDI input channel, or none for an unbound process.
86    pub midi_channel: Option<u8>,
87    /// Local inlet kinds in order: zero for signal, one for message.
88    pub inlets: &'a [u8],
89    /// Local outlet kinds in order: zero for signal, one for message.
90    pub outlets: &'a [u8],
91}
92
93/// One query or response record. No variant owns or allocates storage.
94#[derive(Clone, Copy, Debug, Eq, PartialEq)]
95pub enum Message<'a> {
96    /// Request a coherent snapshot of the currently applied graph.
97    Query,
98    /// Start a snapshot and identify the signal buses bound to physical outputs.
99    Begin {
100        /// Captured revision, timeline, and record counts.
101        meta: SnapshotMeta,
102        /// Signal bus IDs, in physical-output order.
103        outputs: &'a [u8],
104    },
105    /// Describe one of the native process objects in the snapshot.
106    Node(NodeRef<'a>),
107    /// Append contiguous signal bytecode to the snapshot.
108    Code {
109        /// Byte offset of this chunk in the complete program.
110        offset: u16,
111        /// Program bytes, including the bytecode version in the first chunk.
112        bytes: &'a [u8],
113    },
114    /// Finish the snapshot. The client validates all counts and connections.
115    End,
116    /// Reject a query without changing the running graph.
117    Error(ErrorCode),
118}
119
120/// Whether a complete or partial message starts with the remote namespace.
121#[must_use]
122pub fn is_remote(bytes: &[u8]) -> bool {
123    bytes.starts_with(&PREFIX)
124}
125
126/// Read the correlation ID from a framed message without decoding its payload.
127///
128/// This envelope is shared across protocol versions. Clients can discard a
129/// different request's reply before interpreting its version or payload.
130///
131/// # Errors
132/// Rejects incomplete framing, a different namespace, or invalid request digits.
133pub fn request_id(bytes: &[u8]) -> Result<u32, ProtocolError> {
134    if bytes.len() < HEADER + 1 || !is_remote(bytes) || bytes.last() != Some(&0xf7) {
135        return Err(ProtocolError::Frame);
136    }
137    if bytes[6..HEADER].iter().any(|digit| *digit >= 128) || bytes[10] > 15 {
138        return Err(ProtocolError::Value);
139    }
140    let mut request = 0;
141    for (digit, shift) in bytes[6..HEADER].iter().zip([0, 7, 14, 21, 28]) {
142        request |= u32::from(*digit) << shift;
143    }
144    Ok(request)
145}
146
147/// Encode one complete SysEx record into caller-owned storage.
148///
149/// # Errors
150/// Returns an error for invalid fields or insufficient output capacity.
151pub fn encode(
152    request: u32,
153    message: Message<'_>,
154    output: &mut [u8],
155) -> Result<usize, ProtocolError> {
156    let mut payload = [0; MAX_PAYLOAD];
157    let mut writer = Writer::new(&mut payload);
158    let kind = match message {
159        Message::Query => 1,
160        Message::Begin { meta, outputs } => {
161            writer.bytes(&meta.session.to_le_bytes())?;
162            writer.bytes(&meta.revision.to_le_bytes())?;
163            writer.bytes(&meta.first_frame.to_le_bytes())?;
164            writer.byte(meta.nodes)?;
165            writer.bytes(&meta.code_len.to_le_bytes())?;
166            writer.byte(length(outputs)?)?;
167            writer.bytes(outputs)?;
168            2
169        }
170        Message::Node(node) => {
171            validate_node(node)?;
172            writer.byte(node.id)?;
173            writer.bytes(&node.generation.to_le_bytes())?;
174            writer.byte(node.midi_channel.unwrap_or(255))?;
175            writer.byte(length(node.inlets)?)?;
176            writer.byte(length(node.outlets)?)?;
177            writer.byte(length(node.alias.as_bytes())?)?;
178            writer.byte(length(node.kind.as_bytes())?)?;
179            writer.bytes(node.inlets)?;
180            writer.bytes(node.outlets)?;
181            writer.bytes(node.alias.as_bytes())?;
182            writer.bytes(node.kind.as_bytes())?;
183            3
184        }
185        Message::Code { offset, bytes } => {
186            if bytes.is_empty() {
187                return Err(ProtocolError::Value);
188            }
189            writer.bytes(&offset.to_le_bytes())?;
190            writer.bytes(bytes)?;
191            4
192        }
193        Message::End => 5,
194        Message::Error(code) => {
195            writer.byte(match code {
196                ErrorCode::Busy => 1,
197                ErrorCode::NotReady => 2,
198                ErrorCode::Unsupported => 3,
199            })?;
200            6
201        }
202    };
203    let payload_len = writer.len;
204    let mut writer = Writer::new(output);
205    writer.bytes(&PREFIX)?;
206    writer.byte(VERSION)?;
207    writer.byte(kind)?;
208    for shift in [0, 7, 14, 21, 28] {
209        writer.byte(u8::try_from((request >> shift) & 0x7f).map_err(|_| ProtocolError::Value)?)?;
210    }
211    for chunk in payload[..payload_len].chunks(7) {
212        let mask = chunk
213            .iter()
214            .enumerate()
215            .fold(0u8, |mask, (bit, byte)| mask | ((byte >> 7) << bit));
216        writer.byte(mask)?;
217        for byte in chunk {
218            writer.byte(byte & 0x7f)?;
219        }
220    }
221    writer.byte(0xf7)?;
222    Ok(writer.len)
223}
224
225/// Decode one complete SysEx record into the supplied payload buffer.
226///
227/// Returned strings and slices borrow `scratch`, which must remain unchanged
228/// while the returned message is used. A record is never partially accepted.
229///
230/// # Errors
231/// Rejects malformed, noncanonical, oversized, and unsupported records.
232pub fn decode<'a>(
233    bytes: &[u8],
234    scratch: &'a mut [u8],
235) -> Result<(u32, Message<'a>), ProtocolError> {
236    let request = request_id(bytes)?;
237    if bytes.len() > MAX_FRAME {
238        return Err(ProtocolError::Frame);
239    }
240    let body = bytes.strip_suffix(&[0xf7]).ok_or(ProtocolError::Frame)?;
241    if body[1..].iter().any(|b| *b >= 128) {
242        return Err(ProtocolError::Frame);
243    }
244    if bytes[4] != VERSION {
245        return Err(ProtocolError::Version);
246    }
247    let mut writer = Writer::new(scratch);
248    for chunk in body[HEADER..].chunks(8) {
249        let (&mask, data) = chunk.split_first().ok_or(ProtocolError::Frame)?;
250        if data.is_empty() || (mask >> data.len()) != 0 {
251            return Err(ProtocolError::Frame);
252        }
253        for (bit, byte) in data.iter().enumerate() {
254            writer.byte(byte | (((mask >> bit) & 1) << 7))?;
255        }
256    }
257    let len = writer.len;
258    if len > MAX_PAYLOAD {
259        return Err(ProtocolError::Capacity);
260    }
261    let mut reader = Reader(&scratch[..len]);
262    let message = match bytes[5] {
263        1 => Message::Query,
264        2 => {
265            let meta = SnapshotMeta {
266                session: u32::from_le_bytes(reader.array()?),
267                revision: u32::from_le_bytes(reader.array()?),
268                first_frame: u64::from_le_bytes(reader.array()?),
269                nodes: reader.byte()?,
270                code_len: u16::from_le_bytes(reader.array()?),
271            };
272            let count = reader.byte()?;
273            Message::Begin {
274                meta,
275                outputs: reader.take(usize::from(count))?,
276            }
277        }
278        3 => {
279            let id = reader.byte()?;
280            let generation = u32::from_le_bytes(reader.array()?);
281            let channel = reader.byte()?;
282            let inputs = reader.byte()?;
283            let outputs = reader.byte()?;
284            let alias_len = reader.byte()?;
285            let kind_len = reader.byte()?;
286            let node = NodeRef {
287                id,
288                generation,
289                midi_channel: (channel != 255).then_some(channel),
290                inlets: reader.take(usize::from(inputs))?,
291                outlets: reader.take(usize::from(outputs))?,
292                alias: str::from_utf8(reader.take(usize::from(alias_len))?)
293                    .map_err(|_| ProtocolError::Value)?,
294                kind: str::from_utf8(reader.take(usize::from(kind_len))?)
295                    .map_err(|_| ProtocolError::Value)?,
296            };
297            validate_node(node)?;
298            Message::Node(node)
299        }
300        4 => {
301            let offset = u16::from_le_bytes(reader.array()?);
302            let bytes = reader.take(reader.0.len())?;
303            if bytes.is_empty() {
304                return Err(ProtocolError::Value);
305            }
306            Message::Code { offset, bytes }
307        }
308        5 => Message::End,
309        6 => Message::Error(match reader.byte()? {
310            1 => ErrorCode::Busy,
311            2 => ErrorCode::NotReady,
312            3 => ErrorCode::Unsupported,
313            _ => return Err(ProtocolError::Value),
314        }),
315        _ => return Err(ProtocolError::Frame),
316    };
317    if !reader.0.is_empty() {
318        return Err(ProtocolError::Frame);
319    }
320    Ok((request, message))
321}
322
323fn validate_node(node: NodeRef<'_>) -> Result<(), ProtocolError> {
324    if node.alias.is_empty()
325        || node.alias.len() > 32
326        || !node
327            .alias
328            .as_bytes()
329            .first()
330            .is_some_and(u8::is_ascii_alphabetic)
331        || !node.alias.bytes().all(|b| b.is_ascii_alphanumeric())
332        || node.kind.is_empty()
333        || node.kind.len() > 32
334        || !node.kind.bytes().all(|b| (0x20..=0x7e).contains(&b))
335        || node.midi_channel.is_some_and(|channel| channel >= 16)
336        || node.inlets.iter().chain(node.outlets).any(|kind| *kind > 1)
337    {
338        return Err(ProtocolError::Value);
339    }
340    Ok(())
341}
342
343fn length(bytes: &[u8]) -> Result<u8, ProtocolError> {
344    u8::try_from(bytes.len()).map_err(|_| ProtocolError::Capacity)
345}
346
347struct Writer<'a> {
348    bytes: &'a mut [u8],
349    len: usize,
350}
351
352impl<'a> Writer<'a> {
353    fn new(bytes: &'a mut [u8]) -> Self {
354        Self { bytes, len: 0 }
355    }
356    fn byte(&mut self, byte: u8) -> Result<(), ProtocolError> {
357        self.bytes(&[byte])
358    }
359    fn bytes(&mut self, bytes: &[u8]) -> Result<(), ProtocolError> {
360        let end = self
361            .len
362            .checked_add(bytes.len())
363            .ok_or(ProtocolError::Capacity)?;
364        self.bytes
365            .get_mut(self.len..end)
366            .ok_or(ProtocolError::Capacity)?
367            .copy_from_slice(bytes);
368        self.len = end;
369        Ok(())
370    }
371}
372
373struct Reader<'a>(&'a [u8]);
374
375impl<'a> Reader<'a> {
376    fn byte(&mut self) -> Result<u8, ProtocolError> {
377        Ok(self.array::<1>()?[0])
378    }
379    fn array<const N: usize>(&mut self) -> Result<[u8; N], ProtocolError> {
380        self.take(N)?.try_into().map_err(|_| ProtocolError::Frame)
381    }
382    fn take(&mut self, len: usize) -> Result<&'a [u8], ProtocolError> {
383        let (value, rest) = self.0.split_at_checked(len).ok_or(ProtocolError::Frame)?;
384        self.0 = rest;
385        Ok(value)
386    }
387}