wavegraph 0.1.1

Run text patches as a remotely controlled WaveGraph audio engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Synchronous rendering of a compiled patch. The host supplies the audio clock.

use crate::{
    effects::{Effect, EffectStorage},
    nodes::{self, Message},
    sequencer::Sequence,
    voices::{self, Voice},
};
use std::io;
use wavegraph_audio::{Block, FRAMES};
use wavegraph_compiler::CompiledPatch;
use wavegraph_core::{
    Event, Port, Process,
    midi::{MidiMessage, Note},
};
use wavegraph_dsp::{
    bytecode::{Patch, Program},
    dsp::Software,
};
use wavegraph_remote::{Channel, Graph, MidiCommand, Node, PortKind};
use wavegraph_sample::I24;

/// Source sample rate of the native TR-909 cymbal bank.
pub(crate) const RATE: u32 = 44_100;
const MAX_NODES: usize = u8::MAX as usize + 1;
const MAX_PORTS: usize = 16;
/// Maximum number of ordered RPC messages accepted in a render job.
pub(crate) const MAX_COMMANDS: usize = 64;
// The initial Start and up to six simultaneous drum strikes can share a block.
const MAX_EVENTS: usize = 1 + MAX_COMMANDS + 6;
type Object<'a> = dyn Process<Message, I24> + 'a;

pub(crate) fn compile(source: &str) -> io::Result<CompiledPatch> {
    wavegraph_compiler::compile(source, nodes::spec).map_err(invalid)
}

/// Construct and bind the graph once for the lifetime of this DSP session.
/// Native effects borrow their delay lines and the decoded schedule borrows its
/// bytecode. Keeping the render loop inside this callback preserves those borrows.
pub(crate) fn with_renderer<R>(
    compiled: CompiledPatch,
    bpm: u16,
    run: impl FnOnce(&mut Renderer<'_, '_>, Graph) -> io::Result<R>,
) -> io::Result<R> {
    if !(30..=300).contains(&bpm) {
        return Err(invalid("tempo must be between 30 and 300 BPM"));
    }
    let mut storage: Vec<_> = compiled
        .nodes
        .iter()
        .map(|n| EffectStorage::new(&n.kind, RATE))
        .collect();
    let mut objects = Vec::<Box<Object<'_>>>::with_capacity(storage.len());
    let mut nodes = Vec::with_capacity(storage.len());
    let mut tracks = Vec::with_capacity(storage.len());
    for (mut node, storage) in compiled.nodes.into_iter().zip(&mut storage) {
        let at_node = |msg: String| invalid(format!("line {} ({}): {msg}", node.line, node.alias));
        let channel = if let Some(index) = node.options.iter().position(|(key, _)| key == "ch") {
            let (_, text) = node.options.remove(index);
            let number = text
                .parse::<u8>()
                .ok()
                .and_then(|n| Channel::new(n).ok())
                .ok_or_else(|| {
                    at_node(format!(
                        "ch must be a MIDI channel from 1 to 16, found '{text}'"
                    ))
                })?;
            Some(number)
        } else {
            None
        };
        let (object, sequence): (Box<Object<'_>>, _) = if voices::spec(&node.kind).is_some() {
            (
                Box::new(Voice::new(&node, RATE).map_err(at_node)?),
                Some(Sequence::from_node(&node).map_err(at_node)?),
            )
        } else {
            (
                Box::new(Effect::new(&node, RATE, bpm, storage).map_err(at_node)?),
                None,
            )
        };
        nodes.push(Node {
            id: u8::try_from(nodes.len()).map_err(invalid)?,
            generation: 1,
            alias: node.alias,
            kind: node.kind,
            midi_channel: channel,
            inlets: port_kinds(object.inlets()),
            outlets: port_kinds(object.outlets()),
        });
        objects.push(object);
        tracks.push(Track {
            channel,
            sequence,
            events: heapless::Vec::new(),
        });
    }
    let mut objects: Vec<_> = objects
        .iter_mut()
        .map(|node| -> &mut Object<'_> { node.as_mut() })
        .collect();
    // The format permits up to 256 output buses. Every host node has a signal outlet.
    let program = Program::<256, MAX_PORTS>::decode(&compiled.bytecode).map_err(dsp_error)?;
    let buffers = vec![[I24::default(); FRAMES]; program.buses()];
    let patch = program.bind(&mut objects).map_err(dsp_error)?;
    let graph = Graph {
        session: std::process::id(),
        revision: 1,
        first_frame: 0,
        nodes,
        program: compiled.bytecode.clone(),
        outputs: compiled.outputs.to_vec(),
    };
    run(
        &mut Renderer {
            patch,
            tracks,
            buffers,
            outputs: compiled.outputs.map(usize::from),
            clock: Clock::new(RATE, bpm),
            start_on_first_block: true,
        },
        graph,
    )
}

fn port_kinds(ports: &[Port]) -> Vec<PortKind> {
    ports
        .iter()
        .map(|port| match port {
            Port::Message => PortKind::Message,
            Port::Signal => PortKind::Signal,
        })
        .collect()
}

fn invalid(message: impl core::fmt::Display) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, message.to_string())
}

