wavegraph_remote/
graph.rs1use alloc::{string::String, vec::Vec};
2use std::io;
3use wavegraph_core::{Op, bytecode::VERSION};
4
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub enum PortKind {
8 Signal,
10 Message,
12}
13
14#[derive(Clone, Debug, Eq, PartialEq)]
16pub struct Node {
17 pub id: u8,
19 pub generation: u32,
21 pub alias: String,
23 pub kind: String,
25 pub midi_channel: Option<crate::Channel>,
27 pub inlets: Vec<PortKind>,
29 pub outlets: Vec<PortKind>,
31}
32
33#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct Connection {
36 pub source: String,
38 pub destination: String,
40}
41
42#[derive(Clone, Debug, Eq, PartialEq)]
50pub struct Graph {
51 pub session: u32,
53 pub revision: u32,
55 pub first_frame: u64,
57 pub nodes: Vec<Node>,
59 pub program: Vec<u8>,
61 pub outputs: Vec<u8>,
63}
64
65impl Graph {
66 #[must_use]
68 pub fn node(&self, alias: &str) -> Option<&Node> {
69 self.nodes.iter().find(|node| node.alias == alias)
70 }
71
72 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}