From 4f6568e319e14e1a9ec6864da8b03922c7c780ef Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 05:26:11 +0000 Subject: [PATCH] Offline bounce: read seekable clips at random access, not through the real-time rings --- src/track/clip_render.rs | 50 ++++++++- src/track/mod.rs | 4 + src/track/process.rs | 1 + src/track/seekable_streaming.rs | 40 ++++++++ src/workers/worker.rs | 176 ++++++++++++++++++++++++-------- 5 files changed, 224 insertions(+), 47 deletions(-) diff --git a/src/track/clip_render.rs b/src/track/clip_render.rs index bb69cec..72b8c95 100644 --- a/src/track/clip_render.rs +++ b/src/track/clip_render.rs @@ -96,6 +96,41 @@ fn clip_sample_window( } impl TrackData { + /// Offline renders of seekable (engine-rate PCM) clips only: fill + /// `clip_render_stream_scratch` with exactly `len` frames from + /// `source_from` by a blocking random-access read (`clip_sample_window`), + /// instead of popping the real-time rings, which silence-fill whenever the + /// producer thread falls behind. + fn read_clip_window_offline( + &mut self, + buffer: &AudioClipBuffer, + source_from: usize, + len: usize, + channels: usize, + ) { + let mut window = std::mem::take(&mut self.rt.clip_window_scratch); + let mut bytes = std::mem::take(&mut self.rt.clip_window_bytes); + let mut interleaved = std::mem::take(&mut self.rt.clip_window_interleaved); + let read = clip_sample_window( + buffer, + source_from, + len, + &mut window, + &mut bytes, + &mut interleaved, + ); + self.rt.clip_window_bytes = bytes; + self.rt.clip_window_interleaved = interleaved; + let blocks = &mut self.rt.clip_render_stream_scratch; + reset_channel_buffers(blocks, channels, len); + if read.is_some() { + for (dst, src) in blocks.iter_mut().zip(&window) { + dst.copy_from_slice(&src[..len]); + } + } + self.rt.clip_window_scratch = window; + } + /// Decoding strategy for an audio clip file. #[cfg(feature = "audio")] pub(crate) fn choose_clip_strategy( @@ -1088,6 +1123,9 @@ impl TrackData { let input_count = self.audio.ins.len().max(1); let local_start = absolute_from.saturating_sub(clip_start); let source_from = clip.offset.saturating_add(local_start); + // Offline renders keep the rings here: a random-access read of + // a compressed file re-decodes it from the start on every call + // and returns frames at the file's own rate, not the engine's. let stream_blocks = &mut self.rt.clip_render_stream_scratch; reset_channel_buffers(stream_blocks, clip_channels, request_len); stream.read_frames(source_from, request_len, stream_blocks); @@ -1108,9 +1146,17 @@ impl TrackData { let input_count = self.audio.ins.len().max(1); let local_start = absolute_from.saturating_sub(clip_start); let source_from = clip.offset.saturating_add(local_start); + if self + .offline_random_access + .load(std::sync::atomic::Ordering::Relaxed) + { + self.read_clip_window_offline(&buffer, source_from, request_len, clip_channels); + } else { + let stream_blocks = &mut self.rt.clip_render_stream_scratch; + reset_channel_buffers(stream_blocks, clip_channels, request_len); + stream.read_frames(source_from, request_len, stream_blocks); + } let stream_blocks = &mut self.rt.clip_render_stream_scratch; - reset_channel_buffers(stream_blocks, clip_channels, request_len); - stream.read_frames(source_from, request_len, stream_blocks); reset_channel_buffers(out, input_count, request_len); for (in_channel, block) in out.iter_mut().enumerate() { let source_channel = if clip_channels == 1 { diff --git a/src/track/mod.rs b/src/track/mod.rs index 9e0d814..bd4b502 100644 --- a/src/track/mod.rs +++ b/src/track/mod.rs @@ -997,6 +997,10 @@ pub struct TrackData { pub phase_inverted: AtomicBool, pub soloed: AtomicBool, pub is_master: AtomicBool, + /// Set by the offline bounce worker: read seekable (engine-rate PCM) clips + /// by random access (blocking disk read) instead of the real-time rings, + /// so a bounce never silence-fills on a producer underrun. + pub offline_random_access: AtomicBool, input_monitor: ArcSwap>, disk_monitor: ArcSwap>, midi_input_monitor: ArcSwap>, diff --git a/src/track/process.rs b/src/track/process.rs index 4fdf165..8fcb2b4 100644 --- a/src/track/process.rs +++ b/src/track/process.rs @@ -40,6 +40,7 @@ impl TrackData { phase_inverted: AtomicBool::new(false), soloed: AtomicBool::new(false), is_master: AtomicBool::new(false), + offline_random_access: AtomicBool::new(false), input_monitor: ArcSwap::from_pointee(vec![false; io.audio_ins]), disk_monitor: ArcSwap::from_pointee(vec![true; io.audio_ins]), midi_input_monitor: ArcSwap::from_pointee(vec![false; io.midi_ins]), diff --git a/src/track/seekable_streaming.rs b/src/track/seekable_streaming.rs index aa7cd4c..2101c30 100644 --- a/src/track/seekable_streaming.rs +++ b/src/track/seekable_streaming.rs @@ -773,6 +773,46 @@ mod tests { ); } + #[test] + #[cfg_attr(miri, ignore = "Miri isolation does not support filesystem open")] + fn offline_random_access_is_exact_from_the_first_block_at_a_clip_offset() { + use crate::track::Track; + + let (path, source) = tone_wav("maolan_seekstream_offline", 48_000, 1.0, 440.0); + let mut track = Track::new("t".to_string(), 2, 2, 0, 0, 256, 48_000.0); + track.set_input_monitor(vec![false; 2]); + track.set_disk_monitor(vec![true; 2]); + let mut clip = crate::audio::clip::AudioClip::new( + path.to_string_lossy().into_owned(), + 0, + 48_000 * 240, + ); + clip.id = "clip-1".to_string(); + clip.fade_enabled = false; + clip.offset = 1_000; + track.audio.push_clip(clip); + track + .offline_random_access + .store(true, std::sync::atomic::Ordering::Relaxed); + + // No waiting for the producer thread: an offline render must read + // exactly the requested frames, starting at the clip offset, on the + // very first block, where the real-time rings would still be priming. + for cycle in 0..4 { + track.rt.transport_sample = cycle * 256; + track.process(); + let out = track.last_audio_outputs(); + let expected = &source[1_000 + cycle * 256..1_000 + (cycle + 1) * 256]; + for (&actual, &want) in out[0].iter().zip(expected) { + assert!( + (actual - want).abs() < 1.0e-6, + "block {cycle} is not frame-exact at the clip offset" + ); + } + } + std::fs::remove_file(&path).expect("remove temporary test file"); + } + #[test] #[cfg_attr(miri, ignore = "Miri isolation does not support filesystem open")] fn seekable_stream_wakes_after_full_ring_is_consumed() { diff --git a/src/workers/worker.rs b/src/workers/worker.rs index 06e34d1..c2482d7 100644 --- a/src/workers/worker.rs +++ b/src/workers/worker.rs @@ -15,6 +15,32 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::sync::mpsc::{Receiver, Sender}; +/// Switches the tracks an offline render reads to random-access clip reads +/// for as long as it lives, and back to the real-time streaming rings when +/// dropped, whichever way the render ends (finished, canceled or failed). +struct OfflineClipReads<'a>(&'a [TrackHandle]); + +impl<'a> OfflineClipReads<'a> { + fn new(tracks: &'a [TrackHandle]) -> Self { + for track in tracks { + track + .offline_random_access + .store(true, std::sync::atomic::Ordering::Relaxed); + } + Self(tracks) + } +} + +impl Drop for OfflineClipReads<'_> { + fn drop(&mut self) { + for track in self.0 { + track + .offline_random_access + .store(false, std::sync::atomic::Ordering::Relaxed); + } + } +} + pub(crate) struct NodeJobResult { pub(crate) worker_id: usize, pub(crate) epoch: u64, @@ -285,7 +311,29 @@ impl Worker { track.set_balance(original_balance); } + /// Run an offline bounce, then return the worker to the pool. `Ready` is + /// sent only after the render has returned, so everything it held (the + /// tracks' random-access clip reads in particular) is released before the + /// engine can start a queued render on another worker. async fn process_offline_bounce(&self, job: OfflineBounceWork) { + self.render_offline_bounce(job).await; + self.return_to_pool().await; + } + + /// Like `process_offline_bounce`, for a stems render. + async fn process_offline_stems_bounce(&self, job: OfflineStemsBounceWork) { + self.render_offline_stems_bounce(job).await; + self.return_to_pool().await; + } + + async fn return_to_pool(&self) { + crate::report_error( + self.tx.send(Message::Ready(self.id)).await, + "Failed to return offline bounce worker", + ); + } + + async fn render_offline_bounce(&self, job: OfflineBounceWork) { let track_handle = job.state.tracks.get(&job.track_name).cloned(); let Some(target_track) = track_handle else { crate::report_error( @@ -296,10 +344,6 @@ impl Worker { .await, "Failed to report missing offline bounce track", ); - crate::report_error( - self.tx.send(Message::Ready(self.id)).await, - "Failed to return offline bounce worker", - ); return; }; let (channels, block_size, sample_rate) = { @@ -354,6 +398,7 @@ impl Worker { selected_tracks = render_tracks.len(), "Selected offline render dependencies" ); + let _clip_reads = OfflineClipReads::new(&render_tracks); let offline_render = crate::offline_render::OfflineRender::new(&render_plan, &render_nodes); let render_plan = Arc::new(basedrop::Owned::new(&plan_collector.handle(), render_plan)); @@ -388,10 +433,6 @@ impl Worker { .await, "Failed to report canceled offline bounce", ); - crate::report_error( - self.tx.send(Message::Ready(self.id)).await, - "Failed to return offline bounce worker", - ); return; } @@ -481,10 +522,6 @@ impl Worker { .await, "Failed to report offline bounce write error", ); - crate::report_error( - self.tx.send(Message::Ready(self.id)).await, - "Failed to return offline bounce worker", - ); return; } @@ -508,17 +545,13 @@ impl Worker { .await, "Failed to report completed offline bounce", ); - crate::report_error( - self.tx.send(Message::Ready(self.id)).await, - "Failed to return offline bounce worker", - ); } /// Render several tracks' outputs in a single offline pass, capturing /// every stem per block the way realtime playback renders all tracks at /// once. Each stem streams 32-bit float WAV to its own file, so memory /// stays bounded by one block per stem regardless of session length. - async fn process_offline_stems_bounce(&self, job: OfflineStemsBounceWork) { + async fn render_offline_stems_bounce(&self, job: OfflineStemsBounceWork) { // Resolve every target before creating files so a bad name fails // the whole job without leaving partial output behind. let mut targets: Vec<(&OfflineBounceStem, TrackHandle, usize, u32)> = @@ -533,10 +566,6 @@ impl Worker { .await, "Failed to report missing offline stems bounce track", ); - crate::report_error( - self.tx.send(Message::Ready(self.id)).await, - "Failed to return offline bounce worker", - ); return; }; let (channels, engine_rate) = { @@ -557,10 +586,6 @@ impl Worker { .await, "Failed to report empty offline stems bounce", ); - crate::report_error( - self.tx.send(Message::Ready(self.id)).await, - "Failed to return offline bounce worker", - ); return; } let block_size = targets @@ -637,10 +662,6 @@ impl Worker { .await, "Failed to report offline stems bounce create error", ); - crate::report_error( - self.tx.send(Message::Ready(self.id)).await, - "Failed to return offline bounce worker", - ); return; } } @@ -688,6 +709,7 @@ impl Worker { selected_tracks = render_tracks.len(), "Selected offline stems render dependencies" ); + let _clip_reads = OfflineClipReads::new(&render_tracks); let offline_render = crate::offline_render::OfflineRender::new(&render_plan, &render_nodes); let render_plan = Arc::new(basedrop::Owned::new(&plan_collector.handle(), render_plan)); @@ -760,10 +782,6 @@ impl Worker { .await, "Failed to report canceled offline stems bounce", ); - crate::report_error( - self.tx.send(Message::Ready(self.id)).await, - "Failed to return offline bounce worker", - ); return; } @@ -868,10 +886,6 @@ impl Worker { .await, "Failed to report offline stems bounce write error", ); - crate::report_error( - self.tx.send(Message::Ready(self.id)).await, - "Failed to return offline bounce worker", - ); return; } @@ -968,10 +982,6 @@ impl Worker { .await, "Failed to report offline stems bounce finalize error", ); - crate::report_error( - self.tx.send(Message::Ready(self.id)).await, - "Failed to return offline bounce worker", - ); return; } restore(&restore_faders); @@ -984,10 +994,6 @@ impl Worker { .await, "Failed to report completed offline stems bounce", ); - crate::report_error( - self.tx.send(Message::Ready(self.id)).await, - "Failed to return offline bounce worker", - ); } #[cfg(all(unix, not(miri)))] @@ -1792,6 +1798,12 @@ mod tests { let track = state_guard.tracks.get("track").expect("track").lock(); assert_eq!(track.level(), -9.0); assert_eq!(track.balance(), -0.3); + assert!( + !track + .offline_random_access + .load(std::sync::atomic::Ordering::Relaxed), + "a canceled bounce must hand the track back to real-time clip reads" + ); } #[cfg_attr( @@ -1865,6 +1877,74 @@ mod tests { assert_eq!(track.balance(), 0.25); } + #[cfg(feature = "audio")] + #[cfg_attr( + all(miri, any(target_os = "freebsd", target_os = "macos")), + ignore = "Tokio runtime uses kqueue, which Miri does not support on FreeBSD or macOS" + )] + #[cfg_attr( + all(miri, target_os = "windows"), + ignore = "Tokio runtime uses Windows IOCP, which Miri does not support" + )] + #[cfg_attr( + all( + miri, + not(any(target_os = "freebsd", target_os = "windows", target_os = "macos")) + ), + ignore = "Offline bounce test uses statx and unlink, which Miri isolation does not support" + )] + #[tokio::test] + async fn offline_render_releases_clip_reads_before_the_worker_is_returned() { + // The engine starts a queued render as soon as it sees `Ready`, maybe + // on another worker and over the same tracks, so the render must have + // handed its tracks back to real-time clip reads before `Ready` goes + // out: the render itself never sends it. + let (_rx_unused_tx, rx_unused) = channel(1); + let (tx, mut out_rx) = channel(16); + let worker = Worker { + id: 9, + rx: rx_unused, + tx, + realtime_priority: 0, + }; + let state = make_state_with_track(Track::new("track".to_string(), 1, 1, 0, 0, 4, 48_000.0)); + let output = unique_temp_wav("ready_boundary"); + let job = OfflineBounceWork { + state: Arc::new(state.lock().snapshot()), + track_name: "track".to_string(), + output_path: output.to_string_lossy().to_string(), + start_sample: 0, + length_samples: 8, + tempo_bpm: 120.0, + tsig_num: 4, + tsig_denom: 4, + automation_lanes: vec![], + cancel: Arc::new(AtomicBool::new(false)), + apply_fader: false, + }; + + worker.render_offline_bounce(job).await; + while let Ok(message) = out_rx.try_recv() { + assert!( + !matches!(message, Message::Ready(_)), + "the render returned the worker itself" + ); + } + assert!( + !state + .lock() + .tracks + .get("track") + .expect("track") + .offline_random_access + .load(std::sync::atomic::Ordering::Relaxed), + "clip reads still random-access when the worker would be returned" + ); + worker.return_to_pool().await; + assert!(matches!(out_rx.try_recv(), Ok(Message::Ready(9)))); + std::fs::remove_file(&output).expect("remove temp wav"); + } + #[cfg(feature = "audio")] #[cfg_attr( all(miri, any(target_os = "freebsd", target_os = "macos")), @@ -1959,6 +2039,12 @@ mod tests { assert_eq!(track.level(), -3.0); assert_eq!(track.balance(), 0.4); assert!(!track.muted()); + assert!( + !track + .offline_random_access + .load(std::sync::atomic::Ordering::Relaxed), + "a finished bounce must hand the track back to real-time clip reads" + ); } /// Read the interleaved f32 payload of a float WAV written by