fn dsp_error(error: wavegraph_dsp::bytecode::Error) -> io::Error {
    invalid(format!("DSP program: {error:?}"))
}

struct Track {
    channel: Option<Channel>,
    sequence: Option<Sequence>,
    events: heapless::Vec<Event<Message>, MAX_EVENTS>,
}

pub(crate) struct Renderer<'run, 'node> {
    patch: Patch<'run, 'node, Message, I24, MAX_PORTS>,
    tracks: Vec<Track>,
    buffers: Vec<[I24; FRAMES]>,
    outputs: [usize; 2],
    clock: Clock,
    start_on_first_block: bool,
}

impl Renderer<'_, '_> {
    pub(crate) fn render(
        &mut self,
        commands: &[MidiCommand],
        output: &mut Block,
    ) -> io::Result<()> {
        if commands.len() > MAX_COMMANDS {
            return Err(invalid("too many MIDI commands for one render block"));
        }
        for track in &mut self.tracks {
            track.events.clear();
        }
        let start = core::mem::take(&mut self.start_on_first_block).then_some(MidiCommand::Play);
        for command in start.into_iter().chain(commands.iter().copied()) {
            let (channel, message) = match command {
                MidiCommand::Play => {
                    self.clock.restart();
                    (None, Message::Start)
                }
                MidiCommand::Stop => {
                    self.clock.playing = false;
                    (None, Message::Stop)
                }
                MidiCommand::NoteOn {
                    channel,
                    note,
                    velocity,
                } => (
                    Some(channel),
                    Message::Midi(MidiMessage::On(Note {
                        number: note,
                        velocity,
                    })),
                ),
                MidiCommand::NoteOff { channel, note } => {
                    (Some(channel), Message::Midi(MidiMessage::Off(note)))
                }
                MidiCommand::ControlChange {
                    channel,
                    controller,
                    value,
                } => (
                    Some(channel),
                    Message::Midi(MidiMessage::Control(controller, value)),
                ),
                MidiCommand::AllNotesOff { channel } => {
                    (Some(channel), Message::Midi(MidiMessage::Control(123, 0)))
                }
            };
            for track in &mut self.tracks {
                if channel.is_none() || track.channel == channel {
                    track
                        .events
                        .push(Event {
                            frame: 0,
                            port: 0,
                            message,
                        })
                        .map_err(|_| invalid("MIDI event capacity exceeded"))?;
                }
            }
        }
        self.clock.advance(FRAMES, |frame, half_step| {
            for track in &mut self.tracks {
                let Some(sequence) = &track.sequence else {
                    continue;
                };
                let mut full = false;
                let mut emit = |midi| {
                    full |= track
                        .events
                        .push(Event {
                            frame,
                            port: 0,
                            message: Message::Midi(midi),
                        })
                        .is_err();
                };
                if half_step.is_multiple_of(2) {
                    sequence.step(half_step / 2, &mut emit);
                } else {
                    sequence.release(half_step / 2, &mut emit);
                }
                if full {
                    return Err(invalid("pattern event capacity exceeded"));
                }
            }
            Ok(())
        })?;
        let events: heapless::Vec<_, MAX_NODES> =
            self.tracks.iter().map(|t| t.events.as_slice()).collect();
        self.patch
            .render(&mut Software, &mut self.buffers, &events, |_, event| {
                Err(event)
            })
            .map_err(dsp_error)?;
        let [left, right] = self.outputs.map(|bus| &self.buffers[bus]);
        for ((dst, l), r) in output.iter_mut().zip(left).zip(right) {
            *dst = [l.inner(), r.inner()];
        }
        Ok(())
    }
}

/// Integer phase for steps and their halfway gate releases. Keep the fractional
/// sample across both block and pattern boundaries.
struct Clock {
    threshold: u64,
    increment: u64,
    phase: u64,
    half_step: u64,
    playing: bool,
}

impl Clock {
    fn new(rate: u32, bpm: u16) -> Self {
        Self {
            threshold: 60 * u64::from(rate),
            increment: 8 * u64::from(bpm),
            phase: 0,
            half_step: 0,
            playing: false,
        }
    }

    fn restart(&mut self) {
        self.playing = true;
        self.phase = self.threshold;
        self.half_step = 0;
    }

