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
RT3: a seek while a film plays shows nothing from where it was, and the sound clock moves on between its callbacks and never goes back
shinyobjectzb7f796aa5e96
diff --git a/runtime/dom/media/src/lib.rs b/runtime/dom/media/src/lib.rsindex 5fd0df5d..c26eb82c 100644--- a/runtime/dom/media/src/lib.rs+++ b/runtime/dom/media/src/lib.rs@@ -119,6 +119,10 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mu{m.seeking = Some(t);st.ask(Cmd::Seek(t));+ // the frames decoded ahead for where it was are never shown: a seek while playing went on showing up+ // to a quarter second of them (and telling their times) until its own frame came, a stretch played+ // again after a seek back (11-16)+ m.ahead.clear();}m.seek = seek;}@@ -142,6 +146,8 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &muout.push(if m.video { json!({"id": id, "type": "loadedmetadata", "w": w, "h": h, "duration": duration}) } else { json!({"id": id, "type": "loadedmetadata", "duration": duration}) });}Msg::Fail(err) => {+ // a seek that failed lands nowhere: the frames after it aren't held back for it+ m.seeking = None;bevy::log::warn!("raea-page: media: {err}");out.push(json!({"id": id, "type": "error", "message": err}));}@@ -166,9 +172,10 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mutold(m, id, t, out);}}- // a playing video's frame, for later; one that comes after a pause is for nothing+ // a playing video's frame, for later; one that comes after a pause is for nothing, and so is one decoded+ // before a seek still on its way (the decoder answers a seek with its frame first, then plays on from it)Msg::Due(t, f, due, halves) => {- if m.playing {+ if keep_due(m.playing, m.seeking) {m.ahead.push_back((t, (f.width, f.height, f.rgba), due, halves));}}@@ -274,6 +281,12 @@ fn due_by<T>(ahead: &mut VecDeque<(f64, T, Instant, Halvings)>, reach: Instant)(due, passed)}+/// Whether a playing video's frame decoded ahead (`Msg::Due`) waits to be shown: not after a pause, and not while a+/// seek is on its way, when it was decoded for where the video was before the seek.+fn keep_due(playing: bool, seeking: Option<f64>) -> bool {+ playing && seeking.is_none()+}+/// A playing element's time: each as `time` (its currentTime), and a `timeupdate` four times a second.fn told(m: &mut Media, id: u64, t: f64, out: &mut Vec<Value>) {out.push(json!({"id": id, "type": "time", "time": t}));@@ -322,6 +335,15 @@ fn set_image(doc: &mut BaseDocument, n: blitz_dom::NodeId, w: u32, h: u32, rgba:mod tests {use super::*;+ /// A frame decoded ahead waits only while playing and no seek is on its way: one that comes between a seek and+ /// its answer was decoded for where the video was, and shown it played that stretch again (11-16).+ #[test]+ fn frames_decoded_before_a_seek_are_not_kept() {+ assert!(keep_due(true, None));+ assert!(!keep_due(true, Some(2.0)));+ assert!(!keep_due(false, None));+ }+/// At a sync the frame shown is the latest one due by then; earlier ones due are passed over, later ones wait.#[test]fn the_frame_due_is_the_latest_whose_moment_has_come() {diff --git a/runtime/js/src/media_play.rs b/runtime/js/src/media_play.rsindex 2e2bf99b..3ec6690d 100644--- a/runtime/js/src/media_play.rs+++ b/runtime/js/src/media_play.rs@@ -147,13 +147,17 @@ impl<'a> Player<'a> {}}if let Some(t) = seek {- // the frame at exactly the time asked (the element's `seeked`), and a playing clock goes on from it- if self.clock.is_some() {- self.go(t);- }+ // the frame at exactly the time asked (the element's `seeked`), and a playing clock goes on from it once+ // it is sent: started before, the seek's decode (from the keyframe before it: 30 to 300 ms at 4K) ran+ // on the clock, and the frames after it were skipped to catch up (11-16)if !self.frame(t, &tx) {return self.stop();}+ if self.clock.is_some() {+ self.go(t);+ // the frame showing at t has gone: the next one is the first to decode+ self.cursor = Self::index_at(t, self.fps) + 1;+ }}if let Some((at, looping)) = play {self.looping = looping;@@ -186,6 +190,11 @@ impl<'a> Player<'a> {Duration::from_secs_f64(wait)}+ /// The index (at fps) of the frame showing at `t`: one on fps's grid is its own, not the one before for a rounding.+ fn index_at(t: f64, fps: f64) -> i64 {+ (t * fps + 1e-6).floor() as i64+ }+/// The cursor's frame's time on the clock.fn cursor_time(&self) -> f64 {self.cursor as f64 / self.fps + self.lap@@ -353,15 +362,78 @@ mod tests {/// A second of 30 fps picture and a tone (ffmpeg's test sources), or None without ffmpeg.fn clip() -> Option<std::path::PathBuf> {- let p = std::env::temp_dir().join(format!("raea-media-play-{}.mp4", std::process::id()));+ clip_of("1", "one")+ }++ /// `seconds` of 30 fps picture and a tone, named `name` among this run's clips, or None without ffmpeg.+ fn clip_of(seconds: &str, name: &str) -> Option<std::path::PathBuf> {+ let p = std::env::temp_dir().join(format!("raea-media-play-{}-{name}.mp4", std::process::id()));let ok = std::process::Command::new("ffmpeg")- .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=30", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-t", "1", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest"])+ .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=30", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-t", seconds, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest"]).arg(&p).status().is_ok_and(|s| s.success());ok.then_some(p)}+ /// A seek while playing (raea feed's timeline, 11-16: a stretch played twice): the decoder answers with the frame+ /// at the time asked before any other news from its new place, nothing it decoded for the old place comes after+ /// that frame, and play goes on from the frame after it, due on a clock started once it was sent.+ #[test]+ fn a_seek_while_playing_answers_first_and_plays_on_from_there() {+ // SAFETY: set before any stream reads it, and nothing else in this test binary reads it concurrently+ unsafe { std::env::set_var("RAEA_AUDIO_MUTE", "1") };+ let Some(path) = clip_of("3", "seek") else { return eprintln!("no ffmpeg: skipped") };+ let mut st = stream::open(path.to_str().unwrap(), true).expect("a stream");+ assert!(matches!(next(&st, Duration::from_secs(10)), Some(Msg::Meta { .. })));+ assert!(matches!(next(&st, Duration::from_secs(5)), Some(Msg::Frame(t, ..)) if t == 0.0));+ st.ask(Cmd::Play { at: 0.0, looping: false });+ // play until frames from past a second are coming+ let until = Instant::now() + Duration::from_secs(3);+ let mut furthest = 0.0;+ while Instant::now() < until && furthest < 1.2 {+ if let Some(Msg::Due(t, ..)) = next(&st, Duration::from_millis(200)) {+ furthest = f64::max(furthest, t);+ }+ }+ assert!(furthest >= 1.2, "played to {furthest}");+ // back to 0.5 while playing: what was on its way may come first, then the seek's frame+ let asked = Instant::now();+ st.ask(Cmd::Seek(0.5));+ let mut answered = None;+ let (mut after, mut last) = (Vec::new(), 0.5);+ let until = Instant::now() + Duration::from_secs(2);+ while Instant::now() < until && after.len() < 10 {+ match next(&st, Duration::from_millis(300)) {+ Some(Msg::Frame(t, ..)) => {+ assert_eq!(t, 0.5, "the seek's frame");+ answered = Some(Instant::now());+ }+ Some(Msg::Due(t, _, due, _)) if answered.is_some() => {+ assert!(t > last, "after the seek, frames in order from it: {t} after {last}");+ last = t;+ after.push((t, due));+ }+ _ => {}+ }+ }+ let answered = answered.expect("the seek answered with its frame");+ assert!(answered.duration_since(asked) < Duration::from_secs(1));+ // the frame after the seek's (index 15 at 30 fps is 0.5 itself): the seek's frame isn't sent twice+ let first = after.first().expect("play went on after the seek").0;+ assert!((first - 16.0 / 30.0).abs() < 1e-9, "the first frame after the seek is at {first}");+ // each due a frame on from the seek's moment, on a clock started when the seek's frame went (not before its+ // decode), so none had to be skipped: ten frames in a row+ for (i, (t, _)) in after.iter().enumerate() {+ assert!((t - (16 + i) as f64 / 30.0).abs() < 1e-9, "frame {i} after the seek is at {t}");+ }+ let (t1, due1) = after[0];+ let on_clock = due1.saturating_duration_since(answered).as_secs_f64();+ assert!(on_clock <= t1 - 0.5 + 0.03, "the first frame after the seek is due {on_clock} s after its answer");+ st.ask(Cmd::Pause);+ let _ = std::fs::remove_file(path);+ }+/// 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]diff --git a/runtime/js/src/media_sound.rs b/runtime/js/src/media_sound.rsindex d600b0e5..225e8270 100644--- a/runtime/js/src/media_sound.rs+++ b/runtime/js/src/media_sound.rs@@ -13,10 +13,20 @@ use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};const NONE: u64 = u64::MAX;struct Shared {- /// where the sound is in the source, in source samples (f64 bits): only the device's callback writes it+ /// where the sound is in the source, in source samples (f64 bits): the end of what the device's callback last+ /// wrote, or where `start` put itpos: AtomicU64,+ /// where that callback's samples began, in source samples (f64 bits): the time is read from here, on the wall's+ /// clock since the callback, and never past `pos`+ from: AtomicU64,+ /// when that callback ran (or `start`), in ns since `base()`+ when: AtomicU64,/// a time asked for, in source samples (f64 bits), taken by the next callback; NONE when there's nonejump: AtomicU64,+ /// counts `start`s: a callback that ran across one doesn't write where it got to over the jump+ starts: AtomicU64,+ /// the clock's last reading, in seconds (f64 bits): it never goes back between starts+ read: AtomicU64,/// the device's delay from a callback to its sound reaching the speaker, in seconds (f64 bits)delay: AtomicU64,muted: AtomicBool,@@ -25,6 +35,88 @@ struct Shared {running: AtomicBool,}+/// The moment the sound clocks count from (Shared::when).+fn base() -> std::time::Instant {+ static BASE: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();+ *BASE.get_or_init(std::time::Instant::now)+}++/// Now, in ns since `base()`.+fn now_ns() -> u64 {+ base().elapsed().as_nanos() as u64+}++impl Shared {+ fn new(muted: bool) -> Shared {+ let zero = 0f64.to_bits();+ Shared { pos: AtomicU64::new(zero), from: AtomicU64::new(zero), when: AtomicU64::new(now_ns()), jump: AtomicU64::new(NONE), starts: AtomicU64::new(0), read: AtomicU64::new(zero), delay: AtomicU64::new(zero), muted: AtomicBool::new(muted), volume: AtomicU32::new(1f32.to_bits()), running: AtomicBool::new(false) }+ }++ /// A callback beginning: where its samples start (a jump asked for, else where the last one ended), and the+ /// `start`s so far, to hand back to `wrote`.+ fn begin(&self) -> (f64, u64) {+ let starts = self.starts.load(Relaxed);+ let jump = self.jump.swap(NONE, Relaxed);+ (if jump != NONE { f64::from_bits(jump) } else { f64::from_bits(self.pos.load(Relaxed)) }, starts)+ }++ /// A callback's samples written, `from` to `to` (source samples), at `when` (ns since `base()`). One that ran+ /// across a `start` leaves the jump it asked for in place: written over it, the clock read the old place until+ /// the next callback (a seek back read as the end of the film: the loop went round twice, frames came twice).+ fn wrote(&self, from: f64, to: f64, when: u64, starts: u64) {+ if self.starts.load(Relaxed) != starts {+ return;+ }+ self.from.store(from.to_bits(), Relaxed);+ self.when.store(when, Relaxed);+ self.pos.store(to.to_bits(), Relaxed);+ }++ /// Plays from `p` (source samples): the next callback starts there, and the clock reads from there at once.+ fn start(&self, p: f64) {+ self.starts.fetch_add(1, Relaxed);+ self.jump.store(p.to_bits(), Relaxed);+ self.from.store(p.to_bits(), Relaxed);+ self.pos.store(p.to_bits(), Relaxed);+ self.when.store(now_ns(), Relaxed);+ self.read.store(f64::NEG_INFINITY.to_bits(), Relaxed);+ }++ /// The source time reaching the speaker at `now` (ns since `base()`), in seconds, from `rate` samples a second:+ /// the last callback's start, moved on by the wall's time since it ran, never past what it wrote (a late callback+ /// holds the picture rather than run ahead of the sound) and never back from the last reading. Read as the end of+ /// what was last written, as it was, the clock stood still between callbacks and jumped a buffer at each (10 ms+ /// steps on this Mac), and a 60 fps film's frames came 6 to 27 ms apart where 16.7 is even.+ fn time_at(&self, now: u64, rate: f64) -> f64 {+ let (from, to) = (f64::from_bits(self.from.load(Relaxed)), f64::from_bits(self.pos.load(Relaxed)));+ let since = now.saturating_sub(self.when.load(Relaxed)) as f64 / 1e9;+ let t = (from / rate + since).min(to / rate) - f64::from_bits(self.delay.load(Relaxed));+ let last = f64::from_bits(self.read.fetch_max_f64(t));+ t.max(last)+ }+}++/// `fetch_max` for an f64 kept as its bits.+trait FetchMaxF64 {+ /// Stores the larger of what's there and `v`; returns what was there.+ fn fetch_max_f64(&self, v: f64) -> u64;+}++impl FetchMaxF64 for AtomicU64 {+ fn fetch_max_f64(&self, v: f64) -> u64 {+ let mut cur = self.load(Relaxed);+ loop {+ if f64::from_bits(cur) >= v {+ return cur;+ }+ match self.compare_exchange_weak(cur, v.to_bits(), Relaxed, Relaxed) {+ Ok(_) => return cur,+ Err(now) => cur = now,+ }+ }+ }+}+/// The device's stream for one element's sound.pub struct Sound {stream: cpal::Stream,@@ -52,7 +144,7 @@ impl Sound {let ch = (def.channels() as usize).max(1);let rate = audio.rate as f64;let step = rate / def.sample_rate().0 as f64;- let shared = Arc::new(Shared { pos: AtomicU64::new(0f64.to_bits()), jump: AtomicU64::new(NONE), delay: AtomicU64::new(0f64.to_bits()), muted: AtomicBool::new(muted), volume: AtomicU32::new(1f32.to_bits()), running: AtomicBool::new(false) });+ let shared = Arc::new(Shared::new(muted));let s = shared.clone();let src = audio.channels;let last = len - 1;@@ -66,15 +158,16 @@ impl Sound {c[i] + (c[i + 1] - c[i]) * f};let callback = move |out: &mut [f32], info: &cpal::OutputCallbackInfo| {+ let when = now_ns();let ts = info.timestamp();if let Some(d) = ts.playback.duration_since(&ts.callback) {s.delay.store(d.as_secs_f64().to_bits(), Relaxed);}- let jump = s.jump.swap(NONE, Relaxed);- let mut p = if jump != NONE { f64::from_bits(jump) } else { f64::from_bits(s.pos.load(Relaxed)) };+ let (from, starts) = s.begin();+ let mut p = from;if !s.running.load(Relaxed) {out.fill(0.0);- s.pos.store(p.to_bits(), Relaxed);+ s.wrote(p, p, when, starts);return;}let gain = if s.muted.load(Relaxed) { 0.0 } else { f32::from_bits(s.volume.load(Relaxed)) };@@ -92,7 +185,7 @@ impl Sound {}p += step;}- s.pos.store(p.to_bits(), Relaxed);+ s.wrote(from, p, when, starts);};let stream = dev.build_output_stream(&def.config(), callback, |e| eprintln!("raea-runtime-js: media sound: {e}"), None).map_err(|e| format!("audio stream: {e}"))?;Ok(Sound { stream, shared, rate, len: len as f64 / rate })@@ -100,9 +193,7 @@ impl Sound {/// Plays from `t` seconds on.pub fn start(&self, t: f64) {- let p = (t.max(0.0) * self.rate).to_bits();- self.shared.jump.store(p, Relaxed);- self.shared.pos.store(p, Relaxed);+ self.shared.start(t.max(0.0) * self.rate);self.shared.running.store(true, Relaxed);let _ = self.stream.play();}@@ -122,9 +213,103 @@ impl Sound {self.shared.volume.store(v.to_bits(), Relaxed);}- /// The source time now reaching the speaker: what the picture shows to be in step with it.+ /// The source time now reaching the speaker: what the picture shows to be in step with it (`Shared::time_at`).pub fn time(&self) -> f64 {- let t = f64::from_bits(self.shared.pos.load(Relaxed)) / self.rate - f64::from_bits(self.shared.delay.load(Relaxed));- t.clamp(0.0, self.len)+ self.shared.time_at(now_ns(), self.rate).clamp(0.0, self.len)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const RATE: f64 = 48_000.0;+ /// a device's buffer: 512 samples, 10.7 ms at 48 kHz+ const BUF: f64 = 512.0;+ const MS: u64 = 1_000_000;++ /// A callback at `at` (ns since `base()`) writing one buffer on from where the last ended.+ fn callback(s: &Shared, at: u64) {+ let (from, starts) = s.begin();+ s.wrote(from, from + BUF, at, starts);+ }++ /// Between two callbacks the clock moves on with the wall's, a millisecond a millisecond: read as the end of+ /// what was last written, it stood still for a buffer and then jumped one (11-16).+ #[test]+ fn the_clock_moves_between_callbacks() {+ let s = Shared::new(false);+ s.start(0.0);+ let t0 = now_ns();+ let (mut last, mut most) = (f64::NAN, 0f64);+ for ms in 0..60u64 {+ // a callback each buffer, right on time+ let at = t0 + ms * MS;+ if ms % 11 == 0 {+ callback(&s, at);+ }+ let t = s.time_at(at, RATE);+ if !last.is_nan() {+ most = most.max(t - last);+ assert!(t >= last, "the clock went back: {t} after {last}");+ }+ last = t;+ }+ assert!(most < 0.0015, "the clock stepped {most} s in a millisecond");+ // and it keeps the wall's pace: 59 ms on, about 59 ms of sound+ assert!((last - 0.059).abs() < 0.003, "{last}");+ }++ /// A callback that comes late holds the clock at the end of what was written rather than running ahead of the+ /// sound; the next one takes it on from there.+ #[test]+ fn a_late_callback_holds_the_clock() {+ let s = Shared::new(false);+ s.start(0.0);+ let t0 = now_ns();+ callback(&s, t0);+ let end = BUF / RATE;+ assert!((s.time_at(t0 + 30 * MS, RATE) - end).abs() < 1e-9, "held at the buffer's end");+ callback(&s, t0 + 30 * MS);+ assert!((s.time_at(t0 + 31 * MS, RATE) - (end + 0.001)).abs() < 1e-6);+ }++ /// A start (a seek, a loop going round) made while a callback runs isn't written over by that callback: the clock+ /// reads the new place at once and after it ends, and the next callback plays from there.+ #[test]+ fn a_start_during_a_callback_stands() {+ let s = Shared::new(false);+ s.start(10.0 * RATE);+ let t0 = now_ns();+ callback(&s, t0);+ // a callback begins, the film goes back to 2 s, the callback ends+ let (from, starts) = s.begin();+ s.start(2.0 * RATE);+ s.wrote(from, from + BUF, t0 + 11 * MS, starts);+ let t = s.time_at(now_ns(), RATE);+ assert!((2.0..2.1).contains(&t), "read {t} after the start at 2 s");+ // the next callback takes the jump+ let (p, _) = s.begin();+ assert_eq!(p, 2.0 * RATE);+ }++ /// The delay to the speaker is taken off, and a delay that grows doesn't take the clock back.+ #[test]+ fn the_delay_never_takes_it_back() {+ let s = Shared::new(false);+ s.start(RATE);+ let t0 = now_ns();+ callback(&s, t0);+ let before = s.time_at(t0 + 5 * MS, RATE);+ assert!((before - 1.005).abs() < 1e-6);+ s.delay.store(0.02f64.to_bits(), Relaxed);+ assert_eq!(s.time_at(t0 + 6 * MS, RATE), before, "held while the delay is made up");+ // (at 10 ms on, 1.010 - 0.02 is still behind what was read)+ assert_eq!(s.time_at(t0 + 10 * MS, RATE), before);+ // once a callback brings the sound past it, the clock goes on from there+ callback(&s, t0 + 11 * MS);+ callback(&s, t0 + 22 * MS);+ let t = s.time_at(t0 + 30 * MS, RATE);+ assert!((t - (1.0 + 2.0 * BUF / RATE + 0.008 - 0.02)).abs() < 1e-6, "{t}");}}