node graph fixes
This commit is contained in:
@@ -74,6 +74,9 @@ pub struct ReadAheadBuffer {
|
||||
/// The disk reader uses this instead of the global playhead to know
|
||||
/// where in the file to buffer around.
|
||||
target_frame: AtomicU64,
|
||||
/// When true, `render_from_file` will block-wait for frames instead of
|
||||
/// returning silence on buffer miss. Used during offline export.
|
||||
export_mode: AtomicBool,
|
||||
}
|
||||
|
||||
// SAFETY: See the doc comment on ReadAheadBuffer for the full safety argument.
|
||||
@@ -108,6 +111,7 @@ impl ReadAheadBuffer {
|
||||
channels,
|
||||
sample_rate,
|
||||
target_frame: AtomicU64::new(0),
|
||||
export_mode: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,6 +204,18 @@ impl ReadAheadBuffer {
|
||||
self.target_frame.load(Ordering::Relaxed) != u64::MAX
|
||||
}
|
||||
|
||||
/// Enable or disable export (blocking) mode. When enabled,
|
||||
/// `render_from_file` will spin-wait for frames instead of returning
|
||||
/// silence on buffer miss.
|
||||
pub fn set_export_mode(&self, export: bool) {
|
||||
self.export_mode.store(export, Ordering::Release);
|
||||
}
|
||||
|
||||
/// Check if export (blocking) mode is active.
|
||||
pub fn is_export_mode(&self) -> bool {
|
||||
self.export_mode.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
@@ -614,8 +630,12 @@ impl DiskReader {
|
||||
}
|
||||
}
|
||||
|
||||
// Sleep briefly to avoid busy-spinning when all buffers are full.
|
||||
std::thread::sleep(std::time::Duration::from_millis(POLL_INTERVAL_MS));
|
||||
// In export mode, skip the sleep so decoding runs at full speed.
|
||||
// Otherwise sleep briefly to avoid busy-spinning.
|
||||
let any_exporting = active_files.values().any(|(_, buf)| buf.is_export_mode());
|
||||
if !any_exporting {
|
||||
std::thread::sleep(std::time::Duration::from_millis(POLL_INTERVAL_MS));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1334,6 +1334,18 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
|
||||
Command::GraphSetNodePosition(track_id, node_index, x, y) => {
|
||||
let graph = match self.project.get_track_mut(track_id) {
|
||||
Some(TrackNode::Midi(track)) => Some(&mut track.instrument_graph),
|
||||
Some(TrackNode::Audio(track)) => Some(&mut track.effects_graph),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(graph) = graph {
|
||||
let node_idx = NodeIndex::new(node_index as usize);
|
||||
graph.set_node_position(node_idx, x, y);
|
||||
}
|
||||
}
|
||||
|
||||
Command::GraphSetMidiTarget(track_id, node_index, enabled) => {
|
||||
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
|
||||
let graph = &mut track.instrument_graph;
|
||||
@@ -2245,7 +2257,10 @@ impl Engine {
|
||||
QueryResponse::AudioImportedSync(self.do_import_audio(&path))
|
||||
}
|
||||
Query::GetProject => {
|
||||
// Clone the entire project for serialization
|
||||
// Save graph presets before cloning — AudioTrack::clone() creates
|
||||
// a fresh default graph (not a copy), so the preset must be populated
|
||||
// first so the clone carries the serialized graph data.
|
||||
self.project.prepare_for_save();
|
||||
QueryResponse::ProjectRetrieved(Ok(Box::new(self.project.clone())))
|
||||
}
|
||||
Query::SetProject(new_project) => {
|
||||
@@ -2950,6 +2965,11 @@ impl EngineController {
|
||||
let _ = self.command_tx.push(Command::GraphSetParameter(track_id, node_id, param_id, value));
|
||||
}
|
||||
|
||||
/// Set the UI position of a node in a track's graph
|
||||
pub fn graph_set_node_position(&mut self, track_id: TrackId, node_id: u32, x: f32, y: f32) {
|
||||
let _ = self.command_tx.push(Command::GraphSetNodePosition(track_id, node_id, x, y));
|
||||
}
|
||||
|
||||
/// Set which node receives MIDI events in a track's instrument graph
|
||||
pub fn graph_set_midi_target(&mut self, track_id: TrackId, node_id: u32, enabled: bool) {
|
||||
let _ = self.command_tx.push(Command::GraphSetMidiTarget(track_id, node_id, enabled));
|
||||
|
||||
@@ -72,29 +72,44 @@ pub fn export_audio<P: AsRef<Path>>(
|
||||
midi_pool: &MidiClipPool,
|
||||
settings: &ExportSettings,
|
||||
output_path: P,
|
||||
event_tx: Option<&mut rtrb::Producer<AudioEvent>>,
|
||||
mut event_tx: Option<&mut rtrb::Producer<AudioEvent>>,
|
||||
) -> Result<(), String>
|
||||
{
|
||||
// Route to appropriate export implementation based on format
|
||||
match settings.format {
|
||||
// Reset all node graphs to clear stale effect buffers (echo, reverb, etc.)
|
||||
project.reset_all_graphs();
|
||||
|
||||
// Enable blocking mode on all read-ahead buffers so compressed audio
|
||||
// streams block until decoded frames are available (instead of returning
|
||||
// silence when the disk reader hasn't caught up with offline rendering).
|
||||
project.set_export_mode(true);
|
||||
|
||||
// Route to appropriate export implementation based on format.
|
||||
// Ensure export mode is disabled even if an error occurs.
|
||||
let result = match settings.format {
|
||||
ExportFormat::Wav | ExportFormat::Flac => {
|
||||
// Render to memory then write (existing path)
|
||||
let samples = render_to_memory(project, pool, midi_pool, settings, event_tx)?;
|
||||
let samples = render_to_memory(project, pool, midi_pool, settings, event_tx.as_mut().map(|tx| &mut **tx))?;
|
||||
// Signal that rendering is done and we're now writing the file
|
||||
if let Some(ref mut tx) = event_tx {
|
||||
let _ = tx.push(AudioEvent::ExportFinalizing);
|
||||
}
|
||||
match settings.format {
|
||||
ExportFormat::Wav => write_wav(&samples, settings, output_path)?,
|
||||
ExportFormat::Flac => write_flac(&samples, settings, output_path)?,
|
||||
ExportFormat::Wav => write_wav(&samples, settings, &output_path),
|
||||
ExportFormat::Flac => write_flac(&samples, settings, &output_path),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
ExportFormat::Mp3 => {
|
||||
export_mp3(project, pool, midi_pool, settings, output_path, event_tx)?;
|
||||
export_mp3(project, pool, midi_pool, settings, output_path, event_tx)
|
||||
}
|
||||
ExportFormat::Aac => {
|
||||
export_aac(project, pool, midi_pool, settings, output_path, event_tx)?;
|
||||
export_aac(project, pool, midi_pool, settings, output_path, event_tx)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(())
|
||||
// Always disable export mode, even on error
|
||||
project.set_export_mode(false);
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Render the project to memory
|
||||
@@ -437,6 +452,11 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
)?;
|
||||
}
|
||||
|
||||
// Signal that rendering is done and we're now flushing/finalizing
|
||||
if let Some(ref mut tx) = event_tx {
|
||||
let _ = tx.push(AudioEvent::ExportFinalizing);
|
||||
}
|
||||
|
||||
// Flush encoder
|
||||
encoder.send_eof()
|
||||
.map_err(|e| format!("Failed to send EOF: {}", e))?;
|
||||
@@ -602,6 +622,11 @@ fn export_aac<P: AsRef<Path>>(
|
||||
)?;
|
||||
}
|
||||
|
||||
// Signal that rendering is done and we're now flushing/finalizing
|
||||
if let Some(ref mut tx) = event_tx {
|
||||
let _ = tx.push(AudioEvent::ExportFinalizing);
|
||||
}
|
||||
|
||||
// Flush encoder
|
||||
encoder.send_eof()
|
||||
.map_err(|e| format!("Failed to send EOF: {}", e))?;
|
||||
|
||||
@@ -161,6 +161,17 @@ impl AudioGraph {
|
||||
// Validate the connection
|
||||
self.validate_connection(from, from_port, to, to_port)?;
|
||||
|
||||
// Remove any existing connection to the same input port (replace semantics).
|
||||
// The frontend UI enforces single-connection inputs, so when a new connection
|
||||
// targets the same port, the old one should be replaced.
|
||||
let edges_to_remove: Vec<_> = self.graph.edges_directed(to, petgraph::Direction::Incoming)
|
||||
.filter(|e| e.weight().to_port == to_port)
|
||||
.map(|e| e.id())
|
||||
.collect();
|
||||
for edge_id in edges_to_remove {
|
||||
self.graph.remove_edge(edge_id);
|
||||
}
|
||||
|
||||
// Add the edge
|
||||
self.graph.add_edge(from, to, Connection { from_port, to_port });
|
||||
self.topo_cache = None;
|
||||
|
||||
@@ -95,6 +95,8 @@ 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>,
|
||||
/// Original compressed file bytes (preserved across save/load to avoid re-encoding)
|
||||
pub original_bytes: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl AudioFile {
|
||||
@@ -108,6 +110,7 @@ impl AudioFile {
|
||||
sample_rate,
|
||||
frames,
|
||||
original_format: None,
|
||||
original_bytes: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,6 +124,7 @@ impl AudioFile {
|
||||
sample_rate,
|
||||
frames,
|
||||
original_format,
|
||||
original_bytes: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,6 +156,7 @@ impl AudioFile {
|
||||
sample_rate,
|
||||
frames: total_frames,
|
||||
original_format: Some("wav".to_string()),
|
||||
original_bytes: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,6 +179,7 @@ impl AudioFile {
|
||||
sample_rate,
|
||||
frames: total_frames,
|
||||
original_format,
|
||||
original_bytes: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -470,6 +476,31 @@ impl AudioClipPool {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// In export mode, block-wait until the disk reader has filled the
|
||||
// frames we need, so offline rendering never gets buffer misses.
|
||||
if use_read_ahead {
|
||||
let ra = read_ahead.unwrap();
|
||||
if ra.is_export_mode() {
|
||||
let src_start = (start_time_seconds * audio_file.sample_rate as f64) as u64;
|
||||
// Tell the disk reader where we need data BEFORE waiting
|
||||
ra.set_target_frame(src_start);
|
||||
// Pad by 64 frames for sinc interpolation taps
|
||||
let frames_needed = (output.len() / engine_channels as usize) as u64 + 64;
|
||||
// Spin-wait with small sleeps until the disk reader fills the buffer
|
||||
let mut wait_iters = 0u64;
|
||||
while !ra.has_range(src_start, frames_needed) {
|
||||
std::thread::sleep(std::time::Duration::from_micros(100));
|
||||
wait_iters += 1;
|
||||
if wait_iters > 100_000 {
|
||||
// Safety valve: 10 seconds of waiting
|
||||
eprintln!("[EXPORT] Timed out waiting for disk reader (need frames {}..{})",
|
||||
src_start, src_start + frames_needed);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Snapshot the read-ahead buffer range once for the entire render call.
|
||||
// This ensures all sinc interpolation taps within a single callback
|
||||
// see a consistent range, preventing crackle from concurrent updates.
|
||||
@@ -834,6 +865,15 @@ impl AudioClipPool {
|
||||
|| fmt_lower == "m4a" || fmt_lower == "opus"
|
||||
});
|
||||
|
||||
// Check for preserved original bytes first (from previous load cycle)
|
||||
if let Some(ref original_bytes) = audio_file.original_bytes {
|
||||
let data_base64 = general_purpose::STANDARD.encode(original_bytes);
|
||||
return EmbeddedAudioData {
|
||||
data_base64,
|
||||
format: audio_file.original_format.clone().unwrap_or_else(|| "wav".to_string()),
|
||||
};
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -1012,9 +1052,12 @@ impl AudioClipPool {
|
||||
// Clean up temporary file
|
||||
let _ = std::fs::remove_file(&temp_path);
|
||||
|
||||
// Update the path to reflect it was embedded
|
||||
// Update the path to reflect it was embedded, and preserve original bytes
|
||||
if result.is_ok() && pool_index < self.files.len() {
|
||||
self.files[pool_index].path = PathBuf::from(format!("<embedded: {}>", name));
|
||||
// Preserve the original compressed/encoded bytes so re-save doesn't need to re-encode
|
||||
self.files[pool_index].original_bytes = Some(data);
|
||||
self.files[pool_index].original_format = Some(embedded.format.clone());
|
||||
}
|
||||
|
||||
eprintln!("📊 [POOL] ✅ Total load_from_embedded time: {:.2}ms", fn_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
@@ -506,6 +506,21 @@ impl Project {
|
||||
}
|
||||
}
|
||||
|
||||
/// Set export (blocking) mode on all clip read-ahead buffers.
|
||||
/// When enabled, `render_from_file` blocks until the disk reader
|
||||
/// has filled the needed frames instead of returning silence.
|
||||
pub fn set_export_mode(&self, export: bool) {
|
||||
for track in self.tracks.values() {
|
||||
if let TrackNode::Audio(t) = track {
|
||||
for clip in &t.clips {
|
||||
if let Some(ref ra) = clip.read_ahead {
|
||||
ra.set_export_mode(export);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset all node graphs (clears effect buffers on seek)
|
||||
pub fn reset_all_graphs(&mut self) {
|
||||
for track in self.tracks.values_mut() {
|
||||
|
||||
@@ -148,6 +148,8 @@ pub enum Command {
|
||||
GraphDisconnect(TrackId, u32, usize, u32, usize),
|
||||
/// Set a parameter on a node (track_id, node_index, param_id, value)
|
||||
GraphSetParameter(TrackId, u32, u32, f32),
|
||||
/// Set the UI position of a node (track_id, node_index, x, y)
|
||||
GraphSetNodePosition(TrackId, u32, f32, f32),
|
||||
/// Set which node receives MIDI events (track_id, node_index, enabled)
|
||||
GraphSetMidiTarget(TrackId, u32, bool),
|
||||
/// Set which node is the audio output (track_id, node_index)
|
||||
@@ -250,6 +252,8 @@ pub enum AudioEvent {
|
||||
frames_rendered: usize,
|
||||
total_frames: usize,
|
||||
},
|
||||
/// Export rendering complete, now writing/encoding the output file
|
||||
ExportFinalizing,
|
||||
/// Waveform generated for audio pool file (pool_index, waveform)
|
||||
WaveformGenerated(usize, Vec<WaveformPeak>),
|
||||
|
||||
|
||||
Reference in New Issue
Block a user