Give metatracks explicit node graphs
This commit is contained in:
@@ -259,12 +259,6 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Process live MIDI input from all MIDI tracks
|
||||
fn process_live_midi(&mut self, output: &mut [f32]) {
|
||||
// Process all MIDI tracks to handle live input
|
||||
self.project.process_live_midi(output, self.sample_rate, self.channels);
|
||||
}
|
||||
|
||||
/// Process audio callback - called from the audio thread
|
||||
pub fn process(&mut self, output: &mut [f32]) {
|
||||
let t_start = if self.debug_audio { Some(std::time::Instant::now()) } else { None };
|
||||
@@ -349,6 +343,7 @@ impl Engine {
|
||||
playhead_seconds,
|
||||
self.sample_rate,
|
||||
self.channels,
|
||||
false,
|
||||
);
|
||||
|
||||
// Copy mix to output
|
||||
@@ -394,8 +389,25 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Not playing, but process live MIDI input
|
||||
self.process_live_midi(output);
|
||||
// Not playing: render live MIDI (keyboard input + note-off tails) through the
|
||||
// normal group hierarchy so mixer gain is correctly applied.
|
||||
let playhead_seconds = self.playhead as f64 / self.sample_rate as f64;
|
||||
if self.mix_buffer.len() != output.len() {
|
||||
self.mix_buffer.resize(output.len(), 0.0);
|
||||
}
|
||||
if self.buffer_pool.buffer_size() != output.len() {
|
||||
self.buffer_pool = BufferPool::new(8, output.len());
|
||||
}
|
||||
self.project.render(
|
||||
&mut self.mix_buffer,
|
||||
&self.audio_pool,
|
||||
&mut self.buffer_pool,
|
||||
playhead_seconds,
|
||||
self.sample_rate,
|
||||
self.channels,
|
||||
true, // live_only
|
||||
);
|
||||
output.copy_from_slice(&self.mix_buffer);
|
||||
}
|
||||
|
||||
// Compute stereo output peaks for master VU meter (independent of playback state)
|
||||
@@ -1224,6 +1236,9 @@ impl Engine {
|
||||
eprintln!("[DEBUG] Found Audio track, using effects_graph");
|
||||
Some(&mut track.effects_graph)
|
||||
},
|
||||
Some(TrackNode::Group(track)) => {
|
||||
Some(&mut track.audio_graph)
|
||||
},
|
||||
_ => {
|
||||
eprintln!("[DEBUG] Track not found or invalid type!");
|
||||
None
|
||||
@@ -1266,6 +1281,7 @@ impl Engine {
|
||||
eprintln!("[DEBUG] Emitting GraphNodeAdded event: track_id={}, node_id={}, node_type={}", track_id, node_id, node_type);
|
||||
// Emit success event
|
||||
let _ = self.event_tx.push(AudioEvent::GraphNodeAdded(track_id, node_id, node_type.clone()));
|
||||
self.set_track_graph_is_default(track_id, false);
|
||||
} else {
|
||||
eprintln!("[DEBUG] Graph was None, node not added!");
|
||||
}
|
||||
@@ -1312,6 +1328,7 @@ impl Engine {
|
||||
let graph = match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(track)) => Some(&mut track.instrument_graph),
|
||||
Some(TrackNode::Audio(track)) => Some(&mut track.effects_graph),
|
||||
Some(TrackNode::Group(track)) => Some(&mut track.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
@@ -1319,6 +1336,7 @@ impl Engine {
|
||||
graph.remove_node(node_idx);
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
}
|
||||
self.set_track_graph_is_default(track_id, false);
|
||||
}
|
||||
|
||||
Command::GraphConnect(track_id, from, from_port, to, to_port) => {
|
||||
@@ -1333,6 +1351,9 @@ impl Engine {
|
||||
eprintln!("[DEBUG] Found Audio track for connection");
|
||||
Some(&mut track.effects_graph)
|
||||
},
|
||||
Some(TrackNode::Group(track)) => {
|
||||
Some(&mut track.audio_graph)
|
||||
},
|
||||
_ => {
|
||||
eprintln!("[DEBUG] Track not found for connection!");
|
||||
None
|
||||
@@ -1347,6 +1368,7 @@ impl Engine {
|
||||
Ok(()) => {
|
||||
eprintln!("[DEBUG] Connection successful!");
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
self.set_track_graph_is_default(track_id, false);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[DEBUG] Connection failed: {:?}", e);
|
||||
@@ -1443,6 +1465,7 @@ impl Engine {
|
||||
eprintln!("[AUDIO ENGINE] Found audio track, disconnecting in effects_graph");
|
||||
Some(&mut track.effects_graph)
|
||||
}
|
||||
Some(TrackNode::Group(track)) => Some(&mut track.audio_graph),
|
||||
_ => {
|
||||
eprintln!("[AUDIO ENGINE] Track not found!");
|
||||
None
|
||||
@@ -1455,12 +1478,14 @@ impl Engine {
|
||||
eprintln!("[AUDIO ENGINE] Disconnect completed");
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
}
|
||||
self.set_track_graph_is_default(track_id, false);
|
||||
}
|
||||
|
||||
Command::GraphSetParameter(track_id, node_index, param_id, value) => {
|
||||
let graph = match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(track)) => Some(&mut track.instrument_graph),
|
||||
Some(TrackNode::Audio(track)) => Some(&mut track.effects_graph),
|
||||
Some(TrackNode::Group(track)) => Some(&mut track.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
@@ -1469,12 +1494,14 @@ impl Engine {
|
||||
graph_node.node.set_parameter(param_id, value);
|
||||
}
|
||||
}
|
||||
self.set_track_graph_is_default(track_id, false);
|
||||
}
|
||||
|
||||
Command::GraphSetNodePosition(track_id, node_index, x, y) => {
|
||||
let graph = match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(track)) => Some(&mut track.instrument_graph),
|
||||
Some(TrackNode::Audio(track)) => Some(&mut track.effects_graph),
|
||||
Some(TrackNode::Group(track)) => Some(&mut track.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
@@ -1505,6 +1532,7 @@ impl Engine {
|
||||
let graph = match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(track)) => Some(&mut track.instrument_graph),
|
||||
Some(TrackNode::Audio(track)) => Some(&mut track.effects_graph),
|
||||
Some(TrackNode::Group(track)) => Some(&mut track.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
@@ -1517,6 +1545,7 @@ impl Engine {
|
||||
let graph = match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(track)) => Some(&mut track.instrument_graph),
|
||||
Some(TrackNode::Audio(track)) => Some(&mut track.effects_graph),
|
||||
Some(TrackNode::Group(track)) => Some(&mut track.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
@@ -1545,6 +1574,7 @@ impl Engine {
|
||||
let graph = match self.project.get_track(track_id) {
|
||||
Some(TrackNode::Midi(track)) => Some(&track.instrument_graph),
|
||||
Some(TrackNode::Audio(track)) => Some(&track.effects_graph),
|
||||
Some(TrackNode::Group(track)) => Some(&track.audio_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
@@ -1595,11 +1625,19 @@ impl Engine {
|
||||
match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(track)) => {
|
||||
track.instrument_graph = graph;
|
||||
track.graph_is_default = true;
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
let _ = self.event_tx.push(AudioEvent::GraphPresetLoaded(track_id));
|
||||
}
|
||||
Some(TrackNode::Audio(track)) => {
|
||||
track.effects_graph = graph;
|
||||
track.graph_is_default = true;
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
let _ = self.event_tx.push(AudioEvent::GraphPresetLoaded(track_id));
|
||||
}
|
||||
Some(TrackNode::Group(track)) => {
|
||||
track.audio_graph = graph;
|
||||
track.graph_is_default = true;
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
let _ = self.event_tx.push(AudioEvent::GraphPresetLoaded(track_id));
|
||||
}
|
||||
@@ -1655,6 +1693,82 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
|
||||
Command::SetMetatrackSubtrackGraph(track_id, subtracks) => {
|
||||
let buffer_size = self.buffer_pool.buffer_size();
|
||||
if let Some(TrackNode::Group(metatrack)) = self.project.get_track_mut(track_id) {
|
||||
let current = metatrack.current_subtracks();
|
||||
|
||||
// No-op if subtrack list is unchanged (prevents every-frame graph rebuilds)
|
||||
if current == subtracks {
|
||||
return;
|
||||
}
|
||||
|
||||
if metatrack.graph_is_default {
|
||||
// Default graph: full rebuild with new subtrack layout
|
||||
metatrack.set_subtrack_graph(subtracks.clone(), self.sample_rate, buffer_size);
|
||||
} else {
|
||||
// User-modified graph: incremental port changes only
|
||||
let current_ids: std::collections::HashSet<TrackId> =
|
||||
current.iter().map(|&(id, _)| id).collect();
|
||||
let new_ids: std::collections::HashSet<TrackId> =
|
||||
subtracks.iter().map(|&(id, _)| id).collect();
|
||||
for (id, name) in &subtracks {
|
||||
if !current_ids.contains(id) {
|
||||
metatrack.add_subtrack_to_graph(*id, name.clone(), buffer_size);
|
||||
}
|
||||
}
|
||||
for &(id, _) in ¤t {
|
||||
if !new_ids.contains(&id) {
|
||||
metatrack.remove_subtrack_from_graph(id, buffer_size);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Sync the group's children list so they render through the mixer graph.
|
||||
// `move_to_group` removes each child from root_tracks (or another parent)
|
||||
// and registers it under this group — idempotent if already there.
|
||||
let new_child_ids: Vec<TrackId> = subtracks.iter().map(|&(id, _)| id).collect();
|
||||
for &child_id in &new_child_ids {
|
||||
// Only move if not already a child of this group
|
||||
let already_child = self.project.get_track(track_id)
|
||||
.and_then(|t| if let TrackNode::Group(g) = t { Some(g) } else { None })
|
||||
.map(|g| g.children.contains(&child_id))
|
||||
.unwrap_or(false);
|
||||
if !already_child {
|
||||
self.project.move_to_group(child_id, track_id);
|
||||
}
|
||||
}
|
||||
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
}
|
||||
}
|
||||
|
||||
Command::AddMetatrackSubtrack(track_id, subtrack_id, name) => {
|
||||
let buffer_size = self.buffer_pool.buffer_size();
|
||||
if let Some(TrackNode::Group(metatrack)) = self.project.get_track_mut(track_id) {
|
||||
metatrack.add_subtrack_to_graph(subtrack_id, name, buffer_size);
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
}
|
||||
}
|
||||
|
||||
Command::RemoveMetatrackSubtrack(track_id, subtrack_id) => {
|
||||
let buffer_size = self.buffer_pool.buffer_size();
|
||||
if let Some(TrackNode::Group(metatrack)) = self.project.get_track_mut(track_id) {
|
||||
metatrack.remove_subtrack_from_graph(subtrack_id, buffer_size);
|
||||
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
|
||||
}
|
||||
}
|
||||
|
||||
Command::UpdateMetatrackSubtrackIds(track_id, subtracks) => {
|
||||
let buffer_size = self.buffer_pool.buffer_size();
|
||||
if let Some(TrackNode::Group(metatrack)) = self.project.get_track_mut(track_id) {
|
||||
metatrack.update_subtrack_ids(subtracks, buffer_size);
|
||||
}
|
||||
}
|
||||
|
||||
Command::SetGraphIsDefault(track_id, value) => {
|
||||
self.set_track_graph_is_default(track_id, value);
|
||||
}
|
||||
|
||||
Command::GraphSetScript(track_id, node_id, source) => {
|
||||
use crate::audio::node_graph::nodes::ScriptNode;
|
||||
|
||||
@@ -2169,6 +2283,14 @@ impl Engine {
|
||||
Err(e) => QueryResponse::GraphState(Err(format!("Failed to serialize graph: {:?}", e))),
|
||||
}
|
||||
}
|
||||
Some(TrackNode::Group(track)) => {
|
||||
let graph = &track.audio_graph;
|
||||
let preset = graph.to_preset("temp");
|
||||
match preset.to_json() {
|
||||
Ok(json) => QueryResponse::GraphState(Ok(json)),
|
||||
Err(e) => QueryResponse::GraphState(Err(format!("Failed to serialize graph: {:?}", e))),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
QueryResponse::GraphState(Err(format!("Track {} not found", track_id)))
|
||||
}
|
||||
@@ -2596,6 +2718,15 @@ impl Engine {
|
||||
None => QueryResponse::MidiClipDuplicated(Err(format!("MIDI clip {} not found", clip_id))),
|
||||
}
|
||||
}
|
||||
Query::GetGraphIsDefault(track_id) => {
|
||||
let is_default = match self.project.get_track(track_id) {
|
||||
Some(TrackNode::Midi(track)) => track.graph_is_default,
|
||||
Some(TrackNode::Audio(track)) => track.graph_is_default,
|
||||
Some(TrackNode::Group(track)) => track.graph_is_default,
|
||||
_ => false,
|
||||
};
|
||||
QueryResponse::GraphIsDefault(is_default)
|
||||
}
|
||||
};
|
||||
|
||||
// Send response back
|
||||
@@ -2605,6 +2736,16 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Set graph_is_default on any track type.
|
||||
fn set_track_graph_is_default(&mut self, track_id: TrackId, value: bool) {
|
||||
match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(track)) => track.graph_is_default = value,
|
||||
Some(TrackNode::Audio(track)) => track.graph_is_default = value,
|
||||
Some(TrackNode::Group(track)) => track.graph_is_default = value,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle starting a recording
|
||||
fn handle_start_recording(&mut self, track_id: TrackId, start_time: f64) {
|
||||
use crate::io::WavWriter;
|
||||
@@ -3431,6 +3572,47 @@ impl EngineController {
|
||||
let _ = self.command_tx.push(Command::MultiSamplerClearLayers(track_id, node_id));
|
||||
}
|
||||
|
||||
/// Set the full subtrack list for a metatrack's mixing graph (rebuilds the graph)
|
||||
pub fn set_metatrack_subtrack_graph(&mut self, track_id: TrackId, subtracks: Vec<(TrackId, String)>) {
|
||||
let _ = self.command_tx.push(Command::SetMetatrackSubtrackGraph(track_id, subtracks));
|
||||
}
|
||||
|
||||
/// Add a subtrack port to a metatrack's mixing graph
|
||||
pub fn add_metatrack_subtrack(&mut self, track_id: TrackId, subtrack_id: TrackId, name: String) {
|
||||
let _ = self.command_tx.push(Command::AddMetatrackSubtrack(track_id, subtrack_id, name));
|
||||
}
|
||||
|
||||
/// Remove a subtrack port from a metatrack's mixing graph
|
||||
pub fn remove_metatrack_subtrack(&mut self, track_id: TrackId, subtrack_id: TrackId) {
|
||||
let _ = self.command_tx.push(Command::RemoveMetatrackSubtrack(track_id, subtrack_id));
|
||||
}
|
||||
|
||||
/// Re-associate backend TrackIds with SubtrackInputsNode slots (called after project load)
|
||||
pub fn update_metatrack_subtrack_ids(&mut self, track_id: TrackId, subtracks: Vec<(TrackId, String)>) {
|
||||
let _ = self.command_tx.push(Command::UpdateMetatrackSubtrackIds(track_id, subtracks));
|
||||
}
|
||||
|
||||
/// Set the graph_is_default flag on a track (command, processed async)
|
||||
pub fn set_graph_is_default(&mut self, track_id: TrackId, value: bool) {
|
||||
let _ = self.command_tx.push(Command::SetGraphIsDefault(track_id, value));
|
||||
}
|
||||
|
||||
/// Query whether a track's graph is the auto-generated default (synchronous)
|
||||
pub fn get_graph_is_default(&mut self, track_id: TrackId) -> bool {
|
||||
if let Err(_) = self.query_tx.push(Query::GetGraphIsDefault(track_id)) {
|
||||
return false;
|
||||
}
|
||||
let start = std::time::Instant::now();
|
||||
let timeout = std::time::Duration::from_millis(500);
|
||||
while start.elapsed() < timeout {
|
||||
if let Ok(QueryResponse::GraphIsDefault(v)) = self.query_response_rx.pop() {
|
||||
return v;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_micros(100));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Send a synchronous query and wait for the response
|
||||
/// This blocks until the audio thread processes the query
|
||||
/// Generic method that works with any Query/QueryResponse pair
|
||||
|
||||
@@ -180,6 +180,7 @@ pub fn render_to_memory(
|
||||
playhead,
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
);
|
||||
|
||||
// Calculate how many samples we actually need from this chunk
|
||||
@@ -397,6 +398,7 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
playhead,
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
);
|
||||
|
||||
// Calculate how many samples we need from this chunk
|
||||
@@ -564,6 +566,7 @@ fn export_aac<P: AsRef<Path>>(
|
||||
playhead,
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
);
|
||||
|
||||
// Calculate how many samples we need from this chunk
|
||||
|
||||
@@ -193,6 +193,15 @@ impl AudioGraph {
|
||||
self.graph.add_edge(from, to, Connection { from_port, to_port });
|
||||
self.topo_cache = None;
|
||||
|
||||
// Auto-grow MixerNode: always keep one spare port beyond the connected count
|
||||
let n_incoming = self.graph.edges_directed(to, petgraph::Direction::Incoming).count();
|
||||
if let Some(graph_node) = self.graph.node_weight_mut(to) {
|
||||
use crate::audio::node_graph::nodes::MixerNode;
|
||||
if let Some(mixer) = graph_node.node.as_any_mut().downcast_mut::<MixerNode>() {
|
||||
mixer.ensure_min_ports(n_incoming + 1);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -204,12 +213,24 @@ impl AudioGraph {
|
||||
to: NodeIndex,
|
||||
to_port: usize,
|
||||
) {
|
||||
// Find and remove the edge
|
||||
let mut did_remove = false;
|
||||
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);
|
||||
self.topo_cache = None;
|
||||
did_remove = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Shrink MixerNode back to n_remaining + 1 spare after a disconnect
|
||||
if did_remove {
|
||||
let n_remaining = self.graph.edges_directed(to, petgraph::Direction::Incoming).count();
|
||||
if let Some(graph_node) = self.graph.node_weight_mut(to) {
|
||||
use crate::audio::node_graph::nodes::MixerNode;
|
||||
if let Some(mixer) = graph_node.node.as_any_mut().downcast_mut::<MixerNode>() {
|
||||
mixer.resize(n_remaining + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -716,6 +737,50 @@ impl AudioGraph {
|
||||
self.graph.node_indices()
|
||||
}
|
||||
|
||||
/// Reallocate a node's output buffers to match its current port list.
|
||||
///
|
||||
/// Must be called after `SubtrackInputsNode::update_subtracks` changes the port count,
|
||||
/// since `GraphNode.output_buffers` was allocated at `add_node` time.
|
||||
pub fn reallocate_node_output_buffers(&mut self, idx: NodeIndex, buffer_size: usize) {
|
||||
if let Some(graph_node) = self.graph.node_weight_mut(idx) {
|
||||
let outputs = graph_node.node.outputs();
|
||||
graph_node.output_buffers.clear();
|
||||
for port in outputs.iter() {
|
||||
match port.signal_type {
|
||||
super::types::SignalType::Audio => graph_node.output_buffers.push(vec![0.0; buffer_size * 2]),
|
||||
super::types::SignalType::CV => graph_node.output_buffers.push(vec![0.0; buffer_size]),
|
||||
super::types::SignalType::Midi => graph_node.output_buffers.push(vec![]),
|
||||
}
|
||||
}
|
||||
self.topo_cache = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove all edges going OUT of a specific output port of a node.
|
||||
pub fn disconnect_output_port(&mut self, node: NodeIndex, port: usize) {
|
||||
let edges: Vec<_> = self.graph
|
||||
.edges_directed(node, petgraph::Direction::Outgoing)
|
||||
.filter(|e| e.weight().from_port == port)
|
||||
.map(|e| e.id())
|
||||
.collect();
|
||||
for edge_id in edges {
|
||||
self.graph.remove_edge(edge_id);
|
||||
}
|
||||
self.topo_cache = None;
|
||||
}
|
||||
|
||||
/// Remove all edges going INTO a node (all input connections).
|
||||
pub fn disconnect_all_inputs(&mut self, node: NodeIndex) {
|
||||
let edges: Vec<_> = self.graph
|
||||
.edges_directed(node, petgraph::Direction::Incoming)
|
||||
.map(|e| e.id())
|
||||
.collect();
|
||||
for edge_id in edges {
|
||||
self.graph.remove_edge(edge_id);
|
||||
}
|
||||
self.topo_cache = None;
|
||||
}
|
||||
|
||||
/// 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()))
|
||||
@@ -787,7 +852,7 @@ impl AudioGraph {
|
||||
/// Serialize the graph to a preset
|
||||
pub fn to_preset(&self, name: impl Into<String>) -> crate::audio::node_graph::preset::GraphPreset {
|
||||
use crate::audio::node_graph::preset::{GraphPreset, SerializedConnection, SerializedNode};
|
||||
use crate::audio::node_graph::nodes::VoiceAllocatorNode;
|
||||
use crate::audio::node_graph::nodes::{VoiceAllocatorNode, MixerNode, SubtrackInputsNode};
|
||||
|
||||
let mut preset = GraphPreset::new(name);
|
||||
|
||||
@@ -805,6 +870,19 @@ impl AudioGraph {
|
||||
serialized.set_parameter(param.id, value);
|
||||
}
|
||||
|
||||
// Save port count for dynamic-port nodes so they round-trip correctly
|
||||
if node.node_type() == "Mixer" {
|
||||
if let Some(mixer) = node.as_any().downcast_ref::<MixerNode>() {
|
||||
serialized.num_ports = Some(mixer.num_inputs() as u32);
|
||||
}
|
||||
}
|
||||
if node.node_type() == "SubtrackInputs" {
|
||||
if let Some(si) = node.as_any().downcast_ref::<SubtrackInputsNode>() {
|
||||
serialized.num_ports = Some(si.num_subtracks() as u32);
|
||||
serialized.port_names = si.subtracks().iter().map(|(_, name)| name.clone()).collect();
|
||||
}
|
||||
}
|
||||
|
||||
// For VoiceAllocator nodes, serialize the template graph
|
||||
if node.node_type() == "VoiceAllocator" {
|
||||
// Downcast using safe Any trait
|
||||
@@ -1002,12 +1080,46 @@ impl AudioGraph {
|
||||
let mut graph = Self::new(sample_rate, buffer_size);
|
||||
let mut index_map: HashMap<u32, NodeIndex> = HashMap::new();
|
||||
|
||||
// Pre-pass: compute required min port count for dynamic-port nodes from the connection list.
|
||||
// This ensures old presets (without num_ports) still size correctly regardless of
|
||||
// connection-restoration order.
|
||||
let mut required_ports: HashMap<u32, usize> = HashMap::new();
|
||||
for conn in &preset.connections {
|
||||
let entry = required_ports.entry(conn.to_node).or_insert(0);
|
||||
*entry = (*entry).max(conn.to_port + 2); // port N + 1 spare
|
||||
}
|
||||
|
||||
// Create all nodes
|
||||
for serialized_node in &preset.nodes {
|
||||
// Create the node based on type
|
||||
let mut node = crate::audio::node_graph::nodes::create_node(&serialized_node.node_type, sample_rate, buffer_size)
|
||||
.ok_or_else(|| format!("Unknown node type: {}", serialized_node.node_type))?;
|
||||
|
||||
// Pre-size dynamic-port nodes before graph.add_node() so output buffers are
|
||||
// allocated at the correct size. num_ports takes priority; fall back to
|
||||
// connection-count inference so old presets without num_ports still work.
|
||||
if serialized_node.node_type == "Mixer" {
|
||||
use crate::audio::node_graph::nodes::MixerNode;
|
||||
if let Some(mixer) = node.as_any_mut().downcast_mut::<MixerNode>() {
|
||||
let from_conns = required_ports.get(&serialized_node.id).copied().unwrap_or(1);
|
||||
let target = serialized_node.num_ports.map(|n| n as usize).unwrap_or(0).max(from_conns).max(1);
|
||||
mixer.resize(target);
|
||||
}
|
||||
}
|
||||
if serialized_node.node_type == "SubtrackInputs" {
|
||||
use crate::audio::node_graph::nodes::SubtrackInputsNode;
|
||||
if let Some(si) = node.as_any_mut().downcast_mut::<SubtrackInputsNode>() {
|
||||
let from_conns = required_ports.get(&serialized_node.id).copied().unwrap_or(0);
|
||||
let target = serialized_node.num_ports.map(|n| n as usize).unwrap_or(0).max(from_conns);
|
||||
if target > 0 {
|
||||
let subtracks = (0..target)
|
||||
.map(|i| (0u32, format!("Subtrack {}", i + 1)))
|
||||
.collect();
|
||||
si.update_subtracks(subtracks, buffer_size);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// VoiceAllocator needs its template graph deserialized and set
|
||||
if serialized_node.node_type == "VoiceAllocator" {
|
||||
if let Some(ref template_preset) = serialized_node.template_graph {
|
||||
|
||||
@@ -1,48 +1,74 @@
|
||||
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
|
||||
/// Mixer node — combines N audio inputs with independent gain controls.
|
||||
///
|
||||
/// The number of input ports is dynamic: one spare unconnected port is always present
|
||||
/// beyond however many are currently wired, so users can keep patching in without
|
||||
/// manually adding inputs. Port count is managed by `AudioGraph::connect` /
|
||||
/// `AudioGraph::disconnect` calling `ensure_min_ports` / `resize`.
|
||||
///
|
||||
/// Gain values are stored separately from the port list so they survive resize
|
||||
/// operations and can be set via `set_parameter` before the port is visible.
|
||||
pub struct MixerNode {
|
||||
name: String,
|
||||
gains: [f32; 4],
|
||||
/// Displayed input ports. Length = num_ports (connected + 1 spare).
|
||||
inputs: Vec<NodePort>,
|
||||
outputs: Vec<NodePort>,
|
||||
/// Per-channel gains, indexed by port. May be longer than `inputs` if gains
|
||||
/// were set before ports were created (handled gracefully).
|
||||
gains: Vec<f32>,
|
||||
/// Mirrored parameter list so `parameters()` stays in sync with `inputs`.
|
||||
parameters: Vec<Parameter>,
|
||||
}
|
||||
|
||||
impl MixerNode {
|
||||
pub fn new(name: impl Into<String>) -> Self {
|
||||
let name = name.into();
|
||||
let mut node = Self {
|
||||
name: name.into(),
|
||||
inputs: Vec::new(),
|
||||
outputs: vec![NodePort::new("Mixed Out", SignalType::Audio, 0)],
|
||||
gains: Vec::new(),
|
||||
parameters: Vec::new(),
|
||||
};
|
||||
node.resize(1); // start with one spare input
|
||||
node
|
||||
}
|
||||
|
||||
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),
|
||||
];
|
||||
/// Return the current number of input ports (connected + 1 spare).
|
||||
pub fn num_inputs(&self) -> usize {
|
||||
self.inputs.len()
|
||||
}
|
||||
|
||||
let outputs = vec![
|
||||
NodePort::new("Mixed Out", SignalType::Audio, 0),
|
||||
];
|
||||
/// Set the exact number of input ports.
|
||||
///
|
||||
/// Existing gain values are preserved. Truncates spare gains when shrinking,
|
||||
/// but gain slots that have already been written survive a grow-shrink-grow cycle.
|
||||
pub fn resize(&mut self, n: usize) {
|
||||
let n = n.max(1); // always at least one spare
|
||||
|
||||
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.inputs = (0..n)
|
||||
.map(|i| NodePort::new(format!("Input {}", i + 1).as_str(), SignalType::Audio, i))
|
||||
.collect();
|
||||
|
||||
Self {
|
||||
name,
|
||||
gains: [1.0, 1.0, 1.0, 1.0],
|
||||
inputs,
|
||||
outputs,
|
||||
parameters,
|
||||
// Extend gains with 1.0 for new slots; preserve existing values.
|
||||
if self.gains.len() < n {
|
||||
self.gains.resize(n, 1.0);
|
||||
}
|
||||
|
||||
self.parameters = (0..n)
|
||||
.map(|i| {
|
||||
Parameter::new(i as u32, format!("Gain {}", i + 1).as_str(), 0.0, 2.0, 1.0, ParameterUnit::Generic)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
/// Ensure at least `n` input ports exist, growing if needed but never shrinking.
|
||||
///
|
||||
/// Called by `AudioGraph::connect` after adding a connection.
|
||||
pub fn ensure_min_ports(&mut self, n: usize) {
|
||||
if n > self.inputs.len() {
|
||||
self.resize(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,23 +91,17 @@ impl AudioNode for MixerNode {
|
||||
}
|
||||
|
||||
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),
|
||||
_ => {}
|
||||
let idx = id as usize;
|
||||
// Extend gains if this port hasn't been created yet (e.g. loaded from preset
|
||||
// before connections are restored).
|
||||
if idx >= self.gains.len() {
|
||||
self.gains.resize(idx + 1, 1.0);
|
||||
}
|
||||
self.gains[idx] = 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,
|
||||
}
|
||||
self.gains.get(id as usize).copied().unwrap_or(1.0)
|
||||
}
|
||||
|
||||
fn process(
|
||||
@@ -97,32 +117,23 @@ impl AudioNode for MixerNode {
|
||||
}
|
||||
|
||||
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];
|
||||
for (input_idx, input) in inputs.iter().enumerate() {
|
||||
let gain = self.gains.get(input_idx).copied().unwrap_or(1.0);
|
||||
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] += input[frame * 2] * gain; // Left
|
||||
output[frame * 2 + 1] += input[frame * 2 + 1] * gain; // Right
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
// No state to reset
|
||||
// No per-frame state
|
||||
}
|
||||
|
||||
fn node_type(&self) -> &str {
|
||||
@@ -136,9 +147,9 @@ impl AudioNode for MixerNode {
|
||||
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(),
|
||||
gains: self.gains.clone(),
|
||||
parameters: self.parameters.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod amp_sim;
|
||||
pub mod bundled_models;
|
||||
mod adsr;
|
||||
mod subtrack_inputs;
|
||||
mod arpeggiator;
|
||||
mod audio_input;
|
||||
mod audio_to_cv;
|
||||
@@ -96,6 +97,7 @@ pub use vibrato::VibratoNode;
|
||||
pub use vocoder::VocoderNode;
|
||||
pub use voice_allocator::VoiceAllocatorNode;
|
||||
pub use wavetable_oscillator::WavetableOscillatorNode;
|
||||
pub use subtrack_inputs::SubtrackInputsNode;
|
||||
|
||||
/// Create a node instance by type name string.
|
||||
///
|
||||
@@ -152,6 +154,7 @@ pub fn create_node(node_type: &str, sample_rate: u32, buffer_size: usize) -> Opt
|
||||
"Vibrato" => Box::new(VibratoNode::new("Vibrato")),
|
||||
"AmpSim" => Box::new(AmpSimNode::new("Amp Sim")),
|
||||
"AudioOutput" => Box::new(AudioOutputNode::new("Output")),
|
||||
"SubtrackInputs" => Box::new(SubtrackInputsNode::new("Subtrack Inputs", vec![])),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
|
||||
use crate::audio::midi::MidiEvent;
|
||||
use crate::audio::track::TrackId;
|
||||
|
||||
/// Subtrack inputs node for metatracks.
|
||||
///
|
||||
/// Exposes one output port per child track so users can route individual subtracks
|
||||
/// independently in the mixing graph (e.g., for sidechain effects).
|
||||
///
|
||||
/// Audio is injected into pre-allocated per-slot buffers by the render system before
|
||||
/// the graph is processed — no heap allocation occurs during audio rendering.
|
||||
pub struct SubtrackInputsNode {
|
||||
name: String,
|
||||
/// Ordered list of (TrackId, display_name) for each subtrack slot.
|
||||
/// TrackId is used by the render system to match the right buffer to the right slot.
|
||||
subtracks: Vec<(TrackId, String)>,
|
||||
/// Output port descriptors — rebuilt whenever subtracks changes.
|
||||
outputs: Vec<NodePort>,
|
||||
/// Pre-allocated audio buffers, one per subtrack slot (stereo interleaved, length = buffer_size * 2).
|
||||
/// Filled by `inject_subtrack_audio` before graph processing; no alloc per frame.
|
||||
buffers: Vec<Vec<f32>>,
|
||||
/// The buffer size this node was last sized for.
|
||||
buffer_size: usize,
|
||||
}
|
||||
|
||||
impl SubtrackInputsNode {
|
||||
pub fn new(name: impl Into<String>, subtracks: Vec<(TrackId, String)>) -> Self {
|
||||
let outputs = Self::build_outputs(&subtracks);
|
||||
let n = subtracks.len();
|
||||
Self {
|
||||
name: name.into(),
|
||||
subtracks,
|
||||
outputs,
|
||||
buffers: vec![Vec::new(); n],
|
||||
buffer_size: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_outputs(subtracks: &[(TrackId, String)]) -> Vec<NodePort> {
|
||||
subtracks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (_, name))| NodePort::new(name.as_str(), SignalType::Audio, i))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Inject audio from a child track into its pre-allocated slot.
|
||||
///
|
||||
/// `idx` is the slot index (matching the order in `subtracks`).
|
||||
/// Called by the render system once per child per frame — no allocation.
|
||||
pub fn inject_subtrack_audio(&mut self, idx: usize, audio: &[f32]) {
|
||||
if let Some(buf) = self.buffers.get_mut(idx) {
|
||||
let len = buf.len().min(audio.len());
|
||||
buf[..len].copy_from_slice(&audio[..len]);
|
||||
// Zero any remaining samples if audio is shorter than the buffer
|
||||
if audio.len() < buf.len() {
|
||||
buf[audio.len()..].fill(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild ports and resize pre-allocated buffers.
|
||||
///
|
||||
/// Only reallocates when the subtrack list actually changes in size or content.
|
||||
/// Pass `buffer_size` in frames (stereo buffers will be `buffer_size * 2` samples).
|
||||
pub fn update_subtracks(&mut self, subtracks: Vec<(TrackId, String)>, buffer_size: usize) {
|
||||
let n = subtracks.len();
|
||||
self.outputs = Self::build_outputs(&subtracks);
|
||||
self.subtracks = subtracks;
|
||||
self.buffer_size = buffer_size;
|
||||
|
||||
// Resize buffers: keep existing allocations where possible
|
||||
self.buffers.resize_with(n, Vec::new);
|
||||
for buf in &mut self.buffers {
|
||||
let target = buffer_size * 2; // stereo interleaved
|
||||
if buf.len() != target {
|
||||
buf.resize(target, 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the slot index for the given TrackId, or None if not found.
|
||||
pub fn subtrack_index_for(&self, track_id: TrackId) -> Option<usize> {
|
||||
self.subtracks.iter().position(|(id, _)| *id == track_id)
|
||||
}
|
||||
|
||||
/// Return the number of subtrack slots.
|
||||
pub fn num_subtracks(&self) -> usize {
|
||||
self.subtracks.len()
|
||||
}
|
||||
|
||||
/// Return the ordered subtrack list.
|
||||
pub fn subtracks(&self) -> &[(TrackId, String)] {
|
||||
&self.subtracks
|
||||
}
|
||||
}
|
||||
|
||||
impl AudioNode for SubtrackInputsNode {
|
||||
fn category(&self) -> NodeCategory {
|
||||
NodeCategory::Input
|
||||
}
|
||||
|
||||
fn inputs(&self) -> &[NodePort] {
|
||||
&[] // No inputs — audio is injected externally
|
||||
}
|
||||
|
||||
fn outputs(&self) -> &[NodePort] {
|
||||
&self.outputs
|
||||
}
|
||||
|
||||
fn parameters(&self) -> &[Parameter] {
|
||||
&[] // No user-facing parameters; port count is stored via num_ports in serialization
|
||||
}
|
||||
|
||||
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 each pre-filled buffer to its output port
|
||||
for (i, output) in outputs.iter_mut().enumerate() {
|
||||
if let Some(buf) = self.buffers.get(i) {
|
||||
let len = output.len().min(buf.len());
|
||||
if len > 0 {
|
||||
output[..len].copy_from_slice(&buf[..len]);
|
||||
}
|
||||
if output.len() > len {
|
||||
output[len..].fill(0.0);
|
||||
}
|
||||
} else {
|
||||
output.fill(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
for buf in &mut self.buffers {
|
||||
buf.fill(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn node_type(&self) -> &str {
|
||||
"SubtrackInputs"
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn clone_node(&self) -> Box<dyn AudioNode> {
|
||||
Box::new(Self {
|
||||
name: self.name.clone(),
|
||||
subtracks: self.subtracks.clone(),
|
||||
outputs: self.outputs.clone(),
|
||||
// Don't clone audio buffers; fresh node starts silent
|
||||
buffers: vec![vec![0.0; self.buffer_size * 2]; self.subtracks.len()],
|
||||
buffer_size: self.buffer_size,
|
||||
})
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -131,6 +131,16 @@ pub struct SerializedNode {
|
||||
/// For AmpSim nodes: path to the .nam model file
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub nam_model_path: Option<String>,
|
||||
|
||||
/// For dynamic-port nodes (Mixer, SubtrackInputs): saved port count so ports
|
||||
/// round-trip correctly through save/load independent of connection order.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub num_ports: Option<u32>,
|
||||
|
||||
/// For SubtrackInputs: ordered port names (one per subtrack slot).
|
||||
/// Allows the UI to display actual track names on the node's output ports.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub port_names: Vec<String>,
|
||||
}
|
||||
|
||||
/// Serialized group definition (frontend-only visual grouping, stored opaquely by backend)
|
||||
@@ -227,6 +237,8 @@ impl SerializedNode {
|
||||
sample_data: None,
|
||||
script_source: None,
|
||||
nam_model_path: None,
|
||||
num_ports: None,
|
||||
port_names: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -356,7 +356,11 @@ impl Project {
|
||||
}
|
||||
}
|
||||
|
||||
/// Render all root tracks into the output buffer
|
||||
/// Render all root tracks into the output buffer.
|
||||
///
|
||||
/// When `live_only` is true, MIDI tracks skip clip event collection and only process
|
||||
/// their live MIDI queue (note-off tails + keyboard input). Audio tracks produce silence.
|
||||
/// This lets the caller use the same group-hierarchy render path regardless of play state.
|
||||
pub fn render(
|
||||
&mut self,
|
||||
output: &mut [f32],
|
||||
@@ -365,18 +369,17 @@ impl Project {
|
||||
playhead_seconds: f64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
live_only: bool,
|
||||
) {
|
||||
output.fill(0.0);
|
||||
|
||||
let any_solo = self.any_solo();
|
||||
|
||||
// Create initial render context
|
||||
let ctx = RenderContext::new(
|
||||
playhead_seconds,
|
||||
sample_rate,
|
||||
channels,
|
||||
output.len(),
|
||||
);
|
||||
let ctx = RenderContext {
|
||||
live_only,
|
||||
..RenderContext::new(playhead_seconds, sample_rate, channels, output.len())
|
||||
};
|
||||
|
||||
// Render each root track (index-based to avoid clone)
|
||||
for i in 0..self.root_tracks.len() {
|
||||
@@ -441,6 +444,10 @@ impl Project {
|
||||
// Handle audio track vs MIDI track vs group track
|
||||
match self.tracks.get_mut(&track_id) {
|
||||
Some(TrackNode::Audio(track)) => {
|
||||
// Audio tracks have no live input; skip in live_only mode.
|
||||
if ctx.live_only {
|
||||
return;
|
||||
}
|
||||
// Render audio track into a temp buffer for peak measurement
|
||||
let mut track_buffer = buffer_pool.acquire();
|
||||
track_buffer.resize(output.len(), 0.0);
|
||||
@@ -460,7 +467,7 @@ impl Project {
|
||||
let mut track_buffer = buffer_pool.acquire();
|
||||
track_buffer.resize(output.len(), 0.0);
|
||||
track_buffer.fill(0.0);
|
||||
track.render(&mut track_buffer, &self.midi_clip_pool, ctx.playhead_seconds, ctx.sample_rate, ctx.channels);
|
||||
track.render(&mut track_buffer, &self.midi_clip_pool, ctx);
|
||||
// Accumulate peak level for VU metering (max over meter interval)
|
||||
let buffer_peak = track_buffer.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
|
||||
track.peak_level = track.peak_level.max(buffer_peak);
|
||||
@@ -471,72 +478,75 @@ impl Project {
|
||||
buffer_pool.release(track_buffer);
|
||||
}
|
||||
Some(TrackNode::Group(group)) => {
|
||||
// Skip rendering if playhead is outside the metatrack's trim window
|
||||
if !group.is_active_at_time(ctx.playhead_seconds) {
|
||||
// Skip rendering if playhead is outside the metatrack's trim window.
|
||||
// In live_only mode always render so note-off tails pass through the mixer.
|
||||
if !ctx.live_only && !group.is_active_at_time(ctx.playhead_seconds) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Read group properties and transform context (index-based child iteration to avoid clone)
|
||||
// Read group properties and transform context before any mutable borrows
|
||||
let num_children = group.children.len();
|
||||
let this_group_is_soloed = group.solo;
|
||||
let child_ctx = group.transform_context(ctx);
|
||||
|
||||
// Acquire a temporary buffer for the group mix
|
||||
let mut group_buffer = buffer_pool.acquire();
|
||||
group_buffer.resize(output.len(), 0.0);
|
||||
group_buffer.fill(0.0);
|
||||
|
||||
// Recursively render all children into the group buffer
|
||||
// If this group is soloed (or parent was soloed), children inherit that state
|
||||
let children_parent_soloed = parent_is_soloed || this_group_is_soloed;
|
||||
|
||||
// Render each child into its own buffer and inject into SubtrackInputsNode.
|
||||
// One pool buffer is reused per child (no extra allocation per frame).
|
||||
for i in 0..num_children {
|
||||
let child_id = match self.tracks.get(&track_id) {
|
||||
Some(TrackNode::Group(g)) => g.children[i],
|
||||
_ => break,
|
||||
};
|
||||
|
||||
let mut child_buffer = buffer_pool.acquire();
|
||||
child_buffer.resize(output.len(), 0.0);
|
||||
child_buffer.fill(0.0);
|
||||
|
||||
self.render_track(
|
||||
child_id,
|
||||
&mut group_buffer,
|
||||
&mut child_buffer,
|
||||
audio_pool,
|
||||
buffer_pool,
|
||||
child_ctx,
|
||||
any_solo,
|
||||
children_parent_soloed,
|
||||
);
|
||||
}
|
||||
|
||||
// Route children's mix through metatrack's audio graph
|
||||
if let Some(TrackNode::Group(group)) = self.tracks.get_mut(&track_id) {
|
||||
// Inject children's mix into audio graph's input node
|
||||
let node_indices: Vec<_> = group.audio_graph.node_indices().collect();
|
||||
for node_idx in node_indices {
|
||||
if let Some(graph_node) = group.audio_graph.get_graph_node_mut(node_idx) {
|
||||
if graph_node.node.node_type() == "AudioInput" {
|
||||
if let Some(input_node) = graph_node.node.as_any_mut()
|
||||
.downcast_mut::<super::node_graph::nodes::AudioInputNode>()
|
||||
{
|
||||
input_node.inject_audio(&group_buffer);
|
||||
// Inject into the SubtrackInputsNode slot for this child
|
||||
if let Some(TrackNode::Group(group)) = self.tracks.get_mut(&track_id) {
|
||||
use super::node_graph::nodes::SubtrackInputsNode;
|
||||
let node_indices: Vec<_> = group.audio_graph.node_indices().collect();
|
||||
for node_idx in node_indices {
|
||||
if let Some(gn) = group.audio_graph.get_graph_node_mut(node_idx) {
|
||||
if gn.node.node_type() == "SubtrackInputs" {
|
||||
if let Some(si) = gn.node.as_any_mut()
|
||||
.downcast_mut::<SubtrackInputsNode>()
|
||||
{
|
||||
if let Some(slot) = si.subtrack_index_for(child_id) {
|
||||
si.inject_subtrack_audio(slot, &child_buffer);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process through the audio graph into a fresh buffer
|
||||
buffer_pool.release(child_buffer);
|
||||
}
|
||||
|
||||
// Process children's audio through the metatrack's mixing graph
|
||||
if let Some(TrackNode::Group(group)) = self.tracks.get_mut(&track_id) {
|
||||
let mut graph_output = buffer_pool.acquire();
|
||||
graph_output.resize(output.len(), 0.0);
|
||||
graph_output.fill(0.0);
|
||||
group.audio_graph.process(&mut graph_output, &[], ctx.playhead_seconds);
|
||||
|
||||
// Apply group volume and mix into output
|
||||
for (out_sample, graph_sample) in output.iter_mut().zip(graph_output.iter()) {
|
||||
*out_sample += graph_sample * group.volume;
|
||||
}
|
||||
buffer_pool.release(graph_output);
|
||||
}
|
||||
|
||||
// Release children mix buffer back to pool
|
||||
buffer_pool.release(group_buffer);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
@@ -620,17 +630,6 @@ impl Project {
|
||||
}
|
||||
}
|
||||
|
||||
/// Process live MIDI input from all MIDI tracks (called even when not playing)
|
||||
pub fn process_live_midi(&mut self, output: &mut [f32], sample_rate: u32, channels: u32) {
|
||||
// Process all MIDI tracks to handle queued live input events
|
||||
for track in self.tracks.values_mut() {
|
||||
if let TrackNode::Midi(midi_track) = track {
|
||||
// Process only queued live events, not clips
|
||||
midi_track.process_live_input(output, sample_rate, channels);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a live MIDI note on event to a track's instrument
|
||||
/// Note: With node-based instruments, MIDI events are handled during the process() call
|
||||
pub fn send_midi_note_on(&mut self, track_id: TrackId, note: u8, velocity: u8) {
|
||||
|
||||
+261
-69
@@ -35,6 +35,10 @@ pub struct RenderContext {
|
||||
pub buffer_size: usize,
|
||||
/// Accumulated time stretch factor (1.0 = normal, 0.5 = half speed, 2.0 = double speed)
|
||||
pub time_stretch: f32,
|
||||
/// When true: skip clip event collection; only render instrument state and live MIDI queue.
|
||||
/// Used after pause/stop to route note-off tails through the normal group hierarchy
|
||||
/// without re-triggering notes from clips at the paused position.
|
||||
pub live_only: bool,
|
||||
}
|
||||
|
||||
impl RenderContext {
|
||||
@@ -51,6 +55,7 @@ impl RenderContext {
|
||||
channels,
|
||||
buffer_size,
|
||||
time_stretch: 1.0,
|
||||
live_only: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +186,10 @@ pub struct Metatrack {
|
||||
pub audio_graph: AudioGraph,
|
||||
/// Saved graph preset for serialization
|
||||
audio_graph_preset: Option<GraphPreset>,
|
||||
/// True while the mixing graph is still the auto-generated default (no user edits).
|
||||
/// Used to auto-connect new subtracks and to prompt before loading a preset.
|
||||
#[serde(default)]
|
||||
pub graph_is_default: bool,
|
||||
}
|
||||
|
||||
impl Clone for Metatrack {
|
||||
@@ -201,15 +210,17 @@ impl Clone for Metatrack {
|
||||
next_automation_id: self.next_automation_id,
|
||||
audio_graph: default_audio_graph(), // Create fresh graph, not cloned
|
||||
audio_graph_preset: self.audio_graph_preset.clone(),
|
||||
graph_is_default: self.graph_is_default,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Metatrack {
|
||||
/// Create a new metatrack with an audio graph (input → output)
|
||||
/// Create a new metatrack. The mixing graph is set up later via `set_subtrack_graph`
|
||||
/// once the child track list is known.
|
||||
pub fn new(id: TrackId, name: String, sample_rate: u32) -> Self {
|
||||
let default_buffer_size = 8192;
|
||||
let audio_graph = Self::create_default_graph(sample_rate, default_buffer_size);
|
||||
let audio_graph = Self::create_empty_graph(sample_rate, default_buffer_size);
|
||||
|
||||
Self {
|
||||
id,
|
||||
@@ -227,25 +238,192 @@ impl Metatrack {
|
||||
next_automation_id: 0,
|
||||
audio_graph,
|
||||
audio_graph_preset: None,
|
||||
graph_is_default: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a default audio graph with AudioInput -> AudioOutput
|
||||
fn create_default_graph(sample_rate: u32, buffer_size: usize) -> AudioGraph {
|
||||
/// Minimal graph used before subtracks are known (just an AudioOutput node).
|
||||
fn create_empty_graph(sample_rate: u32, buffer_size: usize) -> AudioGraph {
|
||||
let mut graph = AudioGraph::new(sample_rate, buffer_size);
|
||||
|
||||
let input_node = Box::new(AudioInputNode::new("Audio Input"));
|
||||
let input_id = graph.add_node(input_node);
|
||||
graph.set_node_position(input_id, 100.0, 150.0);
|
||||
|
||||
let output_node = Box::new(AudioOutputNode::new("Audio Output"));
|
||||
let output_id = graph.add_node(output_node);
|
||||
graph.set_node_position(output_id, 500.0, 150.0);
|
||||
graph.set_output_node(Some(output_id));
|
||||
graph
|
||||
}
|
||||
|
||||
let _ = graph.connect(input_id, 0, output_id, 0);
|
||||
/// Build the explicit subtrack mixing graph: SubtrackInputs → Mixer → AudioOutput.
|
||||
///
|
||||
/// `subtracks` is an ordered list of (backend TrackId, display name) for each child.
|
||||
/// Replaces the current graph and marks `graph_is_default = true`.
|
||||
pub fn set_subtrack_graph(
|
||||
&mut self,
|
||||
subtracks: Vec<(TrackId, String)>,
|
||||
sample_rate: u32,
|
||||
buffer_size: usize,
|
||||
) {
|
||||
use super::node_graph::nodes::{SubtrackInputsNode, MixerNode};
|
||||
|
||||
let n = subtracks.len();
|
||||
let mut graph = AudioGraph::new(sample_rate, buffer_size);
|
||||
|
||||
// SubtrackInputs node (N outputs, one per child)
|
||||
// NOTE: `new()` initialises buffers as zero-length; call `update_subtracks` immediately
|
||||
// to allocate stereo interleaved buffers (buffer_size * 2 samples each).
|
||||
let mut inputs_node = SubtrackInputsNode::new("Subtrack Inputs", subtracks);
|
||||
let subtracks_copy = inputs_node.subtracks().to_vec();
|
||||
inputs_node.update_subtracks(subtracks_copy, buffer_size);
|
||||
let inputs_id = graph.add_node(Box::new(inputs_node));
|
||||
graph.set_node_position(inputs_id, 100.0, 150.0);
|
||||
|
||||
// Mixer node (starts with 1 spare; grows as connections are made)
|
||||
let mixer_node = Box::new(MixerNode::new("Mixer"));
|
||||
let mixer_id = graph.add_node(mixer_node);
|
||||
graph.set_node_position(mixer_id, 350.0, 150.0);
|
||||
|
||||
// AudioOutput node
|
||||
let output_node = Box::new(AudioOutputNode::new("Audio Output"));
|
||||
let output_id = graph.add_node(output_node);
|
||||
graph.set_node_position(output_id, 600.0, 150.0);
|
||||
|
||||
// Connect SubtrackInputs[i] → Mixer[i] for each subtrack
|
||||
for i in 0..n {
|
||||
let _ = graph.connect(inputs_id, i, mixer_id, i);
|
||||
}
|
||||
let _ = graph.connect(mixer_id, 0, output_id, 0);
|
||||
graph.set_output_node(Some(output_id));
|
||||
|
||||
graph
|
||||
self.audio_graph = graph;
|
||||
self.audio_graph_preset = None;
|
||||
self.graph_is_default = true;
|
||||
}
|
||||
|
||||
/// Add a new subtrack port to the existing graph.
|
||||
///
|
||||
/// If `graph_is_default`: also connects the new port to a new Mixer input.
|
||||
/// If the user has modified the graph: just adds the port (unconnected).
|
||||
pub fn add_subtrack_to_graph(&mut self, track_id: TrackId, name: String, buffer_size: usize) {
|
||||
use super::node_graph::nodes::SubtrackInputsNode;
|
||||
|
||||
// Find SubtrackInputs node index
|
||||
let si_idx = self.audio_graph.node_indices()
|
||||
.find(|&idx| self.audio_graph.get_graph_node(idx)
|
||||
.map(|n| n.node.node_type() == "SubtrackInputs")
|
||||
.unwrap_or(false));
|
||||
|
||||
let si_idx = match si_idx {
|
||||
Some(idx) => idx,
|
||||
None => return, // No subtrack graph set up yet
|
||||
};
|
||||
|
||||
// Get current subtrack count (= new port index after adding)
|
||||
let new_slot = {
|
||||
let gn = self.audio_graph.get_graph_node_mut(si_idx).unwrap();
|
||||
let si = gn.node.as_any_mut().downcast_mut::<SubtrackInputsNode>().unwrap();
|
||||
let mut subtracks = si.subtracks().to_vec();
|
||||
subtracks.push((track_id, name));
|
||||
let n = subtracks.len();
|
||||
si.update_subtracks(subtracks, buffer_size);
|
||||
// Rebuild output buffers for the new port count
|
||||
n - 1 // index of the newly added slot
|
||||
};
|
||||
// Reallocate GraphNode output buffers to match new port count
|
||||
self.audio_graph.reallocate_node_output_buffers(si_idx, buffer_size);
|
||||
|
||||
if self.graph_is_default {
|
||||
// Find the Mixer node and connect the new subtrack port to a new Mixer input
|
||||
let mixer_idx = self.audio_graph.node_indices()
|
||||
.find(|&idx| self.audio_graph.get_graph_node(idx)
|
||||
.map(|n| n.node.node_type() == "Mixer")
|
||||
.unwrap_or(false));
|
||||
|
||||
if let Some(mixer_idx) = mixer_idx {
|
||||
// n_incoming after connecting = new_slot + 1; auto-grow handled by connect()
|
||||
let _ = self.audio_graph.connect(si_idx, new_slot, mixer_idx, new_slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a subtrack from the graph (by TrackId).
|
||||
///
|
||||
/// Always disconnects any connections from the removed port and removes the port.
|
||||
/// If `graph_is_default`: also reshuffles Mixer connections to stay compact.
|
||||
pub fn remove_subtrack_from_graph(&mut self, track_id: TrackId, buffer_size: usize) {
|
||||
use super::node_graph::nodes::SubtrackInputsNode;
|
||||
|
||||
let si_idx = self.audio_graph.node_indices()
|
||||
.find(|&idx| self.audio_graph.get_graph_node(idx)
|
||||
.map(|n| n.node.node_type() == "SubtrackInputs")
|
||||
.unwrap_or(false));
|
||||
|
||||
let si_idx = match si_idx {
|
||||
Some(idx) => idx,
|
||||
None => return,
|
||||
};
|
||||
|
||||
// Find the slot index for this track
|
||||
let slot = {
|
||||
let gn = self.audio_graph.get_graph_node(si_idx).unwrap();
|
||||
let si = gn.node.as_any().downcast_ref::<SubtrackInputsNode>().unwrap();
|
||||
si.subtrack_index_for(track_id)
|
||||
};
|
||||
let slot = match slot {
|
||||
Some(s) => s,
|
||||
None => return,
|
||||
};
|
||||
|
||||
// Remove all connections from this output port
|
||||
self.audio_graph.disconnect_output_port(si_idx, slot);
|
||||
|
||||
// Update the SubtrackInputsNode's subtrack list
|
||||
{
|
||||
let gn = self.audio_graph.get_graph_node_mut(si_idx).unwrap();
|
||||
let si = gn.node.as_any_mut().downcast_mut::<SubtrackInputsNode>().unwrap();
|
||||
let mut subtracks = si.subtracks().to_vec();
|
||||
subtracks.remove(slot);
|
||||
si.update_subtracks(subtracks, buffer_size);
|
||||
}
|
||||
self.audio_graph.reallocate_node_output_buffers(si_idx, buffer_size);
|
||||
|
||||
if self.graph_is_default {
|
||||
// Rebuild default Mixer connections (they've shifted after removal)
|
||||
let mixer_idx = self.audio_graph.node_indices()
|
||||
.find(|&idx| self.audio_graph.get_graph_node(idx)
|
||||
.map(|n| n.node.node_type() == "Mixer")
|
||||
.unwrap_or(false));
|
||||
|
||||
if let Some(mixer_idx) = mixer_idx {
|
||||
// Clear all connections TO mixer
|
||||
self.audio_graph.disconnect_all_inputs(mixer_idx);
|
||||
// Get new subtrack count
|
||||
let n = {
|
||||
let gn = self.audio_graph.get_graph_node(si_idx).unwrap();
|
||||
gn.node.as_any().downcast_ref::<SubtrackInputsNode>().unwrap().num_subtracks()
|
||||
};
|
||||
// Resize mixer and reconnect
|
||||
{
|
||||
let gn = self.audio_graph.get_graph_node_mut(mixer_idx).unwrap();
|
||||
let mixer = gn.node.as_any_mut().downcast_mut::<super::node_graph::nodes::MixerNode>().unwrap();
|
||||
mixer.resize(n + 1);
|
||||
}
|
||||
for i in 0..n {
|
||||
let _ = self.audio_graph.connect(si_idx, i, mixer_idx, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the current ordered subtrack list from SubtrackInputsNode, or empty vec if none.
|
||||
pub fn current_subtracks(&self) -> Vec<(TrackId, String)> {
|
||||
use super::node_graph::nodes::SubtrackInputsNode;
|
||||
for idx in self.audio_graph.node_indices().collect::<Vec<_>>() {
|
||||
if let Some(gn) = self.audio_graph.get_graph_node(idx) {
|
||||
if let Some(si) = gn.node.as_any().downcast_ref::<SubtrackInputsNode>() {
|
||||
return si.subtracks().to_vec();
|
||||
}
|
||||
}
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Prepare for serialization by saving the audio graph as a preset
|
||||
@@ -253,20 +431,42 @@ impl Metatrack {
|
||||
self.audio_graph_preset = Some(self.audio_graph.to_preset("Metatrack Graph"));
|
||||
}
|
||||
|
||||
/// Rebuild the audio graph from preset after deserialization
|
||||
/// Rebuild the audio graph from preset after deserialization.
|
||||
///
|
||||
/// After loading, the caller must call `update_subtrack_ids` to re-associate
|
||||
/// backend TrackIds with the SubtrackInputsNode's port slots.
|
||||
pub fn rebuild_audio_graph(&mut self, sample_rate: u32, buffer_size: usize) -> Result<(), String> {
|
||||
if let Some(preset) = &self.audio_graph_preset {
|
||||
if !preset.nodes.is_empty() && preset.output_node.is_some() {
|
||||
self.audio_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None)?;
|
||||
// graph_is_default remains as serialized (false for user-modified graphs)
|
||||
} else {
|
||||
self.audio_graph = Self::create_default_graph(sample_rate, buffer_size);
|
||||
self.audio_graph = Self::create_empty_graph(sample_rate, buffer_size);
|
||||
self.graph_is_default = true;
|
||||
}
|
||||
} else {
|
||||
self.audio_graph = Self::create_default_graph(sample_rate, buffer_size);
|
||||
self.audio_graph = Self::create_empty_graph(sample_rate, buffer_size);
|
||||
self.graph_is_default = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-associate backend TrackIds with the SubtrackInputsNode's port slots after reload.
|
||||
///
|
||||
/// The preset stores placeholder TrackId=0 entries; this call fills in the real IDs.
|
||||
pub fn update_subtrack_ids(&mut self, subtracks: Vec<(TrackId, String)>, buffer_size: usize) {
|
||||
use super::node_graph::nodes::SubtrackInputsNode;
|
||||
|
||||
for idx in self.audio_graph.node_indices().collect::<Vec<_>>() {
|
||||
if let Some(gn) = self.audio_graph.get_graph_node_mut(idx) {
|
||||
if let Some(si) = gn.node.as_any_mut().downcast_mut::<SubtrackInputsNode>() {
|
||||
si.update_subtracks(subtracks, buffer_size);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add an automation lane to this metatrack
|
||||
pub fn add_automation_lane(&mut self, parameter_id: ParameterId) -> AutomationLaneId {
|
||||
let lane_id = self.next_automation_id;
|
||||
@@ -439,6 +639,11 @@ pub struct MidiTrack {
|
||||
/// Peak level of last render() call (for VU metering)
|
||||
#[serde(skip, default)]
|
||||
pub peak_level: f32,
|
||||
|
||||
/// True while the instrument graph is still the auto-generated default (no user edits).
|
||||
/// Used to prompt before loading a preset.
|
||||
#[serde(default)]
|
||||
pub graph_is_default: bool,
|
||||
}
|
||||
|
||||
impl Clone for MidiTrack {
|
||||
@@ -457,6 +662,7 @@ impl Clone for MidiTrack {
|
||||
live_midi_queue: Vec::new(), // Don't clone live MIDI queue
|
||||
prev_active_instances: HashSet::new(),
|
||||
peak_level: 0.0,
|
||||
graph_is_default: self.graph_is_default,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -485,6 +691,7 @@ impl MidiTrack {
|
||||
live_midi_queue: Vec::new(),
|
||||
prev_active_instances: HashSet::new(),
|
||||
peak_level: 0.0,
|
||||
graph_is_default: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -584,77 +791,55 @@ impl MidiTrack {
|
||||
self.live_midi_queue.clear();
|
||||
}
|
||||
|
||||
/// Process only live MIDI input (queued events) without rendering clips
|
||||
/// This is used when playback is stopped but we want to hear live input
|
||||
pub fn process_live_input(
|
||||
&mut self,
|
||||
output: &mut [f32],
|
||||
_sample_rate: u32,
|
||||
_channels: u32,
|
||||
) {
|
||||
// Generate audio using instrument graph with live MIDI events
|
||||
self.instrument_graph.process(output, &self.live_midi_queue, 0.0);
|
||||
|
||||
// Clear the queue after processing
|
||||
self.live_midi_queue.clear();
|
||||
|
||||
// Apply track volume (no automation during live input)
|
||||
for sample in output.iter_mut() {
|
||||
*sample *= self.volume;
|
||||
}
|
||||
}
|
||||
|
||||
/// Render this MIDI track into the output buffer
|
||||
/// Render this MIDI track into the output buffer.
|
||||
///
|
||||
/// When `ctx.live_only` is true, clip event collection is skipped and only the live MIDI
|
||||
/// queue is processed. This lets note-off tails (and live keyboard input) route through
|
||||
/// the normal group hierarchy without re-triggering notes from clips at the paused position.
|
||||
pub fn render(
|
||||
&mut self,
|
||||
output: &mut [f32],
|
||||
midi_pool: &MidiClipPool,
|
||||
playhead_seconds: f64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
ctx: RenderContext,
|
||||
) {
|
||||
let buffer_duration_seconds = output.len() as f64 / (sample_rate as f64 * channels as f64);
|
||||
let buffer_end_seconds = playhead_seconds + buffer_duration_seconds;
|
||||
|
||||
// Collect MIDI events from all clip instances that overlap with current time range
|
||||
let mut midi_events = Vec::new();
|
||||
let mut currently_active = HashSet::new();
|
||||
for instance in &self.clip_instances {
|
||||
if instance.overlaps_range(playhead_seconds, buffer_end_seconds) {
|
||||
currently_active.insert(instance.id);
|
||||
}
|
||||
// Get the clip content from the pool
|
||||
if let Some(clip) = midi_pool.get_clip(instance.clip_id) {
|
||||
let events = instance.get_events_in_range(
|
||||
clip,
|
||||
playhead_seconds,
|
||||
buffer_end_seconds,
|
||||
);
|
||||
midi_events.extend(events);
|
||||
}
|
||||
}
|
||||
|
||||
// Send all-notes-off for clip instances that just became inactive
|
||||
// (playhead exited the clip). This prevents stuck notes from malformed clips.
|
||||
for prev_id in &self.prev_active_instances {
|
||||
if !currently_active.contains(prev_id) {
|
||||
for note in 0..128u8 {
|
||||
midi_events.push(MidiEvent::note_off(playhead_seconds, 0, note, 0));
|
||||
if !ctx.live_only {
|
||||
let buffer_duration_seconds = output.len() as f64 / (ctx.sample_rate as f64 * ctx.channels as f64);
|
||||
let buffer_end_seconds = ctx.playhead_seconds + buffer_duration_seconds;
|
||||
|
||||
// Collect MIDI events from all clip instances that overlap with current time range
|
||||
let mut currently_active = HashSet::new();
|
||||
for instance in &self.clip_instances {
|
||||
if instance.overlaps_range(ctx.playhead_seconds, buffer_end_seconds) {
|
||||
currently_active.insert(instance.id);
|
||||
}
|
||||
if let Some(clip) = midi_pool.get_clip(instance.clip_id) {
|
||||
let events = instance.get_events_in_range(clip, ctx.playhead_seconds, buffer_end_seconds);
|
||||
midi_events.extend(events);
|
||||
}
|
||||
break; // One round of all-notes-off is enough
|
||||
}
|
||||
|
||||
// Send all-notes-off for clip instances that just became inactive
|
||||
for prev_id in &self.prev_active_instances {
|
||||
if !currently_active.contains(prev_id) {
|
||||
for note in 0..128u8 {
|
||||
midi_events.push(MidiEvent::note_off(ctx.playhead_seconds, 0, note, 0));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.prev_active_instances = currently_active;
|
||||
}
|
||||
self.prev_active_instances = currently_active;
|
||||
|
||||
// Add live MIDI events (from virtual keyboard or MIDI controllers)
|
||||
// This allows real-time input to be heard during playback/recording
|
||||
midi_events.extend(self.live_midi_queue.drain(..));
|
||||
|
||||
// Generate audio using instrument graph
|
||||
self.instrument_graph.process(output, &midi_events, playhead_seconds);
|
||||
self.instrument_graph.process(output, &midi_events, ctx.playhead_seconds);
|
||||
|
||||
// Evaluate and apply automation
|
||||
let effective_volume = self.evaluate_automation_at_time(playhead_seconds);
|
||||
// Evaluate and apply automation (skip automation in live_only mode — no playhead to evaluate at)
|
||||
let effective_volume = if ctx.live_only { self.volume } else { self.evaluate_automation_at_time(ctx.playhead_seconds) };
|
||||
|
||||
// Apply track volume
|
||||
for sample in output.iter_mut() {
|
||||
@@ -715,6 +900,11 @@ pub struct AudioTrack {
|
||||
/// Peak level of last render() call (for VU metering)
|
||||
#[serde(skip, default)]
|
||||
pub peak_level: f32,
|
||||
|
||||
/// True while the effects graph is still the auto-generated default (no user edits).
|
||||
/// Used to prompt before loading a preset.
|
||||
#[serde(default)]
|
||||
pub graph_is_default: bool,
|
||||
}
|
||||
|
||||
impl Clone for AudioTrack {
|
||||
@@ -732,6 +922,7 @@ impl Clone for AudioTrack {
|
||||
effects_graph: default_audio_graph(), // Create fresh graph, not cloned
|
||||
clip_render_buffer: Vec::new(),
|
||||
peak_level: 0.0,
|
||||
graph_is_default: self.graph_is_default,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -776,6 +967,7 @@ impl AudioTrack {
|
||||
effects_graph,
|
||||
clip_render_buffer: Vec::new(),
|
||||
peak_level: 0.0,
|
||||
graph_is_default: true,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user