wavegraph 0.1.1

Run text patches as a remotely controlled WaveGraph audio engine
//! One looping, sixteenth-note pattern belonging to an instrument instance.

use wavegraph_compiler::Node;
use wavegraph_core::midi::{MidiMessage, Note};

#[derive(Debug, Default)]
pub(crate) struct Sequence {
    steps: Vec<Vec<Note>>,
    gated: bool,
}

impl Sequence {
    pub(crate) fn from_node(node: &Node) -> Result<Self, String> {
        let Some((_, text)) = node.options.iter().find(|(k, _)| k == "steps") else {
            return Ok(Self::default());
        };
        Self::parse(&node.kind, text)
    }

    fn parse(kind: &str, text: &str) -> Result<Self, String> {
        let gated = kind == "tb303";
        let mut steps = Vec::new();
        for (step, token) in (1..).zip(text.split(',')) {
            if step > 64 {
                return Err("a pattern holds up to 64 sixteenths".into());
            }
            let mut notes = Vec::new();
            if token != "-" {
                for pitch in token.split('+') {
                    let (digits, velocity) =
                        pitch.strip_suffix('!').map_or((pitch, 88), |n| (n, 116));
                    let number: u8 = digits
                        .parse()
                        .ok()
                        .filter(|n: &u8| *n < 128)
                        .ok_or_else(|| format!("invalid note '{pitch}' at step {step}"))?;
                    let mapped = match kind {
                        "tb303" => notes.is_empty(),
                        "tr808" => wavegraph_808::Voice::from_midi_note(number).is_some(),
                        "tr909" => wavegraph_909::Voice::from_midi_note(number).is_some(),
                        _ => false,
                    };
                    if !mapped {
                        return Err(format!("{kind} cannot play '{token}' at step {step}"));
                    }
                    if notes.len() >= 6 || notes.iter().any(|n: &Note| n.number == number) {
                        return Err(format!("too many or repeated hits at step {step}"));
                    }
                    notes.push(Note { number, velocity });
                }
            }
            steps.push(notes);
        }
        Ok(Self { steps, gated })
    }

    #[allow(
        clippy::cast_possible_truncation,
        clippy::arithmetic_side_effects,
        reason = "Modulo the non-empty pattern length bounds the result to a valid usize index."
    )]
    fn at(&self, step: u64) -> &[Note] {
        if self.steps.is_empty() {
            return &[];
        }
        let index = (step % self.steps.len() as u64) as usize;
        &self.steps[index]
    }

    pub(crate) fn step(&self, step: u64, mut emit: impl FnMut(MidiMessage)) {
        for &note in self.at(step) {
            emit(MidiMessage::On(note));
        }
    }

    /// 50% gate time for bass. Drum envelopes and samples run until they decay or choke.
    pub(crate) fn release(&self, step: u64, mut emit: impl FnMut(MidiMessage)) {
        if self.gated {
            for &note in self.at(step) {
                emit(MidiMessage::Off(note.number));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_bass_pattern_loops_with_rests_accents_and_note_offs() {
        let sequence = Sequence::parse("tb303", "38!,45,-").expect("valid sequence");
        let mut messages = Vec::new();
        for step in 0..4 {
            sequence.step(step, |m| messages.push(m));
            sequence.release(step, |m| messages.push(m));
        }
        let first = MidiMessage::On(Note {
            number: 38,
            velocity: 116,
        });
        assert_eq!(
            messages,
            [
                first,
                MidiMessage::Off(38),
                MidiMessage::On(Note {
                    number: 45,
                    velocity: 88
                }),
                MidiMessage::Off(45),
                first,
                MidiMessage::Off(38)
            ]
        );
    }

    #[test]
    fn drum_chords_use_the_kits_midi_map() {
        let sequence = Sequence::parse("tr909", "36+42!,39").expect("valid sequence");
        let mut hits = Vec::new();
        sequence.step(0, |m| hits.push(m));
        sequence.release(0, |m| hits.push(m));
        assert_eq!(hits.len(), 2);
        assert!(Sequence::parse("tr808", "39").is_err());
        assert!(Sequence::parse("tb303", "45+48").is_err());
        assert!(Sequence::parse("tr909", "36+36").is_err());
        assert!(Sequence::parse("tb303", "-,,36").is_err());
    }
}