Skip to main content

wavegraph_remote/
graph.rs

1use alloc::{string::String, vec::Vec};
2use std::io;
3use wavegraph_core::{Op, bytecode::VERSION};
4
5/// Kind of one ordered process port.
6#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub enum PortKind {
8    /// An audio signal bus.
9    Signal,
10    /// Discrete, frame-timed messages.
11    Message,
12}
13
14/// A native process in a captured graph, including its current MIDI binding.
15#[derive(Clone, Debug, Eq, PartialEq)]
16pub struct Node {
17    /// Object-table index in this snapshot's bytecode.
18    pub id: u8,
19    /// Assignment generation within this running engine session.
20    pub generation: u32,
21    /// Unique alphanumeric alias in this snapshot.
22    pub alias: String,
23    /// Type name supplied by the running endpoint.
24    pub kind: String,
25    /// Current MIDI input binding, if any.
26    pub midi_channel: Option<crate::Channel>,
27    /// Local inlet kinds in order, including message ports.
28    pub inlets: Vec<PortKind>,
29    /// Local outlet kinds in order, including message ports.
30    pub outlets: Vec<PortKind>,
31}
32
33/// One audio connection, reconstructed from the actual signal bytecode.
34#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct Connection {
36    /// Source alias and local outlet, or a bytecode operation's output.
37    pub source: String,
38    /// Destination alias and local inlet, or a physical-output binding.
39    pub destination: String,
40}
41
42/// Coherent graph description returned by a running endpoint.
43///
44/// Object IDs and generations are meaningful within an engine session; aliases
45/// are snapshot labels. A reconnect requires a new snapshot. Internal DSP inside
46/// a native process is opaque. `connections` describes signal routing; MIDI
47/// bindings are reported on the nodes, and arbitrary message cords are not yet
48/// represented by this protocol version.
49#[derive(Clone, Debug, Eq, PartialEq)]
50pub struct Graph {
51    /// Target connection epoch, not a globally unique or persistent boot ID.
52    pub session: u32,
53    /// Applied topology revision within this engine session.
54    pub revision: u32,
55    /// First frame of the accepted audio block that introduced this revision.
56    pub first_frame: u64,
57    /// Native process descriptions.
58    pub nodes: Vec<Node>,
59    /// Exact active signal program, including its bytecode version.
60    pub program: Vec<u8>,
61    /// Active signal buses bound to physical outputs, in output order.
62    pub outputs: Vec<u8>,
63}
64
65impl Graph {
66    /// Find a node by its exact, case-sensitive alias.
67    #[must_use]
68    pub fn node(&self, alias: &str) -> Option<&Node> {
69        self.nodes.iter().find(|node| node.alias == alias)
70    }
71
72    /// Reconstruct signal connections from the program and node port layouts.
73    ///
74    /// Message ports retain their local indices even though bytecode signal
75    /// operands omit them. Built-in gain/mix operations have `@gainN`/`@mixN`
76    /// labels; `N` is their instruction ordinal, independent of native IDs.
77    ///
78    /// # Errors
79    /// Rejects unknown versions, duplicate IDs/aliases/calls, missing nodes,
80    /// invalid port layouts, forward bus references and invalid output bindings.
81    pub fn connections(&self) -> io::Result<Vec<Connection>> {
82        for (i, node) in self.nodes.iter().enumerate() {
83            if self.nodes[..i]
84                .iter()
85                .any(|other| other.id == node.id || other.alias == node.alias)
86            {
87                return Err(invalid("duplicate graph node ID or alias"));
88            }
89        }
90        let Some((&VERSION, mut code)) = self.program.split_first() else {
91            return Err(invalid("unsupported or missing signal bytecode version"));
92        };
93        let mut buses = Vec::<String>::new();
94        let mut edges = Vec::new();
95        let mut called = [false; 256];
96        let mut instruction = 0usize;
97        while !code.is_empty() {
98            let (op, rest) = Op::decode(code).map_err(|_| invalid("invalid signal bytecode"))?;
99            code = rest;
100            match op {
101                Op::Call {
102                    object,
103                    inputs,
104                    outputs,
105                } => {
106                    if core::mem::replace(&mut called[usize::from(object)], true) {
107                        return Err(invalid("process appears twice in the signal program"));
108                    }
109                    let node = self
110                        .nodes
111                        .iter()
112                        .find(|node| node.id == object)
113                        .ok_or_else(|| invalid("signal program references an unknown process"))?;
114                    let inlet_count = node
115                        .inlets
116                        .iter()
117                        .filter(|kind| **kind == PortKind::Signal)
118                        .count();
119                    let outlet_count = node
120                        .outlets
121                        .iter()
122                        .filter(|kind| **kind == PortKind::Signal)
123                        .count();
124                    if inlet_count != inputs.len() || outlet_count != usize::from(outputs) {
125                        return Err(invalid("signal program does not match process ports"));
126                    }
127                    let inlets = node
128                        .inlets
129                        .iter()
130                        .enumerate()
131                        .filter(|(_, kind)| **kind == PortKind::Signal);
132                    for ((port, _), bus) in inlets.zip(inputs) {
133                        edges.push(Connection {
134                            source: source(&buses, *bus)?.into(),
135                            destination: format!("{}.in{port}", node.alias),
136                        });
137                    }
138                    for (port, _) in node
139                        .outlets
140                        .iter()
141                        .enumerate()
142                        .filter(|(_, kind)| **kind == PortKind::Signal)
143                    {
144                        buses.push(format!("{}.out{port}", node.alias));
145                    }
146                }
147                Op::Gain { input, level } => {
148                    let alias = format!("@gain{instruction}({level}/128)");
149                    edges.push(Connection {
150                        source: source(&buses, input)?.into(),
151                        destination: format!("{alias}.in0"),
152                    });
153                    buses.push(format!("{alias}.out0"));
154                }
155                Op::Mix { left, right } => {
156                    let alias = format!("@mix{instruction}");
157                    for (port, bus) in [left, right].into_iter().enumerate() {
158                        edges.push(Connection {
159                            source: source(&buses, bus)?.into(),
160                            destination: format!("{alias}.in{port}"),
161                        });
162                    }
163                    buses.push(format!("{alias}.out0"));
164                }
165            }
166            if buses.len() > 256 {
167                return Err(invalid("signal program exceeds 256 buses"));
168            }
169            instruction = instruction.saturating_add(1);
170        }
171        for (index, bus) in self.outputs.iter().enumerate() {
172            edges.push(Connection {
173                source: source(&buses, *bus)?.into(),
174                destination: format!("output{index}"),
175            });
176        }
177        Ok(edges)
178    }
179}
180
181fn source(buses: &[String], bus: u8) -> io::Result<&str> {
182    buses
183        .get(usize::from(bus))
184        .map(String::as_str)
185        .ok_or_else(|| invalid("signal references an unavailable bus"))
186}
187
188pub(crate) fn invalid(message: &'static str) -> io::Error {
189    io::Error::new(io::ErrorKind::InvalidData, message)
190}