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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
SG4a: a live render's parts kept on disk, the MP4 writer's samples on disk, the master's true peak and loudness a block at a time, shapes in 16 MB generations
shinyobjectz4202a8785043
diff --git a/Cargo.lock b/Cargo.lockindex 67a7d7d5..867a050f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14605,6 +14605,17 @@ dependencies = ["url",]+[[package]]+name = "raea-io-kept"+version = "0.1.0"+dependencies = [+ "bevy",+ "raea-core-scene",+ "raea-io-home",+ "serde",+ "serde_json",+]+[[package]]name = "raea-io-media"version = "0.1.0"@@ -15257,6 +15268,7 @@ dependencies = ["raea-gpu-device","raea-io-alpha","raea-io-assets",+ "raea-io-kept","raea-io-media","raea-io-net","raea-page",@@ -16185,6 +16197,7 @@ dependencies = ["cpal 0.15.3","firewheel","raea-io-media",+ "raea-io-trace","raea-sys-mix-level","raea-sys-tone","serde_json",diff --git a/Cargo.toml b/Cargo.tomlindex 14c46aa7..5f251cb5 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -60,6 +60,7 @@ members = ["engine/page/window","io/trace","io/codec",+ "io/kept","io/media","io/assets","io/clef",diff --git a/core/shape/src/lib.rs b/core/shape/src/lib.rsindex 9cd741d6..171220dd 100644--- a/core/shape/src/lib.rs+++ b/core/shape/src/lib.rs@@ -203,35 +203,55 @@ pub fn tris(m: &Manifold) -> Tris {/// A shape made faster than this isn't kept on disk: a box is made in microseconds, and a part whose size changed each/// frame wrote a file a frame (2.4 million in 12 hours of long renders, 11-21); the disk is for the cuts that costconst KEEP_MS: f64 = 2.0;-/// The bytes of triangles held in memory at most: past it they're let go and made (or read) again as asked, so a-/// long render's shapes that change each frame don't grow the process for its whole length (SG4a)-const HELD_BYTES: usize = 1 << 30;+/// The bytes of triangles one generation of held shapes takes: past it, the generation before is let go and this one+/// takes its place. A shape asked for again moves to the newest, so what a scene keeps asking for stays, and two+/// generations at most are held. A long render's shapes that change each frame (a bar that grows, 3D words that count)+/// are let go as it goes: held to 1 GB at once, a one-scene control grew by 100 MB in 4,000 frames (SG4a). Anything+/// let go is made again, or read from disk when it took KEEP_MS to make: a part asks for its shape when it's spawned,+/// and the end checks once more.+const GEN_BYTES: usize = 16 << 20;-/// The shapes held, and their bytes.-type Held = (HashMap<String, std::sync::Arc<Tris>>, usize);+/// The shapes held, the newest generation and the one before, and the newest's bytes.+#[derive(Default)]+struct Held {+ now: HashMap<String, std::sync::Arc<Tris>>,+ old: HashMap<String, std::sync::Arc<Tris>>,+ bytes: usize,+}-/// `t` held for `expr`, the held let go first when they'd pass HELD_BYTES.-fn hold(cache: &Mutex<Held>, expr: &str, t: &std::sync::Arc<Tris>) {- let bytes = (t.positions.len() + t.normals.len()) * 12 + expr.len();- let mut c = cache.lock().unwrap();- if c.1 + bytes > HELD_BYTES {- *c = Default::default();+impl Held {+ fn get(&mut self, expr: &str) -> Option<std::sync::Arc<Tris>> {+ if let Some(t) = self.now.get(expr) {+ return Some(t.clone());+ }+ let t = self.old.remove(expr)?;+ self.hold(expr, &t);+ Some(t)+ }++ /// `t` held for `expr` in the newest generation, which becomes the one before when it would pass GEN_BYTES.+ fn hold(&mut self, expr: &str, t: &std::sync::Arc<Tris>) {+ let bytes = (t.positions.len() + t.normals.len()) * 12 + expr.len();+ if self.bytes + bytes > GEN_BYTES && !self.now.is_empty() {+ self.old = std::mem::take(&mut self.now);+ self.bytes = 0;+ }+ self.bytes += bytes;+ self.now.insert(expr.to_string(), t.clone());}- c.1 += bytes;- c.0.insert(expr.to_string(), t.clone());}/// The mesh for an expression, built once per expression (a re-cut or a key that doesn't change the shape costs nothing).pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {static CACHE: OnceLock<Mutex<Held>> = OnceLock::new();let cache = CACHE.get_or_init(Default::default);- if let Some(t) = cache.lock().unwrap().0.get(expr) {- return Ok(t.clone());+ if let Some(t) = cache.lock().unwrap().get(expr) {+ return Ok(t);}// a buffer mesh's own triangles (buffer.rs): data already, so nothing is kept on disk for itif let Some(b) = expr.strip_prefix("buffer:") {let t = std::sync::Arc::new(buffer_tris(b)?.0);- hold(cache, expr, &t);+ cache.lock().unwrap().hold(expr, &t);return Ok(t);}// made by this build before, on disk (kept.rs): read back as it was written@@ -247,7 +267,7 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {t}};- hold(cache, expr, &t);+ cache.lock().unwrap().hold(expr, &t);Ok(t)}@@ -255,6 +275,20 @@ pub fn cached(expr: &str) -> Result<std::sync::Arc<Tris>, String> {mod tests {use super::*;+ #[test]+ fn held_shapes_go_a_generation_at_a_time_and_what_is_asked_again_stays() {+ let mut h = Held::default();+ // a shape of a quarter of a generation+ let t = std::sync::Arc::new(Tris { positions: vec![[0.0; 3]; GEN_BYTES / 96], normals: vec![[0.0; 3]; GEN_BYTES / 96] });+ h.hold("kept", &t);+ for i in 0..12 {+ h.hold(&format!("bar {i}"), &t);+ assert!(h.get("kept").is_some(), "asked each time, it stays (after bar {i})");+ }+ assert!(h.get("bar 0").is_none(), "made once and never asked again, it went");+ assert!(h.now.len() + h.old.len() <= 8, "two generations at most: {} + {}", h.now.len(), h.old.len());+ }+#[test]fn a_kept_mesh_reads_back_as_it_was_written() {let dir = std::env::temp_dir().join(format!("raea-shape-kept-{}", std::process::id()));diff --git a/docs/stage-guards.feature b/docs/stage-guards.featureindex d1661828..9783829d 100644--- a/docs/stage-guards.feature+++ b/docs/stage-guards.feature@@ -180,6 +180,19 @@ Feature: Stage guards: a 3D render an agent can't break| raea-sys-contact | systems/contact/src/lib.rs | 0 | the clipping check holds each part's solid over its frames only (Held), 3 lines shorter || raea-app-direction | apps/direction/src/pure.rs | +3 | frame purity's stills skip the clipping and staging checks it never reads || raea-runtime-export | runtime/export/src/scene.rs | +1 | a memory mark after what's on screen |+ | raea-io-kept | io/kept/src/lib.rs | +245 | Kept: a live render's parts on disk as its frames come, each props map, string and material once by its content, a part's own place left out but a camera's; read back for the end checks |+ | raea-runtime-export | runtime/export/src/fed.rs | +7 | a live render keeps its parts in Kept, not its scenes; a memory mark after its sound and video |+ | raea-runtime-export | runtime/export/src/scene.rs | +1 | the end checks over the kept parts as read back (checked, for fed.rs); the parts' count in the mark |+ | raea-core-shape | core/shape/src/lib.rs | +34 | Held: shapes in two generations of 16 MB, what's asked for again kept |+ | muxide | vendor/muxide/src/muxer/mp4.rs | +61 | Spill: the writer's samples in a temp file as they come, read back one at a time as the file is finished |+ | raea-io-codec | io/codec/src/resample.rs | +55 | soft_resample_blocks: the resampled sound a block at a time, the same bits |+ | raea-io-codec | io/codec/src/audio.rs | 0 | the true peak, its envelope and the loudness a block at a time, the same bits; the sound borrowed at 48 kHz (7 lines shorter) |+ | raea-io-codec | io/codec/src/audio/tests.rs | +117 | audio.rs's tests, and the block-at-a-time ones against the whole |+ | raea-sys-mix-level | systems/mix/level/src/joins.rs | +1 | filled: the sound itself when there's no gap, not a copy |+ | raea-sys-mix | systems/mix/src/offline.rs | +10 | master_mix hands back its passes' freed copies (give_back); Encode |+ | raea-io-trace | io/trace/src/lib.rs | +20 | give_back: the allocator's freed memory returned to the system now |+ | raea-io-home | io/home/src/lib.rs | +15 | scratch_file: a temp file gone when raea is (the encoder's samples, Kept's parts) |+ | raea-io-codec | io/codec/src/samples.rs | 0 | Samples' temp file from scratch_file (8 lines shorter) |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,@@ -235,6 +248,28 @@ Feature: Stage guards: a 3D render an agent can't break# errors, 705 warns and 47 notes. mimalloc in place of the system allocator was measured and dropped: no less# growth over the frames (3.74 GB at 13,000 against 3.89), and 7.8 GB kept after the end checks (2.3) for a 10.4 GB# peak. Still not met: memory grows by about 45% after the first minute, for the causes left above.+ # Branch stage-guards-20: measured on the film and on a control (one scene for 13,200 frames, nothing added after+ # its first: 48 parts that move, a bar whose size changes each frame, 3D words that count, the page's words), each+ # with a memory mark after the frames, sound and video. Four things grew with the length. Each frame's scene was+ # kept for the end checks: its parts go to a temp file as the frames come now (raea-io-kept), each props map,+ # string and material written once by its content, and a part's own place left out of its props (the checks read+ # it from its matrix, a camera's alone from its props), so a moving part's frames share one map: the control's+ # parts read back fell from 1.35 GB to 0.19 GB. The MP4 writer (muxide) held every sample to the end, after the+ # encoder had kept them on disk: 1.1 GB on the film, 0.55 GB on the control; they go to a temp file as they come.+ # The sound's master oversampled the whole sound 4x three times (676 MB each on the film), weighted all of it in+ # f64 for every loudness reading (about 0.8 GB a reading, up to a dozen), and copied it when it had no gap to fill:+ # the true peak, its envelope and the loudness go a block at a time now, the same bits (each tested against the+ # whole), and what the master freed is handed back. And the shape cache held 1 GB: two 16 MB generations now.+ # The film with every check on: 1.56 GB at frame 1,000, 1.91 GB at 2,000, 2.43 GB at 13,000 (3.7 before), 2.73 GB+ # after its sound and video (5.75 in the run before the mux and master fixes), 3.0 GB with its 2.04 million parts+ # read back, a 4.8 GB peak (6.0), the same 439 errors, 705 warns and 47 notes, at 34.3 ms a frame. The control:+ # 1.05 GB at frame 1,000, 1.27 GB at 13,000 (1.50, +44%, before), a 1.5 GB peak (2.85). Still not met: the+ # control's frames grow 19% after its first minute: each frame's manifest entry kept as JSON values (3 KB a frame)+ # and memory the system allocator keeps once the frames have freed it (Malloc Large's dirty pages grew 97 MB over+ # 8,000 frames while the live heap grew 23 MB; handing memory back every 500 frames left it as it was). The film's+ # frames grow 27%, most of it its later scenes' own (2.07 to 2.55 GB in the 1,000 frames from 5:33). The end+ # checks hold every frame's parts and each part's solid over its frames (the clipping check's 4.7 GB resident+ # peak); flat needs them to run as the frames come.Rule: The SDK stops allowing itdiff --git a/io/codec/src/audio.rs b/io/codec/src/audio.rsindex 13a8604e..8f76846c 100644--- a/io/codec/src/audio.rs+++ b/io/codec/src/audio.rs@@ -88,11 +88,18 @@ pub fn peak_db(a: &Audio) -> f64 {20.0 * (p as f64).max(1e-12).log10()}-/// The K-weighted channels (BS.1770's shelf, then its high-pass), at 48 kHz.-fn k_weighted(a: &Audio) -> Vec<Vec<f64>> {- let a = crate::soft_resample(a, RATE);+/// The sound at 48 kHz, borrowed when it already is.+fn at_rate(a: &Audio) -> std::borrow::Cow<'_, Audio> {+ if a.rate == RATE || a.channels.is_empty() {+ std::borrow::Cow::Borrowed(a)+ } else {+ std::borrow::Cow::Owned(crate::soft_resample(a, RATE))+ }+}++/// The two K-weighting biquads (BS.1770 coefficients, derived for 48 kHz): the shelf, then the high-pass.+fn k_filters() -> ([f64; 5], [f64; 5]) {let fs = RATE as f64;- // the two K-weighting biquads (BS.1770 coefficients, derived for fs)let shelf = {let (f0, g, q) = (1681.974450955533, 3.999843853973347, 0.7071752369554196);let k = (std::f64::consts::PI * f0 / fs).tan();@@ -119,26 +126,38 @@ fn k_weighted(a: &Audio) -> Vec<Vec<f64>> {(1.0 - k / q + k * k) / a0,]};- let biquad = |x: &[f64], c: [f64; 5]| -> Vec<f64> {- let (mut x1, mut x2, mut y1, mut y2) = (0.0, 0.0, 0.0, 0.0);- x.iter()- .map(|&v| {- let y = c[0] * v + c[1] * x1 + c[2] * x2 - c[3] * y1 - c[4] * y2;- x2 = x1;- x1 = v;- y2 = y1;- y1 = y;- y- })- .collect()- };- a.channels+ (shelf, hp)+}++/// One biquad's state, run a sample at a time.+#[derive(Clone, Default)]+struct Biquad {+ x1: f64,+ x2: f64,+ y1: f64,+ y2: f64,+}++impl Biquad {+ fn run(&mut self, c: &[f64; 5], v: f64) -> f64 {+ let y = c[0] * v + c[1] * self.x1 + c[2] * self.x2 - c[3] * self.y1 - c[4] * self.y2;+ self.x2 = self.x1;+ self.x1 = v;+ self.y2 = self.y1;+ self.y1 = y;+ y+ }+}++/// The K-weighted channels (BS.1770's shelf, then its high-pass), at 48 kHz.+fn k_weighted(a: &Audio) -> Vec<Vec<f64>> {+ let (shelf, hp) = k_filters();+ at_rate(a)+ .channels.iter().map(|c| {- biquad(- &biquad(&c.iter().map(|x| *x as f64).collect::<Vec<_>>(), shelf),- hp,- )+ let (mut s, mut h) = (Biquad::default(), Biquad::default());+ c.iter().map(|x| h.run(&hp, s.run(&shelf, *x as f64))).collect()}).collect()}@@ -172,18 +191,31 @@ pub fn momentary(a: &Audio, fps: f64, n: usize) -> Vec<f64> {/// -70 LUFS, relative gate at -10 LU. Written as column scans.pub fn lufs(a: &Audio) -> f64 {let fs = RATE as f64;- let weighted = k_weighted(a);- let len = weighted.first().map(Vec::len).unwrap_or(0);let (block, step) = ((0.4 * fs) as usize, (0.1 * fs) as usize);+ let a = at_rate(a);+ let (shelf, hp) = k_filters();+ // each channel weighted a sample at a time, only its last block held: the whole, in f64 with its copies, was about+ // 0.8 GB a call on a 7-minute film, and its master measures up to a dozen times (SG4a). Each block is summed over+ // the same samples in the same order, so the same bits.+ let mut filters = vec![(Biquad::default(), Biquad::default()); a.channels.len()];+ let mut last = vec![std::collections::VecDeque::with_capacity(block); a.channels.len()];+ let len = a.channels.first().map(Vec::len).unwrap_or(0);let mut z = Vec::new();- let mut s = 0;- while s + block <= len {- let mut e = 0.0;- for c in &weighted {- e += c[s..s + block].iter().map(|v| v * v).sum::<f64>() / block as f64;+ for i in 0..len {+ for ((c, (s, h)), w) in a.channels.iter().zip(&mut filters).zip(&mut last) {+ if w.len() == block {+ w.pop_front();+ }+ w.push_back(h.run(&hp, s.run(&shelf, c.get(i).copied().unwrap_or(0.0) as f64)));+ }+ if i + 1 >= block && (i + 1 - block) % step == 0 {+ let mut e = 0.0;+ for w in &last {+ let (x, y) = w.as_slices();+ e += x.iter().chain(y).map(|v| v * v).sum::<f64>() / block as f64;+ }+ z.push(e);}- z.push(e);- s += step;}let l = |e: f64| -0.691 + 10.0 * e.max(1e-15).log10();let abs: Vec<f64> = z.iter().copied().filter(|&e| l(e) > -70.0).collect();@@ -271,7 +303,9 @@ pub fn master_for(a: &Audio, target: f64, ceiling: f64, encode: &dyn Fn(&Audio)/// The true peak (dBTP): the peak of the signal oversampled 4x.pub fn true_peak_db(a: &Audio) -> f64 {- peak_db(&crate::soft_resample(a, a.rate * 4))+ let mut p = 0f32;+ crate::soft_resample_blocks(a, a.rate * 4, |_, _, b| p = b.iter().fold(p, |m, x| m.max(x.abs())));+ 20.0 * (p as f64).max(1e-12).log10()}/// Each sample's true peak across channels: the largest 4x-oversampled magnitude from half a sample before it to half@@ -282,17 +316,17 @@ fn true_envelope(a: &Audio) -> Vec<f32> {if n == 0 {return env;}- let up = crate::soft_resample(a, a.rate * 4);- for ch in &up.channels {- for (j, y) in ch.iter().enumerate() {- let v = y.abs();+ // the oversampled sound a block at a time, not held whole (SG4a)+ crate::soft_resample_blocks(a, a.rate * 4, |_, from, b| {+ for (k, y) in b.iter().enumerate() {+ let (j, v) = (from + k, y.abs());for i in [(j + 2) / 4, (j + 1) / 4] {if i < n && v > env[i] {env[i] = v;}}}- }+ });for ch in &a.channels {for (i, x) in ch.iter().enumerate() {env[i] = env[i].max(x.abs());@@ -351,45 +385,4 @@ fn limit(a: &Audio, gain_db: f64, ceiling: f64, tp: &[f32]) -> Audio {}#[cfg(test)]-mod tests {- use super::*;-- /// A tone at a quarter of the rate, 45 degrees off the samples: every sample sits at 0.707 of the wave's peak,- /// so a sample-peak limiter lets the true peak through 3 dB over its ceiling. The target is louder than the- /// ceiling allows, so the limiter has to work.- #[test]- fn the_master_ceiling_holds_between_samples() {- let n = 3 * RATE as usize;- let ch: Vec<f32> = (0..n).map(|i| 0.5 * (std::f32::consts::FRAC_PI_2 * i as f32 + std::f32::consts::FRAC_PI_4).sin()).collect();- let a = Audio { rate: RATE, channels: vec![ch.clone(), ch] };- let out = master(&a, 6.0, -1.0);- let (tp, sp) = (true_peak_db(&out), peak_db(&out));- assert!(tp <= -1.0, "true peak {tp:.2} dBTP over the -1 ceiling (sample peak {sp:.2})");- assert!(tp > -2.0, "limited far below the ceiling: {tp:.2} dBTP");- }-- /// A range's sound: a rifle's crack every 1.5 s with a short decaying tail over a quiet bed of wind, its peaks far- /// over its loudness, so reaching -14 LUFS under a -1.5 dBTP ceiling takes limiting that eats most of the gain (a- /// gambit range demo, made up a dB for a dB in three passes, came out at -15.8). Mastered, it reaches the target- /// (made up the old way it stops 0.25 short). Its true peak isn't held here: limited 10 dB, noise like this comes- /// out up to a dB over the ceiling between samples, which `master_for` takes off after the encoder.- #[test]- fn a_percussive_master_reaches_its_loudness() {- let n = 9 * RATE as usize;- // (noise through a one-pole low-pass near 4 kHz, as a crack heard at the firing point is darker than white noise)- let (mut seed, mut lp) = (12345u32, 0f32);- let ch: Vec<f32> = (0..n)- .map(|i| {- seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);- lp += 0.4 * (((seed >> 8) as f32 / (1u32 << 24) as f32 * 2.0 - 1.0) - lp);- let since = (i % (RATE as usize * 3 / 2)) as f32 / RATE as f32;- 1.6 * lp * (-since / 0.06).exp() + 0.1 * lp- })- .collect();- let a = Audio { rate: RATE, channels: vec![ch.clone(), ch] };- let (out, _) = master_gained(&a, -14.0, -1.5);- let (l, tp) = (lufs(&out), true_peak_db(&out));- assert!((l + 14.0).abs() < 0.15, "mastered to {l:.2} LUFS, not -14 (true peak {tp:.2})");- assert!(peak_db(&out) <= -1.5 + 0.05, "sample peak {:.2} dB over the -1.5 ceiling", peak_db(&out));- }-}+mod tests;diff --git a/io/codec/src/audio/tests.rs b/io/codec/src/audio/tests.rsnew file mode 100644index 00000000..f2de1e83--- /dev/null+++ b/io/codec/src/audio/tests.rs@@ -0,0 +1,117 @@+use super::*;++/// lufs as it was: the whole sound weighted (a biquad over each whole channel, then the next), then the blocks+fn lufs_whole(a: &Audio) -> f64 {+ let a = crate::soft_resample(a, RATE);+ let (shelf, hp) = k_filters();+ let biquad = |x: &[f64], c: [f64; 5]| -> Vec<f64> {+ let (mut x1, mut x2, mut y1, mut y2) = (0.0, 0.0, 0.0, 0.0);+ x.iter()+ .map(|&v| {+ let y = c[0] * v + c[1] * x1 + c[2] * x2 - c[3] * y1 - c[4] * y2;+ (x2, x1, y2, y1) = (x1, v, y1, y);+ y+ })+ .collect()+ };+ let weighted: Vec<Vec<f64>> = a.channels.iter().map(|c| biquad(&biquad(&c.iter().map(|x| *x as f64).collect::<Vec<_>>(), shelf), hp)).collect();+ assert!(k_weighted(&a).iter().zip(&weighted).all(|(g, w)| g.iter().zip(w).all(|(x, y)| x.to_bits() == y.to_bits())));+ let len = weighted.first().map(Vec::len).unwrap_or(0);+ let (block, step) = ((0.4 * RATE as f64) as usize, (0.1 * RATE as f64) as usize);+ let (mut z, mut s) = (Vec::new(), 0);+ while s + block <= len {+ z.push(weighted.iter().map(|c| c[s..s + block].iter().map(|v| v * v).sum::<f64>() / block as f64).fold(0.0, |e, x| e + x));+ s += step;+ }+ let l = |e: f64| -0.691 + 10.0 * e.max(1e-15).log10();+ let abs: Vec<f64> = z.iter().copied().filter(|&e| l(e) > -70.0).collect();+ if abs.is_empty() {+ return -70.0;+ }+ let rel = l(abs.iter().sum::<f64>() / abs.len() as f64) - 10.0;+ let gated: Vec<f64> = abs.into_iter().filter(|&e| l(e) > rel).collect();+ l(gated.iter().sum::<f64>() / gated.len().max(1) as f64)+}++#[test]+fn lufs_a_block_at_a_time_is_the_whole_ones_bits() {+ let mut seed = 0x9e37_79b9_7f4a_7c15u64;+ let mut noise = |n: usize, amp: f32| -> Vec<f32> {+ (0..n)+ .map(|i| {+ seed ^= seed << 13;+ seed ^= seed >> 7;+ seed ^= seed << 17;+ amp * ((seed >> 40) as f32 / (1u64 << 23) as f32 - 1.0) * if (i / 30_000) % 3 == 0 { 0.05 } else { 1.0 }+ })+ .collect()+ };+ for (rate, chans, n) in [(48000, 2, 123_457), (44100, 2, 99_991), (48000, 1, 40_000), (48000, 2, 10_000)] {+ let a = Audio { rate, channels: (0..chans).map(|_| noise(n, 0.5)).collect() };+ assert_eq!(lufs(&a).to_bits(), lufs_whole(&a).to_bits(), "{rate} Hz, {chans} channels, {n} samples");+ }+}++#[test]+fn the_true_peak_and_envelope_a_block_at_a_time_are_the_whole_ones() {+ // a tone and its clicks, past one block of the 4x sound (2^20 samples)+ let ch = |f: f32| (0..400_000).map(|i| (i as f32 * f).sin() * if i % 9973 == 0 { 1.4 } else { 0.6 }).collect::<Vec<f32>>();+ let a = Audio { rate: 48000, channels: vec![ch(0.031), ch(0.047)] };+ let up = crate::soft_resample(&a, a.rate * 4);+ assert_eq!(true_peak_db(&a).to_bits(), peak_db(&up).to_bits());+ let mut want = vec![0f32; a.len()];+ for c in &up.channels {+ for (j, y) in c.iter().enumerate() {+ for i in [(j + 2) / 4, (j + 1) / 4] {+ if i < want.len() && y.abs() > want[i] {+ want[i] = y.abs();+ }+ }+ }+ }+ for c in &a.channels {+ for (i, x) in c.iter().enumerate() {+ want[i] = want[i].max(x.abs());+ }+ }+ assert!(true_envelope(&a).iter().zip(&want).all(|(g, w)| g.to_bits() == w.to_bits()));+}++/// A tone at a quarter of the rate, 45 degrees off the samples: every sample sits at 0.707 of the wave's peak,+/// so a sample-peak limiter lets the true peak through 3 dB over its ceiling. The target is louder than the+/// ceiling allows, so the limiter has to work.+#[test]+fn the_master_ceiling_holds_between_samples() {+ let n = 3 * RATE as usize;+ let ch: Vec<f32> = (0..n).map(|i| 0.5 * (std::f32::consts::FRAC_PI_2 * i as f32 + std::f32::consts::FRAC_PI_4).sin()).collect();+ let a = Audio { rate: RATE, channels: vec![ch.clone(), ch] };+ let out = master(&a, 6.0, -1.0);+ let (tp, sp) = (true_peak_db(&out), peak_db(&out));+ assert!(tp <= -1.0, "true peak {tp:.2} dBTP over the -1 ceiling (sample peak {sp:.2})");+ assert!(tp > -2.0, "limited far below the ceiling: {tp:.2} dBTP");+}++/// A range's sound: a rifle's crack every 1.5 s with a short decaying tail over a quiet bed of wind, its peaks far+/// over its loudness, so reaching -14 LUFS under a -1.5 dBTP ceiling takes limiting that eats most of the gain (a+/// gambit range demo, made up a dB for a dB in three passes, came out at -15.8). Mastered, it reaches the target+/// (made up the old way it stops 0.25 short). Its true peak isn't held here: limited 10 dB, noise like this comes+/// out up to a dB over the ceiling between samples, which `master_for` takes off after the encoder.+#[test]+fn a_percussive_master_reaches_its_loudness() {+ let n = 9 * RATE as usize;+ // (noise through a one-pole low-pass near 4 kHz, as a crack heard at the firing point is darker than white noise)+ let (mut seed, mut lp) = (12345u32, 0f32);+ let ch: Vec<f32> = (0..n)+ .map(|i| {+ seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);+ lp += 0.4 * (((seed >> 8) as f32 / (1u32 << 24) as f32 * 2.0 - 1.0) - lp);+ let since = (i % (RATE as usize * 3 / 2)) as f32 / RATE as f32;+ 1.6 * lp * (-since / 0.06).exp() + 0.1 * lp+ })+ .collect();+ let a = Audio { rate: RATE, channels: vec![ch.clone(), ch] };+ let (out, _) = master_gained(&a, -14.0, -1.5);+ let (l, tp) = (lufs(&out), true_peak_db(&out));+ assert!((l + 14.0).abs() < 0.15, "mastered to {l:.2} LUFS, not -14 (true peak {tp:.2})");+ assert!(peak_db(&out) <= -1.5 + 0.05, "sample peak {:.2} dB over the -1.5 ceiling", peak_db(&out));+}diff --git a/io/codec/src/lib.rs b/io/codec/src/lib.rsindex a04e5327..c74bc53c 100644--- a/io/codec/src/lib.rs+++ b/io/codec/src/lib.rs@@ -11,7 +11,7 @@ pub mod samples;mod resample;pub mod yuv;-pub use resample::soft_resample;+pub use resample::{soft_resample, soft_resample_blocks};/// A decoded frame still in VideoToolbox's buffer: NV12 (video range), IOSurface-backed and Metal-compatible, retained/// (frame_surface_at). Nothing was copied; a GPU can sample its two planes as textures.diff --git a/io/codec/src/resample.rs b/io/codec/src/resample.rsindex af2a6bec..80974abf 100644--- a/io/codec/src/resample.rs+++ b/io/codec/src/resample.rs@@ -10,58 +10,108 @@ pub fn soft_resample(a: &Audio, to: u32) -> Audio {if a.rate == 0 || to == 0 {return Audio { rate: to, channels: vec![Vec::new(); a.channels.len()] };}- let (from, to_f) = (a.rate as f64, to as f64);- let n = (a.len() as f64 * to_f / from).round() as usize;- let cutoff = 0.97 * from.min(to_f) / from; // in cycles per input sample x2- let zc = 32.0;- let half = (zc / cutoff).ceil() as i64;- let beta = 9.0f64;- let i0 = |x: f64| {- let (mut s, mut t, mut k) = (1.0, 1.0, 1.0);- while t > 1e-12 * s {- t *= (x / (2.0 * k)).powi(2);- s += t;- k += 1.0;+ let k = Kernel::new(a.rate, to, a.len());+ let channels = a+ .channels+ .iter()+ .map(|c| {+ let mut out = vec![0f32; k.n];+ k.fill(c, 0, &mut out);+ out+ })+ .collect();+ Audio { rate: to, channels }+}++/// soft_resample's samples handed to `f` a block at a time (the channel, the block's first sample, the block), the+/// same bits, never held whole: a 7-minute film's master oversampled its sound 4x three times, 676 MB each (SG4a).+pub fn soft_resample_blocks(a: &Audio, to: u32, mut f: impl FnMut(usize, usize, &[f32])) {+ if a.rate == to {+ for (ci, c) in a.channels.iter().enumerate() {+ f(ci, 0, c);}- s- };- let i0b = i0(beta);- // the kernel at 1024 phases between input samples- const PH: usize = 1024;- let taps = (2 * half + 1) as usize;- let mut table = vec![0f32; (PH + 1) * taps];- for p in 0..=PH {- let frac = p as f64 / PH as f64;- for k in 0..taps {- let x = (k as i64 - half) as f64 - frac;- let u = x * cutoff;- let sinc = if u.abs() < 1e-12 {- 1.0- } else {- (std::f64::consts::PI * u).sin() / (std::f64::consts::PI * u)- };- let r = x / (half as f64 + 1.0);- let w = if r.abs() >= 1.0 {- 0.0- } else {- i0(beta * (1.0 - r * r).sqrt()) / i0b- };- table[p * taps + k] = (cutoff * sinc * w) as f32;+ return;+ }+ if a.rate == 0 || to == 0 || a.channels.is_empty() {+ return;+ }+ const BLOCK: usize = 1 << 20;+ let k = Kernel::new(a.rate, to, a.len());+ let mut buf = vec![0f32; k.n.min(BLOCK)];+ for (ci, c) in a.channels.iter().enumerate() {+ for from in (0..k.n).step_by(BLOCK) {+ let m = (k.n - from).min(BLOCK);+ k.fill(c, from, &mut buf[..m]);+ f(ci, from, &buf[..m]);+ }+ }+}++/// the kernel at this many phases between input samples+const PH: usize = 1024;++/// What soft_resample sums: n output samples, each on its own from the input (the same taps in the same order, so+/// the same bits however they're asked for).+struct Kernel {+ table: Vec<f32>,+ taps: usize,+ half: i64,+ step: f64,+ n: usize,+}++impl Kernel {+ fn new(rate: u32, to: u32, len: usize) -> Kernel {+ let (from, to_f) = (rate as f64, to as f64);+ let n = (len as f64 * to_f / from).round() as usize;+ let cutoff = 0.97 * from.min(to_f) / from; // in cycles per input sample x2+ let zc = 32.0;+ let half = (zc / cutoff).ceil() as i64;+ let beta = 9.0f64;+ let i0 = |x: f64| {+ let (mut s, mut t, mut k) = (1.0, 1.0, 1.0);+ while t > 1e-12 * s {+ t *= (x / (2.0 * k)).powi(2);+ s += t;+ k += 1.0;+ }+ s+ };+ let i0b = i0(beta);+ let taps = (2 * half + 1) as usize;+ let mut table = vec![0f32; (PH + 1) * taps];+ for p in 0..=PH {+ let frac = p as f64 / PH as f64;+ for k in 0..taps {+ let x = (k as i64 - half) as f64 - frac;+ let u = x * cutoff;+ let sinc = if u.abs() < 1e-12 {+ 1.0+ } else {+ (std::f64::consts::PI * u).sin() / (std::f64::consts::PI * u)+ };+ let r = x / (half as f64 + 1.0);+ let w = if r.abs() >= 1.0 {+ 0.0+ } else {+ i0(beta * (1.0 - r * r).sqrt()) / i0b+ };+ table[p * taps + k] = (cutoff * sinc * w) as f32;+ }}+ Kernel { table, taps, half, step: from / to_f, n }}- let step = from / to_f;- // each output sample on its own (the same taps summed in the same order as one at a time, so the same bits), in- // spans across threads; a sample whose taps all land inside the input skips the bounds test. A film's master- // oversamples its 4.5 minutes 4x up to five times: 26.7 s a render on one thread (2026-10-20)- let one = |c: &[f32], i: usize| -> f32 {- let x = i as f64 * step;++ /// Output sample i of channel `c`; a sample whose taps all land inside the input skips the bounds test.+ fn at(&self, c: &[f32], i: usize) -> f32 {+ let x = i as f64 * self.step;let j = x.floor() as i64;let p = (((x - j as f64) * PH as f64).round() as usize).min(PH);- let row = &table[p * taps..(p + 1) * taps];+ let row = &self.table[p * self.taps..(p + 1) * self.taps];let mut acc = 0f32;- let lo = j - half;- if lo >= 0 && ((lo + taps as i64) as usize) <= c.len() {- let src = &c[lo as usize..lo as usize + taps];+ let lo = j - self.half;+ if lo >= 0 && ((lo + self.taps as i64) as usize) <= c.len() {+ let src = &c[lo as usize..lo as usize + self.taps];for (x, w) in src.iter().zip(row) {acc += x * w;}@@ -74,37 +124,31 @@ pub fn soft_resample(a: &Audio, to: u32) -> Audio {}}acc- };- let threads = if n * taps < 1 << 22 { 1 } else { std::thread::available_parallelism().map(|t| t.get()).unwrap_or(4).clamp(1, 8) };- let channels = a- .channels- .iter()- .map(|c| {- let mut out = vec![0f32; n];- if threads == 1 {- for (i, o) in out.iter_mut().enumerate() {- *o = one(c, i);- }- } else {- let span = n.div_ceil(threads);- std::thread::scope(|sc| {- for (t, part) in out.chunks_mut(span).enumerate() {- let one = &one;- sc.spawn(move || {- for (k, o) in part.iter_mut().enumerate() {- *o = one(c, t * span + k);- }- });+ }++ /// `out` as output samples `from`.. in spans across threads when it's long. A film's master oversamples its 4.5+ /// minutes 4x up to five times: 26.7 s a render on one thread (2026-10-20)+ fn fill(&self, c: &[f32], from: usize, out: &mut [f32]) {+ let threads = if out.len() * self.taps < 1 << 22 { 1 } else { std::thread::available_parallelism().map(|t| t.get()).unwrap_or(4).clamp(1, 8) };+ if threads == 1 {+ for (k, o) in out.iter_mut().enumerate() {+ *o = self.at(c, from + k);+ }+ return;+ }+ let span = out.len().div_ceil(threads);+ std::thread::scope(|sc| {+ for (t, part) in out.chunks_mut(span).enumerate() {+ sc.spawn(move || {+ for (k, o) in part.iter_mut().enumerate() {+ *o = self.at(c, from + t * span + k);}});}- out- })- .collect();- Audio { rate: to, channels }+ });+ }}-#[cfg(test)]mod resample_tests {use super::*;@@ -187,5 +231,16 @@ mod resample_tests {assert!(g.iter().zip(w).all(|(x, y)| x.to_bits() == y.to_bits()), "{rate} -> {to}, {len} samples");}}+ // a block at a time, past one block (2^20 samples): the same bits as the whole+ let a = Audio { rate: 48000, channels: vec![noise(300_000), noise(300_000)] };+ let whole = soft_resample(&a, 192_000);+ let mut blocks = vec![Vec::new(); 2];+ soft_resample_blocks(&a, 192_000, |c, from, b| {+ assert_eq!(from, blocks[c].len());+ blocks[c].extend_from_slice(b);+ });+ for (g, w) in blocks.iter().zip(&whole.channels) {+ assert!(g.len() == w.len() && g.iter().zip(w).all(|(x, y)| x.to_bits() == y.to_bits()), "blocks");+ }}}diff --git a/io/codec/src/samples.rs b/io/codec/src/samples.rsindex 5a2d1639..20c8d0b1 100644--- a/io/codec/src/samples.rs+++ b/io/codec/src/samples.rs@@ -1,7 +1,7 @@//! A video encoder's samples kept on disk as they come out, not in memory, and read back one at a time for the mux//! (remux::annexb_mux_from). A 7-minute film's 1 GB of H.264 grew its render by that much and was copied again-//! into the mux (docs/stage-guards.feature SG4a). The file is a temp file gone when raea is (unlinked once open on-//! unix, delete-on-close on Windows), so a render that dies leaves nothing behind.+//! into the mux (docs/stage-guards.feature SG4a). The file is a temp file gone when raea is (raea_io_home::scratch_file),+//! so a render that dies leaves nothing behind.use std::io::{Read, Seek, SeekFrom, Write};@@ -16,15 +16,7 @@ pub struct Samples {impl Samples {pub fn new() -> R<Samples> {- static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);- let p = std::env::temp_dir().join(format!("raea-samples-{}-{}", std::process::id(), N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));- let mut o = std::fs::OpenOptions::new();- o.read(true).write(true).create_new(true);- #[cfg(windows)]- std::os::windows::fs::OpenOptionsExt::custom_flags(&mut o, 0x0400_0000); // FILE_FLAG_DELETE_ON_CLOSE- let f = o.open(&p).map_err(|e| format!("{}: {e}", p.display()))?;- #[cfg(unix)]- let _ = std::fs::remove_file(&p);+ let f = raea_io_home::scratch_file("samples")?;Ok(Samples { file: std::io::BufWriter::with_capacity(1 << 20, f), at: Vec::new(), end: 0 })}diff --git a/io/home/src/lib.rs b/io/home/src/lib.rsindex 6374c8f8..dfd53f1d 100644--- a/io/home/src/lib.rs+++ b/io/home/src/lib.rs@@ -110,6 +110,21 @@ pub fn logs() -> Option<std::path::PathBuf> {user_dir("Library/Logs/raea", "XDG_STATE_HOME", ".local/state", "logs")}+/// A new temp file named `raea-NAME-PID-N`, open to read and write, gone when raea is: unlinked once open on unix,+/// delete-on-close on Windows, so a render that dies leaves nothing behind (an encoder's samples, a render's parts).+pub fn scratch_file(name: &str) -> Result<std::fs::File, String> {+ static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+ let p = std::env::temp_dir().join(format!("raea-{name}-{}-{}", std::process::id(), N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));+ let mut o = std::fs::OpenOptions::new();+ o.read(true).write(true).create_new(true);+ #[cfg(windows)]+ std::os::windows::fs::OpenOptionsExt::custom_flags(&mut o, 0x0400_0000); // FILE_FLAG_DELETE_ON_CLOSE+ let f = o.open(&p).map_err(|e| format!("{}: {e}", p.display()))?;+ #[cfg(unix)]+ let _ = std::fs::remove_file(&p);+ Ok(f)+}+/// macOS's folder under HOME, the XDG base folder (its variable, else its default under HOME) with raea in it, or raea's/// folder of that kind under %LOCALAPPDATA%. An XDG variable that isn't an absolute path is ignored, as the spec says.fn user_dir(apple: &str, xdg: &str, xdg_default: &str, windows: &str) -> Option<std::path::PathBuf> {diff --git a/io/kept/Cargo.toml b/io/kept/Cargo.tomlnew file mode 100644index 00000000..0ef901f5--- /dev/null+++ b/io/kept/Cargo.toml@@ -0,0 +1,15 @@+[package]+name = "raea-io-kept"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "A long render's 3D parts kept on disk as its frames come, each props map written once by its content, read back for the checks at its end"++[dependencies]+bevy = { version = "=0.20.0", default-features = false, features = ["std"] }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+raea-core-scene = { path = "../../core/scene" }+# the temp file the parts go to, gone when raea is+raea-io-home = { path = "../home" }diff --git a/io/kept/src/lib.rs b/io/kept/src/lib.rsnew file mode 100644index 00000000..24a5b59f--- /dev/null+++ b/io/kept/src/lib.rs@@ -0,0 +1,245 @@+//! A long render's 3D parts kept on disk as its frames come, for the checks at its end (docs/stage-guards.feature+//! SG4a). Each frame's scene was held in memory to the end: a 7-minute film grew by about 29 KB a frame (each changed+//! part's props, its node and its parent's list), most of what still grew with the frame count. Each frame's parts go to+//! a temp file instead: each props map, string and material is written once by its content (a part unchanged since the+//! frame before is known by its pointer and not written again), and the parts read back at the end share equal+//! contents. The file is gone when raea is (unlinked once open on unix, delete-on-close on Windows), as the encoders'+//! samples are (raea-io-codec samples.rs).+//!+//! A part's place is its matrix: the props' own place (PLACE) is kept only for a camera, the one part the checks read it+//! from (systems/stage view.rs, systems/contact seen.rs). A part that moves each frame has the same props otherwise,+//! so its frames share one map: the one-scene control's 48 moving boxes were 1.35 GB of maps read back, one a frame.++use std::collections::HashMap;+use std::hash::{Hash, Hasher};+use std::io::{BufRead, Seek, Write};+use std::sync::{Arc, Mutex};++use bevy::math::Mat4;+use raea_core_scene::{Item, Node3};+use serde_json::{Map, Value, json};++type R<T> = Result<T, String>;+type Props = Arc<Map<String, Value>>;+/// a shared value's pointers: what (0 props, 1 a string, 2 a material) and up to three of its Arcs+type Key = (u8, usize, usize, usize);+/// a part's own place in its props, left out but for a camera's+const PLACE: [&str; 4] = ["position", "rotation", "scale", "quaternion"];++/// What a part held the frame before: kept for the frame, so its pointer isn't another value's (held, never read).+#[allow(dead_code)]+enum Held {+ Props(Props),+ Str(Arc<str>),+ Node(Node3),+}++/// Every frame's parts, on disk.+pub struct Kept {+ file: std::io::BufWriter<std::fs::File>,+ frames: usize,+ /// the frame before's shared values, by pointer, with their ids+ last: HashMap<Key, (String, Held)>,+}++impl Kept {+ pub fn new() -> R<Kept> {+ let f = raea_io_home::scratch_file("kept")?;+ Ok(Kept { file: std::io::BufWriter::with_capacity(1 << 20, f), frames: 0, last: HashMap::new() })+ }++ /// The next frame's parts.+ pub fn put(&mut self, items: &[Item]) -> R<()> {+ let mut now: HashMap<Key, (String, Held)> = HashMap::with_capacity(self.last.len());+ let mut defs = String::new();+ let mut row = Vec::with_capacity(items.len());+ for it in items {+ let props = &it.props;+ let p = self.id((0, Arc::as_ptr(props) as *const () as usize, 0, 0), &mut now, &mut defs, || {+ let text = if it.kind != "camera" && PLACE.iter().any(|k| props.contains_key(*k)) {+ serde_json::to_string(&Placeless(props))+ } else {+ serde_json::to_string(&**props)+ };+ (Held::Props(props.clone()), text.unwrap_or_default())+ });+ let s = it.shape.as_ref().map(|s| self.string(s, &mut now, &mut defs));+ let a = it.at.as_ref().map(|s| self.string(s, &mut now, &mut defs));+ let m = it.material.as_ref().map(|n| {+ let key = (2, Arc::as_ptr(&n.props) as *const () as usize, Arc::as_ptr(&n.kids) as *const () as usize, Arc::as_ptr(&n.kind) as *const () as usize);+ self.id(key, &mut now, &mut defs, || (Held::Node(n.clone()), node_json(n).to_string()))+ });+ let world: Vec<u32> = it.world.to_cols_array().iter().map(|v| v.to_bits()).collect();+ row.push(json!([it.kind, p, s, a, m, world]));+ }+ self.last = now;+ defs.push_str(&json!({ "f": row }).to_string());+ defs.push('\n');+ self.file.write_all(defs.as_bytes()).map_err(|e| format!("keeping a frame's parts on disk: {e}"))?;+ self.frames += 1;+ Ok(())+ }++ /// Frames given so far.+ pub fn len(&self) -> usize {+ self.frames+ }++ pub fn is_empty(&self) -> bool {+ self.frames == 0+ }++ /// Every frame's parts, as they were given, equal props, strings and materials shared. A frame's line is read+ /// into the parts alone and a definition only when its id is new: each line parsed whole into JSON values left+ /// 2.7 GB of the film's memory freed but not yet given back at the checks' start.+ pub fn read(self) -> R<Vec<Vec<Item>>> {+ let bad = |e: String| format!("reading the kept parts back: {e}");+ let mut f = self.file.into_inner().map_err(|e| bad(e.to_string()))?;+ f.seek(std::io::SeekFrom::Start(0)).map_err(|e| bad(e.to_string()))?;+ let (mut props, mut strs, mut nodes) = (HashMap::<String, Props>::new(), HashMap::<String, Arc<str>>::new(), HashMap::<String, Node3>::new());+ let mut out = Vec::with_capacity(self.frames);+ for line in std::io::BufReader::new(f).lines() {+ let line = line.map_err(|e| bad(e.to_string()))?;+ if line.starts_with("{\"f\":") {+ let fr: Frame = serde_json::from_str(&line).map_err(|e| bad(e.to_string()))?;+ out.push(fr.f.iter().map(|r| item(r, &props, &strs, &nodes)).collect::<R<Vec<_>>>().map_err(bad)?);+ continue;+ }+ // {"p":"<id>","v":<value>}, as `id` writes it+ let (Some(tag), Some(id), Some(v)) = (line.get(2..3), line.get(6..38), line.get(44..line.len().saturating_sub(1))) else { return Err(bad("a line that isn't a part or a definition".into())) };+ let json = |e: serde_json::Error| bad(e.to_string());+ match tag {+ "p" if !props.contains_key(id) => drop(props.insert(id.into(), Arc::new(serde_json::from_str(v).map_err(json)?))),+ "s" if !strs.contains_key(id) => drop(strs.insert(id.into(), Arc::from(serde_json::from_str::<String>(v).map_err(json)?))),+ "m" if !nodes.contains_key(id) => drop(nodes.insert(id.into(), node_of(&serde_json::from_str(v).map_err(json)?).map_err(bad)?)),+ _ => {}+ }+ }+ if out.len() != self.frames {+ return Err(bad(format!("{} frames back of {}", out.len(), self.frames)));+ }+ Ok(out)+ }++ fn string(&mut self, s: &Arc<str>, now: &mut HashMap<Key, (String, Held)>, defs: &mut String) -> String {+ let key = (1, Arc::as_ptr(s) as *const () as usize, s.len(), 0);+ self.id(key, now, defs, || (Held::Str(s.clone()), serde_json::to_string(&**s).unwrap_or_default()))+ }++ /// A shared value's id: the one it had this frame or the frame before (same pointer), else its content's, its+ /// definition written ahead of the frame.+ fn id(&mut self, key: Key, now: &mut HashMap<Key, (String, Held)>, defs: &mut String, made: impl FnOnce() -> (Held, String)) -> String {+ if let Some((id, _)) = now.get(&key) {+ return id.clone();+ }+ let (id, held) = self.last.remove(&key).unwrap_or_else(|| {+ let (held, text) = made();+ let id = id_of(&text);+ let tag = ["p", "s", "m"][key.0 as usize];+ defs.push_str(&format!("{{\"{tag}\":\"{id}\",\"v\":{text}}}\n"));+ (id, held)+ });+ now.insert(key, (id.clone(), held));+ id+ }+}++/// A part's props without its own place (PLACE), written as they are otherwise.+struct Placeless<'a>(&'a Map<String, Value>);++impl serde::Serialize for Placeless<'_> {+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {+ s.collect_map(self.0.iter().filter(|(k, _)| !PLACE.contains(&k.as_str())))+ }+}++/// 128 bits of a value's text: two SipHashes with fixed keys, told apart by a first byte.+fn id_of(text: &str) -> String {+ let half = |k: u8| {+ let mut h = std::collections::hash_map::DefaultHasher::new();+ k.hash(&mut h);+ text.hash(&mut h);+ h.finish()+ };+ format!("{:016x}{:016x}", half(0), half(1))+}++fn node_json(n: &Node3) -> Value {+ json!({ "k": &*n.kind, "p": &*n.props, "s": n.shape.as_deref(), "a": n.at.as_deref(), "c": n.kids.iter().map(node_json).collect::<Vec<_>>() })+}++fn node_of(v: &Value) -> R<Node3> {+ let Some(Value::Object(p)) = v.get("p") else { return Err("a material without props".into()) };+ let kids = v.get("c").and_then(Value::as_array).map_or(Ok(Vec::new()), |c| c.iter().map(node_of).collect::<R<Vec<_>>>())?;+ let s = |k: &str| v.get(k).and_then(Value::as_str).map(Arc::from);+ Ok(Node3 { kind: s("k").unwrap_or_else(|| Arc::from("")), props: Arc::new(p.clone()), shape: s("s"), at: s("a"), kids: kids.into() })+}++/// A frame's line: its parts, each its kind, the ids of its props, shape, placements and material, and its place's+/// 16 numbers as bits.+#[derive(serde::Deserialize)]+struct Frame<'a> {+ #[serde(borrow)]+ f: Vec<Row<'a>>,+}++#[derive(serde::Deserialize)]+struct Row<'a>(&'a str, &'a str, Option<&'a str>, Option<&'a str>, Option<&'a str>, [u32; 16]);++fn item(r: &Row, props: &HashMap<String, Props>, strs: &HashMap<String, Arc<str>>, nodes: &HashMap<String, Node3>) -> R<Item> {+ let p = props.get(r.1).ok_or("a part whose props weren't written")?.clone();+ let (shape, at, material) = (named(strs, r.2, "shape")?, named(strs, r.3, "placements")?, named(nodes, r.4, "material")?);+ Ok(Item { kind: kind_of(r.0), props: p, shape, at, material, world: Mat4::from_cols_array(&r.5.map(f32::from_bits)) })+}++/// What an id names, None for no id; an id that wasn't written is an error saying which of the part's it was.+fn named<T: Clone>(m: &HashMap<String, T>, id: Option<&str>, what: &str) -> R<Option<T>> {+ id.map(|id| m.get(id).cloned().ok_or(format!("a part whose {what} wasn't written"))).transpose()+}++/// A part's kind as the static name items_of gives it: the kinds are few, each kept once.+fn kind_of(k: &str) -> &'static str {+ static KINDS: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());+ let mut ks = KINDS.lock().unwrap();+ if let Some(s) = ks.iter().find(|s| **s == k) {+ return s;+ }+ let s: &'static str = Box::leak(k.to_string().into_boxed_str());+ ks.push(s);+ s+}++#[cfg(test)]+mod tests {+ use super::*;++ fn part(kind: &'static str, props: &Props, shape: Option<&Arc<str>>, x: f32) -> Item {+ let material = Some(Node3 { kind: Arc::from("meshStandardMaterial"), props: Arc::new(json!({"color": "#ff7a00"}).as_object().unwrap().clone()), shape: None, at: None, kids: Vec::new().into() });+ Item { kind, props: props.clone(), shape: shape.cloned(), at: None, material, world: Mat4::from_translation(bevy::math::Vec3::new(x, 0.1, -2.0)) }+ }++ #[test]+ fn parts_come_back_as_they_went_with_equal_props_shared() {+ let still: Props = Arc::new(json!({"name": "floor", "position": [0, 0, 0]}).as_object().unwrap().clone());+ let shape: Arc<str> = Arc::from("box(4, 0.1, 4)");+ let mut k = Kept::new().unwrap();+ // the floor unchanged across three frames; a card and a camera whose props are made again each frame as they move+ for x in [0.5f32, 0.75, 0.5] {+ let card: Props = Arc::new(json!({"name": "card", "position": [x, 1, 0], "rotation": [0, x, 0]}).as_object().unwrap().clone());+ let cam: Props = Arc::new(json!({"position": [x, 1, 5], "fov": 40}).as_object().unwrap().clone());+ k.put(&[part("mesh", &still, Some(&shape), 0.0), part("panel", &card, None, x), part("camera", &cam, None, 0.0)]).unwrap();+ }+ assert_eq!(k.len(), 3);+ let back = k.read().unwrap();+ assert_eq!(back.len(), 3);+ assert_eq!((back[1][0].kind, back[1][1].kind), ("mesh", "panel"));+ assert!(Arc::ptr_eq(&back[0][0].props, &back[2][0].props), "one floor's props, not three");+ assert_eq!(*back[2][0].props, *json!({"name": "floor"}).as_object().unwrap(), "a part's place is its matrix");+ assert!(Arc::ptr_eq(&back[0][1].props, &back[1][1].props) && Arc::ptr_eq(&back[1][1].props, &back[2][1].props), "a moving card's frames share one map");+ assert_eq!(back[1][2].props["position"][0], json!(0.75), "a camera keeps its own place: the checks read it");+ assert!(Arc::ptr_eq(&back[0][2].props, &back[2][2].props) && !Arc::ptr_eq(&back[0][2].props, &back[1][2].props));+ assert_eq!(back[0][0].shape.as_deref(), Some("box(4, 0.1, 4)"));+ assert_eq!(back[1][1].world.to_cols_array().map(f32::to_bits), Mat4::from_translation(bevy::math::Vec3::new(0.75, 0.1, -2.0)).to_cols_array().map(f32::to_bits));+ assert_eq!(back[2][1].material.as_ref().map(|m| m.props["color"].clone()), Some(json!("#ff7a00")));+ }+}diff --git a/io/trace/src/lib.rs b/io/trace/src/lib.rsindex 20af9257..1a0c46e7 100644--- a/io/trace/src/lib.rs+++ b/io/trace/src/lib.rs@@ -108,6 +108,26 @@ pub fn footprint_mb() -> f64 {0.0}+/// The memory the allocator holds freed handed back to the system now rather than when it gets round to it: macOS's+/// malloc kept a film's freed sound buffers (its master's copies of 7 minutes of sound) counted in its footprint until+/// well into the checks after it, 1.4 GB over its last frame's (SG4a). glibc's malloc_trim on Linux; nothing elsewhere.+pub fn give_back() {+ #[cfg(target_vendor = "apple")]+ unsafe {+ malloc_zone_pressure_relief(std::ptr::null_mut(), 0);+ }+ #[cfg(all(target_os = "linux", target_env = "gnu"))]+ unsafe {+ libc::malloc_trim(0);+ }+}++#[cfg(target_vendor = "apple")]+unsafe extern "C" {+ /// every zone's free memory returned to the system (`goal` 0: all it can), libmalloc's+ fn malloc_zone_pressure_relief(zone: *mut libc::c_void, goal: usize) -> usize;+}+/// Start recording this run of `app` (once; later calls do nothing). Returns the session folder.pub fn start(app: &str) -> Option<PathBuf> {let mut g = SESSION.lock().ok()?;diff --git a/runtime/export/Cargo.toml b/runtime/export/Cargo.tomlindex f95bd3c0..7f081245 100644--- a/runtime/export/Cargo.toml+++ b/runtime/export/Cargo.toml@@ -29,6 +29,7 @@ raea-io-media = { path = "../../io/media", default-features = false, features =raea-io-alpha = { path = "../../io/alpha" }raea-core-program = { path = "../../core/program" }raea-core-scene = { path = "../../core/scene" }+raea-io-kept = { path = "../../io/kept" }raea-runtime-scene = { path = "../scene" }raea-sys-contact = { path = "../../systems/contact" }# the staging checks a render runs at its end (docs/stage-guards.feature SG10-SG14)diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rsindex 55183442..5f3dd6bf 100644--- a/runtime/export/src/fed.rs+++ b/runtime/export/src/fed.rs@@ -214,6 +214,8 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, totlet 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)));+ // a video's 3D made live keeps each frame's parts for its end checks on disk, not its scene in memory (SG4a)+ let kept = std::cell::RefCell::new(LIVE_CLIPS.load(std::sync::atomic::Ordering::Relaxed).then(raea_io_kept::Kept::new).transpose()?);let t0 = std::time::Instant::now();let pic = raea_core_program::ir::Program { fps, width: w, height: h, frames: total, ..Default::default() };let frame_log = std::env::var_os("RAEA_FRAME_LOG").map(PathBuf::from);@@ -271,8 +273,8 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, totfr = raea_gpu_device::check::fed_checked(f, fr, raea_sys_page::wait_drawn, raea_sys_page::redraw_full, || { cx.manifest.as_mut().map(|m| m.pop()); bevy_fed(app.world_mut(), bevy, cx, &page, fps) })?;// a shot starts here (an outermost Sequence, a camera cut): the video's next segment does too (RR3)cuts.find(f, raea_runtime_page::shot_starts(app.world_mut()), matches!(&cx.scene3d, Some(e) if raea_sys_frame::shots::Cut::at(e.world(), f)));- // a video's 3D made live keeps each frame's scene for the clipping check- if LIVE_CLIPS.load(std::sync::atomic::Ordering::Relaxed) { fr.scene = scene_of(app.world_mut()); }+ // a video's 3D made live keeps each frame's parts (`kept`) for the checks at its end+ if let Some(k) = kept.borrow_mut().as_mut() { k.put(&raea_runtime_scene::items_of(&scene_of(app.world_mut())))?; }if cx.scene3d.is_none() && cx.live3d.is_none() && !cx.scene.is_empty() && BEVY_3D_PROBE.load(std::sync::atomic::Ordering::Relaxed) {return Err(FED_3D.into());}@@ -326,10 +328,15 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, totstd::fs::write(&path, out).map_err(|e| format!("{}: {e}", path.display()))?;}r?;+ raea_render::engine::mem_mark("end: the frames, sound and video done");let n = frames.borrow().len();// 3D parts passing through each other on screen: on stderr, and in the manifest for the legacy app's checkslet found = FED_CLIPPING.lock().unwrap().take().and_then(|t| t.join().ok());- let clipping = found.unwrap_or_else(|| scene::told_taking(&mut frames.borrow_mut(), cx.manifest.as_deref(), w, h, fps));+ let clipping = match (found, kept.into_inner()) {+ (Some(found), _) => found,+ (None, Some(k)) => scene::checked(frames.borrow().iter().map(|(f, _)| *f).zip(k.read()?).collect(), cx.manifest.as_deref(), w, h, fps),+ (None, None) => scene::told_taking(&mut frames.borrow_mut(), cx.manifest.as_deref(), w, h, fps),+ };write_manifest(cx, (w, h, fps, total), clipping, |cx| heard(&frames.borrow(), ¬es.borrow(), cx, fps))?;let ms = t0.elapsed().as_secs_f64() * 1e3 / n.max(1) as f64;Ok(format!("APPLIED {n} frames rendered to {} ({ms:.1} ms a frame, pages handed to raea-render on the GPU)", out.display()))diff --git a/runtime/export/src/scene.rs b/runtime/export/src/scene.rsindex 098da177..897485c0 100644--- a/runtime/export/src/scene.rs+++ b/runtime/export/src/scene.rs@@ -27,13 +27,13 @@ pub(crate) fn told_taking(frames: &mut [(i64, Frame)], page: Option<&[serde_jsonchecked(frames.iter_mut().map(|(n, f)| (*n, raea_runtime_scene::items_of(&std::mem::take(&mut f.scene)))).collect(), page, w, h, fps)}-fn checked(frames: Vec<(i64, Vec<raea_core_scene::Item>)>, page: Option<&[serde_json::Value]>, w: u32, h: u32, fps: f64) -> Vec<raea_core_facts::Finding> {+pub(crate) fn checked(frames: Vec<(i64, Vec<raea_core_scene::Item>)>, page: Option<&[serde_json::Value]>, w: u32, h: u32, fps: f64) -> Vec<raea_core_facts::Finding> {if frames.iter().all(|(_, its)| its.is_empty()) {return Vec::new();}// RAEA_MEM_MARKS: the footprint after each end step (raea-render's mem_mark)let mark = raea_render::engine::mem_mark;- mark("end checks: each frame's parts made");+ mark(&format!("end checks: each frame's parts made, {} in all", frames.iter().map(|(_, its)| its.len()).sum::<usize>()));let (nums, all): (Vec<i64>, Vec<_>) = frames.into_iter().unzip();*SEEN.lock().unwrap() = Some(raea_sys_stage::seen(&all, &nums, w, h));mark("end checks: what's on screen");diff --git a/systems/mix/Cargo.toml b/systems/mix/Cargo.tomlindex 311fa499..63c25ca5 100644--- a/systems/mix/Cargo.toml+++ b/systems/mix/Cargo.toml@@ -9,6 +9,7 @@ description = "raea's one mixer core: the same Firewheel graph plays live in the[dependencies]# the mix before the master: dialogue at one level, room tone at the joinsraea-sys-mix-level = { path = "level" }+raea-io-trace = { path = "../../io/trace" }# 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/level/src/joins.rs b/systems/mix/level/src/joins.rsindex c30a72f8..6bb6de0a 100644--- a/systems/mix/level/src/joins.rs+++ b/systems/mix/level/src/joins.rs@@ -67,13 +67,14 @@ pub fn gaps(rms: &[f64]) -> Vec<(usize, usize)> {/// `a` with each dropout filled by the room's tone: the quietest TONE of sound (not silence) in the LOOK before it,/// looped with 10 ms crossfades and faded in and out at the gap's edges. Its gaps are found as the master will play-/// it, `gain` dB up, where the check hears them. Unchanged where there's none.-pub fn filled(a: &Audio, gain: f64) -> Audio {+/// it, `gain` dB up, where the check hears them. `a` itself where there's none, not a copy of it (a 7-minute film's+/// sound is 169 MB, SG4a).+pub fn filled(a: &Audio, gain: f64) -> std::borrow::Cow<'_, Audio> {let hop = (a.rate as usize / 100).max(1);let rms: Vec<f64> = steps(a, hop).into_iter().map(|l| l + gain).collect();let found = gaps(&rms);if found.is_empty() {- return a.clone();+ return std::borrow::Cow::Borrowed(a);}let mut out = a.clone();let longest = (TONE * 100.0) as usize;@@ -107,7 +108,7 @@ pub fn filled(a: &Audio, gain: f64) -> Audio {}}}- out+ std::borrow::Cow::Owned(out)}#[cfg(test)]diff --git a/systems/mix/src/offline.rs b/systems/mix/src/offline.rsindex c950ca61..31c83140 100644--- a/systems/mix/src/offline.rs+++ b/systems/mix/src/offline.rs@@ -181,6 +181,9 @@ pub fn master_raw(raw: &raea_io_media::Audio, master: Option<(f64, f64)>) -> raeraea_io_media::Audio { rate: raw.rate, channels: vec![l, r] }}+/// An encoder's round trip (AAC on Apple), for the overshoot it puts back+pub type Encode<'a> = Option<&'a dyn Fn(&raea_io_media::Audio) -> Result<raea_io_media::Audio, String>>;+/// What raea masters a piece to when it has no <Mix>: the major platforms' loudness (LUFS) and a -1 dBTP ceilingpub const MIX: (f64, f64) = (-14.0, -1.0);@@ -189,7 +192,14 @@ pub const MIX: (f64, f64) = (-14.0, -1.0);/// the limiter at the ceiling, the ceiling lowered by any overshoot `encode` (an AAC round trip) puts back (twice at most);/// without one, MIX; the leveller (nodes::LEVEL) rounds the loud passages first, and the gain is made up for what it/// took. Returns the master it used and the mastered sound.-pub fn master_mix(raw: &raea_io_media::Audio, mix: Option<(f64, f64)>, encode: Option<&dyn Fn(&raea_io_media::Audio) -> Result<raea_io_media::Audio, String>>) -> (Option<(f64, f64)>, raea_io_media::Audio) {+pub fn master_mix(raw: &raea_io_media::Audio, mix: Option<(f64, f64)>, encode: Encode) -> (Option<(f64, f64)>, raea_io_media::Audio) {+ let out = mastered(raw, mix, encode);+ // its passes' copies of the whole sound, freed, handed back now (SG4a)+ raea_io_trace::give_back();+ out+}++fn mastered(raw: &raea_io_media::Audio, mix: Option<(f64, f64)>, encode: Encode) -> (Option<(f64, f64)>, raea_io_media::Audio) {// raea masters whatever it renders (11-19): without a <Mix>, to MIX's loudness and ceilinglet Some((lufs, ceiling)) = mix.or(Some(MIX)).filter(|_| raea_io_media::audio::lufs(raw).is_finite()) else { return (None, master_raw(raw, None)) };let mut gain = raea_io_media::audio::master_gained(raw, lufs, ceiling).1;diff --git a/tools/layers.toml b/tools/layers.tomlindex 1d5f479f..6b00943a 100644--- a/tools/layers.toml+++ b/tools/layers.toml@@ -33,6 +33,7 @@ raea-io-gen-core = "io"raea-io-gen-fit = "io"raea-io-home = "io"raea-io-codec = "io"+raea-io-kept = "io"raea-io-soft = "io"raea-io-av1 = "io"raea-io-ffmpeg = "io"diff --git a/vendor/muxide/src/muxer/mp4.rs b/vendor/muxide/src/muxer/mp4.rsindex a1ab32dc..0b09a594 100644--- a/vendor/muxide/src/muxer/mp4.rs+++ b/vendor/muxide/src/muxer/mp4.rs@@ -1,5 +1,5 @@use std::fmt;-use std::io::{self, Write};+use std::io::{self, Read, Seek, SeekFrom, Write};use crate::api::{AacProfile, AudioCodec, Metadata, VideoCodec};use crate::assert_invariant;@@ -42,6 +42,53 @@ pub struct Mp4Writer<Writer> {audio_last_delta: Option<u32>,finalized: bool,bytes_written: u64,+ /// where the samples' bytes wait for the end (raea patch, Spill)+ spill: Option<Spill>,+}++/// Samples' bytes kept in a temp file as they come rather than in memory, and read back one at a time as the file is+/// finished (raea patch, raea's docs/stage-guards.feature SG4a: the writer held every sample to the end, a 7-minute+/// film's 1.1 GB at once, after its encoder had kept them on disk). The file is gone when the process is (unlinked+/// once open on unix, delete-on-close on Windows). None when no temp file can be made: the samples stay in memory.+struct Spill {+ file: std::fs::File,+ end: u64,+}++impl Spill {+ fn new() -> Option<Spill> {+ static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+ let p = std::env::temp_dir().join(format!("muxide-{}-{}", std::process::id(), N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));+ let mut o = std::fs::OpenOptions::new();+ o.read(true).write(true).create_new(true);+ #[cfg(windows)]+ std::os::windows::fs::OpenOptionsExt::custom_flags(&mut o, 0x0400_0000); // FILE_FLAG_DELETE_ON_CLOSE+ let file = o.open(&p).ok()?;+ #[cfg(unix)]+ let _ = std::fs::remove_file(&p);+ Some(Spill { file, end: 0 })+ }+}++/// A sample's bytes kept: in the spill file when there is one (the bytes left empty, their offset given), else in memory.+fn keep(spill: &mut Option<Spill>, data: Vec<u8>) -> (Vec<u8>, Option<u64>) {+ if let Some(s) = spill.as_mut() {+ let at = s.end;+ if s.file.seek(SeekFrom::Start(at)).and_then(|_| s.file.write_all(&data)).is_ok() {+ s.end += data.len() as u64;+ return (Vec::new(), Some(at));+ }+ }+ (data, None)+}++/// A sample's bytes: from memory, or read back from the spill file into `buf`.+fn bytes<'a>(spill: &mut Option<Spill>, s: &'a SampleInfo, buf: &'a mut Vec<u8>) -> io::Result<&'a [u8]> {+ let (Some(at), Some(sp)) = (s.at, spill.as_mut()) else { return Ok(&s.data) };+ buf.resize(s.len, 0);+ sp.file.seek(SeekFrom::Start(at))?;+ sp.file.read_exact(buf)?;+ Ok(buf)}/// Simplified video track information used when writing the header.@@ -62,7 +109,10 @@ pub struct Mp4AudioTrack {struct SampleInfo {pts: u64,dts: u64, // Decode time (for B-frames: dts != pts)+ /// empty when the bytes are in the spill file, at `at` (raea patch)data: Vec<u8>,+ len: usize,+ at: Option<u64>,is_keyframe: bool,duration: Option<u32>,}@@ -97,7 +147,7 @@ impl SampleTables {}let sizes = samples.iter()- .map(|sample| sample.data.len() as u32)+ .map(|sample| sample.len as u32).collect();let keyframes = samples.iter()@@ -428,6 +478,7 @@ impl<Writer: Write> Mp4Writer<Writer> {audio_last_delta: None,finalized: false,bytes_written: 0,+ spill: Spill::new(),}}@@ -540,10 +591,14 @@ impl<Writer: Write> Mp4Writer<Writer> {return Err(Mp4WriterError::DurationOverflow);}+ let len = converted.len();+ let (data, at) = keep(&mut self.spill, converted);self.video_samples.push(SampleInfo {pts,dts,- data: converted,+ data,+ len,+ at,is_keyframe,duration: None,});@@ -616,10 +671,14 @@ impl<Writer: Write> Mp4Writer<Writer> {return Err(Mp4WriterError::DurationOverflow);}+ let len = sample_data.len();+ let (data, at) = keep(&mut self.spill, sample_data);self.audio_samples.push(SampleInfo {pts,dts: pts, // Audio: dts == pts (no B-frames)- data: sample_data,+ data,+ len,+ at,is_keyframe: false,duration: None,});@@ -671,6 +730,7 @@ impl<Writer: Write> Mp4Writer<Writer> {video_config: &VideoConfig,) -> io::Result<()> {let ftyp_box = build_ftyp_box();+ let mut buf = Vec::new();let ftyp_len = ftyp_box.len() as u32;Self::write_counted(&mut self.writer, &mut self.bytes_written, &ftyp_box)?;@@ -681,7 +741,7 @@ impl<Writer: Write> Mp4Writer<Writer> {let mut payload_size: u64 = 0;for sample in &self.video_samples {payload_size = payload_size- .checked_add(sample.data.len() as u64)+ .checked_add(sample.len as u64).ok_or_else(|| {io::Error::new(io::ErrorKind::InvalidData, "MP4 payload size overflow")})?;@@ -701,7 +761,7 @@ impl<Writer: Write> Mp4Writer<Writer> {)?;Self::write_counted(&mut self.writer, &mut self.bytes_written, b"mdat")?;for sample in &self.video_samples {- Self::write_counted(&mut self.writer, &mut self.bytes_written, &sample.data)?;+ Self::write_counted(&mut self.writer, &mut self.bytes_written, bytes(&mut self.spill, sample, &mut buf)?)?;}Some(ftyp_len + 8)} else {@@ -727,14 +787,14 @@ impl<Writer: Write> Mp4Writer<Writer> {let mut total_payload_size: u64 = 0;for sample in &self.video_samples {total_payload_size = total_payload_size- .checked_add(sample.data.len() as u64)+ .checked_add(sample.len as u64).ok_or_else(|| {io::Error::new(io::ErrorKind::InvalidData, "MP4 payload size overflow")})?;}for sample in &self.audio_samples {total_payload_size = total_payload_size- .checked_add(sample.data.len() as u64)+ .checked_add(sample.len as u64).ok_or_else(|| {io::Error::new(io::ErrorKind::InvalidData, "MP4 payload size overflow")})?;@@ -765,15 +825,15 @@ impl<Writer: Write> Mp4Writer<Writer> {TrackKind::Video => {video_chunk_offsets.push(cursor);let sample = &self.video_samples[idx];- let sample_len = sample.data.len() as u32;- Self::write_counted(&mut self.writer, &mut self.bytes_written, &sample.data)?;+ let sample_len = sample.len as u32;+ Self::write_counted(&mut self.writer, &mut self.bytes_written, bytes(&mut self.spill, sample, &mut buf)?)?;cursor += sample_len;}TrackKind::Audio => {audio_chunk_offsets.push(cursor);let sample = &self.audio_samples[idx];- let sample_len = sample.data.len() as u32;- Self::write_counted(&mut self.writer, &mut self.bytes_written, &sample.data)?;+ let sample_len = sample.len as u32;+ Self::write_counted(&mut self.writer, &mut self.bytes_written, bytes(&mut self.spill, sample, &mut buf)?)?;cursor += sample_len;}}@@ -813,20 +873,21 @@ impl<Writer: Write> Mp4Writer<Writer> {video_config: &VideoConfig,) -> io::Result<()> {let ftyp_box = build_ftyp_box();+ let mut buf = Vec::new();let ftyp_len = ftyp_box.len() as u64;// Calculate total mdat payload sizelet mut mdat_payload_size: u64 = 0;for sample in &self.video_samples {mdat_payload_size = mdat_payload_size- .checked_add(sample.data.len() as u64)+ .checked_add(sample.len as u64).ok_or_else(|| {io::Error::new(io::ErrorKind::InvalidData, "MP4 payload size overflow")})?;}for sample in &self.audio_samples {mdat_payload_size = mdat_payload_size- .checked_add(sample.data.len() as u64)+ .checked_add(sample.len as u64).ok_or_else(|| {io::Error::new(io::ErrorKind::InvalidData, "MP4 payload size overflow")})?;@@ -940,7 +1001,7 @@ impl<Writer: Write> Mp4Writer<Writer> {));}video_offsets.push(cursor as u32);- cursor += self.video_samples[*idx].data.len() as u64;+ cursor += self.video_samples[*idx].len as u64;}TrackKind::Audio => {if cursor > u32::MAX as u64 {@@ -950,7 +1011,7 @@ impl<Writer: Write> Mp4Writer<Writer> {));}audio_offsets.push(cursor as u32);- cursor += self.audio_samples[*idx].data.len() as u64;+ cursor += self.audio_samples[*idx].len as u64;}}}@@ -1027,21 +1088,21 @@ impl<Writer: Write> Mp4Writer<Writer> {Self::write_counted(&mut self.writer,&mut self.bytes_written,- &self.video_samples[idx].data,+ bytes(&mut self.spill, &self.video_samples[idx], &mut buf)?,)?;}TrackKind::Audio => {Self::write_counted(&mut self.writer,&mut self.bytes_written,- &self.audio_samples[idx].data,+ bytes(&mut self.spill, &self.audio_samples[idx], &mut buf)?,)?;}}}} else {for sample in &self.video_samples {- Self::write_counted(&mut self.writer, &mut self.bytes_written, &sample.data)?;+ Self::write_counted(&mut self.writer, &mut self.bytes_written, bytes(&mut self.spill, sample, &mut buf)?)?;}}