MIDI recording

This commit is contained in:
Skyler Lehmkuhl
2025-10-29 01:50:45 -04:00
parent 6e7e90fe57
commit dc32fc4200
19 changed files with 1470 additions and 132 deletions
@@ -791,17 +791,20 @@ impl InstrumentGraph {
"NoiseGenerator" => Box::new(NoiseGeneratorNode::new("Noise")),
"Splitter" => Box::new(SplitterNode::new("Splitter")),
"Pan" => Box::new(PanNode::new("Pan")),
"Quantizer" => Box::new(QuantizerNode::new("Quantizer")),
"Delay" => Box::new(DelayNode::new("Delay")),
"Distortion" => Box::new(DistortionNode::new("Distortion")),
"Reverb" => Box::new(ReverbNode::new("Reverb")),
"Chorus" => Box::new(ChorusNode::new("Chorus")),
"Compressor" => Box::new(CompressorNode::new("Compressor")),
"Limiter" => Box::new(LimiterNode::new("Limiter")),
"Math" => Box::new(MathNode::new("Math")),
"EQ" => Box::new(EQNode::new("EQ")),
"Flanger" => Box::new(FlangerNode::new("Flanger")),
"FMSynth" => Box::new(FMSynthNode::new("FM Synth")),
"WavetableOscillator" => Box::new(WavetableOscillatorNode::new("Wavetable")),
"SimpleSampler" => Box::new(SimpleSamplerNode::new("Sampler")),
"SlewLimiter" => Box::new(SlewLimiterNode::new("Slew Limiter")),
"MultiSampler" => Box::new(MultiSamplerNode::new("Multi Sampler")),
"MidiInput" => Box::new(MidiInputNode::new("MIDI Input")),
"MidiToCV" => Box::new(MidiToCVNode::new("MIDI→CV")),
@@ -0,0 +1,178 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_OPERATION: u32 = 0;
const PARAM_OPERAND: u32 = 1;
/// Mathematical and logical operations on CV signals
/// Operations:
/// 0 = Add, 1 = Subtract, 2 = Multiply, 3 = Divide
/// 4 = Min, 5 = Max, 6 = Average
/// 7 = Invert (1.0 - x), 8 = Absolute Value
/// 9 = Clamp (0.0 to 1.0), 10 = Wrap (-1.0 to 1.0)
/// 11 = Greater Than, 12 = Less Than, 13 = Equal (with tolerance)
pub struct MathNode {
name: String,
operation: u32,
operand: f32,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl MathNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("CV In A", SignalType::CV, 0),
NodePort::new("CV In B", SignalType::CV, 1),
];
let outputs = vec![
NodePort::new("CV Out", SignalType::CV, 0),
];
let parameters = vec![
Parameter::new(PARAM_OPERATION, "Operation", 0.0, 13.0, 0.0, ParameterUnit::Generic),
Parameter::new(PARAM_OPERAND, "Operand", -10.0, 10.0, 1.0, ParameterUnit::Generic),
];
Self {
name,
operation: 0,
operand: 1.0,
inputs,
outputs,
parameters,
}
}
fn apply_operation(&self, a: f32, b: f32) -> f32 {
match self.operation {
0 => a + b, // Add
1 => a - b, // Subtract
2 => a * b, // Multiply
3 => if b.abs() > 0.0001 { a / b } else { 0.0 }, // Divide (with protection)
4 => a.min(b), // Min
5 => a.max(b), // Max
6 => (a + b) * 0.5, // Average
7 => 1.0 - a, // Invert (ignores b)
8 => a.abs(), // Absolute Value (ignores b)
9 => a.clamp(0.0, 1.0), // Clamp to 0-1 (ignores b)
10 => { // Wrap -1 to 1
let mut result = a;
while result > 1.0 {
result -= 2.0;
}
while result < -1.0 {
result += 2.0;
}
result
},
11 => if a > b { 1.0 } else { 0.0 }, // Greater Than
12 => if a < b { 1.0 } else { 0.0 }, // Less Than
13 => if (a - b).abs() < 0.01 { 1.0 } else { 0.0 }, // Equal (with tolerance)
_ => a, // Unknown operation - pass through
}
}
}
impl AudioNode for MathNode {
fn category(&self) -> NodeCategory {
NodeCategory::Utility
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_OPERATION => self.operation = (value as u32).clamp(0, 13),
PARAM_OPERAND => self.operand = value.clamp(-10.0, 10.0),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_OPERATION => self.operation as f32,
PARAM_OPERAND => self.operand,
_ => 0.0,
}
}
fn process(
&mut self,
inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
_midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
_sample_rate: u32,
) {
if outputs.is_empty() {
return;
}
let output = &mut outputs[0];
let length = output.len();
// Get input A (or use 0.0)
let input_a = if !inputs.is_empty() && !inputs[0].is_empty() {
inputs[0]
} else {
&[]
};
// Get input B (or use operand parameter)
let input_b = if inputs.len() > 1 && !inputs[1].is_empty() {
inputs[1]
} else {
&[]
};
// Process each sample
for i in 0..length {
let a = if i < input_a.len() { input_a[i] } else { 0.0 };
let b = if i < input_b.len() {
input_b[i]
} else {
self.operand
};
output[i] = self.apply_operation(a, b);
}
}
fn reset(&mut self) {
// No state to reset
}
fn node_type(&self) -> &str {
"Math"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
operation: self.operation,
operand: self.operand,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -11,6 +11,7 @@ mod limiter;
mod fm_synth;
mod gain;
mod lfo;
mod math;
mod midi_input;
mod midi_to_cv;
mod mixer;
@@ -20,8 +21,10 @@ mod oscillator;
mod oscilloscope;
mod output;
mod pan;
mod quantizer;
mod reverb;
mod simple_sampler;
mod slew_limiter;
mod splitter;
mod template_io;
mod voice_allocator;
@@ -40,6 +43,7 @@ pub use limiter::LimiterNode;
pub use fm_synth::FMSynthNode;
pub use gain::GainNode;
pub use lfo::LFONode;
pub use math::MathNode;
pub use midi_input::MidiInputNode;
pub use midi_to_cv::MidiToCVNode;
pub use mixer::MixerNode;
@@ -49,8 +53,10 @@ pub use oscillator::OscillatorNode;
pub use oscilloscope::OscilloscopeNode;
pub use output::AudioOutputNode;
pub use pan::PanNode;
pub use quantizer::QuantizerNode;
pub use reverb::ReverbNode;
pub use simple_sampler::SimpleSamplerNode;
pub use slew_limiter::SlewLimiterNode;
pub use splitter::SplitterNode;
pub use template_io::{TemplateInputNode, TemplateOutputNode};
pub use voice_allocator::VoiceAllocatorNode;
@@ -0,0 +1,220 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_SCALE: u32 = 0;
const PARAM_ROOT_NOTE: u32 = 1;
/// Quantizer - snaps CV values to musical scales
/// Converts continuous CV into discrete pitch values based on a scale
/// Scale parameter:
/// 0 = Chromatic (all 12 notes)
/// 1 = Major scale
/// 2 = Minor scale (natural)
/// 3 = Pentatonic major
/// 4 = Pentatonic minor
/// 5 = Dorian
/// 6 = Phrygian
/// 7 = Lydian
/// 8 = Mixolydian
/// 9 = Whole tone
/// 10 = Octaves only
pub struct QuantizerNode {
name: String,
scale: u32,
root_note: u32, // 0-11 (C-B)
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl QuantizerNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("CV In", SignalType::CV, 0),
];
let outputs = vec![
NodePort::new("CV Out", SignalType::CV, 0),
NodePort::new("Gate Out", SignalType::CV, 1), // Trigger when note changes
];
let parameters = vec![
Parameter::new(PARAM_SCALE, "Scale", 0.0, 10.0, 0.0, ParameterUnit::Generic),
Parameter::new(PARAM_ROOT_NOTE, "Root", 0.0, 11.0, 0.0, ParameterUnit::Generic),
];
Self {
name,
scale: 0,
root_note: 0,
inputs,
outputs,
parameters,
}
}
/// Get the scale intervals (semitones from root)
fn get_scale_intervals(&self) -> Vec<u32> {
match self.scale {
0 => vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], // Chromatic
1 => vec![0, 2, 4, 5, 7, 9, 11], // Major
2 => vec![0, 2, 3, 5, 7, 8, 10], // Minor (natural)
3 => vec![0, 2, 4, 7, 9], // Pentatonic major
4 => vec![0, 3, 5, 7, 10], // Pentatonic minor
5 => vec![0, 2, 3, 5, 7, 9, 10], // Dorian
6 => vec![0, 1, 3, 5, 7, 8, 10], // Phrygian
7 => vec![0, 2, 4, 6, 7, 9, 11], // Lydian
8 => vec![0, 2, 4, 5, 7, 9, 10], // Mixolydian
9 => vec![0, 2, 4, 6, 8, 10], // Whole tone
10 => vec![0], // Octaves only
_ => vec![0, 2, 4, 5, 7, 9, 11], // Default to major
}
}
/// Quantize a CV value to the nearest note in the scale
fn quantize(&self, cv: f32) -> f32 {
// Convert V/Oct to MIDI note (standard: 0V = A4 = MIDI 69)
// cv = (midi_note - 69) / 12.0
// midi_note = cv * 12.0 + 69
let input_midi_note = cv * 12.0 + 69.0;
// Clamp to reasonable range
let input_midi_note = input_midi_note.clamp(0.0, 127.0);
// Get scale intervals
let intervals = self.get_scale_intervals();
// Find which octave we're in (relative to C)
let octave = (input_midi_note / 12.0).floor() as i32;
let note_in_octave = (input_midi_note % 12.0) as u32;
// Find the nearest note in the scale
let mut closest_interval = intervals[0];
let mut min_distance = (note_in_octave as i32 - closest_interval as i32).abs();
for &interval in &intervals {
let distance = (note_in_octave as i32 - interval as i32).abs();
if distance < min_distance {
min_distance = distance;
closest_interval = interval;
}
}
// Calculate final MIDI note (adjusted for root note)
// Start from the octave * 12, add root note, add scale interval
let quantized_midi_note = (octave * 12) as f32 + self.root_note as f32 + closest_interval as f32;
// Clamp result
let quantized_midi_note = quantized_midi_note.clamp(0.0, 127.0);
// Convert back to V/Oct: voct = (midi_note - 69) / 12.0
(quantized_midi_note - 69.0) / 12.0
}
}
impl AudioNode for QuantizerNode {
fn category(&self) -> NodeCategory {
NodeCategory::Utility
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_SCALE => self.scale = (value as u32).clamp(0, 10),
PARAM_ROOT_NOTE => self.root_note = (value as u32).clamp(0, 11),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_SCALE => self.scale as f32,
PARAM_ROOT_NOTE => self.root_note as f32,
_ => 0.0,
}
}
fn process(
&mut self,
inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
_midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
_sample_rate: u32,
) {
if inputs.is_empty() || outputs.is_empty() {
return;
}
let input = inputs[0];
let length = input.len().min(outputs[0].len());
// Split outputs to avoid borrow conflicts
if outputs.len() > 1 {
let (cv_out, gate_out) = outputs.split_at_mut(1);
let cv_output = &mut cv_out[0];
let gate_output = &mut gate_out[0];
let gate_length = length.min(gate_output.len());
let mut last_note: Option<f32> = None;
for i in 0..length {
let quantized = self.quantize(input[i]);
cv_output[i] = quantized;
// Generate gate trigger when note changes
if i < gate_length {
if let Some(prev) = last_note {
gate_output[i] = if (quantized - prev).abs() > 0.001 { 1.0 } else { 0.0 };
} else {
gate_output[i] = 1.0; // First note triggers gate
}
}
last_note = Some(quantized);
}
} else {
// No gate output, just quantize CV
let cv_output = &mut outputs[0];
for i in 0..length {
cv_output[i] = self.quantize(input[i]);
}
}
}
fn reset(&mut self) {
// No state to reset
}
fn node_type(&self) -> &str {
"Quantizer"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
scale: self.scale,
root_note: self.root_note,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,156 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_RISE_TIME: u32 = 0;
const PARAM_FALL_TIME: u32 = 1;
/// Slew limiter - limits the rate of change of a CV signal
/// Useful for creating portamento/glide effects and smoothing control signals
pub struct SlewLimiterNode {
name: String,
rise_time: f32, // Time in seconds to rise from 0 to 1
fall_time: f32, // Time in seconds to fall from 1 to 0
last_value: f32,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl SlewLimiterNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("CV In", SignalType::CV, 0),
];
let outputs = vec![
NodePort::new("CV Out", SignalType::CV, 0),
];
let parameters = vec![
Parameter::new(PARAM_RISE_TIME, "Rise Time", 0.0, 5.0, 0.01, ParameterUnit::Time),
Parameter::new(PARAM_FALL_TIME, "Fall Time", 0.0, 5.0, 0.01, ParameterUnit::Time),
];
Self {
name,
rise_time: 0.01,
fall_time: 0.01,
last_value: 0.0,
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for SlewLimiterNode {
fn category(&self) -> NodeCategory {
NodeCategory::Utility
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_RISE_TIME => self.rise_time = value.clamp(0.0, 5.0),
PARAM_FALL_TIME => self.fall_time = value.clamp(0.0, 5.0),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_RISE_TIME => self.rise_time,
PARAM_FALL_TIME => self.fall_time,
_ => 0.0,
}
}
fn process(
&mut self,
inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
_midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
sample_rate: u32,
) {
if inputs.is_empty() || outputs.is_empty() {
return;
}
let input = inputs[0];
let output = &mut outputs[0];
let length = input.len().min(output.len());
// Calculate maximum change per sample
let sample_duration = 1.0 / sample_rate as f32;
// Rise/fall rates (units per second)
let rise_rate = if self.rise_time > 0.0001 {
1.0 / self.rise_time
} else {
f32::MAX // No limiting
};
let fall_rate = if self.fall_time > 0.0001 {
1.0 / self.fall_time
} else {
f32::MAX // No limiting
};
for i in 0..length {
let target = input[i];
let difference = target - self.last_value;
let max_change = if difference > 0.0 {
// Rising
rise_rate * sample_duration
} else {
// Falling
fall_rate * sample_duration
};
// Limit the change
let limited_difference = difference.clamp(-max_change, max_change);
self.last_value += limited_difference;
output[i] = self.last_value;
}
}
fn reset(&mut self) {
self.last_value = 0.0;
}
fn node_type(&self) -> &str {
"SlewLimiter"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
rise_time: self.rise_time,
fall_time: self.fall_time,
last_value: self.last_value,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}