Skip to content

Truly independent web browser

LibWeb: Refresh WebAudio specification and implementation comments

Shannon Booth7d19b164382d
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/analyser_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/analyser_node.rs
index 7e6416fd4a3..5855c696a63 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/analyser_node.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/analyser_node.rs
@@ -196,7 +196,7 @@ impl AnalyserNode {
fn current_time_domain_data(&self) -> Vec<f32> {
// The input signal must be down-mixed to mono as if channelCount is 1, channelCountMode is "max" and
// channelInterpretation is "speakers". This is independent of the settings for the AnalyserNode itself.
- // NB: The down-mix happens on the rendering thread in AnalyserRenderNode.
+ // NB: The rendering thread down-mixes samples before writing them to the history ring.
self.drain_time_domain_ring();
// The most recent fftSize frames are used for the down-mixing operation.
@@ -419,7 +419,7 @@ impl AnalyserNode {
// to include past frames that it previously did not. This means that the AnalyserNode
// effectively MUST keep around the last 32768 sample-frames and the current time-domain
// data is the most recent fftSize sample-frames out of that.
- // NB: m_history always spans MAX_FFT_SIZE frames, so this holds by construction.
+ // NB: The history ring holds MAX_FFT_SIZE frames.
}
#[allow(clippy::manual_range_contains, reason = "preserve the C++ validation")]
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer.rs
index 60e1a37a019..e8871a2c64c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer.rs
@@ -178,7 +178,7 @@ impl AudioBuffer {
// https://webaudio.github.io/web-audio-api/#acquire-the-content
pub(crate) fn acquire_contents(this: Ref<Self>, vm: &Vm) -> Option<Arc<AudioBufferContents>> {
- // NB: m_contents is non-null exactly while the channel arrays are detached because step 4 below has not run yet.
+ // NB: contents is populated exactly while the channel arrays are detached because step 4 below has not run yet.
// The snapshot then still holds the buffer's content and script has had no way to modify it, so it can be
// handed out again as-is. This is what makes a sequence of acquisitions with no intervening getChannelData(),
// e.g. one AudioBuffer played by many AudioBufferSourceNodes, free of allocations and copying.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer_source_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer_source_node.rs
index 0bc4a142ed7..5059b8aa5cd 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer_source_node.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer_source_node.rs
@@ -178,7 +178,7 @@ impl AudioBufferSourceNode {
Ok(())
}
- // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-start`
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-start
pub(crate) fn start(
&self,
cx: &mut CallContext,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs
index 296b8c22794..095bf21b458 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs
@@ -277,7 +277,7 @@ impl AudioContext {
Ok(self.output_latency)
}
- // https://www.w3.org/TR/webaudio/#dom-audiocontext-getoutputtimestamp
+ // https://webaudio.github.io/web-audio-api/#dom-audiocontext-getoutputtimestamp
pub(crate) fn get_output_timestamp(&self, _: &mut CallContext) -> WebIdlResult<AudioTimestamp> {
let renderer = self.renderer.borrow();
@@ -356,28 +356,30 @@ impl AudioContext {
}
fn run_control_message_to_resume(&self, vm: &Vm, promise: WebIdlPromise) {
- // 7.1: Attempt to acquire system resources.
- // NB: The renderer acquires system resources and starts rendering in a single resume, performed in step 7.3.
+ // 1. Let promise be the promise passed into this algorithm.
+
+ // 2. Attempt to acquire system resources.
+ // NB: The renderer acquires resources when starting the graph in step 4.
if self.renderer.borrow().is_some() {
self.set_renderer_client(vm);
}
- // 7.2: Set the [[rendering thread state]] on the AudioContext to running.
+ // 3. Set the [[rendering thread state]] on the AudioContext to running.
self.context.set_rendering_state(AudioContextState::Running);
- // 7.3: Start rendering the audio graph.
+ // 4. Start rendering the audio graph.
let started = self.start_rendering_audio_graph();
- // 7.4: In case of failure, queue a media element task to execute the following steps:
+ // 5. In case of failure, queue a media element task to execute the following steps:
if !started {
self.context.queue_a_media_element_task(vm, self.this(), |vm, context| {
- // 7.4.1: Reject all promises from [[pending resume promises]] in order, then clear [[pending resume promises]].
+ // 5.1. Reject all promises from [[pending resume promises]] in order, then clear [[pending resume promises]].
for promise in &*context.pending_resume_promises.borrow() {
with_temporary_execution_context_and_callbacks(promise_realm(*promise), || {
reject_promise(vm, *promise, Value::NULL);
});
- // 7.4.2: Additionally, remove those promises from [[pending promises]].
+ // 5.2. Additionally, remove those promises from [[pending promises]].
let mut pending = context.context.pending_promises.borrow_mut(vm);
if let Some(index) = pending.iter().position(|pending| pending == promise) {
pending.remove(index);
@@ -387,12 +389,14 @@ impl AudioContext {
});
}
- // 7.5: queue a media element task to execute the following steps:
+ // 6. queue a media element task to execute the following steps:
self.context
.queue_a_media_element_task(vm, (self.this(), promise), |vm, (context, promise)| {
- // 7.5.1: Resolve all promises from [[pending resume promises]] in order.
- // 7.5.2: Clear [[pending resume promises]]. Additionally, remove those promises from
- // [[pending promises]].
+ // 6.1. If the [[render quantum size]] of the AudioContext is 0, set it to the actual hardware render quantum size chosen during resource acquisition.
+ // NB: This implementation always uses a fixed quantum size.
+
+ // 6.2. Resolve all promises from [[pending resume promises]] in order.
+ // 6.3. Clear [[pending resume promises]]. Additionally, remove those promises from [[pending promises]].
for pending_resume_promise in &*context.pending_resume_promises.borrow() {
with_temporary_execution_context_and_callbacks(promise_realm(*pending_resume_promise), || {
resolve_promise(vm, *pending_resume_promise, Value::UNDEFINED);
@@ -404,15 +408,15 @@ impl AudioContext {
}
context.pending_resume_promises.borrow_mut(vm).clear();
with_temporary_execution_context_and_callbacks(promise_realm(promise), || {
- // 7.5.3: Resolve promise.
+ // 6.4. Resolve promise.
resolve_promise(vm, promise, Value::UNDEFINED);
- // 7.5.4: If the state attribute of the AudioContext is not already "running":
+ // 6.5. If the state attribute of the AudioContext is not already "running":
if context.context.state_value() != AudioContextState::Running {
- // 7.5.4.1: Set the state attribute of the AudioContext to "running".
+ // 6.5.1. Set the state attribute of the AudioContext to "running".
context.context.set_state(AudioContextState::Running);
- // 7.5.4.2: queue a media element task to fire an event named statechange at the AudioContext.
+ // 6.5.2. Queue a media element task to fire an event named statechange at the AudioContext.
context.context.queue_a_media_element_task(vm, context, |_, context| {
context.context.dispatch_statechange();
});
@@ -421,9 +425,9 @@ impl AudioContext {
});
}
- // https://www.w3.org/TR/webaudio/#dom-audiocontext-suspend
+ // https://webaudio.github.io/web-audio-api/#dom-audiocontext-suspend
pub(crate) fn suspend(&self, cx: &mut CallContext, promise: WebIdlPromise) -> WebIdlResult<()> {
- // 1. If this's relevant global object's associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
+ // 1. If this’s relevant global object’s associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
if !self.context.document_is_fully_active() {
return Err(Exception::Dom(
"InvalidStateError",
@@ -431,6 +435,9 @@ impl AudioContext {
));
}
+ // 2. Let promise be a new Promise.
+ // NB: The bindings create the promise.
+
// 3. If the [[control thread state]] on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
if self.context.control_state() == AudioContextState::Closed {
reject_promise_with_exception(
@@ -453,26 +460,32 @@ impl AudioContext {
// 6. Set the [[control thread state]] on the AudioContext to suspended.
self.context.set_control_state(AudioContextState::Suspended);
- // 7. Queue a control message to suspend the AudioContext.
+ // 7. Queue a control message to suspend the AudioContext with promise.
self.run_control_message_to_suspend(cx.vm(), promise);
+
+ // 8. Return promise.
Ok(())
}
fn run_control_message_to_suspend(&self, vm: &Vm, promise: WebIdlPromise) {
- // 7.1: Attempt to release system resources.
+ // 1. Let promise be the promise passed into this algorithm.
+
+ // 2. Attempt to release system resources.
if let Some(renderer) = &*self.renderer.borrow() {
renderer.suspend();
renderer.set_client(None);
}
- // 7.2: Set the [[rendering thread state]] on the AudioContext to suspended.
+ // FIXME: 3. If the [[rendering thread state]] on the AudioContext is "interrupted", queue a media element task to set the [[state before interruption]] slot to "suspended".
+
+ // 4. Set the [[rendering thread state]] on the AudioContext to "suspended".
self.context.set_rendering_state(AudioContextState::Suspended);
- // 7.3: queue a media element task to execute the following steps:
+ // 5. Queue a media element task to execute the following steps:
self.context
.queue_a_media_element_task(vm, (self.this(), promise), |vm, (context, promise)| {
with_temporary_execution_context_and_callbacks(promise_realm(promise), || {
- // 7.3.1: Resolve promise.
+ // 5.1. Resolve promise.
resolve_promise(vm, promise, Value::UNDEFINED);
// AD-HOC: The spec omits removing a settled suspension promise from [[pending promises]].
@@ -482,12 +495,12 @@ impl AudioContext {
.borrow_mut(vm)
.retain(|pending| *pending != promise);
- // 7.3.2: If the state attribute of the AudioContext is not already "suspended":
+ // 5.2. If the state attribute of the AudioContext is not already "suspended":
if context.context.state_value() != AudioContextState::Suspended {
- // 7.3.2.1: Set the state attribute of the AudioContext to "suspended".
+ // 5.2.1. Set the state attribute of the AudioContext to "suspended".
context.context.set_state(AudioContextState::Suspended);
- // 7.3.2.2: queue a media element task to fire an event named statechange at the AudioContext.
+ // 5.2.2. Queue a media element task to fire an event named statechange at the AudioContext.
context.context.queue_a_media_element_task(vm, context, |_, context| {
context.context.dispatch_statechange();
});
@@ -541,6 +554,7 @@ impl AudioContext {
}
// 2. Set the [[rendering thread state]] to suspended.
+ // NOTE: This will stop rendering.
self.context.set_rendering_state(AudioContextState::Suspended);
// 3. If this control message is being run in a reaction to the document being unloaded, abort this algorithm.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/channel_merger_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/channel_merger_node.rs
index 5d82e52de2e..564aaec1956 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/channel_merger_node.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/channel_merger_node.rs
@@ -93,7 +93,7 @@ impl ChannelMergerNode {
node.node.event_target().set_owner(node);
// Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#BiquadFilterNode
+ // https://webaudio.github.io/web-audio-api/#ChannelMergerNode
let default_options = AudioNodeDefaultOptions {
channel_count: 1,
channel_count_mode: ChannelCountMode::Explicit,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/constant_source_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/constant_source_node.rs
index 2f5f99b9c76..21034d1ce75 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/constant_source_node.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/constant_source_node.rs
@@ -20,7 +20,7 @@ use crate::bindings::event_target::{CppEventTarget, GetTheParent};
use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
use crate::bindings::{CallContext, WebIdlResult};
-// https://webaudio.github.io/web-audio-api/#ChannelMergerNode
+// https://webaudio.github.io/web-audio-api/#ConstantSourceNode
#[derive(Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct ConstantSourceNode {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs
index 573d2889372..fbc71f33b3d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs
@@ -267,11 +267,11 @@ impl OfflineAudioContext {
Ok(())
}
+ // https://webaudio.github.io/web-audio-api/#begin-offline-rendering
fn begin_offline_rendering(&self, vm: &Vm, promise: WebIdlPromise) {
- // To begin offline rendering, the following steps MUST happen on a rendering thread that is created for the occasion.
- // 1: Given the current connections and scheduled changes, start rendering length sample-frames of audio into [[rendered buffer]]
- // 2: For every render quantum, check and suspend rendering if necessary.
- // 3: If a suspended context is resumed, continue to render the buffer.
+ // 1. Given the current connections and scheduled changes, start rendering buffer’s length sample-frames of audio into buffer.
+ // 2. For every render quantum, check and suspend rendering if necessary.
+ // 3. If a suspended context is resumed, continue to render the buffer.
let renderer = OfflineAudioRenderer::new(
Arc::clone(self.context.control_message_queue()),
self.context.destination_value().parent().node_id(),
@@ -317,14 +317,14 @@ impl OfflineAudioContext {
// NB: Break the reference cycle between the renderer's callbacks and this context.
self.renderer.borrow().as_ref().unwrap().set_client(None);
- // 4: Once the rendering is complete, queue a media element task to execute the following steps:
+ // 4. Once the rendering is complete, queue a media element task to execute the following steps:
self.context
.queue_a_media_element_task(vm, (self.this(), promise), |vm, (context, promise)| {
let realm = promise_realm(promise);
with_temporary_execution_context_and_callbacks(realm, || {
let buffer = context.rendered_buffer.get().unwrap();
- // 4.1 Resolve the promise created by startRendering() with [[rendered buffer]].
+ // 4.1. Resolve the promise created by startRendering() with buffer.
resolve_promise(
vm,
promise,
@@ -333,16 +333,20 @@ impl OfflineAudioContext {
.expect("an AudioBuffer wraps"),
);
- // AD-HOC: Remove resolved promise from [[pending promises]]
- // https://github.com/WebAudio/web-audio-api/issues/2648
+ // 4.2. Remove the promise from [[pending promises]].
context
.context
.pending_promises
.borrow_mut(vm)
.retain(|pending| *pending != promise);
- // 4.2: Queue a media element task to fire an event named complete at the OfflineAudioContext using OfflineAudioCompletionEvent
- // whose renderedBuffer property is set to [[rendered buffer]].
+ // FIXME: 4.3. Remove buffer from [[rendered buffers]].
+ // FIXME: 4.4. Set [[rendered frames]] to the sum of [[rendered frames]] and the length of buffer.
+ // 4.5. If length is not null:
+ // NB: One-shot rendering always has a length.
+ // 4.5.1. If [[rendered frames]] is greater than or equal to length, Queue a control message to close the OfflineAudioContext.
+ // NB: The context was closed when rendering completed.
+ // 4.5.2. Queue a media element task to fire an event named complete at the OfflineAudioContext using OfflineAudioCompletionEvent whose renderedBuffer property is set to buffer.
context.context.queue_a_media_element_task(vm, context, |vm, context| {
let event = CppEvent::create_for_owner(
context.context.realm(),
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs
index c9db211eb6d..b0bc6d48b4e 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs
@@ -65,6 +65,7 @@ impl AudioBus {
.any(|channel| channel.iter().any(|&sample| sample != 0.))
}
+ // Preserve active channels' samples and zero newly added channels.
pub fn set_channel_count(&mut self, channel_count: usize) {
if self.channels.len() == channel_count {
return;
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/realtime_audio_renderer.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/realtime_audio_renderer.rs
index 04c2c00069a..915e30b7d39 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/realtime_audio_renderer.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/realtime_audio_renderer.rs
@@ -144,7 +144,7 @@ impl RealtimeAudioRenderer {
}
/// The callback is set on the control thread before rendering starts and is always invoked on the control thread. It
- /// is cleared when the context closes to break the reference cycle with the context.
+ /// is cleared when the context is suspended, closes, or its document becomes inactive.
pub fn set_client(&self, client: Option<Rc<dyn RealtimeAudioRendererClient>>) {
self.client.replace(client);
}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs
index 2a5892ed077..80cc85a0cf0 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs
@@ -596,8 +596,7 @@ impl AudioBufferSourceRenderNode {
self.playhead_valid = true;
}
- // NB: Compare using a half-frame tolerance since m_played_time accumulates one frame's worth of content at
- // a time and would otherwise overshoot the duration by up to one frame due to floating-point rounding.
+ // NB: A half-frame tolerance prevents rounding error in played_time from extending playback by one frame.
let frame_consumption = computed_playback_rate.abs() / context.sample_rate;
if self
.duration
@@ -1257,8 +1256,7 @@ impl std::ops::Mul<f64> for DoubleVector3 {
}
}
-// Gfx::DoubleVector3::normalize() divides by the length unconditionally, which would produce NaN components for a zero
-// vector; the spatialization math needs a zero vector to normalize back to a zero vector instead.
+// Spatialization requires normalizing a zero vector to a zero vector.
fn safe_normalized(vector: DoubleVector3) -> DoubleVector3 {
if vector.length() == 0. {
return DoubleVector3::default();