Load audio clips
This commit is contained in:
@@ -330,8 +330,12 @@ impl FileOperationsWorker {
|
||||
) {
|
||||
use lightningbeam_core::file_io::{save_beam, SaveSettings};
|
||||
|
||||
let save_start = std::time::Instant::now();
|
||||
eprintln!("📊 [SAVE] Starting save operation...");
|
||||
|
||||
// Step 1: Serialize audio pool
|
||||
let _ = progress_tx.send(FileProgress::SerializingAudioPool);
|
||||
let step1_start = std::time::Instant::now();
|
||||
|
||||
let audio_pool_entries = {
|
||||
let mut controller = self.audio_controller.lock().unwrap();
|
||||
@@ -343,8 +347,10 @@ impl FileOperationsWorker {
|
||||
}
|
||||
}
|
||||
};
|
||||
eprintln!("📊 [SAVE] Step 1: Serialize audio pool took {:.2}ms", step1_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// Step 2: Get project
|
||||
let step2_start = std::time::Instant::now();
|
||||
let mut audio_project = {
|
||||
let mut controller = self.audio_controller.lock().unwrap();
|
||||
match controller.get_project() {
|
||||
@@ -355,13 +361,17 @@ impl FileOperationsWorker {
|
||||
}
|
||||
}
|
||||
};
|
||||
eprintln!("📊 [SAVE] Step 2: Get audio project took {:.2}ms", step2_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// Step 3: Save to file
|
||||
let _ = progress_tx.send(FileProgress::WritingZip);
|
||||
let step3_start = std::time::Instant::now();
|
||||
|
||||
let settings = SaveSettings::default();
|
||||
match save_beam(&path, &document, &mut audio_project, audio_pool_entries, &settings) {
|
||||
Ok(()) => {
|
||||
eprintln!("📊 [SAVE] Step 3: save_beam() took {:.2}ms", step3_start.elapsed().as_secs_f64() * 1000.0);
|
||||
eprintln!("📊 [SAVE] ✅ Total save time: {:.2}ms", save_start.elapsed().as_secs_f64() * 1000.0);
|
||||
println!("✅ Saved to: {}", path.display());
|
||||
let _ = progress_tx.send(FileProgress::Done);
|
||||
}
|
||||
@@ -379,8 +389,12 @@ impl FileOperationsWorker {
|
||||
) {
|
||||
use lightningbeam_core::file_io::load_beam;
|
||||
|
||||
let load_start = std::time::Instant::now();
|
||||
eprintln!("📊 [LOAD] Starting load operation...");
|
||||
|
||||
// Step 1: Load from file
|
||||
let _ = progress_tx.send(FileProgress::LoadingProject);
|
||||
let step1_start = std::time::Instant::now();
|
||||
|
||||
let loaded_project = match load_beam(&path) {
|
||||
Ok(p) => p,
|
||||
@@ -389,6 +403,7 @@ impl FileOperationsWorker {
|
||||
return;
|
||||
}
|
||||
};
|
||||
eprintln!("📊 [LOAD] Step 1: load_beam() took {:.2}ms", step1_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// Check for missing files
|
||||
if !loaded_project.missing_files.is_empty() {
|
||||
@@ -398,6 +413,8 @@ impl FileOperationsWorker {
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!("📊 [LOAD] ✅ Total load time: {:.2}ms", load_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// Send the loaded project back to UI thread for processing
|
||||
let _ = progress_tx.send(FileProgress::Complete(Ok(loaded_project)));
|
||||
}
|
||||
@@ -455,6 +472,10 @@ struct EditorApp {
|
||||
/// Prevents repeated backend queries for the same MIDI clip
|
||||
/// Format: (timestamp, note_number, is_note_on)
|
||||
midi_event_cache: HashMap<u32, Vec<(f64, u8, bool)>>,
|
||||
/// Cache for audio waveform data (keyed by audio_pool_index)
|
||||
/// Prevents repeated backend queries for the same audio file
|
||||
/// Format: Vec of WaveformPeak (min/max pairs)
|
||||
waveform_cache: HashMap<usize, Vec<daw_backend::WaveformPeak>>,
|
||||
/// Current file path (None if not yet saved)
|
||||
current_file_path: Option<std::path::PathBuf>,
|
||||
|
||||
@@ -578,6 +599,7 @@ impl EditorApp {
|
||||
paint_bucket_gap_tolerance: 5.0, // Default gap tolerance
|
||||
polygon_sides: 5, // Default to pentagon
|
||||
midi_event_cache: HashMap::new(), // Initialize empty MIDI event cache
|
||||
waveform_cache: HashMap::new(), // Initialize empty waveform cache
|
||||
current_file_path: None, // No file loaded initially
|
||||
file_command_tx,
|
||||
file_operation: None, // No file operation in progress initially
|
||||
@@ -590,48 +612,71 @@ impl EditorApp {
|
||||
/// - After loading a document from file
|
||||
/// - After creating a new document with pre-existing MIDI layers
|
||||
///
|
||||
/// For each MIDI audio layer:
|
||||
/// 1. Creates a daw-backend MIDI track
|
||||
/// 2. Loads the default instrument
|
||||
/// For each audio layer (MIDI or Sampled):
|
||||
/// 1. Creates a daw-backend track (MIDI or Audio)
|
||||
/// 2. For MIDI: Loads the default instrument
|
||||
/// 3. Stores the bidirectional mapping
|
||||
/// 4. Syncs any existing clips on the layer
|
||||
fn sync_midi_layers_to_backend(&mut self) {
|
||||
fn sync_audio_layers_to_backend(&mut self) {
|
||||
use lightningbeam_core::layer::{AnyLayer, AudioLayerType};
|
||||
|
||||
// Iterate through all layers in the document
|
||||
for layer in &self.action_executor.document().root.children {
|
||||
// Only process Audio layers with MIDI type
|
||||
// Only process Audio layers
|
||||
if let AnyLayer::Audio(audio_layer) = layer {
|
||||
if audio_layer.audio_layer_type == AudioLayerType::Midi {
|
||||
let layer_id = audio_layer.layer.id;
|
||||
let layer_name = &audio_layer.layer.name;
|
||||
let layer_id = audio_layer.layer.id;
|
||||
let layer_name = &audio_layer.layer.name;
|
||||
|
||||
// Skip if already mapped (shouldn't happen, but be defensive)
|
||||
if self.layer_to_track_map.contains_key(&layer_id) {
|
||||
continue;
|
||||
}
|
||||
// Skip if already mapped (shouldn't happen, but be defensive)
|
||||
if self.layer_to_track_map.contains_key(&layer_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Create daw-backend MIDI track
|
||||
if let Some(ref controller_arc) = self.audio_controller {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
match controller.create_midi_track_sync(layer_name.clone()) {
|
||||
Ok(track_id) => {
|
||||
// Store bidirectional mapping
|
||||
self.layer_to_track_map.insert(layer_id, track_id);
|
||||
self.track_to_layer_map.insert(track_id, layer_id);
|
||||
// Handle both MIDI and Sampled audio tracks
|
||||
match audio_layer.audio_layer_type {
|
||||
AudioLayerType::Midi => {
|
||||
// Create daw-backend MIDI track
|
||||
if let Some(ref controller_arc) = self.audio_controller {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
match controller.create_midi_track_sync(layer_name.clone()) {
|
||||
Ok(track_id) => {
|
||||
// Store bidirectional mapping
|
||||
self.layer_to_track_map.insert(layer_id, track_id);
|
||||
self.track_to_layer_map.insert(track_id, layer_id);
|
||||
|
||||
// Load default instrument
|
||||
if let Err(e) = default_instrument::load_default_instrument(&mut *controller, track_id) {
|
||||
eprintln!("⚠️ Failed to load default instrument for {}: {}", layer_name, e);
|
||||
} else {
|
||||
println!("✅ Synced MIDI layer '{}' to backend (TrackId: {})", layer_name, track_id);
|
||||
// Load default instrument
|
||||
if let Err(e) = default_instrument::load_default_instrument(&mut *controller, track_id) {
|
||||
eprintln!("⚠️ Failed to load default instrument for {}: {}", layer_name, e);
|
||||
} else {
|
||||
println!("✅ Synced MIDI layer '{}' to backend (TrackId: {})", layer_name, track_id);
|
||||
}
|
||||
|
||||
// TODO: Sync any existing clips on this layer to the backend
|
||||
// This will be implemented when we add clip synchronization
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("⚠️ Failed to create daw-backend track for MIDI layer '{}': {}", layer_name, e);
|
||||
}
|
||||
|
||||
// TODO: Sync any existing clips on this layer to the backend
|
||||
// This will be implemented when we add clip synchronization
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("⚠️ Failed to create daw-backend track for MIDI layer '{}': {}", layer_name, e);
|
||||
}
|
||||
}
|
||||
AudioLayerType::Sampled => {
|
||||
// Create daw-backend Audio track
|
||||
if let Some(ref controller_arc) = self.audio_controller {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
match controller.create_audio_track_sync(layer_name.clone()) {
|
||||
Ok(track_id) => {
|
||||
// Store bidirectional mapping
|
||||
self.layer_to_track_map.insert(layer_id, track_id);
|
||||
self.track_to_layer_map.insert(track_id, layer_id);
|
||||
println!("✅ Synced Audio layer '{}' to backend (TrackId: {})", layer_name, track_id);
|
||||
|
||||
// TODO: Sync any existing clips on this layer to the backend
|
||||
// This will be implemented when we add clip synchronization
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("⚠️ Failed to create daw-backend audio track for '{}': {}", layer_name, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -640,6 +685,34 @@ impl EditorApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch waveform data from backend for a specific audio pool index
|
||||
/// Returns cached data if available, otherwise queries backend
|
||||
fn fetch_waveform(&mut self, pool_index: usize) -> Option<Vec<daw_backend::WaveformPeak>> {
|
||||
// Check if already cached
|
||||
if let Some(waveform) = self.waveform_cache.get(&pool_index) {
|
||||
return Some(waveform.clone());
|
||||
}
|
||||
|
||||
// Fetch from backend
|
||||
// Request 20,000 peaks for high-detail waveform visualization
|
||||
// For a 200s file, this gives ~100 peaks/second, providing smooth visualization at all zoom levels
|
||||
if let Some(ref controller_arc) = self.audio_controller {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
match controller.get_pool_waveform(pool_index, 20000) {
|
||||
Ok(waveform) => {
|
||||
self.waveform_cache.insert(pool_index, waveform.clone());
|
||||
Some(waveform)
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("⚠️ Failed to fetch waveform for pool index {}: {}", pool_index, e);
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn switch_layout(&mut self, index: usize) {
|
||||
self.current_layout_index = index;
|
||||
self.current_layout = self.layouts[index].layout.clone();
|
||||
@@ -969,8 +1042,37 @@ impl EditorApp {
|
||||
// TODO: Implement add video layer
|
||||
}
|
||||
MenuAction::AddAudioTrack => {
|
||||
println!("Menu: Add Audio Track");
|
||||
// TODO: Implement add audio track
|
||||
// Create a new sampled audio layer with a default name
|
||||
let layer_count = self.action_executor.document().root.children.len();
|
||||
let layer_name = format!("Audio Track {}", layer_count + 1);
|
||||
|
||||
// Create audio layer in document
|
||||
let audio_layer = AudioLayer::new_sampled(layer_name.clone());
|
||||
let action = lightningbeam_core::actions::AddLayerAction::new(AnyLayer::Audio(audio_layer));
|
||||
self.action_executor.execute(Box::new(action));
|
||||
|
||||
// Get the newly created layer ID
|
||||
if let Some(last_layer) = self.action_executor.document().root.children.last() {
|
||||
let layer_id = last_layer.id();
|
||||
self.active_layer_id = Some(layer_id);
|
||||
|
||||
// Create corresponding daw-backend audio track
|
||||
if let Some(ref controller_arc) = self.audio_controller {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
match controller.create_audio_track_sync(layer_name.clone()) {
|
||||
Ok(track_id) => {
|
||||
// Store bidirectional mapping
|
||||
self.layer_to_track_map.insert(layer_id, track_id);
|
||||
self.track_to_layer_map.insert(track_id, layer_id);
|
||||
println!("✅ Created {} (backend TrackId: {})", layer_name, track_id);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("⚠️ Failed to create daw-backend audio track for {}: {}", layer_name, e);
|
||||
eprintln!(" Layer created but will be silent until backend track is available");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
MenuAction::AddMidiTrack => {
|
||||
// Create a new MIDI audio layer with a default name
|
||||
@@ -1270,6 +1372,9 @@ impl EditorApp {
|
||||
fn apply_loaded_project(&mut self, loaded_project: lightningbeam_core::file_io::LoadedProject, path: std::path::PathBuf) {
|
||||
use lightningbeam_core::action::ActionExecutor;
|
||||
|
||||
let apply_start = std::time::Instant::now();
|
||||
eprintln!("📊 [APPLY] Starting apply_loaded_project() on UI thread...");
|
||||
|
||||
// Check for missing files
|
||||
if !loaded_project.missing_files.is_empty() {
|
||||
eprintln!("⚠️ {} missing files", loaded_project.missing_files.len());
|
||||
@@ -1280,33 +1385,78 @@ impl EditorApp {
|
||||
}
|
||||
|
||||
// Replace document
|
||||
let step1_start = std::time::Instant::now();
|
||||
self.action_executor = ActionExecutor::new(loaded_project.document);
|
||||
eprintln!("📊 [APPLY] Step 1: Replace document took {:.2}ms", step1_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// Restore UI layout from loaded document
|
||||
let step2_start = std::time::Instant::now();
|
||||
self.restore_layout_from_document();
|
||||
eprintln!("📊 [APPLY] Step 2: Restore UI layout took {:.2}ms", step2_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// Set project in audio engine via query
|
||||
let step3_start = std::time::Instant::now();
|
||||
if let Some(ref controller_arc) = self.audio_controller {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
if let Err(e) = controller.set_project(loaded_project.audio_project) {
|
||||
eprintln!("❌ Failed to set project: {}", e);
|
||||
return;
|
||||
}
|
||||
eprintln!("📊 [APPLY] Step 3: Set audio project took {:.2}ms", step3_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// Load audio pool
|
||||
if let Err(e) = controller.load_audio_pool(
|
||||
loaded_project.audio_pool_entries,
|
||||
&path,
|
||||
) {
|
||||
eprintln!("❌ Failed to load audio pool: {}", e);
|
||||
return;
|
||||
}
|
||||
// Load audio pool asynchronously to avoid blocking UI
|
||||
let step4_start = std::time::Instant::now();
|
||||
let controller_clone = controller_arc.clone();
|
||||
let path_clone = path.clone();
|
||||
let audio_pool_entries = loaded_project.audio_pool_entries;
|
||||
|
||||
std::thread::spawn(move || {
|
||||
eprintln!("📊 [APPLY] Step 4: Starting async audio pool load...");
|
||||
let load_start = std::time::Instant::now();
|
||||
let mut controller = controller_clone.lock().unwrap();
|
||||
if let Err(e) = controller.load_audio_pool(audio_pool_entries, &path_clone) {
|
||||
eprintln!("❌ Failed to load audio pool: {}", e);
|
||||
} else {
|
||||
eprintln!("📊 [APPLY] Step 4: Async audio pool load completed in {:.2}ms", load_start.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
});
|
||||
eprintln!("📊 [APPLY] Step 4: Spawned async audio pool load in {:.2}ms", step4_start.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
|
||||
// Reset state
|
||||
let step5_start = std::time::Instant::now();
|
||||
self.layer_to_track_map.clear();
|
||||
self.track_to_layer_map.clear();
|
||||
self.sync_midi_layers_to_backend();
|
||||
eprintln!("📊 [APPLY] Step 5: Clear track maps took {:.2}ms", step5_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// Sync audio layers (MIDI and Sampled)
|
||||
let step6_start = std::time::Instant::now();
|
||||
self.sync_audio_layers_to_backend();
|
||||
eprintln!("📊 [APPLY] Step 6: Sync audio layers took {:.2}ms", step6_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// Fetch waveforms for all audio clips in the loaded project
|
||||
let step7_start = std::time::Instant::now();
|
||||
// Collect pool indices first to avoid borrowing issues
|
||||
let pool_indices: Vec<usize> = self.action_executor.document()
|
||||
.audio_clips.values()
|
||||
.filter_map(|clip| {
|
||||
if let lightningbeam_core::clip::AudioClipType::Sampled { audio_pool_index } = &clip.clip_type {
|
||||
Some(*audio_pool_index)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut waveforms_fetched = 0;
|
||||
for pool_index in pool_indices {
|
||||
if self.fetch_waveform(pool_index).is_some() {
|
||||
waveforms_fetched += 1;
|
||||
}
|
||||
}
|
||||
eprintln!("📊 [APPLY] Step 7: Fetched {} waveforms in {:.2}ms", waveforms_fetched, step7_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// Reset playback state
|
||||
self.playback_time = 0.0;
|
||||
self.is_playing = false;
|
||||
self.current_file_path = Some(path.clone());
|
||||
@@ -1316,6 +1466,7 @@ impl EditorApp {
|
||||
self.active_layer_id = Some(first.id());
|
||||
}
|
||||
|
||||
eprintln!("📊 [APPLY] ✅ Total apply_loaded_project() time: {:.2}ms", apply_start.elapsed().as_secs_f64() * 1000.0);
|
||||
println!("✅ Loaded from: {}", path.display());
|
||||
}
|
||||
|
||||
@@ -1376,23 +1527,31 @@ impl EditorApp {
|
||||
|
||||
// Add to audio engine pool if available
|
||||
if let Some(ref controller_arc) = self.audio_controller {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
// Send audio data to the engine
|
||||
let path_str = path.to_string_lossy().to_string();
|
||||
controller.add_audio_file(
|
||||
path_str.clone(),
|
||||
audio_file.data,
|
||||
channels,
|
||||
sample_rate,
|
||||
);
|
||||
let pool_index = {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
// Send audio data to the engine
|
||||
let path_str = path.to_string_lossy().to_string();
|
||||
controller.add_audio_file(
|
||||
path_str.clone(),
|
||||
audio_file.data,
|
||||
channels,
|
||||
sample_rate,
|
||||
);
|
||||
|
||||
// For now, use a placeholder pool index (the engine will assign the real one)
|
||||
// In a full implementation, we'd wait for the AudioFileAdded event
|
||||
let pool_index = self.action_executor.document().audio_clips.len();
|
||||
// For now, use a placeholder pool index (the engine will assign the real one)
|
||||
// In a full implementation, we'd wait for the AudioFileAdded event
|
||||
self.action_executor.document().audio_clips.len()
|
||||
}; // Controller lock is dropped here
|
||||
|
||||
// Create audio clip in document
|
||||
let clip = AudioClip::new_sampled(&name, pool_index, duration);
|
||||
let clip_id = self.action_executor.document_mut().add_audio_clip(clip);
|
||||
|
||||
// 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());
|
||||
}
|
||||
|
||||
println!("Imported audio '{}' ({:.1}s, {}ch, {}Hz) - ID: {}",
|
||||
name, duration, channels, sample_rate, clip_id);
|
||||
} else {
|
||||
@@ -1504,6 +1663,29 @@ impl eframe::App for EditorApp {
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch missing waveforms on-demand (for lazy loading after project load)
|
||||
// Collect pool indices that need waveforms
|
||||
let missing_waveforms: Vec<usize> = self.action_executor.document()
|
||||
.audio_clips.values()
|
||||
.filter_map(|clip| {
|
||||
if let lightningbeam_core::clip::AudioClipType::Sampled { audio_pool_index } = &clip.clip_type {
|
||||
// Check if not already cached
|
||||
if !self.waveform_cache.contains_key(audio_pool_index) {
|
||||
Some(*audio_pool_index)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Fetch missing waveforms
|
||||
for pool_index in missing_waveforms {
|
||||
self.fetch_waveform(pool_index);
|
||||
}
|
||||
|
||||
// Handle file operation progress
|
||||
if let Some(ref mut operation) = self.file_operation {
|
||||
// Set wait cursor
|
||||
@@ -1675,6 +1857,7 @@ impl eframe::App for EditorApp {
|
||||
polygon_sides: &mut self.polygon_sides,
|
||||
layer_to_track_map: &self.layer_to_track_map,
|
||||
midi_event_cache: &self.midi_event_cache,
|
||||
waveform_cache: &self.waveform_cache,
|
||||
};
|
||||
|
||||
render_layout_node(
|
||||
@@ -1843,6 +2026,8 @@ struct RenderContext<'a> {
|
||||
layer_to_track_map: &'a std::collections::HashMap<Uuid, daw_backend::TrackId>,
|
||||
/// Cache of MIDI events for rendering (keyed by backend midi_clip_id)
|
||||
midi_event_cache: &'a HashMap<u32, Vec<(f64, u8, bool)>>,
|
||||
/// Cache of waveform data for rendering (keyed by audio_pool_index)
|
||||
waveform_cache: &'a HashMap<usize, Vec<daw_backend::WaveformPeak>>,
|
||||
}
|
||||
|
||||
/// Recursively render a layout node with drag support
|
||||
@@ -2314,6 +2499,7 @@ fn render_pane(
|
||||
paint_bucket_gap_tolerance: ctx.paint_bucket_gap_tolerance,
|
||||
polygon_sides: ctx.polygon_sides,
|
||||
midi_event_cache: ctx.midi_event_cache,
|
||||
waveform_cache: ctx.waveform_cache,
|
||||
};
|
||||
pane_instance.render_header(&mut header_ui, &mut shared);
|
||||
}
|
||||
@@ -2368,6 +2554,7 @@ fn render_pane(
|
||||
paint_bucket_gap_tolerance: ctx.paint_bucket_gap_tolerance,
|
||||
polygon_sides: ctx.polygon_sides,
|
||||
midi_event_cache: ctx.midi_event_cache,
|
||||
waveform_cache: ctx.waveform_cache,
|
||||
};
|
||||
|
||||
// Render pane content (header was already rendered above)
|
||||
|
||||
@@ -127,6 +127,8 @@ pub struct SharedPaneState<'a> {
|
||||
pub polygon_sides: &'a mut u32,
|
||||
/// Cache of MIDI events for rendering (keyed by backend midi_clip_id)
|
||||
pub midi_event_cache: &'a std::collections::HashMap<u32, Vec<(f64, u8, bool)>>,
|
||||
/// Cache of waveform data for rendering (keyed by audio_pool_index)
|
||||
pub waveform_cache: &'a std::collections::HashMap<usize, Vec<daw_backend::WaveformPeak>>,
|
||||
}
|
||||
|
||||
/// Trait for pane rendering
|
||||
|
||||
@@ -14,7 +14,7 @@ use super::{DragClipType, NodePath, PaneRenderer, SharedPaneState};
|
||||
const RULER_HEIGHT: f32 = 30.0;
|
||||
const LAYER_HEIGHT: f32 = 60.0;
|
||||
const LAYER_HEADER_WIDTH: f32 = 200.0;
|
||||
const MIN_PIXELS_PER_SECOND: f32 = 20.0;
|
||||
const MIN_PIXELS_PER_SECOND: f32 = 1.0; // Allow zooming out to see 10+ minutes
|
||||
const MAX_PIXELS_PER_SECOND: f32 = 500.0;
|
||||
const EDGE_DETECTION_PIXELS: f32 = 8.0; // Distance from edge to detect trim handles
|
||||
|
||||
@@ -456,6 +456,135 @@ impl TimelinePane {
|
||||
}
|
||||
}
|
||||
|
||||
/// Render waveform visualization for audio clips on timeline
|
||||
/// Uses peak-based rendering: each waveform sample has a fixed pixel width that scales with zoom
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render_audio_waveform(
|
||||
painter: &egui::Painter,
|
||||
clip_rect: egui::Rect,
|
||||
clip_start_x: f32, // Absolute screen x where clip starts (can be offscreen)
|
||||
clip_bg_color: egui::Color32, // Background color of the clip
|
||||
waveform: &[daw_backend::WaveformPeak],
|
||||
clip_duration: f64,
|
||||
pixels_per_second: f32,
|
||||
trim_start: f64,
|
||||
theme: &crate::theme::Theme,
|
||||
ctx: &egui::Context,
|
||||
) {
|
||||
if waveform.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let clip_height = clip_rect.height();
|
||||
let center_y = clip_rect.center().y;
|
||||
|
||||
// Calculate waveform color: lighten the clip background color
|
||||
// Blend clip background with white (70% white + 30% clip color) for subtle tint
|
||||
// Use full opacity to prevent overlapping lines from blending lighter when zoomed out
|
||||
let r = ((255.0 * 0.7) + (clip_bg_color.r() as f32 * 0.3)) as u8;
|
||||
let g = ((255.0 * 0.7) + (clip_bg_color.g() as f32 * 0.3)) as u8;
|
||||
let b = ((255.0 * 0.7) + (clip_bg_color.b() as f32 * 0.3)) as u8;
|
||||
let waveform_color = egui::Color32::from_rgb(r, g, b);
|
||||
|
||||
// Calculate how wide each peak should be at current zoom (mirrors JavaScript)
|
||||
// fullSourceWidth = sourceDuration * pixelsPerSecond
|
||||
// pixelsPerPeak = fullSourceWidth / waveformData.length
|
||||
let full_source_width = clip_duration * pixels_per_second as f64;
|
||||
let pixels_per_peak = full_source_width / waveform.len() as f64;
|
||||
|
||||
// Calculate which peak corresponds to the clip's offset (trimmed left edge)
|
||||
let offset_peak_index = ((trim_start / clip_duration) * waveform.len() as f64).floor() as usize;
|
||||
let offset_peak_index = offset_peak_index.min(waveform.len().saturating_sub(1));
|
||||
|
||||
// Calculate visible peak range
|
||||
// firstVisiblePeak = max(offsetPeakIndex, floor((visibleStart - startX) / pixelsPerPeak) + offsetPeakIndex)
|
||||
let visible_start = clip_rect.min.x;
|
||||
let visible_end = clip_rect.max.x;
|
||||
|
||||
let first_visible_peak_from_viewport = if pixels_per_peak > 0.0 {
|
||||
(((visible_start - clip_start_x) as f64 / pixels_per_peak).floor() as isize + offset_peak_index as isize).max(0)
|
||||
} else {
|
||||
offset_peak_index as isize
|
||||
};
|
||||
let first_visible_peak = (first_visible_peak_from_viewport as usize).max(offset_peak_index);
|
||||
|
||||
let last_visible_peak_from_viewport = if pixels_per_peak > 0.0 {
|
||||
((visible_end - clip_start_x) as f64 / pixels_per_peak).ceil() as isize + offset_peak_index as isize
|
||||
} else {
|
||||
offset_peak_index as isize
|
||||
};
|
||||
let last_visible_peak = (last_visible_peak_from_viewport as usize)
|
||||
.min(waveform.len().saturating_sub(1));
|
||||
|
||||
if first_visible_peak > last_visible_peak || first_visible_peak >= waveform.len() {
|
||||
return;
|
||||
}
|
||||
|
||||
println!("\n🎵 WAVEFORM RENDER:");
|
||||
println!(" Waveform total peaks: {}", waveform.len());
|
||||
println!(" Clip duration: {:.2}s", clip_duration);
|
||||
println!(" Pixels per second: {}", pixels_per_second);
|
||||
println!(" Pixels per peak: {:.4}", pixels_per_peak);
|
||||
println!(" Trim start: {:.2}s", trim_start);
|
||||
println!(" Offset peak index: {}", offset_peak_index);
|
||||
println!(" Clip start X: {:.1}", clip_start_x);
|
||||
println!(" Clip rect: x=[{:.1}, {:.1}], y=[{:.1}, {:.1}]",
|
||||
clip_rect.min.x, clip_rect.max.x, clip_rect.min.y, clip_rect.max.y);
|
||||
println!(" Visible start: {:.1}, end: {:.1}", visible_start, visible_end);
|
||||
println!(" First visible peak: {} (time: {:.2}s)",
|
||||
first_visible_peak, first_visible_peak as f64 * clip_duration / waveform.len() as f64);
|
||||
println!(" Last visible peak: {} (time: {:.2}s)",
|
||||
last_visible_peak, last_visible_peak as f64 * clip_duration / waveform.len() as f64);
|
||||
println!(" Peak range size: {}", last_visible_peak - first_visible_peak + 1);
|
||||
|
||||
// Draw waveform as vertical lines from min to max
|
||||
// Line width scales with zoom to avoid gaps between peaks
|
||||
let line_width = if pixels_per_peak > 1.0 {
|
||||
pixels_per_peak.ceil() as f32
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
|
||||
let mut peaks_drawn = 0;
|
||||
let mut lines = Vec::new();
|
||||
|
||||
for i in first_visible_peak..=last_visible_peak {
|
||||
if i >= waveform.len() {
|
||||
break;
|
||||
}
|
||||
|
||||
let peak_x = clip_start_x + ((i as isize - offset_peak_index as isize) as f64 * pixels_per_peak) as f32;
|
||||
let peak = &waveform[i];
|
||||
|
||||
// Calculate Y positions for min and max
|
||||
let max_y = center_y + (peak.max * clip_height * 0.45);
|
||||
let min_y = center_y + (peak.min * clip_height * 0.45);
|
||||
|
||||
if peaks_drawn < 3 {
|
||||
println!(" PEAK[{}]: x={:.1}, min={:.3} (y={:.1}), max={:.3} (y={:.1})",
|
||||
i, peak_x, peak.min, min_y, peak.max, max_y);
|
||||
}
|
||||
|
||||
// Draw vertical line from min to max
|
||||
lines.push((
|
||||
egui::pos2(peak_x, max_y),
|
||||
egui::pos2(peak_x, min_y),
|
||||
));
|
||||
|
||||
peaks_drawn += 1;
|
||||
}
|
||||
|
||||
println!(" Peaks drawn: {}, line width: {:.1}px", peaks_drawn, line_width);
|
||||
|
||||
// Draw all lines with clipping
|
||||
for (start, end) in lines {
|
||||
painter.with_clip_rect(clip_rect).line_segment(
|
||||
[start, end],
|
||||
egui::Stroke::new(line_width, waveform_color),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Render layer header column (left side with track names and controls)
|
||||
fn render_layer_headers(
|
||||
&mut self,
|
||||
@@ -514,9 +643,14 @@ impl TimelinePane {
|
||||
let layer_data = layer.layer();
|
||||
let layer_name = &layer_data.name;
|
||||
let (layer_type, type_color) = match layer {
|
||||
lightningbeam_core::layer::AnyLayer::Vector(_) => ("Vector", egui::Color32::from_rgb(100, 150, 255)), // Blue
|
||||
lightningbeam_core::layer::AnyLayer::Audio(_) => ("Audio", egui::Color32::from_rgb(100, 255, 150)), // Green
|
||||
lightningbeam_core::layer::AnyLayer::Video(_) => ("Video", egui::Color32::from_rgb(255, 150, 100)), // Orange
|
||||
lightningbeam_core::layer::AnyLayer::Vector(_) => ("Vector", egui::Color32::from_rgb(255, 180, 100)), // Orange
|
||||
lightningbeam_core::layer::AnyLayer::Audio(audio_layer) => {
|
||||
match audio_layer.audio_layer_type {
|
||||
lightningbeam_core::layer::AudioLayerType::Midi => ("MIDI", egui::Color32::from_rgb(100, 255, 150)), // Green
|
||||
lightningbeam_core::layer::AudioLayerType::Sampled => ("Audio", egui::Color32::from_rgb(100, 180, 255)), // Blue
|
||||
}
|
||||
}
|
||||
lightningbeam_core::layer::AnyLayer::Video(_) => ("Video", egui::Color32::from_rgb(255, 150, 100)), // Orange/Red
|
||||
};
|
||||
|
||||
// Color indicator bar on the left edge
|
||||
@@ -735,6 +869,7 @@ impl TimelinePane {
|
||||
active_layer_id: &Option<uuid::Uuid>,
|
||||
selection: &lightningbeam_core::selection::Selection,
|
||||
midi_event_cache: &std::collections::HashMap<u32, Vec<(f64, u8, bool)>>,
|
||||
waveform_cache: &std::collections::HashMap<usize, Vec<daw_backend::WaveformPeak>>,
|
||||
) {
|
||||
let painter = ui.painter();
|
||||
|
||||
@@ -875,16 +1010,24 @@ impl TimelinePane {
|
||||
// Choose color based on layer type
|
||||
let (clip_color, bright_color) = match layer {
|
||||
lightningbeam_core::layer::AnyLayer::Vector(_) => (
|
||||
egui::Color32::from_rgb(100, 150, 255), // Blue
|
||||
egui::Color32::from_rgb(150, 200, 255), // Bright blue
|
||||
),
|
||||
lightningbeam_core::layer::AnyLayer::Audio(_) => (
|
||||
egui::Color32::from_rgb(100, 255, 150), // Green
|
||||
egui::Color32::from_rgb(150, 255, 200), // Bright green
|
||||
egui::Color32::from_rgb(220, 150, 80), // Orange
|
||||
egui::Color32::from_rgb(255, 210, 150), // Bright orange
|
||||
),
|
||||
lightningbeam_core::layer::AnyLayer::Audio(audio_layer) => {
|
||||
match audio_layer.audio_layer_type {
|
||||
lightningbeam_core::layer::AudioLayerType::Midi => (
|
||||
egui::Color32::from_rgb(100, 200, 150), // Green
|
||||
egui::Color32::from_rgb(150, 255, 200), // Bright green
|
||||
),
|
||||
lightningbeam_core::layer::AudioLayerType::Sampled => (
|
||||
egui::Color32::from_rgb(80, 150, 220), // Blue
|
||||
egui::Color32::from_rgb(150, 210, 255), // Bright blue
|
||||
),
|
||||
}
|
||||
}
|
||||
lightningbeam_core::layer::AnyLayer::Video(_) => (
|
||||
egui::Color32::from_rgb(255, 150, 100), // Orange
|
||||
egui::Color32::from_rgb(255, 200, 150), // Bright orange
|
||||
egui::Color32::from_rgb(255, 150, 100), // Orange/Red
|
||||
egui::Color32::from_rgb(255, 200, 150), // Bright orange/red
|
||||
),
|
||||
};
|
||||
|
||||
@@ -900,24 +1043,47 @@ impl TimelinePane {
|
||||
clip_color,
|
||||
);
|
||||
|
||||
// MIDI VISUALIZATION: Draw piano roll overlay for MIDI clips
|
||||
// AUDIO VISUALIZATION: Draw piano roll or waveform overlay
|
||||
if let lightningbeam_core::layer::AnyLayer::Audio(_) = layer {
|
||||
if let Some(clip) = document.get_audio_clip(&clip_instance.clip_id) {
|
||||
if let lightningbeam_core::clip::AudioClipType::Midi { midi_clip_id } = &clip.clip_type {
|
||||
if let Some(events) = midi_event_cache.get(midi_clip_id) {
|
||||
Self::render_midi_piano_roll(
|
||||
painter,
|
||||
clip_rect,
|
||||
rect.min.x, // Pass timeline panel left edge for proper positioning
|
||||
events,
|
||||
clip_instance.trim_start,
|
||||
instance_duration,
|
||||
instance_start,
|
||||
self.viewport_start_time,
|
||||
self.pixels_per_second,
|
||||
theme,
|
||||
ui.ctx(),
|
||||
);
|
||||
match &clip.clip_type {
|
||||
// MIDI: Draw piano roll
|
||||
lightningbeam_core::clip::AudioClipType::Midi { midi_clip_id } => {
|
||||
if let Some(events) = midi_event_cache.get(midi_clip_id) {
|
||||
Self::render_midi_piano_roll(
|
||||
painter,
|
||||
clip_rect,
|
||||
rect.min.x, // Pass timeline panel left edge for proper positioning
|
||||
events,
|
||||
clip_instance.trim_start,
|
||||
instance_duration,
|
||||
instance_start,
|
||||
self.viewport_start_time,
|
||||
self.pixels_per_second,
|
||||
theme,
|
||||
ui.ctx(),
|
||||
);
|
||||
}
|
||||
}
|
||||
// Sampled Audio: Draw waveform
|
||||
lightningbeam_core::clip::AudioClipType::Sampled { audio_pool_index } => {
|
||||
if let Some(waveform) = waveform_cache.get(audio_pool_index) {
|
||||
// Calculate absolute screen x where clip starts (can be offscreen)
|
||||
let clip_start_x = rect.min.x + start_x;
|
||||
|
||||
Self::render_audio_waveform(
|
||||
painter,
|
||||
clip_rect,
|
||||
clip_start_x,
|
||||
clip_color, // Pass clip background color for tinting
|
||||
waveform,
|
||||
clip.duration,
|
||||
self.pixels_per_second,
|
||||
clip_instance.trim_start,
|
||||
theme,
|
||||
ui.ctx(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1673,7 +1839,7 @@ impl PaneRenderer for TimelinePane {
|
||||
|
||||
// Render layer rows with clipping
|
||||
ui.set_clip_rect(content_rect.intersect(original_clip_rect));
|
||||
self.render_layers(ui, content_rect, shared.theme, document, shared.active_layer_id, shared.selection, shared.midi_event_cache);
|
||||
self.render_layers(ui, content_rect, shared.theme, document, shared.active_layer_id, shared.selection, shared.midi_event_cache, shared.waveform_cache);
|
||||
|
||||
// Render playhead on top (clip to timeline area)
|
||||
ui.set_clip_rect(timeline_rect.intersect(original_clip_rect));
|
||||
|
||||
Reference in New Issue
Block a user