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
@@ -19,3 +19,6 @@ image = { workspace = true }
# Unique identifiers
uuid = { version = "1.0", features = ["v4", "serde"] }
# Audio backend
daw-backend = { path = "../../daw-backend" }
@@ -18,12 +18,34 @@
//! callbacks), the document is cloned before mutation, preserving their snapshot.
use crate::document::Document;
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;
/// Backend context for actions that need to interact with external systems
///
/// This bundles all backend references (audio, future video) that actions
/// may need to synchronize state with external systems beyond the document.
pub struct BackendContext<'a> {
/// Audio engine controller (optional - may not be initialized)
pub audio_controller: Option<&'a mut daw_backend::EngineController>,
/// Mapping from document layer UUIDs to backend track IDs
pub layer_to_track_map: &'a HashMap<Uuid, daw_backend::TrackId>,
// Future: pub video_controller: Option<&'a mut VideoController>,
}
/// Action trait for undo/redo operations
///
/// Each action must be able to execute (apply changes) and rollback (undo changes).
/// Actions are stored in the undo stack and can be re-executed from the redo stack.
///
/// ## Backend Integration
///
/// Actions can optionally implement backend synchronization via `execute_backend()`
/// and `rollback_backend()`. Default implementations do nothing, so actions that
/// only affect the document (vector graphics) don't need to implement these.
pub trait Action: Send {
/// Apply this action to the document
fn execute(&mut self, document: &mut Document);
@@ -33,6 +55,33 @@ pub trait Action: Send {
/// Get a human-readable description of this action (for UI display)
fn description(&self) -> String;
/// Execute backend operations after document changes
///
/// Called AFTER execute() succeeds. If this returns an error, execute()
/// will be automatically rolled back to maintain atomicity.
///
/// # Arguments
/// * `backend` - Backend context with audio/video controllers
/// * `document` - Read-only document access for looking up clip data
///
/// Default: No backend operations
fn execute_backend(&mut self, _backend: &mut BackendContext, _document: &Document) -> Result<(), String> {
Ok(())
}
/// Rollback backend operations during undo
///
/// Called BEFORE rollback() to undo backend changes in reverse order.
///
/// # Arguments
/// * `backend` - Backend context with audio/video controllers
/// * `document` - Read-only document access (if needed)
///
/// Default: No backend operations
fn rollback_backend(&mut self, _backend: &mut BackendContext, _document: &Document) -> Result<(), String> {
Ok(())
}
}
/// Action executor that wraps the document and manages undo/redo
@@ -195,6 +244,104 @@ impl ActionExecutor {
self.undo_stack.drain(0..remove_count);
}
}
/// Execute an action with backend synchronization
///
/// This performs atomic execution: if backend operations fail, the document
/// changes are automatically rolled back to maintain consistency.
///
/// # Arguments
/// * `action` - The action to execute
/// * `backend` - Backend context for audio/video operations
///
/// # Returns
/// * `Ok(())` if both document and backend operations succeeded
/// * `Err(msg)` if backend failed (document changes are rolled back)
pub fn execute_with_backend(
&mut self,
mut action: Box<dyn Action>,
backend: &mut BackendContext,
) -> Result<(), String> {
// 1. Execute document changes
action.execute(Arc::make_mut(&mut self.document));
// 2. Execute backend changes (pass document for reading clip data)
if let Err(e) = action.execute_backend(backend, &self.document) {
// ATOMIC ROLLBACK: Backend failed → undo document
action.rollback(Arc::make_mut(&mut self.document));
return Err(e);
}
// 3. Push to undo stack (both succeeded)
self.redo_stack.clear();
self.undo_stack.push(action);
// Limit undo stack size
if self.undo_stack.len() > self.max_undo_depth {
self.undo_stack.remove(0);
}
Ok(())
}
/// Undo the last action with backend synchronization
///
/// Rollback happens in reverse order: backend first, then document.
///
/// # Arguments
/// * `backend` - Backend context for audio/video operations
///
/// # Returns
/// * `Ok(true)` if an action was undone
/// * `Ok(false)` if undo stack is empty
/// * `Err(msg)` if backend rollback failed
pub fn undo_with_backend(&mut self, backend: &mut BackendContext) -> Result<bool, String> {
if let Some(mut action) = self.undo_stack.pop() {
// Rollback in REVERSE order: backend first, then document
action.rollback_backend(backend, &self.document)?;
action.rollback(Arc::make_mut(&mut self.document));
// Move to redo stack
self.redo_stack.push(action);
Ok(true)
} else {
Ok(false)
}
}
/// Redo the last undone action with backend synchronization
///
/// Re-execution happens in normal order: document first, then backend.
///
/// # Arguments
/// * `backend` - Backend context for audio/video operations
///
/// # Returns
/// * `Ok(true)` if an action was redone
/// * `Ok(false)` if redo stack is empty
/// * `Err(msg)` if backend execution failed
pub fn redo_with_backend(&mut self, backend: &mut BackendContext) -> Result<bool, String> {
if let Some(mut action) = self.redo_stack.pop() {
// Re-execute in same order: document first, then backend
action.execute(Arc::make_mut(&mut self.document));
if let Err(e) = action.execute_backend(backend, &self.document) {
// Rollback document if backend fails
action.rollback(Arc::make_mut(&mut self.document));
// Put action back on redo stack
self.redo_stack.push(action);
return Err(e);
}
// Move back to undo stack
self.undo_stack.push(action);
Ok(true)
} else {
Ok(false)
}
}
}
#[cfg(test)]
@@ -2,7 +2,7 @@
//!
//! Handles adding a clip instance to a layer.
use crate::action::Action;
use crate::action::{Action, BackendContext};
use crate::clip::ClipInstance;
use crate::document::Document;
use crate::layer::AnyLayer;
@@ -18,6 +18,15 @@ pub struct AddClipInstanceAction {
/// Whether the action has been executed (for rollback)
executed: bool,
/// Backend track ID (stored during execute_backend for undo)
backend_track_id: Option<daw_backend::TrackId>,
/// Backend MIDI clip instance ID (stored during execute_backend for undo)
backend_midi_instance_id: Option<daw_backend::MidiClipInstanceId>,
/// Backend audio clip instance ID (stored during execute_backend for undo)
backend_audio_instance_id: Option<daw_backend::AudioClipInstanceId>,
}
impl AddClipInstanceAction {
@@ -32,6 +41,9 @@ impl AddClipInstanceAction {
layer_id,
clip_instance,
executed: false,
backend_track_id: None,
backend_midi_instance_id: None,
backend_audio_instance_id: None,
}
}
@@ -96,6 +108,109 @@ impl Action for AddClipInstanceAction {
fn description(&self) -> String {
"Add clip instance".to_string()
}
fn execute_backend(&mut self, backend: &mut BackendContext, document: &Document) -> Result<(), String> {
// Only sync audio clips to the backend
// Look up the clip from the document
let clip = document
.get_audio_clip(&self.clip_instance.clip_id)
.ok_or_else(|| "Audio clip not found".to_string())?;
// Look up backend track ID from layer mapping
let backend_track_id = backend
.layer_to_track_map
.get(&self.layer_id)
.ok_or_else(|| format!("Layer {} not mapped to backend track", self.layer_id))?;
// Get audio controller
let controller = backend
.audio_controller
.as_mut()
.ok_or_else(|| "Audio controller not available".to_string())?;
// Handle different clip types
use crate::clip::AudioClipType;
match &clip.clip_type {
AudioClipType::Midi { midi_clip_id } => {
// Create a MIDI clip instance referencing the existing clip in the backend pool
// No need to add to pool again - it was added during MIDI import
use daw_backend::command::{Query, QueryResponse};
// Calculate internal start/end from trim parameters
let internal_start = self.clip_instance.trim_start;
let internal_end = self.clip_instance.trim_end.unwrap_or(clip.duration);
let external_start = self.clip_instance.timeline_start;
// Calculate external duration (for looping if timeline_duration is set)
let external_duration = self.clip_instance.timeline_duration
.unwrap_or(internal_end - internal_start);
// Create MidiClipInstance
let instance = daw_backend::MidiClipInstance::new(
0, // Instance ID will be assigned by backend
*midi_clip_id,
internal_start,
internal_end,
external_start,
external_duration,
);
// Send query to add instance and get instance ID
let query = Query::AddMidiClipInstanceSync(*backend_track_id, instance);
match controller.send_query(query)? {
QueryResponse::MidiClipInstanceAdded(Ok(instance_id)) => {
self.backend_track_id = Some(*backend_track_id);
self.backend_midi_instance_id = Some(instance_id);
Ok(())
}
QueryResponse::MidiClipInstanceAdded(Err(e)) => Err(e),
_ => Err("Unexpected query response".to_string()),
}
}
AudioClipType::Sampled { audio_pool_index } => {
// For sampled audio, send AddAudioClipSync query
use daw_backend::command::{Query, QueryResponse};
let duration = clip.duration;
let start_time = self.clip_instance.timeline_start;
let offset = self.clip_instance.trim_start;
let query =
Query::AddAudioClipSync(*backend_track_id, *audio_pool_index, start_time, duration, offset);
match controller.send_query(query)? {
QueryResponse::AudioClipInstanceAdded(Ok(instance_id)) => {
self.backend_track_id = Some(*backend_track_id);
self.backend_audio_instance_id = Some(instance_id);
Ok(())
}
QueryResponse::AudioClipInstanceAdded(Err(e)) => Err(e),
_ => Err("Unexpected query response".to_string()),
}
}
}
}
fn rollback_backend(&mut self, backend: &mut BackendContext, _document: &Document) -> Result<(), String> {
// Remove clip from backend if it was added
if let (Some(track_id), Some(controller)) =
(self.backend_track_id, backend.audio_controller.as_mut())
{
if let Some(midi_instance_id) = self.backend_midi_instance_id {
controller.remove_midi_clip(track_id, midi_instance_id);
} else if let Some(audio_instance_id) = self.backend_audio_instance_id {
controller.remove_audio_clip(track_id, audio_instance_id);
}
// Clear stored IDs
self.backend_track_id = None;
self.backend_midi_instance_id = None;
self.backend_audio_instance_id = None;
}
Ok(())
}
}
#[cfg(test)]
+15 -14
View File
@@ -332,12 +332,12 @@ pub enum AudioClipType {
},
/// MIDI sequence
///
/// Compatible with daw-backend's MidiClip structure.
/// References MIDI data in the backend's MidiClipPool.
/// The clip content is stored in daw-backend, not duplicated here.
Midi {
/// MIDI events with timestamps
events: Vec<MidiEvent>,
/// Whether the clip loops
loop_enabled: bool,
/// Backend MIDI clip ID (references MidiClip in backend pool)
/// This allows sharing MIDI data between multiple clip instances
midi_clip_id: u32,
},
}
@@ -379,20 +379,21 @@ impl AudioClip {
}
/// Create a new MIDI clip
///
/// # Arguments
/// * `name` - Clip name
/// * `midi_clip_id` - Backend MIDI clip ID (from daw-backend MidiClipPool)
/// * `duration` - Clip duration
pub fn new_midi(
name: impl Into<String>,
midi_clip_id: u32,
duration: f64,
events: Vec<MidiEvent>,
loop_enabled: bool,
) -> Self {
Self {
id: Uuid::new_v4(),
name: name.into(),
duration,
clip_type: AudioClipType::Midi {
events,
loop_enabled,
},
clip_type: AudioClipType::Midi { midi_clip_id },
}
}
@@ -404,10 +405,10 @@ impl AudioClip {
}
}
/// Get MIDI events if this is a MIDI clip
pub fn midi_events(&self) -> Option<&[MidiEvent]> {
/// Get backend MIDI clip ID if this is a MIDI clip
pub fn midi_clip_id(&self) -> Option<u32> {
match &self.clip_type {
AudioClipType::Midi { events, .. } => Some(events),
AudioClipType::Midi { midi_clip_id } => Some(*midi_clip_id),
_ => None,
}
}