File save/load for audio projects
This commit is contained in:
Generated
+7
@@ -416,6 +416,7 @@ dependencies = [
|
||||
"dasp_sample",
|
||||
"dasp_signal",
|
||||
"midly",
|
||||
"pathdiff",
|
||||
"petgraph 0.6.5",
|
||||
"rand",
|
||||
"ratatui",
|
||||
@@ -847,6 +848,12 @@ version = "1.0.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
|
||||
|
||||
[[package]]
|
||||
name = "pathdiff"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
|
||||
|
||||
[[package]]
|
||||
name = "petgraph"
|
||||
version = "0.5.1"
|
||||
|
||||
@@ -13,6 +13,7 @@ ratatui = "0.26"
|
||||
crossterm = "0.27"
|
||||
rand = "0.8"
|
||||
base64 = "0.22"
|
||||
pathdiff = "0.2"
|
||||
|
||||
# Node-based audio graph dependencies
|
||||
dasp_graph = "0.11"
|
||||
|
||||
@@ -338,10 +338,18 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
Command::MoveClip(track_id, clip_id, new_start_time) => {
|
||||
if let Some(crate::audio::track::TrackNode::Audio(track)) = self.project.get_track_mut(track_id) {
|
||||
if let Some(clip) = track.clips.iter_mut().find(|c| c.id == clip_id) {
|
||||
clip.start_time = new_start_time;
|
||||
match self.project.get_track_mut(track_id) {
|
||||
Some(crate::audio::track::TrackNode::Audio(track)) => {
|
||||
if let Some(clip) = track.clips.iter_mut().find(|c| c.id == clip_id) {
|
||||
clip.start_time = new_start_time;
|
||||
}
|
||||
}
|
||||
Some(crate::audio::track::TrackNode::Midi(track)) => {
|
||||
if let Some(clip) = track.clips.iter_mut().find(|c| c.id == clip_id) {
|
||||
clip.start_time = new_start_time;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Command::CreateMetatrack(name) => {
|
||||
@@ -390,6 +398,19 @@ impl Engine {
|
||||
let _ = self.event_tx.push(AudioEvent::AudioFileAdded(pool_index, path));
|
||||
}
|
||||
Command::AddAudioClip(track_id, pool_index, start_time, duration, offset) => {
|
||||
eprintln!("[Engine] AddAudioClip: track_id={}, pool_index={}, start_time={}, duration={}",
|
||||
track_id, pool_index, start_time, duration);
|
||||
|
||||
// Check if pool index is valid
|
||||
let pool_size = self.audio_pool.len();
|
||||
if pool_index >= pool_size {
|
||||
eprintln!("[Engine] ERROR: pool_index {} is out of bounds (pool size: {})",
|
||||
pool_index, pool_size);
|
||||
} else {
|
||||
eprintln!("[Engine] Pool index {} is valid, pool has {} files",
|
||||
pool_index, pool_size);
|
||||
}
|
||||
|
||||
// Create a new clip with unique ID
|
||||
let clip_id = self.next_clip_id;
|
||||
self.next_clip_id += 1;
|
||||
@@ -404,8 +425,11 @@ impl Engine {
|
||||
// Add clip to track
|
||||
if let Some(crate::audio::track::TrackNode::Audio(track)) = self.project.get_track_mut(track_id) {
|
||||
track.clips.push(clip);
|
||||
eprintln!("[Engine] Clip {} added to track {} successfully", clip_id, track_id);
|
||||
// Notify UI about the new clip
|
||||
let _ = self.event_tx.push(AudioEvent::ClipAdded(track_id, clip_id));
|
||||
} else {
|
||||
eprintln!("[Engine] ERROR: Track {} not found or is not an audio track", track_id);
|
||||
}
|
||||
}
|
||||
Command::CreateMidiTrack(name) => {
|
||||
@@ -1405,6 +1429,106 @@ impl Engine {
|
||||
QueryResponse::AutomationName(Err(format!("Track {} not found or is not a MIDI track", track_id)))
|
||||
}
|
||||
}
|
||||
|
||||
Query::SerializeAudioPool(project_path) => {
|
||||
QueryResponse::AudioPoolSerialized(self.audio_pool.serialize(&project_path))
|
||||
}
|
||||
|
||||
Query::LoadAudioPool(entries, project_path) => {
|
||||
QueryResponse::AudioPoolLoaded(self.audio_pool.load_from_serialized(entries, &project_path))
|
||||
}
|
||||
|
||||
Query::ResolveMissingAudioFile(pool_index, new_path) => {
|
||||
QueryResponse::AudioFileResolved(self.audio_pool.resolve_missing_file(pool_index, &new_path))
|
||||
}
|
||||
|
||||
Query::SerializeTrackGraph(track_id, _project_path) => {
|
||||
// Get the track and serialize its graph
|
||||
if let Some(track_node) = self.project.get_track(track_id) {
|
||||
let preset_json = match track_node {
|
||||
TrackNode::Audio(track) => {
|
||||
// Serialize effects graph
|
||||
let preset = track.effects_graph.to_preset(format!("track_{}_effects", track_id));
|
||||
serde_json::to_string_pretty(&preset)
|
||||
.map_err(|e| format!("Failed to serialize effects graph: {}", e))
|
||||
}
|
||||
TrackNode::Midi(track) => {
|
||||
// Serialize instrument graph
|
||||
let preset = track.instrument_graph.to_preset(format!("track_{}_instrument", track_id));
|
||||
serde_json::to_string_pretty(&preset)
|
||||
.map_err(|e| format!("Failed to serialize instrument graph: {}", e))
|
||||
}
|
||||
TrackNode::Group(_) => {
|
||||
// TODO: Add graph serialization when we add graphs to group tracks
|
||||
Err("Group tracks don't have graphs to serialize yet".to_string())
|
||||
}
|
||||
};
|
||||
QueryResponse::TrackGraphSerialized(preset_json)
|
||||
} else {
|
||||
QueryResponse::TrackGraphSerialized(Err(format!("Track {} not found", track_id)))
|
||||
}
|
||||
}
|
||||
|
||||
Query::LoadTrackGraph(track_id, preset_json, project_path) => {
|
||||
// Parse preset and load into track's graph
|
||||
use crate::audio::node_graph::preset::GraphPreset;
|
||||
|
||||
let result = (|| -> Result<(), String> {
|
||||
let preset: GraphPreset = serde_json::from_str(&preset_json)
|
||||
.map_err(|e| format!("Failed to parse preset JSON: {}", e))?;
|
||||
|
||||
let preset_base_path = project_path.parent();
|
||||
|
||||
if let Some(track_node) = self.project.get_track_mut(track_id) {
|
||||
match track_node {
|
||||
TrackNode::Audio(track) => {
|
||||
// Load into effects graph with proper buffer size (8192 to handle any callback size)
|
||||
track.effects_graph = AudioGraph::from_preset(&preset, self.sample_rate, 8192, preset_base_path)?;
|
||||
Ok(())
|
||||
}
|
||||
TrackNode::Midi(track) => {
|
||||
// Load into instrument graph with proper buffer size (8192 to handle any callback size)
|
||||
track.instrument_graph = AudioGraph::from_preset(&preset, self.sample_rate, 8192, preset_base_path)?;
|
||||
Ok(())
|
||||
}
|
||||
TrackNode::Group(_) => {
|
||||
// TODO: Add graph loading when we add graphs to group tracks
|
||||
Err("Group tracks don't have graphs to load yet".to_string())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Err(format!("Track {} not found", track_id))
|
||||
}
|
||||
})();
|
||||
|
||||
QueryResponse::TrackGraphLoaded(result)
|
||||
}
|
||||
Query::CreateAudioTrackSync(name) => {
|
||||
let track_id = self.project.add_audio_track(name.clone(), None);
|
||||
eprintln!("[Engine] Created audio track '{}' with ID {}", name, track_id);
|
||||
// Notify UI about the new audio track
|
||||
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, false, name));
|
||||
QueryResponse::TrackCreated(Ok(track_id))
|
||||
}
|
||||
Query::CreateMidiTrackSync(name) => {
|
||||
let track_id = self.project.add_midi_track(name.clone(), None);
|
||||
eprintln!("[Engine] Created MIDI track '{}' with ID {}", name, track_id);
|
||||
// Notify UI about the new MIDI track
|
||||
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, false, name));
|
||||
QueryResponse::TrackCreated(Ok(track_id))
|
||||
}
|
||||
Query::GetPoolWaveform(pool_index, target_peaks) => {
|
||||
match self.audio_pool.generate_waveform(pool_index, target_peaks) {
|
||||
Some(waveform) => QueryResponse::PoolWaveform(Ok(waveform)),
|
||||
None => QueryResponse::PoolWaveform(Err(format!("Pool index {} not found", pool_index))),
|
||||
}
|
||||
}
|
||||
Query::GetPoolFileInfo(pool_index) => {
|
||||
match self.audio_pool.get_file_info(pool_index) {
|
||||
Some(info) => QueryResponse::PoolFileInfo(Ok(info)),
|
||||
None => QueryResponse::PoolFileInfo(Err(format!("Pool index {} not found", pool_index))),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Send response back
|
||||
@@ -1792,6 +1916,46 @@ impl EngineController {
|
||||
let _ = self.command_tx.push(Command::CreateMidiTrack(name));
|
||||
}
|
||||
|
||||
/// Create a new audio track synchronously (waits for creation to complete)
|
||||
pub fn create_audio_track_sync(&mut self, name: String) -> Result<TrackId, String> {
|
||||
if let Err(_) = self.query_tx.push(Query::CreateAudioTrackSync(name)) {
|
||||
return Err("Failed to send track creation query".to_string());
|
||||
}
|
||||
|
||||
// Wait for response (with timeout)
|
||||
let start = std::time::Instant::now();
|
||||
let timeout = std::time::Duration::from_secs(2);
|
||||
|
||||
while start.elapsed() < timeout {
|
||||
if let Ok(QueryResponse::TrackCreated(result)) = self.query_response_rx.pop() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
|
||||
Err("Track creation timeout".to_string())
|
||||
}
|
||||
|
||||
/// Create a new MIDI track synchronously (waits for creation to complete)
|
||||
pub fn create_midi_track_sync(&mut self, name: String) -> Result<TrackId, String> {
|
||||
if let Err(_) = self.query_tx.push(Query::CreateMidiTrackSync(name)) {
|
||||
return Err("Failed to send track creation query".to_string());
|
||||
}
|
||||
|
||||
// Wait for response (with timeout)
|
||||
let start = std::time::Instant::now();
|
||||
let timeout = std::time::Duration::from_secs(2);
|
||||
|
||||
while start.elapsed() < timeout {
|
||||
if let Ok(QueryResponse::TrackCreated(result)) = self.query_response_rx.pop() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
|
||||
Err("Track creation timeout".to_string())
|
||||
}
|
||||
|
||||
/// Create a new MIDI clip on a track
|
||||
pub fn create_midi_clip(&mut self, track_id: TrackId, start_time: f64, duration: f64) -> MidiClipId {
|
||||
// Peek at the next clip ID that will be used
|
||||
@@ -2141,4 +2305,151 @@ impl EngineController {
|
||||
|
||||
Err("Query timeout".to_string())
|
||||
}
|
||||
|
||||
/// Serialize the audio pool for project saving
|
||||
pub fn serialize_audio_pool(&mut self, project_path: &std::path::Path) -> Result<Vec<crate::audio::pool::AudioPoolEntry>, String> {
|
||||
// Send query
|
||||
if let Err(_) = self.query_tx.push(Query::SerializeAudioPool(project_path.to_path_buf())) {
|
||||
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); // Longer timeout for file operations
|
||||
|
||||
while start.elapsed() < timeout {
|
||||
if let Ok(QueryResponse::AudioPoolSerialized(result)) = self.query_response_rx.pop() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
|
||||
Err("Query timeout".to_string())
|
||||
}
|
||||
|
||||
/// Get waveform for a pool index
|
||||
pub fn get_pool_waveform(&mut self, pool_index: usize, target_peaks: usize) -> Result<Vec<crate::io::WaveformPeak>, String> {
|
||||
// Send query
|
||||
if let Err(_) = self.query_tx.push(Query::GetPoolWaveform(pool_index, target_peaks)) {
|
||||
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(2);
|
||||
|
||||
while start.elapsed() < timeout {
|
||||
if let Ok(QueryResponse::PoolWaveform(result)) = self.query_response_rx.pop() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
|
||||
Err("Query timeout".to_string())
|
||||
}
|
||||
|
||||
/// Get file info from pool (duration, sample_rate, channels)
|
||||
pub fn get_pool_file_info(&mut self, pool_index: usize) -> Result<(f64, u32, u32), String> {
|
||||
// Send query
|
||||
if let Err(_) = self.query_tx.push(Query::GetPoolFileInfo(pool_index)) {
|
||||
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(2);
|
||||
|
||||
while start.elapsed() < timeout {
|
||||
if let Ok(QueryResponse::PoolFileInfo(result)) = self.query_response_rx.pop() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
|
||||
Err("Query timeout".to_string())
|
||||
}
|
||||
|
||||
/// Load audio pool from serialized entries
|
||||
pub fn load_audio_pool(&mut self, entries: Vec<crate::audio::pool::AudioPoolEntry>, project_path: &std::path::Path) -> Result<Vec<usize>, String> {
|
||||
// Send command via query mechanism
|
||||
if let Err(_) = self.query_tx.push(Query::LoadAudioPool(entries, project_path.to_path_buf())) {
|
||||
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); // Long timeout for loading multiple files
|
||||
|
||||
while start.elapsed() < timeout {
|
||||
if let Ok(QueryResponse::AudioPoolLoaded(result)) = self.query_response_rx.pop() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
|
||||
Err("Query timeout".to_string())
|
||||
}
|
||||
|
||||
/// Resolve a missing audio file by loading from a new path
|
||||
pub fn resolve_missing_audio_file(&mut self, pool_index: usize, new_path: &std::path::Path) -> Result<(), String> {
|
||||
// Send command via query mechanism
|
||||
if let Err(_) = self.query_tx.push(Query::ResolveMissingAudioFile(pool_index, new_path.to_path_buf())) {
|
||||
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::AudioFileResolved(result)) = self.query_response_rx.pop() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
|
||||
Err("Query timeout".to_string())
|
||||
}
|
||||
|
||||
/// Serialize a track's effects/instrument graph to JSON
|
||||
pub fn serialize_track_graph(&mut self, track_id: TrackId, project_path: &std::path::Path) -> Result<String, String> {
|
||||
// Send query
|
||||
if let Err(_) = self.query_tx.push(Query::SerializeTrackGraph(track_id, project_path.to_path_buf())) {
|
||||
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::TrackGraphSerialized(result)) = self.query_response_rx.pop() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
|
||||
Err("Query timeout".to_string())
|
||||
}
|
||||
|
||||
/// Load a track's effects/instrument graph from JSON
|
||||
pub fn load_track_graph(&mut self, track_id: TrackId, preset_json: &str, project_path: &std::path::Path) -> Result<(), String> {
|
||||
// Send query
|
||||
if let Err(_) = self.query_tx.push(Query::LoadTrackGraph(track_id, preset_json.to_string(), project_path.to_path_buf())) {
|
||||
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 presets
|
||||
|
||||
while start.elapsed() < timeout {
|
||||
if let Ok(QueryResponse::TrackGraphLoaded(result)) = self.query_response_rx.pop() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
|
||||
Err("Query timeout".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -494,12 +494,14 @@ impl AudioGraph {
|
||||
node.node.process(&input_slices, &mut output_slices, &midi_input_slices, &mut midi_output_refs, self.sample_rate);
|
||||
}
|
||||
|
||||
// Copy output node's first output to the provided buffer
|
||||
// Mix output node's first output into the provided buffer
|
||||
if let Some(output_idx) = self.output_node {
|
||||
if let Some(output_node) = self.graph.node_weight(output_idx) {
|
||||
if !output_node.output_buffers.is_empty() {
|
||||
let len = output_buffer.len().min(output_node.output_buffers[0].len());
|
||||
output_buffer[..len].copy_from_slice(&output_node.output_buffers[0][..len]);
|
||||
for i in 0..len {
|
||||
output_buffer[i] += output_node.output_buffers[0][i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -837,6 +839,7 @@ impl AudioGraph {
|
||||
"MidiInput" => Box::new(MidiInputNode::new("MIDI Input")),
|
||||
"MidiToCV" => Box::new(MidiToCVNode::new("MIDI→CV")),
|
||||
"AudioToCV" => Box::new(AudioToCVNode::new("Audio→CV")),
|
||||
"AudioInput" => Box::new(AudioInputNode::new("Audio Input")),
|
||||
"AutomationInput" => Box::new(AutomationInputNode::new("Automation")),
|
||||
"Oscilloscope" => Box::new(OscilloscopeNode::new("Oscilloscope")),
|
||||
"TemplateInput" => Box::new(TemplateInputNode::new("Template Input")),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::f32::consts::PI;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Windowed sinc interpolation for high-quality time stretching
|
||||
/// This is stateless and can handle arbitrary fractional positions
|
||||
@@ -77,6 +78,45 @@ impl AudioFile {
|
||||
pub fn duration_seconds(&self) -> f64 {
|
||||
self.frames as f64 / self.sample_rate as f64
|
||||
}
|
||||
|
||||
/// Generate a waveform overview with the specified number of peaks
|
||||
/// This creates a downsampled representation suitable for timeline visualization
|
||||
pub fn generate_waveform_overview(&self, target_peaks: usize) -> Vec<crate::io::WaveformPeak> {
|
||||
if self.frames == 0 || target_peaks == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let total_frames = self.frames as usize;
|
||||
let frames_per_peak = (total_frames / target_peaks).max(1);
|
||||
let actual_peaks = (total_frames + frames_per_peak - 1) / frames_per_peak;
|
||||
|
||||
let mut peaks = Vec::with_capacity(actual_peaks);
|
||||
|
||||
for peak_idx in 0..actual_peaks {
|
||||
let start_frame = peak_idx * frames_per_peak;
|
||||
let end_frame = ((peak_idx + 1) * frames_per_peak).min(total_frames);
|
||||
|
||||
let mut min = 0.0f32;
|
||||
let mut max = 0.0f32;
|
||||
|
||||
// Scan all samples in this window
|
||||
for frame_idx in start_frame..end_frame {
|
||||
// For multi-channel audio, combine all channels
|
||||
for ch in 0..self.channels as usize {
|
||||
let sample_idx = frame_idx * self.channels as usize + ch;
|
||||
if sample_idx < self.data.len() {
|
||||
let sample = self.data[sample_idx];
|
||||
min = min.min(sample);
|
||||
max = max.max(sample);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
peaks.push(crate::io::WaveformPeak { min, max });
|
||||
}
|
||||
|
||||
peaks
|
||||
}
|
||||
}
|
||||
|
||||
/// Pool of shared audio files
|
||||
@@ -92,6 +132,30 @@ impl AudioPool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the number of files in the pool
|
||||
pub fn len(&self) -> usize {
|
||||
self.files.len()
|
||||
}
|
||||
|
||||
/// Check if the pool is empty
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.files.is_empty()
|
||||
}
|
||||
|
||||
/// Get file info for waveform generation (duration, sample_rate, channels)
|
||||
pub fn get_file_info(&self, pool_index: usize) -> Option<(f64, u32, u32)> {
|
||||
self.files.get(pool_index).map(|file| {
|
||||
(file.duration_seconds(), file.sample_rate, file.channels)
|
||||
})
|
||||
}
|
||||
|
||||
/// Generate waveform overview for a file in the pool
|
||||
pub fn generate_waveform(&self, pool_index: usize, target_peaks: usize) -> Option<Vec<crate::io::WaveformPeak>> {
|
||||
self.files.get(pool_index).map(|file| {
|
||||
file.generate_waveform_overview(target_peaks)
|
||||
})
|
||||
}
|
||||
|
||||
/// Add an audio file to the pool and return its index
|
||||
pub fn add_file(&mut self, file: AudioFile) -> usize {
|
||||
let index = self.files.len();
|
||||
@@ -242,3 +306,345 @@ impl Default for AudioPool {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Embedded audio data stored as base64 in the project file
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct EmbeddedAudioData {
|
||||
/// Base64-encoded audio data
|
||||
pub data_base64: String,
|
||||
/// Original file format (wav, mp3, etc.)
|
||||
pub format: String,
|
||||
}
|
||||
|
||||
/// Serializable audio pool entry for project save/load
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AudioPoolEntry {
|
||||
/// Index in the audio pool
|
||||
pub pool_index: usize,
|
||||
/// Original filename
|
||||
pub name: String,
|
||||
/// Path relative to project file (None if embedded)
|
||||
pub relative_path: Option<String>,
|
||||
/// Duration in seconds
|
||||
pub duration: f64,
|
||||
/// Sample rate
|
||||
pub sample_rate: u32,
|
||||
/// Number of channels
|
||||
pub channels: u32,
|
||||
/// Embedded audio data (for files < 10MB)
|
||||
pub embedded_data: Option<EmbeddedAudioData>,
|
||||
}
|
||||
|
||||
impl AudioPool {
|
||||
/// Serialize the audio pool for project saving
|
||||
///
|
||||
/// Files smaller than 10MB are embedded as base64.
|
||||
/// Larger files are stored as relative paths to the project file.
|
||||
pub fn serialize(&self, project_path: &Path) -> Result<Vec<AudioPoolEntry>, String> {
|
||||
let project_dir = project_path.parent()
|
||||
.ok_or_else(|| "Project path has no parent directory".to_string())?;
|
||||
|
||||
let mut entries = Vec::new();
|
||||
|
||||
for (index, file) in self.files.iter().enumerate() {
|
||||
let file_path = &file.path;
|
||||
let file_path_str = file_path.to_string_lossy();
|
||||
|
||||
// Check if this is a temp file (from recording) or previously embedded audio
|
||||
// Always embed these
|
||||
let is_temp_file = file_path.starts_with(std::env::temp_dir());
|
||||
let is_embedded = file_path_str.starts_with("<embedded:");
|
||||
|
||||
// Try to get relative path (unless it's a temp/embedded file)
|
||||
let relative_path = if is_temp_file || is_embedded {
|
||||
None // Don't store path for temp/embedded files, they'll be embedded
|
||||
} else if let Some(rel) = pathdiff::diff_paths(file_path, project_dir) {
|
||||
Some(rel.to_string_lossy().to_string())
|
||||
} else {
|
||||
// Fall back to absolute path if relative path fails
|
||||
Some(file_path.to_string_lossy().to_string())
|
||||
};
|
||||
|
||||
// Check if we should embed this file
|
||||
// Always embed temp files (recordings) and previously embedded audio,
|
||||
// otherwise use size threshold
|
||||
let embedded_data = if is_temp_file || is_embedded || Self::should_embed(file_path) {
|
||||
// Embed from memory - we already have the audio data loaded
|
||||
Some(Self::embed_from_memory(file))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let entry = AudioPoolEntry {
|
||||
pool_index: index,
|
||||
name: file_path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| format!("file_{}", index)),
|
||||
relative_path,
|
||||
duration: file.duration_seconds(),
|
||||
sample_rate: file.sample_rate,
|
||||
channels: file.channels,
|
||||
embedded_data,
|
||||
};
|
||||
|
||||
entries.push(entry);
|
||||
}
|
||||
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// Check if a file should be embedded (< 10MB)
|
||||
fn should_embed(file_path: &Path) -> bool {
|
||||
const TEN_MB: u64 = 10_000_000;
|
||||
|
||||
std::fs::metadata(file_path)
|
||||
.map(|m| m.len() < TEN_MB)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Embed audio from memory (already loaded in the pool)
|
||||
fn embed_from_memory(audio_file: &AudioFile) -> EmbeddedAudioData {
|
||||
use base64::{Engine as _, engine::general_purpose};
|
||||
|
||||
// Convert the f32 interleaved samples to WAV format bytes
|
||||
let wav_data = Self::encode_wav(
|
||||
&audio_file.data,
|
||||
audio_file.channels,
|
||||
audio_file.sample_rate
|
||||
);
|
||||
|
||||
let data_base64 = general_purpose::STANDARD.encode(&wav_data);
|
||||
|
||||
EmbeddedAudioData {
|
||||
data_base64,
|
||||
format: "wav".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode f32 interleaved samples as WAV file bytes
|
||||
fn encode_wav(samples: &[f32], channels: u32, sample_rate: u32) -> Vec<u8> {
|
||||
let num_samples = samples.len();
|
||||
let bytes_per_sample = 4; // 32-bit float
|
||||
let data_size = num_samples * bytes_per_sample;
|
||||
let file_size = 36 + data_size;
|
||||
|
||||
let mut wav_data = Vec::with_capacity(44 + data_size);
|
||||
|
||||
// RIFF header
|
||||
wav_data.extend_from_slice(b"RIFF");
|
||||
wav_data.extend_from_slice(&(file_size as u32).to_le_bytes());
|
||||
wav_data.extend_from_slice(b"WAVE");
|
||||
|
||||
// fmt chunk
|
||||
wav_data.extend_from_slice(b"fmt ");
|
||||
wav_data.extend_from_slice(&16u32.to_le_bytes()); // chunk size
|
||||
wav_data.extend_from_slice(&3u16.to_le_bytes()); // format code (3 = IEEE float)
|
||||
wav_data.extend_from_slice(&(channels as u16).to_le_bytes());
|
||||
wav_data.extend_from_slice(&sample_rate.to_le_bytes());
|
||||
wav_data.extend_from_slice(&(sample_rate * channels * bytes_per_sample as u32).to_le_bytes()); // byte rate
|
||||
wav_data.extend_from_slice(&((channels * bytes_per_sample as u32) as u16).to_le_bytes()); // block align
|
||||
wav_data.extend_from_slice(&32u16.to_le_bytes()); // bits per sample
|
||||
|
||||
// data chunk
|
||||
wav_data.extend_from_slice(b"data");
|
||||
wav_data.extend_from_slice(&(data_size as u32).to_le_bytes());
|
||||
|
||||
// Write samples as little-endian f32
|
||||
for &sample in samples {
|
||||
wav_data.extend_from_slice(&sample.to_le_bytes());
|
||||
}
|
||||
|
||||
wav_data
|
||||
}
|
||||
|
||||
/// Load audio pool from serialized entries
|
||||
///
|
||||
/// Returns a list of pool indices that failed to load (missing files).
|
||||
/// The caller should present these to the user for resolution.
|
||||
pub fn load_from_serialized(
|
||||
&mut self,
|
||||
entries: Vec<AudioPoolEntry>,
|
||||
project_path: &Path,
|
||||
) -> Result<Vec<usize>, String> {
|
||||
let project_dir = project_path.parent()
|
||||
.ok_or_else(|| "Project path has no parent directory".to_string())?;
|
||||
|
||||
let mut missing_indices = Vec::new();
|
||||
|
||||
// Clear existing pool
|
||||
self.files.clear();
|
||||
|
||||
// Find the maximum pool index to determine required size
|
||||
let max_index = entries.iter()
|
||||
.map(|e| e.pool_index)
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
// Ensure we have space for all entries
|
||||
self.files.resize(max_index + 1, AudioFile::new(PathBuf::new(), Vec::new(), 2, 44100));
|
||||
|
||||
for entry in entries {
|
||||
let success = if let Some(embedded) = entry.embedded_data {
|
||||
// Load from embedded data
|
||||
match Self::load_from_embedded_into_pool(self, entry.pool_index, embedded, &entry.name) {
|
||||
Ok(_) => {
|
||||
eprintln!("[AudioPool] Successfully loaded embedded audio: {}", entry.name);
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[AudioPool] Failed to load embedded audio {}: {}", entry.name, e);
|
||||
false
|
||||
}
|
||||
}
|
||||
} else if let Some(rel_path) = entry.relative_path {
|
||||
// Load from file path
|
||||
let full_path = project_dir.join(&rel_path);
|
||||
|
||||
if full_path.exists() {
|
||||
Self::load_file_into_pool(self, entry.pool_index, &full_path).is_ok()
|
||||
} else {
|
||||
eprintln!("[AudioPool] File not found: {:?}", full_path);
|
||||
false
|
||||
}
|
||||
} else {
|
||||
eprintln!("[AudioPool] Entry has neither embedded data nor path: {}", entry.name);
|
||||
false
|
||||
};
|
||||
|
||||
if !success {
|
||||
missing_indices.push(entry.pool_index);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(missing_indices)
|
||||
}
|
||||
|
||||
/// Load audio from embedded base64 data
|
||||
fn load_from_embedded_into_pool(
|
||||
&mut self,
|
||||
pool_index: usize,
|
||||
embedded: EmbeddedAudioData,
|
||||
name: &str,
|
||||
) -> Result<(), String> {
|
||||
use base64::{Engine as _, engine::general_purpose};
|
||||
|
||||
// Decode base64
|
||||
let data = general_purpose::STANDARD
|
||||
.decode(&embedded.data_base64)
|
||||
.map_err(|e| format!("Failed to decode base64: {}", e))?;
|
||||
|
||||
// Write to temporary file for symphonia to decode
|
||||
let temp_dir = std::env::temp_dir();
|
||||
let temp_path = temp_dir.join(format!("lightningbeam_embedded_{}.{}", pool_index, embedded.format));
|
||||
|
||||
std::fs::write(&temp_path, &data)
|
||||
.map_err(|e| format!("Failed to write temporary file: {}", e))?;
|
||||
|
||||
// Load the temporary file using existing infrastructure
|
||||
let result = Self::load_file_into_pool(self, pool_index, &temp_path);
|
||||
|
||||
// Clean up temporary file
|
||||
let _ = std::fs::remove_file(&temp_path);
|
||||
|
||||
// Update the path to reflect it was embedded
|
||||
if result.is_ok() && pool_index < self.files.len() {
|
||||
self.files[pool_index].path = PathBuf::from(format!("<embedded: {}>", name));
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Load an audio file into a specific pool index
|
||||
fn load_file_into_pool(&mut self, pool_index: usize, file_path: &Path) -> Result<(), String> {
|
||||
use symphonia::core::audio::SampleBuffer;
|
||||
use symphonia::core::codecs::{DecoderOptions, CODEC_TYPE_NULL};
|
||||
use symphonia::core::formats::FormatOptions;
|
||||
use symphonia::core::io::MediaSourceStream;
|
||||
use symphonia::core::meta::MetadataOptions;
|
||||
use symphonia::core::probe::Hint;
|
||||
|
||||
let file = std::fs::File::open(file_path)
|
||||
.map_err(|e| format!("Failed to open audio file: {}", e))?;
|
||||
|
||||
let mss = MediaSourceStream::new(Box::new(file), Default::default());
|
||||
|
||||
let mut hint = Hint::new();
|
||||
if let Some(ext) = file_path.extension() {
|
||||
hint.with_extension(&ext.to_string_lossy());
|
||||
}
|
||||
|
||||
let format_opts = FormatOptions::default();
|
||||
let metadata_opts = MetadataOptions::default();
|
||||
let decoder_opts = DecoderOptions::default();
|
||||
|
||||
let probed = symphonia::default::get_probe()
|
||||
.format(&hint, mss, &format_opts, &metadata_opts)
|
||||
.map_err(|e| format!("Failed to probe audio file: {}", e))?;
|
||||
|
||||
let mut format = probed.format;
|
||||
let track = format
|
||||
.tracks()
|
||||
.iter()
|
||||
.find(|t| t.codec_params.codec != CODEC_TYPE_NULL)
|
||||
.ok_or_else(|| "No audio track found".to_string())?;
|
||||
|
||||
let mut decoder = symphonia::default::get_codecs()
|
||||
.make(&track.codec_params, &decoder_opts)
|
||||
.map_err(|e| format!("Failed to create decoder: {}", e))?;
|
||||
|
||||
let track_id = track.id;
|
||||
let sample_rate = track.codec_params.sample_rate.unwrap_or(44100);
|
||||
let channels = track.codec_params.channels.map(|c| c.count()).unwrap_or(2) as u32;
|
||||
|
||||
let mut samples = Vec::new();
|
||||
let mut sample_buf = None;
|
||||
|
||||
loop {
|
||||
let packet = match format.next_packet() {
|
||||
Ok(packet) => packet,
|
||||
Err(_) => break,
|
||||
};
|
||||
|
||||
if packet.track_id() != track_id {
|
||||
continue;
|
||||
}
|
||||
|
||||
match decoder.decode(&packet) {
|
||||
Ok(decoded) => {
|
||||
if sample_buf.is_none() {
|
||||
let spec = *decoded.spec();
|
||||
let duration = decoded.capacity() as u64;
|
||||
sample_buf = Some(SampleBuffer::<f32>::new(duration, spec));
|
||||
}
|
||||
|
||||
if let Some(ref mut buf) = sample_buf {
|
||||
buf.copy_interleaved_ref(decoded);
|
||||
samples.extend_from_slice(buf.samples());
|
||||
}
|
||||
}
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
|
||||
let audio_file = AudioFile::new(
|
||||
file_path.to_path_buf(),
|
||||
samples,
|
||||
channels,
|
||||
sample_rate,
|
||||
);
|
||||
|
||||
if pool_index >= self.files.len() {
|
||||
return Err(format!("Pool index {} out of bounds", pool_index));
|
||||
}
|
||||
|
||||
self.files[pool_index] = audio_file;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve a missing audio file by loading from a new path
|
||||
/// This is called from the UI when the user manually locates a missing file
|
||||
pub fn resolve_missing_file(&mut self, pool_index: usize, new_path: &Path) -> Result<(), String> {
|
||||
Self::load_file_into_pool(self, pool_index, new_path)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -617,9 +617,6 @@ impl AudioTrack {
|
||||
}
|
||||
}
|
||||
|
||||
// Clear output buffer before graph processing to ensure clean output
|
||||
output.fill(0.0);
|
||||
|
||||
// Find and inject audio into the AudioInputNode
|
||||
let node_indices: Vec<_> = self.effects_graph.node_indices().collect();
|
||||
for node_idx in node_indices {
|
||||
|
||||
@@ -224,6 +224,24 @@ pub enum Query {
|
||||
GetAutomationKeyframes(TrackId, u32),
|
||||
/// Get the display name of an AutomationInput node (track_id, node_id)
|
||||
GetAutomationName(TrackId, u32),
|
||||
/// Serialize audio pool for project saving (project_path)
|
||||
SerializeAudioPool(std::path::PathBuf),
|
||||
/// Load audio pool from serialized entries (entries, project_path)
|
||||
LoadAudioPool(Vec<crate::audio::pool::AudioPoolEntry>, std::path::PathBuf),
|
||||
/// Resolve a missing audio file (pool_index, new_path)
|
||||
ResolveMissingAudioFile(usize, std::path::PathBuf),
|
||||
/// Serialize a track's effects/instrument graph (track_id, project_path)
|
||||
SerializeTrackGraph(TrackId, std::path::PathBuf),
|
||||
/// Load a track's effects/instrument graph (track_id, preset_json, project_path)
|
||||
LoadTrackGraph(TrackId, String, std::path::PathBuf),
|
||||
/// Create a new audio track (name) - returns track ID synchronously
|
||||
CreateAudioTrackSync(String),
|
||||
/// Create a new MIDI track (name) - returns track ID synchronously
|
||||
CreateMidiTrackSync(String),
|
||||
/// Get waveform data from audio pool (pool_index, target_peaks)
|
||||
GetPoolWaveform(usize, usize),
|
||||
/// Get file info from audio pool (pool_index) - returns (duration, sample_rate, channels)
|
||||
GetPoolFileInfo(usize),
|
||||
}
|
||||
|
||||
/// Oscilloscope data from a node
|
||||
@@ -265,4 +283,20 @@ pub enum QueryResponse {
|
||||
AutomationKeyframes(Result<Vec<AutomationKeyframeData>, String>),
|
||||
/// Automation node name
|
||||
AutomationName(Result<String, String>),
|
||||
/// Serialized audio pool entries
|
||||
AudioPoolSerialized(Result<Vec<crate::audio::pool::AudioPoolEntry>, String>),
|
||||
/// Audio pool loaded (returns list of missing pool indices)
|
||||
AudioPoolLoaded(Result<Vec<usize>, String>),
|
||||
/// Audio file resolved
|
||||
AudioFileResolved(Result<(), String>),
|
||||
/// Track graph serialized as JSON
|
||||
TrackGraphSerialized(Result<String, String>),
|
||||
/// Track graph loaded
|
||||
TrackGraphLoaded(Result<(), String>),
|
||||
/// Track created (returns track ID)
|
||||
TrackCreated(Result<TrackId, String>),
|
||||
/// Pool waveform data
|
||||
PoolWaveform(Result<Vec<crate::io::WaveformPeak>, String>),
|
||||
/// Pool file info (duration, sample_rate, channels)
|
||||
PoolFileInfo(Result<(f64, u32, u32), String>),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user