Import .mid files to midi tracks

This commit is contained in:
Skyler Lehmkuhl
2025-12-01 05:35:53 -05:00
parent c09cd276a0
commit 5379e3bc8c
13 changed files with 683 additions and 84 deletions
@@ -288,6 +288,11 @@ struct EditorApp {
fill_enabled: bool, // Whether to fill shapes (default: true)
paint_bucket_gap_tolerance: f64, // Fill gap tolerance for paint bucket (default: 5.0)
polygon_sides: u32, // Number of sides for polygon tool (default: 5)
/// Cache for MIDI event data (keyed by backend midi_clip_id)
/// 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)>>,
}
/// Import filter types for the file dialog
@@ -382,6 +387,7 @@ impl EditorApp {
fill_enabled: true, // Default to filling shapes
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
}
}
@@ -601,17 +607,43 @@ impl EditorApp {
// Edit menu
MenuAction::Undo => {
if self.action_executor.undo() {
println!("Undid: {}", self.action_executor.redo_description().unwrap_or_default());
if let Some(ref mut audio_system) = self.audio_system {
let mut backend_context = lightningbeam_core::action::BackendContext {
audio_controller: Some(&mut audio_system.controller),
layer_to_track_map: &self.layer_to_track_map,
};
match self.action_executor.undo_with_backend(&mut backend_context) {
Ok(true) => println!("Undid: {}", self.action_executor.redo_description().unwrap_or_default()),
Ok(false) => println!("Nothing to undo"),
Err(e) => eprintln!("Undo failed: {}", e),
}
} else {
println!("Nothing to undo");
if self.action_executor.undo() {
println!("Undid: {}", self.action_executor.redo_description().unwrap_or_default());
} else {
println!("Nothing to undo");
}
}
}
MenuAction::Redo => {
if self.action_executor.redo() {
println!("Redid: {}", self.action_executor.undo_description().unwrap_or_default());
if let Some(ref mut audio_system) = self.audio_system {
let mut backend_context = lightningbeam_core::action::BackendContext {
audio_controller: Some(&mut audio_system.controller),
layer_to_track_map: &self.layer_to_track_map,
};
match self.action_executor.redo_with_backend(&mut backend_context) {
Ok(true) => println!("Redid: {}", self.action_executor.undo_description().unwrap_or_default()),
Ok(false) => println!("Nothing to redo"),
Err(e) => eprintln!("Redo failed: {}", e),
}
} else {
println!("Nothing to redo");
if self.action_executor.redo() {
println!("Redid: {}", self.action_executor.undo_description().unwrap_or_default());
} else {
println!("Nothing to redo");
}
}
}
MenuAction::Cut => {
@@ -948,7 +980,7 @@ impl EditorApp {
/// Import a MIDI file via daw-backend
fn import_midi(&mut self, path: &std::path::Path) {
use lightningbeam_core::clip::{AudioClip, AudioClipType, MidiEvent};
use lightningbeam_core::clip::AudioClip;
let name = path.file_stem()
.and_then(|s| s.to_str())
@@ -956,26 +988,45 @@ impl EditorApp {
.to_string();
// Load MIDI file via daw-backend
// Note: daw-backend's load_midi_file returns a MidiClip with events
match daw_backend::io::midi_file::load_midi_file(path, 0, 44100) {
Ok(midi_clip) => {
// Convert daw-backend MidiEvents to our MidiEvent type
let events: Vec<MidiEvent> = midi_clip.events.iter().map(|e| {
MidiEvent::new(e.timestamp, e.status, e.data1, e.data2)
}).collect();
let duration = midi_clip.duration;
let event_count = midi_clip.events.len();
// Create MIDI audio clip in document library
let clip = AudioClip::new_midi(&name, duration, events, false);
let clip_id = self.action_executor.document_mut().add_audio_clip(clip);
println!("Imported MIDI '{}' ({:.1}s, {} events) to library - ID: {}",
name, duration, midi_clip.events.len(), clip_id);
// Process MIDI events to cache format: (timestamp, note_number, is_note_on)
// Filter to note events only (status 0x90 = note-on, 0x80 = note-off)
let processed_events: Vec<(f64, u8, bool)> = midi_clip.events.iter()
.filter_map(|event| {
let status_type = event.status & 0xF0;
if status_type == 0x90 || status_type == 0x80 {
// Note-on is 0x90 with velocity > 0, Note-off is 0x80 or velocity = 0
let is_note_on = status_type == 0x90 && event.data2 > 0;
Some((event.timestamp, event.data1, is_note_on))
} else {
None // Ignore non-note events (CC, pitch bend, etc.)
}
})
.collect();
// Add to daw-backend MIDI clip pool (for playback when placed on timeline)
let note_event_count = processed_events.len();
// Add to backend MIDI clip pool FIRST and get the backend clip ID
if let Some(ref mut audio_system) = self.audio_system {
audio_system.controller.add_midi_clip_to_pool(midi_clip);
println!("✅ Added MIDI clip to backend pool");
audio_system.controller.add_midi_clip_to_pool(midi_clip.clone());
let backend_clip_id = midi_clip.id; // The backend clip ID
// Cache MIDI events in frontend for rendering (thumbnails & timeline piano roll)
self.midi_event_cache.insert(backend_clip_id, processed_events);
// Create frontend MIDI clip referencing the backend pool
let clip = AudioClip::new_midi(&name, backend_clip_id, duration);
let frontend_clip_id = self.action_executor.document_mut().add_audio_clip(clip);
println!("Imported MIDI '{}' ({:.1}s, {} total events, {} note events) - Frontend ID: {}, Backend ID: {}",
name, duration, event_count, note_event_count, frontend_clip_id, backend_clip_id);
println!("✅ Added MIDI clip to backend pool and cached {} note events", note_event_count);
} else {
eprintln!("⚠️ Cannot import MIDI: audio system not available");
}
}
Err(e) => {
@@ -1102,6 +1153,7 @@ impl eframe::App for EditorApp {
paint_bucket_gap_tolerance: &mut self.paint_bucket_gap_tolerance,
polygon_sides: &mut self.polygon_sides,
layer_to_track_map: &self.layer_to_track_map,
midi_event_cache: &self.midi_event_cache,
};
render_layout_node(
@@ -1136,7 +1188,21 @@ impl eframe::App for EditorApp {
// Execute all pending actions (two-phase dispatch)
for action in pending_actions {
self.action_executor.execute(action);
// Create backend context for actions that need backend sync
if let Some(ref mut audio_system) = self.audio_system {
let mut backend_context = lightningbeam_core::action::BackendContext {
audio_controller: Some(&mut audio_system.controller),
layer_to_track_map: &self.layer_to_track_map,
};
// Execute action with backend synchronization
if let Err(e) = self.action_executor.execute_with_backend(action, &mut backend_context) {
eprintln!("Action execution failed: {}", e);
}
} else {
// No audio system available, execute without backend
self.action_executor.execute(action);
}
}
// Set cursor based on hover state
@@ -1253,6 +1319,8 @@ struct RenderContext<'a> {
polygon_sides: &'a mut u32,
/// Mapping from Document layer UUIDs to daw-backend TrackIds
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)>>,
}
/// Recursively render a layout node with drag support
@@ -1723,6 +1791,7 @@ fn render_pane(
fill_enabled: ctx.fill_enabled,
paint_bucket_gap_tolerance: ctx.paint_bucket_gap_tolerance,
polygon_sides: ctx.polygon_sides,
midi_event_cache: ctx.midi_event_cache,
};
pane_instance.render_header(&mut header_ui, &mut shared);
}
@@ -1776,6 +1845,7 @@ fn render_pane(
fill_enabled: ctx.fill_enabled,
paint_bucket_gap_tolerance: ctx.paint_bucket_gap_tolerance,
polygon_sides: ctx.polygon_sides,
midi_event_cache: ctx.midi_event_cache,
};
// Render pane content (header was already rendered above)
@@ -1172,23 +1172,15 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Midi { events, .. } => {
let note_color = egui::Color32::from_rgb(100, 150, 255);
// Convert MIDI events to (timestamp, note, is_note_on) tuples
// Note on: 0x90-0x9F, Note off: 0x80-0x8F
let midi_events: Vec<(f64, u8, bool)> = events.iter()
.filter_map(|e| {
let msg_type = e.status & 0xF0;
let is_note_on = msg_type == 0x90 && e.data2 > 0;
let is_note_off = msg_type == 0x80 || (msg_type == 0x90 && e.data2 == 0);
if is_note_on || is_note_off {
Some((e.timestamp, e.data1, is_note_on))
} else {
None
}
})
.collect();
Some(generate_midi_thumbnail(&midi_events, clip.duration, bg_color, note_color))
AudioClipType::Midi { midi_clip_id } => {
let bg_color = egui::Color32::from_rgba_unmultiplied(40, 40, 40, 200);
let note_color = egui::Color32::from_rgb(100, 200, 100);
if let Some(events) = shared.midi_event_cache.get(midi_clip_id) {
Some(generate_midi_thumbnail(events, clip.duration, bg_color, note_color))
} else {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
}
} else {
@@ -1449,21 +1441,15 @@ impl AssetLibraryPane {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
AudioClipType::Midi { events, .. } => {
let note_color = egui::Color32::from_rgb(100, 150, 255);
let midi_events: Vec<(f64, u8, bool)> = events.iter()
.filter_map(|e| {
let msg_type = e.status & 0xF0;
let is_note_on = msg_type == 0x90 && e.data2 > 0;
let is_note_off = msg_type == 0x80 || (msg_type == 0x90 && e.data2 == 0);
if is_note_on || is_note_off {
Some((e.timestamp, e.data1, is_note_on))
} else {
None
}
})
.collect();
Some(generate_midi_thumbnail(&midi_events, clip.duration, bg_color, note_color))
AudioClipType::Midi { midi_clip_id } => {
let bg_color = egui::Color32::from_rgba_unmultiplied(40, 40, 40, 200);
let note_color = egui::Color32::from_rgb(100, 200, 100);
if let Some(events) = shared.midi_event_cache.get(midi_clip_id) {
Some(generate_midi_thumbnail(events, clip.duration, bg_color, note_color))
} else {
Some(generate_placeholder_thumbnail(AssetCategory::Audio, 200))
}
}
}
} else {
@@ -125,6 +125,8 @@ pub struct SharedPaneState<'a> {
pub paint_bucket_gap_tolerance: &'a mut f64,
/// Number of sides for polygon tool
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)>>,
}
/// Trait for pane rendering
@@ -347,6 +347,115 @@ impl TimelinePane {
}
}
/// Render mini piano roll visualization for MIDI clips on timeline
/// Shows notes modulo 12 (one octave) matching the JavaScript reference implementation
#[allow(clippy::too_many_arguments)]
fn render_midi_piano_roll(
painter: &egui::Painter,
clip_rect: egui::Rect,
rect_min_x: f32, // Timeline panel left edge (for proper viewport-relative positioning)
events: &[(f64, u8, bool)], // (timestamp, note_number, is_note_on)
trim_start: f64,
visible_duration: f64,
timeline_start: f64,
viewport_start_time: f64,
pixels_per_second: f32,
theme: &crate::theme::Theme,
ctx: &egui::Context,
) {
let clip_height = clip_rect.height();
let note_height = clip_height / 12.0; // 12 semitones per octave
// Get note color from theme CSS (fallback to black)
let note_style = theme.style(".timeline-midi-note", ctx);
let note_color = note_style.background_color.unwrap_or(egui::Color32::BLACK);
// Build a map of active notes (note_number -> note_on_timestamp)
// to calculate durations when we encounter note-offs
let mut active_notes: std::collections::HashMap<u8, f64> = std::collections::HashMap::new();
let mut note_rectangles: Vec<(egui::Rect, u8)> = Vec::new();
// First pass: pair note-ons with note-offs to calculate durations
for &(timestamp, note_number, is_note_on) in events {
if is_note_on {
// Store note-on timestamp
active_notes.insert(note_number, timestamp);
} else {
// Note-off: find matching note-on and calculate duration
if let Some(&note_on_time) = active_notes.get(&note_number) {
let duration = timestamp - note_on_time;
// Skip notes outside visible trim range
if note_on_time < trim_start || note_on_time > trim_start + visible_duration {
active_notes.remove(&note_number);
continue;
}
// Calculate X position and width
// Convert note position to absolute timeline position
let note_timeline_pos = timeline_start + (note_on_time - trim_start);
// Convert to screen X using same formula as clip positioning (time_to_x)
let note_x = rect_min_x + ((note_timeline_pos - viewport_start_time) * pixels_per_second as f64) as f32;
// Calculate note width from duration (minimum 2px for visibility)
let note_width = (duration as f32 * pixels_per_second).max(2.0);
// Calculate Y position (modulo 12 for octave wrapping)
let pitch_class = note_number % 12;
let note_y = clip_rect.min.y + ((11 - pitch_class) as f32 * note_height);
let note_rect = egui::Rect::from_min_size(
egui::pos2(note_x, note_y),
egui::vec2(note_width, note_height - 1.0), // -1 for spacing between notes
);
// Store for rendering (only if visible)
if note_rect.right() >= clip_rect.left() && note_rect.left() <= clip_rect.right() {
note_rectangles.push((note_rect, note_number));
}
active_notes.remove(&note_number);
}
}
}
// Handle any notes that didn't get a note-off (still active at end of clip)
for (&note_number, &note_on_time) in &active_notes {
// Skip notes outside visible trim range
if note_on_time < trim_start || note_on_time > trim_start + visible_duration {
continue;
}
// Use a default duration (extend to end of visible area or 0.5 seconds, whichever is shorter)
let max_end_time = (trim_start + visible_duration).min(note_on_time + 0.5);
let duration = max_end_time - note_on_time;
// Convert note position to absolute timeline position
let note_timeline_pos = timeline_start + (note_on_time - trim_start);
// Convert to screen X using same formula as clip positioning (time_to_x)
let note_x = rect_min_x + ((note_timeline_pos - viewport_start_time) * pixels_per_second as f64) as f32;
let note_width = (duration as f32 * pixels_per_second).max(2.0);
let pitch_class = note_number % 12;
let note_y = clip_rect.min.y + ((11 - pitch_class) as f32 * note_height);
let note_rect = egui::Rect::from_min_size(
egui::pos2(note_x, note_y),
egui::vec2(note_width, note_height - 1.0),
);
if note_rect.right() >= clip_rect.left() && note_rect.left() <= clip_rect.right() {
note_rectangles.push((note_rect, note_number));
}
}
// Second pass: render all note rectangles
for (note_rect, _note_number) in note_rectangles {
painter.rect_filled(note_rect, 1.0, note_color);
}
}
/// Render layer header column (left side with track names and controls)
fn render_layer_headers(
&mut self,
@@ -625,6 +734,7 @@ impl TimelinePane {
document: &lightningbeam_core::document::Document,
active_layer_id: &Option<uuid::Uuid>,
selection: &lightningbeam_core::selection::Selection,
midi_event_cache: &std::collections::HashMap<u32, Vec<(f64, u8, bool)>>,
) {
let painter = ui.painter();
@@ -790,6 +900,29 @@ impl TimelinePane {
clip_color,
);
// MIDI VISUALIZATION: Draw piano roll overlay for MIDI clips
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(),
);
}
}
}
}
// Draw border only if selected (brighter version of clip color)
if selection.contains_clip_instance(&clip_instance.id) {
painter.rect_stroke(
@@ -1534,7 +1667,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);
self.render_layers(ui, content_rect, shared.theme, document, shared.active_layer_id, shared.selection, shared.midi_event_cache);
// Render playhead on top (clip to timeline area)
ui.set_clip_rect(timeline_rect.intersect(original_clip_rect));