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
RR3: in progress. A whole video made as shot segments and joined by stream copy, behind RAEA_SEGMENTS=1 until RR3's gates are measured. raea-runtime-segments: a new encoder run (unsigned) at each cut once the segment before holds a second of frames (split.rs), the whole wrapped by the signer so the export is one file with one watermark id, signed once after the join (encode.rs); the join reads the segments' MP4s with re_mp4 (H.264/HEVC to Annex B with their parameter sets ahead of each keyframe, AV1 OBUs as they are) and writes one with muxide, the sound laid under once from the backend's new Backend::sound (AAC on Apple, Opus on soft and av1) (join.rs). Cuts come from each frame of the fed render (an outermost Sequence's data-raea-start, raea-runtime-page shot_starts; the engine's camera cut, raea_sys_frame::shots::Cut set in pre_step) and the timeline's Shots up front. io-codec gains SoundTrack, remux::aac_track and hvcc_params; io-media backend_unsigned and a public sign::wrap. Benches: film.tsx's cut and cut-long compositions, pages.tsx, rr3.sh (segmented against one run: SSIM >= 0.999 and VMAF >= 99 per frame; join under 1 s on 3,600 frames). Tests: two segments joined are one video with one sound and the segments' own bytes; the encoder splits at cuts but not after a short shot
shinyobjectze50c22064fb9
diff --git a/Cargo.lock b/Cargo.lockindex a89daf2a..9a236c45 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15209,6 +15209,7 @@ dependencies = ["raea-io-net","raea-page","raea-render",+ "raea-runtime-segments","raea-runtime-view","raea-sys-frame","raea-sys-k",@@ -15490,6 +15491,16 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-runtime-segments"+version = "0.1.0"+dependencies = [+ "muxide",+ "raea-io-codec",+ "raea-io-media",+ "re_mp4",+]+[[package]]name = "raea-runtime-shared"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 2397ec17..5bac56a2 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -150,6 +150,7 @@ members = ["runtime/view","runtime/world","runtime/encode",+ "runtime/segments","runtime/plugins","runtime/input","tools/perceive",diff --git a/apps/media/src/command.rs b/apps/media/src/command.rsindex 826fa556..22240233 100644--- a/apps/media/src/command.rs+++ b/apps/media/src/command.rs@@ -53,7 +53,7 @@ fn run(args: Vec<String>) {"render" => {let out = PathBuf::from(flag("-o").unwrap_or_else(|| fail("render needs -o OUT.mp4|DIR")));let frames = flag("--at").map(|at| at.split(',').map(|f| f.trim().parse().unwrap_or_else(|_| fail(format!("bad frame {f}")))).collect());- let opts = raea_runtime_encode::RenderOpts { frames, codec: flag("--codec"), kbps: flag("--kbps").and_then(|k| k.parse().ok()), quality: flag("--quality").map(|q| raea_io_media::parse_quality(&q).unwrap_or_else(|e| fail(e))), ssim: flag_on("--ssim"), sound: None, ten_bit: flag_on("--10bit"), alpha: flag_on("--alpha") };+ let opts = raea_runtime_encode::RenderOpts { frames, codec: flag("--codec"), kbps: flag("--kbps").and_then(|k| k.parse().ok()), quality: flag("--quality").map(|q| raea_io_media::parse_quality(&q).unwrap_or_else(|e| fail(e))), ssim: flag_on("--ssim"), sound: None, ten_bit: flag_on("--10bit"), alpha: flag_on("--alpha"), ..Default::default() };if opts.alpha && out.extension().is_some_and(|x| x != "png") {fail("--alpha writes PNGs (OUT.png or a folder): video here is H.264 or HEVC, which hold no alpha");}diff --git a/bench/rerender/film.tsx b/bench/rerender/film.tsxindex c247c92e..dae4d8f5 100644--- a/bench/rerender/film.tsx+++ b/bench/rerender/film.tsx@@ -1,16 +1,35 @@// RR0's film (docs/rerender.feature): six 5 s shots at 1920x1080, 30 fps (900 frames), each with its own look and-// camera, on one procedural set (no media files, so it renders the same on macOS, Windows and Linux). Two forms:+// camera, on one procedural set (no media files, so it renders the same on macOS, Windows and Linux). Its forms:// "film" one composition, one camera that jumps at the cuts and a look that changes at every cut: what// RR1 makes render correctly (before RR1 a render holds the first frame's look for all six)// "shot-1".."shot-6" each shot as its own composition, as agents split films today; bench.sh renders these as// chunks and joins them, the baseline the overhaul is measured against+// "cut" the film with each shot a Sequence of its own, so its timeline knows the cuts (RR3: the video+// splits into segments there); the same frames as "film"+// "cut-long" "cut" four times over, 2 minutes (3,600 frames): RR3's join is timed on it// Shot 4 (noir) is the one change.sh edits, as a note would.-import { Composition, registerRoot } from "raea";+import { Composition, Sequence, registerRoot } from "raea";import { FPS, Film, SHOT, SHOTS, one } from "./shots";+const ONE = SHOTS.map((_, k) => one(k));+/** `n` shots in turn, each a Sequence, the six over and over. */+const cut = (n: number) =>+ function Cut() {+ return (+ <>+ {Array.from({ length: n }, (_, i) => {+ const Shot = ONE[i % 6];+ return <Sequence key={i} from={i * SHOT} durationInFrames={SHOT}><Shot /></Sequence>;+ })}+ </>+ );+ };+registerRoot(() => (<><Composition id="film" component={Film} width={1920} height={1080} fps={FPS} durationInFrames={SHOT * 6} />{SHOTS.map((_, k) => <Composition key={k} id={`shot-${k + 1}`} component={one(k)} width={1920} height={1080} fps={FPS} durationInFrames={SHOT} />)}+ <Composition id="cut" component={cut(6)} width={1920} height={1080} fps={FPS} durationInFrames={SHOT * 6} />+ <Composition id="cut-long" component={cut(24)} width={1920} height={1080} fps={FPS} durationInFrames={SHOT * 24} /></>));diff --git a/bench/rerender/pages.tsx b/bench/rerender/pages.tsxnew file mode 100644index 00000000..8ecd40a6--- /dev/null+++ b/bench/rerender/pages.tsx@@ -0,0 +1,32 @@+// RR3's page check (rr3.sh): a composition with no 3D whose shots are Sequences, three 3 s title cards at 1280x720,+// 30 fps (270 frames). Its video splits into a segment at each Sequence's start.+import { AbsoluteFill, Composition, Sequence, interpolate, registerRoot, useCurrentFrame } from "raea";++const CARDS = [+ { title: "One", bg: "#1d3557" },+ { title: "Two", bg: "#e63946" },+ { title: "Three", bg: "#2a9d8f" },+];++function Card({ title, bg }: { title: string; bg: string }) {+ const f = useCurrentFrame();+ return (+ <AbsoluteFill style={{ background: bg, alignItems: "center", justifyContent: "center" }}>+ <div style={{ fontFamily: "Helvetica, Arial, sans-serif", fontSize: 140, fontWeight: 700, color: "#fff", transform: `translateY(${interpolate(f, [0, 30], [40, 0], { extrapolateRight: "clamp" })}px)` }}>{title}</div>+ </AbsoluteFill>+ );+}++function Pages() {+ return (+ <>+ {CARDS.map((c, i) => (+ <Sequence key={i} from={i * 90} durationInFrames={90}>+ <Card {...c} />+ </Sequence>+ ))}+ </>+ );+}++registerRoot(() => <Composition id="pages" component={Pages} width={1280} height={720} fps={30} durationInFrames={270} />);diff --git a/bench/rerender/rr3.sh b/bench/rerender/rr3.shnew file mode 100644index 00000000..8c70f53e--- /dev/null+++ b/bench/rerender/rr3.sh@@ -0,0 +1,81 @@+#!/usr/bin/env bash+# RR3 (docs/rerender.feature): a video is made of shot segments, joined without encoding again. Three checks, each+# writing OUT/<check>.json:+# equal film.tsx's "cut" (RR0's film, each shot a Sequence) rendered as segments and in one run (RAEA_SEGMENTS=0) at+# the same --quality: the segmented file's frames against the one run's, SSIM on every frame (>= 0.999) and+# VMAF over the film (>= 99); how many segments, and both render times+# join "cut-long" (the film four times over: 2 minutes, 3,600 frames at 1080p) rendered as segments: the join's+# time from RAEA_SEGMENTS_TRACE (< 1 s), and the frame count read back+# page a composition without 3D whose Sequences are its shots (bench/rerender/pages.tsx): its segments+# bench/rerender/rr3.sh [OUT] [CHECKS]+# RAEA_BIN the raea to run (target/release/raea)+# QUALITY the --quality both renders take (high)+# CHECKS "equal join page" by default+# Exits 1 when a check fails.+set -u+cd "$(dirname "$0")/../.." || exit 2+ROOT=$PWD+BIN=${RAEA_BIN:-$ROOT/target/release/raea}+OUT=${1:-${TMPDIR:-/tmp}/raea-rr3}+CHECKS=${2:-equal join page}+Q=${QUALITY:-high}+FILM=$ROOT/bench/rerender/film.tsx+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0 RAEA_SEGMENTS_TRACE=1 RAEA_AUDIO_MUTE=1+mkdir -p "$OUT"+fail=0++now() { perl -MTime::HiRes=time -e 'printf "%.3f", time'; }+frames() { ffprobe -v error -count_packets -select_streams v:0 -show_entries stream=nb_read_packets -of csv=p=0 "$1"; }+# the trace's line: "N frames in K segments joined in T ms"+segs() { sed -n 's/.*frames in \([0-9]*\) segments joined in \([0-9.]*\) ms.*/\1 \2/p' "$1" | tail -1; }++# render SRC ID OUT.mp4 [ENV...]: prints its seconds, its log beside it+render() {+ local src=$1 id=$2 out=$3 t0 t1+ shift 3+ t0=$(now)+ env "$@" "$BIN" render "$src" --composition "$id" --quality "$Q" -o "$out" > "$out.log" 2>&1 || { echo "$id failed: $(grep -E 'REFUSED|error' "$out.log" | head -2)" >&2; return 1; }+ t1=$(now)+ echo "$t0 $t1" | awk '{printf "%.1f", $2 - $1}'+}++equal() {+ local ts t1 seg one min vmaf n+ ts=$(render "$FILM" cut "$OUT/cut-seg.mp4") || return 1+ t1=$(render "$FILM" cut "$OUT/cut-one.mp4" RAEA_SEGMENTS=0) || return 1+ read -r n _ <<< "$(segs "$OUT/cut-seg.mp4.log")"+ ffmpeg -hide_banner -nostats -i "$OUT/cut-seg.mp4" -i "$OUT/cut-one.mp4" -lavfi "ssim=stats_file=$OUT/ssim.txt" -f null - > /dev/null 2>&1+ min=$(sed -n 's/.*All:\([0-9.]*\).*/\1/p' "$OUT/ssim.txt" | sort -n | head -1)+ seg=$(awk '{for (i = 1; i <= NF; i++) if ($i ~ /^All:/) { split($i, a, ":"); if (a[2] < 0.999) n++ }} END {print n + 0}' "$OUT/ssim.txt")+ ffmpeg -hide_banner -nostats -i "$OUT/cut-seg.mp4" -i "$OUT/cut-one.mp4" -lavfi "libvmaf=log_fmt=json:log_path=$OUT/vmaf.json" -f null - > /dev/null 2>&1+ vmaf=$(jq '.pooled_metrics.vmaf.mean' "$OUT/vmaf.json")+ one=$(frames "$OUT/cut-seg.mp4")+ printf '{"segments": %s, "frames": %s, "ssim_min": %s, "frames_under_0.999": %s, "vmaf": %s, "seconds_segmented": %s, "seconds_one_run": %s}\n' \+ "${n:-0}" "$one" "$min" "$seg" "$vmaf" "$ts" "$t1" | tee "$OUT/equal.json"+ [ "${n:-0}" -ge 2 ] && [ "$seg" = 0 ] && awk -v v="$vmaf" 'BEGIN {exit !(v >= 99)}' && [ "$one" = 900 ]+}++join() {+ local t n ms got+ t=$(render "$FILM" cut-long "$OUT/long.mp4") || return 1+ read -r n ms <<< "$(segs "$OUT/long.mp4.log")"+ got=$(frames "$OUT/long.mp4")+ printf '{"segments": %s, "join_ms": %s, "frames": %s, "seconds": %s}\n' "${n:-0}" "${ms:-null}" "$got" "$t" | tee "$OUT/join.json"+ [ "$got" = 3600 ] && awk -v m="${ms:-99999}" 'BEGIN {exit !(m < 1000)}'+}++page() {+ local t n got+ t=$(render "$ROOT/bench/rerender/pages.tsx" pages "$OUT/pages.mp4") || return 1+ read -r n _ <<< "$(segs "$OUT/pages.mp4.log")"+ got=$(frames "$OUT/pages.mp4")+ printf '{"segments": %s, "frames": %s, "seconds": %s}\n' "${n:-0}" "$got" "$t" | tee "$OUT/page.json"+ [ "${n:-0}" = 3 ] && [ "$got" = 270 ]+}++for c in $CHECKS; do+ echo "== $c"+ if ! "$c"; then echo "FAIL $c" >&2; fail=1; fi+done+rm -f "$OUT"/*.mp4+exit $faildiff --git a/engine/render/src/engine.rs b/engine/render/src/engine.rsindex 5f31885b..23e87099 100644--- a/engine/render/src/engine.rs+++ b/engine/render/src/engine.rs@@ -269,8 +269,9 @@ impl Engine {let f = self.app.world().resource::<Clock>().0;let moved = self.app.world_mut().remove_resource::<raea_sys_frame::shots::Moved>().is_some();let cut = moved || self.app.world().get_resource::<raea_sys_frame::shots::Shots>().is_some_and(|s| s.starts(f));- #[cfg(feature = "raytracing")]if cut {+ self.app.world_mut().insert_resource(raea_sys_frame::shots::Cut(f));+ #[cfg(feature = "raytracing")]raea_render_raytrace::cut(self.app.world_mut());}if !self.prestep || f <= 0 || (plugins::active(self.app.world()) && !cut) {diff --git a/io/apple/src/lib.rs b/io/apple/src/lib.rsindex 71b077bc..5207e15f 100644--- a/io/apple/src/lib.rs+++ b/io/apple/src/lib.rs@@ -67,6 +67,14 @@ impl Backend for Apple {fn encoder_10bit(&self, out: &Path, o: &EncodeOpts) -> R<Box<dyn VideoEncoder>> {objc2::rc::autoreleasepool(|_| VtEncoder::new(out, o, true).map(|e| Box::new(e) as Box<dyn VideoEncoder>))}+ /// AAC through AudioToolbox, as VtEncoder lays it under its video+ fn sound(&self, a: &Audio) -> R<raea_io_codec::SoundTrack> {+ let p = std::env::temp_dir().join(format!("raea-sound-{}-{:?}.m4a", std::process::id(), std::thread::current().id()));+ objc2::rc::autoreleasepool(|_| write_aac(&p, a))?;+ let t = raea_io_codec::remux::aac_track(&p);+ let _ = std::fs::remove_file(&p);+ t+ }}// A decoder moves to another thread whole and is used by one thread at a time (open_video_send): AVURLAsset anddiff --git a/io/av1/src/lib.rs b/io/av1/src/lib.rsindex b5bf6944..a3bdc6cd 100644--- a/io/av1/src/lib.rs+++ b/io/av1/src/lib.rs@@ -366,4 +366,8 @@ impl Backend for Av1 {pushed: 0,}))}+ /// Opus at 48 kHz, as the encoder lays it under its video+ fn sound(&self, a: &Audio) -> R<raea_io_codec::SoundTrack> {+ Ok(raea_io_codec::SoundTrack { aac: false, rate: 48000, channels: a.channels.len().clamp(1, 2) as u16, priming: 0, packets: raea_io_soft::opus_packets(a)? })+ }}diff --git a/io/codec/src/lib.rs b/io/codec/src/lib.rsindex 97069768..1a7f86a9 100644--- a/io/codec/src/lib.rs+++ b/io/codec/src/lib.rs@@ -205,6 +205,22 @@ pub trait Backend {fn encoder_10bit(&self, _out: &Path, _opts: &EncodeOpts) -> R<Box<dyn VideoEncoder>> {Err(format!("the {} backend has no 10-bit encoder", self.name()))}+ /// `a` encoded as this backend's encoders lay sound under their video (VideoEncoder::finish), for a video put+ /// together from parts encoded apart (raea-runtime-segments' join).+ fn sound(&self, _a: &Audio) -> R<SoundTrack> {+ Err(format!("the {} backend lays no sound under a joined video", self.name()))+ }+}++/// A sound encoded for a muxer, as a backend lays it under its video: AAC (each packet an ADTS frame, after `priming`+/// samples of the encoder's own silence) or Opus, each packet with its time in seconds.+#[derive(Debug, Clone, Default)]+pub struct SoundTrack {+ pub aac: bool,+ pub rate: u32,+ pub channels: u16,+ pub priming: u32,+ pub packets: Vec<(f64, Vec<u8>)>,}diff --git a/io/codec/src/remux.rs b/io/codec/src/remux.rsindex b2d73780..791346a9 100644--- a/io/codec/src/remux.rs+++ b/io/codec/src/remux.rs@@ -22,7 +22,38 @@ pub fn avcc_to_annexb(sample: &[u8], prefix: Option<&[u8]>) -> Vec<u8> {out}-fn avcc_params(avcc: &[u8]) -> Vec<u8> {+/// An hvcC's parameter sets (VPS, SPS, PPS and any other arrays it holds) as Annex B, to go before a keyframe.+pub fn hvcc_params(hvcc: &[u8]) -> Vec<u8> {+ let mut out = Vec::new();+ let mut i = 23;+ for _ in 0..hvcc.get(22).copied().unwrap_or(0) {+ let Some(c) = hvcc.get(i + 1..i + 3) else { break };+ i += 3;+ for _ in 0..u16::from_be_bytes([c[0], c[1]]) {+ let Some(n) = hvcc.get(i..i + 2).map(|l| u16::from_be_bytes([l[0], l[1]]) as usize) else { return out };+ let Some(nal) = hvcc.get(i + 2..i + 2 + n) else { return out };+ out.extend_from_slice(&[0, 0, 0, 1]);+ out.extend_from_slice(nal);+ i += 2 + n;+ }+ }+ out+}++/// An .m4a's AAC as a muxer takes it (Backend::sound): each packet an ADTS frame with its time, its channels and its+/// encoder's priming.+pub fn aac_track(m4a: &Path) -> R<crate::SoundTrack> {+ let ab = std::fs::read(m4a).map_err(|e| format!("{}: {e}", m4a.display()))?;+ let am = re_mp4::Mp4::read_bytes(&ab).map_err(|e| format!("{}: {e}", m4a.display()))?;+ let (_, at) = am.tracks().iter().find(|(_, t)| t.kind == Some(re_mp4::TrackKind::Audio)).ok_or("no audio")?;+ let rate = at.timescale as u32;+ let mut packets: Vec<(f64, Vec<u8>)> = at.samples.iter().map(|s| (s.composition_timestamp as f64 / s.timescale as f64, adts(&ab[s.byte_range()], rate, 1))).collect();+ packets.sort_by(|a, b| a.0.total_cmp(&b.0));+ Ok(crate::SoundTrack { aac: true, rate, channels: aac_channels(&am, at), priming: aac_priming(&ab), packets })+}++/// An avcC's SPS and PPS as Annex B, to go before a keyframe.+pub fn avcc_params(avcc: &[u8]) -> Vec<u8> {let mut out = Vec::new();let mut i = 5;let nsps = (avcc[i] & 0x1f) as usize;diff --git a/io/media/src/lib.rs b/io/media/src/lib.rsindex af2f145f..c3eb6a55 100644--- a/io/media/src/lib.rs+++ b/io/media/src/lib.rs@@ -45,6 +45,11 @@ pub fn probe_seconds(path: &Path) -> Option<f64> {/// The backends compiled into this build, by name.pub fn backends() -> Vec<Box<dyn Backend>> {+ // an installed signer wraps each backend, so its encoders sign and mark what they write (sign.rs)+ unsigned().into_iter().map(sign::wrap).collect()+}++fn unsigned() -> Vec<Box<dyn Backend>> {#[allow(unused_mut)] // with no backend features, nothing is pushedlet mut v: Vec<Box<dyn Backend>> = vec![Box::new(ffmpeg::Ffmpeg)];#[cfg(feature = "soft-audio")]@@ -53,8 +58,13 @@ pub fn backends() -> Vec<Box<dyn Backend>> {v.push(Box::new(apple::Apple));#[cfg(feature = "av1")]v.push(Box::new(av1::Av1));- // an installed signer wraps each backend, so its encoders sign and mark what they write (sign.rs)- v.into_iter().map(sign::wrap).collect()+ v+}++/// The backend named, not wrapped by the signer: for an encoder whose parts are signed as one once they're put+/// together (raea-runtime-segments' segments, the joined video signed).+pub fn backend_unsigned(name: &str) -> R<Box<dyn Backend>> {+ unsigned().into_iter().find(|b| b.name() == name).ok_or(format!("no backend {name:?} in this build"))}/// Signing what raea writes (Content Credentials, the watermark): a hook a signer installs from outside this cratediff --git a/io/media/src/sign.rs b/io/media/src/sign.rsindex 54dfcf0a..5416810f 100644--- a/io/media/src/sign.rs+++ b/io/media/src/sign.rs@@ -35,7 +35,9 @@ pub fn signs() -> bool {SIGNER.get().is_some()}-pub(crate) fn wrap(backend: Box<dyn Backend>) -> Box<dyn Backend> {+/// `backend` wrapped by the signer when one is installed: each encoder it makes signs and marks what it finishes as one+/// export (backends() wraps each of its own; raea-runtime-segments wraps its segmented encoder whole).+pub fn wrap(backend: Box<dyn Backend>) -> Box<dyn Backend> {match SIGNER.get() {Some(s) => s.wrap(backend),None => backend,diff --git a/io/soft/src/lib.rs b/io/soft/src/lib.rsindex 3d250d96..3802771c 100644--- a/io/soft/src/lib.rs+++ b/io/soft/src/lib.rs@@ -208,6 +208,10 @@ impl Backend for Soft {fn encoder(&self, out: &Path, o: &EncodeOpts) -> R<Box<dyn VideoEncoder>> {h264_encoder(out, o, None)}+ /// Opus at 48 kHz, as mux_h264 lays it under its video+ fn sound(&self, a: &Audio) -> R<raea_io_codec::SoundTrack> {+ Ok(raea_io_codec::SoundTrack { aac: false, rate: 48000, channels: a.channels.len().clamp(1, 2) as u16, priming: 0, packets: opus_packets(a)? })+ }}/// An H.264 MP4 (no B-frames) as a decoder.diff --git a/runtime/encode/Cargo.toml b/runtime/encode/Cargo.tomlindex 767b9b06..63fb3515 100644--- a/runtime/encode/Cargo.toml+++ b/runtime/encode/Cargo.toml@@ -11,6 +11,7 @@ raea-render = { path = "../../engine/render", default-features = false, featuresraea-core-program = { path = "../../core/program" }raea-sys-frame = { path = "../../systems/frame", features = ["native"] }raea-runtime-view = { path = "../view" }+raea-runtime-segments = { path = "../segments" }raea-page = { path = "../../engine/page" }raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }raea-io-home = { path = "../../io/home" }diff --git a/runtime/encode/src/lib.rs b/runtime/encode/src/lib.rsindex d06a6c09..3441c531 100644--- a/runtime/encode/src/lib.rs+++ b/runtime/encode/src/lib.rs@@ -39,8 +39,13 @@ pub struct RenderOpts {pub ten_bit: bool,/// PNGs kept transparent where the composition draws nothing: an HTML page's canvas clear instead of white (#32)pub alpha: bool,+ /// the frames that start shots, found as the frames are made (an outermost Sequence's start, the 3D's camera cut):+ /// a whole video splits into segments there (raea-runtime-segments)+ pub cuts: Cuts,}+pub use raea_runtime_segments::Cuts;+impl RenderOpts {/// ten_bit, or RAEA_EXPORT_10BIT=1pub fn wants_10bit(&self) -> bool {@@ -53,10 +58,23 @@ impl RenderOpts {let kbps = self.kbps.unwrap_or_else(|| raea_io_media::default_kbps(width, height, fps, hevc));raea_io_media::EncodeOpts { width, height, fps, kbps, quality: self.quality, nv12, realtime }}++ /// A whole render's cuts, where its video splits into segments: the ones its frames find (`cuts`) and its 3D's+ /// camera cuts (the timeline's Shots). None for part of a render, which is encoded in one run.+ fn cuts_of(&self, prog: &Program) -> Option<Cuts> {+ self.frames.is_none().then(|| {+ raea_sys_frame::shots::Shots::of(prog).0.into_iter().for_each(|f| self.cuts.mark(f));+ self.cuts.clone()+ })+ }}-/// The encoder for a direct or fed render: 10-bit (P010 frames) when `ten_bit`, else the platform's 8-bit (NV12).-fn direct_encoder(codec: &str, out: &Path, opts: &raea_io_media::EncodeOpts, ten_bit: bool) -> Result<Box<dyn raea_io_media::VideoEncoder>, String> {+/// The encoder for a render's video: a whole one's in segments split at `cuts` (raea-runtime-segments), a part's in+/// one run; 10-bit (P010 frames) when `ten_bit`, else the platform's 8-bit (NV12).+fn direct_encoder(codec: &str, out: &Path, opts: &raea_io_media::EncodeOpts, ten_bit: bool, cuts: Option<&Cuts>) -> Result<Box<dyn raea_io_media::VideoEncoder>, String> {+ if let Some(c) = cuts {+ return raea_runtime_segments::encoder(codec, out, opts, ten_bit, c);+ }let b = raea_io_media::backend(codec)?;if ten_bit { b.encoder_10bit(out, opts) } else { b.encoder(out, opts) }}diff --git a/runtime/encode/src/render.rs b/runtime/encode/src/render.rsindex 261ab7a0..cfb926e0 100644--- a/runtime/encode/src/render.rs+++ b/runtime/encode/src/render.rs@@ -89,9 +89,9 @@ pub fn render_fed(let opts = ro.encode_opts(w, h, prog.fps, true, false, ten);let (t, rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(4);tx = Some(t);- let out = out.to_path_buf();+ let (out, cuts) = (out.to_path_buf(), ro.cuts_of(prog));enc_thread = Some(std::thread::spawn(move || -> Result<(raea_io_media::EncodeStats, f64), String> {- let mut enc = direct_encoder(&codec, &out, &opts, ten)?;+ let mut enc = direct_encoder(&codec, &out, &opts, ten, cuts.as_ref())?;for px in rx {push_direct(&mut enc, &px, w, h, ten)?;}@@ -190,9 +190,9 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Relet opts = ro.encode_opts(w, h, prog.fps, true, false, ten);let (t, rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(4);tx = Some(t);- let out = out.to_path_buf();+ let (out, cuts) = (out.to_path_buf(), ro.cuts_of(&prog));enc_thread = Some(std::thread::spawn(move || -> Result<raea_io_media::EncodeStats, String> {- let mut enc = direct_encoder(&codec, &out, &opts, ten)?;+ let mut enc = direct_encoder(&codec, &out, &opts, ten, cuts.as_ref())?;for px in rx {push_direct(&mut enc, &px, w, h, ten)?;}@@ -261,9 +261,9 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Relet opts = ro.encode_opts(w, h, prog.fps, true, engine::has_3d(&rows), ten);let (t, rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(4);tx = Some(t);- let out = out.to_path_buf();+ let (out, cuts) = (out.to_path_buf(), ro.cuts_of(&prog));enc_thread = Some(std::thread::spawn(move || -> Result<(raea_io_media::EncodeStats, f64), String> {- let mut enc = direct_encoder(&codec, &out, &opts, ten)?;+ let mut enc = direct_encoder(&codec, &out, &opts, ten, cuts.as_ref())?;for px in rx {push_direct(&mut enc, &px, w, h, ten)?;}@@ -332,7 +332,7 @@ pub fn render_with(prog: &Program, rows: &[Tup], dir: &Path, out: &Path, ro: &Reif ro.wants_10bit() {eprintln!("warning: 10-bit export: this render goes through the engine (3D, --ssim or RAEA_READBACK/RAEA_COMPOSITE), which makes 8-bit NV12; encoding 8-bit H.264");}- let mut enc = raea_io_media::backend(&codec).and_then(|b| b.encoder(&out, &opts))?;+ let mut enc = direct_encoder(&codec, &out, &opts, false, ro.cuts_of(&prog).as_ref())?;engine::mem_mark("render: encoder made");let mut encode_s = 0.0;let t_all = std::time::Instant::now();diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rsindex af45519a..e39f8ffd 100644--- a/runtime/export/src/fed.rs+++ b/runtime/export/src/fed.rs@@ -211,11 +211,12 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot// RAEA_REACT_AHEAD=0: each frame asked for in its turn, as before; and with the Engine's reads, whose frame f - 1// is stepped before f is asked for (engine_before)let ahead = std::env::var("RAEA_REACT_AHEAD").as_deref() != Ok("0") && !raea_runtime_react::shared::engine_reads();+ let cuts = raea_runtime_encode::Cuts::default();let r = raea_runtime_encode::render_fed(&pic,work,out,- &render_opts(),+ &raea_runtime_encode::RenderOpts { cuts: cuts.clone(), ..render_opts() },|f| {if f == 0 {raea_runtime_react::startup_mark("the fed render's first frame");@@ -253,6 +254,8 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot}// a page draw past Vello's bump buffers, painted again at Vello's own sizes before the frame is encoded (#23)fr = 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()), cx.scene3d.as_ref().is_some_and(|e| raea_sys_frame::shots::Cut::at(e.world(), f)));// a video's 3D made live keeps each frame's scene for the clipping checkif LIVE_CLIPS.load(std::sync::atomic::Ordering::Relaxed) { fr.scene = 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) {diff --git a/runtime/page/src/walk.rs b/runtime/page/src/walk.rsindex 8bbe42a3..17932f95 100644--- a/runtime/page/src/walk.rs+++ b/runtime/page/src/walk.rs@@ -268,3 +268,18 @@ pub fn share_texture(id: u64, t: wgpu::Texture, w: u32, h: u32) {pub(crate) fn undrawn(kind: &str) -> bool {matches!(kind, "mesh" | "light" | "camera" | "text3d" | "surface" | "#root" | "audio" | "script")}++/// Where the page's outermost Sequences start this frame (each box's data-raea-start; none inside another, none in a+/// 3D part): the shots its timeline knows, for a render that splits its video at them (raea-runtime-segments).+pub fn shot_starts(react: &mut World) -> Vec<i64> {+ let (mut out, mut stack) = (Vec::new(), raea_runtime_react::scene::surface(react).into_iter().collect::<Vec<_>>());+ while let Some(e) = stack.pop() {+ let props = react.get::<ReactProps>(e).map(|p| &p.0);+ match props.and_then(|p| p.get("data-raea-start")).and_then(Value::as_f64) {+ Some(s) => out.push(s as i64),+ None if props.is_some_and(|p| p.contains_key("data-3d")) => {}+ None => stack.extend(react.get::<Children>(e).into_iter().flat_map(|k| k.iter())),+ }+ }+ out+}diff --git a/runtime/segments/Cargo.toml b/runtime/segments/Cargo.tomlnew file mode 100644index 00000000..b9af1c94--- /dev/null+++ b/runtime/segments/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "raea-runtime-segments"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "A render's video as shot segments, each its own encode starting on a keyframe, joined into one MP4 by stream copy with the sound laid under once (docs/rerender.feature RR3)"++[dependencies]+raea-io-media = { path = "../../io/media", default-features = false }+raea-io-codec = { path = "../../io/codec", features = ["mux"] }+muxide = "0.2"+re_mp4 = "0.5"++[dev-dependencies]+# the tests encode with the portable backend (openh264)+raea-io-media = { path = "../../io/media", default-features = false, features = ["soft"] }diff --git a/runtime/segments/src/encode.rs b/runtime/segments/src/encode.rsnew file mode 100644index 00000000..5e5cf7fc--- /dev/null+++ b/runtime/segments/src/encode.rs@@ -0,0 +1,125 @@+//! A render's video encoded as segments: each one its own encoder run, started on a keyframe at a cut (split.rs) and+//! written as an MP4 of its own, all joined when the render finishes (join.rs). To whoever drives it, it's one encoder+//! from one backend, so a signer wraps it as one: every frame carries one export's watermark, and the joined file is+//! signed once.++use std::path::{Path, PathBuf};++use raea_io_media::{Audio, Backend, EncodeOpts, EncodeStats, R, VideoDecoder, VideoEncoder};++use crate::split::Cuts;++/// The backend a segmented encoder comes from: `name`'s encoders, unsigned, one a segment.+pub(crate) struct Segs {+ pub name: String,+ pub cuts: Cuts,+ pub min: usize,+}++impl Backend for Segs {+ fn name(&self) -> &'static str {+ "segments"+ }+ fn open_video(&self, path: &Path) -> R<Box<dyn VideoDecoder>> {+ raea_io_media::backend_unsigned(&self.name)?.open_video(path)+ }+ fn decode_audio(&self, path: &Path) -> R<Audio> {+ raea_io_media::backend_unsigned(&self.name)?.decode_audio(path)+ }+ fn encoder(&self, out: &Path, opts: &EncodeOpts) -> R<Box<dyn VideoEncoder>> {+ Segmented::new(self, out, opts, false)+ }+ fn encoder_10bit(&self, out: &Path, opts: &EncodeOpts) -> R<Box<dyn VideoEncoder>> {+ Segmented::new(self, out, opts, true)+ }+}++/// Frames pushed in order from frame 0, each to its segment's encoder.+struct Segmented {+ name: String,+ opts: EncodeOpts,+ ten: bool,+ out: PathBuf,+ /// the segments' folder, gone with the encoder (RAEA_KEEP_SEGMENTS=1 keeps it)+ dir: PathBuf,+ cuts: Cuts,+ min: usize,+ cur: Option<Box<dyn VideoEncoder>>,+ /// frames in the current segment, and pushed in all+ len: usize,+ n: usize,+ paths: Vec<PathBuf>,+ /// the segments' video, as their encoder named it+ video: String,+}++impl Segmented {+ fn new(s: &Segs, out: &Path, opts: &EncodeOpts, ten: bool) -> R<Box<dyn VideoEncoder>> {+ static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);+ let k = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ let dir = std::env::temp_dir().join(format!("raea-segments-{}-{k}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ let (name, cuts, min) = (s.name.clone(), s.cuts.clone(), s.min);+ Ok(Box::new(Segmented { name, opts: opts.clone(), ten, out: out.into(), dir, cuts, min, cur: None, len: 0, n: 0, paths: Vec::new(), video: String::new() }))+ }++ /// The encoder frame `n` goes to: a new segment's at a cut (once the one it ends has `min` frames) or at the first.+ fn next(&mut self) -> R<&mut Box<dyn VideoEncoder>> {+ if self.cur.is_some() && self.cuts.starts(self.n as i64, self.len, self.min) {+ self.close()?;+ }+ if self.cur.is_none() {+ let path = self.dir.join(format!("segment-{:04}.mp4", self.paths.len()));+ let b = raea_io_media::backend_unsigned(&self.name)?;+ self.cur = Some(if self.ten { b.encoder_10bit(&path, &self.opts)? } else { b.encoder(&path, &self.opts)? });+ self.paths.push(path);+ self.len = 0;+ }+ self.len += 1;+ self.n += 1;+ Ok(self.cur.as_mut().expect("an encoder was opened above"))+ }++ fn close(&mut self) -> R<()> {+ if let Some(e) = self.cur.take() {+ self.video = e.finish(None)?.video_codec;+ }+ Ok(())+ }+}++impl VideoEncoder for Segmented {+ fn push(&mut self, rgba: &[u8]) -> R<()> {+ self.next()?.push(rgba)+ }+ fn push_nv12(&mut self, nv12: &[u8], w: usize, h: usize) -> R<()> {+ self.next()?.push_nv12(nv12, w, h)+ }+ fn push_p010(&mut self, p010: &[u8], w: usize, h: usize) -> R<()> {+ self.next()?.push_p010(p010, w, h)+ }+ fn finish(mut self: Box<Self>, audio: Option<&Audio>) -> R<EncodeStats> {+ self.close()?;+ let sound = match audio {+ Some(a) => Some(raea_io_media::backend_unsigned(&self.name)?.sound(a)?),+ None => None,+ };+ let t = std::time::Instant::now();+ let frames = crate::join::join(&self.paths, sound.as_ref(), self.opts.fps, &self.out)?;+ if std::env::var_os("RAEA_SEGMENTS_TRACE").is_some() {+ eprintln!("raea segments: {frames} frames in {} segments joined in {:.1} ms (cuts {:?})", self.paths.len(), t.elapsed().as_secs_f64() * 1e3, self.cuts.all());+ }+ let audio_codec = sound.map_or(String::new(), |s| if s.aac { "aac".into() } else { "opus".into() });+ let bytes = std::fs::metadata(&self.out).map(|m| m.len()).unwrap_or(0);+ Ok(EncodeStats { frames, bytes, video_codec: format!("{} in {} segments", self.video, self.paths.len()), audio_codec })+ }+}++impl Drop for Segmented {+ fn drop(&mut self) {+ if std::env::var("RAEA_KEEP_SEGMENTS").as_deref() != Ok("1") {+ let _ = std::fs::remove_dir_all(&self.dir);+ }+ }+}diff --git a/runtime/segments/src/join.rs b/runtime/segments/src/join.rsnew file mode 100644index 00000000..889b434f--- /dev/null+++ b/runtime/segments/src/join.rs@@ -0,0 +1,95 @@+//! Segments joined into one MP4 by stream copy: each segment's samples as they were encoded, one after another (H.264's+//! and HEVC's as Annex B with their parameter sets before each keyframe, AV1's OBUs as they are), and the sound laid+//! under them once, from the render's own mix. Nothing is decoded or encoded again.++use std::path::Path;++use muxide::api::{AacProfile, AudioCodec, MuxerBuilder, VideoCodec};+use raea_io_codec::remux::{avcc_params, avcc_to_annexb, hvcc_params};+use raea_io_media::{R, SoundTrack};++/// A segment's video: its codec and size, and each sample with its key flag, as the muxer takes them.+pub(crate) struct Track {+ pub codec: VideoCodec,+ pub w: u32,+ pub h: u32,+ pub samples: Vec<(Vec<u8>, bool)>,+}++/// Whether a length-prefixed sample carries its own parameter sets (H.264's SPS or PPS, HEVC's VPS, SPS or PPS).+fn has_params(sample: &[u8], hevc: bool) -> bool {+ let mut i = 0;+ while i + 4 < sample.len() {+ let n = u32::from_be_bytes([sample[i], sample[i + 1], sample[i + 2], sample[i + 3]]) as usize;+ let t = sample[i + 4];+ if (!hevc && matches!(t & 0x1f, 7 | 8)) || (hevc && matches!((t >> 1) & 0x3f, 32..=34)) {+ return true;+ }+ i += 4 + n;+ }+ false+}++/// A segment's video read back from its MP4.+pub(crate) fn read(path: &Path) -> R<Track> {+ let b = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;+ let m = re_mp4::Mp4::read_bytes(&b).map_err(|e| format!("{}: {e}", path.display()))?;+ let (_, t) = m.tracks().iter().find(|(_, t)| t.kind == Some(re_mp4::TrackKind::Video)).ok_or_else(|| format!("{}: no video", path.display()))?;+ let config = t.raw_codec_config(&m).unwrap_or_default();+ let (codec, params) = match &t.trak(&m).mdia.minf.stbl.stsd.contents {+ re_mp4::StsdBoxContent::Avc1(_) => (VideoCodec::H264, Some(avcc_params(&config))),+ re_mp4::StsdBoxContent::Hvc1(_) | re_mp4::StsdBoxContent::Hev1(_) => (VideoCodec::H265, Some(hvcc_params(&config))),+ re_mp4::StsdBoxContent::Av01(_) => (VideoCodec::Av1, None),+ _ => return Err(format!("{}: a segment's video is H.264, HEVC or AV1 ({:?})", path.display(), t.codec_string(&m))),+ };+ let hevc = codec == VideoCodec::H265;+ let samples = t.samples.iter().map(|s| {+ let data = &b[s.byte_range()];+ let out = match ¶ms {+ // the parameter sets before a keyframe that doesn't carry its own, as an encoder's own stream has them+ Some(p) => avcc_to_annexb(data, (s.is_sync && !has_params(data, hevc)).then_some(&p[..])),+ None => data.to_vec(),+ };+ (out, s.is_sync)+ });+ Ok(Track { codec, w: t.width as u32, h: t.height as u32, samples: samples.collect() })+}++/// The segments at `paths`, in order, as one MP4 at `out` at `fps`, with `sound` under them. Each segment starts on a+/// keyframe; they share a codec and a size or the join is refused (a segment made with other settings is drawn again).+pub fn join(paths: &[impl AsRef<Path>], sound: Option<&SoundTrack>, fps: f64, out: &Path) -> R<usize> {+ let tracks: Vec<Track> = paths.iter().map(|p| read(p.as_ref())).collect::<R<_>>()?;+ let first = tracks.first().ok_or("no segments to join")?;+ for (t, p) in tracks.iter().zip(paths) {+ if (t.codec, t.w, t.h) != (first.codec, first.w, first.h) {+ return Err(format!("{}: {:?} {}x{}, not the first segment's {:?} {}x{}", p.as_ref().display(), t.codec, t.w, t.h, first.codec, first.w, first.h));+ }+ if t.samples.first().is_some_and(|s| !s.1) {+ return Err(format!("{}: a segment starts on a keyframe", p.as_ref().display()));+ }+ }+ let file = std::fs::File::create(out).map_err(|e| format!("{}: {e}", out.display()))?;+ let mut b = MuxerBuilder::new(std::io::BufWriter::new(file)).video(first.codec, first.w, first.h, fps).with_fast_start(true);+ if let Some(s) = sound {+ let codec = if s.aac { AudioCodec::Aac(AacProfile::Lc) } else { AudioCodec::Opus };+ b = b.audio(codec, s.rate, s.channels).audio_priming(s.priming);+ }+ let mut m = b.build().map_err(|e| format!("muxide: {e}"))?;+ let packets = sound.map_or(&[][..], |s| &s.packets[..]);+ let (mut k, mut ai) = (0usize, 0usize);+ for (data, key) in tracks.iter().flat_map(|t| t.samples.iter()) {+ let pts = k as f64 / fps;+ while ai < packets.len() && packets[ai].0 < pts {+ m.write_audio(packets[ai].0, &packets[ai].1).map_err(|e| format!("muxide audio: {e}"))?;+ ai += 1;+ }+ m.write_video(pts, data, *key).map_err(|e| format!("muxide video: {e}"))?;+ k += 1;+ }+ let end = k as f64 / fps;+ for (pts, d) in packets[ai..].iter().filter(|p| p.0 < end) {+ m.write_audio(*pts, d).map_err(|e| format!("muxide audio: {e}"))?;+ }+ m.finish().map_err(|e| format!("muxide: {e}"))?;+ Ok(k)+}diff --git a/runtime/segments/src/lib.rs b/runtime/segments/src/lib.rsnew file mode 100644index 00000000..6bee641d--- /dev/null+++ b/runtime/segments/src/lib.rs@@ -0,0 +1,37 @@+//! A render's video as shot segments (docs/rerender.feature RR3): split at every cut the timeline knows (split.rs), each+//! segment its own encoder run starting on a keyframe (encode.rs), joined into one MP4 by stream copy with the sound+//! laid under once (join.rs). So a changed shot can be drawn again alone and the film joined around it (RR4), and+//! segments drawn by several workers at once (RR5).++use std::path::Path;++use raea_io_media::{EncodeOpts, R, VideoEncoder};++mod encode;+mod join;+mod split;+pub use join::join;+pub use split::{Cuts, min_frames, segments};++/// The backends whose encoders write segments the join reads (muxide's MP4s: H.264, HEVC, AV1) and lay a sound under+/// a joined video (Backend::sound). The ffmpeg CLI, the baseline, encodes in one run.+pub fn segmentable(codec: &str) -> bool {+ matches!(codec, "apple" | "soft" | "av1")+}++/// Whether renders make their videos as segments: with RAEA_SEGMENTS=1, until RR3's gates are measured+pub fn on() -> bool {+ std::env::var("RAEA_SEGMENTS").as_deref() == Ok("1")+}++/// The encoder for a whole video (frame 0 first, every frame in order) to `out`: `codec`'s, a new segment at each of+/// `cuts` once the one before holds min_frames, the whole wrapped by the signer when one is installed (one export, one+/// watermark id, the joined file signed). The ffmpeg baseline's, or with segments off: one run, as before.+pub fn encoder(codec: &str, out: &Path, opts: &EncodeOpts, ten: bool, cuts: &Cuts) -> R<Box<dyn VideoEncoder>> {+ let b = if segmentable(codec) && on() {+ raea_io_media::sign::wrap(Box::new(encode::Segs { name: codec.into(), cuts: cuts.clone(), min: min_frames(opts.fps) }))+ } else {+ raea_io_media::backend(codec)?+ };+ if ten { b.encoder_10bit(out, opts) } else { b.encoder(out, opts) }+}diff --git a/runtime/segments/src/split.rs b/runtime/segments/src/split.rsnew file mode 100644index 00000000..89b37de4--- /dev/null+++ b/runtime/segments/src/split.rs@@ -0,0 +1,75 @@+//! Where a video splits: at every cut the timeline knows (an outermost Sequence's start, a camera the engine cut to),+//! never inside a shot. The frames' side finds them as each frame is made; the encoder's side starts a segment at one,+//! unless the segment it's in is shorter than the minimum, so a shot under it goes on in the segment it started in.++use std::collections::BTreeSet;+use std::sync::{Arc, Mutex};++/// The cuts a render has found, shared between the thread that makes its frames and the encoder's.+#[derive(Clone, Debug, Default)]+pub struct Cuts(Arc<Mutex<BTreeSet<i64>>>);++impl Cuts {+ /// Frame `f`'s cuts: one when an outermost Sequence starts there (`starts`: each one's start frame, as+ /// raea_runtime_react::scene::shot_starts reads them) or the 3D's camera cut there (`camera`); frame 0 is no cut.+ pub fn find(&self, f: i64, starts: impl IntoIterator<Item = i64>, camera: bool) {+ if f > 0 && (camera || starts.into_iter().any(|s| s == f)) {+ self.mark(f);+ }+ }++ pub fn mark(&self, f: i64) {+ self.0.lock().unwrap().insert(f);+ }++ /// Whether frame `f` starts a shot.+ pub fn at(&self, f: i64) -> bool {+ self.0.lock().unwrap().contains(&f)+ }++ pub fn all(&self) -> Vec<i64> {+ self.0.lock().unwrap().iter().copied().collect()+ }++ /// Whether frame `f` starts a segment after one of `len` frames: at a cut, once that one has `min`.+ pub fn starts(&self, f: i64, len: usize, min: usize) -> bool {+ len >= min && self.at(f)+ }+}++/// The shortest segment, in frames: a cut sooner than this after the segment's first frame is passed over, so a run of+/// short shots shares one (a keyframe a few frames apart buys a cache nothing and costs the encoder bits).+pub fn min_frames(fps: f64) -> usize {+ (fps.round() as usize).max(1)+}++/// The segments a run of `n` frames makes with these cuts: each one's first frame and length.+pub fn segments(n: usize, cuts: &Cuts, min: usize) -> Vec<(usize, usize)> {+ let mut out: Vec<(usize, usize)> = Vec::new();+ for i in 0..n {+ match out.last_mut() {+ Some((_, len)) if !cuts.starts(i as i64, *len, min) => *len += 1,+ _ => out.push((i, 1)),+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_cut_starts_a_segment_unless_the_one_before_is_short() {+ let c = Cuts::default();+ c.find(0, [0], true);+ c.find(40, [0, 40], false);+ c.find(50, [], true);+ c.find(70, [10], false);+ assert_eq!(c.all(), vec![40, 50]);+ // 0..40 is long enough, 40..50 isn't: the cut at 50 is passed over+ assert_eq!(segments(90, &c, 30), vec![(0, 40), (40, 50)]);+ assert_eq!(segments(90, &c, 5), vec![(0, 40), (40, 10), (50, 40)]);+ assert_eq!(segments(30, &Cuts::default(), 30), vec![(0, 30)]);+ }+}diff --git a/runtime/segments/tests/join.rs b/runtime/segments/tests/join.rsnew file mode 100644index 00000000..9c5b5fa4--- /dev/null+++ b/runtime/segments/tests/join.rs@@ -0,0 +1,104 @@+//! A video made as segments and joined by stream copy (docs/rerender.feature RR3), on the portable encoder (openh264):+//! every frame there once and in order, a keyframe where each segment starts and nowhere a cut was passed over, the+//! sound laid under once, and the pictures the segments' own.++use std::path::{Path, PathBuf};++use raea_io_media::{Audio, EncodeOpts};+use raea_runtime_segments::{Cuts, encoder, join};++const W: u32 = 64;+const H: u32 = 64;+const FPS: f64 = 30.0;++fn opts() -> EncodeOpts {+ EncodeOpts { width: W, height: H, fps: FPS, kbps: 800, quality: None, nv12: false, realtime: false }+}++/// Frame i: a flat grey that steps every frame, with a bar whose place says which frame it is.+fn frame(i: usize) -> Vec<u8> {+ let mut px = vec![0u8; (W * H * 4) as usize];+ for (k, p) in px.chunks_exact_mut(4).enumerate() {+ let x = k % W as usize;+ let v = if x / 4 == i % 16 { 250 } else { (40 + i * 3 % 120) as u8 };+ p.copy_from_slice(&[v, v, v, 255]);+ }+ px+}++fn scratch(name: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("raea-segments-test-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ std::fs::create_dir_all(&d).unwrap();+ d+}++/// The video track's samples' key flags, and whether there's a sound track.+fn keys(path: &Path) -> (Vec<bool>, bool) {+ let b = std::fs::read(path).unwrap();+ let m = re_mp4::Mp4::read_bytes(&b).unwrap();+ let video = m.tracks().values().find(|t| t.kind == Some(re_mp4::TrackKind::Video)).unwrap();+ // re_mp4 names only AAC (mp4a) a sound track; Opus (soft, av1) reads as kind None+ let sound = m.tracks().values().any(|t| t.kind != Some(re_mp4::TrackKind::Video));+ (video.samples.iter().map(|s| s.is_sync).collect(), sound)+}++/// The video track's samples as stored.+fn samples(path: &Path) -> Vec<Vec<u8>> {+ let b = std::fs::read(path).unwrap();+ let m = re_mp4::Mp4::read_bytes(&b).unwrap();+ let video = m.tracks().values().find(|t| t.kind == Some(re_mp4::TrackKind::Video)).unwrap();+ video.samples.iter().map(|s| b[s.byte_range()].to_vec()).collect()+}++fn silence(frames: usize) -> Audio {+ Audio { rate: 48000, channels: vec![vec![0.0; 48000 * frames / FPS as usize]; 2] }+}++#[test]+fn segments_joined_are_one_video_with_one_sound() {+ let d = scratch("join");+ let soft = raea_io_media::backend_unsigned("soft").unwrap();+ let mut paths = Vec::new();+ for (k, (from, n)) in [(0usize, 10usize), (10, 7)].into_iter().enumerate() {+ let p = d.join(format!("s{k}.mp4"));+ let mut e = soft.encoder(&p, &opts()).unwrap();+ (from..from + n).for_each(|i| e.push(&frame(i)).unwrap());+ e.finish(None).unwrap();+ paths.push(p);+ }+ let out = d.join("joined.mp4");+ let sound = soft.sound(&silence(17)).unwrap();+ assert_eq!(join(&paths, Some(&sound), FPS, &out).unwrap(), 17);+ let (k, has_sound) = keys(&out);+ assert_eq!(k.len(), 17);+ assert!(k[0] && k[10], "each segment starts on a keyframe: {k:?}");+ assert!(has_sound);+ // the joined video's samples are its segments' own bytes: nothing was encoded again+ let parts: Vec<Vec<u8>> = paths.iter().flat_map(|p| samples(p)).collect();+ assert!(samples(&out) == parts, "the joined samples aren't the segments'");+ let _ = std::fs::remove_dir_all(&d);+}++#[test]+fn the_encoder_splits_at_cuts_but_not_short_shots() {+ let d = scratch("cuts");+ let out = d.join("film.mp4");+ let cuts = Cuts::default();+ // 30 fps: a segment holds at least 30 frames, so the cut at 45 (15 frames after 30) is passed over+ for f in [30, 45, 80] {+ cuts.mark(f);+ }+ // SAFETY: the only test in this binary that reads the environment+ unsafe { std::env::set_var("RAEA_SEGMENTS", "1") };+ let mut e = encoder("soft", &out, &opts(), false, &cuts).unwrap();+ (0..100).for_each(|i| e.push(&frame(i)).unwrap());+ let st = e.finish(Some(&silence(100))).unwrap();+ assert_eq!(st.frames, 100);+ assert!(st.video_codec.ends_with("in 3 segments"), "{}", st.video_codec);+ let (k, has_sound) = keys(&out);+ let at: Vec<usize> = k.iter().enumerate().filter(|(_, s)| **s).map(|(i, _)| i).collect();+ assert_eq!(at, vec![0, 30, 80]);+ assert!(has_sound);+ let _ = std::fs::remove_dir_all(&d);+}diff --git a/systems/frame/src/shots.rs b/systems/frame/src/shots.rsindex 64310512..bd6ec502 100644--- a/systems/frame/src/shots.rs+++ b/systems/frame/src/shots.rs@@ -12,6 +12,18 @@ pub struct Shots(pub Vec<i64>);#[derive(bevy::prelude::Resource)]pub struct Moved;+/// The frame an engine last drew as a cut (Engine::pre_step), whichever said so: a render splits its video there+/// (raea-runtime-segments).+#[derive(bevy::prelude::Resource)]+pub struct Cut(pub i64);++impl Cut {+ /// Whether `world`'s engine drew frame `f` as a cut.+ pub fn at(world: &bevy::prelude::World, f: i64) -> bool {+ world.get_resource::<Cut>().is_some_and(|c| c.0 == f)+ }+}+impl Shots {pub fn of(prog: &raea_core_program::ir::Program) -> Shots {let keys = prog.keys.get(&("cam".to_string(), "shot".to_string()));