1use core::{fmt, str};
12
13pub const MAX_PAYLOAD: usize = 80;
15pub const MAX_FRAME: usize = 112;
17pub const VERSION: u8 = 1;
19const PREFIX: [u8; 4] = [0xf0, 0x7d, b'W', b'G'];
20const HEADER: usize = 11;
21
22#[derive(Clone, Copy, Debug, Eq, PartialEq)]
24pub enum ProtocolError {
25 Frame,
27 Version,
29 Capacity,
31 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
50pub enum ErrorCode {
51 Busy,
53 NotReady,
55 Unsupported,
57}
58
59#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61pub struct SnapshotMeta {
62 pub session: u32,
64 pub revision: u32,
66 pub first_frame: u64,
68 pub nodes: u8,
70 pub code_len: u16,
72}
73
74#[derive(Clone, Copy, Debug, Eq, PartialEq)]
76pub struct NodeRef<'a> {
77 pub id: u8,
79 pub generation: u32,
81 pub alias: &'a str,
83 pub kind: &'a str,
85 pub midi_channel: Option<u8>,
87 pub inlets: &'a [u8],
89 pub outlets: &'a [u8],
91}
92
93#[derive(Clone, Copy, Debug, Eq, PartialEq)]
95pub enum Message<'a> {
96 Query,
98 Begin {
100 meta: SnapshotMeta,
102 outputs: &'a [u8],
104 },
105 Node(NodeRef<'a>),
107 Code {
109 offset: u16,
111 bytes: &'a [u8],
113 },
114 End,
116 Error(ErrorCode),
118}
119
120#[must_use]
122pub fn is_remote(bytes: &[u8]) -> bool {
123 bytes.starts_with(&PREFIX)
124}
125
126pub 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
147pub 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
225pub 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}