Add copy and paste

This commit is contained in:
Skyler Lehmkuhl
2026-02-15 04:38:42 -05:00
parent 5164d7a0a9
commit c6a8b944e5
17 changed files with 1298 additions and 74 deletions
+10
View File
@@ -1,3 +1,4 @@
use std::sync::Arc;
use serde::{Serialize, Deserialize};
/// Audio clip instance ID type
@@ -35,6 +36,13 @@ pub struct AudioClipInstance {
/// Clip-level gain
pub gain: f32,
/// Per-instance read-ahead buffer for compressed audio streaming.
/// Each clip instance gets its own buffer so multiple instances of the
/// same file (on different tracks or at different positions) don't fight
/// over a single target_frame.
#[serde(skip)]
pub read_ahead: Option<Arc<super::disk_reader::ReadAheadBuffer>>,
}
/// Type alias for backwards compatibility
@@ -58,6 +66,7 @@ impl AudioClipInstance {
external_start,
external_duration,
gain: 1.0,
read_ahead: None,
}
}
@@ -78,6 +87,7 @@ impl AudioClipInstance {
external_start: start_time,
external_duration: duration,
gain: 1.0,
read_ahead: None,
}
}
+45 -19
View File
@@ -166,11 +166,27 @@ impl ReadAheadBuffer {
/// Update the target frame — the file-local frame the audio callback
/// is currently reading from. Called by `render_from_file` (consumer).
/// Each clip instance has its own buffer, so a plain store is sufficient.
#[inline]
pub fn set_target_frame(&self, frame: u64) {
self.target_frame.store(frame, Ordering::Relaxed);
}
/// Reset the target frame to MAX before a new render cycle.
/// If no clip calls `set_target_frame` this cycle, `has_active_target()`
/// returns false, telling the disk reader to skip this buffer.
#[inline]
pub fn reset_target_frame(&self) {
self.target_frame.store(u64::MAX, Ordering::Relaxed);
}
/// Force-set the target frame to an exact value.
/// Used by the disk reader's seek command where we need an absolute position.
#[inline]
pub fn force_target_frame(&self, frame: u64) {
self.target_frame.store(frame, Ordering::Relaxed);
}
/// Get the target frame set by the audio callback.
/// Called by the disk reader thread (producer).
#[inline]
@@ -178,6 +194,12 @@ impl ReadAheadBuffer {
self.target_frame.load(Ordering::Relaxed)
}
/// Check if any clip set a target this cycle (vs still at reset value).
#[inline]
pub fn has_active_target(&self) -> bool {
self.target_frame.load(Ordering::Relaxed) != u64::MAX
}
/// Reset the buffer to start at `new_start` with zero valid frames.
/// Called by the **disk reader thread** (producer) after a seek.
pub fn reset(&self, new_start: u64) {
@@ -413,14 +435,14 @@ impl CompressedReader {
/// Commands sent from the engine to the disk reader thread.
pub enum DiskReaderCommand {
/// Start streaming a compressed file.
/// Start streaming a compressed file for a clip instance.
ActivateFile {
pool_index: usize,
reader_id: u64,
path: PathBuf,
buffer: Arc<ReadAheadBuffer>,
},
/// Stop streaming a file.
DeactivateFile { pool_index: usize },
/// Stop streaming for a clip instance.
DeactivateFile { reader_id: u64 },
/// The playhead has jumped — refill buffers from the new position.
Seek { frame: u64 },
/// Shut down the disk reader thread.
@@ -491,7 +513,7 @@ impl DiskReader {
mut command_rx: rtrb::Consumer<DiskReaderCommand>,
running: Arc<AtomicBool>,
) {
let mut active_files: HashMap<usize, (CompressedReader, Arc<ReadAheadBuffer>)> =
let mut active_files: HashMap<u64, (CompressedReader, Arc<ReadAheadBuffer>)> =
HashMap::new();
let mut decode_buf = Vec::with_capacity(8192);
@@ -500,14 +522,14 @@ impl DiskReader {
while let Ok(cmd) = command_rx.pop() {
match cmd {
DiskReaderCommand::ActivateFile {
pool_index,
reader_id,
path,
buffer,
} => match CompressedReader::open(&path) {
Ok(reader) => {
eprintln!("[DiskReader] Activated pool={}, ch={}, sr={}, path={:?}",
pool_index, reader.channels, reader.sample_rate, path);
active_files.insert(pool_index, (reader, buffer));
eprintln!("[DiskReader] Activated reader={}, ch={}, sr={}, path={:?}",
reader_id, reader.channels, reader.sample_rate, path);
active_files.insert(reader_id, (reader, buffer));
}
Err(e) => {
eprintln!(
@@ -516,12 +538,12 @@ impl DiskReader {
);
}
},
DiskReaderCommand::DeactivateFile { pool_index } => {
active_files.remove(&pool_index);
DiskReaderCommand::DeactivateFile { reader_id } => {
active_files.remove(&reader_id);
}
DiskReaderCommand::Seek { frame } => {
for (_, (reader, buffer)) in active_files.iter_mut() {
buffer.set_target_frame(frame);
buffer.force_target_frame(frame);
buffer.reset(frame);
if let Err(e) = reader.seek(frame) {
eprintln!("[DiskReader] Seek error: {}", e);
@@ -534,11 +556,15 @@ impl DiskReader {
}
}
// Fill each active file's buffer ahead of its target frame.
// Each file's target_frame is set by the audio callback in
// render_from_file, giving the file-local frame being read.
// This is independent of the global engine playhead.
for (_pool_index, (reader, buffer)) in active_files.iter_mut() {
// Fill each active reader's buffer ahead of its target frame.
// Each clip instance has its own buffer and target_frame, set by
// render_from_file during the audio callback.
for (_reader_id, (reader, buffer)) in active_files.iter_mut() {
// Skip files where no clip is currently playing
if !buffer.has_active_target() {
continue;
}
let target = buffer.target_frame();
let buf_start = buffer.start_frame();
let buf_valid = buffer.valid_frames_count();
@@ -578,8 +604,8 @@ impl DiskReader {
let was_empty = buffer.valid_frames_count() == 0;
buffer.write_samples(&decode_buf, frames);
if was_empty {
eprintln!("[DiskReader] pool={}: first fill, {} frames, buf_start={}, valid={}",
_pool_index, frames, buffer.start_frame(), buffer.valid_frames_count());
eprintln!("[DiskReader] reader={}: first fill, {} frames, buf_start={}, valid={}",
_reader_id, frames, buffer.start_frame(), buffer.valid_frames_count());
}
}
Err(e) => {
+33 -15
View File
@@ -313,6 +313,9 @@ impl Engine {
// Convert playhead from frames to seconds for timeline-based rendering
let playhead_seconds = self.playhead as f64 / self.sample_rate as f64;
// Reset per-clip read-ahead targets before rendering.
self.project.reset_read_ahead_targets();
// Render the entire project hierarchy into the mix buffer
// Note: We need to use a raw pointer to avoid borrow checker issues
// The midi_clip_pool is part of project, so we extract a reference before mutable borrow
@@ -798,6 +801,12 @@ impl Engine {
let _ = self.project.remove_midi_clip(track_id, instance_id);
}
Command::RemoveAudioClip(track_id, instance_id) => {
// Deactivate the per-clip disk reader before removing
if let Some(ref mut dr) = self.disk_reader {
dr.send(crate::audio::disk_reader::DiskReaderCommand::DeactivateFile {
reader_id: instance_id as u64,
});
}
// Remove an audio clip instance from a track (for undo/redo support)
let _ = self.project.remove_audio_clip(track_id, instance_id);
}
@@ -1754,7 +1763,7 @@ impl Engine {
(metadata.duration * metadata.sample_rate as f64).ceil() as u64
});
let mut audio_file = crate::audio::pool::AudioFile::from_compressed(
let audio_file = crate::audio::pool::AudioFile::from_compressed(
path.to_path_buf(),
metadata.channels,
metadata.sample_rate,
@@ -1762,25 +1771,11 @@ impl Engine {
ext,
);
let buffer = crate::audio::disk_reader::DiskReader::create_buffer(
metadata.sample_rate,
metadata.channels,
);
audio_file.read_ahead = Some(buffer.clone());
let idx = self.audio_pool.add_file(audio_file);
eprintln!("[ENGINE] Compressed: total_frames={}, pool_index={}, has_disk_reader={}",
total_frames, idx, self.disk_reader.is_some());
if let Some(ref mut dr) = self.disk_reader {
dr.send(crate::audio::disk_reader::DiskReaderCommand::ActivateFile {
pool_index: idx,
path: path.to_path_buf(),
buffer,
});
}
// Spawn background thread to decode file progressively for waveform display
let bg_tx = self.chunk_generation_tx.clone();
let bg_path = path.to_path_buf();
@@ -2138,6 +2133,28 @@ impl Engine {
let instance_id = self.next_clip_id;
self.next_clip_id += 1;
// For compressed files, create a per-clip read-ahead buffer
let read_ahead = if let Some(file) = self.audio_pool.get_file(pool_index) {
if matches!(file.storage, crate::audio::pool::AudioStorage::Compressed { .. }) {
let buffer = crate::audio::disk_reader::DiskReader::create_buffer(
file.sample_rate,
file.channels,
);
if let Some(ref mut dr) = self.disk_reader {
dr.send(crate::audio::disk_reader::DiskReaderCommand::ActivateFile {
reader_id: instance_id as u64,
path: file.path.clone(),
buffer: buffer.clone(),
});
}
Some(buffer)
} else {
None
}
} else {
None
};
let clip = AudioClipInstance {
id: instance_id,
audio_pool_index: pool_index,
@@ -2146,6 +2163,7 @@ impl Engine {
external_start: start_time,
external_duration: duration,
gain: 1.0,
read_ahead,
};
match self.project.add_clip(track_id, clip) {
+3 -8
View File
@@ -95,9 +95,6 @@ pub struct AudioFile {
/// Original file format (mp3, ogg, wav, flac, etc.)
/// Used to determine if we should preserve lossy encoding during save
pub original_format: Option<String>,
/// Read-ahead buffer for streaming playback (Compressed files).
/// When present, `render_from_file` reads from this buffer instead of `data()`.
pub read_ahead: Option<Arc<super::disk_reader::ReadAheadBuffer>>,
}
impl AudioFile {
@@ -111,7 +108,6 @@ impl AudioFile {
sample_rate,
frames,
original_format: None,
read_ahead: None,
}
}
@@ -125,7 +121,6 @@ impl AudioFile {
sample_rate,
frames,
original_format,
read_ahead: None,
}
}
@@ -157,7 +152,6 @@ impl AudioFile {
sample_rate,
frames: total_frames,
original_format: Some("wav".to_string()),
read_ahead: None,
}
}
@@ -180,7 +174,6 @@ impl AudioFile {
sample_rate,
frames: total_frames,
original_format,
read_ahead: None,
}
}
@@ -444,6 +437,7 @@ impl AudioClipPool {
/// Render audio from a file in the pool with high-quality windowed sinc interpolation
/// start_time_seconds: position in the audio file to start reading from (in seconds)
/// clip_read_ahead: per-clip-instance read-ahead buffer for compressed audio streaming
/// Returns the number of samples actually rendered
pub fn render_from_file(
&self,
@@ -453,13 +447,14 @@ impl AudioClipPool {
gain: f32,
engine_sample_rate: u32,
engine_channels: u32,
clip_read_ahead: Option<&super::disk_reader::ReadAheadBuffer>,
) -> usize {
let Some(audio_file) = self.files.get(pool_index) else {
return 0;
};
let audio_data = audio_file.data();
let read_ahead = audio_file.read_ahead.as_deref();
let read_ahead = clip_read_ahead;
let use_read_ahead = audio_data.is_empty();
let src_channels = audio_file.channels as usize;
+13
View File
@@ -484,6 +484,19 @@ impl Project {
}
}
/// Reset all per-clip read-ahead target frames before a new render cycle.
pub fn reset_read_ahead_targets(&self) {
for track in self.tracks.values() {
if let TrackNode::Audio(audio_track) = track {
for clip in &audio_track.clips {
if let Some(ra) = clip.read_ahead.as_deref() {
ra.reset_target_frame();
}
}
}
}
}
/// Stop all notes on all MIDI tracks
pub fn stop_all_notes(&mut self) {
for track in self.tracks.values_mut() {
+2
View File
@@ -917,6 +917,7 @@ impl AudioTrack {
combined_gain,
sample_rate,
channels,
clip.read_ahead.as_deref(),
);
} else {
// Looping case: need to handle wrap-around at loop boundaries
@@ -951,6 +952,7 @@ impl AudioTrack {
combined_gain,
sample_rate,
channels,
clip.read_ahead.as_deref(),
);
total_rendered += rendered;