Skip to main content

wavegraph_core/
bytecode.rs

1//! Portable instructions shared by patch compilers and interpreters.
2//!
3//! A program starts with [`VERSION`] followed by instructions. Every
4//! instruction appends its outputs to a table of mono signal buffers (buses).
5//! Sources refer to earlier buses. All fields occupy one byte.
6//!
7//! | Opcode | Operands | Outputs |
8//! | --- | --- | --- |
9//! | 1 (call) | object index, signal input count, signal output count, one source bus per signal input | One bus per signal outlet, in order |
10//! | 2 (gain) | source bus, unsigned gain (128 is unity) | One bus |
11//! | 3 (mix) | left bus, right bus | One bus |
12
13/// Version byte that precedes a stream of encoded [`Op`]s.
14pub const VERSION: u8 = 1;
15
16const CALL: u8 = 1;
17const GAIN: u8 = 2;
18const MIX: u8 = 3;
19
20/// A block-level signal graph instruction. Object IDs refer to stateful native
21/// instances installed by the application. A decoded call borrows its input
22/// bus indices directly from the bytecode.
23#[derive(Clone, Copy, Debug, Eq, PartialEq)]
24pub enum Op<'a> {
25    /// Run a patch object once on the current audio block.
26    Call {
27        /// Index in the patch's object table.
28        object: u8,
29        /// One source bus per signal inlet, in inlet order.
30        inputs: &'a [u8],
31        /// Number of consecutive buses produced, in signal outlet order.
32        outputs: u8,
33    },
34    /// Scale one input bus and append the saturated result.
35    Gain {
36        /// Source bus.
37        input: u8,
38        /// Gain in units of 1/128. A value of 128 is unity.
39        level: u8,
40    },
41    /// Append the saturating sum of two input buses.
42    Mix {
43        /// First source bus.
44        left: u8,
45        /// Second source bus.
46        right: u8,
47    },
48}
49
50/// Errors decoding a single instruction.
51#[derive(Clone, Copy, Debug, Eq, PartialEq)]
52pub enum DecodeError {
53    /// An opcode or one of its operands is missing.
54    Truncated,
55    /// This version of the instruction set has no such opcode.
56    UnknownOpcode(u8),
57}
58
59/// Errors encoding a single instruction.
60#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61pub enum EncodeError {
62    /// The destination is too short for the entire instruction.
63    BufferTooSmall,
64    /// The input list length exceeds its one-byte wire field.
65    TooManyInputs,
66}
67
68impl<'a> Op<'a> {
69    /// Decode the first instruction and return the unconsumed suffix.
70    ///
71    /// # Errors
72    /// Returns [`DecodeError`] for an incomplete or unrecognized instruction.
73    pub fn decode(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), DecodeError> {
74        match bytes {
75            [CALL, object, count, outputs, rest @ ..] => {
76                let (inputs, rest) = rest
77                    .split_at_checked(usize::from(*count))
78                    .ok_or(DecodeError::Truncated)?;
79                Ok((
80                    Self::Call {
81                        object: *object,
82                        inputs,
83                        outputs: *outputs,
84                    },
85                    rest,
86                ))
87            }
88            [GAIN, input, level, rest @ ..] => Ok((
89                Self::Gain {
90                    input: *input,
91                    level: *level,
92                },
93                rest,
94            )),
95            [MIX, left, right, rest @ ..] => Ok((
96                Self::Mix {
97                    left: *left,
98                    right: *right,
99                },
100                rest,
101            )),
102            [] | [CALL | GAIN | MIX, ..] => Err(DecodeError::Truncated),
103            [unknown, ..] => Err(DecodeError::UnknownOpcode(*unknown)),
104        }
105    }
106
107    /// Write one complete instruction and return the number of bytes written.
108    /// The program's leading version byte is supplied by the caller.
109    ///
110    /// # Errors
111    /// Returns [`EncodeError`] before writing anything if the instruction
112    /// cannot be represented or the output buffer is too short.
113    pub fn encode(self, output: &mut [u8]) -> Result<usize, EncodeError> {
114        match self {
115            Self::Call {
116                object,
117                inputs,
118                outputs,
119            } => {
120                let count = u8::try_from(inputs.len()).map_err(|_| EncodeError::TooManyInputs)?;
121                let len = 4 + usize::from(count);
122                let dst = output.get_mut(..len).ok_or(EncodeError::BufferTooSmall)?;
123                dst[..4].copy_from_slice(&[CALL, object, count, outputs]);
124                dst[4..].copy_from_slice(inputs);
125                Ok(len)
126            }
127            Self::Gain { input, level } => write_three(output, [GAIN, input, level]),
128            Self::Mix { left, right } => write_three(output, [MIX, left, right]),
129        }
130    }
131}
132
133fn write_three(output: &mut [u8], bytes: [u8; 3]) -> Result<usize, EncodeError> {
134    output
135        .get_mut(..3)
136        .ok_or(EncodeError::BufferTooSmall)?
137        .copy_from_slice(&bytes);
138    Ok(3)
139}