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
use crate::{
Channel, Graph, MidiCommand, Node, PortKind,
graph::invalid,
protocol::{self, ErrorCode, Message, SnapshotMeta},
};
use alloc::vec::Vec;
use core::{hash::BuildHasher as _, time::Duration};
use std::{collections::hash_map::RandomState, io, time::Instant};
/// Bidirectional transport carrying complete MIDI messages.
///
/// Implementations supply message boundaries and bounded receive waits. A local
/// socket implementation can length-prefix the same messages; an in-process
/// implementation can pass them directly. No terminal behavior is required.
pub trait Transport {
/// Submit one complete MIDI message.
///
/// # Errors
/// Returns an I/O error if the message cannot be submitted.
fn send(&mut self, message: &[u8]) -> io::Result<()>;
/// Receive one complete message, waiting at most `timeout`.
///
/// # Errors
/// Returns `TimedOut` on expiry, or a transport error on failure/disconnect.
fn receive(&mut self, timeout: Duration) -> io::Result<Vec<u8>>;
}
/// A transport-independent MIDI controller and graph-discovery client.
#[derive(Debug)]
pub struct Client<T> {
transport: T,
request: u32,
}
impl<T: Transport> Client<T> {
/// Start a client with a randomized request-ID seed for reply correlation.
/// Request IDs are not authentication credentials.
#[must_use]
pub fn new(transport: T) -> Self {
let seed = RandomState::new().hash_one(Instant::now()) & u64::from(u32::MAX);
Self {
transport,
request: u32::try_from(seed).unwrap_or_default(),
}
}
/// Return the owned transport.
#[must_use]
pub fn into_transport(self) -> T {
self.transport
}
/// Send an ordinary MIDI command, validating data bytes before transmission.
///
/// This confirms transport submission only. It does not wait for audio
/// application, and ordinary MIDI commands have no remote completion receipt.
///
/// # Errors
/// Returns an error for invalid MIDI values or a failed transport send.
pub fn send(&mut self, command: MidiCommand) -> io::Result<()> {
let mut bytes = [0; 3];
let len = command.encode(&mut bytes)?;
self.transport.send(&bytes[..len])
}
/// Query a complete, coherent graph snapshot within a total time budget.
///
/// Unrelated MIDI and replies to other requests are ignored. Missing,
/// duplicated, out-of-order and malformed records fail the whole query.
/// Every call starts fresh; a failed snapshot never replaces a caller's graph.
///
/// # Errors
/// Returns `TimedOut` when no complete snapshot arrives (including firmware
/// without this protocol), a target rejection, or invalid-data/transport errors.
pub fn graph(&mut self, timeout: Duration) -> io::Result<Graph> {
let deadline = Instant::now()
.checked_add(timeout)
.filter(|_| !timeout.is_zero())
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"timeout must be finite and nonzero",
)
})?;
self.request = self.request.wrapping_add(1);
let request = self.request;
let mut frame = [0; protocol::MAX_FRAME];
let length =
protocol::encode(request, Message::Query, &mut frame).map_err(invalid_protocol)?;
self.transport.send(&frame[..length])?;
let mut scratch = [0; protocol::MAX_PAYLOAD];
let mut snapshot: Option<Snapshot> = None;
loop {
let remaining = deadline
.checked_duration_since(Instant::now())
.filter(|wait| !wait.is_zero())
.ok_or_else(timed_out)?;
let bytes = self.transport.receive(remaining).map_err(|error| {
if error.kind() == io::ErrorKind::TimedOut {
timed_out()
} else {
error
}
})?;
if !protocol::is_remote(&bytes) {
continue;
}
if protocol::request_id(&bytes).map_err(invalid_protocol)? != request {
continue;
}
let (reply, message) =
protocol::decode(&bytes, &mut scratch).map_err(invalid_protocol)?;
if reply != request {
continue;
}
match message {
Message::Begin { meta, outputs } => {
if snapshot.is_some()
|| meta.code_len == 0
|| meta.code_len > 4096
|| outputs.len() > 16
{
return Err(invalid("invalid or duplicate graph snapshot header"));
}
snapshot = Some(Snapshot {
meta,
graph: Graph {
session: meta.session,
revision: meta.revision,
first_frame: meta.first_frame,
nodes: Vec::with_capacity(usize::from(meta.nodes)),
program: Vec::with_capacity(usize::from(meta.code_len)),
outputs: outputs.to_vec(),
},
});
}
Message::Node(node) => {
let snapshot = snapshot
.as_mut()
.ok_or_else(|| invalid("node arrived before snapshot header"))?;
if snapshot.graph.nodes.len() >= usize::from(snapshot.meta.nodes)
|| !snapshot.graph.program.is_empty()
|| snapshot
.graph
.nodes
.iter()
.any(|old| old.id == node.id || old.alias == node.alias)
{
return Err(invalid("unexpected or duplicate graph node"));
}
let midi_channel = node
.midi_channel
.map(|channel| Channel::new(channel.saturating_add(1)))
.transpose()?;
let ports = |bytes: &[u8]| {
bytes
.iter()
.map(|kind| {
if *kind == 0 {
PortKind::Signal
} else {
PortKind::Message
}
})
.collect()
};
snapshot.graph.nodes.push(Node {
id: node.id,
generation: node.generation,
alias: node.alias.into(),
kind: node.kind.into(),
midi_channel,
inlets: ports(node.inlets),
outlets: ports(node.outlets),
});
}
Message::Code { offset, bytes } => {
let snapshot = snapshot
.as_mut()
.ok_or_else(|| invalid("bytecode arrived before snapshot header"))?;
if snapshot.graph.nodes.len() != usize::from(snapshot.meta.nodes)
|| usize::from(offset) != snapshot.graph.program.len()
|| snapshot.graph.program.len().saturating_add(bytes.len())
> usize::from(snapshot.meta.code_len)
{
return Err(invalid(
"missing, reordered, or oversized graph bytecode chunk",
));
}
snapshot.graph.program.extend_from_slice(bytes);
}
Message::End => {
let snapshot =
snapshot.ok_or_else(|| invalid("snapshot ended before its header"))?;
if snapshot.graph.nodes.len() != usize::from(snapshot.meta.nodes)
|| snapshot.graph.program.len() != usize::from(snapshot.meta.code_len)
{
return Err(invalid("incomplete graph snapshot"));
}
snapshot.graph.connections()?;
return Ok(snapshot.graph);
}
Message::Error(code) => {
return Err(match code {
ErrorCode::Busy => io::Error::new(
io::ErrorKind::WouldBlock,
"WaveGraph is serving another graph query; retry",
),
ErrorCode::NotReady => io::Error::new(
io::ErrorKind::WouldBlock,
"WaveGraph has not accepted an audio block yet",
),
ErrorCode::Unsupported => io::Error::new(
io::ErrorKind::Unsupported,
"WaveGraph does not support this query",
),
});
}
Message::Query => {
return Err(invalid("received a query instead of a graph response"));
}
}
}
}
}
struct Snapshot {
meta: SnapshotMeta,
graph: Graph,
}
fn invalid_protocol(error: protocol::ProtocolError) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, error)
}
fn timed_out() -> io::Error {
io::Error::new(
io::ErrorKind::TimedOut,
"no complete WaveGraph snapshot; install firmware with wavegraph-remote support or increase the timeout",
)
}