Add audio node graph editing

This commit is contained in:
Skyler Lehmkuhl
2025-10-25 03:29:54 -04:00
parent 19e99fa8bf
commit 16f4a2a359
43 changed files with 7110 additions and 824 deletions
+235 -1
View File
@@ -1,12 +1,14 @@
use crate::audio::buffer_pool::BufferPool;
use crate::audio::clip::ClipId;
use crate::audio::midi::{MidiClip, MidiClipId, MidiEvent};
use crate::audio::node_graph::{nodes::*, InstrumentGraph};
use crate::audio::pool::AudioPool;
use crate::audio::project::Project;
use crate::audio::recording::RecordingState;
use crate::audio::track::{Track, TrackId};
use crate::audio::track::{Track, TrackId, TrackNode};
use crate::command::{AudioEvent, Command};
use crate::effects::{Effect, GainEffect, PanEffect, SimpleEQ};
use petgraph::stable_graph::NodeIndex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
@@ -718,6 +720,193 @@ impl Engine {
// Send a live MIDI note off event to the specified track's instrument
self.project.send_midi_note_off(track_id, note);
}
// Node graph commands
Command::GraphAddNode(track_id, node_type, _x, _y) => {
// Get MIDI track (graphs are only for MIDI tracks currently)
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
// Create graph if it doesn't exist
if track.instrument_graph.is_none() {
// Use large buffer to accommodate any audio callback size
track.instrument_graph = Some(InstrumentGraph::new(self.sample_rate, 8192));
}
if let Some(graph) = &mut track.instrument_graph {
// Create the node based on type
let node: Box<dyn crate::audio::node_graph::AudioNode> = match node_type.as_str() {
"Oscillator" => Box::new(OscillatorNode::new("Oscillator".to_string())),
"Gain" => Box::new(GainNode::new("Gain".to_string())),
"Mixer" => Box::new(MixerNode::new("Mixer".to_string())),
"Filter" => Box::new(FilterNode::new("Filter".to_string())),
"ADSR" => Box::new(ADSRNode::new("ADSR".to_string())),
"MidiInput" => Box::new(MidiInputNode::new("MIDI Input".to_string())),
"MidiToCV" => Box::new(MidiToCVNode::new("MIDI→CV".to_string())),
"AudioToCV" => Box::new(AudioToCVNode::new("Audio→CV".to_string())),
"Oscilloscope" => Box::new(OscilloscopeNode::new("Oscilloscope".to_string())),
"TemplateInput" => Box::new(TemplateInputNode::new("Template Input".to_string())),
"TemplateOutput" => Box::new(TemplateOutputNode::new("Template Output".to_string())),
"VoiceAllocator" => Box::new(VoiceAllocatorNode::new("VoiceAllocator".to_string(), self.sample_rate, 8192)),
"AudioOutput" => Box::new(AudioOutputNode::new("Output".to_string())),
_ => {
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
format!("Unknown node type: {}", node_type)
));
return;
}
};
// Add node to graph
let node_idx = graph.add_node(node);
let node_id = node_idx.index() as u32;
// Automatically set MIDI-receiving nodes as MIDI targets
if node_type == "MidiInput" || node_type == "VoiceAllocator" {
graph.set_midi_target(node_idx, true);
}
// Emit success event
let _ = self.event_tx.push(AudioEvent::GraphNodeAdded(track_id, node_id, node_type.clone()));
}
}
}
Command::GraphAddNodeToTemplate(track_id, voice_allocator_id, node_type, _x, _y) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
if let Some(graph) = &mut track.instrument_graph {
let va_idx = NodeIndex::new(voice_allocator_id as usize);
// Create the node
let node: Box<dyn crate::audio::node_graph::AudioNode> = match node_type.as_str() {
"Oscillator" => Box::new(OscillatorNode::new("Oscillator".to_string())),
"Gain" => Box::new(GainNode::new("Gain".to_string())),
"Mixer" => Box::new(MixerNode::new("Mixer".to_string())),
"Filter" => Box::new(FilterNode::new("Filter".to_string())),
"ADSR" => Box::new(ADSRNode::new("ADSR".to_string())),
"MidiInput" => Box::new(MidiInputNode::new("MIDI Input".to_string())),
"MidiToCV" => Box::new(MidiToCVNode::new("MIDI→CV".to_string())),
"AudioToCV" => Box::new(AudioToCVNode::new("Audio→CV".to_string())),
"Oscilloscope" => Box::new(OscilloscopeNode::new("Oscilloscope".to_string())),
"TemplateInput" => Box::new(TemplateInputNode::new("Template Input".to_string())),
"TemplateOutput" => Box::new(TemplateOutputNode::new("Template Output".to_string())),
"AudioOutput" => Box::new(AudioOutputNode::new("Output".to_string())),
_ => {
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
format!("Unknown node type: {}", node_type)
));
return;
}
};
// Add node to VoiceAllocator's template graph
match graph.add_node_to_voice_allocator_template(va_idx, node) {
Ok(node_id) => {
println!("Added node {} (ID: {}) to VoiceAllocator {} template", node_type, node_id, voice_allocator_id);
let _ = self.event_tx.push(AudioEvent::GraphNodeAdded(track_id, node_id, node_type.clone()));
}
Err(e) => {
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
format!("Failed to add node to template: {}", e)
));
}
}
}
}
}
Command::GraphRemoveNode(track_id, node_index) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
if let Some(graph) = &mut track.instrument_graph {
let node_idx = NodeIndex::new(node_index as usize);
graph.remove_node(node_idx);
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
}
}
}
Command::GraphConnect(track_id, from, from_port, to, to_port) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
if let Some(graph) = &mut track.instrument_graph {
let from_idx = NodeIndex::new(from as usize);
let to_idx = NodeIndex::new(to as usize);
match graph.connect(from_idx, from_port, to_idx, to_port) {
Ok(()) => {
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
}
Err(e) => {
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
format!("{:?}", e)
));
}
}
}
}
}
Command::GraphConnectInTemplate(track_id, voice_allocator_id, from, from_port, to, to_port) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
if let Some(graph) = &mut track.instrument_graph {
let va_idx = NodeIndex::new(voice_allocator_id as usize);
match graph.connect_in_voice_allocator_template(va_idx, from, from_port, to, to_port) {
Ok(()) => {
println!("Connected nodes in VoiceAllocator {} template: {} -> {}", voice_allocator_id, from, to);
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
}
Err(e) => {
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
format!("Failed to connect in template: {}", e)
));
}
}
}
}
}
Command::GraphDisconnect(track_id, from, from_port, to, to_port) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
if let Some(graph) = &mut track.instrument_graph {
let from_idx = NodeIndex::new(from as usize);
let to_idx = NodeIndex::new(to as usize);
graph.disconnect(from_idx, from_port, to_idx, to_port);
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
}
}
}
Command::GraphSetParameter(track_id, node_index, param_id, value) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
if let Some(graph) = &mut track.instrument_graph {
let node_idx = NodeIndex::new(node_index as usize);
if let Some(graph_node) = graph.get_graph_node_mut(node_idx) {
graph_node.node.set_parameter(param_id, value);
}
}
}
}
Command::GraphSetMidiTarget(track_id, node_index, enabled) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
if let Some(graph) = &mut track.instrument_graph {
let node_idx = NodeIndex::new(node_index as usize);
graph.set_midi_target(node_idx, enabled);
}
}
}
Command::GraphSetOutputNode(track_id, node_index) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
if let Some(graph) = &mut track.instrument_graph {
let node_idx = NodeIndex::new(node_index as usize);
graph.set_output_node(Some(node_idx));
}
}
}
}
}
@@ -1143,4 +1332,49 @@ impl EngineController {
pub fn send_midi_note_off(&mut self, track_id: TrackId, note: u8) {
let _ = self.command_tx.push(Command::SendMidiNoteOff(track_id, note));
}
// Node graph operations
/// Add a node to a track's instrument graph
pub fn graph_add_node(&mut self, track_id: TrackId, node_type: String, x: f32, y: f32) {
let _ = self.command_tx.push(Command::GraphAddNode(track_id, node_type, x, y));
}
pub fn graph_add_node_to_template(&mut self, track_id: TrackId, voice_allocator_id: u32, node_type: String, x: f32, y: f32) {
let _ = self.command_tx.push(Command::GraphAddNodeToTemplate(track_id, voice_allocator_id, node_type, x, y));
}
pub fn graph_connect_in_template(&mut self, track_id: TrackId, voice_allocator_id: u32, from_node: u32, from_port: usize, to_node: u32, to_port: usize) {
let _ = self.command_tx.push(Command::GraphConnectInTemplate(track_id, voice_allocator_id, from_node, from_port, to_node, to_port));
}
/// Remove a node from a track's instrument graph
pub fn graph_remove_node(&mut self, track_id: TrackId, node_id: u32) {
let _ = self.command_tx.push(Command::GraphRemoveNode(track_id, node_id));
}
/// Connect two nodes in a track's instrument graph
pub fn graph_connect(&mut self, track_id: TrackId, from_node: u32, from_port: usize, to_node: u32, to_port: usize) {
let _ = self.command_tx.push(Command::GraphConnect(track_id, from_node, from_port, to_node, to_port));
}
/// Disconnect two nodes in a track's instrument graph
pub fn graph_disconnect(&mut self, track_id: TrackId, from_node: u32, from_port: usize, to_node: u32, to_port: usize) {
let _ = self.command_tx.push(Command::GraphDisconnect(track_id, from_node, from_port, to_node, to_port));
}
/// Set a parameter on a node in a track's instrument graph
pub fn graph_set_parameter(&mut self, track_id: TrackId, node_id: u32, param_id: u32, value: f32) {
let _ = self.command_tx.push(Command::GraphSetParameter(track_id, node_id, param_id, value));
}
/// Set which node receives MIDI events in a track's instrument graph
pub fn graph_set_midi_target(&mut self, track_id: TrackId, node_id: u32, enabled: bool) {
let _ = self.command_tx.push(Command::GraphSetMidiTarget(track_id, node_id, enabled));
}
/// Set which node is the audio output in a track's instrument graph
pub fn graph_set_output_node(&mut self, track_id: TrackId, node_id: u32) {
let _ = self.command_tx.push(Command::GraphSetOutputNode(track_id, node_id));
}
}
+1
View File
@@ -3,6 +3,7 @@ pub mod buffer_pool;
pub mod clip;
pub mod engine;
pub mod midi;
pub mod node_graph;
pub mod pool;
pub mod project;
pub mod recording;
+546
View File
@@ -0,0 +1,546 @@
use super::node_trait::AudioNode;
use super::types::{ConnectionError, SignalType};
use crate::audio::midi::MidiEvent;
use petgraph::algo::has_path_connecting;
use petgraph::stable_graph::{NodeIndex, StableGraph};
use petgraph::visit::{EdgeRef, IntoEdgeReferences};
use petgraph::Direction;
/// Connection information between nodes
#[derive(Debug, Clone)]
pub struct Connection {
pub from_port: usize,
pub to_port: usize,
}
/// Wrapper for audio nodes in the graph
pub struct GraphNode {
pub node: Box<dyn AudioNode>,
/// Buffers for each audio/CV output port
pub output_buffers: Vec<Vec<f32>>,
/// Buffers for each MIDI output port
pub midi_output_buffers: Vec<Vec<MidiEvent>>,
}
impl GraphNode {
pub fn new(node: Box<dyn AudioNode>, buffer_size: usize) -> Self {
let outputs = node.outputs();
// Allocate buffers based on signal type
// Audio signals are stereo (2 samples per frame), CV is mono (1 sample per frame)
let mut output_buffers = Vec::new();
let mut midi_output_buffers = Vec::new();
for port in outputs.iter() {
match port.signal_type {
SignalType::Audio => {
output_buffers.push(vec![0.0; buffer_size * 2]); // Stereo (interleaved L/R)
}
SignalType::CV => {
output_buffers.push(vec![0.0; buffer_size]); // Mono
}
SignalType::Midi => {
output_buffers.push(vec![]); // Placeholder for indexing alignment
let mut midi_buf = Vec::new();
midi_buf.reserve(128); // Max 128 MIDI events per cycle
midi_output_buffers.push(midi_buf);
}
}
}
Self {
node,
output_buffers,
midi_output_buffers,
}
}
}
/// Audio processing graph for instruments/effects
pub struct InstrumentGraph {
/// The audio graph (StableGraph allows node removal without index invalidation)
graph: StableGraph<GraphNode, Connection>,
/// MIDI input mapping (which nodes receive MIDI)
midi_targets: Vec<NodeIndex>,
/// Audio output node index (where we read final audio)
output_node: Option<NodeIndex>,
/// Sample rate
sample_rate: u32,
/// Buffer size for internal processing
buffer_size: usize,
/// Temporary buffers for node audio/CV inputs during processing
input_buffers: Vec<Vec<f32>>,
/// Temporary buffers for node MIDI inputs during processing
midi_input_buffers: Vec<Vec<MidiEvent>>,
}
impl InstrumentGraph {
/// Create a new empty instrument graph
pub fn new(sample_rate: u32, buffer_size: usize) -> Self {
Self {
graph: StableGraph::new(),
midi_targets: Vec::new(),
output_node: None,
sample_rate,
buffer_size,
// Pre-allocate input buffers with stereo size (2x) to accommodate Audio signals
// CV signals will only use the first half
input_buffers: vec![vec![0.0; buffer_size * 2]; 16],
// Pre-allocate MIDI input buffers (max 128 events per port)
midi_input_buffers: (0..16).map(|_| Vec::with_capacity(128)).collect(),
}
}
/// Add a node to the graph
pub fn add_node(&mut self, node: Box<dyn AudioNode>) -> NodeIndex {
let graph_node = GraphNode::new(node, self.buffer_size);
self.graph.add_node(graph_node)
}
/// Connect two nodes with type checking
pub fn connect(
&mut self,
from: NodeIndex,
from_port: usize,
to: NodeIndex,
to_port: usize,
) -> Result<(), ConnectionError> {
// Validate the connection
self.validate_connection(from, from_port, to, to_port)?;
// Add the edge
self.graph.add_edge(from, to, Connection { from_port, to_port });
Ok(())
}
/// Disconnect two nodes
pub fn disconnect(
&mut self,
from: NodeIndex,
from_port: usize,
to: NodeIndex,
to_port: usize,
) {
// Find and remove the edge
if let Some(edge_idx) = self.graph.find_edge(from, to) {
let conn = &self.graph[edge_idx];
if conn.from_port == from_port && conn.to_port == to_port {
self.graph.remove_edge(edge_idx);
}
}
}
/// Remove a node from the graph
pub fn remove_node(&mut self, node: NodeIndex) {
self.graph.remove_node(node);
// Update MIDI targets
self.midi_targets.retain(|&idx| idx != node);
// Update output node
if self.output_node == Some(node) {
self.output_node = None;
}
}
/// Validate a connection is type-compatible and wouldn't create a cycle
fn validate_connection(
&self,
from: NodeIndex,
from_port: usize,
to: NodeIndex,
to_port: usize,
) -> Result<(), ConnectionError> {
// Check nodes exist
let from_node = self.graph.node_weight(from).ok_or(ConnectionError::InvalidPort)?;
let to_node = self.graph.node_weight(to).ok_or(ConnectionError::InvalidPort)?;
// Check ports are valid
let from_outputs = from_node.node.outputs();
let to_inputs = to_node.node.inputs();
if from_port >= from_outputs.len() || to_port >= to_inputs.len() {
return Err(ConnectionError::InvalidPort);
}
// Check signal types match
let from_type = from_outputs[from_port].signal_type;
let to_type = to_inputs[to_port].signal_type;
if from_type != to_type {
return Err(ConnectionError::TypeMismatch {
expected: to_type,
got: from_type,
});
}
// Check for cycles: if there's already a path from 'to' to 'from',
// then adding 'from' -> 'to' would create a cycle
if has_path_connecting(&self.graph, to, from, None) {
return Err(ConnectionError::WouldCreateCycle);
}
Ok(())
}
/// Set which node receives MIDI events
pub fn set_midi_target(&mut self, node: NodeIndex, enabled: bool) {
if enabled {
if !self.midi_targets.contains(&node) {
self.midi_targets.push(node);
}
} else {
self.midi_targets.retain(|&idx| idx != node);
}
}
/// Set the output node (where final audio is read from)
pub fn set_output_node(&mut self, node: Option<NodeIndex>) {
self.output_node = node;
}
/// Add a node to a VoiceAllocator's template graph
pub fn add_node_to_voice_allocator_template(
&mut self,
voice_allocator_idx: NodeIndex,
node: Box<dyn AudioNode>,
) -> Result<u32, String> {
use crate::audio::node_graph::nodes::VoiceAllocatorNode;
// Get the VoiceAllocator node
if let Some(graph_node) = self.graph.node_weight_mut(voice_allocator_idx) {
// We need to downcast to VoiceAllocatorNode
// This is tricky with trait objects, so we'll need to use Any
// For now, let's use a different approach - store the node pointer temporarily
// Check node type first
if graph_node.node.node_type() != "VoiceAllocator" {
return Err("Node is not a VoiceAllocator".to_string());
}
// Get mutable reference and downcast using raw pointers
let node_ptr = &mut *graph_node.node as *mut dyn AudioNode;
// SAFETY: We just checked that this is a VoiceAllocator
// This is safe because we know the concrete type
unsafe {
let va_ptr = node_ptr as *mut VoiceAllocatorNode;
let va = &mut *va_ptr;
// Add node to template graph
let node_idx = va.template_graph_mut().add_node(node);
let node_id = node_idx.index() as u32;
// Rebuild voice instances from template
va.rebuild_voices();
return Ok(node_id);
}
}
Err("VoiceAllocator node not found".to_string())
}
/// Connect nodes in a VoiceAllocator's template graph
pub fn connect_in_voice_allocator_template(
&mut self,
voice_allocator_idx: NodeIndex,
from_node: u32,
from_port: usize,
to_node: u32,
to_port: usize,
) -> Result<(), String> {
use crate::audio::node_graph::nodes::VoiceAllocatorNode;
// Get the VoiceAllocator node
if let Some(graph_node) = self.graph.node_weight_mut(voice_allocator_idx) {
// Check node type first
if graph_node.node.node_type() != "VoiceAllocator" {
return Err("Node is not a VoiceAllocator".to_string());
}
// Get mutable reference and downcast using raw pointers
let node_ptr = &mut *graph_node.node as *mut dyn AudioNode;
// SAFETY: We just checked that this is a VoiceAllocator
unsafe {
let va_ptr = node_ptr as *mut VoiceAllocatorNode;
let va = &mut *va_ptr;
// Connect in template graph
let from_idx = NodeIndex::new(from_node as usize);
let to_idx = NodeIndex::new(to_node as usize);
va.template_graph_mut().connect(from_idx, from_port, to_idx, to_port)
.map_err(|e| format!("{:?}", e))?;
// Rebuild voice instances from template
va.rebuild_voices();
return Ok(());
}
}
Err("VoiceAllocator node not found".to_string())
}
/// Process the graph and produce audio output
pub fn process(&mut self, output_buffer: &mut [f32], midi_events: &[MidiEvent]) {
// Use the requested output buffer size for processing
let process_size = output_buffer.len();
// Clear all output buffers (audio/CV and MIDI)
for node in self.graph.node_weights_mut() {
for buffer in &mut node.output_buffers {
let len = buffer.len();
buffer[..process_size.min(len)].fill(0.0);
}
for midi_buffer in &mut node.midi_output_buffers {
midi_buffer.clear();
}
}
// Distribute incoming MIDI events to target nodes' MIDI output buffers
// This puts MIDI into the graph so it can flow through connections
for &target_idx in &self.midi_targets {
if let Some(node) = self.graph.node_weight_mut(target_idx) {
// Find the first MIDI output port and add events there
if !node.midi_output_buffers.is_empty() {
node.midi_output_buffers[0].extend_from_slice(midi_events);
}
}
}
// Topological sort for processing order
let topo = petgraph::algo::toposort(&self.graph, None)
.unwrap_or_else(|_| {
// If there's a cycle (shouldn't happen due to validation), just process in index order
self.graph.node_indices().collect()
});
// Process nodes in topological order
for node_idx in topo {
// Get input port information
let inputs = self.graph[node_idx].node.inputs();
let num_audio_cv_inputs = inputs.iter().filter(|p| p.signal_type != SignalType::Midi).count();
let num_midi_inputs = inputs.iter().filter(|p| p.signal_type == SignalType::Midi).count();
// Clear audio/CV input buffers
for i in 0..num_audio_cv_inputs {
if i < self.input_buffers.len() {
self.input_buffers[i].fill(0.0);
}
}
// Clear MIDI input buffers
for i in 0..num_midi_inputs {
if i < self.midi_input_buffers.len() {
self.midi_input_buffers[i].clear();
}
}
// Collect inputs from connected nodes
let incoming = self.graph.edges_directed(node_idx, Direction::Incoming).collect::<Vec<_>>();
for edge in incoming {
let source_idx = edge.source();
let conn = edge.weight();
let source_node = &self.graph[source_idx];
// Determine source port type
if conn.from_port < source_node.node.outputs().len() {
let source_port_type = source_node.node.outputs()[conn.from_port].signal_type;
match source_port_type {
SignalType::Audio | SignalType::CV => {
// Copy audio/CV data
if conn.to_port < num_audio_cv_inputs && conn.from_port < source_node.output_buffers.len() {
let source_buffer = &source_node.output_buffers[conn.from_port];
if conn.to_port < self.input_buffers.len() {
for (dst, src) in self.input_buffers[conn.to_port].iter_mut().zip(source_buffer.iter()) {
*dst += src;
}
}
}
}
SignalType::Midi => {
// Copy MIDI events
// Map from global port index to MIDI-only port index
let midi_port_idx = inputs.iter()
.take(conn.to_port + 1)
.filter(|p| p.signal_type == SignalType::Midi)
.count() - 1;
let source_midi_idx = source_node.node.outputs().iter()
.take(conn.from_port + 1)
.filter(|p| p.signal_type == SignalType::Midi)
.count() - 1;
if midi_port_idx < self.midi_input_buffers.len() &&
source_midi_idx < source_node.midi_output_buffers.len() {
self.midi_input_buffers[midi_port_idx]
.extend_from_slice(&source_node.midi_output_buffers[source_midi_idx]);
}
}
}
}
}
// Prepare audio/CV input slices
let input_slices: Vec<&[f32]> = (0..num_audio_cv_inputs)
.map(|i| {
if i < self.input_buffers.len() {
&self.input_buffers[i][..process_size.min(self.input_buffers[i].len())]
} else {
&[][..]
}
})
.collect();
// Prepare MIDI input slices
let midi_input_slices: Vec<&[MidiEvent]> = (0..num_midi_inputs)
.map(|i| {
if i < self.midi_input_buffers.len() {
&self.midi_input_buffers[i][..]
} else {
&[][..]
}
})
.collect();
// Get mutable access to output buffers
let node = &mut self.graph[node_idx];
let outputs = node.node.outputs();
let num_audio_cv_outputs = outputs.iter().filter(|p| p.signal_type != SignalType::Midi).count();
let num_midi_outputs = outputs.iter().filter(|p| p.signal_type == SignalType::Midi).count();
// Create mutable slices for audio/CV outputs
let mut output_slices: Vec<&mut [f32]> = Vec::with_capacity(num_audio_cv_outputs);
for i in 0..num_audio_cv_outputs {
if i < node.output_buffers.len() {
// Safety: We need to work around borrowing rules here
// This is safe because each output buffer is independent
let buffer = &mut node.output_buffers[i] as *mut Vec<f32>;
unsafe {
let slice = &mut (*buffer)[..process_size.min((*buffer).len())];
output_slices.push(slice);
}
}
}
// Create mutable references for MIDI outputs
let mut midi_output_refs: Vec<&mut Vec<MidiEvent>> = Vec::with_capacity(num_midi_outputs);
for i in 0..num_midi_outputs {
if i < node.midi_output_buffers.len() {
// Safety: Similar to above
let buffer = &mut node.midi_output_buffers[i] as *mut Vec<MidiEvent>;
unsafe {
midi_output_refs.push(&mut *buffer);
}
}
}
// Process the node with both audio/CV and MIDI
node.node.process(&input_slices, &mut output_slices, &midi_input_slices, &mut midi_output_refs, self.sample_rate);
}
// Copy output node's first output to the provided buffer
if let Some(output_idx) = self.output_node {
if let Some(output_node) = self.graph.node_weight(output_idx) {
if !output_node.output_buffers.is_empty() {
let len = output_buffer.len().min(output_node.output_buffers[0].len());
output_buffer[..len].copy_from_slice(&output_node.output_buffers[0][..len]);
}
}
}
}
/// Get node by index
pub fn get_node(&self, idx: NodeIndex) -> Option<&dyn AudioNode> {
self.graph.node_weight(idx).map(|n| &*n.node)
}
/// Get oscilloscope data from a specific node
pub fn get_oscilloscope_data(&self, idx: NodeIndex, sample_count: usize) -> Option<Vec<f32>> {
self.get_node(idx).and_then(|node| node.get_oscilloscope_data(sample_count))
}
/// Get node mutably by index
/// Note: Due to lifetime constraints with trait objects, this returns a mutable reference
/// to the GraphNode, from which you can access the node
pub fn get_graph_node_mut(&mut self, idx: NodeIndex) -> Option<&mut GraphNode> {
self.graph.node_weight_mut(idx)
}
/// Get all node indices
pub fn node_indices(&self) -> impl Iterator<Item = NodeIndex> + '_ {
self.graph.node_indices()
}
/// Get all connections
pub fn connections(&self) -> impl Iterator<Item = (NodeIndex, NodeIndex, &Connection)> + '_ {
self.graph.edge_references().map(|e| (e.source(), e.target(), e.weight()))
}
/// Reset all nodes in the graph
pub fn reset(&mut self) {
// Collect indices first to avoid borrow checker issues
let indices: Vec<_> = self.graph.node_indices().collect();
for node_idx in indices {
if let Some(node) = self.graph.node_weight_mut(node_idx) {
node.node.reset();
}
}
}
/// Clone the graph structure with all nodes and connections
pub fn clone_graph(&self) -> Self {
let mut new_graph = Self::new(self.sample_rate, self.buffer_size);
// Map from old NodeIndex to new NodeIndex
let mut index_map = std::collections::HashMap::new();
// Clone all nodes
for node_idx in self.graph.node_indices() {
if let Some(graph_node) = self.graph.node_weight(node_idx) {
let cloned_node = graph_node.node.clone_node();
let new_idx = new_graph.add_node(cloned_node);
index_map.insert(node_idx, new_idx);
}
}
// Clone all connections
for edge in self.graph.edge_references() {
let source = edge.source();
let target = edge.target();
let conn = edge.weight();
if let (Some(&new_source), Some(&new_target)) = (index_map.get(&source), index_map.get(&target)) {
let _ = new_graph.connect(new_source, conn.from_port, new_target, conn.to_port);
}
}
// Clone MIDI targets
for &old_target in &self.midi_targets {
if let Some(&new_target) = index_map.get(&old_target) {
new_graph.set_midi_target(new_target, true);
}
}
// Clone output node reference
if let Some(old_output) = self.output_node {
if let Some(&new_output) = index_map.get(&old_output) {
new_graph.output_node = Some(new_output);
}
}
new_graph
}
}
+8
View File
@@ -0,0 +1,8 @@
mod graph;
mod node_trait;
mod types;
pub mod nodes;
pub use graph::{Connection, GraphNode, InstrumentGraph};
pub use node_trait::AudioNode;
pub use types::{ConnectionError, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
@@ -0,0 +1,67 @@
use super::types::{NodeCategory, NodePort, Parameter};
use crate::audio::midi::MidiEvent;
/// Custom node trait for audio processing nodes
///
/// All nodes must be Send to be usable in the audio thread.
/// Nodes should be real-time safe: no allocations, no blocking operations.
pub trait AudioNode: Send {
/// Node category for UI organization
fn category(&self) -> NodeCategory;
/// Input port definitions
fn inputs(&self) -> &[NodePort];
/// Output port definitions
fn outputs(&self) -> &[NodePort];
/// User-facing parameters
fn parameters(&self) -> &[Parameter];
/// Set parameter by ID
fn set_parameter(&mut self, id: u32, value: f32);
/// Get parameter by ID
fn get_parameter(&self, id: u32) -> f32;
/// Process audio buffers
///
/// # Arguments
/// * `inputs` - Audio/CV input buffers for each input port
/// * `outputs` - Audio/CV output buffers for each output port
/// * `midi_inputs` - MIDI event buffers for each MIDI input port
/// * `midi_outputs` - MIDI event buffers for each MIDI output port
/// * `sample_rate` - Current sample rate in Hz
fn process(
&mut self,
inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
midi_inputs: &[&[MidiEvent]],
midi_outputs: &mut [&mut Vec<MidiEvent>],
sample_rate: u32,
);
/// Handle MIDI events (for nodes with MIDI inputs)
fn handle_midi(&mut self, _event: &MidiEvent) {
// Default: do nothing
}
/// Reset internal state (clear delays, resonances, etc.)
fn reset(&mut self);
/// Get the node type name (for serialization)
fn node_type(&self) -> &str;
/// Get a unique identifier for this node instance
fn name(&self) -> &str;
/// Clone this node into a new boxed instance
/// Required for VoiceAllocator to create multiple instances
fn clone_node(&self) -> Box<dyn AudioNode>;
/// Get oscilloscope data if this is an oscilloscope node
/// Returns None for non-oscilloscope nodes
fn get_oscilloscope_data(&self, _sample_count: usize) -> Option<Vec<f32>> {
None
}
}
@@ -0,0 +1,215 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_ATTACK: u32 = 0;
const PARAM_DECAY: u32 = 1;
const PARAM_SUSTAIN: u32 = 2;
const PARAM_RELEASE: u32 = 3;
#[derive(Debug, Clone, Copy, PartialEq)]
enum EnvelopeStage {
Idle,
Attack,
Decay,
Sustain,
Release,
}
/// ADSR Envelope Generator
/// Outputs a CV signal (0.0-1.0) based on gate input and ADSR parameters
pub struct ADSRNode {
name: String,
attack: f32, // seconds
decay: f32, // seconds
sustain: f32, // level (0.0-1.0)
release: f32, // seconds
stage: EnvelopeStage,
level: f32, // current envelope level
gate_was_high: bool,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl ADSRNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Gate", SignalType::CV, 0),
];
let outputs = vec![
NodePort::new("Envelope Out", SignalType::CV, 0),
];
let parameters = vec![
Parameter::new(PARAM_ATTACK, "Attack", 0.001, 5.0, 0.01, ParameterUnit::Time),
Parameter::new(PARAM_DECAY, "Decay", 0.001, 5.0, 0.1, ParameterUnit::Time),
Parameter::new(PARAM_SUSTAIN, "Sustain", 0.0, 1.0, 0.7, ParameterUnit::Generic),
Parameter::new(PARAM_RELEASE, "Release", 0.001, 5.0, 0.2, ParameterUnit::Time),
];
Self {
name,
attack: 0.01,
decay: 0.1,
sustain: 0.7,
release: 0.2,
stage: EnvelopeStage::Idle,
level: 0.0,
gate_was_high: false,
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for ADSRNode {
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_ATTACK => self.attack = value.clamp(0.001, 5.0),
PARAM_DECAY => self.decay = value.clamp(0.001, 5.0),
PARAM_SUSTAIN => self.sustain = value.clamp(0.0, 1.0),
PARAM_RELEASE => self.release = value.clamp(0.001, 5.0),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_ATTACK => self.attack,
PARAM_DECAY => self.decay,
PARAM_SUSTAIN => self.sustain,
PARAM_RELEASE => self.release,
_ => 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 sample_rate_f32 = sample_rate as f32;
// CV signals are mono
let frames = output.len();
for frame in 0..frames {
// Read gate input (if available)
let gate_high = if !inputs.is_empty() && frame < inputs[0].len() {
inputs[0][frame] > 0.5 // Gate is high if CV > 0.5
} else {
false
};
// Detect gate transitions
if gate_high && !self.gate_was_high {
// Note on: Start attack
self.stage = EnvelopeStage::Attack;
} else if !gate_high && self.gate_was_high {
// Note off: Start release
self.stage = EnvelopeStage::Release;
}
self.gate_was_high = gate_high;
// Process envelope stage
match self.stage {
EnvelopeStage::Idle => {
self.level = 0.0;
}
EnvelopeStage::Attack => {
// Rise from current level to 1.0
let increment = 1.0 / (self.attack * sample_rate_f32);
self.level += increment;
if self.level >= 1.0 {
self.level = 1.0;
self.stage = EnvelopeStage::Decay;
}
}
EnvelopeStage::Decay => {
// Fall from 1.0 to sustain level
let target = self.sustain;
let decrement = (1.0 - target) / (self.decay * sample_rate_f32);
self.level -= decrement;
if self.level <= target {
self.level = target;
self.stage = EnvelopeStage::Sustain;
}
}
EnvelopeStage::Sustain => {
// Hold at sustain level
self.level = self.sustain;
}
EnvelopeStage::Release => {
// Fall from current level to 0.0
let decrement = self.level / (self.release * sample_rate_f32);
self.level -= decrement;
if self.level <= 0.001 {
self.level = 0.0;
self.stage = EnvelopeStage::Idle;
}
}
}
// Write envelope value (CV is mono)
output[frame] = self.level;
}
}
fn reset(&mut self) {
self.stage = EnvelopeStage::Idle;
self.level = 0.0;
self.gate_was_high = false;
}
fn node_type(&self) -> &str {
"ADSR"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
attack: self.attack,
decay: self.decay,
sustain: self.sustain,
release: self.release,
stage: EnvelopeStage::Idle, // Reset state
level: 0.0, // Reset level
gate_was_high: false, // Reset gate
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,151 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_ATTACK: u32 = 0;
const PARAM_RELEASE: u32 = 1;
/// Audio to CV converter (Envelope Follower)
/// Converts audio amplitude to control voltage
pub struct AudioToCVNode {
name: String,
envelope: f32, // Current envelope value
attack: f32, // Attack time in seconds
release: f32, // Release time in seconds
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl AudioToCVNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
];
let outputs = vec![
NodePort::new("CV Out", SignalType::CV, 0),
];
let parameters = vec![
Parameter::new(PARAM_ATTACK, "Attack", 0.001, 1.0, 0.01, ParameterUnit::Time),
Parameter::new(PARAM_RELEASE, "Release", 0.001, 1.0, 0.1, ParameterUnit::Time),
];
Self {
name,
envelope: 0.0,
attack: 0.01,
release: 0.1,
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for AudioToCVNode {
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_ATTACK => self.attack = value.clamp(0.001, 1.0),
PARAM_RELEASE => self.release = value.clamp(0.001, 1.0),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_ATTACK => self.attack,
PARAM_RELEASE => self.release,
_ => 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];
// Audio input is stereo (interleaved L/R), CV output is mono
let audio_frames = input.len() / 2;
let cv_frames = output.len();
let frames = audio_frames.min(cv_frames);
// Calculate attack and release coefficients
let sample_rate_f32 = sample_rate as f32;
let attack_coeff = (-1.0 / (self.attack * sample_rate_f32)).exp();
let release_coeff = (-1.0 / (self.release * sample_rate_f32)).exp();
for frame in 0..frames {
// Get stereo samples
let left = input[frame * 2];
let right = input[frame * 2 + 1];
// Calculate RMS-like value (average of absolute values for simplicity)
let amplitude = (left.abs() + right.abs()) / 2.0;
// Envelope follower with attack/release
if amplitude > self.envelope {
// Attack: follow signal up quickly
self.envelope = amplitude * (1.0 - attack_coeff) + self.envelope * attack_coeff;
} else {
// Release: decay slowly
self.envelope = amplitude * (1.0 - release_coeff) + self.envelope * release_coeff;
}
// Output CV (mono)
output[frame] = self.envelope;
}
}
fn reset(&mut self) {
self.envelope = 0.0;
}
fn node_type(&self) -> &str {
"AudioToCV"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
envelope: 0.0, // Reset envelope
attack: self.attack,
release: self.release,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,201 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
use crate::dsp::biquad::BiquadFilter;
const PARAM_CUTOFF: u32 = 0;
const PARAM_RESONANCE: u32 = 1;
const PARAM_TYPE: u32 = 2;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FilterType {
Lowpass = 0,
Highpass = 1,
}
impl FilterType {
fn from_f32(value: f32) -> Self {
match value.round() as i32 {
1 => FilterType::Highpass,
_ => FilterType::Lowpass,
}
}
}
/// Filter node using biquad implementation
pub struct FilterNode {
name: String,
filter: BiquadFilter,
cutoff: f32,
resonance: f32,
filter_type: FilterType,
sample_rate: u32,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl FilterNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
NodePort::new("Cutoff CV", SignalType::CV, 1),
];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
let parameters = vec![
Parameter::new(PARAM_CUTOFF, "Cutoff", 20.0, 20000.0, 1000.0, ParameterUnit::Frequency),
Parameter::new(PARAM_RESONANCE, "Resonance", 0.1, 10.0, 0.707, ParameterUnit::Generic),
Parameter::new(PARAM_TYPE, "Type", 0.0, 1.0, 0.0, ParameterUnit::Generic),
];
let filter = BiquadFilter::lowpass(1000.0, 0.707, 44100.0);
Self {
name,
filter,
cutoff: 1000.0,
resonance: 0.707,
filter_type: FilterType::Lowpass,
sample_rate: 44100,
inputs,
outputs,
parameters,
}
}
fn update_filter(&mut self) {
match self.filter_type {
FilterType::Lowpass => {
self.filter.set_lowpass(self.cutoff, self.resonance, self.sample_rate as f32);
}
FilterType::Highpass => {
self.filter.set_highpass(self.cutoff, self.resonance, self.sample_rate as f32);
}
}
}
}
impl AudioNode for FilterNode {
fn category(&self) -> NodeCategory {
NodeCategory::Effect
}
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_CUTOFF => {
self.cutoff = value.clamp(20.0, 20000.0);
self.update_filter();
}
PARAM_RESONANCE => {
self.resonance = value.clamp(0.1, 10.0);
self.update_filter();
}
PARAM_TYPE => {
self.filter_type = FilterType::from_f32(value);
self.update_filter();
}
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_CUTOFF => self.cutoff,
PARAM_RESONANCE => self.resonance,
PARAM_TYPE => self.filter_type as i32 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;
}
// Update sample rate if changed
if self.sample_rate != sample_rate {
self.sample_rate = sample_rate;
self.update_filter();
}
let input = inputs[0];
let output = &mut outputs[0];
let len = input.len().min(output.len());
// Copy input to output
output[..len].copy_from_slice(&input[..len]);
// Check for CV modulation (modulates cutoff)
if inputs.len() > 1 && !inputs[1].is_empty() {
// CV input modulates cutoff frequency
// For now, just use the base cutoff - per-sample modulation would be expensive
// TODO: Sample CV at frame rate and update filter periodically
}
// Apply filter (processes stereo interleaved)
self.filter.process_buffer(&mut output[..len], 2);
}
fn reset(&mut self) {
self.filter.reset();
}
fn node_type(&self) -> &str {
"Filter"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
// Create new filter with same parameters but reset state
let mut new_filter = BiquadFilter::new();
// Set filter to match current type
match self.filter_type {
FilterType::Lowpass => {
new_filter.set_lowpass(self.sample_rate as f32, self.cutoff, self.resonance);
}
FilterType::Highpass => {
new_filter.set_highpass(self.sample_rate as f32, self.cutoff, self.resonance);
}
}
Box::new(Self {
name: self.name.clone(),
filter: new_filter,
cutoff: self.cutoff,
resonance: self.resonance,
filter_type: self.filter_type,
sample_rate: self.sample_rate,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,130 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_GAIN: u32 = 0;
/// Gain/volume control node
pub struct GainNode {
name: String,
gain: f32,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl GainNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
NodePort::new("Gain CV", SignalType::CV, 1),
];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
let parameters = vec![
Parameter::new(PARAM_GAIN, "Gain", 0.0, 2.0, 1.0, ParameterUnit::Generic),
];
Self {
name,
gain: 1.0,
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for GainNode {
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_GAIN => self.gain = value.clamp(0.0, 2.0),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_GAIN => self.gain,
_ => 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];
// Audio signals are stereo (interleaved L/R)
// Process by frames, not samples
let frames = input.len().min(output.len()) / 2;
for frame in 0..frames {
// Calculate final gain
let mut final_gain = self.gain;
// CV input acts as a VCA (voltage-controlled amplifier)
// CV ranges from 0.0 (silence) to 1.0 (full gain parameter value)
if inputs.len() > 1 && frame < inputs[1].len() {
let cv = inputs[1][frame];
final_gain *= cv; // Multiply gain by CV (0.0 = silence, 1.0 = full gain)
}
// Apply gain to both channels
output[frame * 2] = input[frame * 2] * final_gain; // Left
output[frame * 2 + 1] = input[frame * 2 + 1] * final_gain; // Right
}
}
fn reset(&mut self) {
// No state to reset
}
fn node_type(&self) -> &str {
"Gain"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
gain: self.gain,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,105 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::midi::MidiEvent;
/// MIDI Input node - receives MIDI events from the track and passes them through
pub struct MidiInputNode {
name: String,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
pending_events: Vec<MidiEvent>,
}
impl MidiInputNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![];
let outputs = vec![
NodePort::new("MIDI Out", SignalType::Midi, 0),
];
Self {
name,
inputs,
outputs,
parameters: vec![],
pending_events: Vec::new(),
}
}
/// Add MIDI events to be processed
pub fn add_midi_events(&mut self, events: Vec<MidiEvent>) {
self.pending_events.extend(events);
}
/// Get pending MIDI events (used for routing to connected nodes)
pub fn take_midi_events(&mut self) -> Vec<MidiEvent> {
std::mem::take(&mut self.pending_events)
}
}
impl AudioNode for MidiInputNode {
fn category(&self) -> NodeCategory {
NodeCategory::Input
}
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) {
// No parameters
}
fn get_parameter(&self, _id: u32) -> 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,
) {
// MidiInput receives MIDI from external sources (marked as MIDI target)
// and outputs it through the graph
// The MIDI was already placed in midi_outputs by the graph before calling process()
}
fn reset(&mut self) {
self.pending_events.clear();
}
fn node_type(&self) -> &str {
"MidiInput"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
pending_events: Vec::new(),
})
}
fn handle_midi(&mut self, event: &MidiEvent) {
self.pending_events.push(*event);
}
}
@@ -0,0 +1,185 @@
use crate::audio::midi::MidiEvent;
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
/// 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 (0.0-1.0 V/oct)
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
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),
];
let outputs = vec![
NodePort::new("V/Oct", SignalType::CV, 0), // 0.0-1.0 pitch CV
NodePort::new("Gate", SignalType::CV, 1), // 1.0 = on, 0.0 = off
NodePort::new("Velocity", SignalType::CV, 2), // 0.0-1.0
];
Self {
name,
note: 60, // Middle C
gate: 0.0,
velocity: 0.0,
pitch_cv: Self::midi_note_to_voct(60),
inputs,
outputs,
parameters: vec![], // No user parameters
}
}
/// Convert MIDI note to V/oct CV (0-1 range representing pitch)
/// Maps MIDI notes 0-127 to CV 0.0-1.0 for pitch tracking
fn midi_note_to_voct(note: u8) -> f32 {
// Simple linear mapping: each semitone is 1/127 of the CV range
note as f32 / 127.0
}
}
impl AudioNode for MidiToCVNode {
fn category(&self) -> NodeCategory {
NodeCategory::Input
}
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) {
// No parameters
}
fn get_parameter(&self, _id: u32) -> f32 {
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;
}
}
_ => {}
}
}
fn process(
&mut self,
_inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
_sample_rate: u32,
) {
// 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;
}
}
_ => {}
}
}
}
if outputs.len() < 3 {
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);
let pitch_out = &mut pitch_and_rest[0];
let gate_out = &mut gate_and_rest[0];
let velocity_out = &mut velocity_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;
velocity_out[frame] = self.velocity;
}
}
fn reset(&mut self) {
self.gate = 0.0;
self.velocity = 0.0;
}
fn node_type(&self) -> &str {
"MidiToCV"
}
fn name(&self) -> &str {
&self.name
}
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
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,145 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_GAIN_1: u32 = 0;
const PARAM_GAIN_2: u32 = 1;
const PARAM_GAIN_3: u32 = 2;
const PARAM_GAIN_4: u32 = 3;
/// Mixer node - combines multiple audio inputs with independent gain controls
pub struct MixerNode {
name: String,
gains: [f32; 4],
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl MixerNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Input 1", SignalType::Audio, 0),
NodePort::new("Input 2", SignalType::Audio, 1),
NodePort::new("Input 3", SignalType::Audio, 2),
NodePort::new("Input 4", SignalType::Audio, 3),
];
let outputs = vec![
NodePort::new("Mixed Out", SignalType::Audio, 0),
];
let parameters = vec![
Parameter::new(PARAM_GAIN_1, "Gain 1", 0.0, 2.0, 1.0, ParameterUnit::Generic),
Parameter::new(PARAM_GAIN_2, "Gain 2", 0.0, 2.0, 1.0, ParameterUnit::Generic),
Parameter::new(PARAM_GAIN_3, "Gain 3", 0.0, 2.0, 1.0, ParameterUnit::Generic),
Parameter::new(PARAM_GAIN_4, "Gain 4", 0.0, 2.0, 1.0, ParameterUnit::Generic),
];
Self {
name,
gains: [1.0, 1.0, 1.0, 1.0],
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for MixerNode {
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_GAIN_1 => self.gains[0] = value.clamp(0.0, 2.0),
PARAM_GAIN_2 => self.gains[1] = value.clamp(0.0, 2.0),
PARAM_GAIN_3 => self.gains[2] = value.clamp(0.0, 2.0),
PARAM_GAIN_4 => self.gains[3] = value.clamp(0.0, 2.0),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_GAIN_1 => self.gains[0],
PARAM_GAIN_2 => self.gains[1],
PARAM_GAIN_3 => self.gains[2],
PARAM_GAIN_4 => self.gains[3],
_ => 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];
// Audio signals are stereo (interleaved L/R)
let frames = output.len() / 2;
// Clear output buffer first
output.fill(0.0);
// Mix each input with its gain
for (input_idx, input) in inputs.iter().enumerate().take(4) {
if input_idx >= self.gains.len() {
break;
}
let gain = self.gains[input_idx];
let input_frames = input.len() / 2;
let process_frames = frames.min(input_frames);
for frame in 0..process_frames {
output[frame * 2] += input[frame * 2] * gain; // Left
output[frame * 2 + 1] += input[frame * 2 + 1] * gain; // Right
}
}
}
fn reset(&mut self) {
// No state to reset
}
fn node_type(&self) -> &str {
"Mixer"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
gains: self.gains,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,25 @@
mod adsr;
mod audio_to_cv;
mod filter;
mod gain;
mod midi_input;
mod midi_to_cv;
mod mixer;
mod oscillator;
mod oscilloscope;
mod output;
mod template_io;
mod voice_allocator;
pub use adsr::ADSRNode;
pub use audio_to_cv::AudioToCVNode;
pub use filter::FilterNode;
pub use gain::GainNode;
pub use midi_input::MidiInputNode;
pub use midi_to_cv::MidiToCVNode;
pub use mixer::MixerNode;
pub use oscillator::OscillatorNode;
pub use oscilloscope::OscilloscopeNode;
pub use output::AudioOutputNode;
pub use template_io::{TemplateInputNode, TemplateOutputNode};
pub use voice_allocator::VoiceAllocatorNode;
@@ -0,0 +1,198 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
use std::f32::consts::PI;
const PARAM_FREQUENCY: u32 = 0;
const PARAM_AMPLITUDE: u32 = 1;
const PARAM_WAVEFORM: u32 = 2;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Waveform {
Sine = 0,
Saw = 1,
Square = 2,
Triangle = 3,
}
impl Waveform {
fn from_f32(value: f32) -> Self {
match value.round() as i32 {
1 => Waveform::Saw,
2 => Waveform::Square,
3 => Waveform::Triangle,
_ => Waveform::Sine,
}
}
}
/// Oscillator node with multiple waveforms
pub struct OscillatorNode {
name: String,
frequency: f32,
amplitude: f32,
waveform: Waveform,
phase: f32,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl OscillatorNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("V/Oct", SignalType::CV, 0),
NodePort::new("FM", SignalType::CV, 1),
];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
let parameters = vec![
Parameter::new(PARAM_FREQUENCY, "Frequency", 20.0, 20000.0, 440.0, ParameterUnit::Frequency),
Parameter::new(PARAM_AMPLITUDE, "Amplitude", 0.0, 1.0, 0.5, ParameterUnit::Generic),
Parameter::new(PARAM_WAVEFORM, "Waveform", 0.0, 3.0, 0.0, ParameterUnit::Generic),
];
Self {
name,
frequency: 440.0,
amplitude: 0.5,
waveform: Waveform::Sine,
phase: 0.0,
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for OscillatorNode {
fn category(&self) -> NodeCategory {
NodeCategory::Generator
}
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_FREQUENCY => self.frequency = value.clamp(20.0, 20000.0),
PARAM_AMPLITUDE => self.amplitude = value.clamp(0.0, 1.0),
PARAM_WAVEFORM => self.waveform = Waveform::from_f32(value),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_FREQUENCY => self.frequency,
PARAM_AMPLITUDE => self.amplitude,
PARAM_WAVEFORM => self.waveform as i32 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 outputs.is_empty() {
return;
}
let output = &mut outputs[0];
let sample_rate_f32 = sample_rate as f32;
// Audio signals are stereo (interleaved L/R)
// Process by frames, not samples
let frames = output.len() / 2;
for frame in 0..frames {
// Start with base frequency
let mut frequency = self.frequency;
// V/Oct input: 0.0-1.0 maps to MIDI notes 0-127
if !inputs.is_empty() && frame < inputs[0].len() {
let voct = inputs[0][frame]; // Read V/Oct CV (mono)
if voct > 0.001 {
// Convert CV to MIDI note number (0-1 -> 0-127)
let midi_note = voct * 127.0;
// Convert MIDI note to frequency: f = 440 * 2^((n-69)/12)
frequency = 440.0 * 2.0_f32.powf((midi_note - 69.0) / 12.0);
}
}
// FM input: modulates the frequency
if inputs.len() > 1 && frame < inputs[1].len() {
let fm = inputs[1][frame]; // Read FM CV (mono)
frequency *= 1.0 + fm;
}
let freq_mod = frequency;
// Generate waveform sample based on waveform type
let sample = match self.waveform {
Waveform::Sine => (self.phase * 2.0 * PI).sin(),
Waveform::Saw => 2.0 * self.phase - 1.0, // Ramp from -1 to 1
Waveform::Square => {
if self.phase < 0.5 { 1.0 } else { -1.0 }
}
Waveform::Triangle => {
// Triangle: rises from -1 to 1, falls back to -1
4.0 * (self.phase - 0.5).abs() - 1.0
}
} * self.amplitude;
// Write to both channels (mono source duplicated to stereo)
output[frame * 2] = sample; // Left
output[frame * 2 + 1] = sample; // Right
// Update phase once per frame
self.phase += freq_mod / sample_rate_f32;
if self.phase >= 1.0 {
self.phase -= 1.0;
}
}
}
fn reset(&mut self) {
self.phase = 0.0;
}
fn node_type(&self) -> &str {
"Oscillator"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
frequency: self.frequency,
amplitude: self.amplitude,
waveform: self.waveform,
phase: 0.0, // Reset phase for new instance
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,253 @@
use crate::audio::midi::MidiEvent;
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use std::sync::{Arc, Mutex};
const PARAM_TIME_SCALE: u32 = 0;
const PARAM_TRIGGER_MODE: u32 = 1;
const PARAM_TRIGGER_LEVEL: u32 = 2;
const BUFFER_SIZE: usize = 96000; // 2 seconds at 48kHz (stereo)
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TriggerMode {
FreeRunning = 0,
RisingEdge = 1,
FallingEdge = 2,
}
impl TriggerMode {
fn from_f32(value: f32) -> Self {
match value.round() as i32 {
1 => TriggerMode::RisingEdge,
2 => TriggerMode::FallingEdge,
_ => TriggerMode::FreeRunning,
}
}
}
/// Circular buffer for storing audio samples
struct CircularBuffer {
buffer: Vec<f32>,
write_pos: usize,
capacity: usize,
}
impl CircularBuffer {
fn new(capacity: usize) -> Self {
Self {
buffer: vec![0.0; capacity],
write_pos: 0,
capacity,
}
}
fn write(&mut self, samples: &[f32]) {
for &sample in samples {
self.buffer[self.write_pos] = sample;
self.write_pos = (self.write_pos + 1) % self.capacity;
}
}
fn read(&self, count: usize) -> Vec<f32> {
let count = count.min(self.capacity);
let mut result = Vec::with_capacity(count);
// Read backwards from current write position
let start_pos = if self.write_pos >= count {
self.write_pos - count
} else {
self.capacity - (count - self.write_pos)
};
for i in 0..count {
let pos = (start_pos + i) % self.capacity;
result.push(self.buffer[pos]);
}
result
}
fn clear(&mut self) {
self.buffer.fill(0.0);
self.write_pos = 0;
}
}
/// Oscilloscope node for visualizing audio signals
pub struct OscilloscopeNode {
name: String,
time_scale: f32, // Milliseconds to display (10-1000ms)
trigger_mode: TriggerMode,
trigger_level: f32, // -1.0 to 1.0
last_sample: f32, // For edge detection
// Shared buffer for reading from Tauri commands
buffer: Arc<Mutex<CircularBuffer>>,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl OscilloscopeNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
let parameters = vec![
Parameter::new(PARAM_TIME_SCALE, "Time Scale", 10.0, 1000.0, 100.0, ParameterUnit::Milliseconds),
Parameter::new(PARAM_TRIGGER_MODE, "Trigger", 0.0, 2.0, 0.0, ParameterUnit::Generic),
Parameter::new(PARAM_TRIGGER_LEVEL, "Trigger Level", -1.0, 1.0, 0.0, ParameterUnit::Generic),
];
Self {
name,
time_scale: 100.0,
trigger_mode: TriggerMode::FreeRunning,
trigger_level: 0.0,
last_sample: 0.0,
buffer: Arc::new(Mutex::new(CircularBuffer::new(BUFFER_SIZE))),
inputs,
outputs,
parameters,
}
}
/// Get a clone of the buffer Arc for reading from external code (Tauri commands)
pub fn get_buffer(&self) -> Arc<Mutex<CircularBuffer>> {
Arc::clone(&self.buffer)
}
/// Read samples from the buffer (for Tauri commands)
pub fn read_samples(&self, count: usize) -> Vec<f32> {
if let Ok(buffer) = self.buffer.lock() {
buffer.read(count)
} else {
vec![0.0; count]
}
}
/// Clear the buffer
pub fn clear_buffer(&self) {
if let Ok(mut buffer) = self.buffer.lock() {
buffer.clear();
}
}
/// Check if trigger condition is met
fn is_triggered(&self, current_sample: f32) -> bool {
match self.trigger_mode {
TriggerMode::FreeRunning => true,
TriggerMode::RisingEdge => {
self.last_sample <= self.trigger_level && current_sample > self.trigger_level
}
TriggerMode::FallingEdge => {
self.last_sample >= self.trigger_level && current_sample < self.trigger_level
}
}
}
}
impl AudioNode for OscilloscopeNode {
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_TIME_SCALE => self.time_scale = value.clamp(10.0, 1000.0),
PARAM_TRIGGER_MODE => self.trigger_mode = TriggerMode::from_f32(value),
PARAM_TRIGGER_LEVEL => self.trigger_level = value.clamp(-1.0, 1.0),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_TIME_SCALE => self.time_scale,
PARAM_TRIGGER_MODE => self.trigger_mode as i32 as f32,
PARAM_TRIGGER_LEVEL => self.trigger_level,
_ => 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 len = input.len().min(output.len());
// Pass through audio (copy input to output)
output[..len].copy_from_slice(&input[..len]);
// Capture samples to buffer
if let Ok(mut buffer) = self.buffer.lock() {
buffer.write(&input[..len]);
}
// Update last sample for trigger detection (use left channel, frame 0)
if !input.is_empty() {
self.last_sample = input[0];
}
}
fn reset(&mut self) {
self.last_sample = 0.0;
self.clear_buffer();
}
fn node_type(&self) -> &str {
"Oscilloscope"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
time_scale: self.time_scale,
trigger_mode: self.trigger_mode,
trigger_level: self.trigger_level,
last_sample: 0.0,
buffer: Arc::new(Mutex::new(CircularBuffer::new(BUFFER_SIZE))),
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
fn get_oscilloscope_data(&self, sample_count: usize) -> Option<Vec<f32>> {
Some(self.read_samples(sample_count))
}
}
@@ -0,0 +1,96 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::midi::MidiEvent;
/// Audio output node - collects audio and passes it to the main output
pub struct AudioOutputNode {
name: String,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
}
impl AudioOutputNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
];
// Output node has an output for graph consistency, but it's typically the final node
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
Self {
name,
inputs,
outputs,
}
}
}
impl AudioNode for AudioOutputNode {
fn category(&self) -> NodeCategory {
NodeCategory::Output
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&[] // No parameters
}
fn set_parameter(&mut self, _id: u32, _value: f32) {
// No parameters
}
fn get_parameter(&self, _id: u32) -> 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;
}
// Simply pass through the input to the output
let input = inputs[0];
let output = &mut outputs[0];
let len = input.len().min(output.len());
output[..len].copy_from_slice(&input[..len]);
}
fn reset(&mut self) {
// No state to reset
}
fn node_type(&self) -> &str {
"AudioOutput"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
})
}
}
@@ -0,0 +1,176 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::midi::MidiEvent;
/// Template Input node - represents the MIDI input for one voice in a VoiceAllocator
pub struct TemplateInputNode {
name: String,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl TemplateInputNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![];
let outputs = vec![
NodePort::new("MIDI Out", SignalType::Midi, 0),
];
Self {
name,
inputs,
outputs,
parameters: vec![],
}
}
}
impl AudioNode for TemplateInputNode {
fn category(&self) -> NodeCategory {
NodeCategory::Input
}
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) {}
fn get_parameter(&self, _id: u32) -> 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,
) {
// TemplateInput receives MIDI from VoiceAllocator and outputs it
// The MIDI was already placed in midi_outputs by the graph before calling process()
// So there's nothing to do here - the MIDI is already in the output buffer
}
fn reset(&mut self) {}
fn node_type(&self) -> &str {
"TemplateInput"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
fn handle_midi(&mut self, _event: &MidiEvent) {
// Pass through to connected nodes
}
}
/// Template Output node - represents the audio output from one voice in a VoiceAllocator
pub struct TemplateOutputNode {
name: String,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl TemplateOutputNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
Self {
name,
inputs,
outputs,
parameters: vec![],
}
}
}
impl AudioNode for TemplateOutputNode {
fn category(&self) -> NodeCategory {
NodeCategory::Output
}
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) {}
fn get_parameter(&self, _id: u32) -> 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,
) {
// Copy input to output - the graph reads from output buffers
if !inputs.is_empty() && !outputs.is_empty() {
let input = inputs[0];
let output = &mut outputs[0];
let len = input.len().min(output.len());
output[..len].copy_from_slice(&input[..len]);
}
}
fn reset(&mut self) {}
fn node_type(&self) -> &str {
"TemplateOutput"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,344 @@
use crate::audio::midi::MidiEvent;
use crate::audio::node_graph::{AudioNode, InstrumentGraph, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
const PARAM_VOICE_COUNT: u32 = 0;
const MAX_VOICES: usize = 16; // Maximum allowed voices
const DEFAULT_VOICES: usize = 8;
/// Voice state for voice allocation
#[derive(Clone)]
struct VoiceState {
active: bool,
note: u8,
age: u32, // For voice stealing
pending_events: Vec<MidiEvent>, // MIDI events to send to this voice
}
impl VoiceState {
fn new() -> Self {
Self {
active: false,
note: 0,
age: 0,
pending_events: Vec::new(),
}
}
}
/// VoiceAllocatorNode - A group node that creates N polyphonic instances of its internal graph
///
/// This node acts as a container for a "voice template" graph. At runtime, it creates
/// N instances of that graph (one per voice) and routes MIDI note events to them.
/// All voice outputs are mixed together into a single output.
pub struct VoiceAllocatorNode {
name: String,
/// The template graph (edited by user via UI)
template_graph: InstrumentGraph,
/// Runtime voice instances (clones of template)
voice_instances: Vec<InstrumentGraph>,
/// Voice allocation state
voices: [VoiceState; MAX_VOICES],
/// Number of active voices (configurable parameter)
voice_count: usize,
/// Mix buffer for combining voice outputs
mix_buffer: Vec<f32>,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl VoiceAllocatorNode {
pub fn new(name: impl Into<String>, sample_rate: u32, buffer_size: usize) -> Self {
let name = name.into();
// MIDI input for receiving note events
let inputs = vec![
NodePort::new("MIDI In", SignalType::Midi, 0),
];
// Single mixed audio output
let outputs = vec![
NodePort::new("Mixed Out", SignalType::Audio, 0),
];
// Voice count parameter
let parameters = vec![
Parameter::new(PARAM_VOICE_COUNT, "Voices", 1.0, MAX_VOICES as f32, DEFAULT_VOICES as f32, ParameterUnit::Generic),
];
// Create empty template graph
let template_graph = InstrumentGraph::new(sample_rate, buffer_size);
// Create voice instances (initially empty clones of template)
let voice_instances: Vec<InstrumentGraph> = (0..MAX_VOICES)
.map(|_| InstrumentGraph::new(sample_rate, buffer_size))
.collect();
Self {
name,
template_graph,
voice_instances,
voices: std::array::from_fn(|_| VoiceState::new()),
voice_count: DEFAULT_VOICES,
mix_buffer: vec![0.0; buffer_size * 2], // Stereo
inputs,
outputs,
parameters,
}
}
/// Get mutable reference to template graph (for UI editing)
pub fn template_graph_mut(&mut self) -> &mut InstrumentGraph {
&mut self.template_graph
}
/// Get reference to template graph (for serialization)
pub fn template_graph(&self) -> &InstrumentGraph {
&self.template_graph
}
/// Rebuild voice instances from template (called after template is edited)
pub fn rebuild_voices(&mut self) {
// Clone template to all voice instances
for voice in &mut self.voice_instances {
*voice = self.template_graph.clone_graph();
// Find TemplateInput and TemplateOutput nodes
let mut template_input_idx = None;
let mut template_output_idx = None;
for node_idx in voice.node_indices() {
if let Some(node) = voice.get_node(node_idx) {
match node.node_type() {
"TemplateInput" => template_input_idx = Some(node_idx),
"TemplateOutput" => template_output_idx = Some(node_idx),
_ => {}
}
}
}
// Mark ONLY TemplateInput as a MIDI target
// MIDI will flow through graph connections to other nodes (like MidiToCV)
if let Some(input_idx) = template_input_idx {
voice.set_midi_target(input_idx, true);
}
// Set TemplateOutput as output node
voice.set_output_node(template_output_idx);
}
}
/// Find a free voice, or steal the oldest one
fn find_voice_for_note_on(&mut self) -> usize {
// Only search within active voice_count
// First, look for an inactive voice
for (i, voice) in self.voices[..self.voice_count].iter().enumerate() {
if !voice.active {
return i;
}
}
// No free voices, steal the oldest one within voice_count
self.voices[..self.voice_count]
.iter()
.enumerate()
.max_by_key(|(_, v)| v.age)
.map(|(i, _)| i)
.unwrap_or(0)
}
/// Find all voices playing a specific note
fn find_voices_for_note_off(&self, note: u8) -> Vec<usize> {
self.voices[..self.voice_count]
.iter()
.enumerate()
.filter_map(|(i, v)| {
if v.active && v.note == note {
Some(i)
} else {
None
}
})
.collect()
}
}
impl AudioNode for VoiceAllocatorNode {
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_VOICE_COUNT => {
let new_count = (value.round() as usize).clamp(1, MAX_VOICES);
if new_count != self.voice_count {
self.voice_count = new_count;
// Stop voices beyond the new count
for voice in &mut self.voices[new_count..] {
voice.active = false;
}
}
}
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_VOICE_COUNT => self.voice_count as f32,
_ => 0.0,
}
}
fn handle_midi(&mut self, event: &MidiEvent) {
let status = event.status & 0xF0;
match status {
0x90 => {
// Note on
if event.data2 > 0 {
let voice_idx = self.find_voice_for_note_on();
self.voices[voice_idx].active = true;
self.voices[voice_idx].note = event.data1;
self.voices[voice_idx].age = 0;
// Store MIDI event for this voice to process
self.voices[voice_idx].pending_events.push(*event);
} else {
// Velocity = 0 means note off - send to ALL voices playing this note
let voice_indices = self.find_voices_for_note_off(event.data1);
for voice_idx in voice_indices {
self.voices[voice_idx].active = false;
self.voices[voice_idx].pending_events.push(*event);
}
}
}
0x80 => {
// Note off - send to ALL voices playing this note
let voice_indices = self.find_voices_for_note_off(event.data1);
for voice_idx in voice_indices {
self.voices[voice_idx].active = false;
self.voices[voice_idx].pending_events.push(*event);
}
}
_ => {
// Other MIDI events (CC, pitch bend, etc.) - send to all active voices
for voice_idx in 0..self.voice_count {
if self.voices[voice_idx].active {
self.voices[voice_idx].pending_events.push(*event);
}
}
}
}
}
fn process(
&mut self,
_inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
_sample_rate: u32,
) {
// Process MIDI events from input (allocate notes to voices)
if !midi_inputs.is_empty() {
for event in midi_inputs[0] {
self.handle_midi(event);
}
}
if outputs.is_empty() {
return;
}
let output = &mut outputs[0];
let output_len = output.len();
// Process each active voice and mix (only up to voice_count)
for voice_idx in 0..self.voice_count {
let voice_state = &mut self.voices[voice_idx];
if voice_state.active {
voice_state.age = voice_state.age.saturating_add(1);
// Get pending MIDI events for this voice
let midi_events = std::mem::take(&mut voice_state.pending_events);
// IMPORTANT: Process only the slice of mix_buffer that matches output size
// This prevents phase discontinuities in oscillators
let mix_slice = &mut self.mix_buffer[..output_len];
mix_slice.fill(0.0);
// Process this voice's graph with its MIDI events
self.voice_instances[voice_idx].process(mix_slice, &midi_events);
// Mix into output (accumulate)
for (i, sample) in mix_slice.iter().enumerate() {
output[i] += sample;
}
}
}
// Apply normalization to prevent clipping (divide by active voice count)
let active_count = self.voices[..self.voice_count].iter().filter(|v| v.active).count();
if active_count > 1 {
let scale = 1.0 / (active_count as f32).sqrt(); // Use sqrt for better loudness perception
for sample in output.iter_mut() {
*sample *= scale;
}
}
}
fn reset(&mut self) {
for voice in &mut self.voices {
voice.active = false;
voice.pending_events.clear();
}
for graph in &mut self.voice_instances {
graph.reset();
}
self.template_graph.reset();
}
fn node_type(&self) -> &str {
"VoiceAllocator"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
// Clone creates a new VoiceAllocator with the same template graph
// Voice instances will be rebuilt when rebuild_voices() is called
Box::new(Self {
name: self.name.clone(),
template_graph: self.template_graph.clone_graph(),
voice_instances: self.voice_instances.iter().map(|g| g.clone_graph()).collect(),
voices: std::array::from_fn(|_| VoiceState::new()), // Reset voices
voice_count: self.voice_count,
mix_buffer: vec![0.0; self.mix_buffer.len()],
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
+96
View File
@@ -0,0 +1,96 @@
use serde::{Deserialize, Serialize};
/// Three distinct signal types for graph edges
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SignalType {
/// Audio-rate signals (-1.0 to 1.0 typically) - Blue in UI
Audio,
/// MIDI events (discrete messages) - Green in UI
Midi,
/// Control Voltage (modulation signals, typically 0.0 to 1.0) - Orange in UI
CV,
}
/// Port definition for node inputs/outputs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodePort {
pub name: String,
pub signal_type: SignalType,
pub index: usize,
}
impl NodePort {
pub fn new(name: impl Into<String>, signal_type: SignalType, index: usize) -> Self {
Self {
name: name.into(),
signal_type,
index,
}
}
}
/// Node category for UI organization
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NodeCategory {
Input,
Generator,
Effect,
Utility,
Output,
}
/// User-facing parameter definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Parameter {
pub id: u32,
pub name: String,
pub min: f32,
pub max: f32,
pub default: f32,
pub unit: ParameterUnit,
}
impl Parameter {
pub fn new(id: u32, name: impl Into<String>, min: f32, max: f32, default: f32, unit: ParameterUnit) -> Self {
Self {
id,
name: name.into(),
min,
max,
default,
unit,
}
}
}
/// Units for parameter values
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ParameterUnit {
Generic,
Frequency, // Hz
Decibels, // dB
Time, // seconds
Percent, // 0-100
}
/// Errors that can occur during graph operations
#[derive(Debug, Clone)]
pub enum ConnectionError {
TypeMismatch { expected: SignalType, got: SignalType },
InvalidPort,
WouldCreateCycle,
}
impl std::fmt::Display for ConnectionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConnectionError::TypeMismatch { expected, got } => {
write!(f, "Signal type mismatch: expected {:?}, got {:?}", expected, got)
}
ConnectionError::InvalidPort => write!(f, "Invalid port index"),
ConnectionError::WouldCreateCycle => write!(f, "Connection would create a cycle"),
}
}
}
impl std::error::Error for ConnectionError {}
+11
View File
@@ -198,6 +198,17 @@ impl Project {
self.tracks.get_mut(&track_id)
}
/// Get oscilloscope data from a node in a track's graph
pub fn get_oscilloscope_data(&self, track_id: TrackId, node_id: u32, sample_count: usize) -> Option<Vec<f32>> {
if let Some(TrackNode::Midi(track)) = self.tracks.get(&track_id) {
if let Some(ref graph) = track.instrument_graph {
let node_idx = petgraph::stable_graph::NodeIndex::new(node_id as usize);
return graph.get_oscilloscope_data(node_idx, sample_count);
}
}
None
}
/// Get all root-level track IDs
pub fn root_tracks(&self) -> &[TrackId] {
&self.root_tracks
+30 -6
View File
@@ -1,6 +1,7 @@
use super::automation::{AutomationLane, AutomationLaneId, ParameterId};
use super::clip::Clip;
use super::midi::MidiClip;
use super::node_graph::InstrumentGraph;
use super::pool::AudioPool;
use crate::effects::{Effect, SimpleSynth};
use std::collections::HashMap;
@@ -309,6 +310,8 @@ pub struct MidiTrack {
/// Automation lanes for this track
pub automation_lanes: HashMap<AutomationLaneId, AutomationLane>,
next_automation_id: AutomationLaneId,
/// Optional instrument graph (replaces SimpleSynth when present)
pub instrument_graph: Option<InstrumentGraph>,
}
impl MidiTrack {
@@ -325,6 +328,7 @@ impl MidiTrack {
solo: false,
automation_lanes: HashMap::new(),
next_automation_id: 0,
instrument_graph: None,
}
}
@@ -401,8 +405,19 @@ impl MidiTrack {
sample_rate: u32,
channels: u32,
) {
// Generate audio from the instrument (which processes queued events)
self.instrument.process(output, channels as usize, sample_rate);
// Generate audio - use instrument graph if available, otherwise SimpleSynth
if let Some(graph) = &mut self.instrument_graph {
// Get pending MIDI events from SimpleSynth (they're queued there by send_midi_note_on/off)
// We need to drain them so they're not processed again
let events: Vec<crate::audio::midi::MidiEvent> =
self.instrument.pending_events.drain(..).collect();
// Process graph with MIDI events
graph.process(output, &events);
} else {
// Fallback to SimpleSynth (which processes queued events)
self.instrument.process(output, channels as usize, sample_rate);
}
// Apply effect chain
for effect in &mut self.effects {
@@ -427,6 +442,7 @@ impl MidiTrack {
let buffer_end_seconds = playhead_seconds + buffer_duration_seconds;
// Collect MIDI events from all clips that overlap with current time range
let mut midi_events = Vec::new();
for clip in &self.clips {
let events = clip.get_events_in_range(
playhead_seconds,
@@ -434,14 +450,22 @@ impl MidiTrack {
sample_rate,
);
// Queue events in the instrument
for (_timestamp, event) in events {
self.instrument.queue_event(event);
midi_events.push(event);
}
}
// Generate audio from the instrument
self.instrument.process(output, channels as usize, sample_rate);
// Generate audio - use instrument graph if available, otherwise SimpleSynth
if let Some(graph) = &mut self.instrument_graph {
// Use node graph for audio generation
graph.process(output, &midi_events);
} else {
// Fallback to SimpleSynth
for event in &midi_events {
self.instrument.queue_event(*event);
}
self.instrument.process(output, channels as usize, sample_rate);
}
// Apply effect chain
for effect in &mut self.effects {
+28
View File
@@ -117,6 +117,26 @@ pub enum Command {
SendMidiNoteOn(TrackId, u8, u8),
/// Send a live MIDI note off event to a track's instrument (track_id, note)
SendMidiNoteOff(TrackId, u8),
// Node graph commands
/// Add a node to a track's instrument graph (track_id, node_type, position_x, position_y)
GraphAddNode(TrackId, String, f32, f32),
/// Add a node to a VoiceAllocator's template graph (track_id, voice_allocator_node_id, node_type, position_x, position_y)
GraphAddNodeToTemplate(TrackId, u32, String, f32, f32),
/// Remove a node from a track's instrument graph (track_id, node_index)
GraphRemoveNode(TrackId, u32),
/// Connect two nodes in a track's graph (track_id, from_node, from_port, to_node, to_port)
GraphConnect(TrackId, u32, usize, u32, usize),
/// Connect nodes in a VoiceAllocator template (track_id, voice_allocator_node_id, from_node, from_port, to_node, to_port)
GraphConnectInTemplate(TrackId, u32, u32, usize, u32, usize),
/// Disconnect two nodes in a track's graph (track_id, from_node, from_port, to_node, to_port)
GraphDisconnect(TrackId, u32, usize, u32, usize),
/// Set a parameter on a node (track_id, node_index, param_id, value)
GraphSetParameter(TrackId, u32, u32, f32),
/// Set which node receives MIDI events (track_id, node_index, enabled)
GraphSetMidiTarget(TrackId, u32, bool),
/// Set which node is the audio output (track_id, node_index)
GraphSetOutputNode(TrackId, u32),
}
/// Events sent from audio thread back to UI/control thread
@@ -152,4 +172,12 @@ pub enum AudioEvent {
NoteOn(u8, u8),
/// MIDI note stopped playing (note)
NoteOff(u8),
// Node graph events
/// Node added to graph (track_id, node_index, node_type)
GraphNodeAdded(TrackId, u32, String),
/// Connection error occurred (track_id, error_message)
GraphConnectionError(TrackId, String),
/// Graph state changed (for full UI sync)
GraphStateChanged(TrackId),
}
+1 -1
View File
@@ -130,7 +130,7 @@ impl SynthVoice {
pub struct SimpleSynth {
voices: Vec<SynthVoice>,
sample_rate: f32,
pending_events: Vec<MidiEvent>,
pub pending_events: Vec<MidiEvent>,
}
impl SimpleSynth {
+1
View File
@@ -9,6 +9,7 @@ pub mod command;
pub mod dsp;
pub mod effects;
pub mod io;
pub mod tui;
// Re-export commonly used types
pub use audio::{
+64 -806
View File
@@ -1,826 +1,84 @@
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use daw_backend::{load_midi_file, AudioEvent, AudioFile, Clip, CurveType, Engine, ParameterId, PoolAudioFile, Track};
use daw_backend::{AudioEvent, AudioSystem, EventEmitter};
use daw_backend::tui::run_tui;
use std::env;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use std::time::Duration;
use std::sync::{Arc, Mutex};
/// Event emitter that pushes events to a ringbuffer for the TUI
struct TuiEventEmitter {
tx: Arc<Mutex<rtrb::Producer<AudioEvent>>>,
}
impl TuiEventEmitter {
fn new(tx: rtrb::Producer<AudioEvent>) -> Self {
Self {
tx: Arc::new(Mutex::new(tx)),
}
}
}
impl EventEmitter for TuiEventEmitter {
fn emit(&self, event: AudioEvent) {
if let Ok(mut tx) = self.tx.lock() {
let _ = tx.push(event);
}
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Get audio file paths from command line arguments
// Check if user wants the old CLI mode
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} <audio_file1> [audio_file2] [audio_file3] ...", args[0]);
eprintln!("Example: {} track1.wav track2.wav", args[0]);
if args.len() > 1 && args[1] == "--help" {
print_usage();
return Ok(());
}
println!("DAW Backend - Phase 6: Hierarchical Tracks\n");
println!("Lightningbeam DAW - Starting TUI...\n");
println!("Controls:");
println!(" ESC - Enter Command mode (type commands like 'track MyTrack')");
println!(" i - Enter Play mode (play MIDI notes with keyboard)");
println!(" awsedftgyhujkolp;' - Play MIDI notes (chromatic scale in Play mode)");
println!(" r - Release all notes (in Play mode)");
println!(" SPACE - Play/Pause");
println!(" Ctrl+Q - Quit");
println!("\nStarting audio system...");
// Load all audio files
let mut audio_files = Vec::new();
let mut max_sample_rate = 0;
let mut max_channels = 0;
// Create event channel for TUI
let (event_tx, event_rx) = rtrb::RingBuffer::new(256);
let emitter = Arc::new(TuiEventEmitter::new(event_tx));
for (i, path) in args.iter().skip(1).enumerate() {
println!("Loading file {}: {}", i + 1, path);
match AudioFile::load(path) {
Ok(audio_file) => {
let duration = audio_file.frames as f64 / audio_file.sample_rate as f64;
println!(
" {} Hz, {} channels, {} frames ({:.2}s)",
audio_file.sample_rate, audio_file.channels, audio_file.frames, duration
);
// Initialize audio system with event emitter
let mut audio_system = AudioSystem::new(Some(emitter))?;
max_sample_rate = max_sample_rate.max(audio_file.sample_rate);
max_channels = max_channels.max(audio_file.channels);
println!("Audio system initialized:");
println!(" Sample rate: {} Hz", audio_system.sample_rate);
println!(" Channels: {}", audio_system.channels);
audio_files.push((
Path::new(path)
.file_name()
.unwrap()
.to_string_lossy()
.to_string(),
PathBuf::from(path),
audio_file,
));
}
Err(e) => {
eprintln!(" Error loading {}: {}", path, e);
eprintln!(" Skipping this file...");
}
}
}
// Create a test MIDI track to verify event handling
audio_system.controller.create_midi_track("Test Track".to_string());
if audio_files.is_empty() {
eprintln!("No audio files loaded. Exiting.");
return Ok(());
}
println!("\nTUI starting...\n");
std::thread::sleep(std::time::Duration::from_millis(100)); // Give time for event
println!("\nProject settings:");
println!(" Sample rate: {} Hz", max_sample_rate);
println!(" Channels: {}", max_channels);
println!(" Files: {}", audio_files.len());
// Initialize cpal
let host = cpal::default_host();
let device = host
.default_output_device()
.ok_or("No output device available")?;
println!("\nUsing audio device: {}", device.name()?);
// Get the default output config to determine sample format
let default_config = device.default_output_config()?;
let sample_format = default_config.sample_format();
// Create a custom config matching the project settings
let config = cpal::StreamConfig {
channels: max_channels as u16,
sample_rate: cpal::SampleRate(max_sample_rate),
buffer_size: cpal::BufferSize::Default,
};
println!("Output config: {:?} with format {:?}", config, sample_format);
// Create lock-free command and event queues
let (command_tx, command_rx) = rtrb::RingBuffer::<daw_backend::Command>::new(256);
let (event_tx, event_rx) = rtrb::RingBuffer::<AudioEvent>::new(256);
// Create the audio engine
let mut engine = Engine::new(max_sample_rate, max_channels, command_rx, event_tx);
// Add all files to the audio pool and create tracks with clips
let track_ids = Arc::new(Mutex::new(Vec::new()));
let mut clip_info = Vec::new(); // Store (track_id, clip_id, name, duration)
let mut max_duration = 0.0f64;
let mut clip_id_counter = 0u32;
println!("\nCreating tracks and clips:");
for (name, path, audio_file) in audio_files.into_iter() {
let duration = audio_file.frames as f64 / audio_file.sample_rate as f64;
max_duration = max_duration.max(duration);
// Add audio file to pool
let pool_file = PoolAudioFile::new(
path,
audio_file.data,
audio_file.channels,
audio_file.sample_rate,
);
let pool_index = engine.audio_pool_mut().add_file(pool_file);
// Create track (the ID passed to Track::new is ignored; Project assigns IDs)
let mut track = Track::new(0, name.clone());
// Create clip that plays the entire file starting at time 0
let clip_id = clip_id_counter;
let clip = Clip::new(
clip_id,
pool_index,
0.0, // start at beginning of timeline
duration, // full duration
0.0, // no offset into file
);
clip_id_counter += 1;
track.add_clip(clip);
// Capture the ACTUAL track ID assigned by the project
let actual_track_id = engine.add_track(track);
track_ids.lock().unwrap().push(actual_track_id);
clip_info.push((actual_track_id, clip_id, name.clone(), duration));
println!(" Track {}: {} (clip {} at 0.0s, duration {:.2}s)", actual_track_id, name, clip_id, duration);
}
println!("\nTimeline duration: {:.2}s", max_duration);
let mut controller = engine.get_controller(command_tx);
// Build the output stream - Engine moves into the audio thread (no Arc, no Mutex!)
let stream = match sample_format {
cpal::SampleFormat::F32 => build_stream::<f32>(&device, &config, engine)?,
cpal::SampleFormat::I16 => build_stream::<i16>(&device, &config, engine)?,
cpal::SampleFormat::U16 => build_stream::<u16>(&device, &config, engine)?,
_ => return Err("Unsupported sample format".into()),
};
// Start the audio stream
stream.play()?;
println!("\nAudio stream started!");
print_help();
{
let ids = track_ids.lock().unwrap();
print_status(0.0, max_duration, &ids);
}
// Spawn event listener thread
// Wrap event receiver for TUI
let event_rx = Arc::new(Mutex::new(event_rx));
let event_rx_clone = Arc::clone(&event_rx);
let track_ids_clone = Arc::clone(&track_ids);
let _event_thread = thread::spawn(move || {
loop {
thread::sleep(Duration::from_millis(50));
let mut rx = event_rx_clone.lock().unwrap();
while let Ok(event) = rx.pop() {
match event {
AudioEvent::PlaybackPosition(pos) => {
// Clear the line and show position
print!("\r\x1b[K");
print!("Position: {:.2}s / {:.2}s", pos, max_duration);
print!(" [");
let bar_width = 30;
let filled = ((pos / max_duration) * bar_width as f64) as usize;
for i in 0..bar_width {
if i < filled {
print!("=");
} else if i == filled {
print!(">");
} else {
print!(" ");
}
}
print!("]");
io::stdout().flush().ok();
}
AudioEvent::PlaybackStopped => {
print!("\r\x1b[K");
println!("Playback stopped (end of timeline)");
print!("> ");
io::stdout().flush().ok();
}
AudioEvent::BufferUnderrun => {
eprintln!("\nWarning: Buffer underrun detected");
}
AudioEvent::TrackCreated(track_id, is_metatrack, name) => {
print!("\r\x1b[K");
if is_metatrack {
println!("Metatrack {} created: '{}' (ID: {})", track_id, name, track_id);
} else {
println!("Track {} created: '{}' (ID: {})", track_id, name, track_id);
}
track_ids_clone.lock().unwrap().push(track_id);
print!("> ");
io::stdout().flush().ok();
}
AudioEvent::BufferPoolStats(stats) => {
print!("\r\x1b[K");
println!("\n=== Buffer Pool Statistics ===");
println!(" Total buffers: {}", stats.total_buffers);
println!(" Available buffers: {}", stats.available_buffers);
println!(" In-use buffers: {}", stats.in_use_buffers);
println!(" Peak usage: {}", stats.peak_usage);
println!(" Total allocations: {}", stats.total_allocations);
println!(" Buffer size: {} samples", stats.buffer_size);
if stats.total_allocations == 0 {
println!(" Status: \x1b[32mOK\x1b[0m - Zero allocations during playback");
} else {
println!(" Status: \x1b[33mWARNING\x1b[0m - {} allocation(s) occurred", stats.total_allocations);
println!(" Recommendation: Increase initial buffer pool capacity to {}", stats.peak_usage + 2);
}
println!();
print!("> ");
io::stdout().flush().ok();
}
AudioEvent::AutomationLaneCreated(track_id, lane_id, parameter_id) => {
print!("\r\x1b[K");
println!("Automation lane {} created on track {} for parameter {:?}",
lane_id, track_id, parameter_id);
print!("> ");
io::stdout().flush().ok();
}
AudioEvent::AudioFileAdded(pool_index, path) => {
print!("\r\x1b[K");
println!("Audio file added to pool at index {}: '{}'", pool_index, path);
print!("> ");
io::stdout().flush().ok();
}
AudioEvent::ClipAdded(track_id, clip_id) => {
print!("\r\x1b[K");
println!("Clip {} added to track {}", clip_id, track_id);
print!("> ");
io::stdout().flush().ok();
}
AudioEvent::RecordingStarted(track_id, clip_id) => {
print!("\r\x1b[K");
println!("Recording started on track {} (clip {})", track_id, clip_id);
print!("> ");
io::stdout().flush().ok();
}
AudioEvent::RecordingProgress(clip_id, duration) => {
print!("\r\x1b[K");
print!("Recording clip {}: {:.2}s", clip_id, duration);
io::stdout().flush().ok();
}
AudioEvent::RecordingStopped(clip_id, pool_index, _waveform) => {
print!("\r\x1b[K");
println!("Recording stopped (clip {}, pool index {})", clip_id, pool_index);
print!("> ");
io::stdout().flush().ok();
}
AudioEvent::RecordingError(error) => {
print!("\r\x1b[K");
println!("Recording error: {}", error);
print!("> ");
io::stdout().flush().ok();
}
AudioEvent::ProjectReset => {
print!("\r\x1b[K");
println!("Project reset - all tracks and audio cleared");
// Clear the local track list
track_ids_clone.lock().unwrap().clear();
print!("> ");
io::stdout().flush().ok();
}
}
}
}
});
// Simple command loop
loop {
let mut input = String::new();
print!("\r\x1b[K> ");
io::stdout().flush()?;
io::stdin().read_line(&mut input)?;
let input = input.trim();
// Parse input
if input.is_empty() {
controller.play();
println!("Playing...");
} else if input == "q" || input == "quit" {
println!("Quitting...");
break;
} else if input == "s" || input == "stop" {
controller.stop();
println!("Stopped (reset to beginning)");
} else if input == "p" || input == "play" {
controller.play();
println!("Playing...");
} else if input == "pause" {
controller.pause();
println!("Paused");
} else if input.starts_with("seek ") {
// Parse seek time
if let Ok(seconds) = input[5..].trim().parse::<f64>() {
if seconds >= 0.0 {
controller.seek(seconds);
println!("Seeking to {:.2}s", seconds);
} else {
println!("Invalid seek time (must be >= 0.0)");
}
} else {
println!("Invalid seek format. Usage: seek <seconds>");
}
} else if input.starts_with("volume ") {
// Parse: volume <track_id> <volume>
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() == 3 {
if let (Ok(track_id), Ok(volume)) = (parts[1].parse::<u32>(), parts[2].parse::<f32>()) {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
controller.set_track_volume(track_id, volume);
println!("Set track {} volume to {:.2}", track_id, volume);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Invalid format. Usage: volume <track_id> <volume>");
}
} else {
println!("Usage: volume <track_id> <volume>");
}
} else if input.starts_with("mute ") {
// Parse: mute <track_id>
if let Ok(track_id) = input[5..].trim().parse::<u32>() {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
controller.set_track_mute(track_id, true);
println!("Muted track {}", track_id);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Usage: mute <track_id>");
}
} else if input.starts_with("unmute ") {
// Parse: unmute <track_id>
if let Ok(track_id) = input[7..].trim().parse::<u32>() {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
controller.set_track_mute(track_id, false);
println!("Unmuted track {}", track_id);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Usage: unmute <track_id>");
}
} else if input.starts_with("solo ") {
// Parse: solo <track_id>
if let Ok(track_id) = input[5..].trim().parse::<u32>() {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
controller.set_track_solo(track_id, true);
println!("Soloed track {}", track_id);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Usage: solo <track_id>");
}
} else if input.starts_with("unsolo ") {
// Parse: unsolo <track_id>
if let Ok(track_id) = input[7..].trim().parse::<u32>() {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
controller.set_track_solo(track_id, false);
println!("Unsoloed track {}", track_id);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Usage: unsolo <track_id>");
}
} else if input.starts_with("move ") {
// Parse: move <track_id> <clip_id> <new_start_time>
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() == 4 {
if let (Ok(track_id), Ok(clip_id), Ok(time)) =
(parts[1].parse::<u32>(), parts[2].parse::<u32>(), parts[3].parse::<f64>()) {
// Validate track and clip exist
if let Some((_tid, _cid, name, _)) = clip_info.iter().find(|(t, c, _, _)| *t == track_id && *c == clip_id) {
controller.move_clip(track_id, clip_id, time);
println!("Moved clip {} ('{}') on track {} to {:.2}s", clip_id, name, track_id, time);
} else {
println!("Invalid track ID or clip ID");
println!("Available clips:");
for (tid, cid, name, dur) in &clip_info {
println!(" Track {}, Clip {} ('{}', duration {:.2}s)", tid, cid, name, dur);
}
}
} else {
println!("Invalid format. Usage: move <track_id> <clip_id> <time>");
}
} else {
println!("Usage: move <track_id> <clip_id> <time>");
}
} else if input == "tracks" {
let ids = track_ids.lock().unwrap();
println!("Available tracks: {:?}", *ids);
} else if input == "clips" {
// Display clips from the tracked clip_info
println!("Available clips:");
if clip_info.is_empty() {
println!(" (no clips)");
} else {
for (tid, cid, name, dur) in &clip_info {
println!(" Track {}, Clip {} ('{}', duration {:.2}s)", tid, cid, name, dur);
}
}
} else if input.starts_with("gain ") {
// Parse: gain <track_id> <gain_db>
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() == 3 {
if let (Ok(track_id), Ok(gain_db)) = (parts[1].parse::<u32>(), parts[2].parse::<f32>()) {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
controller.add_gain_effect(track_id, gain_db);
println!("Set gain on track {} to {:.1} dB", track_id, gain_db);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Invalid format. Usage: gain <track_id> <gain_db>");
}
} else {
println!("Usage: gain <track_id> <gain_db>");
}
} else if input.starts_with("pan ") {
// Parse: pan <track_id> <pan>
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() == 3 {
if let (Ok(track_id), Ok(pan)) = (parts[1].parse::<u32>(), parts[2].parse::<f32>()) {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
let clamped_pan = pan.clamp(-1.0, 1.0);
controller.add_pan_effect(track_id, clamped_pan);
let pos = if clamped_pan < -0.01 {
format!("{:.0}% left", -clamped_pan * 100.0)
} else if clamped_pan > 0.01 {
format!("{:.0}% right", clamped_pan * 100.0)
} else {
"center".to_string()
};
println!("Set pan on track {} to {} ({:.2})", track_id, pos, clamped_pan);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Invalid format. Usage: pan <track_id> <pan>");
}
} else {
println!("Usage: pan <track_id> <pan> (where pan is -1.0=left, 0.0=center, 1.0=right)");
}
} else if input.starts_with("eq ") {
// Parse: eq <track_id> <low_db> <mid_db> <high_db>
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() == 5 {
if let (Ok(track_id), Ok(low), Ok(mid), Ok(high)) =
(parts[1].parse::<u32>(), parts[2].parse::<f32>(), parts[3].parse::<f32>(), parts[4].parse::<f32>()) {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
controller.add_eq_effect(track_id, low, mid, high);
println!("Set EQ on track {}: Low {:.1} dB, Mid {:.1} dB, High {:.1} dB",
track_id, low, mid, high);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Invalid format. Usage: eq <track_id> <low_db> <mid_db> <high_db>");
}
} else {
println!("Usage: eq <track_id> <low_db> <mid_db> <high_db>");
}
} else if input.starts_with("clearfx ") {
// Parse: clearfx <track_id>
if let Ok(track_id) = input[8..].trim().parse::<u32>() {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
controller.clear_effects(track_id);
println!("Cleared all effects from track {}", track_id);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Usage: clearfx <track_id>");
}
} else if input.starts_with("meta ") {
// Parse: meta <name>
let name = input[5..].trim().to_string();
if !name.is_empty() {
controller.create_metatrack(name.clone());
println!("Created metatrack '{}'", name);
} else {
println!("Usage: meta <name>");
}
} else if input.starts_with("addtometa ") {
// Parse: addtometa <track_id> <metatrack_id>
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() == 3 {
if let (Ok(track_id), Ok(metatrack_id)) = (parts[1].parse::<u32>(), parts[2].parse::<u32>()) {
controller.add_to_metatrack(track_id, metatrack_id);
println!("Added track {} to metatrack {}", track_id, metatrack_id);
} else {
println!("Invalid format. Usage: addtometa <track_id> <metatrack_id>");
}
} else {
println!("Usage: addtometa <track_id> <metatrack_id>");
}
} else if input.starts_with("removefrommeta ") {
// Parse: removefrommeta <track_id>
if let Ok(track_id) = input[15..].trim().parse::<u32>() {
controller.remove_from_metatrack(track_id);
println!("Removed track {} from its metatrack", track_id);
} else {
println!("Usage: removefrommeta <track_id>");
}
} else if input.starts_with("midi ") {
// Parse: midi <name>
let name = input[5..].trim().to_string();
if !name.is_empty() {
controller.create_midi_track(name.clone());
println!("Created MIDI track '{}'", name);
} else {
println!("Usage: midi <name>");
}
} else if input.starts_with("midiclip ") {
// Parse: midiclip <track_id> <start_time> <duration>
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() == 4 {
if let (Ok(track_id), Ok(start_time), Ok(duration)) =
(parts[1].parse::<u32>(), parts[2].parse::<f64>(), parts[3].parse::<f64>()) {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
controller.create_midi_clip(track_id, start_time, duration);
println!("Created MIDI clip on track {} at {:.2}s (duration {:.2}s)",
track_id, start_time, duration);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Invalid format. Usage: midiclip <track_id> <start_time> <duration>");
}
} else {
println!("Usage: midiclip <track_id> <start_time> <duration>");
}
} else if input.starts_with("note ") {
// Parse: note <track_id> <clip_id> <time_offset> <note> <velocity> <duration>
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() == 7 {
if let (Ok(track_id), Ok(clip_id), Ok(time_offset), Ok(note), Ok(velocity), Ok(duration)) =
(parts[1].parse::<u32>(), parts[2].parse::<u32>(), parts[3].parse::<f64>(),
parts[4].parse::<u8>(), parts[5].parse::<u8>(), parts[6].parse::<f64>()) {
if note > 127 || velocity > 127 {
println!("Note and velocity must be 0-127");
} else {
controller.add_midi_note(track_id, clip_id, time_offset, note, velocity, duration);
println!("Added note {} (velocity {}) to clip {} on track {} at offset {:.2}s (duration {:.2}s)",
note, velocity, clip_id, track_id, time_offset, duration);
}
} else {
println!("Invalid format. Usage: note <track_id> <clip_id> <time_offset> <note> <velocity> <duration>");
}
} else {
println!("Usage: note <track_id> <clip_id> <time_offset> <note> <velocity> <duration>");
}
} else if input.starts_with("loadmidi ") {
// Parse: loadmidi <track_id> <file_path> [start_time]
let parts: Vec<&str> = input.splitn(4, ' ').collect();
if parts.len() >= 3 {
if let Ok(track_id) = parts[1].parse::<u32>() {
let file_path = parts[2];
let start_time = if parts.len() == 4 {
parts[3].parse::<f64>().unwrap_or(0.0)
} else {
0.0
};
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
// Load the MIDI file (this happens on the UI thread, not audio thread)
match load_midi_file(file_path, clip_id_counter, max_sample_rate) {
Ok(mut clip) => {
clip.start_time = start_time;
let event_count = clip.events.len();
let duration = clip.duration;
let clip_id = clip.id;
clip_id_counter += 1;
controller.add_loaded_midi_clip(track_id, clip);
println!("Loaded MIDI file '{}' to track {} as clip {} at {:.2}s ({} events, duration {:.2}s)",
file_path, track_id, clip_id, start_time, event_count, duration);
}
Err(e) => {
println!("Error loading MIDI file: {}", e);
}
}
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Invalid format. Usage: loadmidi <track_id> <file_path> [start_time]");
}
} else {
println!("Usage: loadmidi <track_id> <file_path> [start_time]");
}
} else if input.starts_with("stretch ") {
// Parse: stretch <track_id> <factor>
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() == 3 {
if let (Ok(track_id), Ok(stretch)) = (parts[1].parse::<u32>(), parts[2].parse::<f32>()) {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
controller.set_time_stretch(track_id, stretch);
let speed = if stretch < 0.99 {
format!("{:.0}% speed (slower)", stretch * 100.0)
} else if stretch > 1.01 {
format!("{:.0}% speed (faster)", stretch * 100.0)
} else {
"normal speed".to_string()
};
println!("Set time stretch on track {} to {:.2}x ({})", track_id, stretch, speed);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Invalid format. Usage: stretch <track_id> <factor>");
}
} else {
println!("Usage: stretch <track_id> <factor> (0.5=half speed, 1.0=normal, 2.0=double speed)");
}
} else if input.starts_with("offset ") {
// Parse: offset <track_id> <seconds>
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() == 3 {
if let (Ok(track_id), Ok(offset)) = (parts[1].parse::<u32>(), parts[2].parse::<f64>()) {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
controller.set_offset(track_id, offset);
let direction = if offset > 0.01 {
format!("{:.2}s later", offset)
} else if offset < -0.01 {
format!("{:.2}s earlier", -offset)
} else {
"no offset".to_string()
};
println!("Set time offset on track {} to {:.2}s (content shifted {})", track_id, offset, direction);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Invalid format. Usage: offset <track_id> <seconds>");
}
} else {
println!("Usage: offset <track_id> <seconds> (positive=later, negative=earlier)");
}
} else if input == "stats" || input == "buffers" {
controller.request_buffer_pool_stats();
} else if input.starts_with("autovolume ") {
// Parse: autovolume <track_id> <time> <value>
let parts: Vec<&str> = input.split_whitespace().collect();
if parts.len() == 4 {
if let (Ok(track_id), Ok(time), Ok(value)) =
(parts[1].parse::<u32>(), parts[2].parse::<f64>(), parts[3].parse::<f32>()) {
let ids = track_ids.lock().unwrap();
if ids.contains(&track_id) {
drop(ids);
// Create automation lane (if not exists, will be reused)
controller.create_automation_lane(track_id, ParameterId::TrackVolume);
// Add automation point (note: lane_id=0 is assumed, real app would track this)
controller.add_automation_point(track_id, 0, time, value, CurveType::Linear);
println!("Added volume automation point on track {} at {:.2}s: {:.2}", track_id, time, value);
} else {
println!("Invalid track ID. Available tracks: {:?}", *ids);
}
} else {
println!("Invalid format. Usage: autovolume <track_id> <time> <value>");
}
} else {
println!("Usage: autovolume <track_id> <time> <value>");
println!(" Example: autovolume 0 2.0 0.5 (set volume to 0.5 at 2 seconds)");
}
} else if input == "reset" {
controller.reset();
// Clear local clip info tracking
clip_info.clear();
println!("Resetting project...");
} else if input == "help" || input == "h" {
print_help();
} else {
println!("Unknown command: {}. Type 'help' for commands.", input);
}
}
// Drop the stream to stop playback
drop(stream);
println!("Goodbye!");
// Run the TUI
run_tui(audio_system.controller, event_rx)?;
println!("\nGoodbye!");
Ok(())
}
fn print_help() {
println!("\nTransport Commands:");
println!(" ENTER - Play");
println!(" p, play - Play");
println!(" pause - Pause");
println!(" s, stop - Stop and reset to beginning");
println!(" seek <time> - Seek to position in seconds (e.g. 'seek 10.5')");
println!("\nTrack Commands:");
println!(" tracks - List all track IDs");
println!(" volume <id> <v> - Set track volume (e.g. 'volume 0 0.5' for 50%)");
println!(" mute <id> - Mute a track");
println!(" unmute <id> - Unmute a track");
println!(" solo <id> - Solo a track (only soloed tracks play)");
println!(" unsolo <id> - Unsolo a track");
println!("\nClip Commands:");
println!(" clips - List all clips");
println!(" move <t> <c> <s> - Move clip to new timeline position");
println!(" (e.g. 'move 0 0 5.0' moves clip 0 on track 0 to 5.0s)");
println!("\nEffect Commands:");
println!(" gain <id> <db> - Add/update gain effect (e.g. 'gain 0 6.0' for +6dB)");
println!(" pan <id> <pan> - Add/update pan effect (-1.0=left, 0.0=center, 1.0=right)");
println!(" eq <id> <l> <m> <h> - Add/update 3-band EQ (low, mid, high in dB)");
println!(" (e.g. 'eq 0 3.0 0.0 -2.0')");
println!(" clearfx <id> - Clear all effects from a track");
println!("\nMetatrack Commands:");
println!(" meta <name> - Create a new metatrack");
println!(" addtometa <t> <m> - Add track to metatrack (e.g. 'addtometa 0 2')");
println!(" removefrommeta <t> - Remove track from its parent metatrack");
println!(" stretch <id> <f> - Set time stretch (0.5=half speed, 1.0=normal, 2.0=double)");
println!(" offset <id> <s> - Set time offset in seconds (positive=later, negative=earlier)");
println!("\nMIDI Commands:");
println!(" midi <name> - Create a new MIDI track");
println!(" midiclip <t> <s> <d> - Create MIDI clip on track (start, duration)");
println!(" (e.g. 'midiclip 0 0.0 4.0')");
println!(" note <t> <c> <o> <n> <v> <d> - Add note to MIDI clip");
println!(" (track, clip, time_offset, note, velocity, duration)");
println!(" (e.g. 'note 0 0 0.0 60 100 0.5' adds middle C)");
println!(" loadmidi <t> <file> [start] - Load .mid file into track");
println!(" (e.g. 'loadmidi 0 song.mid 0.0')");
println!("\nDiagnostics:");
println!(" stats, buffers - Show buffer pool statistics");
println!("\nProject Commands:");
println!(" reset - Clear all tracks and audio (reset to empty project)");
println!("\nOther:");
println!(" h, help - Show this help");
println!(" q, quit - Quit");
println!();
}
fn print_status(position: f64, duration: f64, track_ids: &[u32]) {
println!("Position: {:.2}s / {:.2}s", position, duration);
println!("Tracks: {:?}", track_ids);
}
fn build_stream<T>(
device: &cpal::Device,
config: &cpal::StreamConfig,
mut engine: Engine,
) -> Result<cpal::Stream, Box<dyn std::error::Error>>
where
T: cpal::Sample + cpal::SizedSample + cpal::FromSample<f32>,
{
let err_fn = |err| eprintln!("Audio stream error: {}", err);
// Preallocate a large buffer for format conversion to avoid allocations in audio callback
// Size it generously to handle typical buffer sizes (up to 8192 samples = 2048 frames * stereo * 2x safety)
let mut conversion_buffer = vec![0.0f32; 16384];
let stream = device.build_output_stream(
config,
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
// NO MUTEX LOCK! Engine lives entirely on audio thread with ownership
// Safety check - if buffer is too small, we have a problem
if conversion_buffer.len() < data.len() {
eprintln!("ERROR: Audio buffer size {} exceeds preallocated buffer size {}",
data.len(), conversion_buffer.len());
return;
}
// Get a slice of the preallocated buffer
let buffer_slice = &mut conversion_buffer[..data.len()];
buffer_slice.fill(0.0);
// Process audio - completely lock-free!
engine.process(buffer_slice);
// Convert f32 samples to output format
for (i, sample) in data.iter_mut().enumerate() {
*sample = cpal::Sample::from_sample(buffer_slice[i]);
}
},
err_fn,
None,
)?;
Ok(stream)
fn print_usage() {
println!("Lightningbeam DAW - Terminal User Interface");
println!("\nUsage: {} [OPTIONS]", env::args().next().unwrap());
println!("\nOptions:");
println!(" --help Show this help message");
println!("\nThe DAW will start in TUI mode with an empty project.");
println!("Use commands to create tracks and load audio:");
println!(" :track <name> - Create MIDI track");
println!(" :audiotrack <name> - Create audio track");
println!(" :play - Start playback");
println!(" :stop - Stop playback");
println!(" :quit - Exit application");
}
+923
View File
@@ -0,0 +1,923 @@
use crate::audio::EngineController;
use crate::command::AudioEvent;
use crate::io::load_midi_file;
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
backend::CrosstermBackend,
layout::{Constraint, Direction, Layout},
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, List, ListItem, Paragraph},
Frame, Terminal,
};
use std::io;
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// TUI application mode
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AppMode {
/// Command mode - type vim-style commands
Command,
/// Play mode - use keyboard to play MIDI notes
Play,
}
/// TUI application state
pub struct TuiApp {
/// Current application mode
mode: AppMode,
/// Command input buffer (for Command mode)
command_input: String,
/// Current playback position (seconds)
playback_position: f64,
/// Whether playback is active
is_playing: bool,
/// Status message to display
status_message: String,
/// List of tracks (track_id, name)
tracks: Vec<(u32, String)>,
/// Currently selected track for MIDI input
selected_track: Option<u32>,
/// Active MIDI notes (currently held down)
active_notes: Vec<u8>,
/// Command history for up/down navigation
command_history: Vec<String>,
/// Current position in command history
history_index: Option<usize>,
/// Clips on timeline: (track_id, clip_id, start_time, duration, name, notes)
/// Notes: Vec<(pitch, time_offset, duration)>
clips: Vec<(u32, u32, f64, f64, String, Vec<(u8, f64, f64)>)>,
/// Next clip ID for locally created clips
next_clip_id: u32,
/// Timeline scroll offset in seconds (start of visible window)
timeline_scroll: f64,
/// Timeline visible duration in seconds (zoom level)
timeline_visible_duration: f64,
}
impl TuiApp {
pub fn new() -> Self {
Self {
mode: AppMode::Command,
command_input: String::new(),
playback_position: 0.0,
is_playing: false,
status_message: "SPACE=play/pause | ←/→ scroll | -/+ zoom | 'i'=Play mode | Type 'help'".to_string(),
tracks: Vec::new(),
selected_track: None,
active_notes: Vec::new(),
command_history: Vec::new(),
history_index: None,
clips: Vec::new(),
next_clip_id: 0,
timeline_scroll: 0.0,
timeline_visible_duration: 10.0, // Show 10 seconds at a time by default
}
}
/// Switch to command mode
pub fn enter_command_mode(&mut self) {
self.mode = AppMode::Command;
self.command_input.clear();
self.history_index = None;
self.status_message = "-- COMMAND -- SPACE=play/pause | ←/→ scroll | -/+ zoom | 'i' for Play mode | Type 'help'".to_string();
}
/// Switch to play mode
pub fn enter_play_mode(&mut self) {
self.mode = AppMode::Play;
self.command_input.clear();
self.status_message = "-- PLAY -- Press '?' for help, 'ESC' for Command mode".to_string();
}
/// Add a character to command input
pub fn push_command_char(&mut self, c: char) {
self.command_input.push(c);
}
/// Remove last character from command input
pub fn pop_command_char(&mut self) {
self.command_input.pop();
}
/// Get the current command input
pub fn command_input(&self) -> &str {
&self.command_input
}
/// Clear command input
pub fn clear_command(&mut self) {
self.command_input.clear();
self.history_index = None;
}
/// Add command to history
pub fn add_to_history(&mut self, command: String) {
if !command.is_empty() && self.command_history.last() != Some(&command) {
self.command_history.push(command);
}
}
/// Navigate command history up
pub fn history_up(&mut self) {
if self.command_history.is_empty() {
return;
}
let new_index = match self.history_index {
None => Some(self.command_history.len() - 1),
Some(0) => Some(0),
Some(i) => Some(i - 1),
};
if let Some(idx) = new_index {
self.history_index = Some(idx);
self.command_input = self.command_history[idx].clone();
}
}
/// Navigate command history down
pub fn history_down(&mut self) {
match self.history_index {
None => {}
Some(i) if i >= self.command_history.len() - 1 => {
self.history_index = None;
self.command_input.clear();
}
Some(i) => {
let new_idx = i + 1;
self.history_index = Some(new_idx);
self.command_input = self.command_history[new_idx].clone();
}
}
}
/// Update playback position and auto-scroll timeline if needed
pub fn update_playback_position(&mut self, position: f64) {
self.playback_position = position;
// Auto-scroll to keep playhead in view when playing
if self.is_playing {
// Keep playhead in the visible window, with some margin
let margin = self.timeline_visible_duration * 0.1; // 10% margin
// If playhead is ahead of visible window, scroll forward
if position > self.timeline_scroll + self.timeline_visible_duration - margin {
self.timeline_scroll = (position - self.timeline_visible_duration * 0.5).max(0.0);
}
// If playhead is behind visible window, scroll backward
else if position < self.timeline_scroll + margin {
self.timeline_scroll = (position - margin).max(0.0);
}
}
}
/// Set playing state
pub fn set_playing(&mut self, playing: bool) {
self.is_playing = playing;
}
/// Set status message
pub fn set_status(&mut self, message: String) {
self.status_message = message;
}
/// Add a track to the UI
pub fn add_track(&mut self, track_id: u32, name: String) {
self.tracks.push((track_id, name));
// Auto-select first MIDI track for playing
if self.selected_track.is_none() {
self.selected_track = Some(track_id);
}
}
/// Clear all tracks
pub fn clear_tracks(&mut self) {
self.tracks.clear();
self.clips.clear();
self.selected_track = None;
self.next_clip_id = 0;
self.timeline_scroll = 0.0;
}
/// Select a track by index
pub fn select_track(&mut self, index: usize) {
if let Some((track_id, _)) = self.tracks.get(index) {
self.selected_track = Some(*track_id);
}
}
/// Get selected track
pub fn selected_track(&self) -> Option<u32> {
self.selected_track
}
/// Add a clip to the timeline
pub fn add_clip(&mut self, track_id: u32, clip_id: u32, start_time: f64, duration: f64, name: String, notes: Vec<(u8, f64, f64)>) {
self.clips.push((track_id, clip_id, start_time, duration, name, notes));
}
/// Get max timeline duration based on clips
pub fn get_timeline_duration(&self) -> f64 {
self.clips
.iter()
.map(|(_, _, start, dur, _, _)| start + dur)
.max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
.unwrap_or(10.0) // Default to 10 seconds if no clips
}
/// Add an active MIDI note
pub fn add_active_note(&mut self, note: u8) {
if !self.active_notes.contains(&note) {
self.active_notes.push(note);
}
}
/// Remove an active MIDI note
pub fn remove_active_note(&mut self, note: u8) {
self.active_notes.retain(|&n| n != note);
}
/// Get current mode
pub fn mode(&self) -> AppMode {
self.mode
}
/// Scroll timeline left
pub fn scroll_timeline_left(&mut self) {
let scroll_amount = self.timeline_visible_duration * 0.2; // Scroll by 20% of visible duration
self.timeline_scroll = (self.timeline_scroll - scroll_amount).max(0.0);
}
/// Scroll timeline right
pub fn scroll_timeline_right(&mut self) {
let scroll_amount = self.timeline_visible_duration * 0.2; // Scroll by 20% of visible duration
let max_duration = self.get_timeline_duration();
self.timeline_scroll = (self.timeline_scroll + scroll_amount).min(max_duration - self.timeline_visible_duration).max(0.0);
}
/// Zoom timeline in (show less time, more detail)
pub fn zoom_timeline_in(&mut self) {
self.timeline_visible_duration = (self.timeline_visible_duration * 0.8).max(1.0); // Min 1 second visible
}
/// Zoom timeline out (show more time, less detail)
pub fn zoom_timeline_out(&mut self) {
let max_duration = self.get_timeline_duration();
self.timeline_visible_duration = (self.timeline_visible_duration * 1.25).min(max_duration).max(1.0);
}
}
/// Map keyboard keys to MIDI notes
/// Uses chromatic layout: awsedftgyhujkolp;'
/// This provides 1.5 octaves starting from C4 (MIDI note 60)
pub fn key_to_midi_note(key: KeyCode) -> Option<u8> {
let base = 60; // C4
match key {
KeyCode::Char('a') => Some(base), // C4
KeyCode::Char('w') => Some(base + 1), // C#4
KeyCode::Char('s') => Some(base + 2), // D4
KeyCode::Char('e') => Some(base + 3), // D#4
KeyCode::Char('d') => Some(base + 4), // E4
KeyCode::Char('f') => Some(base + 5), // F4
KeyCode::Char('t') => Some(base + 6), // F#4
KeyCode::Char('g') => Some(base + 7), // G4
KeyCode::Char('y') => Some(base + 8), // G#4
KeyCode::Char('h') => Some(base + 9), // A4
KeyCode::Char('u') => Some(base + 10), // A#4
KeyCode::Char('j') => Some(base + 11), // B4
KeyCode::Char('k') => Some(base + 12), // C5
KeyCode::Char('o') => Some(base + 13), // C#5
KeyCode::Char('l') => Some(base + 14), // D5
KeyCode::Char('p') => Some(base + 15), // D#5
KeyCode::Char(';') => Some(base + 16), // E5
KeyCode::Char('\'') => Some(base + 17), // F5
_ => None,
}
}
/// Convert pitch % 8 to braille dot bit position
fn pitch_to_braille_bit(pitch_mod_8: u8) -> u8 {
match pitch_mod_8 {
0 => 0x01, // Dot 1
1 => 0x02, // Dot 2
2 => 0x04, // Dot 3
3 => 0x40, // Dot 7
4 => 0x08, // Dot 4
5 => 0x10, // Dot 5
6 => 0x20, // Dot 6
7 => 0x80, // Dot 8
_ => 0x00,
}
}
/// Draw the timeline view with clips
fn draw_timeline(f: &mut Frame, area: ratatui::layout::Rect, app: &TuiApp) {
let num_tracks = app.tracks.len();
// Use visible duration for the timeline window
let visible_start = app.timeline_scroll;
let visible_end = app.timeline_scroll + app.timeline_visible_duration;
// Create the timeline block with visible range
let block = Block::default()
.borders(Borders::ALL)
.title(format!("Timeline ({:.1}s - {:.1}s) | ←/→ scroll | -/+ zoom", visible_start, visible_end));
let inner_area = block.inner(area);
f.render_widget(block, area);
// Calculate dimensions
let width = inner_area.width as usize;
if width == 0 || num_tracks == 0 {
return;
}
// Fixed track height: 2 lines per track
let track_height = 2;
// Build timeline content with braille characters
let mut lines: Vec<Line> = Vec::new();
for track_idx in 0..num_tracks {
let track_id = if let Some((id, _)) = app.tracks.get(track_idx) {
*id
} else {
continue;
};
// Create exactly 2 lines for this track
for _ in 0..track_height {
let mut spans = Vec::new();
// Build the timeline character by character
for char_x in 0..width {
// Map character position to time, using scroll offset
let time_pos = visible_start + (char_x as f64 / width as f64) * app.timeline_visible_duration;
// Check if playhead is at this position
let is_playhead = (time_pos - app.playback_position).abs() < (app.timeline_visible_duration / width as f64);
// Find all notes active at this time position on this track
let mut braille_pattern: u8 = 0;
let mut has_notes = false;
for (clip_track_id, _clip_id, clip_start, _clip_duration, _name, notes) in &app.clips {
if *clip_track_id == track_id {
// Check each note in this clip
for (pitch, note_offset, note_duration) in notes {
let note_start = clip_start + note_offset;
let note_end = note_start + note_duration;
// Is this note active at current time position?
if time_pos >= note_start && time_pos < note_end {
let pitch_mod = pitch % 8;
braille_pattern |= pitch_to_braille_bit(pitch_mod);
has_notes = true;
}
}
}
}
// Determine color
let color = if Some(track_id) == app.selected_track {
Color::Yellow
} else {
Color::Cyan
};
// Create span
if is_playhead {
// Playhead: red background
if has_notes {
// Show white notes with red background
let braille_char = char::from_u32(0x2800 + braille_pattern as u32).unwrap_or(' ');
spans.push(Span::styled(braille_char.to_string(), Style::default().fg(Color::White).bg(Color::Red)));
} else {
spans.push(Span::styled(" ", Style::default().bg(Color::Red)));
}
} else if has_notes {
// Show white braille pattern on colored background
let braille_char = char::from_u32(0x2800 + braille_pattern as u32).unwrap_or(' ');
spans.push(Span::styled(braille_char.to_string(), Style::default().fg(Color::White).bg(color)));
} else {
// Empty space
spans.push(Span::raw(" "));
}
}
lines.push(Line::from(spans));
}
}
let paragraph = Paragraph::new(lines);
f.render_widget(paragraph, inner_area);
}
/// Draw the TUI
pub fn draw_ui(f: &mut Frame, app: &TuiApp) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Title bar
Constraint::Min(10), // Main content
Constraint::Length(3), // Status bar
Constraint::Length(1), // Command line
])
.split(f.size());
// Title bar
let title = Paragraph::new("Lightningbeam DAW")
.style(Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD))
.block(Block::default().borders(Borders::ALL));
f.render_widget(title, chunks[0]);
// Main content area - split into tracks and timeline
let content_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(20), Constraint::Percentage(80)])
.split(chunks[1]);
// Tracks list - each track gets 2 lines to match timeline
let track_items: Vec<ListItem> = app
.tracks
.iter()
.map(|(id, name)| {
let style = if app.selected_track == Some(*id) {
Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD)
} else {
Style::default()
};
// Create a 2-line item: track info on first line, empty second line
let lines = vec![
Line::from(format!("T{}: {}", id, name)),
Line::from(""),
];
ListItem::new(lines).style(style)
})
.collect();
let tracks_list = List::new(track_items)
.block(Block::default().borders(Borders::ALL).title("Tracks"));
f.render_widget(tracks_list, content_chunks[0]);
// Timeline area - split vertically into playback info and timeline view
let timeline_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(4), Constraint::Min(5)])
.split(content_chunks[1]);
// Playback info
let playback_info = vec![
Line::from(vec![
Span::raw("Position: "),
Span::styled(
format!("{:.2}s", app.playback_position),
Style::default().fg(Color::Green),
),
Span::raw(" | Status: "),
Span::styled(
if app.is_playing { "Playing" } else { "Stopped" },
if app.is_playing {
Style::default().fg(Color::Green)
} else {
Style::default().fg(Color::Red)
},
),
]),
Line::from(format!("Active Notes: {}",
app.active_notes
.iter()
.map(|n| format!("{} ", n))
.collect::<String>()
)),
];
let info = Paragraph::new(playback_info)
.block(Block::default().borders(Borders::ALL).title("Playback"));
f.render_widget(info, timeline_chunks[0]);
// Draw timeline
draw_timeline(f, timeline_chunks[1], app);
// Status bar
let mode_indicator = match app.mode {
AppMode::Command => "COMMAND",
AppMode::Play => "PLAY",
};
let status_text = format!("Mode: {} | {}", mode_indicator, app.status_message);
let status_bar = Paragraph::new(status_text)
.style(Style::default().fg(Color::White))
.block(Block::default().borders(Borders::ALL));
f.render_widget(status_bar, chunks[2]);
// Command line
let command_line = if app.mode == AppMode::Command {
format!(":{}", app.command_input)
} else {
String::from("ESC=cmd mode | awsedftgyhujkolp;'=notes | R=release notes | ?=help | SPACE=play/pause")
};
let cmd_widget = Paragraph::new(command_line).style(Style::default().fg(Color::Yellow));
f.render_widget(cmd_widget, chunks[3]);
}
/// Run the TUI application
pub fn run_tui(
mut controller: EngineController,
event_rx: Arc<Mutex<rtrb::Consumer<AudioEvent>>>,
) -> Result<(), Box<dyn std::error::Error>> {
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Create app state
let mut app = TuiApp::new();
// Main loop
loop {
// Draw UI
terminal.draw(|f| draw_ui(f, &app))?;
// Poll for audio events
if let Ok(mut rx) = event_rx.lock() {
while let Ok(event) = rx.pop() {
match event {
AudioEvent::PlaybackPosition(pos) => {
app.update_playback_position(pos);
}
AudioEvent::PlaybackStopped => {
app.set_playing(false);
}
AudioEvent::TrackCreated(track_id, _, name) => {
app.add_track(track_id, name);
}
AudioEvent::RecordingStopped(clip_id, _pool_index, _waveform) => {
// Update status
app.set_status(format!("Recording stopped - Clip {}", clip_id));
}
AudioEvent::ProjectReset => {
app.clear_tracks();
app.set_status("Project reset".to_string());
}
_ => {}
}
}
}
// Handle keyboard input with timeout
if event::poll(Duration::from_millis(100))? {
if let Event::Key(key) = event::read()? {
match app.mode() {
AppMode::Command => {
match key.code {
KeyCode::Left => {
// Scroll timeline left only if command buffer is empty
if app.command_input().is_empty() {
app.scroll_timeline_left();
}
}
KeyCode::Right => {
// Scroll timeline right only if command buffer is empty
if app.command_input().is_empty() {
app.scroll_timeline_right();
}
}
KeyCode::Char('-') | KeyCode::Char('_') => {
// Zoom out only if command buffer is empty
if app.command_input().is_empty() {
app.zoom_timeline_out();
}
}
KeyCode::Char('+') | KeyCode::Char('=') => {
// Zoom in only if command buffer is empty
if app.command_input().is_empty() {
app.zoom_timeline_in();
}
}
KeyCode::Char(' ') => {
// Spacebar toggles play/pause only if command buffer is empty
// Otherwise, add space to command
if app.command_input().is_empty() {
if app.is_playing {
controller.pause();
app.set_playing(false);
app.set_status("Paused".to_string());
} else {
controller.play();
app.set_playing(true);
app.set_status("Playing".to_string());
}
} else {
app.push_command_char(' ');
}
}
KeyCode::Esc => {
app.clear_command();
}
KeyCode::Enter => {
let command = app.command_input().to_string();
app.add_to_history(command.clone());
// Execute command
match execute_command(&command, &mut controller, &mut app) {
Err(e) if e == "Quit requested" => {
break; // Exit the application
}
Err(e) => {
app.set_status(format!("Error: {}", e));
}
Ok(_) => {}
}
app.clear_command();
}
KeyCode::Backspace => {
app.pop_command_char();
}
KeyCode::Up => {
app.history_up();
}
KeyCode::Down => {
app.history_down();
}
KeyCode::Char('i') => {
// Only switch to Play mode if command buffer is empty
if app.command_input().is_empty() {
app.enter_play_mode();
} else {
app.push_command_char('i');
}
}
KeyCode::Char(c) => {
app.push_command_char(c);
}
_ => {}
}
}
AppMode::Play => {
// Check for mode switch first
if key.code == KeyCode::Esc {
app.enter_command_mode();
continue;
}
// Check for quit
if key.code == KeyCode::Char('q') && key.modifiers.contains(KeyModifiers::CONTROL) {
break;
}
// Handle MIDI note playing
if let Some(note) = key_to_midi_note(key.code) {
if let Some(track_id) = app.selected_track() {
// Release all previous notes before playing new one
for prev_note in app.active_notes.clone() {
controller.send_midi_note_off(track_id, prev_note);
}
app.active_notes.clear();
// Play the new note
controller.send_midi_note_on(track_id, note, 100);
app.add_active_note(note);
}
} else {
// Handle other play mode shortcuts
match key.code {
KeyCode::Char(' ') => {
// Release all notes and toggle play/pause
if let Some(track_id) = app.selected_track() {
for note in app.active_notes.clone() {
controller.send_midi_note_off(track_id, note);
}
app.active_notes.clear();
}
if app.is_playing {
controller.pause();
app.set_playing(false);
} else {
controller.play();
app.set_playing(true);
}
}
KeyCode::Char('s') if key.modifiers.contains(KeyModifiers::CONTROL) => {
// Release all notes and stop
if let Some(track_id) = app.selected_track() {
for note in app.active_notes.clone() {
controller.send_midi_note_off(track_id, note);
}
app.active_notes.clear();
}
controller.stop();
app.set_playing(false);
}
KeyCode::Char('r') | KeyCode::Char('R') => {
// Release all notes manually (r for release)
if let Some(track_id) = app.selected_track() {
for note in app.active_notes.clone() {
controller.send_midi_note_off(track_id, note);
}
app.active_notes.clear();
}
app.set_status("All notes released".to_string());
}
KeyCode::Char('?') | KeyCode::Char('h') | KeyCode::Char('H') => {
app.set_status("Play Mode: awsedftgyhujkolp;'=notes | R=release | SPACE=play/pause | ESC=command | Ctrl+Q=quit".to_string());
}
_ => {}
}
}
}
}
}
}
}
// Restore terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
Ok(())
}
/// Execute a command string
fn execute_command(
command: &str,
controller: &mut EngineController,
app: &mut TuiApp,
) -> Result<(), String> {
let parts: Vec<&str> = command.trim().split_whitespace().collect();
if parts.is_empty() {
return Ok(());
}
match parts[0] {
"play" => {
controller.play();
app.set_playing(true);
app.set_status("Playing".to_string());
}
"pause" => {
controller.pause();
app.set_playing(false);
app.set_status("Paused".to_string());
}
"stop" => {
controller.stop();
app.set_playing(false);
app.set_status("Stopped".to_string());
}
"seek" => {
if parts.len() < 2 {
return Err("Usage: seek <seconds>".to_string());
}
let pos: f64 = parts[1].parse().map_err(|_| "Invalid position")?;
controller.seek(pos);
app.set_status(format!("Seeked to {:.2}s", pos));
}
"track" => {
if parts.len() < 2 {
return Err("Usage: track <name>".to_string());
}
let name = parts[1..].join(" ");
controller.create_midi_track(name.clone());
app.set_status(format!("Created MIDI track: {}", name));
}
"audiotrack" => {
if parts.len() < 2 {
return Err("Usage: audiotrack <name>".to_string());
}
let name = parts[1..].join(" ");
controller.create_audio_track(name.clone());
app.set_status(format!("Created audio track: {}", name));
}
"select" => {
if parts.len() < 2 {
return Err("Usage: select <track_number>".to_string());
}
let idx: usize = parts[1].parse().map_err(|_| "Invalid track number")?;
app.select_track(idx);
app.set_status(format!("Selected track {}", idx));
}
"clip" => {
if parts.len() < 4 {
return Err("Usage: clip <track_id> <start_time> <duration>".to_string());
}
let track_id: u32 = parts[1].parse().map_err(|_| "Invalid track ID")?;
let start_time: f64 = parts[2].parse().map_err(|_| "Invalid start time")?;
let duration: f64 = parts[3].parse().map_err(|_| "Invalid duration")?;
// Add clip to local UI state (empty clip, no notes)
let clip_id = app.next_clip_id;
app.next_clip_id += 1;
app.add_clip(track_id, clip_id, start_time, duration, format!("Clip {}", clip_id), Vec::new());
controller.create_midi_clip(track_id, start_time, duration);
app.set_status(format!("Created MIDI clip on track {} at {:.2}s for {:.2}s", track_id, start_time, duration));
}
"loadmidi" => {
if parts.len() < 3 {
return Err("Usage: loadmidi <track_id> <file_path> [start_time]".to_string());
}
let track_id: u32 = parts[1].parse().map_err(|_| "Invalid track ID")?;
let file_path = parts[2];
let start_time: f64 = if parts.len() >= 4 {
parts[3].parse().unwrap_or(0.0)
} else {
0.0
};
// Load the MIDI file
match load_midi_file(file_path, app.next_clip_id, 48000) {
Ok(mut midi_clip) => {
midi_clip.start_time = start_time;
let clip_id = midi_clip.id;
let duration = midi_clip.duration;
let event_count = midi_clip.events.len();
// Extract note data for visualization
let mut notes = Vec::new();
let mut active_notes: std::collections::HashMap<u8, f64> = std::collections::HashMap::new();
let sample_rate = 48000.0; // Sample rate used for loading MIDI
for event in &midi_clip.events {
let status = event.status & 0xF0;
let time_seconds = event.timestamp as f64 / sample_rate;
match status {
0x90 if event.data2 > 0 => {
// Note on
active_notes.insert(event.data1, time_seconds);
}
0x80 | 0x90 => {
// Note off (or note on with velocity 0)
if let Some(start) = active_notes.remove(&event.data1) {
let note_duration = time_seconds - start;
notes.push((event.data1, start, note_duration));
}
}
_ => {}
}
}
// Add to local UI state with note data
app.add_clip(track_id, clip_id, start_time, duration, file_path.to_string(), notes);
app.next_clip_id += 1;
// Send to audio engine
controller.add_loaded_midi_clip(track_id, midi_clip);
app.set_status(format!("Loaded {} ({} events, {:.2}s) to track {} at {:.2}s",
file_path, event_count, duration, track_id, start_time));
}
Err(e) => {
return Err(format!("Failed to load MIDI file: {}", e));
}
}
}
"reset" => {
controller.reset();
app.clear_tracks();
app.set_status("Project reset".to_string());
}
"q" | "quit" => {
return Err("Quit requested".to_string());
}
"help" | "h" | "?" => {
// Show comprehensive help
let help_msg = concat!(
"Commands: ",
"play | pause | stop | seek <s> | ",
"track <name> | audiotrack <name> | select <idx> | ",
"clip <track_id> <start> <dur> | ",
"loadmidi <track_id> <file> [start] | ",
"reset | quit | help | ",
"Keys: ←/→ scroll | -/+ zoom"
);
app.set_status(help_msg.to_string());
}
_ => {
return Err(format!("Unknown command: '{}'. Type 'help' for commands", parts[0]));
}
}
Ok(())
}