1use 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum Error {
19 Version,
21 Instruction(DecodeError),
23 Capacity,
25 Bus,
27 Object,
29 Ports,
31 Buffers,
33 Event,
35}
36
37#[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 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 #[must_use]
104 pub fn buses(&self) -> usize {
105 self.buses
106 }
107
108 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 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
163pub 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 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 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 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 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 if addressed == 0 {
302 Ok(())
303 } else {
304 Err(Error::Event)
305 }
306 }
307}