initial audio export

This commit is contained in:
Skyler Lehmkuhl
2025-12-03 17:54:15 -05:00
parent 2a7c26df57
commit 727d782190
21 changed files with 2657 additions and 78 deletions
Binary file not shown.
+279 -18
View File
@@ -30,6 +30,10 @@ pub struct Engine {
query_rx: rtrb::Consumer<Query>,
query_response_tx: rtrb::Producer<QueryResponse>,
// Background chunk generation channel
chunk_generation_rx: std::sync::mpsc::Receiver<AudioEvent>,
chunk_generation_tx: std::sync::mpsc::Sender<AudioEvent>,
// Shared playhead for UI reads
playhead_atomic: Arc<AtomicU64>,
@@ -76,6 +80,9 @@ impl Engine {
// Calculate a reasonable buffer size for the pool (typical audio callback size * channels)
let buffer_size = 512 * channels as usize;
// Create channel for background chunk generation
let (chunk_generation_tx, chunk_generation_rx) = std::sync::mpsc::channel();
Self {
project: Project::new(sample_rate),
audio_pool: AudioClipPool::new(),
@@ -89,6 +96,8 @@ impl Engine {
event_tx,
query_rx,
query_response_tx,
chunk_generation_rx,
chunk_generation_tx,
playhead_atomic: Arc::new(AtomicU64::new(0)),
next_midi_clip_id_atomic: Arc::new(AtomicU32::new(0)),
frames_since_last_event: 0,
@@ -188,6 +197,7 @@ impl Engine {
next_midi_clip_id: Arc::clone(&self.next_midi_clip_id_atomic),
sample_rate: self.sample_rate,
channels: self.channels,
cached_export_response: None,
}
}
@@ -224,6 +234,14 @@ impl Engine {
self.handle_query(query);
}
// Forward chunk generation events from background threads
while let Ok(event) = self.chunk_generation_rx.try_recv() {
if let AudioEvent::WaveformChunksReady { pool_index, detail_level, ref chunks } = event {
println!("📬 [AUDIO THREAD] Received {} chunks for pool {} level {}, forwarding to UI", chunks.len(), pool_index, detail_level);
}
let _ = self.event_tx.push(event);
}
if self.playing {
// Ensure mix buffer is sized correctly
if self.mix_buffer.len() != output.len() {
@@ -483,6 +501,7 @@ impl Engine {
let _ = self.event_tx.push(AudioEvent::TrackCreated(track_id, false, name));
}
Command::AddAudioFile(path, data, channels, sample_rate) => {
println!("🎵 [ENGINE] Received AddAudioFile command for: {}", path);
// Detect original format from file extension
let path_buf = std::path::PathBuf::from(path.clone());
let original_format = path_buf.extension()
@@ -491,13 +510,60 @@ impl Engine {
// Create AudioFile and add to pool
let audio_file = crate::audio::pool::AudioFile::with_format(
path_buf,
data,
path_buf.clone(),
data.clone(), // Clone data for background thread
channels,
sample_rate,
original_format,
);
let pool_index = self.audio_pool.add_file(audio_file);
println!("📦 [ENGINE] Added to pool at index {}", pool_index);
// Generate Level 0 (overview) waveform chunks asynchronously in background thread
let chunk_tx = self.chunk_generation_tx.clone();
let duration = data.len() as f64 / (sample_rate as f64 * channels as f64);
println!("🔄 [ENGINE] Spawning background thread to generate Level 0 chunks for pool {}", pool_index);
std::thread::spawn(move || {
// Create temporary AudioFile for chunk generation
let temp_audio_file = crate::audio::pool::AudioFile::with_format(
path_buf,
data,
channels,
sample_rate,
None,
);
// Generate Level 0 chunks
let chunk_count = crate::audio::waveform_cache::WaveformCache::calculate_chunk_count(duration, 0);
println!("🔄 [BACKGROUND] Generating {} Level 0 chunks for pool {}", chunk_count, pool_index);
let chunks = crate::audio::waveform_cache::WaveformCache::generate_chunks(
&temp_audio_file,
pool_index,
0, // Level 0 (overview)
&(0..chunk_count).collect::<Vec<_>>(),
);
// Send chunks via MPSC channel (will be forwarded by audio thread)
if !chunks.is_empty() {
println!("📤 [BACKGROUND] Generated {} chunks, sending to audio thread (pool {})", chunks.len(), pool_index);
let event_chunks: Vec<(u32, (f64, f64), Vec<crate::io::WaveformPeak>)> = chunks
.into_iter()
.map(|chunk| (chunk.chunk_index, chunk.time_range, chunk.peaks))
.collect();
match chunk_tx.send(AudioEvent::WaveformChunksReady {
pool_index,
detail_level: 0,
chunks: event_chunks,
}) {
Ok(_) => println!("✅ [BACKGROUND] Chunks sent successfully for pool {}", pool_index),
Err(e) => eprintln!("❌ [BACKGROUND] Failed to send chunks: {}", e),
}
} else {
eprintln!("⚠️ [BACKGROUND] No chunks generated for pool {}", pool_index);
}
});
// Notify UI about the new audio file
let _ = self.event_tx.push(AudioEvent::AudioFileAdded(pool_index, path));
}
@@ -1446,6 +1512,62 @@ impl Engine {
}
}
}
Command::GenerateWaveformChunks {
pool_index,
detail_level,
chunk_indices,
priority: _priority, // TODO: Use priority for scheduling
} => {
println!("🔧 [ENGINE] Received GenerateWaveformChunks command: pool={}, level={}, chunks={:?}",
pool_index, detail_level, chunk_indices);
// Get audio file data from pool
if let Some(audio_file) = self.audio_pool.get_file(pool_index) {
println!("✅ [ENGINE] Found audio file in pool, spawning background thread");
// Clone necessary data for background thread
let data = audio_file.data.clone();
let channels = audio_file.channels;
let sample_rate = audio_file.sample_rate;
let path = audio_file.path.clone();
let chunk_tx = self.chunk_generation_tx.clone();
// Generate chunks in background thread to avoid blocking audio thread
std::thread::spawn(move || {
// Create temporary AudioFile for chunk generation
let temp_audio_file = crate::audio::pool::AudioFile::with_format(
path,
data,
channels,
sample_rate,
None,
);
// Generate requested chunks
let chunks = crate::audio::waveform_cache::WaveformCache::generate_chunks(
&temp_audio_file,
pool_index,
detail_level,
&chunk_indices,
);
// Send chunks via MPSC channel (will be forwarded by audio thread)
if !chunks.is_empty() {
let event_chunks: Vec<(u32, (f64, f64), Vec<crate::io::WaveformPeak>)> = chunks
.into_iter()
.map(|chunk| (chunk.chunk_index, chunk.time_range, chunk.peaks))
.collect();
let _ = chunk_tx.send(AudioEvent::WaveformChunksReady {
pool_index,
detail_level,
chunks: event_chunks,
});
}
});
} else {
eprintln!("❌ [ENGINE] Pool index {} not found for waveform generation", pool_index);
}
}
}
}
@@ -1693,7 +1815,16 @@ impl Engine {
// Use raw pointer to get midi_pool reference before mutable borrow of project
let midi_pool_ptr: *const _ = &self.project.midi_clip_pool;
let midi_pool_ref = unsafe { &*midi_pool_ptr };
match crate::audio::export_audio(&mut self.project, &self.audio_pool, midi_pool_ref, &settings, &output_path) {
// Pass event_tx directly - Rust allows borrowing different fields simultaneously
match crate::audio::export_audio(
&mut self.project,
&self.audio_pool,
midi_pool_ref,
&settings,
&output_path,
Some(&mut self.event_tx),
) {
Ok(()) => QueryResponse::AudioExported(Ok(())),
Err(e) => QueryResponse::AudioExported(Err(e)),
}
@@ -1747,14 +1878,59 @@ impl Engine {
// Create AudioFile and add to pool
let audio_file = crate::audio::pool::AudioFile::with_format(
path_buf,
data,
path_buf.clone(),
data.clone(), // Clone data for background thread
channels,
sample_rate,
original_format,
);
let pool_index = self.audio_pool.add_file(audio_file);
// Generate Level 0 (overview) waveform chunks asynchronously in background thread
let chunk_tx = self.chunk_generation_tx.clone();
let duration = data.len() as f64 / (sample_rate as f64 * channels as f64);
println!("🔄 [ENGINE] Spawning background thread to generate Level 0 chunks for pool {}", pool_index);
std::thread::spawn(move || {
// Create temporary AudioFile for chunk generation
let temp_audio_file = crate::audio::pool::AudioFile::with_format(
path_buf,
data,
channels,
sample_rate,
None,
);
// Generate Level 0 chunks
let chunk_count = crate::audio::waveform_cache::WaveformCache::calculate_chunk_count(duration, 0);
println!("🔄 [BACKGROUND] Generating {} Level 0 chunks for pool {}", chunk_count, pool_index);
let chunks = crate::audio::waveform_cache::WaveformCache::generate_chunks(
&temp_audio_file,
pool_index,
0, // Level 0 (overview)
&(0..chunk_count).collect::<Vec<_>>(),
);
// Send chunks via MPSC channel (will be forwarded by audio thread)
if !chunks.is_empty() {
println!("📤 [BACKGROUND] Generated {} chunks, sending to audio thread (pool {})", chunks.len(), pool_index);
let event_chunks: Vec<(u32, (f64, f64), Vec<crate::io::WaveformPeak>)> = chunks
.into_iter()
.map(|chunk| (chunk.chunk_index, chunk.time_range, chunk.peaks))
.collect();
match chunk_tx.send(AudioEvent::WaveformChunksReady {
pool_index,
detail_level: 0,
chunks: event_chunks,
}) {
Ok(_) => println!("✅ [BACKGROUND] Chunks sent successfully for pool {}", pool_index),
Err(e) => eprintln!("❌ [BACKGROUND] Failed to send chunks: {}", e),
}
} else {
eprintln!("⚠️ [BACKGROUND] No chunks generated for pool {}", pool_index);
}
});
// Notify UI about the new audio file (for event listeners)
let _ = self.event_tx.push(AudioEvent::AudioFileAdded(pool_index, path));
@@ -1779,7 +1955,10 @@ impl Engine {
};
// Send response back
let _ = self.query_response_tx.push(response);
match self.query_response_tx.push(response) {
Ok(_) => {},
Err(_) => eprintln!("❌ [ENGINE] FAILED to send query response - queue full!"),
}
}
/// Handle starting a recording
@@ -2051,6 +2230,8 @@ pub struct EngineController {
sample_rate: u32,
#[allow(dead_code)] // Used in public getter method
channels: u32,
/// Cached export response found by other query methods
cached_export_response: Option<Result<(), String>>,
}
// Safety: EngineController is safe to Send across threads because:
@@ -2169,7 +2350,10 @@ impl EngineController {
/// Add an audio file to the pool (must be called from non-audio thread with pre-loaded data)
pub fn add_audio_file(&mut self, path: String, data: Vec<f32>, channels: u32, sample_rate: u32) {
let _ = self.command_tx.push(Command::AddAudioFile(path, data, channels, sample_rate));
match self.command_tx.push(Command::AddAudioFile(path.clone(), data, channels, sample_rate)) {
Ok(_) => println!("✅ [CONTROLLER] AddAudioFile command queued successfully: {}", path),
Err(_) => eprintln!("❌ [CONTROLLER] Failed to queue AddAudioFile command (buffer full): {}", path),
}
}
/// Add an audio file to the pool synchronously and get the pool index
@@ -2660,13 +2844,21 @@ impl EngineController {
return Err("Failed to send query - queue full".to_string());
}
// Wait for response (with timeout)
// Wait for response (with shorter timeout to avoid blocking UI during export)
let start = std::time::Instant::now();
let timeout = std::time::Duration::from_secs(2);
let timeout = std::time::Duration::from_millis(50);
while start.elapsed() < timeout {
if let Ok(QueryResponse::PoolWaveform(result)) = self.query_response_rx.pop() {
return result;
if let Ok(response) = self.query_response_rx.pop() {
match response {
QueryResponse::PoolWaveform(result) => return result,
QueryResponse::AudioExported(result) => {
// Cache for poll_export_completion()
println!("💾 [CONTROLLER] Caching AudioExported response from get_pool_waveform");
self.cached_export_response = Some(result);
}
_ => {} // Discard other responses
}
}
std::thread::sleep(std::time::Duration::from_millis(1));
}
@@ -2681,13 +2873,21 @@ impl EngineController {
return Err("Failed to send query - queue full".to_string());
}
// Wait for response (with timeout)
// Wait for response (with shorter timeout to avoid blocking UI during export)
let start = std::time::Instant::now();
let timeout = std::time::Duration::from_secs(2);
let timeout = std::time::Duration::from_millis(50);
while start.elapsed() < timeout {
if let Ok(QueryResponse::PoolFileInfo(result)) = self.query_response_rx.pop() {
return result;
if let Ok(response) = self.query_response_rx.pop() {
match response {
QueryResponse::PoolFileInfo(result) => return result,
QueryResponse::AudioExported(result) => {
// Cache for poll_export_completion()
println!("💾 [CONTROLLER] Caching AudioExported response from get_pool_file_info");
self.cached_export_response = Some(result);
}
_ => {} // Discard other responses
}
}
std::thread::sleep(std::time::Duration::from_millis(1));
}
@@ -2695,6 +2895,29 @@ impl EngineController {
Err("Query timeout".to_string())
}
/// Request waveform chunks to be generated
/// This is an asynchronous command - chunks will be returned via WaveformChunksReady events
pub fn generate_waveform_chunks(
&mut self,
pool_index: usize,
detail_level: u8,
chunk_indices: Vec<u32>,
priority: u8,
) -> Result<(), String> {
let command = Command::GenerateWaveformChunks {
pool_index,
detail_level,
chunk_indices,
priority,
};
if let Err(_) = self.command_tx.push(command) {
return Err("Failed to send command - queue full".to_string());
}
Ok(())
}
/// 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
@@ -2779,19 +3002,57 @@ impl EngineController {
Err("Query timeout".to_string())
}
/// Export audio to a file
pub fn export_audio<P: AsRef<std::path::Path>>(&mut self, settings: &crate::audio::ExportSettings, output_path: P) -> Result<(), String> {
/// Start an audio export (non-blocking)
///
/// Sends the export query to the audio thread and returns immediately.
/// Use `poll_export_completion()` to check for completion.
pub fn start_export_audio<P: AsRef<std::path::Path>>(&mut self, settings: &crate::audio::ExportSettings, output_path: P) -> Result<(), String> {
// Send export query
if let Err(_) = self.query_tx.push(Query::ExportAudio(settings.clone(), output_path.as_ref().to_path_buf())) {
return Err("Failed to send export query - queue full".to_string());
}
Ok(())
}
/// Poll for export completion (non-blocking)
///
/// Returns:
/// - `Ok(Some(result))` if export completed (result may be Ok or Err)
/// - `Ok(None)` if export is still in progress
/// - `Err` should not happen in normal operation
pub fn poll_export_completion(&mut self) -> Result<Option<Result<(), String>>, String> {
// Check if we have a cached response from another query method
if let Some(result) = self.cached_export_response.take() {
println!("✅ [CONTROLLER] Found cached AudioExported response!");
return Ok(Some(result));
}
// Keep popping responses until we find AudioExported or queue is empty
while let Ok(response) = self.query_response_rx.pop() {
println!("📥 [CONTROLLER] Received response: {:?}", std::mem::discriminant(&response));
if let QueryResponse::AudioExported(result) = response {
println!("✅ [CONTROLLER] Found AudioExported response!");
return Ok(Some(result));
}
// Discard other query responses (they're for synchronous queries)
println!("⏭️ [CONTROLLER] Skipping non-export response");
}
Ok(None)
}
/// Export audio to a file (blocking)
///
/// This is a convenience method that calls start_export_audio and waits for completion.
/// For non-blocking export with progress updates, use start_export_audio() and poll_export_completion().
pub fn export_audio<P: AsRef<std::path::Path>>(&mut self, settings: &crate::audio::ExportSettings, output_path: P) -> Result<(), String> {
self.start_export_audio(settings, &output_path)?;
// Wait for response (with longer timeout since export can take a while)
let start = std::time::Instant::now();
let timeout = std::time::Duration::from_secs(300); // 5 minute timeout for export
while start.elapsed() < timeout {
if let Ok(QueryResponse::AudioExported(result)) = self.query_response_rx.pop() {
if let Some(result) = self.poll_export_completion()? {
return result;
}
std::thread::sleep(std::time::Duration::from_millis(100));
+31 -4
View File
@@ -2,6 +2,7 @@ use super::buffer_pool::BufferPool;
use super::midi_pool::MidiClipPool;
use super::pool::AudioPool;
use super::project::Project;
use crate::command::AudioEvent;
use std::path::Path;
/// Supported export formats
@@ -59,15 +60,20 @@ impl Default for ExportSettings {
///
/// This performs offline rendering, processing the entire timeline
/// in chunks to generate the final audio file.
///
/// If an event producer is provided, progress events will be sent
/// after each chunk with (frames_rendered, total_frames).
pub fn export_audio<P: AsRef<Path>>(
project: &mut Project,
pool: &AudioPool,
midi_pool: &MidiClipPool,
settings: &ExportSettings,
output_path: P,
) -> Result<(), String> {
mut event_tx: Option<&mut rtrb::Producer<AudioEvent>>,
) -> Result<(), String>
{
// Render the project to memory
let samples = render_to_memory(project, pool, midi_pool, settings)?;
let samples = render_to_memory(project, pool, midi_pool, settings, event_tx)?;
// Write to file based on format
match settings.format {
@@ -79,12 +85,23 @@ pub fn export_audio<P: AsRef<Path>>(
}
/// Render the project to memory
fn render_to_memory(
///
/// This function renders the project's audio to an in-memory buffer
/// of interleaved f32 samples. This is useful for custom export formats
/// or for passing audio to external encoders (e.g., FFmpeg for MP3/AAC).
///
/// The returned samples are interleaved (L,R,L,R,... for stereo).
///
/// If an event producer is provided, progress events will be sent
/// after each chunk with (frames_rendered, total_frames).
pub fn render_to_memory(
project: &mut Project,
pool: &AudioPool,
midi_pool: &MidiClipPool,
settings: &ExportSettings,
) -> Result<Vec<f32>, String> {
mut event_tx: Option<&mut rtrb::Producer<AudioEvent>>,
) -> Result<Vec<f32>, String>
{
// Calculate total number of frames
let duration = settings.end_time - settings.start_time;
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
@@ -106,6 +123,7 @@ fn render_to_memory(
let mut playhead = settings.start_time;
let chunk_duration = CHUNK_FRAMES as f64 / settings.sample_rate as f64;
let mut frames_rendered = 0;
// Render the entire timeline in chunks
while playhead < settings.end_time {
@@ -138,6 +156,15 @@ fn render_to_memory(
// Append to output
all_samples.extend_from_slice(&render_buffer[..samples_needed]);
// Update progress
frames_rendered += samples_needed / settings.channels as usize;
if let Some(event_tx) = event_tx.as_mut() {
let _ = event_tx.push(AudioEvent::ExportProgress {
frames_rendered,
total_frames,
});
}
playhead += chunk_duration;
}
+2
View File
@@ -13,6 +13,7 @@ pub mod project;
pub mod recording;
pub mod sample_loader;
pub mod track;
pub mod waveform_cache;
pub use automation::{AutomationLane, AutomationLaneId, AutomationPoint, CurveType, ParameterId};
pub use buffer_pool::BufferPool;
@@ -27,3 +28,4 @@ pub use project::Project;
pub use recording::RecordingState;
pub use sample_loader::{load_audio_file, SampleData};
pub use track::{AudioTrack, Metatrack, MidiTrack, RenderContext, Track, TrackId, TrackNode};
pub use waveform_cache::{ChunkPriority, DetailLevel, WaveformCache};
+94
View File
@@ -170,6 +170,8 @@ impl AudioFile {
/// Pool of shared audio files (audio clip content)
pub struct AudioClipPool {
files: Vec<AudioFile>,
/// Waveform chunk cache for multi-resolution waveform generation
waveform_cache: crate::audio::waveform_cache::WaveformCache,
}
/// Type alias for backwards compatibility
@@ -180,6 +182,7 @@ impl AudioClipPool {
pub fn new() -> Self {
Self {
files: Vec::new(),
waveform_cache: crate::audio::waveform_cache::WaveformCache::new(100), // 100MB cache
}
}
@@ -369,6 +372,97 @@ impl AudioClipPool {
rendered_frames * dst_channels
}
/// Generate waveform chunks for a file in the pool
///
/// This generates chunks at a specific detail level and caches them.
/// Returns the generated chunks.
pub fn generate_waveform_chunks(
&mut self,
pool_index: usize,
detail_level: u8,
chunk_indices: &[u32],
) -> Vec<crate::io::WaveformChunk> {
let file = match self.files.get(pool_index) {
Some(f) => f,
None => return Vec::new(),
};
let chunks = crate::audio::waveform_cache::WaveformCache::generate_chunks(
file,
pool_index,
detail_level,
chunk_indices,
);
// Store chunks in cache
for chunk in &chunks {
let key = crate::io::WaveformChunkKey {
pool_index,
detail_level: chunk.detail_level,
chunk_index: chunk.chunk_index,
};
self.waveform_cache.store_chunk(key, chunk.peaks.clone());
}
chunks
}
/// Generate Level 0 (overview) chunks for a file
///
/// This should be called immediately when a file is imported.
/// Returns the generated chunks.
pub fn generate_overview_chunks(
&mut self,
pool_index: usize,
) -> Vec<crate::io::WaveformChunk> {
let file = match self.files.get(pool_index) {
Some(f) => f,
None => return Vec::new(),
};
self.waveform_cache.generate_overview_chunks(file, pool_index)
}
/// Get a cached waveform chunk
pub fn get_waveform_chunk(
&self,
pool_index: usize,
detail_level: u8,
chunk_index: u32,
) -> Option<&Vec<crate::io::WaveformPeak>> {
let key = crate::io::WaveformChunkKey {
pool_index,
detail_level,
chunk_index,
};
self.waveform_cache.get_chunk(&key)
}
/// Check if a waveform chunk is cached
pub fn has_waveform_chunk(
&self,
pool_index: usize,
detail_level: u8,
chunk_index: u32,
) -> bool {
let key = crate::io::WaveformChunkKey {
pool_index,
detail_level,
chunk_index,
};
self.waveform_cache.has_chunk(&key)
}
/// Get waveform cache memory usage in MB
pub fn waveform_cache_memory_mb(&self) -> f64 {
self.waveform_cache.memory_usage_mb()
}
/// Get number of cached waveform chunks
pub fn waveform_chunk_count(&self) -> usize {
self.waveform_cache.chunk_count()
}
}
impl Default for AudioClipPool {
+290
View File
@@ -0,0 +1,290 @@
//! Waveform chunk cache for scalable multi-resolution waveform generation
//!
//! This module provides a chunk-based waveform caching system that generates
//! waveform data progressively at multiple detail levels, avoiding the limitations
//! of the old fixed 20,000-peak approach.
use crate::io::{WaveformChunk, WaveformChunkKey, WaveformPeak};
use crate::audio::pool::AudioFile;
use std::collections::HashMap;
/// Detail levels for multi-resolution waveform storage
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DetailLevel {
Overview = 0, // 1 peak per second
Low = 1, // 10 peaks per second
Medium = 2, // 100 peaks per second
High = 3, // 1000 peaks per second
Max = 4, // Full resolution (sample-accurate)
}
impl DetailLevel {
/// Get peaks per second for this detail level
pub fn peaks_per_second(self) -> usize {
match self {
DetailLevel::Overview => 1,
DetailLevel::Low => 10,
DetailLevel::Medium => 100,
DetailLevel::High => 1000,
DetailLevel::Max => 48000, // Approximate max for sample-accurate
}
}
/// Create from u8 value
pub fn from_u8(value: u8) -> Option<Self> {
match value {
0 => Some(DetailLevel::Overview),
1 => Some(DetailLevel::Low),
2 => Some(DetailLevel::Medium),
3 => Some(DetailLevel::High),
4 => Some(DetailLevel::Max),
_ => None,
}
}
}
/// Priority for chunk generation
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ChunkPriority {
Low = 0, // Background generation
Medium = 1, // Precache adjacent to viewport
High = 2, // Visible in current viewport
}
/// Chunk generation request
#[derive(Debug, Clone)]
pub struct ChunkGenerationRequest {
pub key: WaveformChunkKey,
pub priority: ChunkPriority,
}
/// Waveform chunk cache with multi-resolution support
pub struct WaveformCache {
/// Cached chunks indexed by key
chunks: HashMap<WaveformChunkKey, Vec<WaveformPeak>>,
/// Maximum memory usage in MB (for future LRU eviction)
max_memory_mb: usize,
/// Current memory usage estimate in bytes
current_memory_bytes: usize,
}
impl WaveformCache {
/// Create a new waveform cache with the specified memory limit
pub fn new(max_memory_mb: usize) -> Self {
Self {
chunks: HashMap::new(),
max_memory_mb,
current_memory_bytes: 0,
}
}
/// Get a chunk from the cache
pub fn get_chunk(&self, key: &WaveformChunkKey) -> Option<&Vec<WaveformPeak>> {
self.chunks.get(key)
}
/// Store a chunk in the cache
pub fn store_chunk(&mut self, key: WaveformChunkKey, peaks: Vec<WaveformPeak>) {
let chunk_size = peaks.len() * std::mem::size_of::<WaveformPeak>();
self.current_memory_bytes += chunk_size;
self.chunks.insert(key, peaks);
// TODO: Implement LRU eviction if memory exceeds limit
}
/// Check if a chunk exists in the cache
pub fn has_chunk(&self, key: &WaveformChunkKey) -> bool {
self.chunks.contains_key(key)
}
/// Clear all chunks for a specific pool index (when file is unloaded)
pub fn clear_pool(&mut self, pool_index: usize) {
self.chunks.retain(|key, peaks| {
if key.pool_index == pool_index {
let chunk_size = peaks.len() * std::mem::size_of::<WaveformPeak>();
self.current_memory_bytes = self.current_memory_bytes.saturating_sub(chunk_size);
false
} else {
true
}
});
}
/// Generate a single waveform chunk for an audio file
///
/// This generates peaks for a specific time range at a specific detail level.
/// The chunk covers a time range based on the detail level and chunk index.
pub fn generate_chunk(
audio_file: &AudioFile,
detail_level: u8,
chunk_index: u32,
) -> Option<WaveformChunk> {
let level = DetailLevel::from_u8(detail_level)?;
let peaks_per_second = level.peaks_per_second();
// Calculate time range for this chunk based on detail level
// Each chunk covers a varying amount of time depending on detail level
let chunk_duration_seconds = match level {
DetailLevel::Overview => 60.0, // 60 seconds per chunk (60 peaks)
DetailLevel::Low => 30.0, // 30 seconds per chunk (300 peaks)
DetailLevel::Medium => 10.0, // 10 seconds per chunk (1000 peaks)
DetailLevel::High => 5.0, // 5 seconds per chunk (5000 peaks)
DetailLevel::Max => 1.0, // 1 second per chunk (48000 peaks)
};
let start_time = chunk_index as f64 * chunk_duration_seconds;
let end_time = start_time + chunk_duration_seconds;
// Check if this chunk is within the audio file duration
let audio_duration = audio_file.duration_seconds();
if start_time >= audio_duration {
return None; // Chunk is completely beyond file end
}
// Clamp end_time to file duration
let end_time = end_time.min(audio_duration);
// Calculate frame range
let start_frame = (start_time * audio_file.sample_rate as f64) as usize;
let end_frame = (end_time * audio_file.sample_rate as f64) as usize;
// Calculate number of peaks for this time range
let duration = end_time - start_time;
let target_peaks = (duration * peaks_per_second as f64).ceil() as usize;
if target_peaks == 0 {
return None;
}
// Generate peaks using the existing method
let peaks = audio_file.generate_waveform_overview_range(
start_frame,
end_frame,
target_peaks,
);
Some(WaveformChunk {
audio_pool_index: 0, // Will be set by caller
detail_level,
chunk_index,
time_range: (start_time, end_time),
peaks,
})
}
/// Generate multiple chunks for an audio file
///
/// This is a convenience method for generating several chunks at once.
pub fn generate_chunks(
audio_file: &AudioFile,
pool_index: usize,
detail_level: u8,
chunk_indices: &[u32],
) -> Vec<WaveformChunk> {
chunk_indices
.iter()
.filter_map(|&chunk_index| {
let mut chunk = Self::generate_chunk(audio_file, detail_level, chunk_index)?;
chunk.audio_pool_index = pool_index;
Some(chunk)
})
.collect()
}
/// Calculate how many chunks are needed for a file at a given detail level
pub fn calculate_chunk_count(duration_seconds: f64, detail_level: u8) -> u32 {
let level = match DetailLevel::from_u8(detail_level) {
Some(l) => l,
None => return 0,
};
let chunk_duration_seconds = match level {
DetailLevel::Overview => 60.0,
DetailLevel::Low => 30.0,
DetailLevel::Medium => 10.0,
DetailLevel::High => 5.0,
DetailLevel::Max => 1.0,
};
((duration_seconds / chunk_duration_seconds).ceil() as u32).max(1)
}
/// Generate all Level 0 (overview) chunks for a file
///
/// This should be called immediately when a file is imported to provide
/// instant thumbnail display.
pub fn generate_overview_chunks(
&mut self,
audio_file: &AudioFile,
pool_index: usize,
) -> Vec<WaveformChunk> {
let duration = audio_file.duration_seconds();
let chunk_count = Self::calculate_chunk_count(duration, 0);
let chunk_indices: Vec<u32> = (0..chunk_count).collect();
let chunks = Self::generate_chunks(audio_file, pool_index, 0, &chunk_indices);
// Store chunks in cache
for chunk in &chunks {
let key = WaveformChunkKey {
pool_index,
detail_level: chunk.detail_level,
chunk_index: chunk.chunk_index,
};
self.store_chunk(key, chunk.peaks.clone());
}
chunks
}
/// Get current memory usage in bytes
pub fn memory_usage_bytes(&self) -> usize {
self.current_memory_bytes
}
/// Get current memory usage in megabytes
pub fn memory_usage_mb(&self) -> f64 {
self.current_memory_bytes as f64 / 1_000_000.0
}
/// Get number of cached chunks
pub fn chunk_count(&self) -> usize {
self.chunks.len()
}
}
impl Default for WaveformCache {
fn default() -> Self {
Self::new(100) // Default 100MB cache
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_detail_level_peaks_per_second() {
assert_eq!(DetailLevel::Overview.peaks_per_second(), 1);
assert_eq!(DetailLevel::Low.peaks_per_second(), 10);
assert_eq!(DetailLevel::Medium.peaks_per_second(), 100);
assert_eq!(DetailLevel::High.peaks_per_second(), 1000);
}
#[test]
fn test_chunk_count_calculation() {
// 60 second file, Overview level (60s chunks) = 1 chunk
assert_eq!(WaveformCache::calculate_chunk_count(60.0, 0), 1);
// 120 second file, Overview level (60s chunks) = 2 chunks
assert_eq!(WaveformCache::calculate_chunk_count(120.0, 0), 2);
// 10 second file, Medium level (10s chunks) = 1 chunk
assert_eq!(WaveformCache::calculate_chunk_count(10.0, 2), 1);
// 25 second file, Medium level (10s chunks) = 3 chunks
assert_eq!(WaveformCache::calculate_chunk_count(25.0, 2), 3);
}
}
+25
View File
@@ -176,6 +176,16 @@ pub enum Command {
AutomationRemoveKeyframe(TrackId, u32, f64),
/// Set the display name of an AutomationInput node (track_id, node_id, name)
AutomationSetName(TrackId, u32, String),
// Waveform chunk generation commands
/// Generate waveform chunks for an audio file
/// (pool_index, detail_level, chunk_indices, priority)
GenerateWaveformChunks {
pool_index: usize,
detail_level: u8,
chunk_indices: Vec<u32>,
priority: u8, // 0=Low, 1=Medium, 2=High
},
}
/// Events sent from audio thread back to UI/control thread
@@ -228,6 +238,21 @@ pub enum AudioEvent {
GraphPresetLoaded(TrackId),
/// Preset has been saved to file (track_id, preset_path)
GraphPresetSaved(TrackId, String),
/// Export progress (frames_rendered, total_frames)
ExportProgress {
frames_rendered: usize,
total_frames: usize,
},
/// Waveform generated for audio pool file (pool_index, waveform)
WaveformGenerated(usize, Vec<WaveformPeak>),
/// Waveform chunks ready for retrieval
/// (pool_index, detail_level, chunks: Vec<(chunk_index, time_range, peaks)>)
WaveformChunksReady {
pool_index: usize,
detail_level: u8,
chunks: Vec<(u32, (f64, f64), Vec<WaveformPeak>)>,
},
}
/// Synchronous queries sent from UI thread to audio thread
+18
View File
@@ -13,6 +13,24 @@ pub struct WaveformPeak {
pub max: f32,
}
/// Uniquely identifies a waveform chunk
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WaveformChunkKey {
pub pool_index: usize,
pub detail_level: u8, // 0-4
pub chunk_index: u32, // Sequential chunk number
}
/// A chunk of waveform data at a specific detail level
#[derive(Debug, Clone)]
pub struct WaveformChunk {
pub audio_pool_index: usize,
pub detail_level: u8, // 0-4 (overview to max detail)
pub chunk_index: u32, // Sequential chunk number
pub time_range: (f64, f64), // Start and end time in seconds
pub peaks: Vec<WaveformPeak>, // Variable length based on level
}
pub struct AudioFile {
pub data: Vec<f32>,
pub channels: u32,
+1 -1
View File
@@ -3,7 +3,7 @@ pub mod midi_file;
pub mod midi_input;
pub mod wav_writer;
pub use audio_file::{AudioFile, WaveformPeak};
pub use audio_file::{AudioFile, WaveformChunk, WaveformChunkKey, WaveformPeak};
pub use midi_file::load_midi_file;
pub use midi_input::MidiInputManager;
pub use wav_writer::WavWriter;
+1 -1
View File
@@ -20,7 +20,7 @@ pub use audio::{
pub use audio::node_graph::{GraphPreset, AudioGraph, PresetMetadata, SerializedConnection, SerializedNode};
pub use command::{AudioEvent, Command, OscilloscopeData};
pub use command::types::AutomationKeyframeData;
pub use io::{load_midi_file, AudioFile, WaveformPeak, WavWriter};
pub use io::{load_midi_file, AudioFile, WaveformChunk, WaveformChunkKey, WaveformPeak, WavWriter};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};