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
media: a quarter second of frames waits ahead; a video drawn small sends only the halving it is drawn from
shinyobjectzf9b6f22ecfab
diff --git a/runtime/dom/media/src/lib.rs b/runtime/dom/media/src/lib.rsindex f33782ae..5fd0df5d 100644--- a/runtime/dom/media/src/lib.rs+++ b/runtime/dom/media/src/lib.rs@@ -38,7 +38,7 @@ pub struct Media {duration: f64,/// the latest frame: width, height, pixelsframe: Option<(u32, u32, Arc<Vec<u8>>)>,- /// its halvings, until they go to the painter with it+ /// what it is drawn from when it came as its size alone (its halving), until that goes to the painter with ithalves: Halvings,/// how many halvings its decoder is asked to send with each framehalvings: u8,diff --git a/runtime/js/src/media_html.rs b/runtime/js/src/media_html.rsindex 35190eb6..fd7c42ee 100644--- a/runtime/js/src/media_html.rs+++ b/runtime/js/src/media_html.rs@@ -12,7 +12,8 @@ pub mod stream {/// where a playing source has got to, that it played to its end, or its failure.pub enum Msg {Meta { w: u32, h: u32, duration: f64 },- /// a frame to show now (the first, a seek's), with its halvings when they're asked for (`Cmd::Halvings`)+ /// a frame to show now (the first, a seek's). Asked for halvings (`Cmd::Halvings`), it comes as its size and+ /// the halving it is drawn from, its own pixels left behindFrame(f64, raea_io_media::Frame, Halvings),/// a playing video's frame, decoded ahead of its time: the frame at this time, to show at this momentDue(f64, raea_io_media::Frame, std::time::Instant, Halvings),@@ -25,9 +26,10 @@ pub mod stream {Fail(String),}- /// A frame's halvings, largest first: each a 2x2 mean of the one before (width, height, RGBA). A frame drawn at- /// under half its size is drawn from one of them, so a 4K frame in a small player is neither sampled across- /// four of its pixels at a time (it shimmers) nor sent whole to the GPU for every frame.+ /// Halvings of a frame, largest first: each a 2x2 mean of the one before (width, height, RGBA). A frame drawn at+ /// under half its size is drawn from one, so a 4K frame in a small player is neither sampled across four of+ /// its pixels at a time (it shimmers) nor sent whole to the GPU for every frame; and since the one it is drawn+ /// from is all that is sent, a quarter second of 4K frames waiting is 30 to 120 MB where whole it would be 500.pub type Halvings = Vec<(u32, u32, Vec<u8>)>;/// `n` halvings of an RGBA picture (fewer once a side is a pixel).@@ -57,6 +59,15 @@ pub mod stream {out}+ /// A frame as it is sent when `n` halvings are asked for: whole with none; else its size, and the nth halving+ /// alone (the one it is drawn from).+ pub fn sent(f: raea_io_media::Frame, n: u8) -> (raea_io_media::Frame, Halvings) {+ match halvings(f.width, f.height, &f.rgba, n).pop() {+ Some(last) => (raea_io_media::Frame { rgba: Vec::new(), ..f }, vec![last]),+ None => (f, Vec::new()),+ }+ }+/// What the element asks of its decoder. Play plays from `at` on the source's clock (its sound's, when it has/// sound and a device): frames as they fall due, each `Frame` news, and `Ended` at its end unless `looping`.pub enum Cmd {@@ -66,8 +77,8 @@ pub mod stream {Muted(bool),/// the element's volume, 0..1: the sound's gain while it isn't mutedVolume(f32),- /// how many halvings each frame should come with from here on (the page counts them from the size the- /// video is drawn at; 0 while it is drawn at half its size or more)+ /// how many times each frame should be halved from here on (the page counts them from the size the video is+ /// drawn at; 0 while it is drawn at over half its size)Halvings(u8),}diff --git a/runtime/js/src/media_play.rs b/runtime/js/src/media_play.rsindex 88732560..2e2bf99b 100644--- a/runtime/js/src/media_play.rs+++ b/runtime/js/src/media_play.rs@@ -9,7 +9,7 @@ use std::path::Path;use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};use std::time::{Duration, Instant};-use crate::media_html::stream::{Cmd, Msg, halvings};+use crate::media_html::stream::{Cmd, Msg, sent};use crate::media_sound::Sound;/// What was opened: a video's decoder, or an audio source's samples.@@ -132,7 +132,7 @@ impl<'a> Player<'a> {}Cmd::Halvings(n) => {// paused, the picture showing is sent again with what it is now drawn from- if n > self.halvings && self.clock.is_none() && seek.is_none() {+ if n != self.halvings && self.clock.is_none() && seek.is_none() {seek = self.still;}self.halvings = n;@@ -196,19 +196,19 @@ impl<'a> Player<'a> {!self.looping && self.duration.is_finite() && self.cursor as f64 / self.fps >= self.duration - 0.5 / self.fps}- /// How far ahead of the clock frames are decoded: two frames, 50 ms at the least; and nearing a loop's end 150 ms,- /// since going back to the start is a seek (70 ms measured) that must be over before the first frame is due. No- /// more than 200 MB of frames wait at once (a 4K frame is 33 MB).+ /// How far ahead of the clock frames are decoded: a quarter second, which rides out a decode that stalls (a+ /// reader starting again, a busy machine: 40 to 85 ms seen) and the seek back to a loop's start (70 ms). No more+ /// than 128 MB of frames wait at once, 200 nearing a loop's end, and never fewer than two frames: a 4K frame+ /// sent whole is 33 MB (three wait), sent as the halving it is drawn from 8 or 2 (the quarter second).fn lead(&self) -> f64 {let frame = 1.0 / self.fps;let bytes = match &self.source {- Source::Video(d) => (d.info().width as f64 * d.info().height as f64 * 4.0).max(1.0),+ Source::Video(d) => (d.info().width as f64 * d.info().height as f64 * 4.0 / 4f64.powi(self.halvings as i32)).max(1.0),Source::Audio(_) => 1.0,};- let most = (200e6 / bytes).floor().max(2.0) * frame;- let near_wrap = self.looping && self.duration.is_finite() && self.duration - self.cursor as f64 * frame < 0.25;- let want = if near_wrap || self.lap > 0.0 { 0.15 } else { (2.0 * frame).max(0.05) };- want.min(most)+ let near_wrap = self.looping && self.duration.is_finite() && (self.lap > 0.0 || self.duration - self.cursor as f64 * frame < 0.25);+ let most = ((if near_wrap { 200e6 } else { 128e6 }) / bytes).floor().max(2.0) * frame;+ most.min(0.25)}/// The clock's time now.@@ -265,7 +265,7 @@ impl<'a> Player<'a> {self.still = Some(t);let n = self.halvings;tx.send(dec.frame_at(t).map_or_else(Msg::Fail, |f| {- let halves = halvings(f.width, f.height, &f.rgba, n);+ let (f, halves) = sent(f, n);Msg::Frame(t, f, halves)})).is_ok()@@ -313,10 +313,7 @@ impl<'a> Player<'a> {let Source::Video(dec) = &mut self.source else { return true };// asked for mid-frame: a source whose frames aren't exactly on fps's grid gives the frame showing thenlet n = self.halvings;- let got = dec.frame_at(at + 0.5 * frame).map(|f| {- let halves = halvings(f.width, f.height, &f.rgba, n);- (f, halves)- });+ let got = dec.frame_at(at + 0.5 * frame).map(|f| sent(f, n));let took = began.elapsed();let due = began + Duration::from_secs_f64(due_in.max(0.0));self.cursor += 1;@@ -365,6 +362,23 @@ mod tests {ok.then_some(p)}+ /// A halving's pixel is the mean of the four it stands for; an odd last row or column is left out; a picture a+ /// pixel wide has none; and a frame is sent whole when none are asked for.+ #[test]+ fn halvings_are_means_of_four() {+ use crate::media_html::stream::{halvings, sent};+ let px: Vec<u8> = (0..5 * 3 * 4).map(|i| (i * 3) as u8).collect();+ let h = halvings(5, 3, &px, 3);+ assert_eq!(h.iter().map(|(w, h, p)| (*w, *h, p.len())).collect::<Vec<_>>(), vec![(2, 1, 8)]);+ let mean = |x: usize, c: usize| ((px[x * 4 + c] as u16 + px[(x + 1) * 4 + c] as u16 + px[(5 + x) * 4 + c] as u16 + px[(5 + x + 1) * 4 + c] as u16 + 2) / 4) as u8;+ assert_eq!(h[0].2, vec![mean(0, 0), mean(0, 1), mean(0, 2), mean(0, 3), mean(2, 0), mean(2, 1), mean(2, 2), mean(2, 3)]);+ let f = raea_io_media::Frame { pts: 0.0, width: 5, height: 3, rgba: px.clone() };+ let (whole, none) = sent(f.clone(), 0);+ assert!(whole.rgba == px && none.is_empty());+ let (size, one) = sent(f, 1);+ assert!(size.rgba.is_empty() && (size.width, size.height) == (5, 3) && one == vec![h[0].clone()]);+ }+/// Played on the wall's clock (RAEA_AUDIO_MUTE=1: no device), a video's frames come as they fall due and it ends/// at its end; a seek answers with the frame at exactly its time; looping, it goes round; paused, it stops.#[test]@@ -405,16 +419,22 @@ mod tests {st.ask(Cmd::Seek(0.5));assert!(matches!(next(&st, Duration::from_secs(2)), Some(Msg::Frame(t, ..)) if t == 0.5));+ let looped = Instant::now();st.ask(Cmd::Play { at: 0.5, looping: true });- let (mut wrapped, mut last, until) = (false, 0.5, Instant::now() + Duration::from_millis(1200));+ let (mut wrapped, mut last, mut laps, until) = (false, 0.5, 0.0, Instant::now() + Duration::from_millis(2300));while Instant::now() < until {match next(&st, Duration::from_millis(200)) {Some(Msg::Due(t, _, due, _)) => {// the first frame of the next lap is sent before the last frame of this one has goneif t < last {wrapped = true;+ laps += 1.0;assert!(due > Instant::now(), "the loop's first frame came after it was due");}+ // round the loop a frame is still due when the clock is at its time: half a second of play+ // to the end, then a second a lap+ let on_clock = due.duration_since(looped).as_secs_f64();+ assert!((on_clock - (t - 0.5 + laps)).abs() < 0.06, "lap {laps}: the frame at {t} is due {on_clock} s after play");last = t;}Some(Msg::Ended(_)) => panic!("a looping source doesn't end"),@@ -424,16 +444,14 @@ mod tests {assert!(wrapped, "looping went round");st.ask(Cmd::Pause);- // paused, asked for halvings: the picture showing comes again with them, each half the one before+ // paused, asked for two halvings: the picture showing comes again as its size and its second halvingwhile next(&st, Duration::from_millis(300)).is_some() {}st.ask(Cmd::Halvings(2));match next(&st, Duration::from_secs(2)) {Some(Msg::Frame(_, f, halves)) => {assert_eq!((f.width, f.height), (160, 90));- assert_eq!(halves.iter().map(|(w, h, px)| (*w, *h, px.len())).collect::<Vec<_>>(), vec![(80, 45, 80 * 45 * 4), (40, 22, 40 * 22 * 4)]);- // a level's pixel is the mean of the four it stands for- let mean = |c: usize| ((f.rgba[c] as u16 + f.rgba[4 + c] as u16 + f.rgba[160 * 4 + c] as u16 + f.rgba[160 * 4 + 4 + c] as u16 + 2) / 4) as u8;- assert_eq!(&halves[0].2[..4], &[mean(0), mean(1), mean(2), mean(3)]);+ assert!(f.rgba.is_empty(), "the frame's own pixels stay behind");+ assert_eq!(halves.iter().map(|(w, h, px)| (*w, *h, px.len())).collect::<Vec<_>>(), vec![(40, 22, 40 * 22 * 4)]);}_ => panic!("no frame with its halvings"),}diff --git a/vendor/blitz-paint/src/render.rs b/vendor/blitz-paint/src/render.rsindex 37ed9d62..92329ca8 100644--- a/vendor/blitz-paint/src/render.rs+++ b/vendor/blitz-paint/src/render.rs@@ -1516,8 +1516,9 @@ fn halve(src: &RasterImageData) -> RasterImageData {RasterImageData::new(w, h, Arc::new(out))}-/// raea: an image's halvings handed over ready made (each half the last, the first half the image): a video's frame,-/// halved on its decoder's thread. Kept while the image lives, as the ones made here are.+/// raea: halvings of an image handed over ready made, largest first: a video's frame, halved on its decoder's thread.+/// Not every halving need be there, and the image itself may come without its pixels (only its size): it is then+/// drawn from these alone (video_level). Kept while the image lives, as the ones made here are.pub fn preload_mips(image: &RasterImageData, levels: Vec<RasterImageData>) {MIPS.with_borrow_mut(|mips| {mips.retain(|_, (weak, _)| weak.upgrade().is_some());@@ -1525,24 +1526,43 @@ pub fn preload_mips(image: &RasterImageData, levels: Vec<RasterImageData>) {});}-/// The level of `image` to sample when it is drawn at `scale` of its size: the image itself, or a halving of it.-/// `make`: halvings not there yet are made now (an img's, once); without it only the ones handed over are used (a-/// video's frame is a new picture each time: nothing is halved for it on the page's thread).-fn mip_level(image: &RasterImageData, scale: f64, make: bool) -> RasterImageData {+/// How many times `image` is halved to be sampled at `scale` of its size: the most that leaves it at least the+/// size it is drawn.+fn halvings_at(image: &RasterImageData, scale: f64) -> usize {let mut want = 0;while scale * f64::from(1u32 << (want + 1)) <= 1.0 && image.width >> (want + 1) >= 1 && image.height >> (want + 1) >= 1 {want += 1;}+ want+}++/// A video's frame as it is drawn at `scale` of its size: nothing is halved for it here (it is a new picture each+/// time), so of the halvings it came with (preload_mips) the smallest still at least the size mip_level would+/// sample, else the largest. The frame itself when it came with none, or is drawn at over half its size and has+/// its pixels.+fn video_level(image: &RasterImageData, scale: f64) -> RasterImageData {+ let whole = image.data.data().len() >= image.width as usize * image.height as usize * 4;+ let want = halvings_at(image, scale);+ if want == 0 && whole {+ return image.clone();+ }+ MIPS.with_borrow(|mips| match mips.get(&image.data.id()) {+ Some((_, Some(levels))) if !levels.is_empty() => {+ let least = (image.width >> want).max(1);+ levels.iter().rev().find(|l| l.width >= least).unwrap_or(&levels[0]).clone()+ }+ _ => image.clone(),+ })+}++/// The level of `image` to sample when it is drawn at `scale` of its size: the image itself, or a halving of it,+/// made now if it isn't there yet (an img's, once).+fn mip_level(image: &RasterImageData, scale: f64) -> RasterImageData {+ let want = halvings_at(image, scale);if want == 0 {return image.clone();}MIPS.with_borrow_mut(|mips| {- if !make {- return match mips.get(&image.data.id()) {- Some((_, Some(levels))) if !levels.is_empty() => levels[want.min(levels.len()) - 1].clone(),- _ => image.clone(),- };- }mips.retain(|_, (weak, _)| weak.upgrade().is_some());// an all-zero image is a placeholder whose blob keys a GPU texture's override (raea-page's views, filters):// drawn as is, or the override is lost@@ -2405,9 +2425,17 @@ impl ElementCx<'_, '_> {// are each a new picture, so one is drawn from the halvings it came with (preload_mips), as it comes// when it came with nonelet outer = self.transform.determinant().abs().sqrt();- let img = self.element.name.local == local_name!("img");- let mip = quality != peniko::ImageQuality::Low && (img || self.element.name.local == local_name!("video"));- let level = if mip { mip_level(image, x_scale.min(y_scale) * outer, img) } else { image.clone() };+ let level = if self.element.name.local == local_name!("video") {+ video_level(image, x_scale.min(y_scale) * outer)+ } else if quality != peniko::ImageQuality::Low && self.element.name.local == local_name!("img") {+ mip_level(image, x_scale.min(y_scale) * outer)+ } else {+ image.clone()+ };+ // a frame that came as its size alone, and nothing to draw it from: nothing is drawn+ if level.data.data().len() < level.width as usize * level.height as usize * 4 {+ return;+ }let (lx, ly) = (image.width as f64 / level.width as f64, image.height as f64 / level.height as f64);let image = &level;let transform = self