Skip to main content

wavegraph_dsp/
bytecode.rs

1//! A bounded interpreter for compiled, feed-forward signal graphs.
2//!
3//! The [wire format][wavegraph_core::bytecode] and [`Op`] are shared with host
4//! compilers. Every instruction appends its outputs to the table of mono buses.
5//!
6//! Object indices name instances supplied by the application. Control messages
7//! use the patch's Rust payload type and are delivered separately from this
8//! instruction stream.
9
10use crate::{Event, Port, Process, ProcessContext, dsp::Dsp};
11use core::{fmt, marker::PhantomData};
12use heapless::Vec;
13
14pub use wavegraph_core::bytecode::{DecodeError, Op, VERSION};
15
16/// Indicates which part of a program or render request could not be accepted.
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum Error {
19    /// Missing or unsupported version byte.
20    Version,
21    /// Unknown opcode or incomplete operands.
22    Instruction(DecodeError),
23    /// The program exceeds an instruction, bus, or per-object port limit.
24    Capacity,
25    /// A source refers to a bus which has not yet been produced.
26    Bus,
27    /// An object is absent or called more than once per block.
28    Object,
29    /// The declared signal arity differs from the object's port layout.
30    Ports,
31    /// Too few signal buffers were supplied.
32    Buffers,
33    /// An input event has an invalid destination, frame offset, or order.
34    Event,
35}
36
37/// A decoded, feed-forward block schedule. It can be prepared while another
38/// program plays. `OPS` bounds the stored instructions. `PORTS` bounds the
39/// signal inlets and outlets per object independently.
40#[derive(Debug)]
41pub struct Program<'code, const OPS: usize, const PORTS: usize = 8> {
42    ops: Vec<Op<'code>, OPS>,
43    buses: usize,
44}
45
46impl<'code, const OPS: usize, const PORTS: usize> Program<'code, OPS, PORTS> {
47    /// Decode the wire format and validate its routing and resource bounds.
48    ///
49    /// # Errors
50    /// Returns an error for invalid bytecode or exceeded capacities. Wire
51    /// indices address up to 256 objects and 256 signal buses.
52    pub fn decode(code: &'code [u8]) -> Result<Self, Error> {
53        let Some((&VERSION, mut code)) = code.split_first() else {
54            return Err(Error::Version);
55        };
56        let mut ops = Vec::new();
57        let mut buses: usize = 0;
58        let mut called = [false; 256];
59        while !code.is_empty() {
60            let (op, next) = Op::decode(code).map_err(Error::Instruction)?;
61            code = next;
62            let produced = match op {
63                Op::Call {
64                    object,
65                    inputs,
66                    outputs,
67                } => {
68                    if core::mem::replace(&mut called[usize::from(object)], true) {
69                        return Err(Error::Object);
70                    }
71                    let outputs = usize::from(outputs);
72                    if inputs.len() > PORTS || outputs > PORTS {
73                        return Err(Error::Capacity);
74                    }
75                    if inputs.iter().any(|&bus| usize::from(bus) >= buses) {
76                        return Err(Error::Bus);
77                    }
78                    outputs
79                }
80                Op::Gain { input, .. } => {
81                    if usize::from(input) >= buses {
82                        return Err(Error::Bus);
83                    }
84                    1
85                }
86                Op::Mix { left, right } => {
87                    if usize::from(left.max(right)) >= buses {
88                        return Err(Error::Bus);
89                    }
90                    1
91                }
92            };
93            buses = buses.saturating_add(produced);
94            if buses > 256 {
95                return Err(Error::Capacity);
96            }
97            ops.push(op).map_err(|_| Error::Capacity)?;
98        }
99        Ok(Self { ops, buses })
100    }
101
102    /// Number of mono block buffers required by this program.
103    #[must_use]
104    pub fn buses(&self) -> usize {
105        self.buses
106    }
107
108    /// Bind application-owned processor instances to the program's object indices.
109    ///
110    /// # Errors
111    /// Returns [`Error::Object`] for missing instances and [`Error::Ports`] for
112    /// signal layouts that disagree with the bytecode.
113    pub fn bind<'run, 'node, M, S>(
114        &'run self,
115        objects: &'run mut [&'node mut dyn Process<M, S>],
116    ) -> Result<Patch<'run, 'node, M, S, PORTS>, Error> {
117        self.bind_nodes(objects)
118    }
119
120    /// Bind nodes while retaining their concrete type or trait-object bounds.
121    /// For example, a table of `dyn Process<M, S> + Send` produces a `Send`
122    /// patch that can be handed to an audio task.
123    ///
124    /// # Errors
125    /// Returns the same object and port errors as [`Self::bind`].
126    pub fn bind_nodes<'run, 'node, M, S, P: Process<M, S> + ?Sized>(
127        &'run self,
128        objects: &'run mut [&'node mut P],
129    ) -> Result<Patch<'run, 'node, M, S, PORTS, P>, Error> {
130        self.check_objects(objects)?;
131        Ok(Patch {
132            ops: &self.ops,
133            buses: self.buses,
134            objects,
135            format: PhantomData,
136        })
137    }
138
139    fn check_objects<M, S, P: Process<M, S> + ?Sized>(
140        &self,
141        objects: &[&mut P],
142    ) -> Result<(), Error> {
143        for op in &self.ops {
144            if let Op::Call {
145                object,
146                inputs,
147                outputs,
148            } = op
149            {
150                let node = objects.get(usize::from(*object)).ok_or(Error::Object)?;
151                let signals = |ports: &[Port]| ports.iter().filter(|&&p| p == Port::Signal).count();
152                if inputs.len() != signals(node.inlets())
153                    || usize::from(*outputs) != signals(node.outlets())
154                {
155                    return Err(Error::Ports);
156                }
157            }
158        }
159        Ok(())
160    }
161}
162
163/// A decoded schedule bound to the stateful objects it will render.
164pub struct Patch<'run, 'node, M, S, const PORTS: usize, P: ?Sized = dyn Process<M, S> + 'node> {
165    ops: &'run [Op<'run>],
166    buses: usize,
167    objects: &'run mut [&'node mut P],
168    // Messages and samples are borrowed only during render.
169    format: PhantomData<fn(M, S)>,
170}
171
172impl<M, S, const PORTS: usize, P: ?Sized> fmt::Debug for Patch<'_, '_, M, S, PORTS, P> {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        f.debug_struct("Patch")
175            .field("instructions", &self.ops.len())
176            .field("buses", &self.buses)
177            .finish_non_exhaustive()
178    }
179}
180
181impl<'run, M, S, const PORTS: usize, P: Process<M, S> + ?Sized> Patch<'run, '_, M, S, PORTS, P> {
182    /// Switch schedules between blocks, retaining every object's state.
183    ///
184    /// # Errors
185    /// If the program needs more than `available_buses` or the object layouts
186    /// are incompatible, the current schedule remains active.
187    pub fn replace<const OPS: usize>(
188        &mut self,
189        program: &'run Program<'_, OPS, PORTS>,
190        available_buses: usize,
191    ) -> Result<(), Error> {
192        if program.buses > available_buses {
193            return Err(Error::Buffers);
194        }
195        program.check_objects(self.objects)?;
196        self.ops = &program.ops;
197        self.buses = program.buses;
198        Ok(())
199    }
200
201    /// Render one block into caller-owned mono buses. The host chooses which
202    /// bus to send to each physical output. `events[i]` belongs to object
203    /// `i`; omitted trailing lists are empty. The `emit` sink receives the
204    /// emitting object's index and its unmodified local outlet event. The
205    /// host bounds the number of input events per block and the work in its
206    /// event sink to fit its audio deadline.
207    ///
208    /// # Errors
209    /// Invalid events, events addressed to inactive objects, and insufficient
210    /// buffers are rejected before processing
211    /// any object or writing any output.
212    pub fn render<const FRAMES: usize>(
213        &mut self,
214        dsp: &mut impl Dsp<S>,
215        buffers: &mut [[S; FRAMES]],
216        events: &[&[Event<M>]],
217        mut emit: impl FnMut(u8, Event<M>) -> Result<(), Event<M>>,
218    ) -> Result<(), Error> {
219        if buffers.len() < self.buses {
220            return Err(Error::Buffers);
221        }
222        self.check_events::<FRAMES>(events)?;
223
224        let mut used = 0;
225        for op in self.ops {
226            let (ready, free) = buffers.split_at_mut(used);
227            let produced = match *op {
228                Op::Call {
229                    object,
230                    inputs,
231                    outputs,
232                } => {
233                    let inputs: Vec<_, PORTS> = inputs
234                        .iter()
235                        .map(|&bus| ready[usize::from(bus)].as_slice())
236                        .collect();
237                    let count = usize::from(outputs);
238                    let mut outputs: Vec<_, PORTS> = free[..count]
239                        .iter_mut()
240                        .map(|bus| bus.as_mut_slice())
241                        .collect();
242                    let index = usize::from(object);
243                    self.objects[index].process(&mut ProcessContext {
244                        frames: FRAMES,
245                        inputs: &inputs,
246                        outputs: &mut outputs,
247                        events: events.get(index).copied().unwrap_or_default(),
248                        emit: &mut |event| emit(object, event),
249                    });
250                    count
251                }
252                Op::Gain { input, level } => {
253                    dsp.gain(&ready[usize::from(input)], level, &mut free[0]);
254                    1
255                }
256                Op::Mix { left, right } => {
257                    dsp.mix(
258                        &ready[usize::from(left)],
259                        &ready[usize::from(right)],
260                        &mut free[0],
261                    );
262                    1
263                }
264            };
265            used = used.saturating_add(produced);
266        }
267        Ok(())
268    }
269
270    fn check_events<const FRAMES: usize>(&self, events: &[&[Event<M>]]) -> Result<(), Error> {
271        if events.is_empty() {
272            return Ok(());
273        }
274        if events.len() > self.objects.len() {
275            return Err(Error::Event);
276        }
277        let mut addressed = events.iter().filter(|batch| !batch.is_empty()).count();
278        for op in self.ops {
279            // The decoder allows each object only one call per program.
280            if addressed == 0 {
281                return Ok(());
282            }
283            let Op::Call { object, .. } = op else {
284                continue;
285            };
286            let index = usize::from(*object);
287            let Some(&batch) = events.get(index).filter(|batch| !batch.is_empty()) else {
288                continue;
289            };
290            let mut previous = 0;
291            let ports = self.objects[index].inlets().len();
292            for event in batch {
293                if event.frame < previous || event.frame >= FRAMES.max(1) || event.port >= ports {
294                    return Err(Error::Event);
295                }
296                previous = event.frame;
297            }
298            addressed = addressed.saturating_sub(1);
299        }
300        // A live edit may have disconnected an object that still has queued notes.
301        if addressed == 0 {
302            Ok(())
303        } else {
304            Err(Error::Event)
305        }
306    }
307}