wavegraph-remote 0.1.1

MIDI control and live graph discovery for WaveGraph
Documentation
use alloc::{string::String, vec::Vec};
use std::io;
use wavegraph_core::{Op, bytecode::VERSION};

/// Kind of one ordered process port.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PortKind {
    /// An audio signal bus.
    Signal,
    /// Discrete, frame-timed messages.
    Message,
}

/// A native process in a captured graph, including its current MIDI binding.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Node {
    /// Object-table index in this snapshot's bytecode.
    pub id: u8,
    /// Assignment generation within this running engine session.
    pub generation: u32,
    /// Unique alphanumeric alias in this snapshot.
    pub alias: String,
    /// Type name supplied by the running endpoint.
    pub kind: String,
    /// Current MIDI input binding, if any.
    pub midi_channel: Option<crate::Channel>,
    /// Local inlet kinds in order, including message ports.
    pub inlets: Vec<PortKind>,
    /// Local outlet kinds in order, including message ports.
    pub outlets: Vec<PortKind>,
}

/// One audio connection, reconstructed from the actual signal bytecode.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Connection {
    /// Source alias and local outlet, or a bytecode operation's output.
    pub source: String,
    /// Destination alias and local inlet, or a physical-output binding.
    pub destination: String,
}

/// Coherent graph description returned by a running endpoint.
///
/// Object IDs and generations are meaningful within an engine session; aliases
/// are snapshot labels. A reconnect requires a new snapshot. Internal DSP inside
/// a native process is opaque. `connections` describes signal routing; MIDI
/// bindings are reported on the nodes, and arbitrary message cords are not yet
/// represented by this protocol version.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Graph {
    /// Target connection epoch, not a globally unique or persistent boot ID.
    pub session: u32,
    /// Applied topology revision within this engine session.
    pub revision: u32,
    /// First frame of the accepted audio block that introduced this revision.
    pub first_frame: u64,
    /// Native process descriptions.
    pub nodes: Vec<Node>,
    /// Exact active signal program, including its bytecode version.
    pub program: Vec<u8>,
    /// Active signal buses bound to physical outputs, in output order.
    pub outputs: Vec<u8>,
}

impl Graph {
    /// Find a node by its exact, case-sensitive alias.
    #[must_use]
    pub fn node(&self, alias: &str) -> Option<&Node> {
        self.nodes.iter().find(|node| node.alias == alias)
    }

    /// Reconstruct signal connections from the program and node port layouts.
    ///
    /// Message ports retain their local indices even though bytecode signal
    /// operands omit them. Built-in gain/mix operations have `@gainN`/`@mixN`
    /// labels; `N` is their instruction ordinal, independent of native IDs.
    ///
    /// # Errors
    /// Rejects unknown versions, duplicate IDs/aliases/calls, missing nodes,
    /// invalid port layouts, forward bus references and invalid output bindings.
    pub fn connections(&self) -> io::Result<Vec<Connection>> {
        for (i, node) in self.nodes.iter().enumerate() {
            if self.nodes[..i]
                .iter()
                .any(|other| other.id == node.id || other.alias == node.alias)
            {
                return Err(invalid("duplicate graph node ID or alias"));
            }
        }
        let Some((&VERSION, mut code)) = self.program.split_first() else {
            return Err(invalid("unsupported or missing signal bytecode version"));
        };
        let mut buses = Vec::<String>::new();
        let mut edges = Vec::new();
        let mut called = [false; 256];
        let mut instruction = 0usize;
        while !code.is_empty() {
            let (op, rest) = Op::decode(code).map_err(|_| invalid("invalid signal bytecode"))?;
            code = rest;
            match op {
                Op::Call {
                    object,
                    inputs,
                    outputs,
                } => {
                    if core::mem::replace(&mut called[usize::from(object)], true) {
                        return Err(invalid("process appears twice in the signal program"));
                    }
                    let node = self
                        .nodes
                        .iter()
                        .find(|node| node.id == object)
                        .ok_or_else(|| invalid("signal program references an unknown process"))?;
                    let inlet_count = node
                        .inlets
                        .iter()
                        .filter(|kind| **kind == PortKind::Signal)
                        .count();
                    let outlet_count = node
                        .outlets
                        .iter()
                        .filter(|kind| **kind == PortKind::Signal)
                        .count();
                    if inlet_count != inputs.len() || outlet_count != usize::from(outputs) {
                        return Err(invalid("signal program does not match process ports"));
                    }
                    let inlets = node
                        .inlets
                        .iter()
                        .enumerate()
                        .filter(|(_, kind)| **kind == PortKind::Signal);
                    for ((port, _), bus) in inlets.zip(inputs) {
                        edges.push(Connection {
                            source: source(&buses, *bus)?.into(),
                            destination: format!("{}.in{port}", node.alias),
                        });
                    }
                    for (port, _) in node
                        .outlets
                        .iter()
                        .enumerate()
                        .filter(|(_, kind)| **kind == PortKind::Signal)
                    {
                        buses.push(format!("{}.out{port}", node.alias));
                    }
                }
                Op::Gain { input, level } => {
                    let alias = format!("@gain{instruction}({level}/128)");
                    edges.push(Connection {
                        source: source(&buses, input)?.into(),
                        destination: format!("{alias}.in0"),
                    });
                    buses.push(format!("{alias}.out0"));
                }
                Op::Mix { left, right } => {
                    let alias = format!("@mix{instruction}");
                    for (port, bus) in [left, right].into_iter().enumerate() {
                        edges.push(Connection {
                            source: source(&buses, bus)?.into(),
                            destination: format!("{alias}.in{port}"),
                        });
                    }
                    buses.push(format!("{alias}.out0"));
                }
            }
            if buses.len() > 256 {
                return Err(invalid("signal program exceeds 256 buses"));
            }
            instruction = instruction.saturating_add(1);
        }
        for (index, bus) in self.outputs.iter().enumerate() {
            edges.push(Connection {
                source: source(&buses, *bus)?.into(),
                destination: format!("output{index}"),
            });
        }
        Ok(edges)
    }
}

fn source(buses: &[String], bus: u8) -> io::Result<&str> {
    buses
        .get(usize::from(bus))
        .map(String::as_str)
        .ok_or_else(|| invalid("signal references an unavailable bus"))
}

pub(crate) fn invalid(message: &'static str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, message)
}