Add pitch bend support

This commit is contained in:
Skyler Lehmkuhl
2026-03-18 23:11:24 -04:00
parent 4f3da810d0
commit 6b6ae230a1
14 changed files with 891 additions and 199 deletions
+66
View File
@@ -992,6 +992,13 @@ impl Engine {
clip.events.sort_by(|a, b| a.timestamp.partial_cmp(&b.timestamp).unwrap());
}
}
Command::UpdateMidiClipEvents(_track_id, clip_id, events) => {
// Replace all events in a MIDI clip (used for CC/pitch bend editing)
if let Some(clip) = self.project.midi_clip_pool.get_clip_mut(clip_id) {
clip.events = events;
clip.events.sort_by(|a, b| a.timestamp.partial_cmp(&b.timestamp).unwrap());
}
}
Command::RemoveMidiClip(track_id, instance_id) => {
// Remove a MIDI clip instance from a track (for undo/redo support)
let _ = self.project.remove_midi_clip(track_id, instance_id);
@@ -2818,6 +2825,40 @@ impl Engine {
};
QueryResponse::GraphIsDefault(is_default)
}
Query::GetPitchBendRange(track_id) => {
use crate::audio::node_graph::nodes::{MidiToCVNode, MultiSamplerNode, VoiceAllocatorNode};
use crate::audio::node_graph::AudioNode;
let range = if let Some(TrackNode::Midi(track)) = self.project.get_track(track_id) {
let graph = &track.instrument_graph;
let mut found = None;
for idx in graph.node_indices() {
if let Some(gn) = graph.get_graph_node(idx) {
if let Some(ms) = gn.node.as_any().downcast_ref::<MultiSamplerNode>() {
found = Some(ms.get_parameter(4)); // PARAM_PITCH_BEND_RANGE
break;
}
// Search inside VoiceAllocator template for MidiToCV
if let Some(va) = gn.node.as_any().downcast_ref::<VoiceAllocatorNode>() {
let tg = va.template_graph();
for tidx in tg.node_indices() {
if let Some(tgn) = tg.get_graph_node(tidx) {
if let Some(mc) = tgn.node.as_any().downcast_ref::<MidiToCVNode>() {
found = Some(mc.get_parameter(0)); // PARAM_PITCH_BEND_RANGE
break;
}
}
}
if found.is_some() { break; }
}
}
}
found.unwrap_or(2.0)
} else {
2.0
};
QueryResponse::PitchBendRange(range)
}
};
// Send response back
@@ -3412,6 +3453,11 @@ impl EngineController {
let _ = self.command_tx.push(Command::UpdateMidiClipNotes(track_id, clip_id, notes));
}
/// Replace all events in a MIDI clip (used for CC/pitch bend editing from the piano roll)
pub fn update_midi_clip_events(&mut self, track_id: TrackId, clip_id: MidiClipId, events: Vec<crate::audio::midi::MidiEvent>) {
let _ = self.command_tx.push(Command::UpdateMidiClipEvents(track_id, clip_id, events));
}
/// Remove a MIDI clip instance from a track (for undo/redo support)
pub fn remove_midi_clip(&mut self, track_id: TrackId, instance_id: MidiClipInstanceId) {
let _ = self.command_tx.push(Command::RemoveMidiClip(track_id, instance_id));
@@ -3952,6 +3998,26 @@ impl EngineController {
Err("Query timeout".to_string())
}
/// Query the pitch bend range (semitones) for the instrument on a MIDI track.
/// Returns 2.0 (default) if the track or instrument cannot be found.
pub fn query_pitch_bend_range(&mut self, track_id: TrackId) -> f32 {
if let Err(_) = self.query_tx.push(Query::GetPitchBendRange(track_id)) {
return 2.0;
}
let start = std::time::Instant::now();
let timeout = std::time::Duration::from_millis(100);
while start.elapsed() < timeout {
if let Ok(QueryResponse::PitchBendRange(range)) = self.query_response_rx.pop() {
return range;
}
std::thread::sleep(std::time::Duration::from_micros(50));
}
2.0 // default on timeout
}
/// Serialize the audio pool for project saving
pub fn serialize_audio_pool(&mut self, project_path: &std::path::Path) -> Result<Vec<crate::audio::pool::AudioPoolEntry>, String> {
// Send query
@@ -1,14 +1,19 @@
use crate::audio::midi::MidiEvent;
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
const PARAM_PITCH_BEND_RANGE: u32 = 0;
/// MIDI to CV converter
/// Converts MIDI note events to control voltage signals
pub struct MidiToCVNode {
name: String,
note: u8, // Current MIDI note number
gate: f32, // Gate CV (1.0 when note on, 0.0 when off)
velocity: f32, // Velocity CV (0.0-1.0)
pitch_cv: f32, // Pitch CV (V/Oct: 0V = A4, ±1V per octave)
note: u8, // Current MIDI note number
gate: f32, // Gate CV (1.0 when note on, 0.0 when off)
velocity: f32, // Velocity CV (0.0-1.0)
pitch_cv: f32, // Pitch CV (V/Oct: 0V = A4, ±1V per octave), without bend
pitch_bend_range: f32, // Pitch bend range in semitones (default 2.0)
current_bend: f32, // Current pitch bend, normalised -1.0..=1.0 (0 = centre)
current_mod: f32, // Current modulation (CC1), 0.0..=1.0
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
@@ -18,26 +23,41 @@ impl MidiToCVNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
// MIDI input port for receiving MIDI through graph connections
let inputs = vec![
NodePort::new("MIDI In", SignalType::Midi, 0),
NodePort::new("Bend CV", SignalType::CV, 0), // External pitch bend in semitones
NodePort::new("Mod CV", SignalType::CV, 1), // External modulation 0.0..=1.0
];
let outputs = vec![
NodePort::new("V/Oct", SignalType::CV, 0), // V/Oct: 0V = A4, ±1V per octave
NodePort::new("V/Oct", SignalType::CV, 0), // V/Oct: 0V = A4, ±1V per octave (with bend applied)
NodePort::new("Gate", SignalType::CV, 1), // 1.0 = on, 0.0 = off
NodePort::new("Velocity", SignalType::CV, 2), // 0.0-1.0
NodePort::new("Bend", SignalType::CV, 3), // Total pitch bend in semitones (MIDI + CV)
NodePort::new("Mod", SignalType::CV, 4), // Total modulation 0.0..=1.0 (MIDI CC1 + CV)
];
let parameters = vec![
Parameter::new(
PARAM_PITCH_BEND_RANGE,
"Pitch Bend Range",
0.0, 48.0, 2.0,
ParameterUnit::Generic,
),
];
Self {
name,
note: 60, // Middle C
note: 60,
gate: 0.0,
velocity: 0.0,
pitch_cv: Self::midi_note_to_voct(60),
pitch_bend_range: 2.0,
current_bend: 0.0,
current_mod: 0.0,
inputs,
outputs,
parameters: vec![], // No user parameters
parameters,
}
}
@@ -48,6 +68,37 @@ impl MidiToCVNode {
// Standard V/Oct: 0V at A4, 1V per octave (12 semitones)
(note as f32 - 69.0) / 12.0
}
fn apply_midi_event(&mut self, event: &MidiEvent) {
let status = event.status & 0xF0;
match status {
0x90 if event.data2 > 0 => {
// Note on — reset per-note expression so previous note's bend doesn't bleed in
self.note = event.data1;
self.pitch_cv = Self::midi_note_to_voct(self.note);
self.velocity = event.data2 as f32 / 127.0;
self.gate = 1.0;
self.current_bend = 0.0;
self.current_mod = 0.0;
}
0x80 | 0x90 => {
// Note off (or note on with velocity 0)
if event.data1 == self.note {
self.gate = 0.0;
}
}
0xE0 => {
// Pitch bend: 14-bit value, center = 8192
let bend_raw = ((event.data2 as i16) << 7) | (event.data1 as i16);
self.current_bend = (bend_raw - 8192) as f32 / 8192.0;
}
0xB0 if event.data1 == 1 => {
// CC1 (modulation wheel)
self.current_mod = event.data2 as f32 / 127.0;
}
_ => {}
}
}
}
impl AudioNode for MidiToCVNode {
@@ -67,46 +118,27 @@ impl AudioNode for MidiToCVNode {
&self.parameters
}
fn set_parameter(&mut self, _id: u32, _value: f32) {
// No parameters
fn set_parameter(&mut self, id: u32, value: f32) {
if id == PARAM_PITCH_BEND_RANGE {
self.pitch_bend_range = value.clamp(0.0, 48.0);
}
}
fn get_parameter(&self, _id: u32) -> f32 {
0.0
fn get_parameter(&self, id: u32) -> f32 {
if id == PARAM_PITCH_BEND_RANGE {
self.pitch_bend_range
} else {
0.0
}
}
fn handle_midi(&mut self, event: &MidiEvent) {
let status = event.status & 0xF0;
match status {
0x90 => {
// Note on
if event.data2 > 0 {
// Velocity > 0 means note on
self.note = event.data1;
self.pitch_cv = Self::midi_note_to_voct(self.note);
self.velocity = event.data2 as f32 / 127.0;
self.gate = 1.0;
} else {
// Velocity = 0 means note off
if event.data1 == self.note {
self.gate = 0.0;
}
}
}
0x80 => {
// Note off
if event.data1 == self.note {
self.gate = 0.0;
}
}
_ => {}
}
self.apply_midi_event(event);
}
fn process(
&mut self,
_inputs: &[&[f32]],
inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
@@ -115,52 +147,56 @@ impl AudioNode for MidiToCVNode {
// Process MIDI events from input buffer
if !midi_inputs.is_empty() {
for event in midi_inputs[0] {
let status = event.status & 0xF0;
match status {
0x90 if event.data2 > 0 => {
// Note on
self.note = event.data1;
self.pitch_cv = Self::midi_note_to_voct(self.note);
self.velocity = event.data2 as f32 / 127.0;
self.gate = 1.0;
}
0x80 | 0x90 => {
// Note off (or note on with velocity 0)
if event.data1 == self.note {
self.gate = 0.0;
}
}
_ => {}
}
self.apply_midi_event(event);
}
}
if outputs.len() < 3 {
if outputs.len() < 5 {
return;
}
// CV signals are mono
// Use split_at_mut to get multiple mutable references
let (pitch_and_rest, rest) = outputs.split_at_mut(1);
let (gate_and_rest, velocity_slice) = rest.split_at_mut(1);
// Read CV inputs (use first sample of buffer). NaN = unconnected port → treat as 0.
let bend_cv = inputs.get(0).and_then(|b| b.first().copied())
.filter(|v| v.is_finite()).unwrap_or(0.0);
let mod_cv = inputs.get(1).and_then(|b| b.first().copied())
.filter(|v| v.is_finite()).unwrap_or(0.0);
let pitch_out = &mut pitch_and_rest[0];
let gate_out = &mut gate_and_rest[0];
let velocity_out = &mut velocity_slice[0];
// Total bend in semitones: MIDI bend + CV bend
let bend_semitones = self.current_bend * self.pitch_bend_range + bend_cv;
// Total mod: MIDI CC1 + CV mod, clamped to 0..1
let total_mod = (self.current_mod + mod_cv).clamp(0.0, 1.0);
// Pitch output includes bend
let pitch_out_val = self.pitch_cv + bend_semitones / 12.0;
// Use split_at_mut to get multiple mutable references
let (v0, rest) = outputs.split_at_mut(1);
let (v1, rest) = rest.split_at_mut(1);
let (v2, rest) = rest.split_at_mut(1);
let (v3, v4_slice) = rest.split_at_mut(1);
let pitch_out = &mut v0[0];
let gate_out = &mut v1[0];
let velocity_out = &mut v2[0];
let bend_out = &mut v3[0];
let mod_out = &mut v4_slice[0];
let frames = pitch_out.len();
// Output constant CV values for the entire buffer
for frame in 0..frames {
pitch_out[frame] = self.pitch_cv;
gate_out[frame] = self.gate;
pitch_out[frame] = pitch_out_val;
gate_out[frame] = self.gate;
velocity_out[frame] = self.velocity;
bend_out[frame] = bend_semitones;
mod_out[frame] = total_mod;
}
}
fn reset(&mut self) {
self.gate = 0.0;
self.velocity = 0.0;
self.current_bend = 0.0;
self.current_mod = 0.0;
}
fn node_type(&self) -> &str {
@@ -174,10 +210,13 @@ impl AudioNode for MidiToCVNode {
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
note: 60, // Reset to middle C
gate: 0.0, // Reset gate
velocity: 0.0, // Reset velocity
pitch_cv: Self::midi_note_to_voct(60), // Reset pitch
note: 60,
gate: 0.0,
velocity: 0.0,
pitch_cv: Self::midi_note_to_voct(60),
pitch_bend_range: self.pitch_bend_range,
current_bend: 0.0,
current_mod: 0.0,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
@@ -6,6 +6,7 @@ const PARAM_GAIN: u32 = 0;
const PARAM_ATTACK: u32 = 1;
const PARAM_RELEASE: u32 = 2;
const PARAM_TRANSPOSE: u32 = 3;
const PARAM_PITCH_BEND_RANGE: u32 = 4;
/// Loop playback mode
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
@@ -201,6 +202,7 @@ struct Voice {
layer_index: usize,
playhead: f32,
note: u8,
channel: u8, // MIDI channel this voice was activated on
velocity: u8,
is_active: bool,
@@ -221,11 +223,12 @@ enum EnvelopePhase {
}
impl Voice {
fn new(layer_index: usize, note: u8, velocity: u8) -> Self {
fn new(layer_index: usize, note: u8, channel: u8, velocity: u8) -> Self {
Self {
layer_index,
playhead: 0.0,
note,
channel,
velocity,
is_active: true,
envelope_phase: EnvelopePhase::Attack,
@@ -250,9 +253,14 @@ pub struct MultiSamplerNode {
// Parameters
gain: f32,
attack_time: f32, // seconds
release_time: f32, // seconds
transpose: i8, // semitones
attack_time: f32, // seconds
release_time: f32, // seconds
transpose: i8, // semitones
pitch_bend_range: f32, // semitones (default 2.0)
// Live MIDI state
bend_per_channel: [f32; 16], // Pitch bend per MIDI channel; ch0 = global broadcast
current_mod: f32, // MIDI CC1 modulation 0.0..=1.0
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
@@ -265,6 +273,8 @@ impl MultiSamplerNode {
let inputs = vec![
NodePort::new("MIDI In", SignalType::Midi, 0),
NodePort::new("Bend CV", SignalType::CV, 0), // External pitch bend in semitones
NodePort::new("Mod CV", SignalType::CV, 1), // External modulation 0.0..=1.0
];
let outputs = vec![
@@ -276,6 +286,7 @@ impl MultiSamplerNode {
Parameter::new(PARAM_ATTACK, "Attack", 0.001, 1.0, 0.01, ParameterUnit::Time),
Parameter::new(PARAM_RELEASE, "Release", 0.01, 5.0, 0.1, ParameterUnit::Time),
Parameter::new(PARAM_TRANSPOSE, "Transpose", -24.0, 24.0, 0.0, ParameterUnit::Generic),
Parameter::new(PARAM_PITCH_BEND_RANGE, "Pitch Bend Range", 0.0, 48.0, 2.0, ParameterUnit::Generic),
];
Self {
@@ -288,6 +299,9 @@ impl MultiSamplerNode {
attack_time: 0.01,
release_time: 0.1,
transpose: 0,
pitch_bend_range: 2.0,
bend_per_channel: [0.0; 16],
current_mod: 0.0,
inputs,
outputs,
parameters,
@@ -478,7 +492,9 @@ impl MultiSamplerNode {
}
/// Trigger a note
fn note_on(&mut self, note: u8, velocity: u8) {
fn note_on(&mut self, note: u8, channel: u8, velocity: u8) {
// Reset per-channel bend on note-on so a previous note's bend doesn't bleed in
self.bend_per_channel[channel as usize] = 0.0;
let transposed_note = (note as i16 + self.transpose as i16).clamp(0, 127) as u8;
if let Some(layer_index) = self.find_layer(transposed_note, velocity) {
@@ -496,7 +512,7 @@ impl MultiSamplerNode {
}
});
let voice = Voice::new(layer_index, note, velocity);
let voice = Voice::new(layer_index, note, channel, velocity);
if voice_index < self.voices.len() {
self.voices[voice_index] = voice;
@@ -547,6 +563,9 @@ impl AudioNode for MultiSamplerNode {
PARAM_TRANSPOSE => {
self.transpose = value.clamp(-24.0, 24.0) as i8;
}
PARAM_PITCH_BEND_RANGE => {
self.pitch_bend_range = value.clamp(0.0, 48.0);
}
_ => {}
}
}
@@ -557,13 +576,14 @@ impl AudioNode for MultiSamplerNode {
PARAM_ATTACK => self.attack_time,
PARAM_RELEASE => self.release_time,
PARAM_TRANSPOSE => self.transpose as f32,
PARAM_PITCH_BEND_RANGE => self.pitch_bend_range,
_ => 0.0,
}
}
fn process(
&mut self,
_inputs: &[&[f32]],
inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
@@ -582,14 +602,32 @@ impl AudioNode for MultiSamplerNode {
// Process MIDI events
if !midi_inputs.is_empty() {
for event in midi_inputs[0].iter() {
if event.is_note_on() {
self.note_on(event.data1, event.data2);
} else if event.is_note_off() {
self.note_off(event.data1);
let status = event.status & 0xF0;
match status {
_ if event.is_note_on() => self.note_on(event.data1, event.status & 0x0F, event.data2),
_ if event.is_note_off() => self.note_off(event.data1),
0xE0 => {
// Pitch bend: 14-bit value, center = 8192; stored per-channel
let bend_raw = ((event.data2 as i16) << 7) | (event.data1 as i16);
let ch = (event.status & 0x0F) as usize;
self.bend_per_channel[ch] = (bend_raw - 8192) as f32 / 8192.0;
}
0xB0 if event.data1 == 1 => {
// CC1 (modulation wheel)
self.current_mod = event.data2 as f32 / 127.0;
}
_ => {}
}
}
}
// Read CV inputs. NaN = unconnected port → treat as 0.
let bend_cv = inputs.get(0).and_then(|b| b.first().copied())
.filter(|v| v.is_finite()).unwrap_or(0.0);
// Global bend (channel 0) applies to all voices; per-channel bend is added per-voice below.
let global_bend_norm = self.bend_per_channel[0];
let bend_per_channel = self.bend_per_channel;
// Extract parameters needed for processing
let gain = self.gain;
let attack_time = self.attack_time;
@@ -607,9 +645,12 @@ impl AudioNode for MultiSamplerNode {
let layer = &self.layers[voice.layer_index];
// Calculate playback speed
// Calculate playback speed (includes pitch bend)
// Channel-0 = global; voice's own channel bend is added on top.
let voice_bend_norm = global_bend_norm + bend_per_channel[voice.channel as usize];
let total_bend_semitones = voice_bend_norm * self.pitch_bend_range + bend_cv;
let semitone_diff = voice.note as i16 - layer.root_key as i16;
let speed = 2.0_f32.powf(semitone_diff as f32 / 12.0);
let speed = 2.0_f32.powf((semitone_diff as f32 + total_bend_semitones) / 12.0);
let speed_adjusted = speed * (layer.sample_rate / sample_rate as f32);
for frame in 0..frames {
@@ -765,6 +806,8 @@ impl AudioNode for MultiSamplerNode {
fn reset(&mut self) {
self.voices.clear();
self.bend_per_channel = [0.0; 16];
self.current_mod = 0.0;
}
fn node_type(&self) -> &str {
@@ -11,6 +11,7 @@ struct VoiceState {
active: bool,
releasing: bool, // Note-off received, still processing (e.g. ADSR release)
note: u8,
note_channel: u8, // MIDI channel this voice was allocated on (0 = global/unset)
age: u32, // For voice stealing
pending_events: Vec<MidiEvent>, // MIDI events to send to this voice
}
@@ -21,6 +22,7 @@ impl VoiceState {
active: false,
releasing: false,
note: 0,
note_channel: 0,
age: 0,
pending_events: Vec::new(),
}
@@ -273,6 +275,7 @@ impl AudioNode for VoiceAllocatorNode {
self.voices[voice_idx].active = true;
self.voices[voice_idx].releasing = false;
self.voices[voice_idx].note = event.data1;
self.voices[voice_idx].note_channel = event.status & 0x0F;
self.voices[voice_idx].age = 0;
// Store MIDI event for this voice to process
@@ -295,10 +298,12 @@ impl AudioNode for VoiceAllocatorNode {
}
}
_ => {
// Other MIDI events (CC, pitch bend, etc.) - send to all active voices
// Route to matching-channel voices; channel 0 = global broadcast
let event_channel = event.status & 0x0F;
for voice_idx in 0..self.voice_count {
if self.voices[voice_idx].active {
self.voices[voice_idx].pending_events.push(*event);
let voice = &mut self.voices[voice_idx];
if voice.active && (event_channel == 0 || voice.note_channel == event_channel) {
voice.pending_events.push(*event);
}
}
}
+8
View File
@@ -2,6 +2,7 @@ use crate::audio::{
AudioClipInstanceId, AutomationLaneId, ClipId, CurveType, MidiClip, MidiClipId,
MidiClipInstanceId, ParameterId, TrackId,
};
use crate::audio::midi::MidiEvent;
use crate::audio::buffer_pool::BufferPoolStats;
use crate::audio::node_graph::nodes::LoopMode;
use crate::io::WaveformPeak;
@@ -85,6 +86,8 @@ pub enum Command {
/// Update MIDI clip notes (track_id, clip_id, notes: Vec<(start_time, note, velocity, duration)>)
/// NOTE: May need to switch to individual note operations if this becomes slow on clips with many notes
UpdateMidiClipNotes(TrackId, MidiClipId, Vec<(f64, u8, u8, f64)>),
/// Replace all events in a MIDI clip (track_id, clip_id, events). Used for CC/pitch bend editing.
UpdateMidiClipEvents(TrackId, MidiClipId, Vec<MidiEvent>),
/// Remove a MIDI clip instance from a track (track_id, instance_id) - for undo/redo support
RemoveMidiClip(TrackId, MidiClipInstanceId),
/// Remove an audio clip instance from a track (track_id, instance_id) - for undo/redo support
@@ -445,6 +448,9 @@ pub enum Query {
DuplicateMidiClipSync(MidiClipId),
/// Get whether a track's graph is still the auto-generated default
GetGraphIsDefault(TrackId),
/// Get the pitch bend range (in semitones) for the instrument on a MIDI track.
/// Searches for MidiToCVNode (in VA templates) or MultiSamplerNode (direct).
GetPitchBendRange(TrackId),
}
/// Oscilloscope data from a node
@@ -522,4 +528,6 @@ pub enum QueryResponse {
MidiClipDuplicated(Result<MidiClipId, String>),
/// Whether a track's graph is the auto-generated default
GraphIsDefault(bool),
/// Pitch bend range in semitones for the track's instrument
PitchBendRange(f32),
}