wavegraph-remote 0.1.1

MIDI control and live graph discovery for WaveGraph
Documentation
use core::fmt;
use std::io;
use wavegraph_core::midi::{MidiMessage, Note};

/// A validated, human-numbered MIDI channel (1 through 16).
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Channel(u8);

impl Channel {
    /// Validate a one-based channel number.
    ///
    /// # Errors
    /// Returns `InvalidInput` for a number outside 1 through 16.
    pub fn new(number: u8) -> io::Result<Self> {
        if (1..=16).contains(&number) {
            Ok(Self(number))
        } else {
            Err(invalid("MIDI channel must be between 1 and 16"))
        }
    }

    /// Human-facing channel number, from 1 through 16.
    #[must_use]
    pub const fn number(self) -> u8 {
        self.0
    }

    /// Zero-based MIDI wire channel, from 0 through 15.
    #[must_use]
    pub const fn index(self) -> u8 {
        self.0.saturating_sub(1)
    }
}

impl fmt::Display for Channel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Musical commands sent as ordinary MIDI, independently of graph discovery.
///
/// Sending confirms submission to the transport, not application by the DSP.
/// Receivers decide which channels and controllers they support.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MidiCommand {
    /// MIDI Start: start or restart the sequencer.
    Play,
    /// MIDI Stop: stop the sequencer.
    Stop,
    /// Strike a note with nonzero velocity.
    NoteOn {
        /// Destination channel.
        channel: Channel,
        /// Note number, 0 through 127.
        note: u8,
        /// Strike velocity, 1 through 127.
        velocity: u8,
    },
    /// Release a previously struck note.
    NoteOff {
        /// Destination channel.
        channel: Channel,
        /// Note number, 0 through 127.
        note: u8,
    },
    /// Set a MIDI controller, including channel-mode controllers.
    ControlChange {
        /// Destination channel.
        channel: Channel,
        /// Controller number, 0 through 127.
        controller: u8,
        /// Controller value, 0 through 127.
        value: u8,
    },
    /// Send All Notes Off (CC123) on one channel.
    AllNotesOff {
        /// Destination channel.
        channel: Channel,
    },
}

impl MidiCommand {
    /// Decode a complete performance message, normalizing zero-velocity notes.
    #[must_use]
    pub fn decode(bytes: &[u8]) -> Option<Self> {
        match bytes {
            [0xfa] => Some(Self::Play),
            [0xfc] => Some(Self::Stop),
            &[status, key, value] => {
                let channel = Channel((status & 0x0f).saturating_add(1));
                Some(match MidiMessage::decode([status, key, value])? {
                    MidiMessage::On(note) => Self::NoteOn {
                        channel,
                        note: note.number,
                        velocity: note.velocity,
                    },
                    MidiMessage::Off(note) => Self::NoteOff { channel, note },
                    MidiMessage::Control(123, _) => Self::AllNotesOff { channel },
                    MidiMessage::Control(controller, value) => Self::ControlChange {
                        channel,
                        controller,
                        value,
                    },
                })
            }
            _ => None,
        }
    }

    pub(crate) fn encode(self, bytes: &mut [u8; 3]) -> io::Result<usize> {
        let (channel, message) = match self {
            Self::Play => {
                bytes[0] = 0xfa;
                return Ok(1);
            }
            Self::Stop => {
                bytes[0] = 0xfc;
                return Ok(1);
            }
            Self::NoteOn {
                channel,
                note,
                velocity,
            } => (
                channel,
                MidiMessage::On(Note {
                    number: note,
                    velocity,
                }),
            ),
            Self::NoteOff { channel, note } => (channel, MidiMessage::Off(note)),
            Self::ControlChange {
                channel,
                controller,
                value,
            } => (channel, MidiMessage::Control(controller, value)),
            Self::AllNotesOff { channel } => (channel, MidiMessage::Control(123, 0)),
        };
        *bytes = message.encode(channel.index()).ok_or_else(|| {
            invalid("MIDI data must fit seven bits; note-on velocity must be nonzero")
        })?;
        Ok(3)
    }
}

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