Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

SG4a: the bounce spills to a scratch file as the frames come

shinyobjectz4797b5ca61c1
diff --git a/Cargo.lock b/Cargo.lock
index 742e4935..6f6b2f1b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16250,6 +16250,7 @@ dependencies = [
"audioadapter-buffers",
"cpal 0.15.3",
"firewheel",
+ "raea-io-home",
"raea-io-media",
"raea-io-trace",
"raea-sys-mix-level",
diff --git a/docs/stage-guards.feature b/docs/stage-guards.feature
index 70e95f23..651a3686 100644
--- a/docs/stage-guards.feature
+++ b/docs/stage-guards.feature
@@ -157,6 +157,7 @@ Feature: Stage guards: a 3D render an agent can't break
# Status 11-21 (branch stage-guards-4): built ("frame N: Could not despawn entity: the text part 'quote' had
# already gone, despawned with another part it hung from"); the store test covers it.
+ @done
Scenario: SG4a. A long render's memory stays flat
Given the plan
| crate | file | lines | job |
@@ -206,6 +207,8 @@ Feature: Stage guards: a 3D render an agent can't break
| raea-runtime-endchecks | runtime/endchecks/src/lib.rs | +55 | EndChecks: the clipping check, the staging and the parts on screen fed each frame's parts as it's drawn |
| raea-runtime-export | runtime/export/src/fed.rs | +3 | a live render's frames go to EndChecks as they're drawn |
| raea-runtime-export | runtime/export/src/scene.rs | 0 | a still's frames go to EndChecks one at a time, its parts made and let go (3 lines shorter) |
+ | raea-sys-mix | systems/mix/src/offline.rs | +23 | Streamer: each frame's samples to a scratch file as they come, read back once after the last (13 KB a frame held before) |
+ | raea-runtime-export | runtime/export/src/fed.rs | +1 | a render with nothing to hear lets its bounce go unread |
Then a 13,000-frame 3D render's memory stays within 10% of its first minute's
# Status 11-21 (branch stage-guards-8): the film (13,175 frames, 7:19) renders whole with every end check on, at
# a 9.4 to 13.6 GB peak. Before, memguard killed it past 24 GB (28 to 33 GB) after its last frame. Four causes,
@@ -294,6 +297,14 @@ Feature: Stage guards: a 3D render an agent can't break
# GB before). Still not met: the frames grow. The control's 1.06 GB at frame 1,000 is 1.32 GB at 13,000 (+25%;
# +20% over frame 2,000), as before; the film's frames now carry the clipping check's solids for the parts on
# screen, 2.31 GB at frame 1,000 and 2.91 GB at 13,000 (+26%), 4.13 GB in its densest minute (frame 5,000).
+ # Most of the control's growth was the bounce: its streamer reserved both channels for the whole render and
+ # filled them a frame at a time (12.8 KB a frame, Malloc Large's resident pages climbing at a constant size). Its
+ # samples now go to a scratch file as they come, read back once after the last frame, and not at all when
+ # nothing sounded. The streamer alone, pushed the control's 13,200 silent frames: 26.8 MB at frame 1,800 and 167
+ # MB at 13,199 before, 4.8 MB and 5.8 MB after. Met, on the release build of the whole stack (11-22): the
+ # control's 1,064.5 MB at its first minute (frame 1,800) is 1,151.4 MB at frame 13,000, +8.2% (it was +20%), and
+ # 1,148.2 MB after the end checks; marked every 200 frames, it rises 7.9 KB a frame, about 3 KB of it each frame's
+ # manifest entry kept as JSON values, which is what to move next for more room under the bar.
Rule: The SDK stops allowing it
diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rs
index ee6f179f..287e32d0 100644
--- a/runtime/export/src/fed.rs
+++ b/runtime/export/src/fed.rs
@@ -219,7 +219,7 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
let notes: std::cell::RefCell<Vec<raea_sys_mix::ToneCue>> = std::cell::RefCell::new(Vec::new());
let dir = cx.dir.to_path_buf();
// the sound bounced as the frames come, on its own thread (it was mixed after the last frame: 3 s on the export)
- let streamer = std::cell::RefCell::new(Some(raea_sys_mix::offline::Streamer::start(fps, total.max(0) as usize)));
+ let streamer = std::cell::RefCell::new(Some(raea_sys_mix::offline::Streamer::start(fps)));
// a video's 3D made live is checked as its frames come, each frame's parts let go once read (SG4a)
let ends = std::cell::RefCell::new(LIVE_CLIPS.load(std::sync::atomic::Ordering::Relaxed).then(|| raea_runtime_endchecks::EndChecks::new(w, h, fps)));
let t0 = std::time::Instant::now();
@@ -309,14 +309,15 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
let p = program_of(&frames.borrow(), w, h, fps, false);
sound_lint(&p, fps);
let st = streamer.borrow_mut().take().ok_or("the sound was asked for twice")?;
- let t_bounce = std::time::Instant::now();
- let raw = st.finish()?;
- let bounce_ms = t_bounce.elapsed().as_secs_f64() * 1e3;
- let t_master = std::time::Instant::now();
if frames.borrow().iter().all(|(_, f)| f.sounds.is_empty()) && notes.borrow().iter().all(|n| n.is_empty()) {
+ st.discard()?;
no_sound_but_declared(js)?;
return Ok(None);
}
+ let t_bounce = std::time::Instant::now();
+ let raw = st.finish()?;
+ let bounce_ms = t_bounce.elapsed().as_secs_f64() * 1e3;
+ let t_master = std::time::Instant::now();
let (master, a) = core_master_raw(&raw, frames.borrow().iter().find_map(|(_, f)| f.mix))?;
if let Some(p) = std::env::var_os("RAEA_AUDIO_BOUNCE") {
raea_sys_mix::write_wav(&a, Path::new(&p))?;
diff --git a/systems/mix/Cargo.toml b/systems/mix/Cargo.toml
index 63c25ca5..cd498069 100644
--- a/systems/mix/Cargo.toml
+++ b/systems/mix/Cargo.toml
@@ -10,6 +10,8 @@ description = "raea's one mixer core: the same Firewheel graph plays live in the
# the mix before the master: dialogue at one level, room tone at the joins
raea-sys-mix-level = { path = "level" }
raea-io-trace = { path = "../../io/trace" }
+# the bounce's scratch file, as the frames come (SG4a)
+raea-io-home = { path = "../../io/home" }
# the audio graph: sample-accurate scheduled events, custom nodes, a CPAL stream live and a processor pulled by hand
# offline. 0.12 because bevy_seedling 0.8 pins it: one Firewheel for raea and Bevy. On Bevy 0.20 both are vendored and
# ported (vendor/firewheel*, vendor/bevy_seedling) until their releases catch up.
diff --git a/systems/mix/src/offline.rs b/systems/mix/src/offline.rs
index 27079a6b..11873adf 100644
--- a/systems/mix/src/offline.rs
+++ b/systems/mix/src/offline.rs
@@ -159,7 +159,7 @@ pub fn bounce(frames: &[Cue], fps: f64, master: Option<(f64, f64)>) -> Result<ra
/// master is then `master_raw` over it, the same limiter the live master node runs, sample for sample: one bounce, and
/// mastering (or mastering again for AAC) is a pass over a buffer.
pub fn bounce_raw(frames: &[Cue], fps: f64) -> Result<raea_io_media::Audio, String> {
- let s = Streamer::start(fps, frames.len());
+ let s = Streamer::start(fps);
for c in frames {
s.push(c.clone());
}
@@ -233,38 +233,37 @@ fn mastered(raw: &raea_io_media::Audio, mix: Option<(f64, f64)>, encode: Encode)
}
/// A raw bounce made as the frames come (a render streams each frame's cue while it draws the frames), on its own
-/// thread: the sound is ready when the last frame is.
+/// thread: the sound is ready when the last frame is. Each frame's samples go to a scratch file (stereo f32, interleaved;
+/// `done` gives it and its length) as they come, so a long render doesn't hold its sound (13 KB a frame, SG4a).
pub struct Streamer {
tx: std::sync::mpsc::Sender<Cue>,
- done: std::thread::JoinHandle<Result<raea_io_media::Audio, String>>,
+ done: std::thread::JoinHandle<Result<(std::fs::File, usize), String>>,
}
impl Streamer {
- /// A bounce of `frames` frames at `fps` (the count sizes its buffers once; more frames than that still come out).
- pub fn start(fps: f64, frames: usize) -> Streamer {
+ /// A bounce at `fps`, of as many frames as are pushed.
+ pub fn start(fps: f64) -> Streamer {
let (tx, rx) = std::sync::mpsc::channel::<Cue>();
let done = std::thread::Builder::new()
.name("raea mixer bounce".into())
- .spawn(move || -> Result<raea_io_media::Audio, String> {
+ .spawn(move || -> Result<(std::fs::File, usize), String> {
let mut e = Engine::new(fps, None)?;
e.cx.queue_event_for(e.master, event(crate::nodes::Master { pre: 1.0, ceiling: 1.0, bypass: true }));
e.cx.update().map_err(|x| format!("{x:?}"))?;
- // each channel filled as the frames come, from one frame's interleaved samples at a time: an
- // interleaved copy of the whole sound split at the end held it twice (340 MB on a 7-minute film, SG4a)
- let size = e.score.t(frames as i64).max(0) as usize;
- let (mut l, mut r, mut buf) = (Vec::with_capacity(size), Vec::with_capacity(size), Vec::new());
- let mut f = 0i64;
+ let mut out = std::io::BufWriter::new(raea_io_home::scratch_file("bounce")?);
+ let (mut len, mut buf, mut bytes, mut f) = (0usize, Vec::new(), Vec::new(), 0i64);
for cue in rx {
e.feed(f, &cue, 0)?;
- let n = (e.score.t(f + 1).max(0) as usize).saturating_sub(l.len());
+ let n = (e.score.t(f + 1).max(0) as usize).saturating_sub(len);
buf.clear();
buf.resize(n * 2, 0.0);
e.pull(&mut buf)?;
- l.extend(buf.iter().step_by(2));
- r.extend(buf.iter().skip(1).step_by(2));
- f += 1;
+ bytes.clear();
+ bytes.extend(buf.iter().flat_map(|s: &f32| s.to_le_bytes()));
+ std::io::Write::write_all(&mut out, &bytes).map_err(scratch)?;
+ (len, f) = (len + n, f + 1);
}
- Ok(raea_io_media::Audio { rate: RATE, channels: vec![l, r] })
+ Ok((out.into_inner().map_err(|x| scratch(x.into_error()))?, len))
})
.expect("bounce thread");
Streamer { tx, done }
@@ -275,13 +274,37 @@ impl Streamer {
let _ = self.tx.send(cue);
}
- /// The raw bounce of every frame pushed.
+ /// The raw bounce of every frame pushed, read back from its scratch file.
pub fn finish(self) -> Result<raea_io_media::Audio, String> {
+ let (file, len) = self.wait()?;
+ let mut read = std::io::BufReader::new(file);
+ std::io::Seek::rewind(&mut read).map_err(scratch)?;
+ let (mut l, mut r, mut two) = (Vec::with_capacity(len), Vec::with_capacity(len), [0u8; 8]);
+ for _ in 0..len {
+ std::io::Read::read_exact(&mut read, &mut two).map_err(scratch)?;
+ l.push(f32::from_le_bytes([two[0], two[1], two[2], two[3]]));
+ r.push(f32::from_le_bytes([two[4], two[5], two[6], two[7]]));
+ }
+ Ok(raea_io_media::Audio { rate: RATE, channels: vec![l, r] })
+ }
+
+ /// The bounce let go unread: nothing sounded.
+ pub fn discard(self) -> Result<(), String> {
+ self.wait().map(drop)
+ }
+
+ fn wait(self) -> Result<(std::fs::File, usize), String> {
drop(self.tx);
self.done.join().map_err(|_| "the bounce thread panicked".to_string())?
}
}
+/// A failure writing or reading the bounce's scratch file, a full disk said as one.
+fn scratch(x: std::io::Error) -> String {
+ let full = x.kind() == std::io::ErrorKind::StorageFull;
+ format!("the bounce's scratch file: {}{x}", if full { "the disk is full, free some room and render again: " } else { "" })
+}
+
#[cfg(test)]
mod tests {
use super::*;