File save/load

This commit is contained in:
Skyler Lehmkuhl
2025-12-01 09:18:49 -05:00
parent 5379e3bc8c
commit ba9a4ee812
19 changed files with 1339 additions and 73 deletions
+3 -1
View File
@@ -1,3 +1,5 @@
use serde::{Serialize, Deserialize};
/// Audio clip instance ID type
pub type AudioClipInstanceId = u32;
@@ -16,7 +18,7 @@ pub type ClipId = AudioClipInstanceId;
/// ## Looping
/// If `external_duration` is greater than `internal_end - internal_start`,
/// the clip will seamlessly loop back to `internal_start` when it reaches `internal_end`.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioClipInstance {
pub id: AudioClipInstanceId,
pub audio_pool_index: usize,
+70 -3
View File
@@ -483,12 +483,19 @@ impl Engine {
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, false, name));
}
Command::AddAudioFile(path, data, channels, sample_rate) => {
// Detect original format from file extension
let path_buf = std::path::PathBuf::from(path.clone());
let original_format = path_buf.extension()
.and_then(|ext| ext.to_str())
.map(|s| s.to_lowercase());
// Create AudioFile and add to pool
let audio_file = crate::audio::pool::AudioFile::new(
std::path::PathBuf::from(path.clone()),
let audio_file = crate::audio::pool::AudioFile::with_format(
path_buf,
data,
channels,
sample_rate,
original_format,
);
let pool_index = self.audio_pool.add_file(audio_file);
// Notify UI about the new audio file
@@ -1730,6 +1737,22 @@ impl Engine {
Err(e) => QueryResponse::AudioClipInstanceAdded(Err(e.to_string())),
}
}
Query::GetProject => {
// Clone the entire project for serialization
QueryResponse::ProjectRetrieved(Ok(Box::new(self.project.clone())))
}
Query::SetProject(new_project) => {
// Replace the current project with the new one
// Need to rebuild audio graphs with current sample_rate and buffer_size
let mut project = *new_project;
match project.rebuild_audio_graphs(self.buffer_pool.buffer_size()) {
Ok(()) => {
self.project = project;
QueryResponse::ProjectSet(Ok(()))
}
Err(e) => QueryResponse::ProjectSet(Err(format!("Failed to rebuild audio graphs: {}", e))),
}
}
};
// Send response back
@@ -1850,11 +1873,13 @@ impl Engine {
frames_recorded, temp_file_path, waveform.len(), audio_data.len());
// Add to pool using the in-memory audio data (no file loading needed!)
let pool_file = crate::audio::pool::AudioFile::new(
// Recorded audio is always WAV format
let pool_file = crate::audio::pool::AudioFile::with_format(
temp_file_path.clone(),
audio_data,
channels,
sample_rate,
Some("wav".to_string()),
);
let pool_index = self.audio_pool.add_file(pool_file);
eprintln!("[STOP_RECORDING] Added to pool at index {}", pool_index);
@@ -2741,4 +2766,46 @@ impl EngineController {
Err("Export timeout".to_string())
}
/// Get a clone of the current project for serialization
pub fn get_project(&mut self) -> Result<crate::audio::project::Project, String> {
// Send query
if let Err(_) = self.query_tx.push(Query::GetProject) {
return Err("Failed to send query - queue full".to_string());
}
// Wait for response (with timeout)
let start = std::time::Instant::now();
let timeout = std::time::Duration::from_secs(5);
while start.elapsed() < timeout {
if let Ok(QueryResponse::ProjectRetrieved(result)) = self.query_response_rx.pop() {
return result.map(|boxed| *boxed);
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
Err("Query timeout".to_string())
}
/// Set the project (replaces current project state)
pub fn set_project(&mut self, project: crate::audio::project::Project) -> Result<(), String> {
// Send query
if let Err(_) = self.query_tx.push(Query::SetProject(Box::new(project))) {
return Err("Failed to send query - queue full".to_string());
}
// Wait for response (with timeout)
let start = std::time::Instant::now();
let timeout = std::time::Duration::from_secs(10); // Longer timeout for loading project
while start.elapsed() < timeout {
if let Ok(QueryResponse::ProjectSet(result)) = self.query_response_rx.pop() {
return result;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
Err("Query timeout".to_string())
}
}
+2 -2
View File
@@ -73,7 +73,7 @@ pub type MidiClipInstanceId = u32;
///
/// This represents the content data stored in the MidiClipPool.
/// Events have timestamps relative to the start of the clip (0.0 = clip beginning).
#[derive(Debug, Clone)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MidiClip {
pub id: MidiClipId,
pub events: Vec<MidiEvent>,
@@ -132,7 +132,7 @@ impl MidiClip {
/// ## Looping
/// If `external_duration` is greater than `internal_end - internal_start`,
/// the instance will seamlessly loop back to `internal_start` when it reaches `internal_end`.
#[derive(Debug, Clone)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MidiClipInstance {
pub id: MidiClipInstanceId,
pub clip_id: MidiClipId, // Reference to MidiClip in pool
+2
View File
@@ -1,8 +1,10 @@
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use super::midi::{MidiClip, MidiClipId, MidiEvent};
/// Pool for storing MIDI clip content
/// Similar to AudioClipPool but for MIDI data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MidiClipPool {
clips: HashMap<MidiClipId, MidiClip>,
next_id: MidiClipId,
+11
View File
@@ -22,6 +22,16 @@ pub struct GraphNode {
pub midi_output_buffers: Vec<Vec<MidiEvent>>,
}
impl std::fmt::Debug for GraphNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GraphNode")
.field("node", &"<AudioNode>")
.field("output_buffers_len", &self.output_buffers.len())
.field("midi_output_buffers_len", &self.midi_output_buffers.len())
.finish()
}
}
impl GraphNode {
pub fn new(node: Box<dyn AudioNode>, buffer_size: usize) -> Self {
let outputs = node.outputs();
@@ -57,6 +67,7 @@ impl GraphNode {
}
/// Audio processing graph for instruments/effects
#[derive(Debug)]
pub struct AudioGraph {
/// The audio graph (StableGraph allows node removal without index invalidation)
graph: StableGraph<GraphNode, Connection>,
+45 -2
View File
@@ -59,6 +59,9 @@ pub struct AudioFile {
pub channels: u32,
pub sample_rate: u32,
pub frames: u64,
/// Original file format (mp3, ogg, wav, flac, etc.)
/// Used to determine if we should preserve lossy encoding during save
pub original_format: Option<String>,
}
impl AudioFile {
@@ -71,6 +74,20 @@ impl AudioFile {
channels,
sample_rate,
frames,
original_format: None,
}
}
/// Create a new AudioFile with original format information
pub fn with_format(path: PathBuf, data: Vec<f32>, channels: u32, sample_rate: u32, original_format: Option<String>) -> Self {
let frames = (data.len() / channels as usize) as u64;
Self {
path,
data,
channels,
sample_rate,
frames,
original_format,
}
}
@@ -452,7 +469,27 @@ impl AudioClipPool {
fn embed_from_memory(audio_file: &AudioFile) -> EmbeddedAudioData {
use base64::{Engine as _, engine::general_purpose};
// Convert the f32 interleaved samples to WAV format bytes
// Check if this is a lossy format that should be preserved
let is_lossy = audio_file.original_format.as_ref().map_or(false, |fmt| {
let fmt_lower = fmt.to_lowercase();
fmt_lower == "mp3" || fmt_lower == "ogg" || fmt_lower == "aac"
|| fmt_lower == "m4a" || fmt_lower == "opus"
});
if is_lossy {
// For lossy formats, read the original file bytes (if it still exists)
if let Ok(original_bytes) = std::fs::read(&audio_file.path) {
let data_base64 = general_purpose::STANDARD.encode(&original_bytes);
return EmbeddedAudioData {
data_base64,
format: audio_file.original_format.clone().unwrap_or_else(|| "mp3".to_string()),
};
}
// If we can't read the original file, fall through to WAV conversion
}
// For lossless/PCM or if we couldn't read the original lossy file,
// convert the f32 interleaved samples to WAV format bytes
let wav_data = Self::encode_wav(
&audio_file.data,
audio_file.channels,
@@ -672,11 +709,17 @@ impl AudioClipPool {
}
}
let audio_file = AudioFile::new(
// Detect original format from file extension
let original_format = file_path.extension()
.and_then(|ext| ext.to_str())
.map(|s| s.to_lowercase());
let audio_file = AudioFile::with_format(
file_path.to_path_buf(),
samples,
channels,
sample_rate,
original_format,
);
if pool_index >= self.files.len() {
+43
View File
@@ -4,6 +4,7 @@ use super::midi::{MidiClip, MidiClipId, MidiClipInstance, MidiClipInstanceId, Mi
use super::midi_pool::MidiClipPool;
use super::pool::AudioClipPool;
use super::track::{AudioTrack, Metatrack, MidiTrack, RenderContext, TrackId, TrackNode};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
/// Project manages the hierarchical track structure and clip pools
@@ -13,6 +14,7 @@ use std::collections::HashMap;
///
/// Clip content is stored in pools (MidiClipPool), while tracks store
/// clip instances that reference the pool content.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Project {
tracks: HashMap<TrackId, TrackNode>,
next_track_id: TrackId,
@@ -515,6 +517,47 @@ impl Project {
track.queue_live_midi(event);
}
}
/// Prepare all tracks for serialization by saving their audio graphs as presets
pub fn prepare_for_save(&mut self) {
for track in self.tracks.values_mut() {
match track {
TrackNode::Audio(audio_track) => {
audio_track.prepare_for_save();
}
TrackNode::Midi(midi_track) => {
midi_track.prepare_for_save();
}
TrackNode::Group(_) => {
// Groups don't have audio graphs
}
}
}
}
/// Rebuild all audio graphs from presets after deserialization
///
/// This should be called after deserializing a Project to reconstruct
/// the AudioGraph instances from their stored presets.
///
/// # Arguments
/// * `buffer_size` - Buffer size for audio processing (typically 8192)
pub fn rebuild_audio_graphs(&mut self, buffer_size: usize) -> Result<(), String> {
for track in self.tracks.values_mut() {
match track {
TrackNode::Audio(audio_track) => {
audio_track.rebuild_audio_graph(self.sample_rate, buffer_size)?;
}
TrackNode::Midi(midi_track) => {
midi_track.rebuild_audio_graph(self.sample_rate, buffer_size)?;
}
TrackNode::Group(_) => {
// Groups don't have audio graphs
}
}
}
Ok(())
}
}
impl Default for Project {
+96 -1
View File
@@ -4,12 +4,19 @@ use super::midi::{MidiClipInstance, MidiClipInstanceId, MidiEvent};
use super::midi_pool::MidiClipPool;
use super::node_graph::AudioGraph;
use super::node_graph::nodes::{AudioInputNode, AudioOutputNode};
use super::node_graph::preset::GraphPreset;
use super::pool::AudioClipPool;
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
/// Track ID type
pub type TrackId = u32;
/// Default function for creating empty AudioGraph during deserialization
fn default_audio_graph() -> AudioGraph {
AudioGraph::new(48000, 8192)
}
/// Type alias for backwards compatibility
pub type Track = AudioTrack;
@@ -59,6 +66,7 @@ impl RenderContext {
}
/// Node in the track hierarchy - can be an audio track, MIDI track, or a metatrack
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TrackNode {
Audio(AudioTrack),
Midi(MidiTrack),
@@ -145,6 +153,7 @@ impl TrackNode {
}
/// Metatrack that contains other tracks with time transformation capabilities
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Metatrack {
pub id: TrackId,
pub name: String,
@@ -301,12 +310,21 @@ impl Metatrack {
}
/// MIDI track with MIDI clip instances and a node-based instrument
#[derive(Debug, Serialize, Deserialize)]
pub struct MidiTrack {
pub id: TrackId,
pub name: String,
/// Clip instances placed on this track (reference clips in the MidiClipPool)
pub clip_instances: Vec<MidiClipInstance>,
/// Serialized instrument graph (used for save/load)
#[serde(default, skip_serializing_if = "Option::is_none")]
instrument_graph_preset: Option<GraphPreset>,
/// Runtime instrument graph (rebuilt from preset on load)
#[serde(skip, default = "default_audio_graph")]
pub instrument_graph: AudioGraph,
pub volume: f32,
pub muted: bool,
pub solo: bool,
@@ -314,9 +332,28 @@ pub struct MidiTrack {
pub automation_lanes: HashMap<AutomationLaneId, AutomationLane>,
next_automation_id: AutomationLaneId,
/// Queue for live MIDI input (virtual keyboard, MIDI controllers)
#[serde(skip)]
live_midi_queue: Vec<MidiEvent>,
}
impl Clone for MidiTrack {
fn clone(&self) -> Self {
Self {
id: self.id,
name: self.name.clone(),
clip_instances: self.clip_instances.clone(),
instrument_graph_preset: self.instrument_graph_preset.clone(),
instrument_graph: default_audio_graph(), // Create fresh graph, not cloned
volume: self.volume,
muted: self.muted,
solo: self.solo,
automation_lanes: self.automation_lanes.clone(),
next_automation_id: self.next_automation_id,
live_midi_queue: Vec::new(), // Don't clone live MIDI queue
}
}
}
impl MidiTrack {
/// Create a new MIDI track with default settings
pub fn new(id: TrackId, name: String, sample_rate: u32) -> Self {
@@ -327,6 +364,7 @@ impl MidiTrack {
id,
name,
clip_instances: Vec::new(),
instrument_graph_preset: None,
instrument_graph: AudioGraph::new(sample_rate, default_buffer_size),
volume: 1.0,
muted: false,
@@ -337,6 +375,22 @@ impl MidiTrack {
}
}
/// Prepare for serialization by saving the instrument graph as a preset
pub fn prepare_for_save(&mut self) {
self.instrument_graph_preset = Some(self.instrument_graph.to_preset("Instrument Graph"));
}
/// Rebuild the instrument graph from preset after deserialization
pub fn rebuild_audio_graph(&mut self, sample_rate: u32, buffer_size: usize) -> Result<(), String> {
if let Some(preset) = &self.instrument_graph_preset {
self.instrument_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None)?;
} else {
// No preset - create default graph
self.instrument_graph = AudioGraph::new(sample_rate, buffer_size);
}
Ok(())
}
/// Add an automation lane to this track
pub fn add_automation_lane(&mut self, parameter_id: ParameterId) -> AutomationLaneId {
let lane_id = self.next_automation_id;
@@ -504,6 +558,7 @@ impl MidiTrack {
}
/// Audio track with audio clip instances
#[derive(Debug, Serialize, Deserialize)]
pub struct AudioTrack {
pub id: TrackId,
pub name: String,
@@ -515,10 +570,33 @@ pub struct AudioTrack {
/// Automation lanes for this track
pub automation_lanes: HashMap<AutomationLaneId, AutomationLane>,
next_automation_id: AutomationLaneId,
/// Effects processing graph for this audio track
/// Serialized effects graph (used for save/load)
#[serde(default, skip_serializing_if = "Option::is_none")]
effects_graph_preset: Option<GraphPreset>,
/// Runtime effects processing graph (rebuilt from preset on load)
#[serde(skip, default = "default_audio_graph")]
pub effects_graph: AudioGraph,
}
impl Clone for AudioTrack {
fn clone(&self) -> Self {
Self {
id: self.id,
name: self.name.clone(),
clips: self.clips.clone(),
volume: self.volume,
muted: self.muted,
solo: self.solo,
automation_lanes: self.automation_lanes.clone(),
next_automation_id: self.next_automation_id,
effects_graph_preset: self.effects_graph_preset.clone(),
effects_graph: default_audio_graph(), // Create fresh graph, not cloned
}
}
}
impl AudioTrack {
/// Create a new audio track with default settings
pub fn new(id: TrackId, name: String, sample_rate: u32) -> Self {
@@ -555,10 +633,27 @@ impl AudioTrack {
solo: false,
automation_lanes: HashMap::new(),
next_automation_id: 0,
effects_graph_preset: None,
effects_graph,
}
}
/// Prepare for serialization by saving the effects graph as a preset
pub fn prepare_for_save(&mut self) {
self.effects_graph_preset = Some(self.effects_graph.to_preset("Effects Graph"));
}
/// Rebuild the effects graph from preset after deserialization
pub fn rebuild_audio_graph(&mut self, sample_rate: u32, buffer_size: usize) -> Result<(), String> {
if let Some(preset) = &self.effects_graph_preset {
self.effects_graph = AudioGraph::from_preset(preset, sample_rate, buffer_size, None)?;
} else {
// No preset - create default graph
self.effects_graph = AudioGraph::new(sample_rate, buffer_size);
}
Ok(())
}
/// Add an automation lane to this track
pub fn add_automation_lane(&mut self, parameter_id: ParameterId) -> AutomationLaneId {
let lane_id = self.next_automation_id;
+8
View File
@@ -272,6 +272,10 @@ pub enum Query {
AddMidiClipInstanceSync(TrackId, crate::audio::midi::MidiClipInstance),
/// Add an audio clip to a track synchronously (track_id, pool_index, start_time, duration, offset) - returns instance ID
AddAudioClipSync(TrackId, usize, f64, f64, f64),
/// Get a clone of the current project for serialization
GetProject,
/// Set the project (replaces current project state)
SetProject(Box<crate::audio::project::Project>),
}
/// Oscilloscope data from a node
@@ -335,4 +339,8 @@ pub enum QueryResponse {
MidiClipInstanceAdded(Result<MidiClipInstanceId, String>),
/// Audio clip instance added (returns instance ID)
AudioClipInstanceAdded(Result<AudioClipInstanceId, String>),
/// Project retrieved
ProjectRetrieved(Result<Box<crate::audio::project::Project>, String>),
/// Project set
ProjectSet(Result<(), String>),
}