Add nested audio tracks
This commit is contained in:
@@ -658,8 +658,8 @@ impl Engine {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Command::CreateMetatrack(name) => {
|
||||
let track_id = self.project.add_group_track(name.clone(), None);
|
||||
Command::CreateMetatrack(name, parent_id) => {
|
||||
let track_id = self.project.add_group_track(name.clone(), parent_id);
|
||||
// Notify UI about the new metatrack
|
||||
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, true, name));
|
||||
}
|
||||
@@ -686,8 +686,18 @@ impl Engine {
|
||||
metatrack.pitch_shift = semitones;
|
||||
}
|
||||
}
|
||||
Command::CreateAudioTrack(name) => {
|
||||
let track_id = self.project.add_audio_track(name.clone(), None);
|
||||
Command::SetTrimStart(track_id, trim_start) => {
|
||||
if let Some(crate::audio::track::TrackNode::Group(metatrack)) = self.project.get_track_mut(track_id) {
|
||||
metatrack.trim_start = trim_start.max(0.0);
|
||||
}
|
||||
}
|
||||
Command::SetTrimEnd(track_id, trim_end) => {
|
||||
if let Some(crate::audio::track::TrackNode::Group(metatrack)) = self.project.get_track_mut(track_id) {
|
||||
metatrack.trim_end = trim_end.map(|t| t.max(0.0));
|
||||
}
|
||||
}
|
||||
Command::CreateAudioTrack(name, parent_id) => {
|
||||
let track_id = self.project.add_audio_track(name.clone(), parent_id);
|
||||
// Notify UI about the new audio track
|
||||
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, false, name));
|
||||
}
|
||||
@@ -793,8 +803,8 @@ impl Engine {
|
||||
eprintln!("[Engine] ERROR: Track {} not found or is not an audio track", track_id);
|
||||
}
|
||||
}
|
||||
Command::CreateMidiTrack(name) => {
|
||||
let track_id = self.project.add_midi_track(name.clone(), None);
|
||||
Command::CreateMidiTrack(name, parent_id) => {
|
||||
let track_id = self.project.add_midi_track(name.clone(), parent_id);
|
||||
// Notify UI about the new MIDI track
|
||||
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, false, name));
|
||||
}
|
||||
@@ -2348,20 +2358,24 @@ impl Engine {
|
||||
|
||||
QueryResponse::TrackGraphLoaded(result)
|
||||
}
|
||||
Query::CreateAudioTrackSync(name) => {
|
||||
let track_id = self.project.add_audio_track(name.clone(), None);
|
||||
eprintln!("[Engine] Created audio track '{}' with ID {}", name, track_id);
|
||||
// Notify UI about the new audio track
|
||||
Query::CreateAudioTrackSync(name, parent_id) => {
|
||||
let track_id = self.project.add_audio_track(name.clone(), parent_id);
|
||||
eprintln!("[Engine] Created audio track '{}' with ID {} (parent: {:?})", name, track_id, parent_id);
|
||||
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, false, name));
|
||||
QueryResponse::TrackCreated(Ok(track_id))
|
||||
}
|
||||
Query::CreateMidiTrackSync(name) => {
|
||||
let track_id = self.project.add_midi_track(name.clone(), None);
|
||||
eprintln!("[Engine] Created MIDI track '{}' with ID {}", name, track_id);
|
||||
// Notify UI about the new MIDI track
|
||||
Query::CreateMidiTrackSync(name, parent_id) => {
|
||||
let track_id = self.project.add_midi_track(name.clone(), parent_id);
|
||||
eprintln!("[Engine] Created MIDI track '{}' with ID {} (parent: {:?})", name, track_id, parent_id);
|
||||
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, false, name));
|
||||
QueryResponse::TrackCreated(Ok(track_id))
|
||||
}
|
||||
Query::CreateMetatrackSync(name, parent_id) => {
|
||||
let track_id = self.project.add_group_track(name.clone(), parent_id);
|
||||
eprintln!("[Engine] Created metatrack '{}' with ID {} (parent: {:?})", name, track_id, parent_id);
|
||||
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, true, name));
|
||||
QueryResponse::TrackCreated(Ok(track_id))
|
||||
}
|
||||
Query::GetPoolWaveform(pool_index, target_peaks) => {
|
||||
match self.audio_pool.generate_waveform(pool_index, target_peaks) {
|
||||
Some(waveform) => QueryResponse::PoolWaveform(Ok(waveform)),
|
||||
@@ -2930,7 +2944,7 @@ impl EngineController {
|
||||
|
||||
/// Create a new metatrack
|
||||
pub fn create_metatrack(&mut self, name: String) {
|
||||
let _ = self.command_tx.push(Command::CreateMetatrack(name));
|
||||
let _ = self.command_tx.push(Command::CreateMetatrack(name, None));
|
||||
}
|
||||
|
||||
/// Add a track to a metatrack
|
||||
@@ -2960,9 +2974,19 @@ impl EngineController {
|
||||
let _ = self.command_tx.push(Command::SetPitchShift(track_id, semitones));
|
||||
}
|
||||
|
||||
/// Set metatrack trim start in seconds
|
||||
pub fn set_trim_start(&mut self, track_id: TrackId, trim_start: f64) {
|
||||
let _ = self.command_tx.push(Command::SetTrimStart(track_id, trim_start));
|
||||
}
|
||||
|
||||
/// Set metatrack trim end in seconds (None = no end trim)
|
||||
pub fn set_trim_end(&mut self, track_id: TrackId, trim_end: Option<f64>) {
|
||||
let _ = self.command_tx.push(Command::SetTrimEnd(track_id, trim_end));
|
||||
}
|
||||
|
||||
/// Create a new audio track
|
||||
pub fn create_audio_track(&mut self, name: String) {
|
||||
let _ = self.command_tx.push(Command::CreateAudioTrack(name));
|
||||
let _ = self.command_tx.push(Command::CreateAudioTrack(name, None));
|
||||
}
|
||||
|
||||
/// Add an audio file to the pool (must be called from non-audio thread with pre-loaded data)
|
||||
@@ -3012,7 +3036,7 @@ impl EngineController {
|
||||
|
||||
/// Create a new MIDI track
|
||||
pub fn create_midi_track(&mut self, name: String) {
|
||||
let _ = self.command_tx.push(Command::CreateMidiTrack(name));
|
||||
let _ = self.command_tx.push(Command::CreateMidiTrack(name, None));
|
||||
}
|
||||
|
||||
/// Add a MIDI clip to the pool without placing it on any track
|
||||
@@ -3022,8 +3046,8 @@ impl EngineController {
|
||||
}
|
||||
|
||||
/// Create a new audio track synchronously (waits for creation to complete)
|
||||
pub fn create_audio_track_sync(&mut self, name: String) -> Result<TrackId, String> {
|
||||
if let Err(_) = self.query_tx.push(Query::CreateAudioTrackSync(name)) {
|
||||
pub fn create_audio_track_sync(&mut self, name: String, parent: Option<TrackId>) -> Result<TrackId, String> {
|
||||
if let Err(_) = self.query_tx.push(Query::CreateAudioTrackSync(name, parent)) {
|
||||
return Err("Failed to send track creation query".to_string());
|
||||
}
|
||||
|
||||
@@ -3042,8 +3066,8 @@ impl EngineController {
|
||||
}
|
||||
|
||||
/// Create a new MIDI track synchronously (waits for creation to complete)
|
||||
pub fn create_midi_track_sync(&mut self, name: String) -> Result<TrackId, String> {
|
||||
if let Err(_) = self.query_tx.push(Query::CreateMidiTrackSync(name)) {
|
||||
pub fn create_midi_track_sync(&mut self, name: String, parent: Option<TrackId>) -> Result<TrackId, String> {
|
||||
if let Err(_) = self.query_tx.push(Query::CreateMidiTrackSync(name, parent)) {
|
||||
return Err("Failed to send track creation query".to_string());
|
||||
}
|
||||
|
||||
@@ -3061,6 +3085,25 @@ impl EngineController {
|
||||
Err("Track creation timeout".to_string())
|
||||
}
|
||||
|
||||
/// Create a new metatrack/group synchronously (waits for creation to complete)
|
||||
pub fn create_group_track_sync(&mut self, name: String, parent: Option<TrackId>) -> Result<TrackId, String> {
|
||||
if let Err(_) = self.query_tx.push(Query::CreateMetatrackSync(name, parent)) {
|
||||
return Err("Failed to send metatrack creation query".to_string());
|
||||
}
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
let timeout = std::time::Duration::from_secs(2);
|
||||
|
||||
while start.elapsed() < timeout {
|
||||
if let Ok(QueryResponse::TrackCreated(result)) = self.query_response_rx.pop() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
|
||||
Err("Metatrack creation timeout".to_string())
|
||||
}
|
||||
|
||||
/// Create a new MIDI clip on a track
|
||||
pub fn create_midi_clip(&mut self, track_id: TrackId, start_time: f64, duration: f64) -> MidiClipId {
|
||||
// Peek at the next clip ID that will be used
|
||||
|
||||
@@ -82,7 +82,7 @@ impl Project {
|
||||
/// The new group's ID
|
||||
pub fn add_group_track(&mut self, name: String, parent_id: Option<TrackId>) -> TrackId {
|
||||
let id = self.next_id();
|
||||
let group = Metatrack::new(id, name);
|
||||
let group = Metatrack::new(id, name, self.sample_rate);
|
||||
self.tracks.insert(id, TrackNode::Group(group));
|
||||
|
||||
if let Some(parent) = parent_id {
|
||||
@@ -450,6 +450,11 @@ impl Project {
|
||||
track.render(output, &self.midi_clip_pool, ctx.playhead_seconds, ctx.sample_rate, ctx.channels);
|
||||
}
|
||||
Some(TrackNode::Group(group)) => {
|
||||
// Skip rendering if playhead is outside the metatrack's trim window
|
||||
if !group.is_active_at_time(ctx.playhead_seconds) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Read group properties and transform context (index-based child iteration to avoid clone)
|
||||
let num_children = group.children.len();
|
||||
let this_group_is_soloed = group.solo;
|
||||
@@ -479,14 +484,37 @@ impl Project {
|
||||
);
|
||||
}
|
||||
|
||||
// Apply group volume and mix into output
|
||||
// Route children's mix through metatrack's audio graph
|
||||
if let Some(TrackNode::Group(group)) = self.tracks.get_mut(&track_id) {
|
||||
for (out_sample, group_sample) in output.iter_mut().zip(group_buffer.iter()) {
|
||||
*out_sample += group_sample * group.volume;
|
||||
// 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);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process through the audio graph into a fresh buffer
|
||||
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 buffer back to pool
|
||||
// Release children mix buffer back to pool
|
||||
buffer_pool.release(group_buffer);
|
||||
}
|
||||
None => {}
|
||||
@@ -581,8 +609,8 @@ impl Project {
|
||||
TrackNode::Midi(midi_track) => {
|
||||
midi_track.prepare_for_save();
|
||||
}
|
||||
TrackNode::Group(_) => {
|
||||
// Groups don't have audio graphs
|
||||
TrackNode::Group(group) => {
|
||||
group.prepare_for_save();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -604,8 +632,8 @@ impl Project {
|
||||
TrackNode::Midi(midi_track) => {
|
||||
midi_track.rebuild_audio_graph(self.sample_rate, buffer_size)?;
|
||||
}
|
||||
TrackNode::Group(_) => {
|
||||
// Groups don't have audio graphs
|
||||
TrackNode::Group(group) => {
|
||||
group.rebuild_audio_graph(self.sample_rate, buffer_size)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,7 +153,7 @@ impl TrackNode {
|
||||
}
|
||||
|
||||
/// Metatrack that contains other tracks with time transformation capabilities
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Metatrack {
|
||||
pub id: TrackId,
|
||||
pub name: String,
|
||||
@@ -167,14 +167,50 @@ pub struct Metatrack {
|
||||
pub pitch_shift: f32,
|
||||
/// Time offset in seconds (shift content forward/backward in time)
|
||||
pub offset: f64,
|
||||
/// Trim start: offset into the metatrack's internal content (seconds)
|
||||
/// Children will see time starting from this point
|
||||
pub trim_start: f64,
|
||||
/// Trim end: offset into the metatrack's internal content (seconds)
|
||||
/// None means no end trim (play until content ends)
|
||||
pub trim_end: Option<f64>,
|
||||
/// Automation lanes for this metatrack
|
||||
pub automation_lanes: HashMap<AutomationLaneId, AutomationLane>,
|
||||
next_automation_id: AutomationLaneId,
|
||||
/// Audio node graph for effects processing (input → output)
|
||||
#[serde(skip, default = "default_audio_graph")]
|
||||
pub audio_graph: AudioGraph,
|
||||
/// Saved graph preset for serialization
|
||||
audio_graph_preset: Option<GraphPreset>,
|
||||
}
|
||||
|
||||
impl Clone for Metatrack {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
id: self.id,
|
||||
name: self.name.clone(),
|
||||
children: self.children.clone(),
|
||||
volume: self.volume,
|
||||
muted: self.muted,
|
||||
solo: self.solo,
|
||||
time_stretch: self.time_stretch,
|
||||
pitch_shift: self.pitch_shift,
|
||||
offset: self.offset,
|
||||
trim_start: self.trim_start,
|
||||
trim_end: self.trim_end,
|
||||
automation_lanes: self.automation_lanes.clone(),
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Metatrack {
|
||||
/// Create a new metatrack
|
||||
pub fn new(id: TrackId, name: String) -> Self {
|
||||
/// Create a new metatrack with an audio graph (input → output)
|
||||
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);
|
||||
|
||||
Self {
|
||||
id,
|
||||
name,
|
||||
@@ -185,11 +221,52 @@ impl Metatrack {
|
||||
time_stretch: 1.0,
|
||||
pitch_shift: 0.0,
|
||||
offset: 0.0,
|
||||
trim_start: 0.0,
|
||||
trim_end: None,
|
||||
automation_lanes: HashMap::new(),
|
||||
next_automation_id: 0,
|
||||
audio_graph,
|
||||
audio_graph_preset: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a default audio graph with AudioInput -> AudioOutput
|
||||
fn create_default_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);
|
||||
|
||||
let _ = graph.connect(input_id, 0, output_id, 0);
|
||||
graph.set_output_node(Some(output_id));
|
||||
|
||||
graph
|
||||
}
|
||||
|
||||
/// Prepare for serialization by saving the audio graph as a preset
|
||||
pub fn prepare_for_save(&mut self) {
|
||||
self.audio_graph_preset = Some(self.audio_graph.to_preset("Metatrack Graph"));
|
||||
}
|
||||
|
||||
/// Rebuild the audio graph from preset after deserialization
|
||||
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)?;
|
||||
} else {
|
||||
self.audio_graph = Self::create_default_graph(sample_rate, buffer_size);
|
||||
}
|
||||
} else {
|
||||
self.audio_graph = Self::create_default_graph(sample_rate, buffer_size);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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;
|
||||
@@ -282,11 +359,27 @@ impl Metatrack {
|
||||
!self.muted && (!any_solo || self.solo)
|
||||
}
|
||||
|
||||
/// Check whether this metatrack should produce audio at the given parent time.
|
||||
/// Returns false if the playhead is outside the trim window.
|
||||
pub fn is_active_at_time(&self, parent_playhead: f64) -> bool {
|
||||
let local_time = (parent_playhead - self.offset) * self.time_stretch as f64;
|
||||
if local_time < self.trim_start {
|
||||
return false;
|
||||
}
|
||||
if let Some(end) = self.trim_end {
|
||||
if local_time >= end {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Transform a render context for this metatrack's children
|
||||
///
|
||||
/// Applies time stretching and offset transformations.
|
||||
/// Applies time stretching, offset, and trim transformations.
|
||||
/// Time stretch affects how fast content plays: 0.5 = half speed, 2.0 = double speed
|
||||
/// Offset shifts content forward/backward in time
|
||||
/// Trim start offsets into the internal content
|
||||
pub fn transform_context(&self, ctx: RenderContext) -> RenderContext {
|
||||
let mut transformed = ctx;
|
||||
|
||||
@@ -300,7 +393,11 @@ impl Metatrack {
|
||||
// With stretch=0.5, when parent time is 2.0s, child reads from 1.0s (plays slower, pitches down)
|
||||
// With stretch=2.0, when parent time is 2.0s, child reads from 4.0s (plays faster, pitches up)
|
||||
// Note: This creates pitch shift as well - true time stretching would require resampling
|
||||
transformed.playhead_seconds = adjusted_playhead * self.time_stretch as f64;
|
||||
let stretched = adjusted_playhead * self.time_stretch as f64;
|
||||
|
||||
// 3. Add trim_start so children see time starting from the trim point
|
||||
// If trim_start=2.0, children start seeing time 2.0 when parent reaches offset
|
||||
transformed.playhead_seconds = stretched + self.trim_start;
|
||||
|
||||
// Accumulate time stretch for nested metatracks
|
||||
transformed.time_stretch *= self.time_stretch;
|
||||
|
||||
@@ -38,8 +38,8 @@ pub enum Command {
|
||||
ExtendClip(TrackId, ClipId, f64),
|
||||
|
||||
// Metatrack management commands
|
||||
/// Create a new metatrack with a name
|
||||
CreateMetatrack(String),
|
||||
/// Create a new metatrack with a name and optional parent group
|
||||
CreateMetatrack(String, Option<TrackId>),
|
||||
/// Add a track to a metatrack (track_id, metatrack_id)
|
||||
AddToMetatrack(TrackId, TrackId),
|
||||
/// Remove a track from its parent metatrack
|
||||
@@ -54,10 +54,16 @@ pub enum Command {
|
||||
SetOffset(TrackId, f64),
|
||||
/// Set metatrack pitch shift in semitones (track_id, semitones) - for future use
|
||||
SetPitchShift(TrackId, f32),
|
||||
/// Set metatrack trim start in seconds (track_id, trim_start)
|
||||
/// Children won't hear content before this point
|
||||
SetTrimStart(TrackId, f64),
|
||||
/// Set metatrack trim end in seconds (track_id, trim_end)
|
||||
/// None means no end trim
|
||||
SetTrimEnd(TrackId, Option<f64>),
|
||||
|
||||
// Audio track commands
|
||||
/// Create a new audio track with a name
|
||||
CreateAudioTrack(String),
|
||||
/// Create a new audio track with a name and optional parent group
|
||||
CreateAudioTrack(String, Option<TrackId>),
|
||||
/// Add an audio file to the pool (path, data, channels, sample_rate)
|
||||
/// Returns the pool index via an AudioEvent
|
||||
AddAudioFile(String, Vec<f32>, u32, u32),
|
||||
@@ -65,8 +71,8 @@ pub enum Command {
|
||||
AddAudioClip(TrackId, usize, f64, f64, f64),
|
||||
|
||||
// MIDI commands
|
||||
/// Create a new MIDI track with a name
|
||||
CreateMidiTrack(String),
|
||||
/// Create a new MIDI track with a name and optional parent group
|
||||
CreateMidiTrack(String, Option<TrackId>),
|
||||
/// Add a MIDI clip to the pool without placing it on a track
|
||||
AddMidiClipToPool(MidiClip),
|
||||
/// Create a new MIDI clip on a track (track_id, start_time, duration)
|
||||
@@ -361,10 +367,12 @@ pub enum Query {
|
||||
SerializeTrackGraph(TrackId, std::path::PathBuf),
|
||||
/// Load a track's effects/instrument graph (track_id, preset_json, project_path)
|
||||
LoadTrackGraph(TrackId, String, std::path::PathBuf),
|
||||
/// Create a new audio track (name) - returns track ID synchronously
|
||||
CreateAudioTrackSync(String),
|
||||
/// Create a new MIDI track (name) - returns track ID synchronously
|
||||
CreateMidiTrackSync(String),
|
||||
/// Create a new audio track (name, parent) - returns track ID synchronously
|
||||
CreateAudioTrackSync(String, Option<TrackId>),
|
||||
/// Create a new MIDI track (name, parent) - returns track ID synchronously
|
||||
CreateMidiTrackSync(String, Option<TrackId>),
|
||||
/// Create a new metatrack/group (name, parent) - returns track ID synchronously
|
||||
CreateMetatrackSync(String, Option<TrackId>),
|
||||
/// Get waveform data from audio pool (pool_index, target_peaks)
|
||||
GetPoolWaveform(usize, usize),
|
||||
/// Get file info from audio pool (pool_index) - returns (duration, sample_rate, channels)
|
||||
|
||||
Reference in New Issue
Block a user