Skip to content

armgit / raea

Public Imported from GitHub
0

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.

A page's <video> and <audio> play at their element's volume in raea's window (Shane 11-10: 'a loudness lever not just on and off'). sdk/ui's element takes volume as a browser's does (0..1, RangeError outside it, volumechange) and tells the host __volume, again with each play; runtime/dom/media asks the decoder Cmd::Volume when it changes; raea-runtime-js keeps it per player and plays the sound at that gain while it isn't muted (an AtomicU32 beside muted, read in the audio callback), set again when a sound opens. Before this the window had only muted, so the app's volume slider changed nothing. sdk/ui test: the element's volume reaches the host as __volume, fires volumechange once and is told again with a play. The live composition stage has no volume call yet

shinyobjectz75b1c69e715e
diff --git a/runtime/dom/media/src/lib.rs b/runtime/dom/media/src/lib.rs
index 0fdb4cae..2f50715f 100644
--- a/runtime/dom/media/src/lib.rs
+++ b/runtime/dom/media/src/lib.rs
@@ -3,7 +3,7 @@
//! (`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`); 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
+//! loop], set by `play()` and `pause()`), `__muted` the element's muted and `__volume` its volume. 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. raea-runtime-dom's
//! page host keeps one `Medias` and syncs it after each commit.
@@ -39,6 +39,7 @@ pub struct Media {
play: Option<Value>,
playing: bool,
muted: Option<bool>,
+ volume: Option<f64>,
/// when the last `timeupdate` went
told: Option<std::time::Instant>,
}
@@ -70,7 +71,7 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mu
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, 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.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, volume: None, told: None });
medias.get_mut(&id).unwrap()
}
};
@@ -86,6 +87,13 @@ pub fn sync(doc: &mut BaseDocument, nodes: &Nodes, medias: &mut Medias, out: &mu
}
m.muted = muted;
}
+ let volume = props.and_then(|p| p.get("__volume")).and_then(Value::as_f64);
+ if m.volume != volume {
+ if let (Some(v), Some(st)) = (volume, m.stream.as_mut()) {
+ st.ask(Cmd::Volume(v as f32));
+ }
+ m.volume = volume;
+ }
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()
diff --git a/runtime/js/src/media_html.rs b/runtime/js/src/media_html.rs
index ebe443d1..55b93ba0 100644
--- a/runtime/js/src/media_html.rs
+++ b/runtime/js/src/media_html.rs
@@ -29,6 +29,8 @@ pub mod stream {
Play { at: f64, looping: bool },
Pause,
Muted(bool),
+ /// the element's volume, 0..1: the sound's gain while it isn't muted
+ Volume(f32),
}
pub struct Stream {
diff --git a/runtime/js/src/media_play.rs b/runtime/js/src/media_play.rs
index c1bdffaa..0f1027f9 100644
--- a/runtime/js/src/media_play.rs
+++ b/runtime/js/src/media_play.rs
@@ -30,6 +30,7 @@ pub struct Player<'a> {
/// the sound, opened on the first play; None after it couldn't be
sound: Option<Option<Sound>>,
muted: bool,
+ volume: f32,
clock: Option<Clock>,
looping: bool,
/// the frame (index at fps) last sent while playing, so a frame isn't decoded twice
@@ -45,7 +46,7 @@ impl<'a> Player<'a> {
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 }
+ Player { path, source, duration, fps, sound: None, muted: false, volume: 1.0, clock: None, looping: false, shown: None, told: None }
}
/// Answers the element's asks until it's gone (its stream dropped).
@@ -77,6 +78,12 @@ impl<'a> Player<'a> {
s.set_muted(m);
}
}
+ Cmd::Volume(v) => {
+ self.volume = v;
+ if let Some(Some(s)) = &self.sound {
+ s.set_volume(v);
+ }
+ }
}
}
if pause && self.clock.is_some() {
@@ -127,7 +134,8 @@ impl<'a> Player<'a> {
// 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()));
+ let volume = self.volume;
+ self.sound = Some(audio.and_then(|a| Sound::open(a, self.muted).inspect(|s| s.set_volume(volume)).inspect_err(|e| bevy::log::debug!("raea-runtime-js: media plays on the wall's clock: {e}")).ok()));
}
self.shown = None;
self.told = None;
diff --git a/runtime/js/src/media_sound.rs b/runtime/js/src/media_sound.rs
index 2f899834..d600b0e5 100644
--- a/runtime/js/src/media_sound.rs
+++ b/runtime/js/src/media_sound.rs
@@ -5,7 +5,7 @@
//! clock instead.
use std::sync::Arc;
-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
+use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering::Relaxed};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
@@ -20,6 +20,8 @@ struct Shared {
/// the device's delay from a callback to its sound reaching the speaker, in seconds (f64 bits)
delay: AtomicU64,
muted: AtomicBool,
+ /// the element's volume, 0..1 (f32 bits): the gain while it isn't muted
+ volume: AtomicU32,
running: AtomicBool,
}
@@ -50,7 +52,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), running: AtomicBool::new(false) });
+ 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 s = shared.clone();
let src = audio.channels;
let last = len - 1;
@@ -75,7 +77,7 @@ impl Sound {
s.pos.store(p.to_bits(), Relaxed);
return;
}
- let gain = if s.muted.load(Relaxed) { 0.0 } else { 1.0 };
+ let gain = if s.muted.load(Relaxed) { 0.0 } else { f32::from_bits(s.volume.load(Relaxed)) };
for frame in out.chunks_mut(ch) {
if p as usize > last {
frame.fill(0.0);
@@ -114,6 +116,12 @@ impl Sound {
self.shared.muted.store(muted, Relaxed);
}
+ /// How loud it plays while it isn't muted, 0..1 (a page's element.volume).
+ pub fn set_volume(&self, volume: f32) {
+ let v = if volume.is_finite() { volume.clamp(0.0, 1.0) } else { 1.0 };
+ 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.
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));
diff --git a/sdk/ui/src/dom/media.ts b/sdk/ui/src/dom/media.ts
index 09fa2f74..f54a8d7f 100644
--- a/sdk/ui/src/dom/media.ts
+++ b/sdk/ui/src/dom/media.ts
@@ -32,7 +32,7 @@ export class HTMLImageElement_ extends HTMLElement_ {
/** 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;
+ * picture), muted (`__muted`) and volume (`__volume`, 0..1). 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;
@@ -45,6 +45,7 @@ export class HTMLMediaElement_ extends HTMLElement_ {
_time = 0;
_seeks = 0;
_muted?: boolean;
+ _volume?: number;
_playing = false;
_plays = 0;
/** the host told this element (a prop of its own beside its attributes) */
@@ -82,6 +83,7 @@ export class HTMLMediaElement_ extends HTMLElement_ {
this._playing = true;
this._ended = false;
this._tell("__muted", this.muted);
+ if (this._volume !== undefined) this._tell("__volume", this._volume);
this._tell("__play", [true, this._time >= (this.duration || Infinity) ? 0 : this._time, ++this._plays, this.loop]);
dispatchDirect(this, new Event_("play", { bubbles: false }));
}
@@ -128,6 +130,18 @@ export class HTMLMediaElement_ extends HTMLElement_ {
this._tell("__muted", this._muted);
if (was !== this._muted) dispatchDirect(this, new Event_("volumechange", { bubbles: false }));
}
+ get volume() {
+ return this._volume ?? 1;
+ }
+ /** 0..1, as a browser's: outside it throws, as a browser's IndexSizeError does */
+ set volume(v: number) {
+ const x = Number(v);
+ if (!Number.isFinite(x) || x < 0 || x > 1) throw new RangeError(`The volume provided (${v}) is outside the range [0, 1].`);
+ if (x === this.volume && this._volume !== undefined) return;
+ this._volume = x;
+ this._tell("__volume", x);
+ dispatchDirect(this, new Event_("volumechange", { bubbles: false }));
+ }
get duration() {
return this._media?.duration ?? NaN;
}
diff --git a/sdk/ui/test/dom.test.tsx b/sdk/ui/test/dom.test.tsx
index e959e770..34fd01c7 100644
--- a/sdk/ui/test/dom.test.tsx
+++ b/sdk/ui/test/dom.test.tsx
@@ -407,4 +407,29 @@ describe("video and audio play on the host's player (runtime/dom media.rs, raea-
flush();
expect(host.nodes.get(id)!.props.__muted).toBe(false);
});
+
+ test("volume reaches the host's player as __volume, fires volumechange, and is told again with a play", () => {
+ const host = fresh();
+ let v: any;
+ const seen: string[] = [];
+ function App() {
+ const r = useRef<any>(null);
+ useEffect(() => void (v = r.current), []);
+ return <video ref={r} data-testid="v" src="/media/renders/film.mp4" onVolumeChange={(e: any) => seen.push(`${e.type}:${e.currentTarget.volume}`)} />;
+ }
+ mount(<App />, 0, { dom: true });
+ const id = host.tid("v");
+ const prop = (k: string) => (flush(), host.nodes.get(id)!.props[k]);
+ expect(v.volume).toBe(1);
+ expect(prop("__volume")).toBeUndefined();
+ v.volume = 0.4;
+ expect(v.volume).toBe(0.4);
+ expect(prop("__volume")).toBe(0.4);
+ v.volume = 0.4;
+ expect(() => (v.volume = 1.5)).toThrow(RangeError);
+ expect(v.volume).toBe(0.4);
+ v.play();
+ expect(prop("__volume")).toBe(0.4);
+ expect(seen).toEqual(["volumechange:0.4"]);
+ });
});