Audio from videos

This commit is contained in:
Skyler Lehmkuhl
2025-12-03 01:04:09 -05:00
parent d453571c9b
commit ccb29a9e04
14 changed files with 937 additions and 23 deletions
@@ -426,6 +426,26 @@ impl FileOperationsWorker {
}
}
/// Result from background audio extraction thread
#[derive(Debug)]
enum AudioExtractionResult {
Success {
video_clip_id: Uuid,
audio_clip: lightningbeam_core::clip::AudioClip,
pool_index: usize,
video_name: String,
channels: u32,
sample_rate: u32,
},
NoAudio {
video_clip_id: Uuid,
},
Error {
video_clip_id: Uuid,
error: String,
},
}
struct EditorApp {
layouts: Vec<LayoutDefinition>,
current_layout_index: usize,
@@ -463,6 +483,8 @@ struct EditorApp {
// Track ID mapping (Document layer UUIDs <-> daw-backend TrackIds)
layer_to_track_map: HashMap<Uuid, daw_backend::TrackId>,
track_to_layer_map: HashMap<daw_backend::TrackId, Uuid>,
// Clip instance ID mapping (Document clip instance UUIDs <-> backend clip instance IDs)
clip_instance_to_backend_map: HashMap<Uuid, lightningbeam_core::action::BackendClipInstanceId>,
// Playback state (global for all panes)
playback_time: f64, // Current playback position in seconds (persistent - save with document)
is_playing: bool, // Whether playback is currently active (transient - don't save)
@@ -496,6 +518,10 @@ struct EditorApp {
file_command_tx: std::sync::mpsc::Sender<FileCommand>,
/// Current file operation in progress (if any)
file_operation: Option<FileOperation>,
/// Audio extraction channel for background thread communication
audio_extraction_tx: std::sync::mpsc::Sender<AudioExtractionResult>,
audio_extraction_rx: std::sync::mpsc::Receiver<AudioExtractionResult>,
}
/// Import filter types for the file dialog
@@ -580,6 +606,9 @@ impl EditorApp {
}
};
// Create audio extraction channel for background thread communication
let (audio_extraction_tx, audio_extraction_rx) = std::sync::mpsc::channel();
Self {
layouts,
current_layout_index: 0,
@@ -615,6 +644,7 @@ impl EditorApp {
)),
layer_to_track_map: HashMap::new(),
track_to_layer_map: HashMap::new(),
clip_instance_to_backend_map: HashMap::new(),
playback_time: 0.0, // Start at beginning
is_playing: false, // Start paused
dragging_asset: None, // No asset being dragged initially
@@ -630,6 +660,8 @@ impl EditorApp {
config,
file_command_tx,
file_operation: None, // No file operation in progress initially
audio_extraction_tx,
audio_extraction_rx,
}
}
@@ -983,6 +1015,7 @@ impl EditorApp {
let mut backend_context = lightningbeam_core::action::BackendContext {
audio_controller: Some(&mut *controller),
layer_to_track_map: &self.layer_to_track_map,
clip_instance_to_backend_map: &mut self.clip_instance_to_backend_map,
};
match self.action_executor.undo_with_backend(&mut backend_context) {
@@ -1004,6 +1037,7 @@ impl EditorApp {
let mut backend_context = lightningbeam_core::action::BackendContext {
audio_controller: Some(&mut *controller),
layer_to_track_map: &self.layer_to_track_map,
clip_instance_to_backend_map: &mut self.clip_instance_to_backend_map,
};
match self.action_executor.redo_with_backend(&mut backend_context) {
@@ -1723,8 +1757,78 @@ impl EditorApp {
}
drop(video_mgr);
// TODO: Extract audio in background thread if present
// TODO: Create AudioClip and link to VideoClip via linked_audio_clip_id
// Spawn background thread for audio extraction if video has audio
if metadata.has_audio {
if let Some(ref audio_controller) = self.audio_controller {
let path_clone = path_str.clone();
let video_clip_id = clip_id;
let video_name = name.clone();
let audio_controller_clone = Arc::clone(audio_controller);
let tx = self.audio_extraction_tx.clone();
std::thread::spawn(move || {
use lightningbeam_core::video::extract_audio_from_video;
use lightningbeam_core::clip::{AudioClip, AudioClipType};
// Extract audio from video (slow FFmpeg operation)
match extract_audio_from_video(&path_clone) {
Ok(Some(extracted)) => {
// Add audio to daw-backend pool synchronously to get pool index
let pool_index = {
let mut controller = audio_controller_clone.lock().unwrap();
match controller.add_audio_file_sync(
path_clone.clone(),
extracted.samples,
extracted.channels,
extracted.sample_rate,
) {
Ok(index) => index,
Err(e) => {
eprintln!("Failed to add audio file to backend: {}", e);
let _ = tx.send(AudioExtractionResult::Error {
video_clip_id,
error: format!("Failed to add audio to backend: {}", e),
});
return;
}
}
};
// Create AudioClip
let audio_clip_name = format!("{} (Audio)", video_name);
let audio_clip = AudioClip::new_sampled(
&audio_clip_name,
pool_index,
extracted.duration,
);
// Send success result
let _ = tx.send(AudioExtractionResult::Success {
video_clip_id,
audio_clip,
pool_index,
video_name,
channels: extracted.channels,
sample_rate: extracted.sample_rate,
});
}
Ok(None) => {
// Video has no audio stream
let _ = tx.send(AudioExtractionResult::NoAudio { video_clip_id });
}
Err(e) => {
// Audio extraction failed
let _ = tx.send(AudioExtractionResult::Error {
video_clip_id,
error: e,
});
}
}
});
} else {
eprintln!(" ⚠️ Video has audio but audio engine not initialized - skipping extraction");
}
}
// Spawn background thread for thumbnail generation
let video_manager_clone = Arc::clone(&self.video_manager);
@@ -1751,7 +1855,58 @@ impl EditorApp {
);
if metadata.has_audio {
println!(" Video has audio track (extraction not yet implemented)");
println!(" Extracting audio track in background...");
}
}
/// Handle audio extraction results from background thread
fn handle_audio_extraction_result(&mut self, result: AudioExtractionResult) {
match result {
AudioExtractionResult::Success {
video_clip_id,
audio_clip,
pool_index,
video_name,
channels,
sample_rate,
} => {
// Add AudioClip to document
let audio_clip_id = self.action_executor.document_mut().add_audio_clip(audio_clip);
// Update VideoClip's linked_audio_clip_id
if let Some(video_clip) = self.action_executor.document_mut().video_clips
.get_mut(&video_clip_id)
{
video_clip.linked_audio_clip_id = Some(audio_clip_id);
// Get audio clip duration for logging
let duration = self.action_executor.document().audio_clips
.get(&audio_clip_id)
.map(|c| c.duration)
.unwrap_or(0.0);
println!("✅ Extracted audio from '{}' ({:.1}s, {}ch, {}Hz) - AudioClip ID: {}",
video_name,
duration,
channels,
sample_rate,
audio_clip_id
);
// Fetch waveform from backend and cache it for rendering
if let Some(waveform) = self.fetch_waveform(pool_index) {
println!(" Cached waveform with {} peaks", waveform.len());
}
} else {
eprintln!("⚠️ Audio extracted but VideoClip {} not found (may have been deleted)", video_clip_id);
}
}
AudioExtractionResult::NoAudio { video_clip_id } => {
println!("ℹ️ Video {} has no audio stream", video_clip_id);
}
AudioExtractionResult::Error { video_clip_id, error } => {
eprintln!("❌ Failed to extract audio from video {}: {}", video_clip_id, error);
}
}
}
}
@@ -1764,6 +1919,11 @@ impl eframe::App for EditorApp {
o.zoom_with_keyboard = false;
});
// Poll audio extraction results from background threads
while let Ok(result) = self.audio_extraction_rx.try_recv() {
self.handle_audio_extraction_result(result);
}
// Check for native menu events (macOS)
if let Some(menu_system) = &self.menu_system {
if let Some(action) = menu_system.check_events() {
@@ -2014,6 +2174,11 @@ impl eframe::App for EditorApp {
self.pending_view_action = None;
}
// Sync any new audio layers created during this frame to the backend
// This handles layers created directly (e.g., auto-created audio tracks for video+audio)
// Must happen BEFORE executing actions so the layer-to-track mapping is available
self.sync_audio_layers_to_backend();
// Execute all pending actions (two-phase dispatch)
for action in pending_actions {
// Create backend context for actions that need backend sync
@@ -2022,6 +2187,7 @@ impl eframe::App for EditorApp {
let mut backend_context = lightningbeam_core::action::BackendContext {
audio_controller: Some(&mut *controller),
layer_to_track_map: &self.layer_to_track_map,
clip_instance_to_backend_map: &mut self.clip_instance_to_backend_map,
};
// Execute action with backend synchronization
@@ -674,8 +674,18 @@ impl AssetLibraryPane {
});
}
// Collect audio clips
// Build set of audio clip IDs that are linked to videos
let linked_audio_ids: std::collections::HashSet<uuid::Uuid> = document.video_clips.values()
.filter_map(|video| video.linked_audio_clip_id)
.collect();
// Collect audio clips (skip those linked to videos)
for (id, clip) in &document.audio_clips {
// Skip if this audio clip is linked to a video
if linked_audio_ids.contains(id) {
continue;
}
let (extra_info, drag_clip_type) = match &clip.clip_type {
AudioClipType::Sampled { .. } => ("Sampled".to_string(), DragClipType::AudioSampled),
AudioClipType::Midi { .. } => ("MIDI".to_string(), DragClipType::AudioMidi),
@@ -1292,12 +1302,23 @@ impl AssetLibraryPane {
// Handle drag start
if response.drag_started() {
// For video clips, get the linked audio clip ID
let linked_audio_clip_id = if asset.drag_clip_type == DragClipType::Video {
let result = document.video_clips.get(&asset.id)
.and_then(|video| video.linked_audio_clip_id);
eprintln!("DEBUG DRAG: Video clip {} has linked audio: {:?}", asset.id, result);
result
} else {
None
};
*shared.dragging_asset = Some(DraggingAsset {
clip_id: asset.id,
clip_type: asset.drag_clip_type,
name: asset.name.clone(),
duration: asset.duration,
dimensions: asset.dimensions,
linked_audio_clip_id,
});
}
@@ -1587,12 +1608,23 @@ impl AssetLibraryPane {
// Handle drag start
if response.drag_started() {
// For video clips, get the linked audio clip ID
let linked_audio_clip_id = if asset.drag_clip_type == DragClipType::Video {
let result = document.video_clips.get(&asset.id)
.and_then(|video| video.linked_audio_clip_id);
eprintln!("DEBUG DRAG: Video clip {} has linked audio: {:?}", asset.id, result);
result
} else {
None
};
*shared.dragging_asset = Some(DraggingAsset {
clip_id: asset.id,
clip_type: asset.drag_clip_type,
name: asset.name.clone(),
duration: asset.duration,
dimensions: asset.dimensions,
linked_audio_clip_id,
});
}
}
@@ -48,6 +48,8 @@ pub struct DraggingAsset {
pub duration: f64,
/// Dimensions (width, height) for vector/video clips, None for audio
pub dimensions: Option<(f64, f64)>,
/// Optional linked audio clip ID (for video clips with extracted audio)
pub linked_audio_clip_id: Option<Uuid>,
}
pub mod toolbar;
@@ -38,6 +38,19 @@ fn create_layer_for_clip_type(clip_type: DragClipType, name: &str) -> AnyLayer {
}
}
/// Find an existing sampled audio track in the document
/// Returns the layer ID if found, None otherwise
fn find_sampled_audio_track(document: &lightningbeam_core::document::Document) -> Option<uuid::Uuid> {
for layer in &document.root.children {
if let AnyLayer::Audio(audio_layer) = layer {
if audio_layer.audio_layer_type == AudioLayerType::Sampled {
return Some(audio_layer.layer.id);
}
}
}
None
}
/// Shared Vello resources (created once, reused by all Stage panes)
struct SharedVelloResources {
renderer: Arc<Mutex<vello::Renderer>>,
@@ -4169,6 +4182,9 @@ impl PaneRenderer for StagePane {
// Handle drop on mouse release
if ui.input(|i| i.pointer.any_released()) {
eprintln!("DEBUG STAGE DROP: Dropping clip type {:?}, linked_audio: {:?}",
dragging.clip_type, dragging.linked_audio_clip_id);
// Convert screen position to world coordinates
let canvas_pos = pointer_pos - rect.min;
let world_pos = (canvas_pos - self.pan_offset) / self.zoom;
@@ -4274,12 +4290,67 @@ impl PaneRenderer for StagePane {
}
}
// Create and queue action
// Save instance ID for potential grouping
let video_instance_id = clip_instance.id;
// Create and queue action for video
let action = lightningbeam_core::actions::AddClipInstanceAction::new(
layer_id,
clip_instance,
);
shared.pending_actions.push(Box::new(action));
// If video has linked audio, auto-place it and create group
if let Some(linked_audio_clip_id) = dragging.linked_audio_clip_id {
eprintln!("DEBUG STAGE: Video has linked audio clip: {}", linked_audio_clip_id);
// Find or create sampled audio track
let audio_layer_id = {
let doc = shared.action_executor.document();
let result = find_sampled_audio_track(doc);
if let Some(id) = result {
eprintln!("DEBUG STAGE: Found existing audio track: {}", id);
} else {
eprintln!("DEBUG STAGE: No existing audio track found");
}
result
}.unwrap_or_else(|| {
eprintln!("DEBUG STAGE: Creating new audio track");
// Create new sampled audio layer
let audio_layer = AudioLayer::new_sampled("Audio Track");
let layer_id = shared.action_executor.document_mut().root.add_child(
AnyLayer::Audio(audio_layer)
);
eprintln!("DEBUG STAGE: Created audio layer with ID: {}", layer_id);
layer_id
});
eprintln!("DEBUG STAGE: Using audio layer ID: {}", audio_layer_id);
// Create audio clip instance at same timeline position
let audio_instance = ClipInstance::new(linked_audio_clip_id)
.with_timeline_start(drop_time);
let audio_instance_id = audio_instance.id;
eprintln!("DEBUG STAGE: Created audio instance: {} for clip: {}", audio_instance_id, linked_audio_clip_id);
// Queue audio action
let audio_action = lightningbeam_core::actions::AddClipInstanceAction::new(
audio_layer_id,
audio_instance,
);
shared.pending_actions.push(Box::new(audio_action));
eprintln!("DEBUG STAGE: Queued audio action, total pending: {}", shared.pending_actions.len());
// Create instance group linking video and audio
let mut group = lightningbeam_core::instance_group::InstanceGroup::new();
group.add_member(layer_id, video_instance_id);
group.add_member(audio_layer_id, audio_instance_id);
shared.action_executor.document_mut().add_instance_group(group);
eprintln!("DEBUG STAGE: Created instance group");
} else {
eprintln!("DEBUG STAGE: Video has NO linked audio clip!");
}
}
}
@@ -72,6 +72,19 @@ fn can_drop_on_layer(layer: &AnyLayer, clip_type: DragClipType) -> bool {
}
}
/// Find an existing sampled audio track in the document
/// Returns the layer ID if found, None otherwise
fn find_sampled_audio_track(document: &lightningbeam_core::document::Document) -> Option<uuid::Uuid> {
for layer in &document.root.children {
if let AnyLayer::Audio(audio_layer) = layer {
if audio_layer.audio_layer_type == AudioLayerType::Sampled {
return Some(audio_layer.layer.id);
}
}
}
None
}
impl TimelinePane {
pub fn new() -> Self {
Self {
@@ -2086,35 +2099,93 @@ impl PaneRenderer for TimelinePane {
let layer_id = layer.id();
let drop_time = self.x_to_time(pointer_pos.x - content_rect.min.x).max(0.0);
// Get document dimensions for centering
let doc = shared.action_executor.document();
let center_x = doc.width / 2.0;
let center_y = doc.height / 2.0;
// Get document dimensions for centering and create clip instance
let (center_x, center_y, mut clip_instance) = {
let doc = shared.action_executor.document();
let center_x = doc.width / 2.0;
let center_y = doc.height / 2.0;
// Create clip instance centered on stage, at drop time
let mut clip_instance = ClipInstance::new(dragging.clip_id)
.with_timeline_start(drop_time)
.with_position(center_x, center_y);
let mut clip_instance = ClipInstance::new(dragging.clip_id)
.with_timeline_start(drop_time)
.with_position(center_x, center_y);
// For video clips, scale to fill document dimensions
if dragging.clip_type == DragClipType::Video {
if let Some((video_width, video_height)) = dragging.dimensions {
// Calculate scale to fill document
let scale_x = doc.width / video_width;
let scale_y = doc.height / video_height;
// For video clips, scale to fill document dimensions
if dragging.clip_type == DragClipType::Video {
if let Some((video_width, video_height)) = dragging.dimensions {
// Calculate scale to fill document
let scale_x = doc.width / video_width;
let scale_y = doc.height / video_height;
clip_instance.transform.scale_x = scale_x;
clip_instance.transform.scale_y = scale_y;
clip_instance.transform.scale_x = scale_x;
clip_instance.transform.scale_y = scale_y;
}
}
}
// Create and queue action
(center_x, center_y, clip_instance)
}; // doc is dropped here
// Save instance ID for potential grouping
let video_instance_id = clip_instance.id;
// Create and queue action for video
let action = lightningbeam_core::actions::AddClipInstanceAction::new(
layer_id,
clip_instance,
);
shared.pending_actions.push(Box::new(action));
// If video has linked audio, auto-place it and create group
if let Some(linked_audio_clip_id) = dragging.linked_audio_clip_id {
eprintln!("DEBUG: Video has linked audio clip: {}", linked_audio_clip_id);
// Find or create sampled audio track
let audio_layer_id = {
let doc = shared.action_executor.document();
let result = find_sampled_audio_track(doc);
if let Some(id) = result {
eprintln!("DEBUG: Found existing audio track: {}", id);
} else {
eprintln!("DEBUG: No existing audio track found");
}
result
}.unwrap_or_else(|| {
eprintln!("DEBUG: Creating new audio track");
// Create new sampled audio layer
let audio_layer = lightningbeam_core::layer::AudioLayer::new_sampled("Audio Track");
let layer_id = shared.action_executor.document_mut().root.add_child(
lightningbeam_core::layer::AnyLayer::Audio(audio_layer)
);
eprintln!("DEBUG: Created audio layer with ID: {}", layer_id);
layer_id
});
eprintln!("DEBUG: Using audio layer ID: {}", audio_layer_id);
// Create audio clip instance at same timeline position
let audio_instance = ClipInstance::new(linked_audio_clip_id)
.with_timeline_start(drop_time);
let audio_instance_id = audio_instance.id;
eprintln!("DEBUG: Created audio instance: {} for clip: {}", audio_instance_id, linked_audio_clip_id);
// Queue audio action
let audio_action = lightningbeam_core::actions::AddClipInstanceAction::new(
audio_layer_id,
audio_instance,
);
shared.pending_actions.push(Box::new(audio_action));
eprintln!("DEBUG: Queued audio action, total pending: {}", shared.pending_actions.len());
// Create instance group linking video and audio
let mut group = lightningbeam_core::instance_group::InstanceGroup::new();
group.add_member(layer_id, video_instance_id);
group.add_member(audio_layer_id, audio_instance_id);
shared.action_executor.document_mut().add_instance_group(group);
eprintln!("DEBUG: Created instance group");
} else {
eprintln!("DEBUG: Video has NO linked audio clip!");
}
// Clear drag state
*shared.dragging_asset = None;
}