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 long render's encoded video and its sound are kept on disk, not in memory
shinyobjectzbc42f11ff2b8
diff --git a/io/apple/src/vt.rs b/io/apple/src/vt.rsindex c41caf46..32eca21e 100644--- a/io/apple/src/vt.rs+++ b/io/apple/src/vt.rs@@ -28,7 +28,8 @@ pub(crate) struct VtState {pub(crate) max_inflight: usize,pub(crate) kept: usize,pub(crate) discard: bool,- pub(crate) frames: Vec<Option<(Vec<u8>, bool)>>,+ /// each frame's sample on disk as it comes out, not in memory (SG4a: a 7-minute film's 1 GB)+ pub(crate) samples: Option<raea_io_codec::samples::Samples>,/// SPS and PPS, Annex B, from the first sample's format descriptionpub(crate) params: Option<Vec<u8>>,pub(crate) err: Option<String>,@@ -127,12 +128,12 @@ pub(crate) unsafe fn vt_output_pooled(refcon: *mut std::ffi::c_void, frame: *mut})();match got {Ok(f) => {- if st.frames.len() <= idx {- st.frames.resize(idx + 1, None);- }- st.kept += f.0.len();// RAEA_VT_DISCARD (diagnostics): drop the samples, to tell our storage from the encoder's- st.frames[idx] = Some(if st.discard { (Vec::new(), f.1) } else { f });+ let data: &[u8] = if st.discard { &[] } else { &f.0 };+ st.kept += data.len();+ if let Some(Err(e)) = st.samples.as_mut().map(|s| s.put(idx, data, f.1)) {+ st.err = Some(format!("VideoToolbox: {e}"));+ }}Err(e) => st.err = Some(e),}@@ -145,7 +146,7 @@ impl VtEncoder {pub(crate) fn new(out: &Path, o: &EncodeOpts, hevc10: bool) -> R<VtEncoder> {use objc2_core_foundation::{CFBoolean, CFDictionary, CFNumber, CFType};use objc2_video_toolbox::*;- let shared = Box::new(VtShared { st: std::sync::Mutex::new(VtState { inflight: 0, max_inflight: 0, kept: 0, discard: std::env::var_os("RAEA_VT_DISCARD").is_some(), frames: Vec::new(), params: None, err: None }), cv: std::sync::Condvar::new(), hevc: hevc10 });+ let shared = Box::new(VtShared { st: std::sync::Mutex::new(VtState { inflight: 0, max_inflight: 0, kept: 0, discard: std::env::var_os("RAEA_VT_DISCARD").is_some(), samples: Some(raea_io_codec::samples::Samples::new()?), params: None, err: None }), cv: std::sync::Condvar::new(), hevc: hevc10 });unsafe {let fmt = CFNumber::new_i32(if hevc10 {kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange@@ -428,7 +429,11 @@ impl VideoEncoder for VtEncoder {if let Some(e) = st.err.take() {return Err(e);}- let frames: Vec<(Vec<u8>, bool)> = std::mem::take(&mut st.frames).into_iter().enumerate().map(|(i, f)| f.ok_or(format!("VideoToolbox: frame {i} never came out"))).collect::<R<_>>()?;+ // each frame's sample on disk (samples::Samples), read back one at a time as the mux asks+ let frames = st.samples.take().ok_or("VideoToolbox: finished twice")?;+ if let Some(i) = frames.missing() {+ return Err(format!("VideoToolbox: frame {i} never came out"));+ }if frames.len() != self.n as usize {return Err(format!("VideoToolbox: {} of {} frames came out", frames.len(), self.n));}@@ -438,22 +443,24 @@ impl VideoEncoder for VtEncoder {if st.discard {return Ok(EncodeStats { frames: frames.len(), bytes: 0, video_codec: "h264 (VideoToolbox, discarded)".into(), audio_codec: String::new() });}+ let n = frames.len();+ let mut read = frames.reader()?;let codec = if self.hevc10 { muxide::api::VideoCodec::H265 } else { muxide::api::VideoCodec::H264 };let audio_codec = match audio {Some(a) => {let m4a = self.out.with_extension("aac.m4a");write_aac(&m4a, a)?;- raea_io_codec::remux::annexb_mux(codec, &frames, self.opts.width, self.opts.height, self.opts.fps, Some(&m4a), &self.out)?;+ raea_io_codec::remux::annexb_mux_from(codec, n, &mut read, self.opts.width, self.opts.height, self.opts.fps, Some(&m4a), &self.out)?;let _ = std::fs::remove_file(&m4a);"aac (AudioToolbox)".to_string()}None => {- raea_io_codec::remux::annexb_mux(codec, &frames, self.opts.width, self.opts.height, self.opts.fps, None, &self.out)?;+ raea_io_codec::remux::annexb_mux_from(codec, n, &mut read, self.opts.width, self.opts.height, self.opts.fps, None, &self.out)?;String::new()}};let video_codec = if self.hevc10 { "hevc main10 (VideoToolbox)" } else { "h264 (VideoToolbox)" };- Ok(EncodeStats { frames: frames.len(), bytes: std::fs::metadata(&self.out).map(|m| m.len()).unwrap_or(0), video_codec: video_codec.into(), audio_codec })+ Ok(EncodeStats { frames: n, bytes: std::fs::metadata(&self.out).map(|m| m.len()).unwrap_or(0), video_codec: video_codec.into(), audio_codec })}}diff --git a/io/av1/src/lib.rs b/io/av1/src/lib.rsindex a3bdc6cd..68b70998 100644--- a/io/av1/src/lib.rs+++ b/io/av1/src/lib.rs@@ -203,7 +203,8 @@ struct Encoder {ctx: rav1e::Context<u8>,opts: EncodeOpts,out: PathBuf,- packets: Vec<(u64, Vec<u8>, bool)>,+ /// each frame's packet on disk as it comes, not in memory (SG4a)+ packets: raea_io_codec::samples::Samples,pushed: usize,}@@ -211,11 +212,11 @@ impl Encoder {fn drain(&mut self) -> R<()> {loop {match self.ctx.receive_packet() {- Ok(p) => self.packets.push((- p.input_frameno,- p.data,+ Ok(p) => self.packets.put(+ p.input_frameno as usize,+ &p.data,p.frame_type == rav1e::prelude::FrameType::KEY,- )),+ )?,Err(rav1e::EncoderStatus::Encoded) => continue,Err(rav1e::EncoderStatus::NeedMoreData)| Err(rav1e::EncoderStatus::LimitReached) => return Ok(()),@@ -238,7 +239,6 @@ impl VideoEncoder for Encoder {fn finish(mut self: Box<Self>, audio: Option<&Audio>) -> R<EncodeStats> {self.ctx.flush();self.drain()?;- self.packets.sort_by_key(|p| p.0);let file = std::fs::File::create(&self.out).map_err(|e| e.to_string())?;let mut b = muxide::api::MuxerBuilder::new(std::io::BufWriter::new(file)).video(@@ -261,8 +261,12 @@ impl VideoEncoder for Encoder {}let mut m = b.build().map_err(|e| format!("muxide: {e}"))?;let mut ai = 0;- for (n, data, key) in &self.packets {- let pts = *n as f64 / self.opts.fps;+ let n = self.packets.len();+ let mut read = self.packets.reader()?;+ let mut data = Vec::new();+ for k in 0..n {+ let key = read(k, &mut data)?;+ let pts = k as f64 / self.opts.fps;if let Some(p) = &packets {while ai < p.len() && p[ai].0 < pts {m.write_audio(p[ai].0, &p[ai].1)@@ -270,7 +274,7 @@ impl VideoEncoder for Encoder {ai += 1;}}- m.write_video(pts, data, *key)+ m.write_video(pts, &data, key).map_err(|e| format!("muxide video: {e}"))?;}let end = self.pushed as f64 / self.opts.fps;@@ -362,7 +366,7 @@ impl Backend for Av1 {ctx,opts: o.clone(),out: out.to_path_buf(),- packets: Vec::new(),+ packets: raea_io_codec::samples::Samples::new()?,pushed: 0,}))}diff --git a/io/codec/src/lib.rs b/io/codec/src/lib.rsindex 1a7f86a9..a04e5327 100644--- a/io/codec/src/lib.rs+++ b/io/codec/src/lib.rs@@ -7,6 +7,7 @@ pub mod audio;pub mod mezz;#[cfg(feature = "mux")]pub mod remux;+pub mod samples;mod resample;pub mod yuv;diff --git a/io/codec/src/remux.rs b/io/codec/src/remux.rsindex af390f4c..fb608f8a 100644--- a/io/codec/src/remux.rs+++ b/io/codec/src/remux.rs@@ -209,8 +209,11 @@ pub fn h264_aac(video: &Path, aac: &Path, out: &Path, fps: f64) -> R<()> {Ok(())}-/// As annexb_aac, for `codec`'s Annex B frames (H.265: keyframes carry VPS, SPS and PPS).-pub fn annexb_mux(codec: muxide::api::VideoCodec, frames: &[(Vec<u8>, bool)], w: u32, h: u32, fps: f64, aac: Option<&Path>, out: &Path) -> R<()> {+/// As annexb_aac, for `codec`'s Annex B frames (H.265: keyframes carry VPS, SPS and PPS): `n` frames read one at a+/// time (`read(k, buf)` fills frame k's bytes and says whether it's a keyframe), so an encoder that keeps its samples+/// on disk (samples::Samples) never holds the whole video (SG4a: a 7-minute film's 1 GB).+#[allow(clippy::too_many_arguments)]+pub fn annexb_mux_from(codec: muxide::api::VideoCodec, n: usize, read: &mut dyn FnMut(usize, &mut Vec<u8>) -> R<bool>, w: u32, h: u32, fps: f64, aac: Option<&Path>, out: &Path) -> R<()> {let ab = match aac {Some(p) => std::fs::read(p).map_err(|e| e.to_string())?,None => Vec::new(),@@ -232,15 +235,17 @@ pub fn annexb_mux(codec: muxide::api::VideoCodec, frames: &[(Vec<u8>, bool)], w:.unwrap_or_default();audio.sort_by(|a, b| a.0.total_cmp(&b.0));let mut ai = 0;- for (k, (data, key)) in frames.iter().enumerate() {+ let mut data = Vec::new();+ for k in 0..n {+ let key = read(k, &mut data)?;let pts = k as f64 / fps;while ai < audio.len() && audio[ai].0 < pts {m.write_audio(audio[ai].0, &adts(audio[ai].1, rate, 1)).map_err(|e| format!("muxide audio: {e}"))?;ai += 1;}- m.write_video(pts, data, *key).map_err(|e| format!("muxide video: {e}"))?;+ m.write_video(pts, &data, key).map_err(|e| format!("muxide video: {e}"))?;}- let end = frames.len() as f64 / fps;+ let end = n as f64 / fps;for (pts, d) in audio[ai..].iter().filter(|x| x.0 < end) {m.write_audio(*pts, &adts(d, rate, 1)).map_err(|e| format!("muxide audio: {e}"))?;}diff --git a/io/codec/src/samples.rs b/io/codec/src/samples.rsnew file mode 100644index 00000000..5a2d1639--- /dev/null+++ b/io/codec/src/samples.rs@@ -0,0 +1,88 @@+//! 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.++use std::io::{Read, Seek, SeekFrom, Write};++type R<T> = Result<T, String>;++/// Each frame's sample: where it is in the file, its length, and whether it's a keyframe.+pub struct Samples {+ file: std::io::BufWriter<std::fs::File>,+ at: Vec<Option<(u64, u32, bool)>>,+ end: u64,+}++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);+ Ok(Samples { file: std::io::BufWriter::with_capacity(1 << 20, f), at: Vec::new(), end: 0 })+ }++ /// Frame `k`'s sample, in any order (an encoder hands them back as they finish).+ pub fn put(&mut self, k: usize, data: &[u8], key: bool) -> R<()> {+ self.file.write_all(data).map_err(|e| format!("keeping a sample on disk: {e}"))?;+ if self.at.len() <= k {+ self.at.resize(k + 1, None);+ }+ self.at[k] = Some((self.end, data.len() as u32, key));+ self.end += data.len() as u64;+ Ok(())+ }++ /// Frames up to the last one given.+ pub fn len(&self) -> usize {+ self.at.len()+ }++ pub fn is_empty(&self) -> bool {+ self.at.is_empty()+ }++ /// The first frame below len() with no sample.+ pub fn missing(&self) -> Option<usize> {+ self.at.iter().position(Option::is_none)+ }++ /// Frame k's sample into `buf`, and whether it's a keyframe: annexb_mux_from's reader.+ pub fn reader(self) -> R<impl FnMut(usize, &mut Vec<u8>) -> R<bool>> {+ let at = self.at;+ let mut f = self.file.into_inner().map_err(|e| format!("the samples on disk: {e}"))?;+ Ok(move |k: usize, buf: &mut Vec<u8>| -> R<bool> {+ let (o, n, key) = at.get(k).copied().flatten().ok_or(format!("frame {k} has no sample"))?;+ buf.resize(n as usize, 0);+ f.seek(SeekFrom::Start(o)).and_then(|_| f.read_exact(buf)).map_err(|e| format!("reading frame {k}'s sample back: {e}"))?;+ Ok(key)+ })+ }+}++#[cfg(test)]+mod tests {+ #[test]+ fn samples_come_back_by_frame_whatever_order_they_went_in() {+ let mut s = super::Samples::new().unwrap();+ s.put(1, b"second", false).unwrap();+ s.put(0, b"first!", true).unwrap();+ s.put(2, b"", false).unwrap();+ assert_eq!((s.len(), s.missing()), (3, None));+ let mut read = s.reader().unwrap();+ let mut buf = Vec::new();+ assert!(read(0, &mut buf).unwrap() && buf == b"first!");+ assert!(!read(1, &mut buf).unwrap() && buf == b"second");+ assert!(!read(2, &mut buf).unwrap() && buf.is_empty());+ assert!(read(3, &mut buf).is_err());+ let mut gap = super::Samples::new().unwrap();+ gap.put(2, b"x", true).unwrap();+ assert_eq!(gap.missing(), Some(0));+ }+}diff --git a/io/soft/src/h264.rs b/io/soft/src/h264.rsindex 047d7b50..89622e3c 100644--- a/io/soft/src/h264.rs+++ b/io/soft/src/h264.rs@@ -125,7 +125,8 @@ pub(crate) struct Encoder {pub(crate) enc: H264Encoder,pub(crate) opts: EncodeOpts,pub(crate) out: PathBuf,- pub(crate) frames: Vec<(Vec<u8>, bool)>,+ /// each frame's sample on disk as it's made, not in memory (SG4a)+ pub(crate) samples: raea_io_codec::samples::Samples,}#[cfg(feature = "h264")]@@ -140,7 +141,8 @@ impl VideoEncoder for Encoder {self.push_i420(&y, &u, &v)}fn finish(self: Box<Self>, audio: Option<&Audio>) -> R<EncodeStats> {- mux_h264(&self.out, &self.opts, &self.frames, audio)+ let n = self.samples.len();+ mux_h264(&self.out, &self.opts, n, &mut self.samples.reader()?, audio)}}@@ -157,16 +159,18 @@ impl Encoder {bs.frame_type(),openh264::encoder::FrameType::IDR | openh264::encoder::FrameType::I);- self.frames.push((bs.to_vec(), key));- Ok(())+ let k = self.samples.len();+ self.samples.put(k, &bs.to_vec(), key)}}-/// H.264 samples (Annex B, one per frame, display order, with key flags) and the audio columns (as Opus) into an MP4.+/// `n` H.264 samples (Annex B, one per frame, display order), each read as it's muxed (`read(k, buf)` fills frame k's+/// and says whether it's a keyframe), and the audio columns (as Opus) into an MP4.pub fn mux_h264(out: &Path,opts: &EncodeOpts,- frames: &[(Vec<u8>, bool)],+ n: usize,+ read: &mut dyn FnMut(usize, &mut Vec<u8>) -> R<bool>,audio: Option<&Audio>,) -> R<EncodeStats> {let file = std::fs::File::create(&out).map_err(|e| e.to_string())?;@@ -192,7 +196,9 @@ pub fn mux_h264(let mut m = b.build().map_err(|e| format!("muxide: {e}"))?;// interleave by timelet mut ai = 0;- for (k, (data, key)) in frames.iter().enumerate() {+ let mut data = Vec::new();+ for k in 0..n {+ let key = read(k, &mut data)?;let pts = k as f64 / opts.fps;if let Some(p) = &packets {while ai < p.len() && p[ai].0 < pts {@@ -201,10 +207,10 @@ pub fn mux_h264(ai += 1;}}- m.write_video(pts, data, *key)+ m.write_video(pts, &data, key).map_err(|e| format!("muxide video: {e}"))?;}- let end = frames.len() as f64 / opts.fps;+ let end = n as f64 / opts.fps;if let Some(p) = &packets {for (pts, d) in p[ai..].iter().filter(|x| x.0 < end) {m.write_audio(*pts, d)@@ -213,7 +219,7 @@ pub fn mux_h264(}m.finish().map_err(|e| format!("muxide: {e}"))?;Ok(EncodeStats {- frames: frames.len(),+ frames: n,bytes: std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0),video_codec: "h264 (openh264)".into(),audio_codec: if audio.is_some() {diff --git a/io/soft/src/lib.rs b/io/soft/src/lib.rsindex 0c500668..4ab1fbb9 100644--- a/io/soft/src/lib.rs+++ b/io/soft/src/lib.rs@@ -297,5 +297,5 @@ pub fn h264_encoder(out: &Path, o: &EncodeOpts, intra_qp: Option<u8>) -> R<Box<d};let enc = H264Encoder::with_api_config(OpenH264API::from_source(), config).map_err(|e| format!("openh264: {e}"))?;let _ = std::io::stdout().flush();- Ok(Box::new(Encoder { enc, opts: o.clone(), out: out.to_path_buf(), frames: Vec::new() }))+ Ok(Box::new(Encoder { enc, opts: o.clone(), out: out.to_path_buf(), samples: raea_io_codec::samples::Samples::new()? }))}diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rsindex dd0057ce..55183442 100644--- a/runtime/export/src/fed.rs+++ b/runtime/export/src/fed.rs@@ -213,7 +213,7 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, totlet 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)));+ let streamer = std::cell::RefCell::new(Some(raea_sys_mix::offline::Streamer::start(fps, total.max(0) as usize)));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);diff --git a/systems/mix/src/offline.rs b/systems/mix/src/offline.rsindex e777c0d5..c950ca61 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);+ let s = Streamer::start(fps, frames.len());for c in frames {s.push(c.clone());}@@ -230,7 +230,8 @@ pub struct Streamer {}impl Streamer {- pub fn start(fps: f64) -> 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 {let (tx, rx) = std::sync::mpsc::channel::<Cue>();let done = std::thread::Builder::new().name("raea mixer bounce".into())@@ -238,18 +239,21 @@ impl Streamer {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:?}"))?;- let mut out: Vec<f32> = Vec::new();+ // 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;for cue in rx {e.feed(f, &cue, 0)?;- let end = e.score.t(f + 1).max(0) as usize;- let start = out.len() / 2;- out.resize(end * 2, 0.0);- e.pull(&mut out[start * 2..end * 2])?;+ let n = (e.score.t(f + 1).max(0) as usize).saturating_sub(l.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;}- let l: Vec<f32> = out.iter().step_by(2).copied().collect();- let r: Vec<f32> = out.iter().skip(1).step_by(2).copied().collect();Ok(raea_io_media::Audio { rate: RATE, channels: vec![l, r] })}).expect("bounce thread");