    #[allow(
        clippy::arithmetic_side_effects,
        reason = "Phase is reduced below 60 * rate (u32) before adding 8 * tempo (at most 2400)."
    )]
    fn advance(
        &mut self,
        frames: usize,
        mut edge: impl FnMut(usize, u64) -> io::Result<()>,
    ) -> io::Result<()> {
        if self.playing {
            for frame in 0..frames {
                if self.phase >= self.threshold {
                    self.phase -= self.threshold;
                    edge(frame, self.half_step)?;
                    self.half_step = self.half_step.wrapping_add(1);
                }
                self.phase += self.increment;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    reason = "Inputs and expected results are fixed test fixtures."
)]
mod tests {
    use super::*;

    #[test]
    fn bytecode_outputs_and_midi_bindings_determine_the_rendered_pcm() {
        let source = "node kick tr808 ch=3\ngain muted kick.out 0\noutput left kick.out\noutput right muted.out";
        let strike = |ch| MidiCommand::NoteOn {
            channel: Channel::new(ch).unwrap(),
            note: 36,
            velocity: 120,
        };
        with_renderer(compile(source).unwrap(), 122, |renderer, _| {
            let mut block = [[-1; 2]; FRAMES];
            renderer.render(&[strike(4)], &mut block)?;
            assert!(block.iter().all(|frame| *frame == [0, 0]));
            renderer.render(&[strike(3)], &mut block)?;
            assert!(block.iter().any(|frame| frame[0] != 0));
            assert!(block.iter().all(|frame| frame[1] == 0));
            Ok(())
        })
        .unwrap();
    }

    #[test]
    fn first_block_stop_overrides_autoplay_and_play_restarts_at_step_zero() {
        let source = "node kick tr808 steps=36!,-\noutput left kick.out\noutput right kick.out";
        with_renderer(compile(source).unwrap(), 122, |renderer, _| {
            let mut block = [[0; 2]; FRAMES];
            renderer.render(&[MidiCommand::Stop], &mut block)?;
            assert!(block.iter().all(|frame| *frame == [0, 0]));
            renderer.render(&[MidiCommand::Play], &mut block)?;
            assert!(block.iter().any(|frame| *frame != [0, 0]));
            Ok(())
        })
        .unwrap();
    }

    #[test]
    fn renders_all_256_addressable_nodes_without_remote_discovery() {
        use core::fmt::Write as _;

        let mut source = String::new();
        for id in 0..=u8::MAX {
            writeln!(source, "node bass{id} tb303").unwrap();
        }
        source.push_str("output left bass0.out\noutput right bass255.out");
        with_renderer(compile(&source).unwrap(), 122, |renderer, graph| {
            assert_eq!(graph.nodes.len(), 256);
            assert_eq!(graph.outputs, [0, 255]);
            renderer.render(&[], &mut [[0; 2]; FRAMES])
        })
        .unwrap();
    }

    #[test]
    fn sequencer_keeps_fractional_sample_time_across_block_boundaries() {
        let mut clock = Clock::new(44_100, 122);
        clock.restart();
        let mut edges = Vec::new();
        for block in 0..500 {
            clock
                .advance(FRAMES, |offset, half| {
                    assert_eq!(half, edges.len() as u64);
                    edges.push(u64::try_from(block * FRAMES + offset).unwrap());
                    Ok(())
                })
                .unwrap();
        }
        assert!(edges.len() > 20);
        for (half, actual) in (0u64..).zip(edges) {
            assert_eq!(actual, (half * 44_100 * 60).div_ceil(122 * 8));
        }
    }

    #[test]
    fn the_3389_file_plays_through_its_mixer_and_stereo_returns() {
        let compiled = compile(include_str!("../patches/3389.wg")).unwrap();
        with_renderer(compiled, 122, |renderer, graph| {
            let mixer = graph.node("mixer").unwrap().midi_channel.unwrap();
            assert!(
                graph
                    .connections()
                    .unwrap()
                    .iter()
                    .any(|cord| cord.source == "drums909.out1" && cord.destination == "strip1.in2")
            );
            let level = |controller, value| MidiCommand::ControlChange {
                channel: mixer,
                controller,
                value,
            };
            let mut block = [[0; 2]; FRAMES];
            renderer.render(
                &[level(16, 0), level(17, 0), level(18, 0), level(19, 0)],
                &mut block,
            )?;
            assert!(block.iter().all(|frame| *frame == [0, 0]));
            renderer.render(&[level(16, 64)], &mut block)?;
            let mut audible = false;
            let mut stereo = false;
            for _ in 0..180 {
                renderer.render(&[], &mut block)?;
                audible |= block.iter().any(|frame| *frame != [0, 0]);
                stereo |= block.iter().any(|[left, right]| left != right);
            }
            assert!(
                audible,
                "the bass pattern should reach the master through strip 1"
            );
            assert!(
                stereo,
                "the patch pans its reverb and delay to different sides"
            );
            Ok(())
        })
        .unwrap();
    }
}