Add nested audio tracks

This commit is contained in:
Skyler Lehmkuhl
2026-02-21 03:56:07 -05:00
parent 70855963cb
commit 469849a0d6
17 changed files with 600 additions and 150 deletions
@@ -43,6 +43,9 @@ pub struct BackendContext<'a> {
/// Mapping from document clip instance UUIDs to backend clip instance IDs
pub clip_instance_to_backend_map: &'a mut HashMap<Uuid, BackendClipInstanceId>,
/// Mapping from movie clip UUIDs to backend metatrack (group track) TrackIds
pub clip_to_metatrack_map: &'a HashMap<Uuid, daw_backend::TrackId>,
// Future: pub video_controller: Option<&'a mut VideoController>,
}
@@ -12,6 +12,9 @@ pub struct AddLayerAction {
/// The layer to add
layer: AnyLayer,
/// If Some, add to this VectorClip's layers instead of root
target_clip_id: Option<Uuid>,
/// ID of the created layer (set after execution)
created_layer_id: Option<Uuid>,
}
@@ -26,6 +29,7 @@ impl AddLayerAction {
let layer = VectorLayer::new(name);
Self {
layer: AnyLayer::Vector(layer),
target_clip_id: None,
created_layer_id: None,
}
}
@@ -38,10 +42,17 @@ impl AddLayerAction {
pub fn new(layer: AnyLayer) -> Self {
Self {
layer,
target_clip_id: None,
created_layer_id: None,
}
}
/// Set the target clip for this action (add layer inside a movie clip)
pub fn with_target_clip(mut self, clip_id: Option<Uuid>) -> Self {
self.target_clip_id = clip_id;
self
}
/// Get the ID of the created layer (after execution)
pub fn created_layer_id(&self) -> Option<Uuid> {
self.created_layer_id
@@ -50,8 +61,19 @@ impl AddLayerAction {
impl Action for AddLayerAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
// Add layer to the document's root
let layer_id = document.root_mut().add_child(self.layer.clone());
let layer_id = if let Some(clip_id) = self.target_clip_id {
// Add layer inside a vector clip (movie clip)
let clip = document.vector_clips.get_mut(&clip_id)
.ok_or_else(|| format!("Target clip {} not found", clip_id))?;
let id = self.layer.id();
clip.layers.add_root(self.layer.clone());
// Register in layer_to_clip_map for O(1) lookup
document.layer_to_clip_map.insert(id, clip_id);
id
} else {
// Add layer to the document's root
document.root_mut().add_child(self.layer.clone())
};
// Store the ID for rollback
self.created_layer_id = Some(layer_id);
@@ -62,7 +84,15 @@ impl Action for AddLayerAction {
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
// Remove the created layer if it exists
if let Some(layer_id) = self.created_layer_id {
document.root_mut().remove_child(&layer_id);
if let Some(clip_id) = self.target_clip_id {
// Remove from vector clip
if let Some(clip) = document.vector_clips.get_mut(&clip_id) {
clip.layers.roots.retain(|node| node.data.id() != layer_id);
}
document.layer_to_clip_map.remove(&layer_id);
} else {
document.root_mut().remove_child(&layer_id);
}
// Clear the stored ID
self.created_layer_id = None;
@@ -190,6 +190,21 @@ impl Action for MoveClipInstancesAction {
let layer = document.get_layer(layer_id)
.ok_or_else(|| format!("Layer {} not found", layer_id))?;
// Handle vector layers: update metatrack offset for movie clips with audio
if let AnyLayer::Vector(vl) = layer {
for (instance_id, _old_start, new_start) in moves {
if let Some(instance) = vl.clip_instances.iter().find(|ci| ci.id == *instance_id) {
// Check if this clip has a metatrack
if let Some(&metatrack_id) = backend.clip_to_metatrack_map.get(&instance.clip_id) {
controller.set_offset(metatrack_id, *new_start);
controller.set_trim_start(metatrack_id, instance.trim_start);
controller.set_trim_end(metatrack_id, instance.trim_end);
}
}
}
continue;
}
// Only process audio layers
if !matches!(layer, AnyLayer::Audio(_)) {
continue;
@@ -260,6 +275,20 @@ impl Action for MoveClipInstancesAction {
let layer = document.get_layer(layer_id)
.ok_or_else(|| format!("Layer {} not found", layer_id))?;
// Handle vector layers: restore metatrack offset for movie clips with audio
if let AnyLayer::Vector(vl) = layer {
for (instance_id, old_start, _new_start) in moves {
if let Some(instance) = vl.clip_instances.iter().find(|ci| ci.id == *instance_id) {
if let Some(&metatrack_id) = backend.clip_to_metatrack_map.get(&instance.clip_id) {
controller.set_offset(metatrack_id, *old_start);
controller.set_trim_start(metatrack_id, instance.trim_start);
controller.set_trim_end(metatrack_id, instance.trim_end);
}
}
}
continue;
}
// Only process audio layers
if !matches!(layer, AnyLayer::Audio(_)) {
continue;
@@ -76,8 +76,8 @@ impl SetLayerPropertiesAction {
impl Action for SetLayerPropertiesAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
for (i, &layer_id) in self.layer_ids.iter().enumerate() {
// Find the layer in the document
if let Some(layer) = document.root_mut().get_child_mut(&layer_id) {
// Find the layer in the document (searches root + inside movie clips)
if let Some(layer) = document.get_layer_mut(&layer_id) {
// Store old value if not already stored
if self.old_values[i].is_none() {
self.old_values[i] = Some(match &self.property {
@@ -106,8 +106,8 @@ impl Action for SetLayerPropertiesAction {
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
for (i, &layer_id) in self.layer_ids.iter().enumerate() {
// Find the layer in the document
if let Some(layer) = document.root_mut().get_child_mut(&layer_id) {
// Find the layer in the document (searches root + inside movie clips)
if let Some(layer) = document.get_layer_mut(&layer_id) {
// Restore old value if we have one
if let Some(old_value) = &self.old_values[i] {
match old_value {
@@ -355,6 +355,21 @@ impl Action for TrimClipInstancesAction {
let layer = document.get_layer(layer_id)
.ok_or_else(|| format!("Layer {} not found", layer_id))?;
// Handle vector layers: update metatrack trim for movie clips with audio
if let AnyLayer::Vector(vl) = layer {
for (instance_id, _trim_type, _old, _new) in trims {
if let Some(instance) = vl.clip_instances.iter().find(|ci| ci.id == *instance_id) {
if let Some(&metatrack_id) = backend.clip_to_metatrack_map.get(&instance.clip_id) {
// Instance already has new values after execute()
controller.set_offset(metatrack_id, instance.timeline_start);
controller.set_trim_start(metatrack_id, instance.trim_start);
controller.set_trim_end(metatrack_id, instance.trim_end);
}
}
}
continue;
}
// Only process audio layers
if !matches!(layer, AnyLayer::Audio(_)) {
continue;
@@ -430,6 +445,21 @@ impl Action for TrimClipInstancesAction {
let layer = document.get_layer(layer_id)
.ok_or_else(|| format!("Layer {} not found", layer_id))?;
// Handle vector layers: restore metatrack trim for movie clips with audio
if let AnyLayer::Vector(vl) = layer {
for (instance_id, _trim_type, _old, _new) in trims {
if let Some(instance) = vl.clip_instances.iter().find(|ci| ci.id == *instance_id) {
if let Some(&metatrack_id) = backend.clip_to_metatrack_map.get(&instance.clip_id) {
// Instance already has old values after rollback()
controller.set_offset(metatrack_id, instance.timeline_start);
controller.set_trim_start(metatrack_id, instance.trim_start);
controller.set_trim_end(metatrack_id, instance.trim_end);
}
}
}
continue;
}
// Only process audio layers
if !matches!(layer, AnyLayer::Audio(_)) {
continue;
@@ -90,14 +90,49 @@ impl VectorClip {
}
}
/// Calculate the duration of this clip based on its internal keyframe content.
/// Returns the time of the last keyframe across all layers, plus one frame.
/// Falls back to the stored `duration` field if no keyframes exist.
/// Calculate the duration of this clip based on its internal content.
///
/// Considers:
/// - Vector layer keyframes (last keyframe time + one frame)
/// - Audio/video/effect layer clip instances (timeline_start + effective duration)
///
/// The `clip_duration_fn` resolves referenced clip durations for non-vector layers.
/// Falls back to the stored `duration` field if no content exists.
pub fn content_duration(&self, framerate: f64) -> f64 {
self.content_duration_with(framerate, |_| None)
}
/// Like `content_duration`, but with a closure that resolves clip durations
/// for audio/video/effect clip instances inside this movie clip.
pub fn content_duration_with(&self, framerate: f64, clip_duration_fn: impl Fn(&Uuid) -> Option<f64>) -> f64 {
let frame_duration = 1.0 / framerate;
let mut last_time: Option<f64> = None;
for layer_node in self.layers.iter() {
// Check clip instances on ALL layer types (vector, audio, video, effect)
let clip_instances: &[ClipInstance] = match &layer_node.data {
AnyLayer::Vector(vl) => &vl.clip_instances,
AnyLayer::Audio(al) => &al.clip_instances,
AnyLayer::Video(vl) => &vl.clip_instances,
AnyLayer::Effect(el) => &el.clip_instances,
};
for ci in clip_instances {
let end = if let Some(td) = ci.timeline_duration {
ci.timeline_start + td
} else if let Some(te) = ci.trim_end {
ci.timeline_start + (te - ci.trim_start).max(0.0)
} else if let Some(clip_dur) = clip_duration_fn(&ci.clip_id) {
ci.timeline_start + (clip_dur - ci.trim_start).max(0.0)
} else {
continue;
};
last_time = Some(match last_time {
Some(t) => t.max(end),
None => end,
});
}
// Also check vector layer keyframes
if let AnyLayer::Vector(vector_layer) = &layer_node.data {
if let Some(last_kf) = vector_layer.keyframes.last() {
last_time = Some(match last_time {
@@ -462,6 +462,15 @@ impl Document {
self.context_layers_mut(clip_id).into_iter().find(|l| &l.id() == layer_id)
}
/// Get all layers across the entire document (root + inside all vector clips).
pub fn all_layers(&self) -> Vec<&AnyLayer> {
let mut layers: Vec<&AnyLayer> = self.root.children.iter().collect();
for clip in self.vector_clips.values() {
layers.extend(clip.layers.root_data());
}
layers
}
// === CLIP LIBRARY METHODS ===
/// Add a vector clip to the library
@@ -645,7 +654,21 @@ impl Document {
if clip.is_group {
Some(clip.duration)
} else {
Some(clip.content_duration(self.framerate))
Some(clip.content_duration_with(self.framerate, |id| {
// Resolve nested clip durations (audio, video, other vector clips)
if let Some(vc) = self.vector_clips.get(id) {
// Avoid deep recursion — use stored duration for nested vector clips
Some(vc.content_duration(self.framerate))
} else if let Some(ac) = self.audio_clips.get(id) {
Some(ac.duration)
} else if let Some(vc) = self.video_clips.get(id) {
Some(vc.duration)
} else if self.effect_definitions.contains_key(id) {
Some(crate::effect::EFFECT_DURATION)
} else {
None
}
}))
}
} else if let Some(clip) = self.video_clips.get(clip_id) {
Some(clip.duration)
@@ -60,6 +60,10 @@ pub struct SerializedAudioBackend {
/// Preserves the connection between UI layers and audio engine tracks across save/load
#[serde(default)]
pub layer_to_track_map: std::collections::HashMap<uuid::Uuid, u32>,
/// Mapping from movie clip UUIDs to backend metatrack (group track) TrackIds
#[serde(default)]
pub clip_to_metatrack_map: std::collections::HashMap<uuid::Uuid, u32>,
}
/// Settings for saving a project
@@ -96,6 +100,9 @@ pub struct LoadedProject {
/// Mapping from UI layer UUIDs to backend TrackIds (empty for old files)
pub layer_to_track_map: std::collections::HashMap<uuid::Uuid, u32>,
/// Mapping from movie clip UUIDs to backend metatrack TrackIds (empty for old files)
pub clip_to_metatrack_map: std::collections::HashMap<uuid::Uuid, u32>,
/// Loaded audio pool entries
pub audio_pool_entries: Vec<AudioPoolEntry>,
@@ -147,6 +154,7 @@ pub fn save_beam(
audio_project: &mut AudioProject,
audio_pool_entries: Vec<AudioPoolEntry>,
layer_to_track_map: &std::collections::HashMap<uuid::Uuid, u32>,
clip_to_metatrack_map: &std::collections::HashMap<uuid::Uuid, u32>,
_settings: &SaveSettings,
) -> Result<(), String> {
let fn_start = std::time::Instant::now();
@@ -375,6 +383,7 @@ pub fn save_beam(
project: audio_project.clone(),
audio_pool_entries: modified_entries,
layer_to_track_map: layer_to_track_map.clone(),
clip_to_metatrack_map: clip_to_metatrack_map.clone(),
},
};
eprintln!("📊 [SAVE_BEAM] Step 5: Build BeamProject structure took {:.2}ms", step5_start.elapsed().as_secs_f64() * 1000.0);
@@ -462,6 +471,7 @@ pub fn load_beam(path: &Path) -> Result<LoadedProject, String> {
let mut audio_project = beam_project.audio_backend.project;
let audio_pool_entries = beam_project.audio_backend.audio_pool_entries;
let layer_to_track_map = beam_project.audio_backend.layer_to_track_map;
let clip_to_metatrack_map = beam_project.audio_backend.clip_to_metatrack_map;
eprintln!("📊 [LOAD_BEAM] Step 5: Extract document and audio state took {:.2}ms", step5_start.elapsed().as_secs_f64() * 1000.0);
// 6. Rebuild AudioGraphs from presets
@@ -607,6 +617,7 @@ pub fn load_beam(path: &Path) -> Result<LoadedProject, String> {
document,
audio_project,
layer_to_track_map,
clip_to_metatrack_map,
audio_pool_entries: restored_entries,
missing_files,
})
@@ -498,7 +498,7 @@ fn render_clip_instance(
}
0.0
} else {
let clip_dur = vector_clip.content_duration(document.framerate);
let clip_dur = document.get_clip_duration(&vector_clip.id).unwrap_or(vector_clip.duration);
let Some(t) = clip_instance.remap_time(time, clip_dur) else {
return; // Clip instance not active at this time
};