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
Page media plays: video and audio elements' play(), pause() and load() drive the host's player, on the sound's clock
shinyobjectzf8844bb38575
diff --git a/Cargo.lock b/Cargo.lockindex ce5f8549..a9936764 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14810,6 +14810,7 @@ version = "0.1.0"dependencies = ["base64 0.22.1","bevy",+ "cpal 0.15.3","raea-bevy-world","raea-core-wire","raea-io-home",diff --git a/runtime/dom/src/media.rs b/runtime/dom/src/media.rsindex f3428808..69ba64b8 100644--- a/runtime/dom/src/media.rs+++ b/runtime/dom/src/media.rs@@ -2,7 +2,10 @@//! on a thread of its own (raea-runtime-js's stream), what it tells goes to the element's JS as raea-runtime-js's `media` host event//! (`loadedmetadata`, `loadeddata`, `seeked`, `error`: sdk/ui's dom layer fires each at the element), and a video's//! frame is its picture, which its natural size is. Its poster shows until the first seek; with none, the frame does.-//! A seek is the prop `__seek` ([time, n], set by the dom layer's `currentTime`).+//! A seek is the prop `__seek` ([time, n], set by the dom layer's `currentTime`); playing is `__play` ([on, time, n,+//! loop], set by `play()` and `pause()`), and `__muted` the element's muted. Playing, the decoder's frames come on the+//! source's clock (its sound's: raea-runtime-js media_play.rs), each a `time` news for the element's currentTime, with+//! `timeupdate` four times a second as a browser's, `playing` once it's going, and `ended` at its end.use std::collections::HashMap;use std::sync::Arc;@@ -17,6 +20,8 @@ use raea_sys_page::ops::Nodes;/// One media element's source and what its decoder has told.pub struct Media {src: String,+ /// `__load` as last seen (the dom layer's load() count)+ load: u64,poster: Option<String>,seek: Option<Value>,stream: Option<Stream>,@@ -29,6 +34,12 @@ pub struct Media {duration: f64,/// the latest frame: width, height, pixelsframe: Option<(u32, u32, Arc<Vec<u8>>)>,+ /// `__play` as last seen, and whether it asks to play+ play: Option<Value>,+ playing: bool,+ muted: Option<bool>,+ /// when the last `timeupdate` went+ told: Option<std::time::Instant>,}/// Each media element by its wire id.@@ -45,11 +56,13 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mulet props = nodes.props.get(&id);let s = |k: &str| props.and_then(|p| p.get(k)).and_then(Value::as_str).filter(|v| !v.is_empty()).map(String::from);let (src, poster, seek) = (s("src").unwrap_or_default(), s("poster"), props.and_then(|p| p.get("__seek")).cloned());+ // load(): its source opened again, even the same one+ let load = props.and_then(|p| p.get("__load")).and_then(Value::as_u64).unwrap_or(0);let m = match medias.get_mut(&id) {- Some(m) if m.src == src => m,+ Some(m) if m.src == src && m.load == load => m,_ => {let stream = (!src.is_empty()).then(|| raea_runtime_js::media_html::stream::open(&raea_sys_page::net::page_path(&src), video)).flatten();- medias.insert(id, Media { src, poster: None, seek: None, stream, video, loaded: false, seeking: None, seeked: false, duration: f64::NAN, frame: None });+ medias.insert(id, Media { src, load, poster: None, seek: None, stream, video, loaded: false, seeking: None, seeked: false, duration: f64::NAN, frame: None, play: None, playing: false, muted: None, told: None });medias.get_mut(&id).unwrap()}};@@ -58,6 +71,13 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mum.poster = poster;redraw = true;}+ let muted = props.and_then(|p| p.get("__muted")).and_then(Value::as_bool);+ if m.muted != muted {+ if let (Some(v), Some(st)) = (muted, m.stream.as_mut()) {+ st.muted(v);+ }+ m.muted = muted;+ }if m.seek != seek {if let Some(t) = seek.as_ref().and_then(|v| v.get(0)).and_then(Value::as_f64)&& let Some(st) = m.stream.as_mut()@@ -67,6 +87,18 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mu}m.seek = seek;}+ let play = props.and_then(|p| p.get("__play")).cloned();+ if m.play != play {+ if let (Some(p), Some(st)) = (play.as_ref(), m.stream.as_mut()) {+ m.playing = p.get(0).and_then(Value::as_bool).unwrap_or(false);+ if m.playing {+ st.play(p.get(1).and_then(Value::as_f64).unwrap_or(0.0), p.get(3).and_then(Value::as_bool).unwrap_or(false));+ } else {+ st.pause();+ }+ }+ m.play = play;+ }while let Some(msg) = m.stream.as_ref().and_then(Stream::next) {match msg {Msg::Meta { w, h, duration } => {@@ -89,6 +121,25 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mum.seeked = true;out.push(json!({"id": id, "type": "seeked", "time": t}));}+ if m.playing {+ m.seeked = true;+ told(m, id, t, out);+ }+ }+ Msg::Time(t) => {+ if m.seeking.take_if(|s| (*s - t).abs() < 1e-9).is_some() {+ out.push(json!({"id": id, "type": "seeked", "time": t}));+ }+ if m.playing {+ told(m, id, t, out);+ } else {+ out.push(json!({"id": id, "type": "time", "time": t}));+ }+ }+ Msg::Playing(t) => out.push(json!({"id": id, "type": "playing", "time": t})),+ Msg::Ended(t) => {+ m.playing = false;+ out.push(json!({"id": id, "type": "ended", "time": t}));}}}@@ -105,6 +156,15 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mu}}+/// 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}));+ if m.told.is_none_or(|w| w.elapsed() >= std::time::Duration::from_millis(250)) {+ m.told = Some(std::time::Instant::now());+ out.push(json!({"id": id, "type": "timeupdate", "time": t}));+ }+}+/// A poster's picture, decoded as an img's source is.fn poster_image(src: &str) -> Option<(u32, u32, Vec<u8>)> {let (mime, bytes) = match raea_io_net::data_url(src) {diff --git a/runtime/js/Cargo.toml b/runtime/js/Cargo.tomlindex 5b5e2767..e265ac37 100644--- a/runtime/js/Cargo.toml+++ b/runtime/js/Cargo.toml@@ -14,7 +14,7 @@ default = ["media"]# the portable engine (QuickJS) on Apple too, in place of JavaScriptCore: how the portable path is tested on a Macportable = ["raea-runtime-jsengine/portable"]# media (docs/ts-native.feature P15): video and sound through raea-io-media-media = ["dep:raea-io-media"]+media = ["dep:raea-io-media", "dep:cpal"][dependencies]# images@@ -34,6 +34,8 @@ serde_json = "1"raea-runtime-jsengine = { path = "../jsengine" }# video and audio elements' sources decoded (src/media_html.rs): the app's backends, else the ffmpeg CLI'sraea-io-media = { path = "../../io/media", default-features = false, optional = true }+# a playing video's or audio's sound out of the device (src/media_sound.rs), the cpal the mixer and the legacy app use+cpal = { version = "0.15", optional = true }# webaudio's samples across the wirebase64 = "0.22"# the HTML runtime bundled in process (html_page.rs): raea's files where an install or this checkout has them, anddiff --git a/runtime/js/src/lib.rs b/runtime/js/src/lib.rsindex ad8c7e93..7f96a0c0 100644--- a/runtime/js/src/lib.rs+++ b/runtime/js/src/lib.rs@@ -13,6 +13,10 @@ pub mod html_page;pub mod js;pub mod media_html;#[cfg(feature = "media")]+mod media_play;+#[cfg(feature = "media")]+mod media_sound;+#[cfg(feature = "media")]pub mod webaudio;pub mod net;pub mod os;diff --git a/runtime/js/src/media_html.rs b/runtime/js/src/media_html.rsindex 276bbfd8..8cadd95f 100644--- a/runtime/js/src/media_html.rs+++ b/runtime/js/src/media_html.rs@@ -8,21 +8,50 @@ pub mod stream {use std::sync::Mutex;use std::sync::mpsc::{Receiver, Sender, channel};- /// What a decoder tells: the source's metadata, a frame at a time (after the first, a seek's), or its failure.+ /// What a decoder tells: the source's metadata, a frame at a time (after the first, a seek's or a playing one's),+ /// 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 },Frame(f64, raea_io_media::Frame),+ /// a playing source's time (an audio one's, which has no frames; a video's when paused)+ Time(f64),+ /// playing from this time: the sound is on its way+ Playing(f64),+ /// played to its end (a looping source starts again instead)+ Ended(f64),Fail(String),}+ /// What the element asks of its decoder.+ pub(crate) enum Cmd {+ Seek(f64),+ Play { at: f64, looping: bool },+ Pause,+ Muted(bool),+ }+pub struct Stream {- tx: Sender<f64>,+ tx: Sender<Cmd>,rx: Mutex<Receiver<Msg>>,}impl Stream {pub fn seek(&mut self, t: f64) {- let _ = self.tx.send(t);+ let _ = self.tx.send(Cmd::Seek(t));+ }++ /// 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 fn play(&mut self, at: f64, looping: bool) {+ let _ = self.tx.send(Cmd::Play { at, looping });+ }++ pub fn pause(&mut self) {+ let _ = self.tx.send(Cmd::Pause);+ }++ pub fn muted(&mut self, muted: bool) {+ let _ = self.tx.send(Cmd::Muted(muted));}/// The decoder's next news, if it has any now.@@ -65,7 +94,7 @@ pub mod stream {(!s.is_empty()).then(|| PathBuf::from(s))}- fn run(path: &Path, video: bool, ticket: u64, rx: Receiver<f64>, tx: Sender<Msg>) {+ fn run(path: &Path, video: bool, ticket: u64, rx: Receiver<Cmd>, tx: Sender<Msg>) {let (lock, cv) = &TURN;let mut turn = cv.wait_while(lock.lock().unwrap(), |t| *t < ticket).unwrap();let done = |turn: &mut std::sync::MutexGuard<u64>| {@@ -75,31 +104,20 @@ pub mod stream {let r = first(path, video, &tx);done(&mut turn);drop(turn);- let Some(mut dec) = r else { return };- while let Ok(mut t) = rx.recv() {- // only the latest time asked for- while let Ok(n) = rx.try_recv() {- t = n;- }- let m = match dec.frame_at(t) {- Ok(f) => Msg::Frame(t, f),- Err(e) => Msg::Fail(e),- };- if tx.send(m).is_err() {- return;- }- }+ let Some(source) = r else { return };+ crate::media_play::Player::new(path, source).run(rx, tx);}- /// The source opened: audio's duration, or a video's metadata and its first frame (its decoder, to seek on).- fn first(path: &Path, video: bool, tx: &Sender<Msg>) -> Option<Box<dyn raea_io_media::VideoDecoder>> {+ /// The source opened: a video's metadata and first frame (its decoder, to seek and play on), or audio's duration+ /// (its samples, to play).+ fn first(path: &Path, video: bool, tx: &Sender<Msg>) -> Option<crate::media_play::Source> {let mut errs = vec![];if !video {for b in raea_io_media::preferred() {match b.decode_audio(path) {Ok(a) if a.len() > 0 => {let _ = tx.send(Msg::Meta { w: 0, h: 0, duration: a.duration() });- return None;+ return Some(crate::media_play::Source::Audio(a));}Ok(_) => errs.push(format!("{}: no sound", b.name())),Err(e) => errs.push(format!("{}: {e}", b.name())),@@ -128,7 +146,7 @@ pub mod stream {Ok(f) => Msg::Frame(0.0, f),Err(e) => Msg::Fail(e),});- Some(dec)+ Some(crate::media_play::Source::Video(dec))}/// Decoders open, and send their metadata and first frame, one at a time in the order they were made (the@@ -139,7 +157,7 @@ pub mod stream {pub fn open(src: &str, video: bool) -> Option<Stream> {let path = file_of(src)?;let ticket = NEXT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);- let (ttx, trx) = channel::<f64>();+ let (ttx, trx) = channel::<Cmd>();let (mtx, mrx) = channel::<Msg>();std::thread::Builder::new().name("raea-runtime-js-media".into())diff --git a/runtime/js/src/media_play.rs b/runtime/js/src/media_play.rsnew file mode 100644index 00000000..ba5846e3--- /dev/null+++ b/runtime/js/src/media_play.rs@@ -0,0 +1,282 @@+//! A `video` or `audio` playing (media_html.rs's stream, on its decoder's thread): seeks answered with the frame at the+//! time asked; played, frames as they fall due on the source's clock, which is its sound's (media_sound.rs) when it has+//! sound and the Mac a device, else the wall's. Frames are asked for at the clock's time, so a decoder that falls+//! behind skips frames rather than letting the picture lag its sound.++use std::path::Path;+use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};+use std::time::{Duration, Instant};++use crate::media_html::stream::{Cmd, Msg};+use crate::media_sound::Sound;++/// What was opened: a video's decoder, or an audio source's samples.+pub enum Source {+ Video(Box<dyn raea_io_media::VideoDecoder>),+ Audio(raea_io_media::Audio),+}++/// The clock while playing: the sound's, else the wall's from when play began.+enum Clock {+ Sound,+ Wall { from: f64, began: Instant },+}++pub struct Player<'a> {+ path: &'a Path,+ source: Source,+ duration: f64,+ fps: f64,+ /// the sound, opened on the first play; None after it couldn't be+ sound: Option<Option<Sound>>,+ muted: bool,+ clock: Option<Clock>,+ looping: bool,+ /// the frame (index at fps) last sent while playing, so a frame isn't decoded twice+ shown: Option<i64>,+ /// when the last Time news went (an audio source's, which has no frames)+ told: Option<Instant>,+}++impl<'a> Player<'a> {+ pub fn new(path: &'a Path, source: Source) -> Self {+ let (duration, fps) = match &source {+ Source::Video(d) => (d.info().duration, d.info().fps),+ Source::Audio(a) => (a.duration(), 0.0),+ };+ let fps = if fps.is_finite() && fps > 1.0 { fps } else { 30.0 };+ Player { path, source, duration, fps, sound: None, muted: false, clock: None, looping: false, shown: None, told: None }+ }++ /// Answers the element's asks until it's gone (its stream dropped).+ pub fn run(mut self, rx: Receiver<Cmd>, tx: Sender<Msg>) {+ loop {+ // playing: wake for the next frame; paused: wait for an ask+ let first = if self.clock.is_some() {+ match rx.recv_timeout(Duration::from_secs_f64(0.5 / self.fps)) {+ Ok(c) => Some(c),+ Err(RecvTimeoutError::Timeout) => None,+ Err(RecvTimeoutError::Disconnected) => return self.stop(),+ }+ } else {+ match rx.recv() {+ Ok(c) => Some(c),+ Err(_) => return self.stop(),+ }+ };+ // the asks waiting, the latest of each kind+ let (mut seek, mut play, mut pause) = (None, None, false);+ for c in first.into_iter().chain(std::iter::from_fn(|| rx.try_recv().ok())) {+ match c {+ Cmd::Seek(t) => seek = Some(t),+ Cmd::Play { at, looping } => (play, pause) = (Some((at, looping)), false),+ Cmd::Pause => (play, pause) = (None, true),+ Cmd::Muted(m) => {+ self.muted = m;+ if let Some(Some(s)) = &self.sound {+ s.set_muted(m);+ }+ }+ }+ }+ if pause && self.clock.is_some() {+ let t = self.now();+ self.halt();+ if tx.send(Msg::Time(t)).is_err() {+ return;+ }+ }+ 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);+ }+ if !self.frame(t, &tx) {+ return self.stop();+ }+ }+ if let Some((at, looping)) = play {+ self.looping = looping;+ if self.clock.is_none() {+ self.go(seek.unwrap_or(at));+ if tx.send(Msg::Playing(seek.unwrap_or(at))).is_err() {+ return self.stop();+ }+ }+ }+ if self.clock.is_some() && !self.tick(&tx) {+ return self.stop();+ }+ }+ }++ /// The clock's time now.+ fn now(&self) -> f64 {+ match (&self.clock, &self.sound) {+ (Some(Clock::Sound), Some(Some(s))) => s.time(),+ (Some(Clock::Wall { from, began }), _) => from + began.elapsed().as_secs_f64(),+ _ => 0.0,+ }+ }++ /// Plays from `t`: the sound when there is one (opened the first time), else the wall.+ fn go(&mut self, t: f64) {+ if self.sound.is_none() {+ let audio = match &self.source {+ Source::Audio(a) => Some(raea_io_media::Audio { rate: a.rate, channels: a.channels.clone() }),+ // a video's sound track, decoded once, on the first play (a video only looked at never pays for it)+ Source::Video(_) => raea_io_media::preferred().into_iter().find_map(|b| b.decode_audio(self.path).ok()).filter(|a| a.len() > 0),+ };+ self.sound = Some(audio.and_then(|a| Sound::open(a, self.muted).inspect_err(|e| bevy::log::debug!("raea-runtime-js: media plays on the wall's clock: {e}")).ok()));+ }+ self.shown = None;+ self.told = None;+ self.clock = Some(match &self.sound {+ Some(Some(s)) => {+ s.start(t);+ Clock::Sound+ }+ _ => Clock::Wall { from: t, began: Instant::now() },+ });+ }++ fn halt(&mut self) {+ if let Some(Some(s)) = &self.sound {+ s.stop();+ }+ self.clock = None;+ }++ fn stop(mut self) {+ self.halt();+ }++ /// The frame at `t`, sent as the frame at exactly `t`; false when the element's gone.+ fn frame(&mut self, t: f64, tx: &Sender<Msg>) -> bool {+ match &mut self.source {+ Source::Video(dec) => tx.send(dec.frame_at(t).map_or_else(Msg::Fail, |f| Msg::Frame(t, f))).is_ok(),+ Source::Audio(_) => tx.send(Msg::Time(t)).is_ok(),+ }+ }++ /// One step of playing: the end (again from the start when looping), or the frame falling due now.+ fn tick(&mut self, tx: &Sender<Msg>) -> bool {+ let t = self.now();+ if self.duration.is_finite() && t >= self.duration - 0.5 / self.fps {+ if self.looping {+ self.go(0.0);+ return self.frame(0.0, tx);+ }+ self.halt();+ return tx.send(Msg::Ended(self.duration)).is_ok();+ }+ match &self.source {+ Source::Video(_) => {+ let i = (t * self.fps).floor() as i64;+ if self.shown == Some(i) {+ return true;+ }+ self.shown = Some(i);+ self.frame(t, tx)+ }+ Source::Audio(_) => {+ if self.told.is_some_and(|w| w.elapsed() < Duration::from_millis(100)) {+ return true;+ }+ self.told = Some(Instant::now());+ tx.send(Msg::Time(t)).is_ok()+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use crate::media_html::stream::{self, Msg, Stream};+ use std::time::{Duration, Instant};++ /// The next news within `within`, polled as the page host polls it (each frame).+ fn next(st: &Stream, within: Duration) -> Option<Msg> {+ let t = Instant::now();+ while t.elapsed() < within {+ if let Some(m) = st.next() {+ return Some(m);+ }+ std::thread::sleep(Duration::from_millis(2));+ }+ None+ }++ /// 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()));+ 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"])+ .arg(&p)+ .status()+ .is_ok_and(|s| s.success());+ ok.then_some(p)+ }++ /// 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]+ fn plays_seeks_loops_and_pauses() {+ // 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() 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 { w: 160, h: 90, .. })));+ assert!(matches!(next(&st, Duration::from_secs(5)), Some(Msg::Frame(t, _)) if t == 0.0));++ let began = Instant::now();+ st.play(0.0, false);+ assert!(matches!(next(&st, Duration::from_secs(1)), Some(Msg::Playing(t)) if t == 0.0));+ let (mut frames, mut last, mut ended) = (0, -1.0, None);+ while let Some(m) = next(&st, Duration::from_secs(3)) {+ match m {+ Msg::Frame(t, f) => {+ assert!(t > last, "frames in order: {t} after {last}");+ assert_eq!((f.width, f.height), (160, 90));+ (frames, last) = (frames + 1, t);+ }+ Msg::Ended(t) => {+ ended = Some((t, began.elapsed().as_secs_f64()));+ break;+ }+ _ => {}+ }+ }+ let (end, took) = ended.expect("it ended");+ assert!((end - 1.0).abs() < 0.05, "ended at its duration: {end}");+ assert!((0.85..1.4).contains(&took), "a second's clip took {took} s");+ assert!(frames >= 20, "{frames} frames of 30");++ st.seek(0.5);+ assert!(matches!(next(&st, Duration::from_secs(2)), Some(Msg::Frame(t, _)) if t == 0.5));++ st.play(0.5, true);+ let (mut wrapped, mut last, until) = (false, 0.5, Instant::now() + Duration::from_millis(1200));+ while Instant::now() < until {+ match next(&st, Duration::from_millis(200)) {+ Some(Msg::Frame(t, _)) => {+ wrapped |= t < last;+ last = t;+ }+ Some(Msg::Ended(_)) => panic!("a looping source doesn't end"),+ _ => {}+ }+ }+ assert!(wrapped, "looping went round");++ st.pause();+ let mut after = 0;+ while let Some(m) = next(&st, Duration::from_millis(300)) {+ if matches!(m, Msg::Frame(..)) {+ after += 1;+ }+ }+ assert!(after <= 1, "{after} frames after pausing");+ let _ = std::fs::remove_file(path);+ }+}diff --git a/runtime/js/src/media_sound.rs b/runtime/js/src/media_sound.rsnew file mode 100644index 00000000..2f899834--- /dev/null+++ b/runtime/js/src/media_sound.rs@@ -0,0 +1,122 @@+//! A playing `video`'s or `audio`'s sound (media_html.rs's stream plays it): its source's samples out of the default+//! output device through cpal, resampled to the device's rate, from a time on. Where the sound has got to is the+//! element's clock, so a video's frames follow its sound and the two can't drift apart over a long film. A muted element+//! plays silence on the same clock. RAEA_AUDIO_MUTE=1 (agents' runs, tests) opens no device: the stream keeps the wall's+//! clock instead.++use std::sync::Arc;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};++use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};++/// No time asked for (`Shared::jump`).+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+ pos: AtomicU64,+ /// a time asked for, in source samples (f64 bits), taken by the next callback; NONE when there's none+ jump: AtomicU64,+ /// the device's delay from a callback to its sound reaching the speaker, in seconds (f64 bits)+ delay: AtomicU64,+ muted: AtomicBool,+ running: AtomicBool,+}++/// The device's stream for one element's sound.+pub struct Sound {+ stream: cpal::Stream,+ shared: Arc<Shared>,+ rate: f64,+ len: f64,+}++impl Sound {+ /// The default output device, playing `audio` when started; an error when there's no device (or it's muted for+ /// the whole process, or the source has no sound).+ pub fn open(audio: raea_io_media::Audio, muted: bool) -> Result<Sound, String> {+ if std::env::var("RAEA_AUDIO_MUTE").as_deref() == Ok("1") {+ return Err("RAEA_AUDIO_MUTE=1".into());+ }+ let len = audio.len();+ if len == 0 || audio.rate == 0 {+ return Err("no sound".into());+ }+ let dev = cpal::default_host().default_output_device().ok_or("no audio output device")?;+ let def = dev.default_output_config().map_err(|e| format!("audio output: {e}"))?;+ if def.sample_format() != cpal::SampleFormat::F32 {+ return Err(format!("audio output: {:?} samples, not f32", def.sample_format()));+ }+ 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), running: AtomicBool::new(false) });+ let s = shared.clone();+ let src = audio.channels;+ let last = len - 1;+ // the sample at fractional position `p` of channel `c`, straight-line between its neighbours+ let at = move |c: &[f32], p: f64| -> f32 {+ let i = p as usize;+ if i >= last {+ return if i == last { c[last] } else { 0.0 };+ }+ let f = (p - i as f64) as f32;+ c[i] + (c[i + 1] - c[i]) * f+ };+ let callback = move |out: &mut [f32], info: &cpal::OutputCallbackInfo| {+ 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)) };+ if !s.running.load(Relaxed) {+ out.fill(0.0);+ s.pos.store(p.to_bits(), Relaxed);+ return;+ }+ let gain = if s.muted.load(Relaxed) { 0.0 } else { 1.0 };+ for frame in out.chunks_mut(ch) {+ if p as usize > last {+ frame.fill(0.0);+ } else if src.len() == 1 || ch == 1 {+ // mono out of a stereo source, or a mono source on every speaker+ let v = src.iter().map(|c| at(c, p)).sum::<f32>() / src.len() as f32 * gain;+ frame.fill(v);+ } else {+ for (k, o) in frame.iter_mut().enumerate() {+ *o = src.get(k).map(|c| at(c, p) * gain).unwrap_or(0.0);+ }+ }+ p += step;+ }+ s.pos.store(p.to_bits(), Relaxed);+ };+ 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 })+ }++ /// 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.running.store(true, Relaxed);+ let _ = self.stream.play();+ }++ pub fn stop(&self) {+ self.shared.running.store(false, Relaxed);+ let _ = self.stream.pause();+ }++ pub fn set_muted(&self, muted: bool) {+ self.shared.muted.store(muted, Relaxed);+ }++ /// The source time now reaching the speaker: what the picture shows to be in step with it.+ 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)+ }+}diff --git a/sdk/ui/src/dom/host.ts b/sdk/ui/src/dom/host.tsindex 51a22d43..709b5f81 100644--- a/sdk/ui/src/dom/host.ts+++ b/sdk/ui/src/dom/host.ts@@ -294,9 +294,13 @@ const REACT: Record<string, string> = {AnimationStart: "animationstart", AnimationEnd: "animationend", AnimationIteration: "animationiteration", TransitionEnd: "transitionend", TransitionStart: "transitionstart",Scroll: "scroll", ScrollEnd: "scrollend", PointerEnter: "pointerenter", PointerLeave: "pointerleave", MouseEnter: "mouseenter", MouseLeave: "mouseleave", Load: "load", Error: "error", Toggle: "toggle",LoadedMetadata: "loadedmetadata", LoadedData: "loadeddata", Seeking: "seeking", Seeked: "seeked",+ // a video's or audio's playing (dom/media.ts, the host's player)+ Play: "play", Pause: "pause", Playing: "playing", TimeUpdate: "timeupdate", Ended: "ended", CanPlay: "canplay", CanPlayThrough: "canplaythrough",+ Waiting: "waiting", VolumeChange: "volumechange", Emptied: "emptied", DurationChange: "durationchange", RateChange: "ratechange",};-export const DIRECT = new Set(["scroll", "scrollend", "pointerenter", "pointerleave", "mouseenter", "mouseleave", "load", "error", "toggle", "invalid", "loadedmetadata", "loadeddata", "seeking", "seeked"]);+const MEDIA_EVENTS = ["play", "pause", "playing", "timeupdate", "ended", "canplay", "canplaythrough", "waiting", "volumechange", "emptied", "durationchange", "ratechange"];+export const DIRECT = new Set(["scroll", "scrollend", "pointerenter", "pointerleave", "mouseenter", "mouseleave", "load", "error", "toggle", "invalid", "loadedmetadata", "loadeddata", "seeking", "seeked", ...MEDIA_EVENTS]);/** native type -> the React prop names it runs (onChange is special: text fields hear it from input) */export const REACT_BY_NATIVE = new Map<string, string[]>();diff --git a/sdk/ui/src/dom/media.ts b/sdk/ui/src/dom/media.tsindex a0f6c3c4..09fa2f74 100644--- a/sdk/ui/src/dom/media.ts+++ b/sdk/ui/src/dom/media.ts@@ -29,8 +29,11 @@ export class HTMLImageElement_ extends HTMLElement_ {}}-/** video and audio: the source's size and duration as the host decoded them; paused (the host plays nothing yet),- * muted as set, and currentTime, whose set seeks the host's decoder (`__seek`: the time and a count). */+/** video and audio: the source's size and duration as the host decoded them; currentTime, whose set seeks the host's+ * decoder (`__seek`: the time and a count); play() and pause(), which start and stop the host's player (`__play`: on,+ * the time, a count and loop; raea-runtime-js media_play.rs plays on the sound's clock, its frames this element's+ * picture), and muted (`__muted`). The host's news keeps currentTime (`time`) and fires playing, timeupdate and ended;+ * play and pause fire here, as a browser fires them, when they're asked. */export class HTMLMediaElement_ extends HTMLElement_ {_media?: MediaNews;get src() {@@ -42,27 +45,101 @@ export class HTMLMediaElement_ extends HTMLElement_ {_time = 0;_seeks = 0;_muted?: boolean;+ _playing = false;+ _plays = 0;+ /** the host told this element (a prop of its own beside its attributes) */+ _tell(k: string, v: unknown) {+ this._extra[k] = v;+ if (this._wired && this.__wid !== undefined) wire.set(this.__wid, k, v);+ }get paused() {- return true;+ return !this._playing;+ }+ setAttribute(n: string, v: unknown) {+ const was = this.getAttribute("src");+ super.setAttribute(n, v);+ if (this._playing && this._an(n) === "src" && this.getAttribute("src") !== was) {+ // a new source pauses while it loads, as a browser's load algorithm does (the page plays it again)+ this._playing = false;+ this._tell("__play", [false, this._time, ++this._plays, this.loop]);+ dispatchDirect(this, new Event_("pause", { bubbles: false }));+ }+ }+ /** how far the source has loaded (1 its metadata, 2 a frame), for the source it loaded: a new src starts again */+ _ready: [string, number] = ["", 0];+ _ended = false;+ get ended() {+ return this._ended;+ }+ get loop() {+ return this._props.loop === true || this.hasAttribute("loop");+ }+ get autoplay() {+ return this._props.autoPlay === true || this._props.autoplay === true || this.hasAttribute("autoplay");+ }+ play() {+ if (!this._playing) {+ this._playing = true;+ this._ended = false;+ this._tell("__muted", this.muted);+ this._tell("__play", [true, this._time >= (this.duration || Infinity) ? 0 : this._time, ++this._plays, this.loop]);+ dispatchDirect(this, new Event_("play", { bubbles: false }));+ }+ return Promise.resolve();+ }+ pause() {+ if (!this._playing) return;+ this._playing = false;+ this._tell("__play", [false, this._time, ++this._plays, this.loop]);+ dispatchDirect(this, new Event_("pause", { bubbles: false }));+ }+ /** Its source again from the start, as a browser's load algorithm: paused (with no pause event), at time 0, nothing+ * loaded, and the host's decoder opened again (`__load`), or dropped when there's no src. */+ load() {+ if (this._playing) {+ this._playing = false;+ this._tell("__play", [false, 0, ++this._plays, this.loop]);+ }+ this._time = 0;+ this._ended = false;+ this._ready = ["", 0];+ this._tell("__seek", [0, ++this._seeks]);+ this._media = undefined;+ this._tell("__load", ++this._loads);+ dispatchDirect(this, new Event_("emptied", { bubbles: false }));+ }+ _loads = 0;+ /** what the host's decoders take (AVFoundation's and the ffmpeg CLI's): the usual containers and codecs, "maybe" */+ canPlayType(type: string) {+ return /^(video|audio)\/(mp4|quicktime|x-m4v|webm|ogg|mpeg|mp3|aac|x-m4a|mp4a-latm|wav|x-wav|wave|flac)\b/i.test(String(type)) ? "maybe" : "";+ }+ get preload() {+ return this.getAttribute("preload") ?? "auto";+ }+ set preload(v: string) {+ this.setAttribute("preload", String(v));}get muted() {return this._muted ?? (this._props.muted === true || this.hasAttribute("muted"));}set muted(v: boolean) {+ const was = this.muted;this._muted = !!v;+ this._tell("__muted", this._muted);+ if (was !== this._muted) dispatchDirect(this, new Event_("volumechange", { bubbles: false }));}get duration() {return this._media?.duration ?? NaN;}get readyState() {- const t = this._media?.type;- return t === "loadeddata" || t === "seeked" ? 2 : t === "loadedmetadata" ? 1 : 0;+ return this._ready[0] === this.src ? this._ready[1] : 0;}get currentTime() {return this._time;}set currentTime(t: number) {this._time = Number(t) || 0;+ this._ended = false;this._extra.__seek = [this._time, ++this._seeks];if (this._wired && this.__wid !== undefined) wire.set(this.__wid, "__seek", this._extra.__seek);dispatchDirect(this, new Event_("seeking", { bubbles: false }));@@ -83,8 +160,25 @@ export function mediaNews(v: MediaNews & { id: number }) {const el = byWid(v.id) as (HTMLImageElement_ | HTMLMediaElement_) | null;if (!el || !v.type) return;el._media = { ...el._media, ...v, w: v.w ?? el._media?.w, h: v.h ?? el._media?.h, duration: v.duration ?? el._media?.duration };- if (el instanceof HTMLMediaElement_ && typeof v.time === "number") el._time = v.time;+ if (el instanceof HTMLMediaElement_) {+ if (typeof v.time === "number") el._time = v.time;+ const r = v.type === "loadedmetadata" ? 1 : v.type === "loadeddata" || v.type === "seeked" ? 2 : 0;+ if (r) el._ready = [el.src, Math.max(r, el._ready[0] === el.src ? el._ready[1] : 0)];+ }+ // a playing element's time: its currentTime, with no event (timeupdate comes on its own, four times a second)+ if (v.type === "time") return;+ if (el instanceof HTMLMediaElement_ && v.type === "ended") {+ // played to its end: paused there, as a browser's is (pause, then ended)+ if (!el._playing) return;+ el._playing = false;+ el._ended = true;+ dispatchDirect(el, new Event_("pause", { bubbles: false }));+ }dispatchDirect(el, new Event_(v.type, { bubbles: false }));+ if (el instanceof HTMLMediaElement_ && v.type === "loadeddata") {+ dispatchDirect(el, new Event_("canplay", { bubbles: false }));+ if (el.autoplay && !el._plays) void el.play();+ }}export class HTMLStyleElement_ extends HTMLElement_ {diff --git a/sdk/ui/test/dom.test.tsx b/sdk/ui/test/dom.test.tsxindex dfbf34d8..8857d45a 100644--- a/sdk/ui/test/dom.test.tsx+++ b/sdk/ui/test/dom.test.tsx@@ -6,7 +6,7 @@ import { beforeAll, describe, expect, test } from "bun:test";import { useEffect, useRef, useState } from "react";import { install, layout } from "../src/dom";import { createPortal, flushSync, mount } from "../src/react";-import { restart } from "../src/wire";+import { flush, restart } from "../src/wire";import { Host } from "./host";beforeAll(() => install());@@ -320,3 +320,73 @@ describe("dangerouslySetInnerHTML", () => {expect(host.nodes.get(host.tid("mark"))!.children.length).toBe(1);});});++describe("video and audio play on the host's player (runtime/dom media.rs, raea-runtime-js media_play.rs)", () => {+ test("play() and pause() ask the host and fire play and pause; its news keeps currentTime and fires the rest", () => {+ const host = fresh();+ let v: any;+ const seen: string[] = [];+ const ev = (e: any) => seen.push(`${e.type}@${e.currentTarget.currentTime.toFixed(1)}`);+ function App() {+ const r = useRef<any>(null);+ useEffect(() => void (v = r.current), []);+ return <video ref={r} data-testid="v" src="/media/renders/film.mp4" muted loop onPlay={ev} onPause={ev} onPlaying={ev} onTimeUpdate={ev} onEnded={ev} onCanPlay={ev} />;+ }+ mount(<App />, 0, { dom: true });+ const id = host.tid("v");+ const prop = (k: string) => (flush(), host.nodes.get(id)!.props[k]);+ const news = (type: string, extra: Record<string, unknown> = {}) => flushSync(() => host.named("media", { id, type, ...extra }));+ expect(v.paused).toBe(true);+ expect(v.readyState).toBe(0);+ news("loadedmetadata", { w: 1920, h: 1080, duration: 120.6 });+ news("loadeddata", { w: 1920, h: 1080, duration: 120.6 });+ expect(v.readyState).toBe(2);+ expect(v.duration).toBe(120.6);++ const played = v.play();+ expect(played).toBeInstanceOf(Promise);+ expect(v.paused).toBe(false);+ expect(prop("__play")).toEqual([true, 0, 1, true]);+ expect(prop("__muted")).toBe(true);+ news("playing", { time: 0 });+ // each frame's time is the element's currentTime, with no event; timeupdate comes on its own+ news("time", { time: 1.5 });+ expect(v.currentTime).toBe(1.5);+ expect(v.readyState).toBe(2);+ news("timeupdate", { time: 2 });+ v.muted = false;+ expect(prop("__muted")).toBe(false);+ v.pause();+ expect(v.paused).toBe(true);+ expect(prop("__play")).toEqual([false, 2, 2, true]);++ // a new source pauses while it loads, as a browser's does, and its readiness starts again+ v.play();+ v.setAttribute("src", "/media/renders/other.mp4");+ expect(v.paused).toBe(true);+ expect(v.readyState).toBe(0);+ expect(prop("__play")).toEqual([false, 2, 4, true]);++ // played to its end (the host sends ended for a source not looping): paused there, then ended+ v.play();+ news("ended", { time: 120.6 });+ expect(v.paused).toBe(true);+ expect(v.ended).toBe(true);+ expect(v.currentTime).toBe(120.6);+ // played again from the end starts at the beginning+ v.play();+ expect(prop("__play")).toEqual([true, 0, 6, true]);+ expect(seen).toEqual(["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]);++ // load(): back to the start, paused with no pause event, and the host's decoder opened again+ v.load();+ expect(v.paused).toBe(true);+ expect(v.currentTime).toBe(0);+ expect(v.readyState).toBe(0);+ expect(prop("__load")).toBe(1);+ expect(prop("__play")).toEqual([false, 0, 7, true]);+ expect(seen.at(-1)).toBe("[email protected]");+ expect(v.canPlayType("video/mp4")).toBe("maybe");+ expect(v.canPlayType("video/x-unknown")).toBe("");+ });+});