Skip to content

Truly independent web browser

LibWeb: Port WebAudio contexts and nodes to Rust

Shannon Boothec8009081542
diff --git a/Libraries/LibMediaClient/Client.h b/Libraries/LibMediaClient/Client.h
index 9567c64c8bc..31a68e46094 100644
--- a/Libraries/LibMediaClient/Client.h
+++ b/Libraries/LibMediaClient/Client.h
@@ -10,6 +10,7 @@
#include <AK/HashMap.h>
#include <AK/NonnullRefPtr.h>
#include <AK/RefPtr.h>
+#include <AK/kmalloc.h>
#include <LibCore/AnonymousBuffer.h>
#include <LibCore/EventLoop.h>
#include <LibCore/Forward.h>
@@ -63,6 +64,8 @@ public:
// Linear PCM decoded by the server, one channel after another in shared memory.
struct DecodedAudioData {
+ AK_ALLOC_WITH_KMALLOC;
+
u32 sample_rate { 0 };
u32 channel_count { 0 };
u64 frame_count { 0 };
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/analyser_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/analyser_node.rs
new file mode 100644
index 00000000000..bf975a64298
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/analyser_node.rs
@@ -0,0 +1,548 @@
+/*
+ * Copyright (c) 2024, Noah Bright <[email protected]>
+ * Copyright (c) 2025, Tim Ledbetter <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::Cell;
+use std::cell::RefCell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+use ak::Utf16String;
+use ak::math;
+use libjs_rust::api::{
+ ArrayBufferOrder, TypedArrayBase, is_typed_array_out_of_bounds, make_typed_array_with_buffer_witness_record,
+ typed_array_length,
+};
+use libjs_rust::api::{Gc, Trace};
+use libweb_rust::web_audio::control_message::FfiSharedCppObject;
+use libweb_rust::web_audio::rendering::analyser_render_node::web_audio_node_create_analyser;
+use libweb_rust::web_audio::rendering::audio_frame_ring::{AudioFrameRing, AudioFrameRingCallbacks};
+use libweb_rust::web_audio::rendering::fft::{FFT, FFTDirection};
+use libweb_rust::web_audio::rendering::node_message::SharedCppObject;
+
+use super::audio_array::overwrite_float32_array;
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#AnalyserNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct AnalyserNode {
+ node: AudioNode,
+ fft_size: Cell<u32>,
+ #[gc(untraced)]
+ fft: RefCell<Option<FFT>>,
+ max_decibels: Cell<f64>,
+ min_decibels: Cell<f64>,
+ smoothing_time_constant: Cell<f64>,
+
+ // https://webaudio.github.io/web-audio-api/#previous-block
+ #[gc(untraced)]
+ previous_block: RefCell<Vec<f32>>,
+ #[gc(untraced)]
+ time_domain_ring: RefCell<Option<AudioFrameRing>>,
+ #[gc(untraced)]
+ history: RefCell<Vec<f32>>,
+ history_write_index: Cell<usize>,
+ history_valid_frames: Cell<usize>,
+
+ // Frequency data computed within the current render quantum, per the spec's requirement
+ // that repeated getter calls in one quantum return identical data.
+ #[gc(untraced)]
+ cached_frequency_data: RefCell<Vec<f32>>,
+ frequency_data_cache_time: Cell<Option<f64>>,
+}
+
+impl Inherits<AudioNode> for AnalyserNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for AnalyserNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for AnalyserNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize
+// The maximum allowed fftSize; the node must keep this many past sample-frames around so
+// that growing fftSize immediately exposes older data.
+const MAX_FFT_SIZE: u32 = 32768;
+
+pub(crate) struct AnalyserOptions {
+ pub parent: AudioNodeOptions,
+ pub fft_size: u32,
+ pub max_decibels: f64,
+ pub min_decibels: f64,
+ pub smoothing_time_constant: f64,
+}
+
+unsafe extern "C" {
+ fn web_audio_analyser_create_ring(callbacks: *mut AudioFrameRingCallbacks) -> FfiSharedCppObject;
+}
+
+impl AnalyserNode {
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &AnalyserOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // When the constructor is called with a BaseAudioContext c and an option object option, the user agent
+ // MUST initialize the AudioNode this, with context and options as arguments.
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ fft_size: Cell::new(options.fft_size),
+ fft: RefCell::new(None),
+ max_decibels: Cell::new(options.max_decibels),
+ min_decibels: Cell::new(options.min_decibels),
+ smoothing_time_constant: Cell::new(options.smoothing_time_constant),
+ previous_block: RefCell::new(Vec::new()),
+ time_domain_ring: RefCell::new(None),
+ history: RefCell::new(Vec::new()),
+ history_write_index: Cell::new(0),
+ history_valid_frames: Cell::new(0),
+ cached_frequency_data: RefCell::new(Vec::new()),
+ frequency_data_cache_time: Cell::new(None),
+ });
+ node.node.set_this(AnyAudioNode::AnalyserNode(node));
+ node.node.event_target().set_owner(node);
+ node.set_fft_size_without_validation(options.fft_size);
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#AnalyserNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::Max,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to no
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ node.history.borrow_mut().resize(MAX_FFT_SIZE as usize, 0.);
+ let mut callbacks = std::mem::MaybeUninit::uninit();
+ let ring = unsafe { web_audio_analyser_create_ring(callbacks.as_mut_ptr()) };
+ let callbacks = unsafe { callbacks.assume_init() };
+ *node.time_domain_ring.borrow_mut() = Some(AudioFrameRing {
+ owner: SharedCppObject {
+ pointer: ring.pointer,
+ retain: ring.retain,
+ release: ring.release,
+ },
+ callbacks,
+ });
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_analyser(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ ring,
+ callbacks,
+ ))
+ });
+ Ok(node)
+ }
+
+ #[allow(clippy::needless_range_loop, reason = "preserve the C++ frame traversal")]
+ fn drain_time_domain_ring(&self) {
+ let ring = self.time_domain_ring.borrow();
+ let Some(ring) = &*ring else {
+ return;
+ };
+
+ // Ring pops are destructive, so everything the render thread has produced is folded into
+ // the control-side history of the last MAX_FFT_SIZE sample-frames. Keeping the full
+ // maximum window around means growing fftSize immediately exposes older data, as the
+ // spec requires.
+ let mut chunk = [0.; 1024];
+ loop {
+ let frame_count = ring.try_pop(&mut chunk);
+ if frame_count == 0 {
+ break;
+ }
+ let mut history = self.history.borrow_mut();
+ for frame in 0..frame_count {
+ history[self.history_write_index.get()] = chunk[frame];
+ self.history_write_index
+ .set((self.history_write_index.get() + 1) % history.len());
+ }
+ self.history_valid_frames
+ .set(history.len().min(self.history_valid_frames.get() + frame_count));
+ }
+ }
+
+ // https://webaudio.github.io/web-audio-api/#current-time-domain-data
+ 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.
+ self.drain_time_domain_ring();
+
+ // The most recent fftSize frames are used for the down-mixing operation.
+ let mut result = vec![0.; self.fft_size.get() as usize];
+ let frames_available = (self.fft_size.get() as usize).min(self.history_valid_frames.get());
+ let history = self.history.borrow();
+ for frame in 0..frames_available {
+ let history_index =
+ (self.history_write_index.get() + history.len() - frames_available + frame) % history.len();
+ result[self.fft_size.get() as usize - frames_available + frame] = history[history_index];
+ }
+ result
+ }
+
+ // https://webaudio.github.io/web-audio-api/#blackman-window
+ fn apply_a_blackman_window(&self, x: &[f32]) -> Vec<f32> {
+ let a: f32 = 0.16;
+ let a0 = 0.5f32 * (1. - a);
+ let a1: f32 = 0.5;
+ let a2 = a * 0.5f32;
+ let n = self.fft_size.get();
+ let w = |index: u32| {
+ a0 - a1 * math::cos(2. * std::f32::consts::PI * index as f32 / n as f32)
+ + a2 * math::cos(4. * std::f32::consts::PI * index as f32 / n as f32)
+ };
+ let mut x_hat = vec![0.; self.fft_size.get() as usize];
+
+ // FIXME: Naive
+ for i in 0..self.fft_size.get() as usize {
+ x_hat[i] = x[i] * w(i as u32);
+ }
+ x_hat
+ }
+
+ // https://webaudio.github.io/web-audio-api/#smoothing-over-time
+ fn smoothing_over_time(&self, current_block: &[f32]) -> Vec<f32> {
+ // 1. Let X^−1[k] be the result of this operation on the previous block. The previous block is defined as being
+ // the buffer computed by the previous smoothing over time operation, or an array of N zeros if this is the
+ // first time we are smoothing over time.
+ let mut previous_block = self.previous_block.borrow_mut();
+ if previous_block.len() != current_block.len() {
+ previous_block.clear();
+ previous_block.resize(current_block.len(), 0.);
+ }
+
+ // 2. Let τ be the value of the smoothingTimeConstant attribute for this AnalyserNode.
+ let tau = self.smoothing_time_constant.get() as f32;
+
+ // 3. Let X[k] be the result of applying a Fourier transform of the current block.
+ let mut result = vec![0.; current_block.len()];
+
+ // 4. Then the smoothed value, X^[k], is computed by X^[k] = τ * X^−1[k] + (1 − τ) * |X[k]|
+ // If X^[k] is NaN, positive infinity or negative infinity, set X^[k] = 0.
+ for i in 0..current_block.len() {
+ let mut smoothed = tau * previous_block[i] + (1.0f32 - tau) * current_block[i].abs();
+ if !smoothed.is_finite() {
+ smoothed = 0.;
+ }
+ result[i] = smoothed;
+ }
+ *previous_block = result.clone();
+ result
+ }
+
+ // https://webaudio.github.io/web-audio-api/#conversion-to-db
+ fn conversion_to_db(&self, x_hat: &[f32]) -> Vec<f32> {
+ // Y[k] = 20 log10 X^[k] for k = 0,…,N−1
+ let mut result = Vec::with_capacity(x_hat.len());
+ for x in x_hat {
+ // NB: 20 * log10(0) is -∞. The byte-domain conversion clamps this later.
+ if *x > 0. {
+ result.push(20.0f32 * math::log10(*x));
+ } else {
+ result.push(f32::NEG_INFINITY);
+ }
+ }
+ result
+ }
+
+ // https://webaudio.github.io/web-audio-api/#current-frequency-data
+ fn current_frequency_data(&self) -> Vec<f32> {
+ // If another call to getFloatFrequencyData() or getByteFrequencyData() occurs within the same render quantum
+ // as a previous call, the current frequency data is not updated with the same data. Instead, the previously
+ // computed data is returned.
+ // AD-HOC: The control thread cannot observe render quantum boundaries directly; the context's currentTime,
+ // which advances as quanta are rendered, stands in for the quantum stamp.
+ let current_time = self.node.context_value().current_time_value();
+ if self.frequency_data_cache_time.get() == Some(current_time) {
+ return self.cached_frequency_data.borrow().clone();
+ }
+
+ // 1. Compute the current time-domain data.
+ let time_domain_data = self.current_time_domain_data();
+
+ // 2. Apply a Blackman window to the time domain input data.
+ let windowed_input = self.apply_a_blackman_window(&time_domain_data);
+
+ // 3. Apply a Fourier transform to the windowed time domain input data to get real and imaginary frequency data.
+ let frequency_domain_data = apply_a_fourier_transform(
+ self.fft.borrow().as_ref().unwrap(),
+ &windowed_input,
+ self.fft_size.get() as usize / 2,
+ );
+
+ // 4. Smooth over time the frequency domain data.
+ let smoothed_data = self.smoothing_over_time(&frequency_domain_data);
+
+ // 5. Convert to dB.
+ let result = self.conversion_to_db(&smoothed_data);
+ *self.cached_frequency_data.borrow_mut() = result.clone();
+ self.frequency_data_cache_time.set(Some(current_time));
+ result
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-analysernode-getfloatfrequencydata
+ pub(crate) fn get_float_frequency_data(&self, _: &mut CallContext, array: Gc<TypedArrayBase>) -> WebIdlResult<()> {
+ // Write the current frequency data into array. If array has fewer elements than the frequencyBinCount,
+ // the excess elements will be dropped. If array has more elements than the frequencyBinCount, the
+ // excess elements will be ignored. The most recent fftSize frames are used in computing the frequency data.
+ let data = self.current_frequency_data();
+ let record = make_typed_array_with_buffer_witness_record(&array, ArrayBufferOrder::SeqCst);
+ if is_typed_array_out_of_bounds(&record) {
+ return Ok(());
+ }
+ let count = typed_array_length(&record).min(self.fft_size.get() as usize / 2);
+ overwrite_float32_array(&array, &data[..count]);
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-analysernode-getbytefrequencydata
+ pub(crate) fn get_byte_frequency_data(&self, _: &mut CallContext, array: Gc<TypedArrayBase>) -> WebIdlResult<()> {
+ let data = self.current_frequency_data();
+ let mut byte_data = Vec::with_capacity(data.len());
+
+ // For getByteFrequencyData(), the 𝑌[𝑘] is clipped to lie between minDecibels and maxDecibels
+ // and then scaled to fit in an unsigned byte such that minDecibels is represented by the
+ // value 0 and maxDecibels is represented by the value 255.
+ let delta_db = (self.max_decibels.get() - self.min_decibels.get()) as f32;
+ for mut x in data {
+ x = if f64::from(x) < self.min_decibels.get() {
+ self.min_decibels.get() as f32
+ } else {
+ x
+ };
+ x = if self.max_decibels.get() < f64::from(x) {
+ self.max_decibels.get() as f32
+ } else {
+ x
+ };
+ byte_data.push((255. * (f64::from(x) - self.min_decibels.get()) / f64::from(delta_db)) as u8);
+ }
+
+ // Write the current frequency data into array. If array’s byte length is less than frequencyBinCount,
+ // the excess elements will be dropped. If array’s byte length is greater than the frequencyBinCount ,
+ // the excess elements will be ignored. The most recent fftSize frames are used in computing the frequency data.
+ let record = make_typed_array_with_buffer_witness_record(&array, ArrayBufferOrder::SeqCst);
+ if is_typed_array_out_of_bounds(&record) {
+ return Ok(());
+ }
+ let count = typed_array_length(&record).min(self.fft_size.get() as usize / 2);
+ array
+ .viewed_array_buffer()
+ .overwrite(array.byte_offset(), &byte_data[..count]);
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-analysernode-getfloattimedomaindata
+ pub(crate) fn get_float_time_domain_data(
+ &self,
+ _: &mut CallContext,
+ array: Gc<TypedArrayBase>,
+ ) -> WebIdlResult<()> {
+ // Write the current time-domain data (waveform data) into array. If array has fewer elements than the
+ // value of fftSize, the excess elements will be dropped. If array has more elements than the value of
+ // fftSize, the excess elements will be ignored. The most recent fftSize frames are written (after downmixing).
+ let data = self.current_time_domain_data();
+ let record = make_typed_array_with_buffer_witness_record(&array, ArrayBufferOrder::SeqCst);
+ if is_typed_array_out_of_bounds(&record) {
+ return Ok(());
+ }
+ let count = typed_array_length(&record).min(self.fft_size.get() as usize);
+ overwrite_float32_array(&array, &data[..count]);
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-analysernode-getbytetimedomaindata
+ pub(crate) fn get_byte_time_domain_data(&self, _: &mut CallContext, array: Gc<TypedArrayBase>) -> WebIdlResult<()> {
+ // Write the current time-domain data (waveform data) into array. If array’s byte length is less than
+ // fftSize, the excess elements will be dropped. If array’s byte length is greater than the fftSize,
+ // the excess elements will be ignored. The most recent fftSize frames are used in computing the byte data.
+ let data = self.current_time_domain_data();
+ let mut byte_data = Vec::with_capacity(data.len());
+ assert_eq!(data.len(), self.fft_size.get() as usize);
+ for sample in data {
+ let mut x = 128. * (1. + sample);
+ x = if x < 0. { 0. } else { x };
+ x = if 255. < x { 255. } else { x };
+ byte_data.push(x as u8);
+ }
+ let record = make_typed_array_with_buffer_witness_record(&array, ArrayBufferOrder::SeqCst);
+ if is_typed_array_out_of_bounds(&record) {
+ return Ok(());
+ }
+ let count = typed_array_length(&record).min(self.fft_size.get() as usize);
+ array
+ .viewed_array_buffer()
+ .overwrite(array.byte_offset(), &byte_data[..count]);
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize
+ fn set_fft_size_without_validation(&self, fft_size: u32) {
+ // reset previous block to 0s
+ *self.previous_block.borrow_mut() = vec![0.; fft_size as usize / 2];
+ self.frequency_data_cache_time.set(None);
+ self.fft_size.set(fft_size);
+ *self.fft.borrow_mut() = Some(FFT::new(fft_size as usize));
+
+ // Note that increasing fftSize does mean that the current time-domain data must be expanded
+ // 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.
+ }
+
+ #[allow(clippy::manual_range_contains, reason = "preserve the C++ validation")]
+ pub(crate) fn set_fft_size(&self, _: &mut CallContext, fft_size: u32) -> WebIdlResult<()> {
+ if fft_size < 32 || fft_size > MAX_FFT_SIZE || !fft_size.is_power_of_two() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"Analyser node fftSize not a power of 2 between 32 and 32768"),
+ ));
+ }
+ self.set_fft_size_without_validation(fft_size);
+ Ok(())
+ }
+
+ pub(crate) fn set_max_decibels(&self, _: &mut CallContext, max_decibels: f64) -> WebIdlResult<()> {
+ if self.min_decibels.get() >= max_decibels {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"Analyser node minDecibels greater than maxDecibels"),
+ ));
+ }
+ self.max_decibels.set(max_decibels);
+ Ok(())
+ }
+
+ pub(crate) fn set_min_decibels(&self, _: &mut CallContext, min_decibels: f64) -> WebIdlResult<()> {
+ if min_decibels >= self.max_decibels.get() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"Analyser node minDecibels greater than maxDecibels"),
+ ));
+ }
+ self.min_decibels.set(min_decibels);
+ Ok(())
+ }
+
+ pub(crate) fn set_smoothing_time_constant(
+ &self,
+ _: &mut CallContext,
+ smoothing_time_constant: f64,
+ ) -> WebIdlResult<()> {
+ if smoothing_time_constant > 1. || smoothing_time_constant < 0. {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"Analyser node smoothingTimeConstant not between 0.0 and 1.0"),
+ ));
+ }
+ self.smoothing_time_constant.set(smoothing_time_constant);
+ Ok(())
+ }
+
+ pub(crate) fn validate_options(options: &AnalyserOptions) -> WebIdlResult<()> {
+ if options.min_decibels >= options.max_decibels {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"Analyser node minDecibels greater than maxDecibels"),
+ ));
+ }
+ if options.smoothing_time_constant > 1. || options.smoothing_time_constant < 0. {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"Analyser node smoothingTimeConstant not between 0.0 and 1.0"),
+ ));
+ }
+ if options.fft_size < 32 || options.fft_size > MAX_FFT_SIZE || !options.fft_size.is_power_of_two() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"Analyser node fftSize not a power of 2 between 32 and 32768"),
+ ));
+ }
+ Ok(())
+ }
+
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: AnalyserOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::validate_options(&options)?;
+ Self::create(cx, context, &options)
+ }
+
+ pub(crate) fn fft_size(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(self.fft_size.get())
+ }
+
+ pub(crate) fn max_decibels(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.max_decibels.get())
+ }
+
+ pub(crate) fn min_decibels(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.min_decibels.get())
+ }
+
+ pub(crate) fn smoothing_time_constant(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.smoothing_time_constant.get())
+ }
+
+ pub(crate) fn frequency_bin_count(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(self.fft_size.get() / 2)
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#fourier-transform
+//
+// Returns `bin_count` (= fftSize / 2) magnitude values normalized by fftSize, per the spec's
+// `(1/N) * |X[k]|` convention. The caller is expected to have applied a window already.
+#[allow(clippy::manual_memcpy, reason = "preserve the C++ input copy loop")]
+fn apply_a_fourier_transform(fft: &FFT, input: &[f32], bin_count: usize) -> Vec<f32> {
+ let mut magnitudes = vec![0.; bin_count];
+ if input.is_empty() {
+ return magnitudes;
+ }
+ let n = input.len();
+ let mut re = vec![0.; n];
+ let mut im = vec![0.; n];
+ for i in 0..n {
+ re[i] = input[i];
+ }
+ fft.transform(&mut re, &mut im, FFTDirection::Forward);
+ let inv_n = 1.0f32 / n as f32;
+ for k in 0..bin_count.min(n) {
+ magnitudes[k] = (re[k] * re[k] + im[k] * im[k]).sqrt() * inv_n;
+ }
+ magnitudes
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_array.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_array.rs
new file mode 100644
index 00000000000..734271aba11
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_array.rs
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use libjs_rust::api::{
+ ArrayBufferOrder, TypedArrayBase, is_typed_array_out_of_bounds, make_typed_array_with_buffer_witness_record,
+ typed_array_length,
+};
+
+// Utilities for moving sample data in and out of the Float32Arrays exposed by the Web Audio API. A Float32Array's
+// contents can change from JavaScript at any time, so audio data destined for the rendering thread is always snapshotted
+// into an owned buffer first.
+
+// The current element length of a Float32Array, or 0 if it is out of bounds of its backing ArrayBuffer.
+pub(crate) fn float32_array_length(array: &TypedArrayBase) -> usize {
+ let record = make_typed_array_with_buffer_witness_record(array, ArrayBufferOrder::SeqCst);
+ if is_typed_array_out_of_bounds(&record) {
+ return 0;
+ }
+ typed_array_length(&record)
+}
+
+// Snapshots the live contents of a Float32Array into an owned buffer.
+pub(crate) fn copy_float32_array(array: &TypedArrayBase) -> Vec<f32> {
+ let length = float32_array_length(array);
+ let mut values = vec![0.; length];
+ let bytes = unsafe { ak::slice_from_raw_parts_mut(values.as_mut_ptr().cast::<u8>(), length * size_of::<f32>()) };
+ array.viewed_array_buffer().copy_to(array.byte_offset(), bytes);
+ values
+}
+
+// Overwrites the leading elements of a Float32Array with the given samples.
+pub(crate) fn overwrite_float32_array(array: &TypedArrayBase, values: &[f32]) {
+ let bytes = unsafe { ak::slice_from_raw_parts(values.as_ptr().cast::<u8>(), size_of_val(values)) };
+ array.viewed_array_buffer().overwrite(array.byte_offset(), bytes);
+}
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 1aad0274191..60e1a37a019 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer.rs
@@ -13,22 +13,20 @@
)]
use std::cell::RefCell;
-use std::ffi::c_void;
use std::ptr::NonNull;
use std::sync::Arc;
use ak::Utf16String;
use libjs_rust::api::{
ArrayBuffer, ArrayBufferOrder, ArrayBufferShared, DataBlock, EmbedderCell, ErrorKind, ErrorType,
- ExternalPrimitiveStorage, ForeignCellSlot, Gc, GcWeak, RawNativeFunctionResult, Trace, TypedArrayBase,
- TypedArrayKind, Value, Vm, create_typed_array_on_buffer, detach_array_buffer,
- make_typed_array_with_buffer_witness_record,
+ ExternalPrimitiveStorage, ForeignCellSlot, Gc, GcWeak, Trace, TypedArrayBase, TypedArrayKind, Vm,
+ create_typed_array_on_buffer, detach_array_buffer, make_typed_array_with_buffer_witness_record,
};
use libjs_rust::api::{OutOfMemory, OwnedBackingStore};
use libjs_rust::api::{is_typed_array_out_of_bounds, typed_array_byte_length};
use libweb_rust::web_audio::rendering::audio_data::AudioBufferContents;
-use crate::bindings::interface::{Ref, Wrappable, Wrapped, allocate, cell_from_abi, cell_into_abi, realm_arguments};
+use crate::bindings::interface::{Ref, Wrappable, Wrapped, allocate, cell_into_abi};
use crate::bindings::{CallContext, Exception, WebIdlResult};
pub(crate) struct AudioBufferOptions {
@@ -123,29 +121,16 @@ fn prune_live_channel_views(views: &mut Vec<AudioBufferChannelView>) {
views.retain(|entry| entry.array_buffer.get().is_some());
}
-unsafe extern "C" {
- fn web_audio_verify_buffer_options(
- realm: *mut c_void,
- number_of_channels: u32,
- length: u32,
- sample_rate: f32,
- ) -> RawNativeFunctionResult;
-}
-
impl AudioBuffer {
pub(crate) fn construct(cx: &mut CallContext, options: AudioBufferOptions) -> WebIdlResult<Ref<Self>> {
let vm = cx.vm();
// 1. If any of the values in options lie outside its nominal range, throw a NotSupportedError exception and abort the following steps.
- unsafe {
- web_audio_verify_buffer_options(
- cx.realm().as_ptr().cast(),
- options.number_of_channels,
- options.length,
- options.sample_rate,
- )
- }
- .into_completion()?;
+ super::base_audio_context::BaseAudioContext::verify_audio_options_inside_nominal_range(
+ options.number_of_channels,
+ options.length,
+ options.sample_rate,
+ )?;
if options.length as usize > i32::MAX as usize / size_of::<f32>() {
return Err(vm
.throw_completion::<()>(ErrorKind::RangeError, ErrorType::InvalidLength, &[&"typed array"])
@@ -513,84 +498,3 @@ impl AudioBuffer {
Ok(())
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_buffer_create(
- vm: &Vm,
- channels: u32,
- length: u32,
- sample_rate: f32,
- output: *mut *mut c_void,
-) -> bool {
- match AudioBuffer::create(vm, channels, length, sample_rate) {
- Ok(buffer) => {
- unsafe {
- *output = cell_into_abi(buffer);
- }
- true
- }
- Err(_) => false,
- }
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_buffer_sample_rate(cell: *mut c_void) -> f32 {
- let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };
- buffer.sample_rate
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_buffer_length(cell: *mut c_void) -> u32 {
- let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };
- buffer.length
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_buffer_channel_count(cell: *mut c_void) -> u32 {
- let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };
- buffer.channels.borrow().len() as u32
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_buffer_channel(
- cell: *mut c_void,
- channel: u32,
- output: *mut ak::SpanMut<'static, u8>,
-) -> bool {
- let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };
- match buffer.channel_data(channel) {
- Ok((pointer, length)) => {
- unsafe {
- *output = ak::SpanMut::new(ak::slice_from_raw_parts_mut(pointer, length));
- }
- true
- }
- Err(_) => false,
- }
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_buffer_get_channel_data(
- vm: *mut c_void,
- realm: *mut c_void,
- cell: *mut c_void,
- channel: u32,
-) -> RawNativeFunctionResult {
- let (vm, realm) = unsafe { realm_arguments(vm, realm) };
- let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };
- let mut cx = CallContext::new(vm, realm);
- RawNativeFunctionResult::from_completion(
- AudioBuffer::get_channel_data(&buffer, &mut cx, channel)
- .map(|view| Value::from_object(view.upcast::<libjs_rust::api::Object>()))
- .map_err(|error| error.throw(&cx)),
- )
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_buffer_acquire_contents(
- vm: &Vm,
- cell: *mut c_void,
-) -> *const AudioBufferContents {
- let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };
- AudioBuffer::acquire_contents(buffer, vm).map_or(std::ptr::null(), Arc::into_raw)
-}
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
new file mode 100644
index 00000000000..146bad87892
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer_source_node.rs
@@ -0,0 +1,316 @@
+/*
+ * Copyright (c) 2024, Bar Yemini <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::Cell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::control_message::ControlMessage;
+use libweb_rust::web_audio::rendering::audio_data::AudioBufferContents;
+use libweb_rust::web_audio::rendering::node_message::{NodeMessage, SetBufferSourceParameters, StartBufferSource};
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_audio_buffer_source;
+
+use super::audio_buffer::AudioBuffer;
+use super::audio_node::{
+ AnyAudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::audio_param::{AudioParam, AutomationRate, FixedAutomationRate};
+use super::audio_scheduled_source_node::AudioScheduledSourceNode;
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#AudioBufferSourceNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct AudioBufferSourceNode {
+ node: AudioScheduledSourceNode,
+ buffer: Cell<Option<Ref<AudioBuffer>>>,
+ playback_rate: Ref<AudioParam>,
+ detune: Ref<AudioParam>,
+ r#loop: Cell<bool>,
+ loop_start: Cell<f64>,
+ loop_end: Cell<f64>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-buffer-set-slot
+ buffer_set: Cell<bool>,
+}
+
+impl Inherits<AudioScheduledSourceNode> for AudioBufferSourceNode {
+ fn parent(&self) -> &AudioScheduledSourceNode {
+ &self.node
+ }
+}
+
+impl Wrappable for AudioBufferSourceNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.parent().finalize_node();
+ }
+}
+
+impl GetTheParent for AudioBufferSourceNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct AudioBufferSourceOptions {
+ pub buffer: Option<Option<Ref<AudioBuffer>>>,
+ pub playback_rate: f32,
+ pub detune: f32,
+ pub r#loop: bool,
+ pub loop_start: f64,
+ pub loop_end: f64,
+}
+
+impl AudioBufferSourceNode {
+ fn queue_parameters_update(&self, buffer: Option<Arc<AudioBufferContents>>, update_buffer: bool) {
+ self.node
+ .parent()
+ .context_value()
+ .queue_control_message(ControlMessage::NodeMessage(NodeMessage::SetBufferSourceParameters(
+ SetBufferSourceParameters {
+ node_id: self.node.parent().node_id(),
+ r#loop: self.r#loop.get(),
+ loop_start: self.loop_start.get(),
+ loop_end: self.loop_end.get(),
+ buffer,
+ update_buffer,
+ },
+ )));
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-buffer
+ pub(crate) fn set_buffer(&self, cx: &mut CallContext, buffer: Option<Ref<AudioBuffer>>) -> WebIdlResult<()> {
+ // 1. Let new buffer be the AudioBuffer or null value to be assigned to buffer.
+ let new_buffer = buffer;
+
+ // 2. If new buffer is not null and [[buffer set]] is true, throw an InvalidStateError and abort these steps.
+ if new_buffer.is_some() && self.buffer_set.get() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Buffer has already been set"),
+ ));
+ }
+
+ // 3. If new buffer is not null, set [[buffer set]] to true.
+ if new_buffer.is_some() {
+ self.buffer_set.set(true);
+ }
+
+ // 4. Assign new buffer to the buffer attribute.
+ self.buffer.set(new_buffer);
+
+ // 5. If start() has previously been called on this node, perform the operation acquire the content on buffer.
+ if self.node.source_started() {
+ self.queue_parameters_update(
+ self.buffer
+ .get()
+ .and_then(|buffer| AudioBuffer::acquire_contents(buffer, cx.vm())),
+ true,
+ );
+ }
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-buffer
+ pub(crate) fn buffer(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<AudioBuffer>>> {
+ Ok(self.buffer.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-playbackrate
+ pub(crate) fn playback_rate(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.playback_rate)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-detune
+ pub(crate) fn detune(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.detune)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loop
+ pub(crate) fn r#loop(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ Ok(self.r#loop.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loop
+ pub(crate) fn set_loop(&self, _: &mut CallContext, value: bool) -> WebIdlResult<()> {
+ self.r#loop.set(value);
+ self.queue_parameters_update(None, false);
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loopstart
+ pub(crate) fn loop_start(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.loop_start.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loopstart
+ pub(crate) fn set_loop_start(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {
+ self.loop_start.set(value);
+ self.queue_parameters_update(None, false);
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loopend
+ pub(crate) fn loop_end(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.loop_end.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loopend
+ pub(crate) fn set_loop_end(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {
+ self.loop_end.set(value);
+ self.queue_parameters_update(None, false);
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-start`
+ pub(crate) fn start(
+ &self,
+ cx: &mut CallContext,
+ when: f64,
+ offset: Option<f64>,
+ duration: Option<f64>,
+ ) -> WebIdlResult<()> {
+ // 1. If this AudioBufferSourceNode internal slot [[source started]] is true, an InvalidStateError exception MUST be thrown.
+ if self.node.source_started() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"AudioBufferSourceNode has already been started"),
+ ));
+ }
+
+ // 2. Check for any errors that must be thrown due to parameter constraints described below. If any exception is thrown during this step, abort those steps.
+ // A RangeError exception MUST be thrown if when is negative.
+ if when < 0. {
+ return Err(Exception::range_error("when must not be negative"));
+ }
+
+ // A RangeError exception MUST be thrown if offset is negative
+ if offset.is_some_and(|offset| offset < 0.) {
+ return Err(Exception::range_error("offset must not be negative"));
+ }
+
+ // A RangeError exception MUST be thrown if duration is negative.
+ if duration.is_some_and(|duration| duration < 0.) {
+ return Err(Exception::range_error("duration must not be negative"));
+ }
+
+ // 3. Set the internal slot [[source started]] on this AudioBufferSourceNode to true.
+ self.node.set_source_started(true);
+
+ // 4. Queue a control message to start the AudioBufferSourceNode, including the parameter values in the message.
+ // 5. Acquire the contents of the buffer if the buffer has been set.
+ let mut contents = None;
+ if let Some(buffer) = self.buffer.get() {
+ contents = AudioBuffer::acquire_contents(buffer, cx.vm());
+ }
+ self.node
+ .parent()
+ .context_value()
+ .queue_control_message(ControlMessage::NodeMessage(NodeMessage::StartBufferSource(
+ StartBufferSource {
+ node_id: self.node.parent().node_id(),
+ when,
+ offset: offset.unwrap_or(0.),
+ duration,
+ buffer: contents,
+ },
+ )));
+ self.node
+ .parent()
+ .context_value()
+ .add_playing_source(cx.vm(), self.node.parent().this());
+
+ // FIXME: 6. Send a control message to the associated AudioContext to start running its rendering thread only when all the following conditions are met:
+ Ok(())
+ }
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &AudioBufferSourceOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // When the constructor is called with a BaseAudioContext c and an option object option, the user agent
+ // MUST initialize the AudioNode this, with context and options as arguments.
+
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioScheduledSourceNode::new(defer_gc, context),
+ buffer: Cell::new(options.buffer.flatten()),
+ playback_rate: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.playback_rate,
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::KRate,
+ FixedAutomationRate::Yes,
+ ),
+ detune: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.detune,
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::KRate,
+ FixedAutomationRate::Yes,
+ ),
+ r#loop: Cell::new(options.r#loop),
+ loop_start: Cell::new(options.loop_start),
+ loop_end: Cell::new(options.loop_end),
+ buffer_set: Cell::new(false),
+ });
+ node.node.parent().set_this(AnyAudioNode::AudioBufferSourceNode(node));
+ node.node.parent().event_target().set_owner(node);
+ node.playback_rate.set_owner(AnyAudioNode::AudioBufferSourceNode(node));
+ node.detune.set_owner(AnyAudioNode::AudioBufferSourceNode(node));
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#AudioBufferSourceNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::Max,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to no
+ node.node
+ .parent()
+ .initialize_audio_node_options(cx, &AudioNodeOptions::default(), &default_options)?;
+ node.node.parent().queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_audio_buffer_source(
+ node.node.parent().node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ Arc::as_ptr(node.playback_rate.render_param()),
+ Arc::as_ptr(node.detune.render_param()),
+ ))
+ });
+ node.queue_parameters_update(None, false);
+ Ok(node)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-audiobuffersourcenode
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: AudioBufferSourceOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, &options)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs
new file mode 100644
index 00000000000..bb971012332
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs
@@ -0,0 +1,595 @@
+/*
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::{Cell, RefCell};
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, Trace, Value, Vm};
+use libweb_rust::web_audio::control_message::FfiSharedCppObject;
+use libweb_rust::web_audio::rendering::node_message::SharedCppObject;
+
+use super::audio_destination_node::AudioDestinationNode;
+use super::audio_listener::AudioListener;
+use super::audio_node::AudioNodeOptions;
+use super::base_audio_context::{AnyBaseAudioContext, AudioContextState, BaseAudioContext};
+use super::media_element_audio_source_node::MediaElementAudioSourceNode;
+use super::media_stream_audio_destination_node::MediaStreamAudioDestinationNode;
+use super::media_stream_audio_source_node::{MediaStreamAudioSourceNode, MediaStreamAudioSourceOptions};
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::global_object::window_from_global_object;
+use crate::bindings::interface::with_temporary_execution_context_and_callbacks;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi};
+use crate::bindings::promise::{
+ WebIdlPromise, promise_realm, reject_promise, reject_promise_with_exception, resolve_promise,
+};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+#[derive(Clone, Copy)]
+pub(crate) enum AudioContextLatencyCategory {
+ Balanced,
+ Interactive,
+ Playback,
+}
+
+#[allow(dead_code, reason = "the C++ constructor ignores latencyHint")]
+pub(crate) enum AudioContextLatencyCategoryOrDouble {
+ AudioContextLatencyCategory(AudioContextLatencyCategory),
+ Double(f64),
+}
+
+pub(crate) struct AudioContextOptions {
+ #[allow(dead_code, reason = "the C++ constructor ignores latencyHint")]
+ pub latency_hint: AudioContextLatencyCategoryOrDouble,
+ pub sample_rate: Option<f32>,
+}
+
+pub(crate) struct AudioTimestamp {
+ pub context_time: Option<f64>,
+ pub performance_time: Option<f64>,
+}
+
+// https://webaudio.github.io/web-audio-api/#AudioContext
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct AudioContext {
+ context: BaseAudioContext,
+ base_latency: f64,
+ output_latency: f64,
+ allowed_to_start: bool,
+ pending_resume_promises: GcRefCell<Vec<WebIdlPromise>>,
+ suspended_by_user: Cell<bool>,
+ #[gc(untraced)]
+ renderer: RefCell<Option<SharedCppObject>>,
+}
+
+impl Inherits<BaseAudioContext> for AudioContext {
+ fn parent(&self) -> &BaseAudioContext {
+ &self.context
+ }
+}
+
+impl Wrappable for AudioContext {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.context.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(context: Ref<Self>) {
+ context.context.shutdown_audio_worklet();
+ if let Some(renderer) = &*context.renderer.borrow() {
+ unsafe {
+ web_audio_realtime_context_stop(renderer.pointer);
+ web_audio_realtime_context_clear_callbacks(renderer.pointer);
+ }
+ }
+ }
+}
+
+impl GetTheParent for AudioContext {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+unsafe extern "C" {
+ fn web_audio_realtime_context_create(
+ global: *mut c_void,
+ queue: *const c_void,
+ destination: u64,
+ sample_rate: f32,
+ ) -> FfiSharedCppObject;
+ fn web_audio_realtime_context_set_callbacks(renderer: *mut c_void, context: *mut c_void);
+ fn web_audio_realtime_context_start(renderer: *mut c_void);
+ fn web_audio_realtime_context_resume(renderer: *mut c_void);
+ fn web_audio_realtime_context_suspend(renderer: *mut c_void);
+ fn web_audio_realtime_context_stop(renderer: *mut c_void);
+ fn web_audio_realtime_context_clear_callbacks(renderer: *mut c_void);
+ fn web_audio_realtime_context_frames_rendered(renderer: *mut c_void) -> u64;
+ fn web_audio_realtime_context_output_time(renderer: *mut c_void) -> f64;
+ fn web_audio_realtime_context_performance_now(global: *mut c_void) -> f64;
+}
+
+impl AudioContext {
+ fn this(&self) -> Ref<Self> {
+ let AnyBaseAudioContext::AudioContext(context) = self.context.this() else {
+ unreachable!()
+ };
+ context
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiocontext-audiocontext
+ pub(crate) fn construct(cx: &mut CallContext, context_options: AudioContextOptions) -> WebIdlResult<Ref<Self>> {
+ let window =
+ window_from_global_object(cx.realm().global_object()).expect("an AudioContext is constructed on a Window");
+ let global = unsafe { CppCell::from_raw(window.as_event_target().as_ptr()) };
+
+ // If the current settings object’s responsible document is NOT fully active, throw an InvalidStateError and abort these steps.
+ // FIXME: Not all settings objects currently return a responsible document.
+ // Therefore we only fail this check if responsible document is not null.
+ unsafe extern "C" {
+ fn web_audio_context_responsible_document_is_fully_active(global: *mut c_void) -> bool;
+ }
+ if !unsafe { web_audio_context_responsible_document_is_fully_active(global.as_ptr()) } {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Document is not fully active"),
+ ));
+ }
+
+ // AD-HOC: The spec doesn't currently require the sample rate to be validated here,
+ // but other browsers do perform a check and there is a WPT test that expects this.
+ if let Some(sample_rate) = context_options.sample_rate {
+ BaseAudioContext::verify_sample_rate(sample_rate)?;
+ }
+
+ // 1. Let context be a new AudioContext object.
+ let context = allocate(cx.vm(), |defer_gc| Self {
+ context: BaseAudioContext::new(defer_gc, global, 0.),
+ base_latency: 0.,
+ output_latency: 0.,
+ allowed_to_start: true,
+ pending_resume_promises: GcRefCell::new(Vec::new()),
+ suspended_by_user: Cell::new(false),
+ renderer: RefCell::new(None),
+ });
+ context
+ .context
+ .initialize(cx.vm(), AnyBaseAudioContext::AudioContext(context));
+ context.context.event_target().set_owner(context);
+ context.context.listener.set(Some(AudioListener::create(
+ cx.vm(),
+ AnyBaseAudioContext::AudioContext(context),
+ )));
+ context.context.destination.set(Some(AudioDestinationNode::create(
+ cx,
+ AnyBaseAudioContext::AudioContext(context),
+ 2,
+ )?));
+
+ // 2. Set a [[control thread state]] to suspended on context.
+ context.context.set_control_state(AudioContextState::Suspended);
+
+ // 3. Set a [[rendering thread state]] to suspended on context.
+ context.context.set_rendering_state(AudioContextState::Suspended);
+
+ // FIXME: 4. Let messageChannel be a new MessageChannel.
+ // FIXME: 5. Let controlSidePort be the value of messageChannel’s port1 attribute.
+ // FIXME: 6. Let renderingSidePort be the value of messageChannel’s port2 attribute.
+ // FIXME: 7. Let serializedRenderingSidePort be the result of StructuredSerializeWithTransfer(renderingSidePort, « renderingSidePort »).
+ // FIXME: 8. Set this audioWorklet's port to controlSidePort.
+ // FIXME: 9. Queue a control message to set the MessagePort on the AudioContextGlobalScope, with serializedRenderingSidePort.
+ // 10. If contextOptions is given, apply the options:
+ // 1. If sinkId is specified, let sinkId be the value of contextOptions.sinkId and run the following substeps:
+ // 2. Set the internal latency of context according to contextOptions.latencyHint, as described in latencyHint.
+ // FIXME: Determine optimal settings for contextOptions.latencyHint.
+ // 3: If contextOptions.sampleRate is specified, set the sampleRate of context to this value.
+ if let Some(sample_rate) = context_options.sample_rate {
+ context.context.set_sample_rate(sample_rate);
+ } else {
+ // Otherwise, follow these substeps:
+ // FIXME: 1. If sinkId is the empty string or a type of AudioSinkOptions, use the sample rate of the default output device. Abort these substeps.
+ // FIXME: 2. If sinkId is a DOMString, use the sample rate of the output device identified by sinkId. Abort these substeps.
+ // If contextOptions.sampleRate differs from the sample rate of the output device, the user agent MUST resample the audio output to match the sample rate of the output device.
+ context.context.set_sample_rate(44100.);
+ }
+
+ // AD-HOC: Ensure a sample rate is always set, even when no options were passed at all.
+ if context.context.sample_rate_value() == 0. {
+ context.context.set_sample_rate(44100.);
+ }
+
+ // 11. If context is allowed to start, send a control message to start processing.
+ // FIXME: The context is currently always allowed to start; this should be gated on sticky activation.
+ if context.allowed_to_start {
+ // FIXME: 1. Let document be the current settings object's relevant global object's associated Document.
+ // 2. Attempt to acquire system resources to use a following audio output device based on [[sink ID]] for
+ // rendering.
+ let renderer = unsafe {
+ web_audio_realtime_context_create(
+ context.context.global_event_target().as_ptr(),
+ Arc::as_ptr(context.context.control_message_queue()).cast(),
+ context.context.destination_value().parent().node_id(),
+ context.context.sample_rate_value(),
+ )
+ };
+ *context.renderer.borrow_mut() = Some(SharedCppObject {
+ pointer: renderer.pointer,
+ retain: renderer.retain,
+ release: renderer.release,
+ });
+ context.set_renderer_callbacks();
+ unsafe { web_audio_realtime_context_start(renderer.pointer) };
+
+ // 2. Set this [[rendering thread state]] to running on the AudioContext.
+ context.context.set_rendering_state(AudioContextState::Running);
+
+ // 3. Queue a media element task to execute the following steps:
+ context
+ .context
+ .queue_a_media_element_task(cx.vm(), context, |_, context| {
+ // 1. Set the state attribute of the AudioContext to "running".
+ context.context.set_control_state(AudioContextState::Running);
+
+ // 2. Fire an event named statechange at the AudioContext.
+ context.context.dispatch_statechange();
+ });
+ }
+
+ // 12. Return context.
+ Ok(context)
+ }
+
+ pub(crate) fn document_became_inactive(&self) {
+ // Release the audio output device and the GC roots held by the renderer's callbacks, so a context belonging to a
+ // navigated-away document stops playing and can eventually be collected.
+ self.context.shutdown_audio_worklet();
+ if let Some(renderer) = &*self.renderer.borrow() {
+ unsafe {
+ web_audio_realtime_context_stop(renderer.pointer);
+ web_audio_realtime_context_clear_callbacks(renderer.pointer);
+ }
+ }
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-currenttime
+ pub(crate) fn current_time_value(&self) -> f64 {
+ // This is the time in seconds of the sample frame immediately following the last sample-frame in the block of
+ // audio most recently processed by the context's rendering graph.
+ if let Some(renderer) = &*self.renderer.borrow() {
+ return unsafe { web_audio_realtime_context_frames_rendered(renderer.pointer) } as f64
+ / f64::from(self.context.sample_rate_value());
+ }
+ 0.
+ }
+
+ pub(crate) fn base_latency(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.base_latency)
+ }
+
+ pub(crate) fn output_latency(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.output_latency)
+ }
+
+ // https://www.w3.org/TR/webaudio/#dom-audiocontext-getoutputtimestamp
+ pub(crate) fn get_output_timestamp(&self, _: &mut CallContext) -> WebIdlResult<AudioTimestamp> {
+ let renderer = self.renderer.borrow();
+ if renderer
+ .as_ref()
+ .is_none_or(|renderer| unsafe { web_audio_realtime_context_frames_rendered(renderer.pointer) } == 0)
+ {
+ return Ok(AudioTimestamp {
+ context_time: Some(0.),
+ performance_time: Some(0.),
+ });
+ }
+
+ // FIXME: performanceTime should be the moment the sample frame at contextTime was rendered by the output device.
+ // We sample performance.now() when getOutputTimestamp() is called instead of caching a timestamp when the
+ // renderer produced that block, so the returned pair does not describe a single output instant.
+ Ok(AudioTimestamp {
+ context_time: Some(unsafe { web_audio_realtime_context_output_time(renderer.as_ref().unwrap().pointer) }),
+ performance_time: Some(unsafe {
+ web_audio_realtime_context_performance_now(self.context.global_event_target().as_ptr())
+ }),
+ })
+ }
+
+ // https://www.w3.org/TR/webaudio/#dom-audiocontext-resume
+ pub(crate) fn resume(&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.
+ if !self.context.document_is_fully_active() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Document is not fully active"),
+ ));
+ }
+
+ // 3. If the [[control thread state]] on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
+ if self.context.state_value() == AudioContextState::Closed {
+ reject_promise_with_exception(
+ cx.vm(),
+ promise,
+ Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Audio context is already closed."),
+ ),
+ );
+ return Ok(());
+ }
+
+ // 4. Set [[suspended by user]] to true.
+ self.suspended_by_user.set(true);
+
+ // 5. If the context is not allowed to start, append promise to [[pending promises]] and [[pending resume promises]] and abort these steps, returning promise.
+ if self.allowed_to_start {
+ self.context.pending_promises.borrow_mut(cx.vm()).push(promise);
+ self.pending_resume_promises.borrow_mut(cx.vm()).push(promise);
+ }
+
+ // 6. Set the [[control thread state]] on the AudioContext to running.
+ self.context.set_control_state(AudioContextState::Running);
+
+ // 7. Queue a control message to resume the AudioContext.
+ self.run_control_message_to_resume(cx.vm(), promise);
+ Ok(())
+ }
+
+ 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.
+ if self.renderer.borrow().is_some() {
+ self.set_renderer_callbacks();
+ }
+
+ // 7.2: Set the [[rendering thread state]] on the AudioContext to running.
+ self.context.set_rendering_state(AudioContextState::Running);
+
+ // 7.3: 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:
+ 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]].
+ 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]].
+ let mut pending = context.context.pending_promises.borrow_mut(vm);
+ if let Some(index) = pending.iter().position(|pending| pending == promise) {
+ pending.remove(index);
+ }
+ }
+ context.pending_resume_promises.borrow_mut(vm).clear();
+ });
+ }
+
+ // 7.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)| {
+ // 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]].
+ 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);
+ });
+ let mut pending = context.context.pending_promises.borrow_mut(vm);
+ if let Some(index) = pending.iter().position(|promise| promise == pending_resume_promise) {
+ pending.remove(index);
+ }
+ }
+ context.pending_resume_promises.borrow_mut(vm).clear();
+ with_temporary_execution_context_and_callbacks(promise_realm(promise), || {
+ // 7.5.3: Resolve promise.
+ resolve_promise(vm, promise, Value::UNDEFINED);
+
+ // 7.5.4: 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".
+ context.context.set_control_state(AudioContextState::Running);
+
+ // 7.5.4.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();
+ });
+ }
+ });
+ });
+ }
+
+ // https://www.w3.org/TR/webaudio/#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.
+ if !self.context.document_is_fully_active() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Document is not fully active"),
+ ));
+ }
+
+ // 3. If the [[control thread state]] on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
+ if self.context.state_value() == AudioContextState::Closed {
+ reject_promise_with_exception(
+ cx.vm(),
+ promise,
+ Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Audio context is already closed."),
+ ),
+ );
+ return Ok(());
+ }
+
+ // 4. Append promise to [[pending promises]].
+ self.context.pending_promises.borrow_mut(cx.vm()).push(promise);
+
+ // 5. Set [[suspended by user]] to true.
+ self.suspended_by_user.set(true);
+
+ // 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.
+ self.run_control_message_to_suspend(cx.vm(), promise);
+ Ok(())
+ }
+
+ fn run_control_message_to_suspend(&self, vm: &Vm, promise: WebIdlPromise) {
+ // 7.1: Attempt to release system resources.
+ if let Some(renderer) = &*self.renderer.borrow() {
+ unsafe {
+ web_audio_realtime_context_suspend(renderer.pointer);
+ web_audio_realtime_context_clear_callbacks(renderer.pointer);
+ }
+ }
+
+ // 7.2: 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:
+ 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.
+ resolve_promise(vm, promise, Value::UNDEFINED);
+
+ // 7.3.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".
+ context.context.set_control_state(AudioContextState::Suspended);
+
+ // 7.3.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();
+ });
+ }
+ });
+ });
+ }
+
+ // https://www.w3.org/TR/webaudio/#dom-audiocontext-close
+ pub(crate) fn close(&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.
+ if !self.context.document_is_fully_active() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Document is not fully active"),
+ ));
+ }
+
+ // 3. If the [[control thread state]] flag on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
+ if self.context.state_value() == AudioContextState::Closed {
+ reject_promise_with_exception(
+ cx.vm(),
+ promise,
+ Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Audio context is already closed."),
+ ),
+ );
+ return Ok(());
+ }
+
+ // 4. Set the [[control thread state]] flag on the AudioContext to closed.
+ self.context.set_control_state(AudioContextState::Closed);
+
+ // 5. Queue a control message to close the AudioContext.
+ self.run_control_message_to_close(cx.vm(), promise);
+ Ok(())
+ }
+
+ fn run_control_message_to_close(&self, vm: &Vm, promise: WebIdlPromise) {
+ // 5.1: Attempt to release system resources.
+ self.context.shutdown_audio_worklet();
+ if let Some(renderer) = &*self.renderer.borrow() {
+ unsafe {
+ web_audio_realtime_context_stop(renderer.pointer);
+ web_audio_realtime_context_clear_callbacks(renderer.pointer);
+ }
+ }
+
+ // 5.2: Set the [[rendering thread state]] to "suspended".
+ self.context.set_rendering_state(AudioContextState::Suspended);
+
+ // FIXME: 5.3: If this control message is being run in a reaction to the document being unloaded, abort this algorithm.
+ // 5.4: 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), || {
+ // 5.4.1: Resolve promise.
+ resolve_promise(vm, promise, Value::UNDEFINED);
+
+ // 5.4.2: If the state attribute of the AudioContext is not already "closed":
+ if context.context.state_value() != AudioContextState::Closed {
+ // 5.4.2.1: Set the state attribute of the AudioContext to "closed".
+ context.context.set_control_state(AudioContextState::Closed);
+ }
+
+ // 5.4.2.2: queue a media element task to fire an event named statechange at the AudioContext.
+ context.context.dispatch_statechange();
+ });
+ });
+ }
+
+ fn start_rendering_audio_graph(&self) -> bool {
+ if let Some(renderer) = &*self.renderer.borrow() {
+ unsafe { web_audio_realtime_context_resume(renderer.pointer) };
+ }
+ true
+ }
+
+ fn set_renderer_callbacks(&self) {
+ let renderer = self.renderer.borrow();
+ unsafe {
+ web_audio_realtime_context_set_callbacks(renderer.as_ref().unwrap().pointer, cell_into_abi(self.this()));
+ };
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiocontext-createmediaelementsource
+ pub(crate) fn create_media_element_source(
+ &self,
+ cx: &mut CallContext,
+ media_element: CppInterface,
+ ) -> WebIdlResult<Ref<MediaElementAudioSourceNode>> {
+ MediaElementAudioSourceNode::create(cx, self.this(), media_element)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiocontext-createmediastreamsource
+ pub(crate) fn create_media_stream_source(
+ &self,
+ cx: &mut CallContext,
+ media_stream: CppInterface,
+ ) -> WebIdlResult<Ref<MediaStreamAudioSourceNode>> {
+ MediaStreamAudioSourceNode::create(cx, self.this(), &MediaStreamAudioSourceOptions { media_stream })
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audiocontext-createmediastreamdestination
+ pub(crate) fn create_media_stream_destination(
+ &self,
+ cx: &mut CallContext,
+ ) -> WebIdlResult<Ref<MediaStreamAudioDestinationNode>> {
+ MediaStreamAudioDestinationNode::create(cx, self.this(), &AudioNodeOptions::default())
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_audio_context_sources_ended(
+ vm: &Vm,
+ cell: *mut c_void,
+ ids: ak::Span<'_, u64>,
+) {
+ unsafe { AnyBaseAudioContext::from_abi(cell) }.handle_ended_sources(vm, ids.as_slice());
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_destination_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_destination_node.rs
new file mode 100644
index 00000000000..1a87337a1bf
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_destination_node.rs
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2024, Bar Yemini <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#![allow(clippy::collapsible_if, reason = "preserve the C++ branch structure")]
+
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_destination;
+
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#AudioDestinationNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct AudioDestinationNode {
+ node: AudioNode,
+}
+
+impl Inherits<AudioNode> for AudioDestinationNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for AudioDestinationNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for AudioDestinationNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+impl AudioDestinationNode {
+ // https://webaudio.github.io/web-audio-api/#dom-audiodestinationnode-maxchannelcount
+ pub(crate) fn max_channel_count(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(self.max_channel_count_value())
+ }
+
+ fn max_channel_count_value(&self) -> u32 {
+ // The maximum number of channels that the channelCount attribute can be set to. An AudioDestinationNode
+ // representing the audio hardware end-point (the normal case) can potentially output more than 2 channels of
+ // audio if the audio hardware is multi-channel. maxChannelCount is the maximum number of channels that this
+ // hardware is capable of supporting.
+ // NB: For an OfflineAudioContext, channelCount may not be changed, so the maximum equals the channel count the
+ // context was constructed with. For an AudioContext, we follow the recommendation from the spec's privacy
+ // considerations that maxChannelCount be set to two (stereo) instead of exposing the audio hardware's
+ // actual capabilities.
+ if matches!(self.node.context_value(), AnyBaseAudioContext::OfflineAudioContext(_)) {
+ return self.node.channel_count_value();
+ }
+ 2
+ }
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ channel_count: u32,
+ ) -> WebIdlResult<Ref<Self>> {
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, channel_count),
+ });
+ node.node.set_this(AnyAudioNode::AudioDestinationNode(node));
+ node.node.event_target().set_owner(node);
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#AudioDestinationNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count,
+ channel_count_mode: ChannelCountMode::Explicit,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to no
+ node.node
+ .initialize_audio_node_options(cx, &AudioNodeOptions::default(), &default_options)?;
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_destination(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ channel_count as usize,
+ ))
+ });
+ Ok(node)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
+ pub(crate) fn set_channel_count_override(&self, _: &mut CallContext, channel_count: u32) -> WebIdlResult<()> {
+ if channel_count == self.node.channel_count_value() {
+ return Ok(());
+ }
+
+ // The behavior depends on whether the destination node is the destination of an AudioContext
+ // or OfflineAudioContext:
+
+ // AudioContext: The channel count MUST be between 1 and maxChannelCount. An IndexSizeError
+ // exception MUST be thrown for any attempt to set the count outside this range.
+ // NB: Setting the count to zero throws NotSupportedError through AudioNode's channelCount validation below,
+ // taking precedence over the range check here.
+ if matches!(self.node.context_value(), AnyBaseAudioContext::AudioContext(_)) {
+ if channel_count > self.max_channel_count_value() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"Channel index is out of range"),
+ ));
+ }
+ }
+
+ // OfflineAudioContext: This value may not be changed; a NotSupportedError exception MUST be thrown if
+ // channelCount is changed to a different value.
+ if matches!(self.node.context_value(), AnyBaseAudioContext::OfflineAudioContext(_)) {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Cannot change channel count in an OfflineAudioContext"),
+ ));
+ }
+ self.node.set_channel_count_impl(channel_count)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_listener.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_listener.rs
index caeb00560c2..8194392cdaf 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_listener.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_listener.rs
@@ -5,37 +5,35 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use std::ffi::c_void;
-
use libjs_rust::api::{Trace, Vm};
use super::audio_param::{AudioParam, AutomationRate, FixedAutomationRate};
-use crate::bindings::cpp_cell::CppCell;
-use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi};
+use super::base_audio_context::AnyBaseAudioContext;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
use crate::bindings::{CallContext, WebIdlResult};
// https://webaudio.github.io/web-audio-api/#AudioListener
#[derive(Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct AudioListener {
- forward_x: Ref<AudioParam>,
- forward_y: Ref<AudioParam>,
- forward_z: Ref<AudioParam>,
- position_x: Ref<AudioParam>,
- position_y: Ref<AudioParam>,
- position_z: Ref<AudioParam>,
- up_x: Ref<AudioParam>,
- up_y: Ref<AudioParam>,
- up_z: Ref<AudioParam>,
+ pub(crate) forward_x: Ref<AudioParam>,
+ pub(crate) forward_y: Ref<AudioParam>,
+ pub(crate) forward_z: Ref<AudioParam>,
+ pub(crate) position_x: Ref<AudioParam>,
+ pub(crate) position_y: Ref<AudioParam>,
+ pub(crate) position_z: Ref<AudioParam>,
+ pub(crate) up_x: Ref<AudioParam>,
+ pub(crate) up_y: Ref<AudioParam>,
+ pub(crate) up_z: Ref<AudioParam>,
}
impl Wrappable for AudioListener {}
impl AudioListener {
- pub(crate) fn create(vm: &Vm, context: CppCell) -> Ref<Self> {
+ pub(crate) fn create(vm: &Vm, context: AnyBaseAudioContext) -> Ref<Self> {
allocate(vm, |_| Self {
forward_x: AudioParam::create(
vm,
- context.clone(),
+ context,
None,
0.,
f32::MIN,
@@ -45,7 +43,7 @@ impl AudioListener {
),
forward_y: AudioParam::create(
vm,
- context.clone(),
+ context,
None,
0.,
f32::MIN,
@@ -55,7 +53,7 @@ impl AudioListener {
),
forward_z: AudioParam::create(
vm,
- context.clone(),
+ context,
None,
-1.,
f32::MIN,
@@ -65,7 +63,7 @@ impl AudioListener {
),
position_x: AudioParam::create(
vm,
- context.clone(),
+ context,
None,
0.,
f32::MIN,
@@ -75,7 +73,7 @@ impl AudioListener {
),
position_y: AudioParam::create(
vm,
- context.clone(),
+ context,
None,
0.,
f32::MIN,
@@ -85,7 +83,7 @@ impl AudioListener {
),
position_z: AudioParam::create(
vm,
- context.clone(),
+ context,
None,
0.,
f32::MIN,
@@ -95,7 +93,7 @@ impl AudioListener {
),
up_x: AudioParam::create(
vm,
- context.clone(),
+ context,
None,
0.,
f32::MIN,
@@ -105,7 +103,7 @@ impl AudioListener {
),
up_y: AudioParam::create(
vm,
- context.clone(),
+ context,
None,
1.,
f32::MIN,
@@ -115,7 +113,7 @@ impl AudioListener {
),
up_z: AudioParam::create(
vm,
- context.clone(),
+ context,
None,
0.,
f32::MIN,
@@ -205,26 +203,3 @@ impl AudioListener {
Ok(())
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_listener_create(vm: &Vm, context: *mut c_void) -> *mut c_void {
- cell_into_abi(AudioListener::create(vm, unsafe { CppCell::from_raw(context) }))
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_listener_param(cell: *mut c_void, index: usize) -> *mut c_void {
- let listener: Ref<AudioListener> = unsafe { cell_from_abi(cell) };
- let param = match index {
- 0 => listener.forward_x,
- 1 => listener.forward_y,
- 2 => listener.forward_z,
- 3 => listener.position_x,
- 4 => listener.position_y,
- 5 => listener.position_z,
- 6 => listener.up_x,
- 7 => listener.up_y,
- 8 => listener.up_z,
- _ => unreachable!(),
- };
- cell_into_abi(param)
-}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_node.rs
new file mode 100644
index 00000000000..7509a54bbbf
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_node.rs
@@ -0,0 +1,811 @@
+/*
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2025-2026, Ben Eidson <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::Cell;
+use std::ffi::c_void;
+use std::ops::Deref;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::DeferGc;
+use libjs_rust::api::{GcRefCell, ThrowCompletionOr, Trace, Value};
+use libweb_rust::web_audio::control_message::{
+ AddNode, ControlMessage, RemoveNode, ReplaceConnections, SetChannelConfig,
+};
+use libweb_rust::web_audio::rendering::render_node::{NodeHandle, OutgoingNodeConnection, OutgoingParamConnection};
+
+use super::analyser_node::AnalyserNode;
+use super::audio_buffer_source_node::AudioBufferSourceNode;
+use super::audio_destination_node::AudioDestinationNode;
+use super::audio_param::AudioParam;
+use super::audio_scheduled_source_node::AudioScheduledSourceNode;
+use super::audio_worklet_node::AudioWorkletNode;
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use super::biquad_filter_node::BiquadFilterNode;
+use super::channel_merger_node::ChannelMergerNode;
+use super::channel_splitter_node::ChannelSplitterNode;
+use super::constant_source_node::ConstantSourceNode;
+use super::convolver_node::ConvolverNode;
+use super::delay_node::DelayNode;
+use super::dynamics_compressor_node::DynamicsCompressorNode;
+use super::gain_node::GainNode;
+use super::iir_filter_node::IIRFilterNode;
+use super::media_element_audio_source_node::MediaElementAudioSourceNode;
+use super::media_stream_audio_destination_node::MediaStreamAudioDestinationNode;
+use super::media_stream_audio_source_node::MediaStreamAudioSourceNode;
+use super::oscillator_node::OscillatorNode;
+use super::panner_node::PannerNode;
+use super::script_processor_node::ScriptProcessorNode;
+use super::stereo_panner_node::StereoPannerNode;
+use super::wave_shaper_node::WaveShaperNode;
+use crate::bindings::conversions::ToJs;
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+pub(crate) use libweb_rust::web_audio::rendering::render_node::{ChannelCountMode, ChannelInterpretation};
+
+#[derive(Default)]
+pub(crate) struct AudioNodeOptions {
+ pub channel_count: Option<u32>,
+ pub channel_count_mode: Option<ChannelCountMode>,
+ pub channel_interpretation: Option<ChannelInterpretation>,
+}
+
+pub(crate) struct AudioNodeDefaultOptions {
+ pub channel_count: u32,
+ pub channel_count_mode: ChannelCountMode,
+ pub channel_interpretation: ChannelInterpretation,
+}
+
+#[derive(Clone, Copy, PartialEq, Trace)]
+#[gc(crate = libjs_rust)]
+struct AudioNodeConnection {
+ destination_node: AnyAudioNode,
+ output: u32,
+ input: u32,
+}
+
+#[derive(Clone, Copy, PartialEq, Trace)]
+#[gc(crate = libjs_rust)]
+struct AudioParamConnection {
+ destination_param: Ref<AudioParam>,
+ output: u32,
+}
+
+// https://webaudio.github.io/web-audio-api/#AudioNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct AudioNode {
+ event_target: CppEventTarget,
+ context: AnyBaseAudioContext,
+ channel_count: Cell<u32>,
+ #[gc(untraced)]
+ channel_count_mode: Cell<ChannelCountMode>,
+ #[gc(untraced)]
+ channel_interpretation: Cell<ChannelInterpretation>,
+
+ // Connections from this node's outputs into other AudioNode inputs.
+ output_connections: GcRefCell<Vec<AudioNodeConnection>>,
+
+ // Connections from this node's outputs into AudioParams.
+ param_connections: GcRefCell<Vec<AudioParamConnection>>,
+ node_id: u64,
+ this: Cell<Option<AnyAudioNode>>,
+}
+
+impl Wrappable for AudioNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.event_target.as_cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.finalize_node();
+ }
+}
+
+impl GetTheParent for AudioNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+impl AudioNode {
+ pub(crate) fn new(_defer_gc: &DeferGc<'_>, context: AnyBaseAudioContext, channel_count: u32) -> Self {
+ let node_id = context.next_node_id();
+ Self {
+ event_target: CppEventTarget::new(),
+ context,
+ channel_count: Cell::new(channel_count),
+ channel_count_mode: Cell::new(ChannelCountMode::Max),
+ channel_interpretation: Cell::new(ChannelInterpretation::Speakers),
+ output_connections: GcRefCell::new(Vec::new()),
+ param_connections: GcRefCell::new(Vec::new()),
+ node_id,
+ this: Cell::new(None),
+ }
+ }
+
+ pub(crate) fn set_this(&self, this: AnyAudioNode) {
+ self.this.set(Some(this));
+ }
+
+ pub(crate) fn this(&self) -> AnyAudioNode {
+ self.this.get().expect("a node knows itself after allocation")
+ }
+
+ // A node that is no longer reachable from script or the audio graph retires
+ // its renderer node during finalization while the owning context is alive.
+ pub(crate) fn finalize_node(&self) {
+ self.context
+ .queue_control_message(ControlMessage::RemoveNode(RemoveNode { node_id: self.node_id }));
+ }
+
+ pub(crate) fn event_target(&self) -> &CppEventTarget {
+ &self.event_target
+ }
+
+ pub(crate) fn context_value(&self) -> AnyBaseAudioContext {
+ self.context
+ }
+
+ pub(crate) fn node_id(&self) -> u64 {
+ self.node_id
+ }
+
+ pub(crate) fn queue_render_node_creation(&self, node: Box<NodeHandle>) {
+ self.context
+ .queue_control_message(ControlMessage::AddNode(AddNode { node }));
+
+ // The channel configuration is settled before the render node is created, and the rendering thread ignores
+ // messages for nodes it does not know about yet, so it has to be sent again now.
+ self.queue_channel_config_update();
+ }
+
+ fn queue_connection_update(&self) {
+ let node_connections = self
+ .output_connections
+ .borrow()
+ .iter()
+ .map(|connection| OutgoingNodeConnection {
+ destination: connection.destination_node.node_id(),
+ output_index: connection.output as usize,
+ input_index: connection.input as usize,
+ })
+ .collect();
+ let param_connections = self
+ .param_connections
+ .borrow()
+ .iter()
+ .map(|connection| OutgoingParamConnection {
+ destination: Arc::clone(connection.destination_param.render_param()),
+ output_index: connection.output as usize,
+ })
+ .collect();
+ self.context
+ .queue_control_message(ControlMessage::ReplaceConnections(ReplaceConnections {
+ source: self.node_id(),
+ node_connections,
+ param_connections,
+ }));
+ }
+
+ fn queue_channel_config_update(&self) {
+ self.context
+ .queue_control_message(ControlMessage::SetChannelConfig(SetChannelConfig {
+ node_id: self.node_id(),
+ channel_count: self.channel_count.get() as usize,
+ channel_count_mode: self.channel_count_mode.get(),
+ channel_interpretation: self.channel_interpretation.get(),
+ }));
+ }
+
+ pub(crate) fn initialize_audio_node_options(
+ &self,
+ cx: &mut CallContext,
+ given_options: &AudioNodeOptions,
+ default_options: &AudioNodeDefaultOptions,
+ ) -> WebIdlResult<()> {
+ // Set channel count, fallback to default if not provided
+ if let Some(channel_count) = given_options.channel_count {
+ self.set_channel_count(cx, channel_count)?;
+ } else {
+ self.set_channel_count(cx, default_options.channel_count)?;
+ }
+
+ // Set channel count mode, fallback to default if not provided
+ if let Some(channel_count_mode) = given_options.channel_count_mode {
+ self.set_channel_count_mode(cx, channel_count_mode)?;
+ } else {
+ self.set_channel_count_mode(cx, default_options.channel_count_mode)?;
+ }
+
+ // Set channel interpretation, fallback to default if not provided
+ if let Some(channel_interpretation) = given_options.channel_interpretation {
+ self.set_channel_interpretation(cx, channel_interpretation)?;
+ } else {
+ self.set_channel_interpretation(cx, default_options.channel_interpretation)?;
+ }
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-connect
+ pub(crate) fn connect_to_node(
+ &self,
+ cx: &mut CallContext,
+ destination_node: AnyAudioNode,
+ output: u32,
+ input: u32,
+ ) -> WebIdlResult<AnyAudioNode> {
+ let output_connection = AudioNodeConnection {
+ destination_node,
+ output,
+ input,
+ };
+
+ // There can only be one connection between a given output of one specific node and a given input of another specific node.
+ // Multiple connections with the same termini are ignored.
+ for existing_connection in self.output_connections.borrow().iter() {
+ if *existing_connection == output_connection {
+ return Ok(destination_node);
+ }
+ }
+
+ // If the destination parameter is an AudioNode that has been created using another AudioContext, an InvalidAccessError MUST be thrown.
+ if self.context != destination_node.context_value() {
+ return Err(Exception::Dom(
+ "InvalidAccessError",
+ Utf16String::from_ascii(b"Cannot connect to an AudioNode in a different AudioContext"),
+ ));
+ }
+
+ // The output parameter is an index describing which output of the AudioNode from which to connect.
+ // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
+ if output >= self.number_of_outputs_value() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_utf8(&format!("Output index {output} exceeds number of outputs")),
+ ));
+ }
+
+ // The input parameter is an index describing which input of the destination AudioNode to connect to.
+ // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
+ if input >= destination_node.number_of_inputs_value() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_utf8(&format!("Input index '{input}' exceeds number of inputs")),
+ ));
+ }
+
+ // Connect node's output to destination_node input.
+ self.output_connections.borrow_mut(cx.vm()).push(output_connection);
+
+ self.queue_connection_update();
+
+ Ok(destination_node)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-connect-destinationparam-output
+ pub(crate) fn connect_to_param(
+ &self,
+ cx: &mut CallContext,
+ destination_param: Ref<AudioParam>,
+ output: u32,
+ ) -> WebIdlResult<()> {
+ let param_connection = AudioParamConnection {
+ destination_param,
+ output,
+ };
+
+ // There can only be one connection between a given output of one specific node and a specific AudioParam. Multiple connections
+ // with the same termini are ignored.
+ for existing_connection in self.param_connections.borrow().iter() {
+ if *existing_connection == param_connection {
+ return Ok(());
+ }
+ }
+
+ // If destinationParam belongs to an AudioNode that belongs to a BaseAudioContext that is different from the BaseAudioContext
+ // that has created the AudioNode on which this method was called, an InvalidAccessError MUST be thrown.
+ if self.context != destination_param.context_value() {
+ return Err(Exception::Dom(
+ "InvalidAccessError",
+ Utf16String::from_ascii(b"Cannot connect to an AudioParam in a different AudioContext"),
+ ));
+ }
+
+ // The output parameter is an index describing which output of the AudioNode from which to connect.
+ // If the parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
+ if output >= self.number_of_outputs_value() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_utf8(&format!("Output index {output} exceeds number of outputs")),
+ ));
+ }
+
+ // Connect node's output to destination_param.
+ self.param_connections.borrow_mut(cx.vm()).push(param_connection);
+
+ self.queue_connection_update();
+
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect
+ pub(crate) fn disconnect_all(&self, cx: &mut CallContext) -> WebIdlResult<()> {
+ self.output_connections.borrow_mut(cx.vm()).clear();
+ self.param_connections.borrow_mut(cx.vm()).clear();
+
+ self.queue_connection_update();
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-output
+ pub(crate) fn disconnect_output(&self, cx: &mut CallContext, output: u32) -> WebIdlResult<()> {
+ // The output parameter is an index describing which output of the AudioNode to disconnect.
+ // It disconnects all outgoing connections from the given output.
+ // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
+ if output >= self.number_of_outputs_value() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_utf8(&format!("Output index {output} exceeds number of outputs")),
+ ));
+ }
+
+ self.output_connections
+ .borrow_mut(cx.vm())
+ .retain(|connection| !(connection.output == output));
+
+ self.param_connections
+ .borrow_mut(cx.vm())
+ .retain(|connection| !(connection.output == output));
+
+ self.queue_connection_update();
+
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-destinationnode
+ pub(crate) fn disconnect_node(&self, cx: &mut CallContext, destination_node: AnyAudioNode) -> WebIdlResult<()> {
+ // The destinationNode parameter is the AudioNode to disconnect.
+ // It disconnects all outgoing connections to the given destinationNode.
+ let before = self.output_connections.borrow().len();
+ self.output_connections
+ .borrow_mut(cx.vm())
+ .retain(|connection| !(connection.destination_node == destination_node));
+
+ // If there is no connection to the destinationNode, an InvalidAccessError exception MUST be thrown.
+ if self.output_connections.borrow().len() == before {
+ return Err(Exception::Dom(
+ "InvalidAccessError",
+ Utf16String::from_ascii(b"No connection to given AudioNode"),
+ ));
+ }
+
+ self.queue_connection_update();
+
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-destinationnode-output
+ pub(crate) fn disconnect_node_output(
+ &self,
+ cx: &mut CallContext,
+ destination_node: AnyAudioNode,
+ output: u32,
+ ) -> WebIdlResult<()> {
+ // The output parameter is an index describing which output of the AudioNode from which to disconnect.
+ // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
+ if output >= self.number_of_outputs_value() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_utf8(&format!("Output index {output} exceeds number of outputs")),
+ ));
+ }
+
+ // The destinationNode parameter is the AudioNode to disconnect.
+ let before = self.output_connections.borrow().len();
+ self.output_connections
+ .borrow_mut(cx.vm())
+ .retain(|connection| !(connection.destination_node == destination_node && connection.output == output));
+
+ // If there is no connection to the destinationNode from the given output, an InvalidAccessError exception MUST be thrown.
+ if self.output_connections.borrow().len() == before {
+ return Err(Exception::Dom(
+ "InvalidAccessError",
+ Utf16String::from_utf8(&format!("No connection from output {output} to given AudioNode")),
+ ));
+ }
+
+ self.queue_connection_update();
+
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-destinationnode-output-input
+ pub(crate) fn disconnect_node_output_input(
+ &self,
+ cx: &mut CallContext,
+ destination_node: AnyAudioNode,
+ output: u32,
+ input: u32,
+ ) -> WebIdlResult<()> {
+ // The output parameter is an index describing which output of the AudioNode from which to disconnect.
+ // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
+ if output >= self.number_of_outputs_value() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_utf8(&format!("Output index {output} exceeds number of outputs")),
+ ));
+ }
+
+ // The input parameter is an index describing which input of the destination AudioNode to disconnect.
+ // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
+ if input >= destination_node.number_of_inputs_value() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_utf8(&format!("Input index '{input}' exceeds number of inputs")),
+ ));
+ }
+
+ // The destinationNode parameter is the AudioNode to disconnect.
+ let before = self.output_connections.borrow().len();
+ self.output_connections.borrow_mut(cx.vm()).retain(|connection| {
+ !(connection.destination_node == destination_node
+ && connection.output == output
+ && connection.input == input)
+ });
+
+ // If there is no connection to the destinationNode from the given output to the given input, an InvalidAccessError exception MUST be thrown.
+ if self.output_connections.borrow().len() == before {
+ return Err(Exception::Dom(
+ "InvalidAccessError",
+ Utf16String::from_utf8(&format!(
+ "No connection from output {output} to input {input} of given AudioNode"
+ )),
+ ));
+ }
+
+ self.queue_connection_update();
+
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-destinationparam
+ pub(crate) fn disconnect_param(
+ &self,
+ cx: &mut CallContext,
+ destination_param: Ref<AudioParam>,
+ ) -> WebIdlResult<()> {
+ // The destinationParam parameter is the AudioParam to disconnect.
+ let before = self.param_connections.borrow().len();
+ self.param_connections
+ .borrow_mut(cx.vm())
+ .retain(|connection| !(connection.destination_param == destination_param));
+
+ // If there is no connection to the destinationParam, an InvalidAccessError exception MUST be thrown.
+ if self.param_connections.borrow().len() == before {
+ return Err(Exception::Dom(
+ "InvalidAccessError",
+ Utf16String::from_ascii(b"No connection to given AudioParam"),
+ ));
+ }
+
+ self.queue_connection_update();
+
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-destinationparam-output
+ pub(crate) fn disconnect_param_output(
+ &self,
+ cx: &mut CallContext,
+ destination_param: Ref<AudioParam>,
+ output: u32,
+ ) -> WebIdlResult<()> {
+ // The output parameter is an index describing which output of the AudioNode from which to disconnect.
+ // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
+ if output >= self.number_of_outputs_value() {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_utf8(&format!("Output index {output} exceeds number of outputs")),
+ ));
+ }
+
+ // The destinationParam parameter is the AudioParam to disconnect.
+ let before = self.param_connections.borrow().len();
+ self.param_connections
+ .borrow_mut(cx.vm())
+ .retain(|connection| !(connection.destination_param == destination_param && connection.output == output));
+
+ // If there is no connection to the destinationParam, an InvalidAccessError exception MUST be thrown.
+ if self.param_connections.borrow().len() == before {
+ return Err(Exception::Dom(
+ "InvalidAccessError",
+ Utf16String::from_utf8(&format!("No connection from output {output} to given AudioParam")),
+ ));
+ }
+
+ self.queue_connection_update();
+
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-context
+ pub(crate) fn context(&self, _: &mut CallContext) -> WebIdlResult<AnyBaseAudioContext> {
+ // The BaseAudioContext which owns this AudioNode.
+ Ok(self.context)
+ }
+
+ pub(crate) fn channel_count_value(&self) -> u32 {
+ self.channel_count.get()
+ }
+
+ pub(crate) fn channel_count(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(self.channel_count_value())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-numberofinputs
+ pub(crate) fn number_of_inputs(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(self.number_of_inputs_value())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-numberofoutputs
+ pub(crate) fn number_of_outputs(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(self.number_of_outputs_value())
+ }
+
+ pub(crate) fn number_of_inputs_value(&self) -> u32 {
+ self.this().number_of_inputs()
+ }
+
+ pub(crate) fn number_of_outputs_value(&self) -> u32 {
+ self.this().number_of_outputs()
+ }
+
+ pub(crate) fn set_channel_count(&self, cx: &mut CallContext, value: u32) -> WebIdlResult<()> {
+ self.this().set_channel_count(cx, value)
+ }
+
+ pub(crate) fn set_channel_count_mode(&self, cx: &mut CallContext, value: ChannelCountMode) -> WebIdlResult<()> {
+ self.this().set_channel_count_mode(cx, value)
+ }
+
+ pub(crate) fn set_channel_interpretation(
+ &self,
+ cx: &mut CallContext,
+ value: ChannelInterpretation,
+ ) -> WebIdlResult<()> {
+ self.this().set_channel_interpretation(cx, value)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
+ pub(crate) fn set_channel_count_impl(&self, value: u32) -> WebIdlResult<()> {
+ // If this value is set to zero or to a value greater than the implementation’s maximum number
+ // of channels the implementation MUST throw a NotSupportedError exception.
+ if value == 0 || value > BaseAudioContext::MAX_NUMBER_OF_CHANNELS {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"Invalid channel count"),
+ ));
+ }
+ self.channel_count.set(value);
+ self.queue_channel_config_update();
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
+ pub(crate) fn set_channel_count_mode_impl(&self, value: ChannelCountMode) -> WebIdlResult<()> {
+ self.channel_count_mode.set(value);
+ self.queue_channel_config_update();
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
+ pub(crate) fn channel_count_mode(&self, _: &mut CallContext) -> WebIdlResult<ChannelCountMode> {
+ Ok(self.channel_count_mode.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelinterpretation
+ pub(crate) fn set_channel_interpretation_impl(&self, value: ChannelInterpretation) -> WebIdlResult<()> {
+ self.channel_interpretation.set(value);
+ self.queue_channel_config_update();
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelinterpretation
+ pub(crate) fn channel_interpretation(&self, _: &mut CallContext) -> WebIdlResult<ChannelInterpretation> {
+ Ok(self.channel_interpretation.get())
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Trace)]
+#[gc(crate = libjs_rust)]
+#[allow(clippy::enum_variant_names, reason = "the variants have the interfaces’ names")]
+pub(crate) enum AnyAudioNode {
+ AudioNode(Ref<AudioNode>),
+ AudioScheduledSourceNode(Ref<AudioScheduledSourceNode>),
+ AnalyserNode(Ref<AnalyserNode>),
+ AudioBufferSourceNode(Ref<AudioBufferSourceNode>),
+ AudioDestinationNode(Ref<AudioDestinationNode>),
+ AudioWorkletNode(Ref<AudioWorkletNode>),
+ BiquadFilterNode(Ref<BiquadFilterNode>),
+ ChannelMergerNode(Ref<ChannelMergerNode>),
+ ChannelSplitterNode(Ref<ChannelSplitterNode>),
+ ConstantSourceNode(Ref<ConstantSourceNode>),
+ ConvolverNode(Ref<ConvolverNode>),
+ DelayNode(Ref<DelayNode>),
+ DynamicsCompressorNode(Ref<DynamicsCompressorNode>),
+ GainNode(Ref<GainNode>),
+ IIRFilterNode(Ref<IIRFilterNode>),
+ MediaElementAudioSourceNode(Ref<MediaElementAudioSourceNode>),
+ MediaStreamAudioDestinationNode(Ref<MediaStreamAudioDestinationNode>),
+ MediaStreamAudioSourceNode(Ref<MediaStreamAudioSourceNode>),
+ OscillatorNode(Ref<OscillatorNode>),
+ PannerNode(Ref<PannerNode>),
+ ScriptProcessorNode(Ref<ScriptProcessorNode>),
+ StereoPannerNode(Ref<StereoPannerNode>),
+ WaveShaperNode(Ref<WaveShaperNode>),
+}
+
+impl Deref for AnyAudioNode {
+ type Target = AudioNode;
+
+ fn deref(&self) -> &AudioNode {
+ match self {
+ Self::AudioNode(node) => node,
+ Self::AudioScheduledSourceNode(node) => node.parent(),
+ Self::AnalyserNode(node) => node.parent(),
+ Self::AudioBufferSourceNode(node) => node.parent().parent(),
+ Self::AudioDestinationNode(node) => node.parent(),
+ Self::AudioWorkletNode(node) => node.parent(),
+ Self::BiquadFilterNode(node) => node.parent(),
+ Self::ChannelMergerNode(node) => node.parent(),
+ Self::ChannelSplitterNode(node) => node.parent(),
+ Self::ConstantSourceNode(node) => node.parent().parent(),
+ Self::ConvolverNode(node) => node.parent(),
+ Self::DelayNode(node) => node.parent(),
+ Self::DynamicsCompressorNode(node) => node.parent(),
+ Self::GainNode(node) => node.parent(),
+ Self::IIRFilterNode(node) => node.parent(),
+ Self::MediaElementAudioSourceNode(node) => node.parent(),
+ Self::MediaStreamAudioDestinationNode(node) => node.parent(),
+ Self::MediaStreamAudioSourceNode(node) => node.parent(),
+ Self::OscillatorNode(node) => node.parent().parent(),
+ Self::PannerNode(node) => node.parent(),
+ Self::ScriptProcessorNode(node) => node.parent(),
+ Self::StereoPannerNode(node) => node.parent(),
+ Self::WaveShaperNode(node) => node.parent(),
+ }
+ }
+}
+
+impl ToJs for AnyAudioNode {
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {
+ match self {
+ Self::AudioNode(node) => node.to_js(cx),
+ Self::AudioScheduledSourceNode(node) => node.to_js(cx),
+ Self::AnalyserNode(node) => node.to_js(cx),
+ Self::AudioBufferSourceNode(node) => node.to_js(cx),
+ Self::AudioDestinationNode(node) => node.to_js(cx),
+ Self::AudioWorkletNode(node) => node.to_js(cx),
+ Self::BiquadFilterNode(node) => node.to_js(cx),
+ Self::ChannelMergerNode(node) => node.to_js(cx),
+ Self::ChannelSplitterNode(node) => node.to_js(cx),
+ Self::ConstantSourceNode(node) => node.to_js(cx),
+ Self::ConvolverNode(node) => node.to_js(cx),
+ Self::DelayNode(node) => node.to_js(cx),
+ Self::DynamicsCompressorNode(node) => node.to_js(cx),
+ Self::GainNode(node) => node.to_js(cx),
+ Self::IIRFilterNode(node) => node.to_js(cx),
+ Self::MediaElementAudioSourceNode(node) => node.to_js(cx),
+ Self::MediaStreamAudioDestinationNode(node) => node.to_js(cx),
+ Self::MediaStreamAudioSourceNode(node) => node.to_js(cx),
+ Self::OscillatorNode(node) => node.to_js(cx),
+ Self::PannerNode(node) => node.to_js(cx),
+ Self::ScriptProcessorNode(node) => node.to_js(cx),
+ Self::StereoPannerNode(node) => node.to_js(cx),
+ Self::WaveShaperNode(node) => node.to_js(cx),
+ }
+ }
+}
+
+impl AnyAudioNode {
+ fn number_of_inputs(self) -> u32 {
+ match self {
+ Self::AudioNode(_) => unreachable!("an abstract audio node has no instances"),
+ Self::AudioScheduledSourceNode(_) => unreachable!("an abstract audio node has no instances"),
+ Self::AnalyserNode(_) => 1,
+ Self::AudioBufferSourceNode(_) => 0,
+ Self::AudioDestinationNode(_) => 1,
+ Self::AudioWorkletNode(node) => node.number_of_inputs_value(),
+ Self::BiquadFilterNode(_) => 1,
+ Self::ChannelMergerNode(node) => node.number_of_inputs_value(),
+ Self::ChannelSplitterNode(node) => node.number_of_inputs_value(),
+ Self::ConstantSourceNode(_) => 0,
+ Self::ConvolverNode(_) => 1,
+ Self::DelayNode(_) => 1,
+ Self::DynamicsCompressorNode(_) => 1,
+ Self::GainNode(_) => 1,
+ Self::IIRFilterNode(_) => 1,
+ Self::MediaElementAudioSourceNode(_) => 0,
+ Self::MediaStreamAudioDestinationNode(_) => 1,
+ Self::MediaStreamAudioSourceNode(_) => 0,
+ Self::OscillatorNode(_) => 0,
+ Self::PannerNode(_) => 1,
+ Self::ScriptProcessorNode(node) => node.number_of_inputs_value(),
+ Self::StereoPannerNode(_) => 1,
+ Self::WaveShaperNode(_) => 1,
+ }
+ }
+
+ fn number_of_outputs(self) -> u32 {
+ match self {
+ Self::AudioNode(_) => unreachable!("an abstract audio node has no instances"),
+ Self::AudioScheduledSourceNode(_) => unreachable!("an abstract audio node has no instances"),
+ Self::AnalyserNode(_) => 1,
+ Self::AudioBufferSourceNode(_) => 1,
+ Self::AudioDestinationNode(_) => 1,
+ Self::AudioWorkletNode(node) => node.number_of_outputs_value(),
+ Self::BiquadFilterNode(_) => 1,
+ Self::ChannelMergerNode(node) => node.number_of_outputs_value(),
+ Self::ChannelSplitterNode(node) => node.number_of_outputs_value(),
+ Self::ConstantSourceNode(_) => 1,
+ Self::ConvolverNode(_) => 1,
+ Self::DelayNode(_) => 1,
+ Self::DynamicsCompressorNode(_) => 1,
+ Self::GainNode(_) => 1,
+ Self::IIRFilterNode(_) => 1,
+ Self::MediaElementAudioSourceNode(_) => 1,
+ Self::MediaStreamAudioDestinationNode(_) => 0,
+ Self::MediaStreamAudioSourceNode(_) => 1,
+ Self::OscillatorNode(_) => 1,
+ Self::PannerNode(_) => 1,
+ Self::ScriptProcessorNode(node) => node.number_of_outputs_value(),
+ Self::StereoPannerNode(_) => 1,
+ Self::WaveShaperNode(_) => 1,
+ }
+ }
+
+ fn set_channel_count(self, cx: &mut CallContext, value: u32) -> WebIdlResult<()> {
+ match self {
+ Self::AudioDestinationNode(node) => node.set_channel_count_override(cx, value),
+ Self::ChannelMergerNode(node) => node.set_channel_count_override(cx, value),
+ Self::ChannelSplitterNode(node) => node.set_channel_count_override(cx, value),
+ Self::DynamicsCompressorNode(node) => node.set_channel_count_override(cx, value),
+ Self::PannerNode(node) => node.set_channel_count_override(cx, value),
+ Self::StereoPannerNode(node) => node.set_channel_count_override(cx, value),
+ Self::ScriptProcessorNode(node) => node.set_channel_count_override(cx, value),
+ Self::ConvolverNode(node) => node.set_channel_count_override(cx, value),
+ _ => self.deref().set_channel_count_impl(value),
+ }
+ }
+
+ fn set_channel_count_mode(self, cx: &mut CallContext, value: ChannelCountMode) -> WebIdlResult<()> {
+ match self {
+ Self::ChannelMergerNode(node) => node.set_channel_count_mode_override(cx, value),
+ Self::ChannelSplitterNode(node) => node.set_channel_count_mode_override(cx, value),
+ Self::DynamicsCompressorNode(node) => node.set_channel_count_mode_override(cx, value),
+ Self::PannerNode(node) => node.set_channel_count_mode_override(cx, value),
+ Self::StereoPannerNode(node) => node.set_channel_count_mode_override(cx, value),
+ Self::ScriptProcessorNode(node) => node.set_channel_count_mode_override(cx, value),
+ Self::ConvolverNode(node) => node.set_channel_count_mode_override(cx, value),
+ _ => self.deref().set_channel_count_mode_impl(value),
+ }
+ }
+
+ fn set_channel_interpretation(self, cx: &mut CallContext, value: ChannelInterpretation) -> WebIdlResult<()> {
+ match self {
+ Self::ChannelSplitterNode(node) => node.set_channel_interpretation_override(cx, value),
+ _ => self.deref().set_channel_interpretation_impl(value),
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rs
index e76e44cb8e4..24ee67048f2 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rs
@@ -6,17 +6,16 @@
*/
use std::cell::Cell;
-use std::ffi::c_void;
-use std::ptr::NonNull;
use std::sync::Arc;
use ak::Utf16String;
-use libjs_rust::api::{Gc, RawNativeFunctionResult, Realm, Trace, Value, Vm};
+use libjs_rust::api::{Trace, Vm};
use libweb_rust::web_audio::audio_param_timeline::{AudioParamTimeline, InsertResult};
use libweb_rust::web_audio::rendering::render_node::RenderAudioParam;
-use crate::bindings::cpp_cell::CppCell;
-use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, realm_arguments};
+use super::audio_node::AnyAudioNode;
+use super::base_audio_context::AnyBaseAudioContext;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
use crate::bindings::{CallContext, Exception, WebIdlResult};
pub(crate) use libweb_rust::web_audio::rendering::render_node::AutomationRate;
@@ -32,8 +31,11 @@ pub(crate) enum FixedAutomationRate {
#[derive(Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct AudioParam {
- context: CppCell,
- owner: Option<CppCell>,
+ context: AnyBaseAudioContext,
+
+ // An AudioParam is a facet of the AudioNode that exposes it, so holding on to the parameter keeps that node, and
+ // with it the node's render node and automation, alive.
+ owner: Cell<Option<AnyAudioNode>>,
#[gc(untraced)]
timeline: Arc<AudioParamTimeline>,
#[gc(untraced)]
@@ -51,11 +53,6 @@ pub(crate) struct AudioParam {
}
impl Wrappable for AudioParam {}
-unsafe extern "C" {
- fn web_audio_context_current_time(context: *mut c_void) -> f64;
- fn web_audio_context_realm(context: *mut c_void) -> *mut c_void;
-}
-
fn clamp(value: f32, min: f32, max: f32) -> f32 {
assert!(max >= min);
if value > max {
@@ -76,8 +73,8 @@ impl AudioParam {
#[allow(clippy::too_many_arguments, reason = "preserve the C++ parameter initialization")]
pub(crate) fn create(
vm: &Vm,
- context: CppCell,
- owner: Option<CppCell>,
+ context: AnyBaseAudioContext,
+ owner: Option<AnyAudioNode>,
default_value: f32,
min_value: f32,
max_value: f32,
@@ -94,7 +91,7 @@ impl AudioParam {
));
Self {
context,
- owner,
+ owner: Cell::new(owner),
timeline,
render_param,
current_value: Cell::new(default_value),
@@ -107,14 +104,24 @@ impl AudioParam {
})
}
+ pub(crate) fn set_owner(&self, owner: AnyAudioNode) {
+ self.owner.set(Some(owner));
+ }
+
+ pub(crate) fn context_value(&self) -> AnyBaseAudioContext {
+ self.context
+ }
+
+ pub(crate) fn render_param(&self) -> &Arc<RenderAudioParam> {
+ &self.render_param
+ }
+
fn current_time(&self) -> f64 {
- unsafe { web_audio_context_current_time(self.context.as_ptr()) }
+ self.context.current_time_value()
}
fn context_error(&self, vm: &Vm, name: &'static str, message: &[u8]) -> Exception {
- let realm = unsafe {
- Gc::from_non_null(NonNull::new(web_audio_context_realm(self.context.as_ptr()).cast::<Realm>()).unwrap())
- };
+ let realm = self.context.realm();
Exception::Thrown(Exception::Dom(name, Utf16String::from_ascii(message)).throw(&CallContext::new(vm, realm)))
}
@@ -367,61 +374,3 @@ impl AudioParam {
Ok(*this)
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_param_create(
- vm: &Vm,
- context: *mut c_void,
- owner: *mut c_void,
- default_value: f32,
- min_value: f32,
- max_value: f32,
- automation_rate: AutomationRate,
- fixed: FixedAutomationRate,
-) -> *mut c_void {
- cell_into_abi(AudioParam::create(
- vm,
- unsafe { CppCell::from_raw(context) },
- (!owner.is_null()).then(|| unsafe { CppCell::from_raw(owner) }),
- default_value,
- min_value,
- max_value,
- automation_rate,
- fixed,
- ))
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_param_context(cell: *mut c_void) -> *mut c_void {
- let param: Ref<AudioParam> = unsafe { cell_from_abi(cell) };
- param.context.as_ptr()
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_param_set_value(
- vm: *mut c_void,
- realm: *mut c_void,
- cell: *mut c_void,
- value: f32,
-) -> RawNativeFunctionResult {
- let (vm, realm) = unsafe { realm_arguments(vm, realm) };
- let mut cx = CallContext::new(vm, realm);
- let param: Ref<AudioParam> = unsafe { cell_from_abi(cell) };
- RawNativeFunctionResult::from_completion(
- AudioParam::set_value(&param, &mut cx, value)
- .map(|()| Value::UNDEFINED)
- .map_err(|error| error.throw(&cx)),
- )
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_param_intrinsic_value(cell: *mut c_void, time: f64) -> f32 {
- let param: Ref<AudioParam> = unsafe { cell_from_abi(cell) };
- param.intrinsic_value_at_time(time)
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_param_render_param(cell: *mut c_void) -> *const RenderAudioParam {
- let param: Ref<AudioParam> = unsafe { cell_from_abi(cell) };
- Arc::into_raw(Arc::clone(&param.render_param))
-}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param_map.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param_map.rs
index ab2f4af9f80..d3e3a78fa43 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param_map.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param_map.rs
@@ -4,15 +4,13 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use std::ffi::c_void;
-
use ak::Utf16String;
use libjs_rust::api::{Gc, GcRefCell, Map, Trace, Value, Vm};
use super::audio_param::AudioParam;
use crate::bindings::CallContext;
use crate::bindings::conversions::{ToJs, to_dom_string};
-use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, this_implementation, wrap};
+use crate::bindings::interface::{Ref, Wrappable, allocate, this_implementation, wrap};
use crate::bindings::maplike::Maplike;
// https://webaudio.github.io/web-audio-api/#AudioParamMap
@@ -24,6 +22,14 @@ pub(crate) struct AudioParamMap {
impl Wrappable for AudioParamMap {}
impl AudioParamMap {
+ pub(crate) fn values<'vm>(&self, vm: &'vm Vm) -> libjs_rust::api::MarkedVec<'vm, Ref<AudioParam>> {
+ let values = libjs_rust::api::MarkedVec::new(vm);
+ for (_, value) in &*self.entries.borrow() {
+ values.push(*value);
+ }
+ values
+ }
+
pub(crate) fn create(vm: &Vm) -> Ref<Self> {
allocate(vm, |_| Self {
entries: GcRefCell::new(Vec::new()),
@@ -75,34 +81,3 @@ impl Maplike for AudioParamMap {
Some(Value::from_object(wrap(cx, entry.1)))
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_param_map_create(vm: &Vm) -> *mut c_void {
- cell_into_abi(AudioParamMap::create(vm))
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_param_map_set_entry(
- vm: &Vm,
- cell: *mut c_void,
- key: usize,
- param: *mut c_void,
-) {
- let map: Ref<AudioParamMap> = unsafe { cell_from_abi(cell) };
- let param: Ref<AudioParam> = unsafe { cell_from_abi(param) };
- map.set_entry(vm, unsafe { ak::Utf16FlyString::from_raw_borrowed(key).into() }, param);
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_param_map_values(
- cell: *mut c_void,
- context: *mut c_void,
- callback: unsafe extern "C" fn(*mut c_void, *mut c_void),
-) {
- let map: Ref<AudioParamMap> = unsafe { cell_from_abi(cell) };
- for (_key, value) in &*map.entries.borrow() {
- unsafe {
- callback(context, cell_into_abi(*value));
- }
- }
-}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_processing_event.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_processing_event.rs
index ca62d476051..68c45329b63 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_processing_event.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_processing_event.rs
@@ -13,7 +13,7 @@ use libjs_rust::api::{Trace, Vm};
use super::audio_buffer::AudioBuffer;
use crate::bindings::event_target::CppEvent;
-use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi};
+use crate::bindings::interface::{Ref, Wrappable, allocate};
use crate::bindings::{CallContext, WebIdlResult};
use crate::dom::event::EventInit;
@@ -28,7 +28,7 @@ pub(crate) struct AudioProcessingEventInit {
#[derive(Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct AudioProcessingEvent {
- event: CppEvent,
+ pub(crate) event: CppEvent,
playback_time: f64,
input_buffer: Ref<AudioBuffer>,
output_buffer: Ref<AudioBuffer>,
@@ -91,19 +91,3 @@ impl AudioProcessingEvent {
Ok(self.output_buffer)
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_processing_event_create(
- vm: &Vm,
- event: *mut c_void,
- playback_time: f64,
- input: *mut c_void,
- output: *mut c_void,
-) -> *mut c_void {
- let event = unsafe { CppEvent::from_raw(event) };
- let input: Ref<AudioBuffer> = unsafe { cell_from_abi(input) };
- let output: Ref<AudioBuffer> = unsafe { cell_from_abi(output) };
- AudioProcessingEvent::create(vm, event, playback_time, input, output)
- .event
- .as_ptr()
-}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_scheduled_source_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_scheduled_source_node.rs
new file mode 100644
index 00000000000..048feda6270
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_scheduled_source_node.rs
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::Cell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::DeferGc;
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::control_message::ControlMessage;
+use libweb_rust::web_audio::rendering::node_message::{NodeMessage, StartSource, StopSource};
+
+use super::audio_node::AudioNode;
+use super::base_audio_context::AnyBaseAudioContext;
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#AudioScheduledSourceNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct AudioScheduledSourceNode {
+ node: AudioNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-source-started-slot
+ source_started: Cell<bool>,
+}
+
+impl Inherits<AudioNode> for AudioScheduledSourceNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for AudioScheduledSourceNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for AudioScheduledSourceNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+impl AudioScheduledSourceNode {
+ pub(crate) fn new(defer_gc: &DeferGc<'_>, context: AnyBaseAudioContext) -> Self {
+ Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ source_started: Cell::new(false),
+ }
+ }
+
+ pub(crate) fn source_started(&self) -> bool {
+ self.source_started.get()
+ }
+
+ pub(crate) fn set_source_started(&self, value: bool) {
+ self.source_started.set(value);
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-start
+ pub(crate) fn start(&self, cx: &mut CallContext, when: f64) -> WebIdlResult<()> {
+ // 1. If this AudioScheduledSourceNode internal slot [[source started]] is true, an InvalidStateError exception MUST be thrown.
+ if self.source_started() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"AudioScheduledSourceNode source has already started"),
+ ));
+ }
+
+ // 2. Check for any errors that must be thrown due to parameter constraints described below.
+ // If any exception is thrown during this step, abort those steps.
+ // A RangeError exception MUST be thrown if when is negative.
+ if when < 0. {
+ return Err(Exception::range_error("when must not be negative"));
+ }
+
+ // 3. Set the internal slot [[source started]] on this AudioScheduledSourceNode to true.
+ self.set_source_started(true);
+
+ // 4. Queue a control message to start the AudioScheduledSourceNode, including the parameter values in the message.
+ self.node
+ .context_value()
+ .queue_control_message(ControlMessage::NodeMessage(NodeMessage::StartSource(StartSource {
+ node_id: self.node.node_id(),
+ when,
+ })));
+ self.node.context_value().add_playing_source(cx.vm(), self.node.this());
+
+ // FIXME: 5. Send a control message to the associated AudioContext to start running its rendering thread only when all the following conditions are met:
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-stop
+ pub(crate) fn stop(&self, _: &mut CallContext, when: f64) -> WebIdlResult<()> {
+ // 1. If this AudioScheduledSourceNode internal slot [[source started]] is not true, an InvalidStateError exception MUST be thrown.
+ if !self.source_started.get() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"AudioScheduledSourceNode source has not been started"),
+ ));
+ }
+
+ // 2. Check for any errors that must be thrown due to parameter constraints described below.
+ // A RangeError exception MUST be thrown if when is negative.
+ if when < 0. {
+ return Err(Exception::range_error("when must not be negative"));
+ }
+
+ // 3. Queue a control message to stop the AudioScheduledSourceNode, including the parameter values in the message.
+ self.node
+ .context_value()
+ .queue_control_message(ControlMessage::NodeMessage(NodeMessage::StopSource(StopSource {
+ node_id: self.node.node_id(),
+ when,
+ })));
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_worklet_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_worklet_node.rs
new file mode 100644
index 00000000000..d69f34ecde6
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_worklet_node.rs
@@ -0,0 +1,603 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#![allow(clippy::collapsible_if, reason = "preserve the C++ branch structure")]
+
+use std::cell::Cell;
+use std::cell::RefCell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{
+ Array, EmbedderClass, EmbedderValue, FunctionObject, Object, PropertyKey, RawNativeFunctionResult, Value, Vm,
+ construct,
+};
+use libjs_rust::api::{Gc, Realm, Trace};
+use libweb_rust::web_audio::control_message::FfiSharedCppObject;
+use libweb_rust::web_audio::rendering::audio_worklet_pipe::{AudioWorkletPipe, WorkletPipeConfig, WorkletPipeState};
+use libweb_rust::web_audio::rendering::audio_worklet_render_node::web_audio_node_create_audio_worklet;
+use libweb_rust::web_audio::rendering::node_message::SharedCppObject;
+use libweb_rust::web_audio::rendering::render_node::RenderAudioParam;
+
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::audio_param::{AudioParam, AutomationRate, FixedAutomationRate};
+use super::audio_param_map::AudioParamMap;
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::interface::{cell_from_abi, cell_into_abi, with_temporary_execution_context_and_callbacks};
+use crate::bindings::promise::{TaskSource, queue_a_global_task};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::html::message_port::MessagePort;
+
+// https://webaudio.github.io/web-audio-api/#AudioWorkletNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct AudioWorkletNode {
+ node: AudioNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-audioworkletnode-audioworkletnode-context-name-options-name
+ name: Utf16String,
+ number_of_inputs: u32,
+ number_of_outputs: u32,
+ parameter_map: Ref<AudioParamMap>,
+ port: Ref<MessagePort>,
+ processor: Cell<Option<Gc<Object>>>,
+ processor_errored: Cell<bool>,
+ #[gc(untraced)]
+ pipe: RefCell<Option<Arc<AudioWorkletPipe>>>,
+ #[gc(untraced)]
+ pipe_service: RefCell<Option<SharedCppObject>>,
+}
+
+impl Inherits<AudioNode> for AudioWorkletNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for AudioWorkletNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ if let Some(service) = &*node.pipe_service.borrow() {
+ unsafe { web_audio_worklet_clear_pump(service.pointer) };
+ }
+ if let Some(pipe) = &*node.pipe.borrow() {
+ pipe.set_state(WorkletPipeState::ShutDown);
+ }
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for AudioWorkletNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct AudioWorkletNodeOptions {
+ pub parent: AudioNodeOptions,
+ pub number_of_inputs: u32,
+ pub number_of_outputs: u32,
+ pub output_channel_count: Option<Vec<u32>>,
+ pub parameter_data: Option<Vec<(Utf16String, f64)>>,
+ pub processor_options: Option<Gc<Object>>,
+}
+
+struct AudioParamDescriptor {
+ name: Utf16String,
+ default_value: f32,
+ min_value: f32,
+ max_value: f32,
+ automation_rate: AutomationRate,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct ProcessorConstructionTask {
+ node: Ref<AudioWorkletNode>,
+ scope: CppCell,
+ processor_port: Ref<MessagePort>,
+ options_object: Gc<Object>,
+}
+
+static PROCESSOR_CONSTRUCTION_TASK_CLASS: EmbedderClass<ProcessorConstructionTask> =
+ EmbedderClass::new("AudioWorkletProcessorConstructionTask");
+impl EmbedderValue for ProcessorConstructionTask {
+ const CLASS: &'static EmbedderClass<Self> = &PROCESSOR_CONSTRUCTION_TASK_CLASS;
+}
+
+unsafe extern "C" {
+ fn web_audio_worklet_find_definition(
+ worklet: *mut c_void,
+ name: usize,
+ context: *mut c_void,
+ descriptor: unsafe extern "C" fn(*mut c_void, usize, f32, f32, f32, AutomationRate),
+ ) -> bool;
+ fn web_audio_worklet_global_scope(worklet: *mut c_void) -> *mut c_void;
+ fn web_audio_worklet_scope_realm(scope: *mut c_void) -> *mut c_void;
+ fn web_audio_worklet_clone_options(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ error_realm: *mut c_void,
+ options: *mut c_void,
+ ) -> RawNativeFunctionResult;
+ fn web_audio_worklet_create_pipe(
+ config: WorkletPipeConfig<'_>,
+ sample_rate: f32,
+ native_pipe: *mut *const c_void,
+ ) -> FfiSharedCppObject;
+ fn web_audio_worklet_set_pump(pipe: *mut c_void, scope: *mut c_void, node_id: u64);
+ fn web_audio_worklet_clear_pump(pipe: *mut c_void);
+ fn web_audio_worklet_processor_constructor(scope: *mut c_void, name: usize) -> *mut c_void;
+ fn web_audio_worklet_set_pending_port(scope: *mut c_void, port: *mut c_void);
+ fn web_audio_worklet_clear_pending_data(scope: *mut c_void);
+ fn web_audio_worklet_add_processor_slot(
+ scope: *mut c_void,
+ node_id: u64,
+ processor: *mut c_void,
+ port: *mut c_void,
+ node: *mut c_void,
+ pipe: *mut c_void,
+ names: ak::Span<'_, usize>,
+ );
+ fn web_audio_worklet_queue_processor_error(node: *mut c_void, target: *mut c_void, global: *mut c_void, error: u64);
+}
+
+impl AudioWorkletNode {
+ fn this(&self) -> Ref<Self> {
+ let AnyAudioNode::AudioWorkletNode(node) = self.node.this() else {
+ unreachable!()
+ };
+ node
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audioworkletnode-audioworkletnode
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ name: Utf16String,
+ options: AudioWorkletNodeOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ let vm = cx.vm();
+
+ // 1. If nodeName does not exist as a key in the BaseAudioContext's node name to parameter descriptor
+ // map, throw an InvalidStateError exception and abort these steps.
+ let worklet = context.audio_worklet_cell(vm);
+ let mut descriptors = Vec::<AudioParamDescriptor>::new();
+ unsafe extern "C" fn descriptor(
+ context: *mut c_void,
+ name: usize,
+ default_value: f32,
+ min_value: f32,
+ max_value: f32,
+ automation_rate: AutomationRate,
+ ) {
+ let name = unsafe { ak::Utf16FlyString::from_raw_borrowed(name) }.into();
+ unsafe { &mut *context.cast::<Vec<AudioParamDescriptor>>() }.push(AudioParamDescriptor {
+ name,
+ default_value,
+ min_value,
+ max_value,
+ automation_rate,
+ });
+ }
+ if !unsafe {
+ web_audio_worklet_find_definition(
+ worklet.as_ptr(),
+ name.raw_identity(),
+ (&raw mut descriptors).cast(),
+ descriptor,
+ )
+ } {
+ let mut message: Vec<u16> = b"No AudioWorkletProcessor named '"
+ .iter()
+ .copied()
+ .map(u16::from)
+ .collect();
+ message.extend_from_slice(&name.to_utf16());
+ message.extend(b"' is registered".iter().copied().map(u16::from));
+ return Err(Exception::Dom("InvalidStateError", Utf16String::from_utf16(&message)));
+ }
+
+ // https://webaudio.github.io/web-audio-api/#configuring-channels-with-audioworkletnodeoptions
+ // If both numberOfInputs and numberOfOutputs are zero, throw a NotSupportedError.
+ if options.number_of_inputs == 0 && options.number_of_outputs == 0 {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"AudioWorkletNode must have at least one input or output"),
+ ));
+ }
+
+ // If outputChannelCount exists: throw an IndexSizeError if its length does not equal numberOfOutputs;
+ // throw a NotSupportedError if any entry is zero or greater than the supported maximum.
+ if let Some(output_channel_count) = &options.output_channel_count {
+ if output_channel_count.len() != options.number_of_outputs as usize {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"outputChannelCount length must equal numberOfOutputs"),
+ ));
+ }
+ for channel_count in output_channel_count {
+ if *channel_count == 0 || *channel_count > BaseAudioContext::MAX_NUMBER_OF_CHANNELS {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"outputChannelCount entries must be between 1 and 32"),
+ ));
+ }
+ }
+ }
+ let scope = unsafe { CppCell::from_raw(web_audio_worklet_global_scope(worklet.as_ptr())) };
+ let worklet_realm: Gc<Realm> =
+ unsafe { Gc::from_non_null(NonNull::new(web_audio_worklet_scope_realm(scope.as_ptr()).cast()).unwrap()) };
+
+ // 2. Let node be this value; initialize node's AudioNode base with context and options.
+ let parameter_map = AudioParamMap::create(vm);
+ let node_port = MessagePort::create(vm, context.realm());
+ let node = allocate(vm, |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ name,
+ number_of_inputs: options.number_of_inputs,
+ number_of_outputs: options.number_of_outputs,
+ parameter_map,
+ port: node_port,
+ processor: Cell::new(None),
+ processor_errored: Cell::new(false),
+ pipe: RefCell::new(None),
+ pipe_service: RefCell::new(None),
+ });
+ node.node.set_this(AnyAudioNode::AudioWorkletNode(node));
+ node.node.event_target().set_owner(node);
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::Max,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+
+ // 3. Let map be a new AudioParamMap; for each descriptor in the parameter descriptors, create an
+ // AudioParam and append it to map; apply parameterData overrides.
+ for descriptor in &descriptors {
+ let param = AudioParam::create(
+ vm,
+ context,
+ Some(AnyAudioNode::AudioWorkletNode(node)),
+ descriptor.default_value,
+ descriptor.min_value,
+ descriptor.max_value,
+ descriptor.automation_rate,
+ FixedAutomationRate::No,
+ );
+ if let Some(parameter_data) = &options.parameter_data {
+ if let Some(entry) = parameter_data.iter().find(|entry| entry.0 == descriptor.name) {
+ AudioParam::set_value(&param, cx, entry.1 as f32)?;
+ }
+ }
+ parameter_map.set_entry(vm, descriptor.name.clone(), param);
+ }
+
+ // 4. Let messageChannel be a new MessageChannel (collapsed): node.port and the processor's port are
+ // entangled; node.port's message queue is enabled immediately. The processor-side port stays
+ // disabled until the processor constructor has returned, so messages posted before (or during)
+ // construction are queued and delivered to listeners the constructor registered — even ones added
+ // with addEventListener() and no explicit start().
+ let processor_port = MessagePort::create(vm, worklet_realm);
+ MessagePort::entangle(vm, node_port, processor_port);
+ MessagePort::enable(node_port, vm);
+
+ // 5. Let serializedProcessorOptions be StructuredSerialize(optionsObject's processorOptions).
+ // 6-7. (Deserialization happens into the worklet realm when building the processor's options object.)
+ let mut cloned_processor_options = None;
+ if let Some(processor_options) = options.processor_options {
+ let value = unsafe {
+ web_audio_worklet_clone_options(
+ (vm as *const Vm).cast_mut().cast(),
+ worklet_realm.as_ptr().cast(),
+ cx.realm().as_ptr().cast(),
+ processor_options.as_ptr().cast(),
+ )
+ }
+ .into_completion()?;
+ assert!(value.is_object());
+ cloned_processor_options = Some(value.as_object());
+ }
+ let options_object = Object::create(vm, worklet_realm, Some(worklet_realm.intrinsics().object_prototype(vm)));
+ options_object
+ .create_data_property(
+ vm,
+ &PropertyKey::from_utf8("numberOfInputs"),
+ Value::from_f64(f64::from(options.number_of_inputs)),
+ None,
+ None,
+ )
+ .expect("a new options object accepts a property");
+ options_object
+ .create_data_property(
+ vm,
+ &PropertyKey::from_utf8("numberOfOutputs"),
+ Value::from_f64(f64::from(options.number_of_outputs)),
+ None,
+ None,
+ )
+ .expect("a new options object accepts a property");
+ if let Some(output_channel_count) = &options.output_channel_count {
+ let array = Array::create(vm, worklet_realm, output_channel_count.len() as u64, None)
+ .expect("an output-channel array is created");
+ for (index, channel_count) in output_channel_count.iter().enumerate() {
+ array
+ .create_data_property(
+ vm,
+ &PropertyKey::from(index as u32),
+ Value::from_f64(f64::from(*channel_count)),
+ None,
+ None,
+ )
+ .expect("a new array accepts a property");
+ }
+ options_object
+ .create_data_property(
+ vm,
+ &PropertyKey::from_utf8("outputChannelCount"),
+ Value::from_object(array),
+ None,
+ None,
+ )
+ .expect("a new options object accepts a property");
+ }
+ if let Some(parameter_data) = &options.parameter_data {
+ let data = Object::create(vm, worklet_realm, Some(worklet_realm.intrinsics().object_prototype(vm)));
+ for (key, value) in parameter_data {
+ data.create_data_property(
+ vm,
+ &PropertyKey::from_utf16_string(key),
+ Value::from_f64(*value),
+ None,
+ None,
+ )
+ .expect("a new parameter-data object accepts a property");
+ }
+ options_object
+ .create_data_property(
+ vm,
+ &PropertyKey::from_utf8("parameterData"),
+ Value::from_object(data),
+ None,
+ None,
+ )
+ .expect("a new options object accepts a property");
+ }
+
+ // processorOptions is always present; when omitted by the caller, Web Audio specifies an empty object.
+ let processor_options = cloned_processor_options.unwrap_or_else(|| {
+ Object::create(vm, worklet_realm, Some(worklet_realm.intrinsics().object_prototype(vm)))
+ });
+ options_object
+ .create_data_property(
+ vm,
+ &PropertyKey::from_utf8("processorOptions"),
+ Value::from_object(processor_options),
+ None,
+ None,
+ )
+ .expect("a new options object accepts a property");
+
+ // Reserve space for later input layout changes without allocating on the render thread.
+ let input_channel_capacity = vec![BaseAudioContext::MAX_NUMBER_OF_CHANNELS; options.number_of_inputs as usize];
+ let output_channel_count_matches_input =
+ options.number_of_inputs == 1 && options.number_of_outputs == 1 && options.output_channel_count.is_none();
+ let mut output_channel_capacity = Vec::new();
+ for index in 0..options.number_of_outputs as usize {
+ if let Some(counts) = &options.output_channel_count {
+ output_channel_capacity.push(counts[index]);
+ } else {
+ output_channel_capacity.push(if output_channel_count_matches_input {
+ BaseAudioContext::MAX_NUMBER_OF_CHANNELS
+ } else {
+ 1
+ });
+ }
+ }
+ let mut param_is_a_rate = Vec::new();
+ for descriptor in &descriptors {
+ param_is_a_rate.push(descriptor.automation_rate == AutomationRate::ARate);
+ }
+ let sizing = libweb_rust::web_audio::rendering::audio_worklet_pipe::ring_sizing_for_device_latency(
+ 100,
+ context.sample_rate_value(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ );
+ let config = WorkletPipeConfig {
+ quantum_size: BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ input_count: options.number_of_inputs,
+ output_count: options.number_of_outputs,
+ input_channel_capacity: ak::Span::new(&input_channel_capacity),
+ output_channel_capacity: ak::Span::new(&output_channel_capacity),
+ output_channel_count_matches_input,
+ param_count: descriptors.len() as u32,
+ param_is_a_rate: ak::Span::new(&param_is_a_rate),
+ ring_capacity: sizing.ring_capacity,
+ prime_level: sizing.prime_level,
+ };
+ let mut native_pipe = std::ptr::null();
+ let service =
+ unsafe { web_audio_worklet_create_pipe(config, context.sample_rate_value(), &raw mut native_pipe) };
+ let native_pipe = native_pipe.cast::<AudioWorkletPipe>();
+ unsafe { Arc::increment_strong_count(native_pipe) };
+ let pipe = unsafe { Arc::from_raw(native_pipe) };
+ unsafe { pipe.prime_outputs_with_silence(sizing.prime_level) };
+ *node.pipe.borrow_mut() = Some(Arc::clone(&pipe));
+ *node.pipe_service.borrow_mut() = Some(SharedCppObject {
+ pointer: service.pointer,
+ retain: service.retain,
+ release: service.release,
+ });
+ unsafe { web_audio_worklet_set_pump(service.pointer, scope.as_ptr(), node.node.node_id()) };
+ let render_params: Vec<*const RenderAudioParam> = parameter_map
+ .values(vm)
+ .values()
+ .iter()
+ .map(|param| Arc::as_ptr(param.render_param()))
+ .collect();
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_audio_worklet(
+ node.node.node_id(),
+ options.number_of_inputs as usize,
+ options.number_of_outputs as usize,
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ ak::Span::new(&output_channel_capacity),
+ node.node.channel_count_value() as usize,
+ node.node.channel_count_mode(cx)?,
+ node.node.channel_interpretation(cx)?,
+ Arc::as_ptr(&pipe),
+ ak::Span::new(&render_params),
+ ))
+ });
+
+ // FIXME: Implement the spec's actively-processing keep-alive (drop this when the processor's
+ // process() return value has been false and inputs are silent). For now a live worklet
+ // node stays registered with the context until the context goes away.
+ context.add_playing_source(vm, AnyAudioNode::AudioWorkletNode(node));
+
+ // 8. Queue a control message to invoke the constructor of the corresponding AudioWorkletProcessor.
+ // NOTE: The worklet shares the window agent's event loop, so the control message becomes a queued
+ // global task on the worklet global; the node constructor returns before user code runs.
+ let task = PROCESSOR_CONSTRUCTION_TASK_CLASS.allocate(vm, |_| ProcessorConstructionTask {
+ node,
+ scope,
+ processor_port,
+ options_object,
+ });
+ queue_a_global_task(
+ vm,
+ worklet_realm.global_object(),
+ TaskSource::DOMManipulation,
+ task,
+ |vm, task| {
+ task.node
+ .invoke_processor_constructor(vm, &task.scope, task.processor_port, task.options_object);
+ },
+ );
+ Ok(node)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#instantiation-of-audioworkletprocessor
+ // "invoke processor constructor" — deferred to a queued task so the node constructor returns
+ // before user code runs (and pre-constructor port messages queue up for delivery afterwards).
+ fn invoke_processor_constructor(
+ &self,
+ vm: &Vm,
+ scope: &CppCell,
+ processor_port: Ref<MessagePort>,
+ options_object: Gc<Object>,
+ ) {
+ let worklet_realm: Gc<Realm> =
+ unsafe { Gc::from_non_null(NonNull::new(web_audio_worklet_scope_realm(scope.as_ptr()).cast()).unwrap()) };
+ with_temporary_execution_context_and_callbacks(worklet_realm, || {
+ let constructor: Gc<FunctionObject> = unsafe {
+ Gc::from_non_null(
+ NonNull::new(
+ web_audio_worklet_processor_constructor(scope.as_ptr(), self.name.raw_identity()).cast(),
+ )
+ .unwrap(),
+ )
+ };
+
+ // 1. Set the pending processor construction data: the processor-side port.
+ unsafe { web_audio_worklet_set_pending_port(scope.as_ptr(), cell_into_abi(processor_port)) };
+
+ // 2. Construct the processor: Construct(processorCtor, « optionsObject »).
+ let processor_or_error = construct(vm, constructor, &[Value::from_object(options_object)], None);
+
+ // 3. Empty the pending processor construction data slot (a constructor that never chained to
+ // super() leaves it populated).
+ unsafe { web_audio_worklet_clear_pending_data(scope.as_ptr()) };
+ let processor = match processor_or_error {
+ Ok(processor) => processor,
+ Err(error) => {
+ self.processor_errored.set(true);
+ self.pipe.borrow().as_ref().unwrap().set_state(WorkletPipeState::Failed);
+ self.fire_processor_error(error.value());
+ return;
+ }
+ };
+ self.processor.set(Some(processor));
+ let worklet = self.node.context_value().audio_worklet_cell(vm);
+ let mut names = Vec::<Utf16String>::new();
+ unsafe extern "C" fn append(context: *mut c_void, name: usize, _: f32, _: f32, _: f32, _: AutomationRate) {
+ unsafe { &mut *context.cast::<Vec<Utf16String>>() }
+ .push(unsafe { ak::Utf16FlyString::from_raw_borrowed(name) }.into());
+ }
+ unsafe {
+ web_audio_worklet_find_definition(
+ worklet.as_ptr(),
+ self.name.raw_identity(),
+ (&raw mut names).cast(),
+ append,
+ )
+ };
+ let raw_names: Vec<usize> = names.iter().map(Utf16String::raw_identity).collect();
+ unsafe {
+ web_audio_worklet_add_processor_slot(
+ scope.as_ptr(),
+ self.node.node_id(),
+ processor.as_ptr().cast(),
+ cell_into_abi(processor_port),
+ cell_into_abi(self.this()),
+ self.pipe_service.borrow().as_ref().unwrap().pointer,
+ ak::Span::new(&raw_names),
+ );
+ };
+ MessagePort::enable(processor_port, vm);
+ });
+ }
+
+ pub(crate) fn fire_processor_error(&self, error: Value) {
+ // https://webaudio.github.io/web-audio-api/#dom-audioworkletnode-onprocessorerror
+ // "...the processor will queue a task to fire an event named processorerror using ErrorEvent at the
+ // associated AudioWorkletNode."
+ unsafe {
+ web_audio_worklet_queue_processor_error(
+ cell_into_abi(self.this()),
+ self.node.event_target().as_ptr(),
+ self.node.context_value().global_event_target().as_ptr(),
+ error.to_raw(),
+ );
+ };
+ }
+
+ pub(crate) fn parameters(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParamMap>> {
+ Ok(self.parameter_map)
+ }
+
+ pub(crate) fn port(&self, _: &mut CallContext) -> WebIdlResult<Ref<MessagePort>> {
+ Ok(self.port)
+ }
+
+ pub(crate) fn number_of_inputs_value(&self) -> u32 {
+ self.number_of_inputs
+ }
+
+ pub(crate) fn number_of_outputs_value(&self) -> u32 {
+ self.number_of_outputs
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_audio_worklet_node_fire_error(cell: *mut c_void, error: u64) {
+ let node: Ref<AudioWorkletNode> = unsafe { cell_from_abi(cell) };
+ node.fire_processor_error(unsafe { Value::from_raw(error) });
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs
new file mode 100644
index 00000000000..626f7d9c0ae
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs
@@ -0,0 +1,987 @@
+/*
+ * Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#![allow(clippy::collapsible_if, reason = "preserve the C++ branch structure")]
+
+use std::cell::{Cell, RefCell};
+use std::ffi::c_void;
+use std::ops::Deref;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::DeferGc;
+use libjs_rust::api::{ArrayBuffer, EmbedderClass, EmbedderValue, detach_array_buffer};
+use libjs_rust::api::{
+ EmbedderCell, ErrorKind, ErrorType, Gc, GcRefCell, GcWeak, Object, Realm, ThrowCompletionOr, Trace, Value, Visitor,
+ Vm,
+};
+use libweb_rust::web_audio::control_message::ControlMessage;
+use libweb_rust::web_audio::control_message_queue::ControlMessageQueue;
+
+#[cfg(web_idl_bindings)]
+use super::analyser_node::{AnalyserNode, AnalyserOptions};
+use super::audio_buffer::AudioBuffer;
+#[cfg(web_idl_bindings)]
+use super::audio_buffer_source_node::{AudioBufferSourceNode, AudioBufferSourceOptions};
+use super::audio_context::AudioContext;
+use super::audio_destination_node::AudioDestinationNode;
+use super::audio_listener::AudioListener;
+use super::audio_node::AnyAudioNode;
+#[cfg(web_idl_bindings)]
+use super::biquad_filter_node::{BiquadFilterNode, BiquadFilterOptions};
+#[cfg(web_idl_bindings)]
+use super::channel_merger_node::{ChannelMergerNode, ChannelMergerOptions};
+#[cfg(web_idl_bindings)]
+use super::channel_splitter_node::{ChannelSplitterNode, ChannelSplitterOptions};
+#[cfg(web_idl_bindings)]
+use super::constant_source_node::{ConstantSourceNode, ConstantSourceOptions};
+#[cfg(web_idl_bindings)]
+use super::convolver_node::{ConvolverNode, ConvolverOptions};
+#[cfg(web_idl_bindings)]
+use super::delay_node::{DelayNode, DelayOptions};
+#[cfg(web_idl_bindings)]
+use super::dynamics_compressor_node::{DynamicsCompressorNode, DynamicsCompressorOptions};
+#[cfg(web_idl_bindings)]
+use super::gain_node::{GainNode, GainOptions};
+use super::iir_filter_node::{IIRFilterNode, IIRFilterOptions};
+use super::media_stream_audio_source_node::MediaStreamAudioSourceNode;
+use super::offline_audio_context::OfflineAudioContext;
+#[cfg(web_idl_bindings)]
+use super::oscillator_node::{OscillatorNode, OscillatorOptions};
+#[cfg(web_idl_bindings)]
+use super::panner_node::{PannerNode, PannerOptions};
+use super::periodic_wave::{PeriodicWave, PeriodicWaveConstraints, PeriodicWaveOptions};
+use super::script_processor_node::ScriptProcessorNode;
+#[cfg(web_idl_bindings)]
+use super::stereo_panner_node::{StereoPannerNode, StereoPannerOptions};
+#[cfg(web_idl_bindings)]
+use super::wave_shaper_node::{WaveShaperNode, WaveShaperOptions};
+use crate::bindings::callback::CallbackFunction;
+#[cfg(web_idl_bindings)]
+use crate::bindings::conversions::EmptyDictionary;
+use crate::bindings::conversions::{CppInterface, ToJs};
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::event_target::{CppEvent, CppEventTarget, GetTheParent};
+use crate::bindings::interface::with_temporary_execution_context_and_callbacks;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, Wrapped, cell_if_abi, cell_into_abi};
+use crate::bindings::promise::{WebIdlPromise, pending_steps, run_pending_steps};
+use crate::bindings::promise::{create_promise, exception_value, promise_realm, reject_promise, resolve_promise};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum AudioContextState {
+ Suspended,
+ Running,
+ Closed,
+}
+
+struct MediaElementTaskSource(NonNull<c_void>);
+
+impl Drop for MediaElementTaskSource {
+ fn drop(&mut self) {
+ unsafe { web_audio_context_destroy_task_source(self.0.as_ptr()) };
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#BaseAudioContext
+pub(crate) struct BaseAudioContext {
+ event_target: CppEventTarget,
+ pub(crate) destination: Cell<Option<Ref<AudioDestinationNode>>>,
+ pub(crate) pending_promises: GcRefCell<Vec<WebIdlPromise>>,
+ next_node_id: Cell<u64>,
+ sample_rate: Cell<f32>,
+ pub(crate) listener: Cell<Option<Ref<AudioListener>>>,
+ global_object: CppCell,
+ control_thread_state: Cell<AudioContextState>,
+ rendering_thread_state: Cell<AudioContextState>,
+ media_element_event_task_source: MediaElementTaskSource,
+ document_observer: GcRefCell<Option<CppCell>>,
+ audio_worklet: GcRefCell<Option<CppCell>>,
+ control_message_queue: Arc<ControlMessageQueue>,
+ playing_sources: GcRefCell<Vec<(u64, AnyAudioNode)>>,
+ script_processor_nodes: RefCell<Vec<GcWeak<EmbedderCell<Wrapped<ScriptProcessorNode>>>>>,
+ media_stream_sources: RefCell<Vec<GcWeak<EmbedderCell<Wrapped<MediaStreamAudioSourceNode>>>>>,
+ this: Cell<Option<AnyBaseAudioContext>>,
+}
+
+// SAFETY: This traces the context’s strong edges and the weak nodes it keeps alive while rendering.
+unsafe impl Trace for BaseAudioContext {
+ fn trace(&self, visitor: &mut Visitor) {
+ self.event_target.trace(visitor);
+ self.destination.trace(visitor);
+ self.pending_promises.trace(visitor);
+ self.listener.trace(visitor);
+ self.global_object.trace(visitor);
+ self.document_observer.trace(visitor);
+ self.audio_worklet.trace(visitor);
+ self.playing_sources.trace(visitor);
+ self.this.trace(visitor);
+ if self.control_thread_state.get() == AudioContextState::Closed {
+ return;
+ }
+
+ // INTEROP: Blink keeps a ScriptProcessorNode with audioprocess listeners alive until its context is cleared
+ // (ScriptProcessorNode::HasPendingActivity()), whether it is connected or not, so that a node script only
+ // reaches through its listener keeps producing audio.
+ for node in &*self.script_processor_nodes.borrow() {
+ if let Some(node) = node.get() {
+ if node.parent().event_target().has_event_listener("audioprocess") {
+ node.trace(visitor);
+ }
+ }
+ }
+
+ // Keep a source and the nodes it feeds alive while its track is live, even after script drops the source.
+ // https://webaudio.github.io/web-audio-api/#AudioNode-actively-processing
+ // NB: A muted or disabled track only pauses its source, so it stays alive as well.
+ for source in &*self.media_stream_sources.borrow() {
+ if let Some(source) = source.get() {
+ if source.has_live_input_track() {
+ source.trace(visitor);
+ }
+ }
+ }
+ }
+}
+
+impl Wrappable for BaseAudioContext {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.event_target.as_cpp_parent()
+ }
+}
+
+impl GetTheParent for BaseAudioContext {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+unsafe extern "C" {
+ fn web_audio_context_create_task_source() -> *mut c_void;
+ fn web_audio_context_destroy_task_source(source: *mut c_void);
+ fn web_audio_context_queue_task(
+ source: *mut c_void,
+ global: *mut c_void,
+ cell: *mut c_void,
+ invoke: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ );
+ fn web_audio_context_observe_document(global: *mut c_void, cell: *mut c_void) -> *mut c_void;
+ fn web_audio_context_global_realm(global: *mut c_void) -> *mut c_void;
+ fn web_audio_context_global_wrapper(global: *mut c_void) -> *mut c_void;
+ fn web_audio_context_document_is_fully_active(global: *mut c_void) -> bool;
+ fn web_audio_context_navigable_is_destroyed(global: *mut c_void) -> bool;
+ fn web_audio_context_get_worklet(cell: *mut c_void) -> *mut c_void;
+ fn web_audio_context_shutdown_worklet(worklet: *mut c_void);
+ fn web_audio_context_wrap_worklet(realm: *mut c_void, worklet: *mut c_void) -> *mut c_void;
+}
+
+impl BaseAudioContext {
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer-numberofchannels
+ // > An implementation MUST support at least 32 channels.
+ // Other browsers appear to only allow 32 channels - so let's limit ourselves to that too.
+ pub(crate) const MAX_NUMBER_OF_CHANNELS: u32 = 32;
+
+ // https://webaudio.github.io/web-audio-api/#sample-rates
+ // Implementations MUST support sample rates between 3000 Hz and 768000 Hz, inclusive. A NotSupportedError MUST
+ // be thrown if a sample rate outside this range is specified.
+ pub(crate) const MIN_SAMPLE_RATE: f32 = 3000.;
+ pub(crate) const MAX_SAMPLE_RATE: f32 = 768000.;
+
+ // https://webaudio.github.io/web-audio-api/#render-quantum-size
+ pub(crate) const RENDER_QUANTUM_SIZE: u32 = 128;
+
+ pub(crate) fn new(_defer_gc: &DeferGc<'_>, global_object: CppCell, sample_rate: f32) -> Self {
+ Self {
+ event_target: CppEventTarget::new(),
+ destination: Cell::new(None),
+ pending_promises: GcRefCell::new(Vec::new()),
+ next_node_id: Cell::new(0),
+ sample_rate: Cell::new(sample_rate),
+ listener: Cell::new(None),
+ global_object,
+ control_thread_state: Cell::new(AudioContextState::Suspended),
+ rendering_thread_state: Cell::new(AudioContextState::Suspended),
+ media_element_event_task_source: MediaElementTaskSource(
+ NonNull::new(unsafe { web_audio_context_create_task_source() }).unwrap(),
+ ),
+ document_observer: GcRefCell::new(None),
+ audio_worklet: GcRefCell::new(None),
+ control_message_queue: Arc::new(ControlMessageQueue::default()),
+ playing_sources: GcRefCell::new(Vec::new()),
+ script_processor_nodes: RefCell::new(Vec::new()),
+ media_stream_sources: RefCell::new(Vec::new()),
+ this: Cell::new(None),
+ }
+ }
+
+ pub(crate) fn initialize(&self, vm: &Vm, this: AnyBaseAudioContext) {
+ self.this.set(Some(this));
+ let observer = unsafe { web_audio_context_observe_document(self.global_object.as_ptr(), this.as_abi()) };
+ if !observer.is_null() {
+ *self.document_observer.borrow_mut(vm) = Some(unsafe { CppCell::from_raw(observer) });
+ }
+ }
+
+ pub(crate) fn this(&self) -> AnyBaseAudioContext {
+ self.this.get().expect("a context knows itself after allocation")
+ }
+
+ pub(crate) fn event_target(&self) -> &CppEventTarget {
+ &self.event_target
+ }
+
+ pub(crate) fn global_event_target(&self) -> &CppCell {
+ &self.global_object
+ }
+
+ pub(crate) fn realm(&self) -> Gc<Realm> {
+ unsafe {
+ Gc::from_non_null(NonNull::new(web_audio_context_global_realm(self.global_object.as_ptr()).cast()).unwrap())
+ }
+ }
+
+ pub(crate) fn global(&self) -> Gc<Object> {
+ unsafe {
+ Gc::from_non_null(
+ NonNull::new(web_audio_context_global_wrapper(self.global_object.as_ptr()).cast()).unwrap(),
+ )
+ }
+ }
+
+ pub(crate) fn document_is_fully_active(&self) -> bool {
+ unsafe { web_audio_context_document_is_fully_active(self.global_object.as_ptr()) }
+ }
+
+ pub(crate) fn navigable_is_destroyed(&self) -> bool {
+ unsafe { web_audio_context_navigable_is_destroyed(self.global_object.as_ptr()) }
+ }
+
+ pub(crate) fn sample_rate_value(&self) -> f32 {
+ self.sample_rate.get()
+ }
+
+ pub(crate) fn set_sample_rate(&self, sample_rate: f32) {
+ self.sample_rate.set(sample_rate);
+ }
+
+ // https://webaudio.github.io/web-audio-api/#--nyquist-frequency
+ pub(crate) fn nyquist_frequency(&self) -> f32 {
+ self.sample_rate.get() / 2.
+ }
+
+ pub(crate) fn state_value(&self) -> AudioContextState {
+ self.control_thread_state.get()
+ }
+
+ pub(crate) fn set_control_state(&self, state: AudioContextState) {
+ self.control_thread_state.set(state);
+ }
+
+ pub(crate) fn set_rendering_state(&self, state: AudioContextState) {
+ self.rendering_thread_state.set(state);
+ }
+
+ pub(crate) fn destination_value(&self) -> Ref<AudioDestinationNode> {
+ self.destination.get().expect("a context has a destination")
+ }
+
+ pub(crate) fn listener_value(&self) -> Ref<AudioListener> {
+ self.listener.get().expect("a context has a listener")
+ }
+
+ pub(crate) fn control_message_queue(&self) -> &Arc<ControlMessageQueue> {
+ &self.control_message_queue
+ }
+
+ pub(crate) fn next_node_id(&self) -> u64 {
+ let id = self.next_node_id.get() + 1;
+ self.next_node_id.set(id);
+ id
+ }
+
+ pub(crate) fn queue_control_message(&self, message: ControlMessage) {
+ self.control_message_queue.enqueue(message);
+
+ // FIXME: Should signal the rendering thread when implemented
+ }
+
+ pub(crate) fn add_playing_source(&self, vm: &Vm, node: AnyAudioNode) {
+ let mut sources = self.playing_sources.borrow_mut(vm);
+ if let Some(entry) = sources.iter_mut().find(|entry| entry.0 == node.node_id()) {
+ entry.1 = node;
+ } else {
+ sources.push((node.node_id(), node));
+ }
+ }
+
+ pub(crate) fn add_script_processor_node(&self, vm: &Vm, node: Ref<ScriptProcessorNode>) {
+ let mut nodes = self.script_processor_nodes.borrow_mut();
+ nodes.retain(|node| node.get().is_some());
+ if !nodes.iter().any(|entry| entry.get() == Some(node)) {
+ nodes.push(GcWeak::new(vm.heap(), node));
+ }
+ }
+
+ pub(crate) fn add_media_stream_source(&self, vm: &Vm, source: Ref<MediaStreamAudioSourceNode>) {
+ let mut sources = self.media_stream_sources.borrow_mut();
+ sources.retain(|source| source.get().is_some());
+ if !sources.iter().any(|entry| entry.get() == Some(source)) {
+ sources.push(GcWeak::new(vm.heap(), source));
+ }
+ }
+
+ pub(crate) fn handle_ended_sources(&self, vm: &Vm, ended_nodes: &[u64]) {
+ for node_id in ended_nodes {
+ let node = {
+ let mut sources = self.playing_sources.borrow_mut(vm);
+ sources
+ .iter()
+ .position(|entry| entry.0 == *node_id)
+ .map(|index| sources.remove(index).1)
+ };
+ let Some(node) = node else {
+ continue;
+ };
+ self.queue_a_media_element_task(vm, node, |_, node| {
+ node.event_target().dispatch_event(&CppEvent::create(
+ node.context_value().realm(),
+ "ended",
+ false,
+ false,
+ false,
+ ));
+ });
+ }
+ }
+
+ pub(crate) fn queue_a_media_element_task<C: Trace + Copy + 'static>(
+ &self,
+ vm: &Vm,
+ captures: C,
+ steps: fn(&Vm, C),
+ ) {
+ // Rendering completion callbacks run from the audio thread, outside any
+ // JavaScript execution context. Resolve the task target from this context's
+ // associated global rather than consulting the thread-local current ESO.
+ let cell = pending_steps(vm, captures, steps);
+ unsafe {
+ web_audio_context_queue_task(
+ self.media_element_event_task_source.0.as_ptr(),
+ self.global_object.as_ptr(),
+ cell,
+ run_pending_steps,
+ );
+ };
+ }
+
+ pub(crate) fn dispatch_statechange(&self) {
+ self.event_target
+ .dispatch_event(&CppEvent::create(self.realm(), "statechange", false, false, false));
+ }
+
+ pub(crate) fn audio_worklet_cell(&self, vm: &Vm) -> CppCell {
+ if self.audio_worklet.borrow().is_none() {
+ let worklet = unsafe { CppCell::from_raw(web_audio_context_get_worklet(self.this().as_abi())) };
+ *self.audio_worklet.borrow_mut(vm) = Some(worklet);
+ }
+ self.audio_worklet.borrow().as_ref().unwrap().clone()
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-audioworklet
+ pub(crate) fn audio_worklet(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ let worklet = self.audio_worklet_cell(cx.vm());
+ let wrapper = unsafe { web_audio_context_wrap_worklet(cx.realm().as_ptr().cast(), worklet.as_ptr()) };
+ Ok(unsafe { CppInterface::from_wrapper(Gc::<Object>::from_non_null(NonNull::new(wrapper.cast()).unwrap())) })
+ }
+
+ pub(crate) fn shutdown_audio_worklet(&self) {
+ if let Some(worklet) = &*self.audio_worklet.borrow() {
+ unsafe { web_audio_context_shutdown_worklet(worklet.as_ptr()) };
+ }
+ }
+
+ pub(crate) fn destination(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioDestinationNode>> {
+ Ok(self.destination_value())
+ }
+
+ pub(crate) fn sample_rate(&self, _: &mut CallContext) -> WebIdlResult<f32> {
+ Ok(self.sample_rate_value())
+ }
+
+ pub(crate) fn listener(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioListener>> {
+ Ok(self.listener_value())
+ }
+
+ pub(crate) fn state(&self, _: &mut CallContext) -> WebIdlResult<AudioContextState> {
+ Ok(self.state_value())
+ }
+
+ pub(crate) fn render_quantum_size(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(Self::RENDER_QUANTUM_SIZE)
+ }
+
+ pub(crate) fn current_time(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.current_time_value())
+ }
+
+ pub(crate) fn current_time_value(&self) -> f64 {
+ match self.this() {
+ AnyBaseAudioContext::AudioContext(context) => context.current_time_value(),
+ AnyBaseAudioContext::OfflineAudioContext(context) => context.current_time_value(),
+ AnyBaseAudioContext::BaseAudioContext(_) => 0.,
+ }
+ }
+
+ pub(crate) fn verify_sample_rate(sample_rate: f32) -> WebIdlResult<()> {
+ if sample_rate < Self::MIN_SAMPLE_RATE || sample_rate > Self::MAX_SAMPLE_RATE {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"Sample rate is outside of allowed range"),
+ ));
+ }
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer
+ pub(crate) fn verify_audio_options_inside_nominal_range(
+ number_of_channels: u32,
+ length: u32,
+ sample_rate: f32,
+ ) -> WebIdlResult<()> {
+ // A NotSupportedError exception MUST be thrown if any of the arguments is negative, zero, or outside its nominal range.
+ if number_of_channels == 0 {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"Number of channels must not be '0'"),
+ ));
+ }
+ if number_of_channels > Self::MAX_NUMBER_OF_CHANNELS {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"Number of channels is greater than allowed range"),
+ ));
+ }
+ if length == 0 {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"Length of buffer must be at least 1"),
+ ));
+ }
+ Self::verify_sample_rate(sample_rate)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer
+ pub(crate) fn create_buffer(
+ &self,
+ cx: &mut CallContext,
+ number_of_channels: u32,
+ length: u32,
+ sample_rate: f32,
+ ) -> WebIdlResult<Ref<AudioBuffer>> {
+ // Creates an AudioBuffer of the given size. The audio data in the buffer will be zero-initialized (silent).
+ // A NotSupportedError exception MUST be thrown if any of the arguments is negative, zero, or outside its nominal range.
+ Self::verify_audio_options_inside_nominal_range(number_of_channels, length, sample_rate)?;
+ if length as usize > i32::MAX as usize / size_of::<f32>() {
+ return Err(cx
+ .vm()
+ .throw_completion::<()>(ErrorKind::RangeError, ErrorType::InvalidLength, &[&"typed array"])
+ .unwrap_err()
+ .into());
+ }
+ AudioBuffer::create(cx.vm(), number_of_channels, length, sample_rate).map_err(|_| {
+ cx.vm()
+ .throw_completion::<()>(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])
+ .unwrap_err()
+ .into()
+ })
+ }
+}
+
+#[cfg(web_idl_bindings)]
+impl BaseAudioContext {
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createanalyser
+ pub(crate) fn create_analyser(&self, cx: &mut CallContext) -> WebIdlResult<Ref<AnalyserNode>> {
+ AnalyserNode::create(cx, self.this(), &AnalyserOptions::empty())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbiquadfilter
+ pub(crate) fn create_biquad_filter(&self, cx: &mut CallContext) -> WebIdlResult<Ref<BiquadFilterNode>> {
+ // Factory method for a BiquadFilterNode representing a second order filter which can be configured as one of several common filter types.
+ BiquadFilterNode::create(cx, self.this(), &BiquadFilterOptions::empty())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffersource
+ pub(crate) fn create_buffer_source(&self, cx: &mut CallContext) -> WebIdlResult<Ref<AudioBufferSourceNode>> {
+ // Factory method for a AudioBufferSourceNode.
+ AudioBufferSourceNode::create(cx, self.this(), &AudioBufferSourceOptions::empty())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createconstantsource
+ pub(crate) fn create_constant_source(&self, cx: &mut CallContext) -> WebIdlResult<Ref<ConstantSourceNode>> {
+ ConstantSourceNode::create(cx, self.this(), &ConstantSourceOptions::empty())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createconvolver
+ pub(crate) fn create_convolver(&self, cx: &mut CallContext) -> WebIdlResult<Ref<ConvolverNode>> {
+ ConvolverNode::create(cx, self.this(), &ConvolverOptions::empty())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createoscillator
+ pub(crate) fn create_oscillator(&self, cx: &mut CallContext) -> WebIdlResult<Ref<OscillatorNode>> {
+ // Factory method for an OscillatorNode.
+ OscillatorNode::create(cx, self.this(), &OscillatorOptions::empty())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createdynamicscompressor
+ pub(crate) fn create_dynamics_compressor(&self, cx: &mut CallContext) -> WebIdlResult<Ref<DynamicsCompressorNode>> {
+ // Factory method for a DynamicsCompressorNode.
+ DynamicsCompressorNode::create(cx, self.this(), &DynamicsCompressorOptions::empty())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-creategain
+ pub(crate) fn create_gain(&self, cx: &mut CallContext) -> WebIdlResult<Ref<GainNode>> {
+ // Factory method for GainNode.
+ GainNode::create(cx, self.this(), &GainOptions::empty())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createpanner
+ pub(crate) fn create_panner(&self, cx: &mut CallContext) -> WebIdlResult<Ref<PannerNode>> {
+ // Factory method for a PannerNode.
+ PannerNode::create(cx, self.this(), &PannerOptions::empty())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createstereopanner
+ pub(crate) fn create_stereo_panner(&self, cx: &mut CallContext) -> WebIdlResult<Ref<StereoPannerNode>> {
+ // Factory method for a StereoPannerNode.
+ StereoPannerNode::create(cx, self.this(), &StereoPannerOptions::empty())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createwaveshaper
+ pub(crate) fn create_wave_shaper(&self, cx: &mut CallContext) -> WebIdlResult<Ref<WaveShaperNode>> {
+ // Factory method for a WaveShaperNode representing a non-linear distortion.
+ WaveShaperNode::create(cx, self.this(), &WaveShaperOptions::empty())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createchannelmerger
+ pub(crate) fn create_channel_merger(
+ &self,
+ cx: &mut CallContext,
+ number_of_inputs: u32,
+ ) -> WebIdlResult<Ref<ChannelMergerNode>> {
+ let mut options = ChannelMergerOptions::empty();
+ options.number_of_inputs = number_of_inputs;
+ ChannelMergerNode::validate_options(&options)?;
+ ChannelMergerNode::create(cx, self.this(), &options)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createchannelsplitter
+ pub(crate) fn create_channel_splitter(
+ &self,
+ cx: &mut CallContext,
+ number_of_outputs: u32,
+ ) -> WebIdlResult<Ref<ChannelSplitterNode>> {
+ let mut options = ChannelSplitterOptions::empty();
+ options.number_of_outputs = number_of_outputs;
+ ChannelSplitterNode::validate_options(&options)?;
+ ChannelSplitterNode::create(cx, self.this(), &options)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createdelay
+ pub(crate) fn create_delay(&self, cx: &mut CallContext, max_delay_time: f64) -> WebIdlResult<Ref<DelayNode>> {
+ let mut options = DelayOptions::empty();
+ options.max_delay_time = max_delay_time;
+ DelayNode::validate_options(&options)?;
+ DelayNode::create(cx, self.this(), &options)
+ }
+}
+
+impl BaseAudioContext {
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createiirfilter
+ pub(crate) fn create_iir_filter(
+ &self,
+ cx: &mut CallContext,
+ feedforward: Vec<f64>,
+ feedback: Vec<f64>,
+ ) -> WebIdlResult<Ref<IIRFilterNode>> {
+ // Factory method for an IIRFilterNode representing a general IIR Filter.
+ let options = IIRFilterOptions {
+ parent: super::audio_node::AudioNodeOptions::default(),
+ feedforward,
+ feedback,
+ };
+ IIRFilterNode::create(cx, self.this(), &options)
+ }
+
+ pub(crate) fn create_periodic_wave(
+ &self,
+ cx: &mut CallContext,
+ real: Vec<f32>,
+ imag: Vec<f32>,
+ constraints: PeriodicWaveConstraints,
+ ) -> WebIdlResult<Ref<PeriodicWave>> {
+ // 1. If real and imag are not of the same length, an IndexSizeError MUST be thrown.
+ // NB: The PeriodicWave constructor checks the lengths.
+ // 2. Let o be a new object of type PeriodicWaveOptions.
+ // 3. Respectively set the real and imag parameters passed to this factory method to the attributes of the same name on o.
+ // 4. Set the disableNormalization attribute on o to the value of the disableNormalization attribute of the constraints attribute passed to the factory method.
+ let options = PeriodicWaveOptions {
+ parent: constraints,
+ real: Some(real),
+ imag: Some(imag),
+ };
+
+ // 5. Construct a new PeriodicWave p, passing the BaseAudioContext this factory method has been called on as a first argument, and o.
+ // 6. Return p.
+ PeriodicWave::create(cx, options)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createscriptprocessor
+ pub(crate) fn create_script_processor(
+ &self,
+ cx: &mut CallContext,
+ mut buffer_size: u32,
+ number_of_input_channels: u32,
+ number_of_output_channels: u32,
+ ) -> WebIdlResult<Ref<ScriptProcessorNode>> {
+ // The bufferSize parameter determines the buffer size in units of sample-frames. If it’s not passed in, or if the
+ // value is 0, then the implementation will choose the best buffer size for the given environment, which will be
+ // constant power of 2 throughout the lifetime of the node.
+ if buffer_size == 0 {
+ buffer_size = ScriptProcessorNode::DEFAULT_BUFFER_SIZE as u32;
+ }
+ ScriptProcessorNode::validate_options(buffer_size as i32, number_of_input_channels, number_of_output_channels)?;
+ ScriptProcessorNode::create(
+ cx,
+ self.this(),
+ buffer_size as i32,
+ number_of_input_channels,
+ number_of_output_channels,
+ )
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Trace)]
+#[gc(crate = libjs_rust)]
+#[allow(clippy::enum_variant_names, reason = "the variants have the interfaces’ names")]
+pub(crate) enum AnyBaseAudioContext {
+ BaseAudioContext(Ref<BaseAudioContext>),
+ AudioContext(Ref<AudioContext>),
+ OfflineAudioContext(Ref<OfflineAudioContext>),
+}
+
+impl Deref for AnyBaseAudioContext {
+ type Target = BaseAudioContext;
+
+ fn deref(&self) -> &BaseAudioContext {
+ match self {
+ Self::BaseAudioContext(context) => context,
+ Self::AudioContext(context) => context.parent(),
+ Self::OfflineAudioContext(context) => context.parent(),
+ }
+ }
+}
+
+impl ToJs for AnyBaseAudioContext {
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {
+ match self {
+ Self::BaseAudioContext(context) => context.to_js(cx),
+ Self::AudioContext(context) => context.to_js(cx),
+ Self::OfflineAudioContext(context) => context.to_js(cx),
+ }
+ }
+}
+
+impl AnyBaseAudioContext {
+ pub(crate) fn as_abi(self) -> *mut c_void {
+ match self {
+ Self::BaseAudioContext(context) => cell_into_abi(context),
+ Self::AudioContext(context) => cell_into_abi(context),
+ Self::OfflineAudioContext(context) => cell_into_abi(context),
+ }
+ }
+
+ pub(crate) unsafe fn from_abi(cell: *mut c_void) -> Self {
+ if let Some(context) = unsafe { cell_if_abi::<BaseAudioContext>(cell) } {
+ return Self::BaseAudioContext(context);
+ }
+ if let Some(context) = unsafe { cell_if_abi::<AudioContext>(cell) } {
+ return Self::AudioContext(context);
+ }
+ if let Some(context) = unsafe { cell_if_abi::<OfflineAudioContext>(cell) } {
+ return Self::OfflineAudioContext(context);
+ }
+ unreachable!("C++ holds a context cell")
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_audio_context_sample_rate(cell: *mut c_void) -> f32 {
+ unsafe { AnyBaseAudioContext::from_abi(cell) }.sample_rate_value()
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_audio_context_global(cell: *mut c_void) -> *mut c_void {
+ unsafe { AnyBaseAudioContext::from_abi(cell) }.global_object.as_ptr()
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_audio_context_global_wrapper(cell: *mut c_void) -> *mut c_void {
+ unsafe { AnyBaseAudioContext::from_abi(cell) }.global().as_ptr().cast()
+}
+
+// Called when the associated document is destroyed or otherwise stops being fully active, so rendering resources
+// can be released.
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_audio_context_document_inactive(cell: *mut c_void) {
+ match unsafe { AnyBaseAudioContext::from_abi(cell) } {
+ AnyBaseAudioContext::AudioContext(context) => context.document_became_inactive(),
+ AnyBaseAudioContext::OfflineAudioContext(context) => context.document_became_inactive(),
+ AnyBaseAudioContext::BaseAudioContext(_) => {}
+ }
+}
+
+struct DecodedAudioData(NonNull<c_void>);
+
+impl Drop for DecodedAudioData {
+ fn drop(&mut self) {
+ unsafe { web_audio_context_decoded_destroy(self.0.as_ptr()) };
+ }
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct DecodingOperation {
+ context: AnyBaseAudioContext,
+ promise: WebIdlPromise,
+ success_callback: Option<CallbackFunction>,
+ error_callback: Option<CallbackFunction>,
+ #[gc(untraced)]
+ decoded: RefCell<Option<DecodedAudioData>>,
+}
+
+static DECODING_OPERATION_CLASS: EmbedderClass<DecodingOperation> = EmbedderClass::new("WebAudioDecodingOperation");
+
+impl EmbedderValue for DecodingOperation {
+ const CLASS: &'static EmbedderClass<Self> = &DECODING_OPERATION_CLASS;
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct DetachedAudioDataError {
+ realm: Gc<Realm>,
+ callback: CallbackFunction,
+ error: Value,
+}
+
+static DETACHED_AUDIO_DATA_ERROR_CLASS: EmbedderClass<DetachedAudioDataError> =
+ EmbedderClass::new("DetachedAudioDataError");
+impl EmbedderValue for DetachedAudioDataError {
+ const CLASS: &'static EmbedderClass<Self> = &DETACHED_AUDIO_DATA_ERROR_CLASS;
+}
+
+unsafe extern "C" {
+ fn web_audio_context_decode(data: ak::Span<'_, u8>, sample_rate: u32, operation: *mut c_void);
+ fn web_audio_context_decoded_destroy(decoded: *mut c_void);
+ fn web_audio_context_decoded_metadata(
+ decoded: *mut c_void,
+ channels: *mut u32,
+ frames: *mut u64,
+ sample_rate: *mut u32,
+ );
+ fn web_audio_context_decoded_channel(decoded: *mut c_void, channel: u32, samples: *mut ak::Span<'_, f32>);
+ fn web_audio_context_report_exception(realm: *mut c_void, error: u64);
+}
+
+impl BaseAudioContext {
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-decodeaudiodata
+ pub(crate) fn decode_audio_data(
+ &self,
+ cx: &mut CallContext,
+ audio_data: Gc<ArrayBuffer>,
+ success_callback: Option<Option<CallbackFunction>>,
+ error_callback: Option<Option<CallbackFunction>>,
+ ) -> WebIdlResult<WebIdlPromise> {
+ let vm = cx.vm();
+ let promise = create_promise(vm, self.realm());
+ if audio_data.is_detached() {
+ let error = exception_value(
+ vm,
+ promise_realm(promise),
+ Exception::Dom("DataCloneError", Utf16String::from_ascii(b"Audio data is detached.")),
+ );
+ reject_promise(vm, promise, error);
+ if let Some(callback) = error_callback.flatten() {
+ let state = DETACHED_AUDIO_DATA_ERROR_CLASS.allocate(vm, |_| DetachedAudioDataError {
+ realm: cx.realm(),
+ callback,
+ error,
+ });
+ self.queue_a_media_element_task(vm, state, |_, state| {
+ if let Err(error) = state.callback.invoke(None, &[state.error]) {
+ unsafe {
+ web_audio_context_report_exception(state.realm.as_ptr().cast(), error.value().to_raw());
+ };
+ }
+ });
+ }
+ return Ok(promise);
+ }
+ let mut bytes = Vec::new();
+ bytes.try_reserve_exact(audio_data.byte_length()).map_err(|_| {
+ Exception::from(
+ vm.throw_completion::<()>(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])
+ .unwrap_err(),
+ )
+ })?;
+ bytes.resize(audio_data.byte_length(), 0);
+ audio_data.copy_to(0, &mut bytes);
+ detach_array_buffer(vm, audio_data, None)?;
+
+ // FIXME: When decodeAudioData is called, the following steps MUST be performed on the control thread:
+ // 1. If this's relevant global object's associated Document is not fully active then return a
+ // promise rejected with "InvalidStateError" DOMException.
+ if !self.document_is_fully_active() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"The document is not fully active."),
+ ));
+ }
+
+ // 3. Append promise to [[pending promises]] and queue a decoding operation.
+ self.pending_promises.borrow_mut(vm).push(promise);
+ let operation = DECODING_OPERATION_CLASS.allocate(vm, |_| DecodingOperation {
+ context: self.this(),
+ promise,
+ success_callback: success_callback.flatten(),
+ error_callback: error_callback.flatten(),
+ decoded: RefCell::new(None),
+ });
+ self.queue_a_decoding_operation(vm, operation, &bytes);
+ Ok(promise)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-decodeaudiodata
+ fn queue_a_decoding_operation(&self, vm: &Vm, operation: Gc<EmbedderCell<DecodingOperation>>, audio_data: &[u8]) {
+ // NB: The decoding thread is in the media server, which answers on this thread. Promise settlement and callbacks
+ // are posted to the media element task source below.
+ if audio_data.is_empty() {
+ queue_decode_error(vm, operation);
+ return;
+ }
+
+ // The answer arrives outside any task, so the context and callbacks are rooted until it does.
+ unsafe {
+ web_audio_context_decode(
+ ak::Span::new(audio_data),
+ self.sample_rate_value() as u32,
+ operation.as_ptr().cast(),
+ );
+ };
+ }
+}
+
+fn queue_decode_error(vm: &Vm, operation: Gc<EmbedderCell<DecodingOperation>>) {
+ operation
+ .context
+ .queue_a_media_element_task(vm, operation, |vm, operation| {
+ let realm = promise_realm(operation.promise);
+ with_temporary_execution_context_and_callbacks(realm, || {
+ let error = exception_value(
+ vm,
+ realm,
+ Exception::Dom("EncodingError", Utf16String::from_ascii(b"Unable to decode.")),
+ );
+ reject_promise(vm, operation.promise, error);
+ {
+ let mut pending = operation.context.pending_promises.borrow_mut(vm);
+ if let Some(index) = pending.iter().position(|promise| *promise == operation.promise) {
+ pending.remove(index);
+ }
+ }
+ if let Some(callback) = &operation.error_callback {
+ if let Err(error) = callback.invoke(None, &[error]) {
+ unsafe { web_audio_context_report_exception(realm.as_ptr().cast(), error.value().to_raw()) };
+ }
+ }
+ });
+ });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_audio_context_decoded(vm: &Vm, operation: *mut c_void, decoded: *mut c_void) {
+ let operation: Gc<EmbedderCell<DecodingOperation>> =
+ unsafe { Gc::from_non_null(NonNull::new(operation.cast()).unwrap()) };
+ let Some(decoded) = NonNull::new(decoded) else {
+ queue_decode_error(vm, operation);
+ return;
+ };
+ let decoded = DecodedAudioData(decoded);
+ let mut channel_count = 0;
+ let mut frame_count = 0;
+ let mut sample_rate = 0;
+ unsafe {
+ web_audio_context_decoded_metadata(
+ decoded.0.as_ptr(),
+ &raw mut channel_count,
+ &raw mut frame_count,
+ &raw mut sample_rate,
+ );
+ };
+ if frame_count > u64::from(u32::MAX) {
+ queue_decode_error(vm, operation);
+ return;
+ }
+ *operation.decoded.borrow_mut() = Some(decoded);
+ operation.context.queue_a_media_element_task(
+ vm,
+ (operation, channel_count, frame_count, sample_rate),
+ |vm, (operation, channel_count, frame_count, sample_rate)| {
+ let buffer = AudioBuffer::create(vm, channel_count, frame_count as u32, sample_rate as f32);
+ let Ok(buffer) = buffer else {
+ queue_decode_error(vm, operation);
+ return;
+ };
+ let decoded = operation.decoded.borrow_mut().take().unwrap();
+ for channel in 0..channel_count {
+ let (channel_data, length) = buffer
+ .channel_data(channel)
+ .unwrap_or_else(|_| panic!("the decoded channel exists"));
+ let mut samples = ak::Span::default();
+ unsafe { web_audio_context_decoded_channel(decoded.0.as_ptr(), channel, &raw mut samples) };
+ let samples = samples.as_slice();
+ let byte_length = size_of_val(samples);
+ assert!(byte_length <= length);
+
+ // SAFETY: The new buffer's channel has no views yet.
+ let destination = unsafe { ak::slice_from_raw_parts_mut(channel_data, length) };
+ let source = unsafe { ak::slice_from_raw_parts(samples.as_ptr().cast::<u8>(), byte_length) };
+ destination[..byte_length].copy_from_slice(source);
+ }
+ let realm = promise_realm(operation.promise);
+ with_temporary_execution_context_and_callbacks(realm, || {
+ let value = buffer
+ .to_js(&CallContext::new(vm, realm))
+ .expect("an AudioBuffer wraps");
+ resolve_promise(vm, operation.promise, value);
+ {
+ let mut pending = operation.context.pending_promises.borrow_mut(vm);
+ if let Some(index) = pending.iter().position(|promise| *promise == operation.promise) {
+ pending.remove(index);
+ }
+ }
+ if let Some(callback) = &operation.success_callback {
+ if let Err(error) = callback.invoke(None, &[value]) {
+ unsafe { web_audio_context_report_exception(realm.as_ptr().cast(), error.value().to_raw()) };
+ }
+ }
+ });
+ },
+ );
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/biquad_filter_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/biquad_filter_node.rs
new file mode 100644
index 00000000000..3f27ab4909a
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/biquad_filter_node.rs
@@ -0,0 +1,280 @@
+/*
+ * Copyright (c) 2024, Bar Yemini <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::Cell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::TypedArrayBase;
+use libjs_rust::api::{Gc, Trace};
+use libweb_rust::web_audio::control_message::ControlMessage;
+use libweb_rust::web_audio::rendering::biquad_coefficients::{biquad_frequency_response, compute_biquad_coefficients};
+use libweb_rust::web_audio::rendering::node_message::{NodeMessage, SetBiquadFilterType};
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_biquad_filter;
+
+use super::audio_array::{copy_float32_array, float32_array_length, overwrite_float32_array};
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::audio_param::{AudioParam, AutomationRate, FixedAutomationRate};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+pub(crate) use libweb_rust::web_audio::rendering::biquad_coefficients::BiquadFilterType;
+
+// https://webaudio.github.io/web-audio-api/#BiquadFilterNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct BiquadFilterNode {
+ node: AudioNode,
+ #[gc(untraced)]
+ r#type: Cell<BiquadFilterType>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-frequency
+ frequency: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-detune
+ detune: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-q
+ q: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-gain
+ gain: Ref<AudioParam>,
+}
+
+impl Inherits<AudioNode> for BiquadFilterNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for BiquadFilterNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for BiquadFilterNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct BiquadFilterOptions {
+ pub parent: AudioNodeOptions,
+ pub r#type: BiquadFilterType,
+ pub frequency: f32,
+ pub detune: f32,
+ pub q: f32,
+ pub gain: f32,
+}
+
+impl BiquadFilterNode {
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &BiquadFilterOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // When the constructor is called with a BaseAudioContext c and an option object option, the user agent
+ // MUST initialize the AudioNode this, with context and options as arguments.
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ r#type: Cell::new(options.r#type),
+ frequency: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.frequency,
+ 0.,
+ context.nyquist_frequency(),
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ detune: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.detune,
+ -1200. * ak::math::log2(f32::MAX),
+ 1200. * ak::math::log2(f32::MAX),
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ q: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.q,
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ gain: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.gain,
+ f32::MIN,
+ 40. * ak::math::log10(f32::MAX),
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ });
+ node.node.set_this(AnyAudioNode::BiquadFilterNode(node));
+ node.node.event_target().set_owner(node);
+ node.frequency.set_owner(AnyAudioNode::BiquadFilterNode(node));
+ node.detune.set_owner(AnyAudioNode::BiquadFilterNode(node));
+ node.q.set_owner(AnyAudioNode::BiquadFilterNode(node));
+ node.gain.set_owner(AnyAudioNode::BiquadFilterNode(node));
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#BiquadFilterNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::Max,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to yes
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_biquad_filter(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ Arc::as_ptr(node.frequency.render_param()),
+ Arc::as_ptr(node.detune.render_param()),
+ Arc::as_ptr(node.q.render_param()),
+ Arc::as_ptr(node.gain.render_param()),
+ ))
+ });
+ if options.r#type != BiquadFilterType::Lowpass {
+ context.queue_control_message(ControlMessage::NodeMessage(NodeMessage::SetBiquadFilterType(
+ SetBiquadFilterType {
+ node_id: node.node.node_id(),
+ r#type: options.r#type,
+ },
+ )));
+ }
+ Ok(node)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-biquadfilternode
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: BiquadFilterOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, &options)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-type
+ pub(crate) fn set_type(&self, _: &mut CallContext, r#type: BiquadFilterType) -> WebIdlResult<()> {
+ self.r#type.set(r#type);
+ self.node
+ .context_value()
+ .queue_control_message(ControlMessage::NodeMessage(NodeMessage::SetBiquadFilterType(
+ SetBiquadFilterType {
+ node_id: self.node.node_id(),
+ r#type,
+ },
+ )));
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-type
+ pub(crate) fn r#type(&self, _: &mut CallContext) -> WebIdlResult<BiquadFilterType> {
+ Ok(self.r#type.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-frequency
+ pub(crate) fn frequency(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.frequency)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-detune
+ pub(crate) fn detune(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.detune)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-q
+ pub(crate) fn q(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.q)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-gain
+ pub(crate) fn gain(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.gain)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-getfrequencyresponse
+ pub(crate) fn get_frequency_response(
+ &self,
+ cx: &mut CallContext,
+ frequency_hz: Gc<TypedArrayBase>,
+ mag_response: Gc<TypedArrayBase>,
+ phase_response: Gc<TypedArrayBase>,
+ ) -> WebIdlResult<()> {
+ let length = float32_array_length(&frequency_hz);
+
+ // If these arrays do not have the same length, an InvalidAccessError MUST be thrown.
+ if float32_array_length(&mag_response) != length || float32_array_length(&phase_response) != length {
+ return Err(Exception::Thrown(
+ Exception::Dom(
+ "InvalidAccessError",
+ Utf16String::from_ascii(b"Arrays must have the same length"),
+ )
+ .throw(&CallContext::new(cx.vm(), self.node.context_value().realm())),
+ ));
+ }
+ let frequencies = copy_float32_array(&frequency_hz);
+ let mut magnitudes = vec![0.; length];
+ let mut phases = vec![0.; length];
+
+ // The filter response is evaluated with the current parameter values at the context's current time.
+ let current_time = self.node.context_value().current_time_value();
+ let nyquist_frequency = self.node.context_value().nyquist_frequency();
+ let frequency = self.frequency.intrinsic_value_at_time(current_time);
+ let detune = self.detune.intrinsic_value_at_time(current_time);
+ let computed_frequency = f64::from(frequency) * ak::math::exp2(f64::from(detune) / 1200.);
+ let normalized_frequency = computed_frequency / f64::from(nyquist_frequency);
+ let normalized_frequency = normalized_frequency.clamp(0., 1.);
+ let coefficients = compute_biquad_coefficients(
+ self.r#type.get(),
+ normalized_frequency,
+ f64::from(self.q.intrinsic_value_at_time(current_time)),
+ f64::from(self.gain.intrinsic_value_at_time(current_time)),
+ );
+ for index in 0..length {
+ let response_frequency = frequencies[index];
+
+ // Frequencies outside the nominal range produce NaN in both output arrays.
+ if response_frequency.is_nan() || response_frequency < 0. || response_frequency > nyquist_frequency {
+ magnitudes[index] = f32::NAN;
+ phases[index] = f32::NAN;
+ continue;
+ }
+ (magnitudes[index], phases[index]) =
+ biquad_frequency_response(&coefficients, f64::from(response_frequency / nyquist_frequency));
+ }
+ overwrite_float32_array(&mag_response, &magnitudes);
+ overwrite_float32_array(&phase_response, &phases);
+ Ok(())
+ }
+}
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
new file mode 100644
index 00000000000..6cbffff289a
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/channel_merger_node.rs
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_channel_merger;
+
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#ChannelMergerNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ChannelMergerNode {
+ node: AudioNode,
+ number_of_inputs: u32,
+}
+
+impl Inherits<AudioNode> for ChannelMergerNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for ChannelMergerNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for ChannelMergerNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct ChannelMergerOptions {
+ pub parent: AudioNodeOptions,
+ pub number_of_inputs: u32,
+}
+
+impl ChannelMergerNode {
+ pub(crate) fn validate_options(options: &ChannelMergerOptions) -> WebIdlResult<()> {
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createchannelmerger
+ // An IndexSizeError exception MUST be thrown if numberOfInputs is less than 1 or is greater
+ // than the number of supported channels.
+ if options.number_of_inputs < 1 || options.number_of_inputs > BaseAudioContext::MAX_NUMBER_OF_CHANNELS {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"Invalid number of inputs"),
+ ));
+ }
+ Ok(())
+ }
+
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: ChannelMergerOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::validate_options(&options)?;
+ Self::create(cx, context, &options)
+ }
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &ChannelMergerOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ number_of_inputs: options.number_of_inputs,
+ });
+ node.node.set_this(AnyAudioNode::ChannelMergerNode(node));
+ node.node.event_target().set_owner(node);
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#BiquadFilterNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 1,
+ channel_count_mode: ChannelCountMode::Explicit,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to no
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_channel_merger(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ options.number_of_inputs as usize,
+ ))
+ });
+ Ok(node)
+ }
+
+ pub(crate) fn number_of_inputs_value(&self) -> u32 {
+ self.number_of_inputs
+ }
+
+ pub(crate) fn number_of_outputs_value(&self) -> u32 {
+ 1
+ }
+
+ // https://webaudio.github.io/web-audio-api/#audionode-channelcount-constraints
+ pub(crate) fn set_channel_count_override(&self, _: &mut CallContext, channel_count: u32) -> WebIdlResult<()> {
+ // The channel count cannot be changed, and an InvalidStateError exception MUST be thrown for
+ // any attempt to change the value.
+ if channel_count != 1 {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Channel count cannot be changed"),
+ ));
+ }
+
+ self.node.set_channel_count_impl(channel_count)
+ }
+
+ pub(crate) fn set_channel_count_mode_override(
+ &self,
+ _: &mut CallContext,
+ channel_count_mode: ChannelCountMode,
+ ) -> WebIdlResult<()> {
+ // The channel count mode cannot be changed from "explicit" and an InvalidStateError exception
+ // MUST be thrown for any attempt to change the value.
+ if channel_count_mode != ChannelCountMode::Explicit {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Channel count mode cannot be changed"),
+ ));
+ }
+
+ self.node.set_channel_count_mode_impl(channel_count_mode)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/channel_splitter_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/channel_splitter_node.rs
new file mode 100644
index 00000000000..8f456b61894
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/channel_splitter_node.rs
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 2025, Tim Ledbetter <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_channel_splitter;
+
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#ChannelSplitterNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ChannelSplitterNode {
+ node: AudioNode,
+ number_of_outputs: u32,
+}
+
+impl Inherits<AudioNode> for ChannelSplitterNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for ChannelSplitterNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for ChannelSplitterNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct ChannelSplitterOptions {
+ pub parent: AudioNodeOptions,
+ pub number_of_outputs: u32,
+}
+
+impl ChannelSplitterNode {
+ pub(crate) fn validate_options(options: &ChannelSplitterOptions) -> WebIdlResult<()> {
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createchannelsplitter
+ // An IndexSizeError exception MUST be thrown if numberOfOutputs is less than 1 or is greater than the number of supported channels.
+ if options.number_of_outputs < 1 || options.number_of_outputs > BaseAudioContext::MAX_NUMBER_OF_CHANNELS {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"Invalid number of outputs"),
+ ));
+ }
+ Ok(())
+ }
+
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: ChannelSplitterOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::validate_options(&options)?;
+ Self::create(cx, context, &options)
+ }
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &ChannelSplitterOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ number_of_outputs: options.number_of_outputs,
+ });
+ node.node.set_this(AnyAudioNode::ChannelSplitterNode(node));
+ node.node.event_target().set_owner(node);
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#ChannelSplitterNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: node.number_of_outputs,
+ channel_count_mode: ChannelCountMode::Explicit,
+ channel_interpretation: ChannelInterpretation::Discrete,
+ };
+
+ // FIXME: Set tail-time to no
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_channel_splitter(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ options.number_of_outputs as usize,
+ ))
+ });
+ Ok(node)
+ }
+
+ pub(crate) fn number_of_inputs_value(&self) -> u32 {
+ 1
+ }
+
+ pub(crate) fn number_of_outputs_value(&self) -> u32 {
+ self.number_of_outputs
+ }
+
+ pub(crate) fn set_channel_count_override(&self, _: &mut CallContext, channel_count: u32) -> WebIdlResult<()> {
+ // https://webaudio.github.io/web-audio-api/#audionode-channelcount-constraints
+ // The channel count cannot be changed, and an InvalidStateError exception MUST be thrown for any attempt to change the value.
+ if channel_count != self.number_of_outputs {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Channel count must be equal to number of outputs"),
+ ));
+ }
+
+ self.node.set_channel_count_impl(channel_count)
+ }
+
+ pub(crate) fn set_channel_count_mode_override(
+ &self,
+ _: &mut CallContext,
+ channel_count_mode: ChannelCountMode,
+ ) -> WebIdlResult<()> {
+ // https://webaudio.github.io/web-audio-api/#audionode-channelcountmode-constraints
+ // The channel count mode cannot be changed from "explicit" and an InvalidStateError exception MUST be thrown for any attempt to change the value.
+ if channel_count_mode != ChannelCountMode::Explicit {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Channel count mode must be 'explicit'"),
+ ));
+ }
+
+ self.node.set_channel_count_mode_impl(channel_count_mode)
+ }
+
+ pub(crate) fn set_channel_interpretation_override(
+ &self,
+ _: &mut CallContext,
+ channel_interpretation: ChannelInterpretation,
+ ) -> WebIdlResult<()> {
+ // https://webaudio.github.io/web-audio-api/#audionode-channelinterpretation-constraints
+ // The channel interpretation can not be changed from "discrete" and a InvalidStateError exception MUST be thrown for any attempt to change the value.
+ if channel_interpretation != ChannelInterpretation::Discrete {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Channel interpretation must be 'discrete'"),
+ ));
+ }
+
+ self.node.set_channel_interpretation_impl(channel_interpretation)
+ }
+}
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
new file mode 100644
index 00000000000..0a290f660f5
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/constant_source_node.rs
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2025, Tim Ledbetter <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_constant_source;
+
+use super::audio_node::AnyAudioNode;
+use super::audio_param::{AudioParam, AutomationRate, FixedAutomationRate};
+use super::audio_scheduled_source_node::AudioScheduledSourceNode;
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+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
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ConstantSourceNode {
+ node: AudioScheduledSourceNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-constantsourcenode-offset
+ offset: Ref<AudioParam>,
+}
+
+impl Inherits<AudioScheduledSourceNode> for ConstantSourceNode {
+ fn parent(&self) -> &AudioScheduledSourceNode {
+ &self.node
+ }
+}
+
+impl Wrappable for ConstantSourceNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.parent().finalize_node();
+ }
+}
+
+impl GetTheParent for ConstantSourceNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct ConstantSourceOptions {
+ pub offset: f32,
+}
+
+impl ConstantSourceNode {
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: ConstantSourceOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, &options)
+ }
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &ConstantSourceOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioScheduledSourceNode::new(defer_gc, context),
+ offset: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.offset,
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ });
+ node.node.parent().set_this(AnyAudioNode::ConstantSourceNode(node));
+ node.node.parent().event_target().set_owner(node);
+ node.offset.set_owner(AnyAudioNode::ConstantSourceNode(node));
+ node.node.parent().queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_constant_source(
+ node.node.parent().node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ Arc::as_ptr(node.offset.render_param()),
+ ))
+ });
+ Ok(node)
+ }
+
+ pub(crate) fn offset(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.offset)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/convolver_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/convolver_node.rs
new file mode 100644
index 00000000000..4d29638db52
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/convolver_node.rs
@@ -0,0 +1,228 @@
+/*
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#![allow(clippy::collapsible_if, reason = "preserve the C++ branch structure")]
+
+use std::cell::Cell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::control_message::ControlMessage;
+use libweb_rust::web_audio::rendering::convolver_kernel::{AudioBufferContents, ConvolverDelayLine, ConvolverKernel};
+use libweb_rust::web_audio::rendering::node_message::{NodeMessage, SetConvolverKernel};
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_convolver;
+
+use super::audio_buffer::AudioBuffer;
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#ConvolverNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ConvolverNode {
+ node: AudioNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-convolvernode-buffer
+ buffer: Cell<Option<Ref<AudioBuffer>>>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-convolvernode-normalize
+ normalize: Cell<bool>,
+}
+
+impl Inherits<AudioNode> for ConvolverNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for ConvolverNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for ConvolverNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct ConvolverOptions {
+ pub parent: AudioNodeOptions,
+ pub buffer: Option<Option<Ref<AudioBuffer>>>,
+ pub disable_normalization: bool,
+}
+
+impl ConvolverNode {
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &ConvolverOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // NB: The node and its render node are created up front, so that step 2 has something to hand the impulse
+ // response to.
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ buffer: Cell::new(None),
+ normalize: Cell::new(!options.disable_normalization),
+ });
+ node.node.set_this(AnyAudioNode::ConvolverNode(node));
+ node.node.event_target().set_owner(node);
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_convolver(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ ))
+ });
+ // 1. Set the attributes normalize to the inverse of the value of disableNormalization.
+ // NB: Done by the constructor above, so that step 2 already sees the final value.
+ // 2. If buffer exists, set the buffer attribute to its value.
+ if let Some(buffer) = options.buffer {
+ node.set_buffer(cx, buffer)?;
+ }
+
+ // 3. Let o be new AudioNodeOptions dictionary.
+ // 4. If channelCount exists in options, set channelCount on o with the same value.
+ // 5. If channelCountMode exists in options, set channelCountMode on o with the same value.
+ // 6. If channelInterpretation exists in options, set channelInterpretation on o with the same value.
+ // 7. Initialize the AudioNode this, with c and o as argument.
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::ClampedMax,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to yes
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ Ok(node)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-convolvernode-convolvernode
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: ConvolverOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, &options)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-convolvernode-buffer
+ pub(crate) fn set_buffer(&self, cx: &mut CallContext, buffer: Option<Ref<AudioBuffer>>) -> WebIdlResult<()> {
+ // 1. If the buffer number of channels is not 1, 2, 4, or if the sample-rate of the buffer is not the same as the
+ // sample-rate of its associated BaseAudioContext, a NotSupportedError MUST be thrown.
+ // AD-HOC: The steps do not cover a null buffer, which clears the impulse response and leaves the node silent.
+ if let Some(buffer) = buffer {
+ let number_of_channels = buffer.number_of_channels(cx)?;
+ if number_of_channels != 1 && number_of_channels != 2 && number_of_channels != 4 {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"ConvolverNode buffer must have 1, 2 or 4 channels"),
+ ));
+ }
+ if buffer.sample_rate(cx)? != self.node.context_value().sample_rate_value() {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"ConvolverNode buffer must have the same sample rate as its context"),
+ ));
+ }
+ }
+ self.buffer.set(buffer);
+
+ // 2. Acquire the content of the AudioBuffer.
+ // NB: The acquired content is cut into partitions and transformed here, and the delay line that the rendering
+ // thread pairs those partitions with is sized and allocated alongside it, so that the rendering thread
+ // receives both ready to use and never has to build either during a render quantum.
+ let mut kernel = None;
+ let mut delay_line = None;
+ if let Some(buffer) = buffer {
+ if let Some(contents) = AudioBuffer::acquire_contents(buffer, cx.vm()) {
+ let channels: Vec<_> = contents.channels.iter().map(|channel| ak::Span::new(channel)).collect();
+ kernel = ConvolverKernel::create(
+ &AudioBufferContents {
+ channels: &channels,
+ sample_rate: contents.sample_rate,
+ },
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ self.normalize.get(),
+ );
+ }
+ if let Some(kernel) = &kernel {
+ delay_line = Some(Arc::new(ConvolverDelayLine::create(kernel)));
+ }
+ }
+ self.node
+ .context_value()
+ .queue_control_message(ControlMessage::NodeMessage(NodeMessage::SetConvolverKernel(
+ SetConvolverKernel {
+ node_id: self.node.node_id(),
+ kernel,
+ delay_line,
+ },
+ )));
+ Ok(())
+ }
+
+ pub(crate) fn buffer(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<AudioBuffer>>> {
+ Ok(self.buffer.get())
+ }
+
+ pub(crate) fn normalize(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ Ok(self.normalize.get())
+ }
+
+ pub(crate) fn set_normalize(&self, _: &mut CallContext, value: bool) -> WebIdlResult<()> {
+ self.normalize.set(value);
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#audionode-channelcount-constraints
+ pub(crate) fn set_channel_count_override(&self, _: &mut CallContext, channel_count: u32) -> WebIdlResult<()> {
+ // The channel count cannot be greater than two, and a NotSupportedError exception MUST be thrown for any attempt
+ // to change it to a value greater than two.
+ if channel_count > 2 {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"ConvolverNode does not support channel count greater than 2"),
+ ));
+ }
+
+ self.node.set_channel_count_impl(channel_count)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#audionode-channelcountmode-constraints
+ pub(crate) fn set_channel_count_mode_override(
+ &self,
+ _: &mut CallContext,
+ mode: ChannelCountMode,
+ ) -> WebIdlResult<()> {
+ // The channel count mode cannot be set to "max", and a NotSupportedError exception MUST be thrown for any attempt
+ // to set it to "max".
+ if mode == ChannelCountMode::Max {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"ConvolverNode does not support 'max' as channelCountMode."),
+ ));
+ }
+
+ self.node.set_channel_count_mode_impl(mode)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/delay_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/delay_node.rs
new file mode 100644
index 00000000000..ce0a26d584a
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/delay_node.rs
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2025, Tim Ledbetter <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_delay;
+
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::audio_param::{AudioParam, AutomationRate, FixedAutomationRate};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#DelayNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct DelayNode {
+ node: AudioNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-delaynode-delaytime
+ delay_time: Ref<AudioParam>,
+}
+
+impl Inherits<AudioNode> for DelayNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for DelayNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for DelayNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct DelayOptions {
+ pub parent: AudioNodeOptions,
+ pub delay_time: f64,
+ pub max_delay_time: f64,
+}
+
+impl DelayNode {
+ pub(crate) fn validate_options(options: &DelayOptions) -> WebIdlResult<()> {
+ // https://webaudio.github.io/web-audio-api/#dom-delayoptions-maxdelaytime
+ // If specified, this value MUST be greater than zero and less than three minutes or a NotSupportedError exception MUST be thrown.
+ const MAXIMUM_DELAY_TIME_SECONDS: f64 = 180.;
+ if options.max_delay_time <= 0.
+ || options.max_delay_time >= MAXIMUM_DELAY_TIME_SECONDS
+ || options.max_delay_time.is_nan()
+ {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"Max delay time must be between 0 and 180 seconds exclusive"),
+ ));
+ }
+ Ok(())
+ }
+
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: DelayOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::validate_options(&options)?;
+ Self::create(cx, context, &options)
+ }
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &DelayOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ delay_time: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.delay_time as f32,
+ 0.,
+ options.max_delay_time as f32,
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ });
+ node.node.set_this(AnyAudioNode::DelayNode(node));
+ node.node.event_target().set_owner(node);
+ node.delay_time.set_owner(AnyAudioNode::DelayNode(node));
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#DelayNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::Max,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to yes
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_delay(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ Arc::as_ptr(node.delay_time.render_param()),
+ options.max_delay_time,
+ ))
+ });
+ Ok(node)
+ }
+
+ pub(crate) fn delay_time(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.delay_time)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/dynamics_compressor_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/dynamics_compressor_node.rs
new file mode 100644
index 00000000000..7138663702c
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/dynamics_compressor_node.rs
@@ -0,0 +1,235 @@
+/*
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_passthrough;
+
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::audio_param::{AudioParam, AutomationRate, FixedAutomationRate};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#DynamicsCompressorNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct DynamicsCompressorNode {
+ node: AudioNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-threshold
+ threshold: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-knee
+ knee: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-ratio
+ ratio: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-attack
+ attack: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-release
+ release: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-internal-reduction-slot
+ reduction: f32, // [[internal reduction]]
+}
+
+impl Inherits<AudioNode> for DynamicsCompressorNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for DynamicsCompressorNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for DynamicsCompressorNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct DynamicsCompressorOptions {
+ pub parent: AudioNodeOptions,
+ pub threshold: f32,
+ pub knee: f32,
+ pub ratio: f32,
+ pub attack: f32,
+ pub release: f32,
+}
+
+impl DynamicsCompressorNode {
+ // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-dynamicscompressornode
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: DynamicsCompressorOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, &options)
+ }
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &DynamicsCompressorOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // Create the node and allocate memory
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ threshold: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.threshold,
+ -100.,
+ 0.,
+ AutomationRate::KRate,
+ FixedAutomationRate::Yes,
+ ),
+ knee: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.knee,
+ 0.,
+ 40.,
+ AutomationRate::KRate,
+ FixedAutomationRate::Yes,
+ ),
+ ratio: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.ratio,
+ 1.,
+ 20.,
+ AutomationRate::KRate,
+ FixedAutomationRate::Yes,
+ ),
+ attack: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.attack,
+ 0.,
+ 1.,
+ AutomationRate::KRate,
+ FixedAutomationRate::Yes,
+ ),
+ release: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.release,
+ 0.,
+ 1.,
+ AutomationRate::KRate,
+ FixedAutomationRate::Yes,
+ ),
+ reduction: 0.,
+ });
+ node.node.set_this(AnyAudioNode::DynamicsCompressorNode(node));
+ node.node.event_target().set_owner(node);
+ node.threshold.set_owner(AnyAudioNode::DynamicsCompressorNode(node));
+ node.knee.set_owner(AnyAudioNode::DynamicsCompressorNode(node));
+ node.ratio.set_owner(AnyAudioNode::DynamicsCompressorNode(node));
+ node.attack.set_owner(AnyAudioNode::DynamicsCompressorNode(node));
+ node.release.set_owner(AnyAudioNode::DynamicsCompressorNode(node));
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#DynamicsCompressorNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::ClampedMax,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to yes
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+
+ // FIXME: Implement actual dynamics compression; for now the signal passes through unchanged.
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_passthrough(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ ))
+ });
+ Ok(node)
+ }
+
+ pub(crate) fn threshold(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.threshold)
+ }
+
+ pub(crate) fn knee(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.knee)
+ }
+
+ pub(crate) fn ratio(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.ratio)
+ }
+
+ pub(crate) fn attack(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.attack)
+ }
+
+ pub(crate) fn release(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.release)
+ }
+
+ pub(crate) fn reduction(&self, _: &mut CallContext) -> WebIdlResult<f32> {
+ Ok(self.reduction)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
+ pub(crate) fn set_channel_count_override(&self, _: &mut CallContext, channel_count: u32) -> WebIdlResult<()> {
+ if channel_count > 2 {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"DynamicsCompressorNode does not support channel count greater than 2"),
+ ));
+ }
+
+ self.node.set_channel_count_impl(channel_count)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
+ pub(crate) fn set_channel_count_mode_override(
+ &self,
+ _: &mut CallContext,
+ mode: ChannelCountMode,
+ ) -> WebIdlResult<()> {
+ if mode == ChannelCountMode::Max {
+ // Return a NotSupportedError if 'max' is used
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"DynamicsCompressorNode does not support 'max' as channelCountMode."),
+ ));
+ }
+
+ // If the mode is valid, call the base class implementation
+ self.node.set_channel_count_mode_impl(mode)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/gain_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/gain_node.rs
new file mode 100644
index 00000000000..a0eb520b02f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/gain_node.rs
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_gain;
+
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::audio_param::{AudioParam, AutomationRate, FixedAutomationRate};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+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/#GainNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct GainNode {
+ node: AudioNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-gainnode-gain
+ gain: Ref<AudioParam>,
+}
+
+impl Inherits<AudioNode> for GainNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for GainNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for GainNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct GainOptions {
+ pub parent: AudioNodeOptions,
+ pub gain: f32,
+}
+
+impl GainNode {
+ // https://webaudio.github.io/web-audio-api/#dom-gainnode-gainnode
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: GainOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, &options)
+ }
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &GainOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // Create the node and allocate memory
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ gain: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.gain,
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ });
+ node.node.set_this(AnyAudioNode::GainNode(node));
+ node.node.event_target().set_owner(node);
+ node.gain.set_owner(AnyAudioNode::GainNode(node));
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#GainNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::Max,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to no
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_gain(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ Arc::as_ptr(node.gain.render_param()),
+ ))
+ });
+ Ok(node)
+ }
+
+ pub(crate) fn gain(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.gain)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/iir_filter_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/iir_filter_node.rs
new file mode 100644
index 00000000000..d5c64db1f37
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/iir_filter_node.rs
@@ -0,0 +1,242 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::TypedArrayBase;
+use libjs_rust::api::{Gc, Trace};
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_iir_filter;
+
+use super::audio_array::{copy_float32_array, float32_array_length, overwrite_float32_array};
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#IIRFilterNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct IIRFilterNode {
+ node: AudioNode,
+
+ // The coefficients, divided by the first feedback coefficient.
+ #[gc(untraced)]
+ feedforward: Vec<f64>,
+ #[gc(untraced)]
+ feedback: Vec<f64>,
+}
+
+impl Inherits<AudioNode> for IIRFilterNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for IIRFilterNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for IIRFilterNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct IIRFilterOptions {
+ pub parent: AudioNodeOptions,
+ pub feedforward: Vec<f64>,
+ pub feedback: Vec<f64>,
+}
+
+// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createiirfilter
+const MAX_COEFFICIENT_COUNT: usize = 20;
+
+impl IIRFilterNode {
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &IIRFilterOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createiirfilter
+ // feedforward: An array of the feedforward (numerator) coefficients for the transfer function of the IIR filter.
+ // The maximum length of this array is 20. If all of the values are zero, an InvalidStateError MUST be thrown. A
+ // NotSupportedError MUST be thrown if the array length is 0 or greater than 20.
+ // feedback: An array of the feedback (denominator) coefficients for the transfer function of the IIR filter. The
+ // maximum length of this array is 20. If the first element of the array is 0, an InvalidStateError MUST be thrown.
+ // A NotSupportedError MUST be thrown if the array length is 0 or greater than 20.
+ let feedforward = &options.feedforward;
+ let feedback = &options.feedback;
+ if feedforward.is_empty() || feedforward.len() > MAX_COEFFICIENT_COUNT {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"The number of feedforward coefficients must be between 1 and 20"),
+ ));
+ }
+ if feedback.is_empty() || feedback.len() > MAX_COEFFICIENT_COUNT {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"The number of feedback coefficients must be between 1 and 20"),
+ ));
+ }
+ if feedforward.iter().all(|coefficient| *coefficient == 0.) {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"At least one feedforward coefficient must not be zero"),
+ ));
+ }
+ if feedback[0] == 0. {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"The first feedback coefficient must not be zero"),
+ ));
+ }
+
+ // https://webaudio.github.io/web-audio-api/#IIRFilterNode-filter-definition
+ // NB: Dividing every coefficient by a_0 gives the same transfer function with a_0 = 1, which the filter uses.
+ let a0 = feedback[0];
+ let mut normalized_feedforward = Vec::with_capacity(feedforward.len());
+ for coefficient in feedforward {
+ normalized_feedforward.push(coefficient / a0);
+ }
+ let mut normalized_feedback = Vec::with_capacity(feedback.len());
+ for coefficient in feedback {
+ normalized_feedback.push(coefficient / a0);
+ }
+
+ // When the constructor is called with a BaseAudioContext c and an option object option, the user agent MUST
+ // initialize the AudioNode this, with context and options as arguments.
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ feedforward: normalized_feedforward.clone(),
+ feedback: normalized_feedback.clone(),
+ });
+ node.node.set_this(AnyAudioNode::IIRFilterNode(node));
+ node.node.event_target().set_owner(node);
+
+ // https://webaudio.github.io/web-audio-api/#IIRFilterNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::Max,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to yes
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_iir_filter(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ ak::Span::new(&normalized_feedforward),
+ ak::Span::new(&normalized_feedback),
+ ))
+ });
+ Ok(node)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-iirfilternode-iirfilternode
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: IIRFilterOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, &options)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-iirfilternode-getfrequencyresponse
+ pub(crate) fn get_frequency_response(
+ &self,
+ cx: &mut CallContext,
+ frequency_hz: Gc<TypedArrayBase>,
+ mag_response: Gc<TypedArrayBase>,
+ phase_response: Gc<TypedArrayBase>,
+ ) -> WebIdlResult<()> {
+ // Given the current filter parameter settings, synchronously calculates the frequency response for the specified
+ // frequencies. The three parameters MUST be Float32Arrays of the same length, or an InvalidAccessError MUST be
+ // thrown.
+ let length = float32_array_length(&frequency_hz);
+ if float32_array_length(&mag_response) != length || float32_array_length(&phase_response) != length {
+ return Err(Exception::Thrown(
+ Exception::Dom(
+ "InvalidAccessError",
+ Utf16String::from_ascii(b"Arrays must have the same length"),
+ )
+ .throw(&CallContext::new(cx.vm(), self.node.context_value().realm())),
+ ));
+ }
+ let frequencies = copy_float32_array(&frequency_hz);
+ let mut magnitudes = vec![0.; length];
+ let mut phases = vec![0.; length];
+ let nyquist_frequency = self.node.context_value().nyquist_frequency();
+
+ // https://webaudio.github.io/web-audio-api/#IIRFilterNode-filter-definition
+ // NB: H(z) = (sum_{m=0}^{M} b_m z^{-m}) / (sum_{n=0}^{N} a_n z^{-n}), evaluated at z = e^{j omega}. A polynomial in
+ // z^-1 is evaluated with Horner's method, from the coefficient of its highest power down.
+ #[derive(Clone, Copy)]
+ struct ComplexNumber {
+ real: f64,
+ imaginary: f64,
+ }
+ let evaluate = |coefficients: &[f64], z_inverse: ComplexNumber| {
+ let mut result = ComplexNumber {
+ real: 0.,
+ imaginary: 0.,
+ };
+ for index in (0..coefficients.len()).rev() {
+ result = ComplexNumber {
+ real: result.real * z_inverse.real - result.imaginary * z_inverse.imaginary + coefficients[index],
+ imaginary: result.real * z_inverse.imaginary + result.imaginary * z_inverse.real,
+ };
+ }
+ result
+ };
+ for index in 0..length {
+ let frequency = f64::from(frequencies[index]);
+
+ // If a value in the frequencyHz parameter is not within [0, sampleRate/2], where sampleRate is the value of
+ // the sampleRate property of the AudioContext, the corresponding value at the same index of the magResponse
+ // and phaseResponse arrays MUST be NaN.
+ if frequency.is_nan() || frequency < 0. || frequency > f64::from(nyquist_frequency) {
+ magnitudes[index] = f32::NAN;
+ phases[index] = f32::NAN;
+ continue;
+ }
+ let omega = std::f64::consts::PI * frequency / f64::from(nyquist_frequency);
+ let z_inverse = ComplexNumber {
+ real: ak::math::cos(omega),
+ imaginary: -ak::math::sin(omega),
+ };
+ let numerator = evaluate(&self.feedforward, z_inverse);
+ let denominator = evaluate(&self.feedback, z_inverse);
+ let denominator_magnitude_squared =
+ denominator.real * denominator.real + denominator.imaginary * denominator.imaginary;
+ let response = ComplexNumber {
+ real: (numerator.real * denominator.real + numerator.imaginary * denominator.imaginary)
+ / denominator_magnitude_squared,
+ imaginary: (numerator.imaginary * denominator.real - numerator.real * denominator.imaginary)
+ / denominator_magnitude_squared,
+ };
+ magnitudes[index] = ak::math::hypot(response.real, response.imaginary) as f32;
+ phases[index] = ak::math::atan2(response.imaginary, response.real) as f32;
+ }
+ overwrite_float32_array(&mag_response, &magnitudes);
+ overwrite_float32_array(&phase_response, &phases);
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/media_element_audio_source_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/media_element_audio_source_node.rs
new file mode 100644
index 00000000000..148f4e4e600
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/media_element_audio_source_node.rs
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2025, Tim Ledbetter <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+use libjs_rust::api::Object;
+use libjs_rust::api::{Gc, Trace};
+
+use super::audio_context::AudioContext;
+use super::audio_node::{AnyAudioNode, AudioNode};
+use super::base_audio_context::AnyBaseAudioContext;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::cpp_cell::CppCell;
+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/#MediaElementAudioSourceNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct MediaElementAudioSourceNode {
+ node: AudioNode,
+ media_element: CppCell,
+}
+
+impl Inherits<AudioNode> for MediaElementAudioSourceNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for MediaElementAudioSourceNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for MediaElementAudioSourceNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+unsafe extern "C" {
+ fn web_audio_media_element_from_wrapper(wrapper: *mut c_void) -> *mut c_void;
+ fn web_audio_media_element_wrap(realm: *mut c_void, cell: *mut c_void) -> *mut c_void;
+}
+
+pub(crate) struct MediaElementAudioSourceOptions {
+ pub media_element: CppInterface,
+}
+
+impl MediaElementAudioSourceNode {
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: Ref<AudioContext>,
+ media_element: CppInterface,
+ ) -> WebIdlResult<Ref<Self>> {
+ let media_element = unsafe {
+ CppCell::from_raw(web_audio_media_element_from_wrapper(
+ media_element.wrapper().as_ptr().cast(),
+ ))
+ };
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, AnyBaseAudioContext::AudioContext(context), 2),
+ media_element,
+ });
+ node.node.set_this(AnyAudioNode::MediaElementAudioSourceNode(node));
+ node.node.event_target().set_owner(node);
+ Ok(node)
+ }
+
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: Ref<AudioContext>,
+ options: MediaElementAudioSourceOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, options.media_element)
+ }
+
+ pub(crate) fn media_element(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ let wrapper = unsafe { web_audio_media_element_wrap(cx.realm().as_ptr().cast(), self.media_element.as_ptr()) };
+ Ok(unsafe { CppInterface::from_wrapper(Gc::<Object>::from_non_null(NonNull::new(wrapper.cast()).unwrap())) })
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/media_stream_audio_destination_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/media_stream_audio_destination_node.rs
new file mode 100644
index 00000000000..68c284ff65a
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/media_stream_audio_destination_node.rs
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::RefCell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+use libjs_rust::api::Object;
+use libjs_rust::api::{Gc, Trace};
+use libweb_rust::web_audio::control_message::FfiSharedCppObject;
+use libweb_rust::web_audio::rendering::node_message::SharedCppObject;
+use libweb_rust::web_audio::rendering::render_node::NodeHandle;
+
+use super::audio_context::AudioContext;
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::base_audio_context::AnyBaseAudioContext;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::cpp_cell::CppCell;
+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/#MediaStreamAudioDestinationNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct MediaStreamAudioDestinationNode {
+ node: AudioNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiodestinationnode-stream
+ stream: crate::bindings::cpp_cell::CppCell,
+ track: crate::bindings::cpp_cell::CppCell,
+ #[gc(untraced)]
+ shared_state: RefCell<Option<libweb_rust::web_audio::rendering::node_message::SharedCppObject>>,
+}
+
+impl Inherits<AudioNode> for MediaStreamAudioDestinationNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for MediaStreamAudioDestinationNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ // Drop the drain callback — and with it the GC root it holds on the track — on the
+ // control thread. Any drain the render node still has queued becomes a no-op.
+ if let Some(shared_state) = &*node.shared_state.borrow() {
+ unsafe { web_audio_media_destination_clear_drain(shared_state.pointer) };
+ }
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for MediaStreamAudioDestinationNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+unsafe extern "C" {
+ fn web_audio_media_destination_create_stream(stream: *mut *mut c_void, track: *mut *mut c_void);
+ fn web_audio_media_destination_create_state(
+ track: *mut c_void,
+ node_id: u64,
+ channels: u32,
+ sample_rate: u32,
+ render_node: *mut *mut c_void,
+ ) -> FfiSharedCppObject;
+ fn web_audio_media_destination_clear_drain(state: *mut c_void);
+ fn web_audio_media_destination_wrap_stream(realm: *mut c_void, stream: *mut c_void) -> *mut c_void;
+}
+
+impl MediaStreamAudioDestinationNode {
+ // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiodestinationnode-mediastreamaudiodestinationnode
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: Ref<AudioContext>,
+ options: &AudioNodeOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiodestinationnode-stream
+ // A MediaStream containing a single MediaStreamTrack with the same number of channels as
+ // the node itself, and whose kind attribute has the value "audio".
+ // NB: The track is deviceless — it carries no deviceId, so registering audio sinks on it
+ // never opens a capture stream; it is fed exclusively by this node's render node.
+ let mut stream = std::ptr::null_mut();
+ let mut track = std::ptr::null_mut();
+ unsafe { web_audio_media_destination_create_stream(&raw mut stream, &raw mut track) };
+ let stream = unsafe { CppCell::from_raw(stream) };
+ let track = unsafe { CppCell::from_raw(track) };
+
+ // 1. Initialize the AudioNode this, with context and options as arguments.
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, AnyBaseAudioContext::AudioContext(context), 2),
+ stream,
+ track,
+ shared_state: RefCell::new(None),
+ });
+ node.node.set_this(AnyAudioNode::MediaStreamAudioDestinationNode(node));
+ node.node.event_target().set_owner(node);
+
+ // https://webaudio.github.io/web-audio-api/#MediaStreamAudioDestinationNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::Explicit,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+ node.node.initialize_audio_node_options(cx, options, &default_options)?;
+ let sample_rate = context.parent().sample_rate_value() as u32;
+ let mut render_node = std::ptr::null_mut();
+ let shared_state = unsafe {
+ web_audio_media_destination_create_state(
+ node.track.as_ptr(),
+ node.node.node_id(),
+ node.node.channel_count_value(),
+ sample_rate,
+ &raw mut render_node,
+ )
+ };
+ *node.shared_state.borrow_mut() = Some(SharedCppObject {
+ pointer: shared_state.pointer,
+ retain: shared_state.retain,
+ release: shared_state.release,
+ });
+ node.node
+ .queue_render_node_creation(unsafe { Box::from_raw(render_node.cast::<NodeHandle>()) });
+ Ok(node)
+ }
+
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: Ref<AudioContext>,
+ options: AudioNodeOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, &options)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiodestinationnode-stream
+ pub(crate) fn stream(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ let wrapper =
+ unsafe { web_audio_media_destination_wrap_stream(cx.realm().as_ptr().cast(), self.stream.as_ptr()) };
+ Ok(unsafe { CppInterface::from_wrapper(Gc::<Object>::from_non_null(NonNull::new(wrapper.cast()).unwrap())) })
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/media_stream_audio_source_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/media_stream_audio_source_node.rs
new file mode 100644
index 00000000000..b2c80a7d4e0
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/media_stream_audio_source_node.rs
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#![allow(clippy::collapsible_if, reason = "preserve the C++ branch structure")]
+
+use std::cell::RefCell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::MarkedVec;
+use libjs_rust::api::Object;
+use libjs_rust::api::{Gc, Trace};
+use libweb_rust::web_audio::control_message::{ControlMessage, FfiSharedCppObject};
+use libweb_rust::web_audio::rendering::audio_frame_ring::AudioFrameRingCallbacks;
+use libweb_rust::web_audio::rendering::media_stream_source_render_node::web_audio_node_create_media_stream_source;
+use libweb_rust::web_audio::rendering::node_message::{NodeMessage, SetMediaStreamSourceRing, SharedCppObject};
+
+use super::audio_context::AudioContext;
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#MediaStreamAudioSourceNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct MediaStreamAudioSourceNode {
+ node: AudioNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiosourcenode-mediastream
+ media_stream: CppCell,
+
+ // [[input track]]: the first audio track of the input stream, ordered by track id.
+ input_track: libjs_rust::api::GcRefCell<Option<CppCell>>,
+
+ // Carries the track's audio from the producing thread to the render thread; the sink is
+ // registered on the input track and only ever references the ring, never this GC node.
+ #[gc(untraced)]
+ ring: RefCell<Option<SharedCppObject>>,
+ #[gc(untraced)]
+ sink: RefCell<Option<SharedCppObject>>,
+}
+
+impl Inherits<AudioNode> for MediaStreamAudioSourceNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for MediaStreamAudioSourceNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+
+ // NB: Finalizers run before any dead cell is destroyed, so detaching from the input track
+ // is safe even when the track is collected in the same garbage collection cycle.
+ if let Some(track) = &*node.input_track.borrow() {
+ if let Some(sink) = &*node.sink.borrow() {
+ unsafe { web_audio_media_source_detach(track.as_ptr(), sink.pointer) };
+ }
+ }
+ }
+}
+
+impl GetTheParent for MediaStreamAudioSourceNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+unsafe extern "C" {
+ fn web_audio_media_source_stream_from_wrapper(wrapper: *mut c_void) -> *mut c_void;
+ fn web_audio_media_source_stream_wrap(realm: *mut c_void, cell: *mut c_void) -> *mut c_void;
+}
+
+pub(crate) struct MediaStreamAudioSourceOptions {
+ pub media_stream: CppInterface,
+}
+
+unsafe extern "C" {
+ fn web_audio_media_source_audio_tracks(
+ stream: *mut c_void,
+ context: *mut c_void,
+ callback: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ );
+ fn web_audio_media_source_track_id_less(a: *mut c_void, b: *mut c_void) -> bool;
+ fn web_audio_media_source_track_channels(track: *mut c_void) -> u32;
+ fn web_audio_media_source_has_live_track(track: *mut c_void) -> bool;
+ fn web_audio_media_source_ring(channels: u32) -> FfiSharedCppObject;
+ fn web_audio_media_source_ring_callbacks(callbacks: *mut AudioFrameRingCallbacks);
+ fn web_audio_media_source_attach(track: *mut c_void, ring: *mut c_void, sample_rate: f32) -> FfiSharedCppObject;
+ fn web_audio_media_source_detach(track: *mut c_void, sink: *mut c_void);
+}
+
+impl MediaStreamAudioSourceNode {
+ // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiosourcenode-mediastreamaudiosourcenode
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: Ref<AudioContext>,
+ options: &MediaStreamAudioSourceOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // 1. If the mediaStream member of options does not reference a MediaStream that has at least one MediaStreamTrack
+ // whose kind attribute has the value "audio", throw an InvalidStateError and abort these steps. Else, let this
+ // stream be inputStream.
+ let input_stream = unsafe {
+ CppCell::from_raw(web_audio_media_source_stream_from_wrapper(
+ options.media_stream.wrapper().as_ptr().cast(),
+ ))
+ };
+ let audio_tracks = MarkedVec::<CppCell>::new(cx.vm());
+ unsafe extern "C" fn append(context: *mut c_void, track: *mut c_void) {
+ unsafe { &*context.cast::<MarkedVec<'_, CppCell>>() }.push(unsafe { CppCell::from_raw(track) });
+ }
+ unsafe {
+ web_audio_media_source_audio_tracks(
+ input_stream.as_ptr(),
+ (&raw const audio_tracks).cast_mut().cast(),
+ append,
+ );
+ };
+ if audio_tracks.is_empty() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"MediaStream has no audio tracks"),
+ ));
+ }
+
+ // 2. Let tracks be the list of all MediaStreamTracks of inputStream that have a kind of "audio".
+ // 3. Sort the elements in tracks based on their id attribute using an ordering on sequences of code unit values.
+ audio_tracks.values_mut().sort_unstable_by(|a, b| {
+ if unsafe { web_audio_media_source_track_id_less(a.as_ptr(), b.as_ptr()) } {
+ std::cmp::Ordering::Less
+ } else if unsafe { web_audio_media_source_track_id_less(b.as_ptr(), a.as_ptr()) } {
+ std::cmp::Ordering::Greater
+ } else {
+ std::cmp::Ordering::Equal
+ }
+ });
+
+ // 4. Initialize the AudioNode this, with context and options as arguments.
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, AnyBaseAudioContext::AudioContext(context), 2),
+ media_stream: input_stream,
+ input_track: libjs_rust::api::GcRefCell::new(None),
+ ring: RefCell::new(None),
+ sink: RefCell::new(None),
+ });
+ node.node.set_this(AnyAudioNode::MediaStreamAudioSourceNode(node));
+ node.node.event_target().set_owner(node);
+
+ // https://webaudio.github.io/web-audio-api/#MediaStreamAudioSourceNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::Max,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+ node.node
+ .initialize_audio_node_options(cx, &AudioNodeOptions::default(), &default_options)?;
+
+ // 5. Set an internal slot [[input track]] on this MediaStreamAudioSourceNode to be the first element of tracks.
+ // This is the track used as the input audio for this MediaStreamAudioSourceNode.
+ *node.input_track.borrow_mut(cx.vm()) = audio_tracks.get(0);
+ let mut callbacks = std::mem::MaybeUninit::uninit();
+ unsafe { web_audio_media_source_ring_callbacks(callbacks.as_mut_ptr()) };
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_media_stream_source(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ callbacks.assume_init(),
+ ))
+ });
+ node.attach_input_track();
+ context.parent().add_media_stream_source(cx.vm(), node);
+ Ok(node)
+ }
+
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: Ref<AudioContext>,
+ options: MediaStreamAudioSourceOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, &options)
+ }
+
+ fn attach_input_track(&self) {
+ let track = self.input_track.borrow();
+ let track = track.as_ref().expect("the input track has been selected");
+ let channel_count = if unsafe { web_audio_media_source_track_channels(track.as_ptr()) } == 1 {
+ 1
+ } else {
+ 2
+ };
+ let ring = unsafe { web_audio_media_source_ring(channel_count) };
+ let ring = SharedCppObject {
+ pointer: ring.pointer,
+ retain: ring.retain,
+ release: ring.release,
+ };
+ self.node
+ .context_value()
+ .queue_control_message(ControlMessage::NodeMessage(NodeMessage::SetMediaStreamSourceRing(
+ SetMediaStreamSourceRing {
+ node_id: self.node.node_id(),
+ ring: Some(ring.clone()),
+ channel_count,
+ },
+ )));
+ let sink = unsafe {
+ web_audio_media_source_attach(
+ track.as_ptr(),
+ ring.pointer,
+ self.node.context_value().sample_rate_value(),
+ )
+ };
+ *self.ring.borrow_mut() = Some(ring);
+ if !sink.pointer.is_null() {
+ *self.sink.borrow_mut() = Some(SharedCppObject {
+ pointer: sink.pointer,
+ retain: sink.retain,
+ release: sink.release,
+ });
+ }
+ }
+
+ pub(crate) fn has_live_input_track(&self) -> bool {
+ self.input_track
+ .borrow()
+ .as_ref()
+ .is_some_and(|track| unsafe { web_audio_media_source_has_live_track(track.as_ptr()) })
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiosourcenode-mediastream
+ pub(crate) fn media_stream(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ let wrapper =
+ unsafe { web_audio_media_source_stream_wrap(cx.realm().as_ptr().cast(), self.media_stream.as_ptr()) };
+ Ok(unsafe { CppInterface::from_wrapper(Gc::<Object>::from_non_null(NonNull::new(wrapper.cast()).unwrap())) })
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/mod.rs
index e94b3414064..81dd674cfce 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/mod.rs
@@ -4,11 +4,38 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+pub(crate) mod analyser_node;
+pub(crate) mod audio_array;
pub(crate) mod audio_buffer;
+pub(crate) mod audio_buffer_source_node;
+pub(crate) mod audio_context;
+pub(crate) mod audio_destination_node;
pub(crate) mod audio_listener;
+pub(crate) mod audio_node;
pub(crate) mod audio_param;
pub(crate) mod audio_param_map;
pub(crate) mod audio_processing_event;
+pub(crate) mod audio_scheduled_source_node;
+pub(crate) mod audio_worklet_node;
pub(crate) mod audio_worklet_processor;
+pub(crate) mod base_audio_context;
+pub(crate) mod biquad_filter_node;
+pub(crate) mod channel_merger_node;
+pub(crate) mod channel_splitter_node;
+pub(crate) mod constant_source_node;
+pub(crate) mod convolver_node;
+pub(crate) mod delay_node;
+pub(crate) mod dynamics_compressor_node;
+pub(crate) mod gain_node;
+pub(crate) mod iir_filter_node;
+pub(crate) mod media_element_audio_source_node;
+pub(crate) mod media_stream_audio_destination_node;
+pub(crate) mod media_stream_audio_source_node;
pub(crate) mod offline_audio_completion_event;
+pub(crate) mod offline_audio_context;
+pub(crate) mod oscillator_node;
+pub(crate) mod panner_node;
pub(crate) mod periodic_wave;
+pub(crate) mod script_processor_node;
+pub(crate) mod stereo_panner_node;
+pub(crate) mod wave_shaper_node;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_completion_event.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_completion_event.rs
index 20a1cf42f8f..d8575e88b62 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_completion_event.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_completion_event.rs
@@ -13,7 +13,7 @@ use libjs_rust::api::{Trace, Vm};
use super::audio_buffer::AudioBuffer;
use crate::bindings::event_target::CppEvent;
-use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi};
+use crate::bindings::interface::{Ref, Wrappable, allocate};
use crate::bindings::{CallContext, WebIdlResult};
use crate::dom::event::EventInit;
@@ -25,7 +25,7 @@ pub(crate) struct OfflineAudioCompletionEventInit {
#[derive(Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct OfflineAudioCompletionEvent {
- event: CppEvent,
+ pub(crate) event: CppEvent,
rendered_buffer: Option<Ref<AudioBuffer>>,
}
@@ -66,14 +66,3 @@ impl OfflineAudioCompletionEvent {
.expect("the event initializer supplies its required buffer"))
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_offline_audio_completion_event_create(
- vm: &Vm,
- event: *mut c_void,
- buffer: *mut c_void,
-) -> *mut c_void {
- let event = unsafe { CppEvent::from_raw(event) };
- let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(buffer) };
- OfflineAudioCompletionEvent::create(vm, event, buffer).event.as_ptr()
-}
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
new file mode 100644
index 00000000000..6369952ae89
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs
@@ -0,0 +1,489 @@
+/*
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2025, Ben Eidson <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#![allow(clippy::collapsible_if, reason = "preserve the C++ branch structure")]
+
+use std::cell::{Cell, RefCell};
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, Trace, Value, Vm};
+use libweb_rust::web_audio::control_message::FfiSharedCppObject;
+use libweb_rust::web_audio::rendering::node_message::SharedCppObject;
+
+use super::audio_array::overwrite_float32_array;
+use super::audio_buffer::AudioBuffer;
+use super::audio_destination_node::AudioDestinationNode;
+use super::audio_listener::AudioListener;
+use super::base_audio_context::{AnyBaseAudioContext, AudioContextState, BaseAudioContext};
+use super::offline_audio_completion_event::OfflineAudioCompletionEvent;
+use crate::bindings::conversions::ToJs;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::event_target::{CppEvent, CppEventTarget, GetTheParent};
+use crate::bindings::global_object::window_from_global_object;
+use crate::bindings::interface::{
+ Inherits, Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, with_temporary_execution_context_and_callbacks,
+};
+use crate::bindings::promise::{
+ WebIdlPromise, promise_from_abi, promise_realm, reject_promise_with_exception, resolve_promise,
+};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+pub(crate) struct OfflineAudioContextOptions {
+ pub number_of_channels: u32,
+ pub length: u32,
+ pub sample_rate: f32,
+}
+
+// https://webaudio.github.io/web-audio-api/#OfflineAudioContext
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct OfflineAudioContext {
+ context: BaseAudioContext,
+ length: u32,
+ number_of_channels: u32,
+ rendering_started: Cell<bool>,
+ rendered_buffer: Cell<Option<Ref<AudioBuffer>>>,
+ #[gc(untraced)]
+ renderer: RefCell<Option<SharedCppObject>>,
+ suspend_promises: GcRefCell<Vec<(u64, WebIdlPromise)>>,
+}
+
+impl Inherits<BaseAudioContext> for OfflineAudioContext {
+ fn parent(&self) -> &BaseAudioContext {
+ &self.context
+ }
+}
+
+impl Wrappable for OfflineAudioContext {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.context.cpp_parent()
+ }
+}
+
+impl GetTheParent for OfflineAudioContext {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+unsafe extern "C" {
+ fn web_audio_offline_context_create(
+ queue: *const c_void,
+ destination: u64,
+ channels: u32,
+ length: u32,
+ sample_rate: f32,
+ ) -> FfiSharedCppObject;
+ fn web_audio_offline_context_set_callbacks(renderer: *mut c_void, context: *mut c_void, promise: *mut c_void);
+ fn web_audio_offline_context_start(renderer: *mut c_void);
+ fn web_audio_offline_context_resume(renderer: *mut c_void);
+ fn web_audio_offline_context_stop(renderer: *mut c_void);
+ fn web_audio_offline_context_clear_callbacks(renderer: *mut c_void);
+ fn web_audio_offline_context_request_suspend(renderer: *mut c_void, frame: u64) -> bool;
+ fn web_audio_offline_context_frames_rendered(renderer: *mut c_void) -> u64;
+ fn web_audio_offline_context_channel(renderer: *mut c_void, channel: usize, samples: *mut ak::Span<'_, f32>);
+}
+
+impl OfflineAudioContext {
+ fn this(&self) -> Ref<Self> {
+ let AnyBaseAudioContext::OfflineAudioContext(context) = self.context.this() else {
+ unreachable!()
+ };
+ context
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-offlineaudiocontext
+ pub(crate) fn construct_options(
+ cx: &mut CallContext,
+ context_options: OfflineAudioContextOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // AD-HOC: This spec text is currently only mentioned in the constructor overload that takes separate arguments,
+ // but these parameters should be validated for both constructors.
+ // A NotSupportedError exception MUST be thrown if any of the arguments is negative, zero, or outside its nominal range.
+ BaseAudioContext::verify_audio_options_inside_nominal_range(
+ context_options.number_of_channels,
+ context_options.length,
+ context_options.sample_rate,
+ )?;
+ let window = window_from_global_object(cx.realm().global_object())
+ .expect("an OfflineAudioContext is constructed on a Window");
+ let global = unsafe { CppCell::from_raw(window.as_event_target().as_ptr()) };
+
+ // Let c be a new OfflineAudioContext object. Initialize c as follows:
+ let c = allocate(cx.vm(), |defer_gc| Self {
+ context: BaseAudioContext::new(defer_gc, global, context_options.sample_rate),
+ length: context_options.length,
+ number_of_channels: context_options.number_of_channels,
+ rendering_started: Cell::new(false),
+ rendered_buffer: Cell::new(None),
+ renderer: RefCell::new(None),
+ suspend_promises: GcRefCell::new(Vec::new()),
+ });
+ c.context
+ .initialize(cx.vm(), AnyBaseAudioContext::OfflineAudioContext(c));
+ c.context.event_target().set_owner(c);
+ c.context.listener.set(Some(AudioListener::create(
+ cx.vm(),
+ AnyBaseAudioContext::OfflineAudioContext(c),
+ )));
+
+ // 1. Set the [[control thread state]] for c to "suspended".
+ c.context.set_control_state(AudioContextState::Suspended);
+
+ // 2. Set the [[rendering thread state]] for c to "suspended".
+ c.context.set_rendering_state(AudioContextState::Suspended);
+
+ // FIXME: 3. Determine the [[render quantum size]] for this OfflineAudioContext, based on the value of the renderSizeHint:
+ // 4. Construct an AudioDestinationNode with its channelCount set to contextOptions.numberOfChannels.
+ c.context.destination.set(Some(AudioDestinationNode::create(
+ cx,
+ AnyBaseAudioContext::OfflineAudioContext(c),
+ context_options.number_of_channels,
+ )?));
+
+ // FIXME: 5. Let messageChannel be a new MessageChannel.
+ // FIXME: 6. Let controlSidePort be the value of messageChannel’s port1 attribute.
+ // FIXME: 7. Let renderingSidePort be the value of messageChannel’s port2 attribute.
+ // FIXME: 8. Let serializedRenderingSidePort be the result of StructuredSerializeWithTransfer(renderingSidePort, « renderingSidePort »).
+ // FIXME: 9. Set this audioWorklet's port to controlSidePort.
+ // FIXME: 10. Queue a control message to set the MessagePort on the AudioContextGlobalScope, with serializedRenderingSidePort.
+ Ok(c)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-offlineaudiocontext-numberofchannels-length-samplerate
+ pub(crate) fn construct_channels(
+ cx: &mut CallContext,
+ number_of_channels: u32,
+ length: u32,
+ sample_rate: f32,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::construct_options(
+ cx,
+ OfflineAudioContextOptions {
+ number_of_channels,
+ length,
+ sample_rate,
+ },
+ )
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-startrendering
+ pub(crate) fn start_rendering(&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.
+ if !self.context.document_is_fully_active() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Document is not fully active"),
+ ));
+ }
+
+ // AD-HOC: Not in spec explicitly, but this should account for detached iframes too. See /the-offlineaudiocontext-interface/startrendering-after-discard.html WPT.
+ if self.context.navigable_is_destroyed() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"The iframe has been detached"),
+ ));
+ }
+
+ // 2. If the [[rendering started]] slot on the OfflineAudioContext is true, return a rejected promise with InvalidStateError, and abort these steps.
+ if self.rendering_started.get() {
+ reject_promise_with_exception(
+ cx.vm(),
+ promise,
+ Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Rendering is already started"),
+ ),
+ );
+ return Ok(());
+ }
+
+ // 3. Set the [[rendering started]] slot of the OfflineAudioContext to true.
+ self.rendering_started.set(true);
+
+ // 5. Create a new AudioBuffer, with a number of channels, length and sample rate equal respectively to the
+ // numberOfChannels, length and sampleRate values passed to this instance’s constructor in the contextOptions
+ // parameter.
+ let buffer_result = self.context.create_buffer(
+ cx,
+ self.number_of_channels,
+ self.length,
+ self.context.sample_rate_value(),
+ );
+
+ // 6. If an exception was thrown during the preceding AudioBuffer constructor call, reject promise with this exception.
+ let buffer = match buffer_result {
+ Ok(buffer) => buffer,
+ Err(error) => {
+ reject_promise_with_exception(cx.vm(), promise, error);
+ return Ok(());
+ }
+ };
+
+ // Assign this buffer to an internal slot [[rendered buffer]] in the OfflineAudioContext.
+ self.rendered_buffer.set(Some(buffer));
+
+ // 7. Otherwise, in the case that the buffer was successfully constructed, begin offline rendering.
+ self.begin_offline_rendering(cx.vm(), promise);
+
+ // 8. Append promise to [[pending promises]].
+ self.context.pending_promises.borrow_mut(cx.vm()).push(promise);
+ Ok(())
+ }
+
+ 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.
+ let renderer = unsafe {
+ web_audio_offline_context_create(
+ Arc::as_ptr(self.context.control_message_queue()).cast(),
+ self.context.destination_value().parent().node_id(),
+ self.number_of_channels,
+ self.length,
+ self.context.sample_rate_value(),
+ )
+ };
+ *self.renderer.borrow_mut() = Some(SharedCppObject {
+ pointer: renderer.pointer,
+ retain: renderer.retain,
+ release: renderer.release,
+ });
+ unsafe {
+ web_audio_offline_context_set_callbacks(
+ renderer.pointer,
+ cell_into_abi(self.this()),
+ promise.as_ptr().cast(),
+ );
+ };
+ for (frame, _) in &*self.suspend_promises.borrow() {
+ unsafe { web_audio_offline_context_request_suspend(renderer.pointer, *frame) };
+ }
+
+ // AD-HOC: Other engines transition the context to "running" once rendering starts.
+ self.context.set_control_state(AudioContextState::Running);
+ self.context.set_rendering_state(AudioContextState::Running);
+ self.queue_a_statechange_event(vm);
+ unsafe { web_audio_offline_context_start(renderer.pointer) };
+ }
+
+ fn finish_rendering(&self, vm: &Vm, promise: WebIdlPromise) {
+ let buffer = self.rendered_buffer.get().expect("offline rendering has a buffer");
+ let mut cx = CallContext::new(vm, self.context.realm());
+ for channel_index in 0..self.number_of_channels {
+ let channel_data = AudioBuffer::get_channel_data(&buffer, &mut cx, channel_index)
+ .unwrap_or_else(|_| panic!("the rendered channel exists"));
+ let mut samples = ak::Span::default();
+ unsafe {
+ web_audio_offline_context_channel(
+ self.renderer.borrow().as_ref().unwrap().pointer,
+ channel_index as usize,
+ &raw mut samples,
+ );
+ };
+ overwrite_float32_array(&channel_data, samples.as_slice());
+ }
+
+ // AD-HOC: Other engines transition the context to "closed" once rendering completes.
+ self.context.set_control_state(AudioContextState::Closed);
+ self.context.set_rendering_state(AudioContextState::Closed);
+ self.queue_a_statechange_event(vm);
+ unsafe { web_audio_offline_context_clear_callbacks(self.renderer.borrow().as_ref().unwrap().pointer) };
+
+ // 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]].
+ resolve_promise(
+ vm,
+ promise,
+ buffer
+ .to_js(&CallContext::new(vm, realm))
+ .expect("an AudioBuffer wraps"),
+ );
+
+ // AD-HOC: Remove resolved promise from [[pending promises]]
+ // https://github.com/WebAudio/web-audio-api/issues/2648
+ 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]].
+ context.context.queue_a_media_element_task(vm, context, |vm, context| {
+ let event = CppEvent::create_for_owner(
+ context.context.realm(),
+ &Utf16String::from_ascii(b"complete"),
+ false,
+ false,
+ false,
+ );
+ let event =
+ OfflineAudioCompletionEvent::create(vm, event, context.rendered_buffer.get().unwrap());
+ context.context.event_target().dispatch_event(&event.event);
+ });
+ });
+ });
+ }
+
+ fn handle_suspended(&self, vm: &Vm, suspend_time: f64) {
+ self.context.set_control_state(AudioContextState::Suspended);
+ self.context.set_rendering_state(AudioContextState::Suspended);
+ let frame = (suspend_time * f64::from(self.context.sample_rate_value())).round() as u64;
+
+ // Suspensions take effect at the beginning of the first render quantum at
+ // or after the requested time. Keep the promise keyed by that same frame
+ // so the rendering-thread callback can resolve it when it reaches the
+ // boundary.
+ let quantum_size = u64::from(BaseAudioContext::RENDER_QUANTUM_SIZE);
+ let frame = (frame.wrapping_add(quantum_size - 1) / quantum_size) * quantum_size;
+ let suspend_promise = {
+ let mut promises = self.suspend_promises.borrow_mut(vm);
+ promises
+ .iter()
+ .position(|entry| entry.0 == frame)
+ .map(|index| promises.remove(index).1)
+ };
+ self.context.queue_a_media_element_task(
+ vm,
+ (self.this(), suspend_promise),
+ |vm, (context, suspend_promise)| {
+ with_temporary_execution_context_and_callbacks(context.context.realm(), || {
+ if let Some(promise) = suspend_promise {
+ resolve_promise(vm, promise, Value::UNDEFINED);
+ }
+ context.context.dispatch_statechange();
+ });
+ },
+ );
+ }
+
+ fn queue_a_statechange_event(&self, vm: &Vm) {
+ self.context.queue_a_media_element_task(vm, self.this(), |_, context| {
+ context.context.dispatch_statechange();
+ });
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-resume
+ pub(crate) fn resume(&self, cx: &mut CallContext, promise: WebIdlPromise) -> WebIdlResult<()> {
+ // FIXME: 1. If this’s relevant global object’s associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
+ // 2. Let promise be a new Promise.
+ // NB: The binding creates promise before calling this method.
+ // 3. Abort these steps and reject promise with InvalidStateError when any of following conditions is true:
+ if self.renderer.borrow().is_none() || self.context.state_value() != AudioContextState::Suspended {
+ reject_promise_with_exception(
+ cx.vm(),
+ promise,
+ Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"The OfflineAudioContext is not suspended"),
+ ),
+ );
+ return Ok(());
+ }
+ unsafe { web_audio_offline_context_resume(self.renderer.borrow().as_ref().unwrap().pointer) };
+ // 4. Set the [[control thread state]] flag on the OfflineAudioContext to running.
+ self.context.set_control_state(AudioContextState::Running);
+ self.context.set_rendering_state(AudioContextState::Running);
+ self.queue_a_statechange_event(cx.vm());
+
+ // 5. Queue a control message to resume the OfflineAudioContext.
+ resolve_promise(cx.vm(), promise, Value::UNDEFINED);
+
+ // 6. Return promise.
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-suspend
+ pub(crate) fn suspend(&self, cx: &mut CallContext, promise: WebIdlPromise, suspend_time: f64) -> WebIdlResult<()> {
+ if !suspend_time.is_finite() || suspend_time < 0. {
+ return Err(Exception::range_error(
+ "Suspend time must be a finite, non-negative number",
+ ));
+ }
+ let frame = (suspend_time * f64::from(self.context.sample_rate_value())).round() as u64;
+ let quantum_size = u64::from(BaseAudioContext::RENDER_QUANTUM_SIZE);
+ let frame = (frame.wrapping_add(quantum_size - 1) / quantum_size) * quantum_size;
+ if frame >= u64::from(self.length) {
+ return Err(Exception::range_error(
+ "Suspend time must be less than the duration of the context",
+ ));
+ }
+ if self.suspend_promises.borrow().iter().any(|entry| entry.0 == frame) {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"A suspension is already scheduled at this time"),
+ ));
+ }
+ self.suspend_promises.borrow_mut(cx.vm()).push((frame, promise));
+ if let Some(renderer) = &*self.renderer.borrow() {
+ if !unsafe { web_audio_offline_context_request_suspend(renderer.pointer, frame) } {
+ self.suspend_promises
+ .borrow_mut(cx.vm())
+ .retain(|entry| entry.0 != frame);
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"The rendering thread has already passed the requested suspend time"),
+ ));
+ }
+ }
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-currenttime
+ pub(crate) fn current_time_value(&self) -> f64 {
+ // This is the time in seconds of the sample frame immediately following the last sample-frame in the block of
+ // audio most recently processed by the context's rendering graph.
+ if let Some(renderer) = &*self.renderer.borrow() {
+ return unsafe { web_audio_offline_context_frames_rendered(renderer.pointer) } as f64
+ / f64::from(self.context.sample_rate_value());
+ }
+ 0.
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ // The size of the buffer in sample-frames. This is the same as the value of the length parameter for the constructor.
+ Ok(self.length)
+ }
+
+ pub(crate) fn document_became_inactive(&self) {
+ if let Some(renderer) = &*self.renderer.borrow() {
+ unsafe {
+ web_audio_offline_context_stop(renderer.pointer);
+ web_audio_offline_context_clear_callbacks(renderer.pointer);
+ }
+ }
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_offline_audio_context_complete(
+ vm: &Vm,
+ cell: *mut c_void,
+ promise: *mut c_void,
+) {
+ let context: Ref<OfflineAudioContext> = unsafe { cell_from_abi(cell) };
+ context.finish_rendering(vm, unsafe { promise_from_abi(promise) });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_offline_audio_context_suspended(vm: &Vm, cell: *mut c_void, time: f64) {
+ let context: Ref<OfflineAudioContext> = unsafe { cell_from_abi(cell) };
+ context.handle_suspended(vm, time);
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/oscillator_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/oscillator_node.rs
new file mode 100644
index 00000000000..e4d3003755f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/oscillator_node.rs
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2025, Tim Ledbetter <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::Cell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::control_message::ControlMessage;
+use libweb_rust::web_audio::rendering::node_message::{NodeMessage, SetOscillatorWaveform};
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_oscillator;
+
+use super::audio_node::{
+ AnyAudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::audio_param::{AudioParam, AutomationRate, FixedAutomationRate};
+use super::audio_scheduled_source_node::AudioScheduledSourceNode;
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use super::periodic_wave::PeriodicWave;
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+pub(crate) use libweb_rust::web_audio::rendering::node_message::OscillatorType;
+
+// https://webaudio.github.io/web-audio-api/#OscillatorNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct OscillatorNode {
+ node: AudioScheduledSourceNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-oscillatornode-type
+ #[gc(untraced)]
+ r#type: Cell<OscillatorType>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-oscillatornode-frequency
+ frequency: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-oscillatornode-detune
+ detune: Ref<AudioParam>,
+ periodic_wave: Cell<Option<Ref<PeriodicWave>>>,
+}
+
+impl Inherits<AudioScheduledSourceNode> for OscillatorNode {
+ fn parent(&self) -> &AudioScheduledSourceNode {
+ &self.node
+ }
+}
+
+impl Wrappable for OscillatorNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.parent().finalize_node();
+ }
+}
+
+impl GetTheParent for OscillatorNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct OscillatorOptions {
+ pub parent: AudioNodeOptions,
+ pub r#type: OscillatorType,
+ pub frequency: f32,
+ pub detune: f32,
+ pub periodic_wave: Option<Ref<PeriodicWave>>,
+}
+
+impl OscillatorNode {
+ fn queue_waveform_update(&self) {
+ let periodic_wave = self.periodic_wave.get().map(|wave| wave.render_data());
+ self.node
+ .parent()
+ .context_value()
+ .queue_control_message(ControlMessage::NodeMessage(NodeMessage::SetOscillatorWaveform(
+ SetOscillatorWaveform {
+ node_id: self.node.parent().node_id(),
+ r#type: self.r#type.get(),
+ periodic_wave,
+ },
+ )));
+ }
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &OscillatorOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioScheduledSourceNode::new(defer_gc, context),
+ r#type: Cell::new(options.r#type),
+ frequency: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.frequency,
+ -context.nyquist_frequency(),
+ context.nyquist_frequency(),
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ detune: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.detune,
+ -1200. * ak::math::log2(f32::MAX),
+ 1200. * ak::math::log2(f32::MAX),
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ periodic_wave: Cell::new(None),
+ });
+ node.node.parent().set_this(AnyAudioNode::OscillatorNode(node));
+ node.node.parent().event_target().set_owner(node);
+ node.frequency.set_owner(AnyAudioNode::OscillatorNode(node));
+ node.detune.set_owner(AnyAudioNode::OscillatorNode(node));
+ if options.r#type == OscillatorType::Custom {
+ node.set_periodic_wave_value(options.periodic_wave);
+ }
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#OscillatorNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::Max,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to no
+ node.node
+ .parent()
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ node.node.parent().queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_oscillator(
+ node.node.parent().node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ Arc::as_ptr(node.frequency.render_param()),
+ Arc::as_ptr(node.detune.render_param()),
+ ))
+ });
+ node.queue_waveform_update();
+ Ok(node)
+ }
+
+ pub(crate) fn validate_options(options: &OscillatorOptions) -> WebIdlResult<()> {
+ if options.r#type == OscillatorType::Custom && options.periodic_wave.is_none() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Oscillator node type 'custom' requires PeriodicWave to be provided"),
+ ));
+ }
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-oscillatornode-oscillatornode
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: OscillatorOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::validate_options(&options)?;
+ Self::create(cx, context, &options)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-oscillatornode-type
+ pub(crate) fn r#type(&self, _: &mut CallContext) -> WebIdlResult<OscillatorType> {
+ Ok(self.r#type.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-oscillatornode-type
+ pub(crate) fn set_type(&self, _: &mut CallContext, r#type: OscillatorType) -> WebIdlResult<()> {
+ if r#type == OscillatorType::Custom && self.r#type.get() != OscillatorType::Custom {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Oscillator node type cannot be changed to 'custom'"),
+ ));
+ }
+
+ // FIXME: An appropriate PeriodicWave should be set here based on the given type.
+ self.set_periodic_wave_value(None);
+ self.r#type.set(r#type);
+ self.queue_waveform_update();
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-oscillatornode-setperiodicwave
+ pub(crate) fn set_periodic_wave(&self, _: &mut CallContext, wave: Ref<PeriodicWave>) -> WebIdlResult<()> {
+ self.set_periodic_wave_value(Some(wave));
+ Ok(())
+ }
+
+ fn set_periodic_wave_value(&self, wave: Option<Ref<PeriodicWave>>) {
+ self.periodic_wave.set(wave);
+ self.r#type.set(OscillatorType::Custom);
+ self.queue_waveform_update();
+ }
+
+ pub(crate) fn frequency(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.frequency)
+ }
+
+ pub(crate) fn detune(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.detune)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/panner_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/panner_node.rs
new file mode 100644
index 00000000000..e9cc6c58882
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/panner_node.rs
@@ -0,0 +1,486 @@
+/*
+ * Copyright (c) 2024, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::Cell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::control_message::ControlMessage;
+use libweb_rust::web_audio::rendering::node_message::{NodeMessage, SetPannerParameters};
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_panner;
+
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::audio_param::{AudioParam, AutomationRate, FixedAutomationRate};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+pub(crate) use libweb_rust::web_audio::rendering::node_message::{DistanceModelType, PanningModelType};
+
+// https://webaudio.github.io/web-audio-api/#PannerNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct PannerNode {
+ node: AudioNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-panningmodel
+ #[gc(untraced)]
+ panning_model: Cell<PanningModelType>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-positionx
+ position_x: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-positiony
+ position_y: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-positionz
+ position_z: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-orientationx
+ orientation_x: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-orientationy
+ orientation_y: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-orientationz
+ orientation_z: Ref<AudioParam>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-distancemodel
+ #[gc(untraced)]
+ distance_model: Cell<DistanceModelType>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-refdistance
+ ref_distance: Cell<f64>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-maxdistance
+ max_distance: Cell<f64>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-rollofffactor
+ rolloff_factor: Cell<f64>,
+
+ cone_inner_angle: Cell<f64>,
+
+ cone_outer_angle: Cell<f64>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-coneoutergain
+ cone_outer_gain: Cell<f64>,
+}
+
+impl Inherits<AudioNode> for PannerNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for PannerNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for PannerNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct PannerOptions {
+ pub parent: AudioNodeOptions,
+ pub panning_model: PanningModelType,
+ pub distance_model: DistanceModelType,
+ pub ref_distance: f64,
+ pub max_distance: f64,
+ pub rolloff_factor: f64,
+ pub cone_inner_angle: f64,
+ pub cone_outer_angle: f64,
+ pub cone_outer_gain: f64,
+ pub position_x: f32,
+ pub position_y: f32,
+ pub position_z: f32,
+ pub orientation_x: f32,
+ pub orientation_y: f32,
+ pub orientation_z: f32,
+}
+
+impl PannerNode {
+ fn queue_panner_parameters_update(&self) {
+ self.node
+ .context_value()
+ .queue_control_message(ControlMessage::NodeMessage(NodeMessage::SetPannerParameters(
+ SetPannerParameters {
+ node_id: self.node.node_id(),
+ panning_model: self.panning_model.get(),
+ distance_model: self.distance_model.get(),
+ ref_distance: self.ref_distance.get(),
+ max_distance: self.max_distance.get(),
+ rolloff_factor: self.rolloff_factor.get(),
+ cone_inner_angle: self.cone_inner_angle.get(),
+ cone_outer_angle: self.cone_outer_angle.get(),
+ cone_outer_gain: self.cone_outer_gain.get(),
+ },
+ )));
+ }
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &PannerOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // Create the node and allocate memory
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ panning_model: Cell::new(options.panning_model),
+ position_x: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.position_x,
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ position_y: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.position_y,
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ position_z: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.position_z,
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ orientation_x: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.orientation_x,
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ orientation_y: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.orientation_y,
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ orientation_z: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.orientation_z,
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ distance_model: Cell::new(options.distance_model),
+ ref_distance: Cell::new(options.ref_distance),
+ max_distance: Cell::new(options.max_distance),
+ rolloff_factor: Cell::new(options.rolloff_factor),
+ cone_inner_angle: Cell::new(options.cone_inner_angle),
+ cone_outer_angle: Cell::new(options.cone_outer_angle),
+ cone_outer_gain: Cell::new(options.cone_outer_gain),
+ });
+ node.node.set_this(AnyAudioNode::PannerNode(node));
+ node.node.event_target().set_owner(node);
+ node.position_x.set_owner(AnyAudioNode::PannerNode(node));
+ node.position_y.set_owner(AnyAudioNode::PannerNode(node));
+ node.position_z.set_owner(AnyAudioNode::PannerNode(node));
+ node.orientation_x.set_owner(AnyAudioNode::PannerNode(node));
+ node.orientation_y.set_owner(AnyAudioNode::PannerNode(node));
+ node.orientation_z.set_owner(AnyAudioNode::PannerNode(node));
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#PannerNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::ClampedMax,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to maybe
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ let listener = context.listener_value();
+ let params = [
+ Arc::as_ptr(node.position_x.render_param()),
+ Arc::as_ptr(node.position_y.render_param()),
+ Arc::as_ptr(node.position_z.render_param()),
+ Arc::as_ptr(node.orientation_x.render_param()),
+ Arc::as_ptr(node.orientation_y.render_param()),
+ Arc::as_ptr(node.orientation_z.render_param()),
+ Arc::as_ptr(listener.position_x.render_param()),
+ Arc::as_ptr(listener.position_y.render_param()),
+ Arc::as_ptr(listener.position_z.render_param()),
+ Arc::as_ptr(listener.forward_x.render_param()),
+ Arc::as_ptr(listener.forward_y.render_param()),
+ Arc::as_ptr(listener.forward_z.render_param()),
+ Arc::as_ptr(listener.up_x.render_param()),
+ Arc::as_ptr(listener.up_y.render_param()),
+ Arc::as_ptr(listener.up_z.render_param()),
+ ];
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_panner(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ ak::Span::new(&params),
+ ))
+ });
+ node.queue_panner_parameters_update();
+ Ok(node)
+ }
+
+ pub(crate) fn validate_options(options: &PannerOptions) -> WebIdlResult<()> {
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-refdistance
+ // A RangeError exception MUST be thrown if this is set to a negative value.
+ if options.ref_distance < 0. {
+ return Err(Exception::range_error("refDistance cannot be negative"));
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-rollofffactor
+ // A RangeError exception MUST be thrown if this is set to a negative value.
+ if options.rolloff_factor < 0. {
+ return Err(Exception::range_error("rolloffFactor cannot be negative"));
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-maxdistance
+ // A RangeError exception MUST be thrown if this is set to a non-positive value.
+ if options.max_distance <= 0. {
+ return Err(Exception::range_error("maxDistance must be positive"));
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-coneoutergain
+ // It is a linear value (not dB) in the range [0, 1]. An InvalidStateError MUST be thrown if the parameter is outside this range.
+ if options.cone_outer_gain < 0. || options.cone_outer_gain > 1. {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"coneOuterGain must be in the range of [0, 1]"),
+ ));
+ }
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-pannernode
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: PannerOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::validate_options(&options)?;
+ Self::create(cx, context, &options)
+ }
+
+ pub(crate) fn position_x(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.position_x)
+ }
+
+ pub(crate) fn position_y(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.position_y)
+ }
+
+ pub(crate) fn position_z(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.position_z)
+ }
+
+ pub(crate) fn orientation_x(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.orientation_x)
+ }
+
+ pub(crate) fn orientation_y(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.orientation_y)
+ }
+
+ pub(crate) fn orientation_z(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.orientation_z)
+ }
+
+ pub(crate) fn panning_model(&self, _: &mut CallContext) -> WebIdlResult<PanningModelType> {
+ Ok(self.panning_model.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-panningmodel
+ pub(crate) fn set_panning_model(&self, _: &mut CallContext, value: PanningModelType) -> WebIdlResult<()> {
+ self.panning_model.set(value);
+ self.queue_panner_parameters_update();
+ Ok(())
+ }
+
+ pub(crate) fn distance_model(&self, _: &mut CallContext) -> WebIdlResult<DistanceModelType> {
+ Ok(self.distance_model.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-distancemodel
+ pub(crate) fn set_distance_model(&self, _: &mut CallContext, value: DistanceModelType) -> WebIdlResult<()> {
+ self.distance_model.set(value);
+ self.queue_panner_parameters_update();
+ Ok(())
+ }
+
+ pub(crate) fn ref_distance(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.ref_distance.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-refdistance
+ pub(crate) fn set_ref_distance(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {
+ // A RangeError exception MUST be thrown if this is set to a negative value.
+ if value < 0. {
+ return Err(Exception::range_error("refDistance cannot be negative"));
+ }
+ self.ref_distance.set(value);
+ self.queue_panner_parameters_update();
+ Ok(())
+ }
+
+ pub(crate) fn max_distance(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.max_distance.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-maxdistance
+ pub(crate) fn set_max_distance(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {
+ // A RangeError exception MUST be thrown if this is set to a non-positive value.
+ if value <= 0. {
+ return Err(Exception::range_error("maxDistance must be positive"));
+ }
+ self.max_distance.set(value);
+ self.queue_panner_parameters_update();
+ Ok(())
+ }
+
+ pub(crate) fn rolloff_factor(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.rolloff_factor.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-rollofffactor
+ pub(crate) fn set_rolloff_factor(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {
+ // A RangeError exception MUST be thrown if this is set to a negative value.
+ if value < 0. {
+ return Err(Exception::range_error("rolloffFactor cannot be negative"));
+ }
+ self.rolloff_factor.set(value);
+ self.queue_panner_parameters_update();
+ Ok(())
+ }
+
+ pub(crate) fn cone_inner_angle(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.cone_inner_angle.get())
+ }
+
+ pub(crate) fn set_cone_inner_angle(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {
+ self.cone_inner_angle.set(value);
+ self.queue_panner_parameters_update();
+ Ok(())
+ }
+
+ pub(crate) fn cone_outer_angle(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.cone_outer_angle.get())
+ }
+
+ pub(crate) fn set_cone_outer_angle(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {
+ self.cone_outer_angle.set(value);
+ self.queue_panner_parameters_update();
+ Ok(())
+ }
+
+ pub(crate) fn cone_outer_gain(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.cone_outer_gain.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-coneoutergain
+ pub(crate) fn set_cone_outer_gain(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {
+ // It is a linear value (not dB) in the range [0, 1]. An InvalidStateError MUST be thrown if the parameter is outside this range.
+ if value < 0. || value > 1. {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"coneOuterGain must be in the range of [0, 1]"),
+ ));
+ }
+ self.cone_outer_gain.set(value);
+ self.queue_panner_parameters_update();
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-setposition
+ pub(crate) fn set_position(&self, cx: &mut CallContext, x: f32, y: f32, z: f32) -> WebIdlResult<()> {
+ // This method is DEPRECATED. It is equivalent to setting positionX.value, positionY.value, and positionZ.value
+ // attribute directly with the x, y and z parameters, respectively.
+ // Consequently, if any of the positionX, positionY, and positionZ AudioParams have an automation curve set using
+ // setValueCurveAtTime() at the time this method is called, a NotSupportedError MUST be thrown.
+ AudioParam::set_value(&self.position_x, cx, x)?;
+ AudioParam::set_value(&self.position_y, cx, y)?;
+ AudioParam::set_value(&self.position_z, cx, z)?;
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-pannernode-setorientation
+ pub(crate) fn set_orientation(&self, cx: &mut CallContext, x: f32, y: f32, z: f32) -> WebIdlResult<()> {
+ // This method is DEPRECATED. It is equivalent to setting orientationX.value, orientationY.value, and
+ // orientationZ.value attribute directly, with the x, y and z parameters, respectively.
+ // Consequently, if any of the orientationX, orientationY, and orientationZ AudioParams have an automation curve set
+ // using setValueCurveAtTime() at the time this method is called, a NotSupportedError MUST be thrown.
+ AudioParam::set_value(&self.orientation_x, cx, x)?;
+ AudioParam::set_value(&self.orientation_y, cx, y)?;
+ AudioParam::set_value(&self.orientation_z, cx, z)?;
+ Ok(())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
+ pub(crate) fn set_channel_count_override(&self, _: &mut CallContext, channel_count: u32) -> WebIdlResult<()> {
+ if channel_count > 2 {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"PannerNode does not support channel count greater than 2"),
+ ));
+ }
+
+ self.node.set_channel_count_impl(channel_count)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
+ pub(crate) fn set_channel_count_mode_override(
+ &self,
+ _: &mut CallContext,
+ mode: ChannelCountMode,
+ ) -> WebIdlResult<()> {
+ if mode == ChannelCountMode::Max {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"PannerNode does not support 'max' as channelCountMode."),
+ ));
+ }
+
+ self.node.set_channel_count_mode_impl(mode)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/periodic_wave.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/periodic_wave.rs
index b225f346ab2..8ba3075af97 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/periodic_wave.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/periodic_wave.rs
@@ -12,15 +12,14 @@
)]
use std::cell::RefCell;
-use std::ffi::c_void;
use std::sync::Arc;
use ak::Utf16String;
-use libjs_rust::api::{ErrorKind, ErrorType, RawNativeFunctionResult, Trace, Value, Vm};
+use libjs_rust::api::{ErrorKind, ErrorType, Trace, Vm};
use libweb_rust::web_audio::rendering::audio_data::PeriodicWaveData;
-use crate::bindings::conversions::CppInterface;
-use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, realm_arguments};
+use super::base_audio_context::AnyBaseAudioContext;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
use crate::bindings::{CallContext, Exception, WebIdlResult};
pub(crate) struct PeriodicWaveConstraints {
@@ -83,7 +82,7 @@ fn zeroed_float_vector(vm: &Vm, size: usize) -> WebIdlResult<Vec<f32>> {
impl PeriodicWave {
pub(crate) fn construct(
cx: &mut CallContext,
- _context: CppInterface,
+ _context: AnyBaseAudioContext,
options: PeriodicWaveOptions,
) -> WebIdlResult<Ref<Self>> {
Self::create(cx, options)
@@ -181,43 +180,3 @@ impl PeriodicWave {
})
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_periodic_wave_create(
- vm: *mut c_void,
- realm: *mut c_void,
- has_real: bool,
- real: ak::Span<'_, f32>,
- has_imag: bool,
- imag: ak::Span<'_, f32>,
- disable_normalization: bool,
- output: *mut *mut c_void,
-) -> RawNativeFunctionResult {
- let (vm, realm) = unsafe { realm_arguments(vm, realm) };
- let mut cx = CallContext::new(vm, realm);
- let options = PeriodicWaveOptions {
- parent: PeriodicWaveConstraints { disable_normalization },
- real: has_real.then(|| real.as_slice().to_vec()),
- imag: has_imag.then(|| imag.as_slice().to_vec()),
- };
- let result = PeriodicWave::create(&mut cx, options).map(|wave| {
- unsafe {
- *output = cell_into_abi(wave);
- }
- Value::UNDEFINED
- });
- RawNativeFunctionResult::from_completion(result.map_err(|exception| exception.throw(&cx)))
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_periodic_wave_render_data(
- cell: *mut c_void,
- normalize: *mut bool,
-) -> *const PeriodicWaveData {
- let wave: Ref<PeriodicWave> = unsafe { cell_from_abi(cell) };
- let data = wave.render_data();
- unsafe {
- *normalize = data.normalize;
- }
- Arc::into_raw(data)
-}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/script_processor_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/script_processor_node.rs
new file mode 100644
index 00000000000..9b8339df7e9
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/script_processor_node.rs
@@ -0,0 +1,334 @@
+/*
+ * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::Cell;
+use std::cell::RefCell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libjs_rust::api::Vm;
+use libweb_rust::web_audio::control_message::FfiSharedCppObject;
+use libweb_rust::web_audio::rendering::node_message::SharedCppObject;
+use libweb_rust::web_audio::rendering::script_processor_pipe::{ScriptProcessorPipe, ScriptProcessorPipeConfig};
+use libweb_rust::web_audio::rendering::script_processor_render_node::web_audio_node_create_script_processor;
+
+use super::audio_buffer::AudioBuffer;
+use super::audio_node::{AnyAudioNode, AudioNode, ChannelCountMode};
+use super::audio_processing_event::AudioProcessingEvent;
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::CppEvent;
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::interface::{cell_from_abi, cell_into_abi, with_temporary_execution_context_and_callbacks};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#ScriptProcessorNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ScriptProcessorNode {
+ node: AudioNode,
+ #[gc(untraced)]
+ pipe: RefCell<Option<Arc<ScriptProcessorPipe>>>,
+ #[gc(untraced)]
+ pipe_service: RefCell<Option<SharedCppObject>>,
+ buffer_size: Cell<i32>,
+ number_of_input_channels: u8,
+ number_of_output_channels: u8,
+}
+
+impl Inherits<AudioNode> for ScriptProcessorNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for ScriptProcessorNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ if let Some(service) = &*node.pipe_service.borrow() {
+ unsafe { web_audio_script_processor_clear_callback(service.pointer) };
+ }
+ if let Some(pipe) = &*node.pipe.borrow() {
+ pipe.shut_down();
+ }
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for ScriptProcessorNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+unsafe extern "C" {
+ fn web_audio_script_processor_create_pipe(
+ node: *mut c_void,
+ config: ScriptProcessorPipeConfig,
+ pipe: *mut *const c_void,
+ ) -> FfiSharedCppObject;
+ fn web_audio_script_processor_clear_callback(service: *mut c_void);
+}
+
+// Other engines have a latency of two buffers. A realtime context needs more when the device pulls a burst of audio
+// that is longer than a buffer, since script cannot run in the middle of a burst.
+fn block_count_for_context(context: AnyBaseAudioContext, buffer_size: usize) -> usize {
+ if matches!(context, AnyBaseAudioContext::OfflineAudioContext(_)) {
+ return 2;
+ }
+ let quantum_size = BaseAudioContext::RENDER_QUANTUM_SIZE as usize;
+ let sizing = libweb_rust::web_audio::rendering::audio_worklet_pipe::ring_sizing_for_device_latency(
+ 100,
+ context.sample_rate_value(),
+ quantum_size,
+ );
+ let lookahead_frames = sizing.prime_level * quantum_size;
+ (lookahead_frames.div_ceil(buffer_size) + 1).max(2)
+}
+
+impl ScriptProcessorNode {
+ pub(crate) const DEFAULT_BUFFER_SIZE: i32 = 1024;
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ buffer_size: i32,
+ number_of_input_channels: u32,
+ number_of_output_channels: u32,
+ ) -> WebIdlResult<Ref<Self>> {
+ let script_processor_node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, number_of_input_channels as u8 as u32),
+ number_of_input_channels: number_of_input_channels as u8,
+ number_of_output_channels: number_of_output_channels as u8,
+ buffer_size: Cell::new(0),
+ pipe: RefCell::new(None),
+ pipe_service: RefCell::new(None),
+ });
+ script_processor_node
+ .node
+ .set_this(AnyAudioNode::ScriptProcessorNode(script_processor_node));
+ script_processor_node
+ .node
+ .event_target()
+ .set_owner(script_processor_node);
+ script_processor_node.buffer_size.set(buffer_size);
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
+ // The channel count mode cannot be changed from "explicit" and an NotSupportedError exception MUST be thrown for
+ // any attempt to change the value.
+ script_processor_node.set_channel_count_mode_override(cx, ChannelCountMode::Explicit)?;
+ let pipe_config = ScriptProcessorPipeConfig {
+ buffer_size: buffer_size as usize,
+ input_channel_count: number_of_input_channels as usize,
+ output_channel_count: number_of_output_channels as usize,
+ block_count: block_count_for_context(context, buffer_size as usize),
+ waits_for_processing: matches!(context, AnyBaseAudioContext::OfflineAudioContext(_)),
+ };
+ let mut native_pipe = std::ptr::null();
+ let service = unsafe {
+ web_audio_script_processor_create_pipe(
+ cell_into_abi(script_processor_node),
+ pipe_config,
+ &raw mut native_pipe,
+ )
+ };
+ let native_pipe = native_pipe.cast::<ScriptProcessorPipe>();
+ unsafe {
+ Arc::increment_strong_count(native_pipe);
+ }
+ let pipe = unsafe { Arc::from_raw(native_pipe) };
+ *script_processor_node.pipe_service.borrow_mut() = Some(SharedCppObject {
+ pointer: service.pointer,
+ retain: service.retain,
+ release: service.release,
+ });
+ *script_processor_node.pipe.borrow_mut() = Some(Arc::clone(&pipe));
+ context.add_script_processor_node(cx.vm(), script_processor_node);
+ script_processor_node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_script_processor(
+ script_processor_node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ Arc::as_ptr(&pipe),
+ ))
+ });
+ Ok(script_processor_node)
+ }
+
+ fn process_block(&self, vm: &Vm, block: usize, start_frame: u64) {
+ let pipe = self
+ .pipe
+ .borrow()
+ .as_ref()
+ .cloned()
+ .expect("a process callback has a pipe");
+ let config = pipe.config;
+ if !self.node.context_value().document_is_fully_active() {
+ unsafe { pipe.hand_block_back_to_rendering_thread(block, false) };
+ return;
+ }
+ let sample_rate = self.node.context_value().sample_rate_value();
+ let input_buffer = AudioBuffer::create(
+ vm,
+ config.input_channel_count as u32,
+ config.buffer_size as u32,
+ sample_rate,
+ )
+ .expect("input buffer allocation succeeds");
+ for channel in 0..config.input_channel_count {
+ let (destination, size) = input_buffer
+ .channel_data(channel as u32)
+ .unwrap_or_else(|_| panic!("the input channel exists"));
+ let (source, length) = unsafe { pipe.input_channel(block, channel) };
+ assert!(length * size_of::<f32>() <= size);
+ unsafe { std::ptr::copy_nonoverlapping(source.cast::<u8>(), destination, length * size_of::<f32>()) };
+ }
+ let output_buffer = AudioBuffer::create(
+ vm,
+ config.output_channel_count as u32,
+ config.buffer_size as u32,
+ sample_rate,
+ )
+ .expect("output buffer allocation succeeds");
+ let playback_time =
+ (start_frame + (config.block_count * config.buffer_size) as u64) as f64 / f64::from(sample_rate);
+ let realm = self.node.context_value().realm();
+ with_temporary_execution_context_and_callbacks(realm, || {
+ let event =
+ CppEvent::create_for_owner(realm, &Utf16String::from_ascii(b"audioprocess"), false, false, false);
+ let event = AudioProcessingEvent::create(vm, event, playback_time, input_buffer, output_buffer);
+ self.node.event_target().dispatch_event(&event.event);
+ });
+
+ // https://webaudio.github.io/web-audio-api/#acquire-the-content
+ // When the dispatch of an AudioProcessingEvent completes, it acquires the contents of its outputBuffer.
+ let Some(output) = AudioBuffer::acquire_contents(output_buffer, vm) else {
+ unsafe { pipe.hand_block_back_to_rendering_thread(block, false) };
+ return;
+ };
+ for channel in 0..config.output_channel_count {
+ let (destination, length) = unsafe { pipe.output_channel(block, channel) };
+ assert!(output.channels[channel].len() <= length);
+ unsafe {
+ std::ptr::copy_nonoverlapping(
+ output.channels[channel].as_ptr(),
+ destination,
+ output.channels[channel].len(),
+ );
+ };
+ }
+ unsafe { pipe.hand_block_back_to_rendering_thread(block, true) };
+ }
+
+ pub(crate) fn validate_options(
+ buffer_size: i32,
+ number_of_input_channels: u32,
+ number_of_output_channels: u32,
+ ) -> WebIdlResult<()> {
+ // https://webaudio.github.io/web-audio-api/#ScriptProcessorNode
+ // It is invalid for both numberOfInputChannels and numberOfOutputChannels to be zero. In this case an
+ // IndexSizeError MUST be thrown.
+ if number_of_input_channels == 0 && number_of_output_channels == 0 {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(
+ b"Number of input and output channels cannot both be zero in a ScriptProcessorNode",
+ ),
+ ));
+ }
+
+ // This parameter determines the number of channels for this node’s input. The default value is 2. Values of up to
+ // 32 must be supported. A NotSupportedError must be thrown if the number of channels is not supported.
+ if number_of_input_channels > BaseAudioContext::MAX_NUMBER_OF_CHANNELS {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"Invalid number of input channels"),
+ ));
+ }
+
+ // This parameter determines the number of channels for this node’s output. The default value is 2. Values of up to
+ // 32 must be supported. A NotSupportedError must be thrown if the number of channels is not supported.
+ if number_of_output_channels > BaseAudioContext::MAX_NUMBER_OF_CHANNELS {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"Invalid number of output channels"),
+ ));
+ }
+
+ // The size of the buffer (in sample-frames) which needs to be processed each time audioprocess is fired. Legal
+ // values are (256, 512, 1024, 2048, 4096, 8192, 16384).
+ //
+ // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createscriptprocessor
+ // If the value of this parameter is not one of the allowed power-of-2 values listed above, an IndexSizeError MUST
+ // be thrown.
+ if !matches!(buffer_size, 256 | 512 | 1024 | 2048 | 4096 | 8192 | 16384) {
+ return Err(Exception::Dom(
+ "IndexSizeError",
+ Utf16String::from_ascii(b"Unsupported buffer size for a ScriptProcessorNode"),
+ ));
+ }
+ Ok(())
+ }
+
+ pub(crate) fn buffer_size(&self, _: &mut CallContext) -> WebIdlResult<i32> {
+ Ok(self.buffer_size.get())
+ }
+
+ pub(crate) fn number_of_inputs_value(&self) -> u32 {
+ 1
+ }
+
+ pub(crate) fn number_of_outputs_value(&self) -> u32 {
+ 1
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
+ pub(crate) fn set_channel_count_override(&self, _: &mut CallContext, _: u32) -> WebIdlResult<()> {
+ // ScriptProcessorNode: The channel count cannot be changed, and an NotSupportedError exception MUST be thrown for
+ // any attempt to change the value.
+ Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Cannot modify channel count in a ScriptProcessorNode"),
+ ))
+ }
+
+ pub(crate) fn set_channel_count_mode_override(
+ &self,
+ _: &mut CallContext,
+ channel_count_mode: ChannelCountMode,
+ ) -> WebIdlResult<()> {
+ // https://webaudio.github.io/web-audio-api/#audionode-channelcountmode-constraints
+ // ScriptProcessorNode: The channel count mode cannot be changed from "explicit" and an NotSupportedError exception
+ // MUST be thrown for any attempt to change the value.
+ if channel_count_mode != ChannelCountMode::Explicit {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Channel count mode must be 'explicit'"),
+ ));
+ }
+
+ self.node.set_channel_count_mode_impl(channel_count_mode)
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_script_processor_process(
+ vm: &Vm,
+ cell: *mut c_void,
+ block: usize,
+ start_frame: u64,
+) {
+ let node: Ref<ScriptProcessorNode> = unsafe { cell_from_abi(cell) };
+ node.process_block(vm, block, start_frame);
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/stereo_panner_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/stereo_panner_node.rs
new file mode 100644
index 00000000000..174695037a5
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/stereo_panner_node.rs
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2025, Tim Ledbetter <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_stereo_panner;
+
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::audio_param::{AudioParam, AutomationRate, FixedAutomationRate};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+// https://webaudio.github.io/web-audio-api/#stereopannernode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct StereoPannerNode {
+ node: AudioNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-stereopannernode-pan
+ pan: Ref<AudioParam>,
+}
+
+impl Inherits<AudioNode> for StereoPannerNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for StereoPannerNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for StereoPannerNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct StereoPannerOptions {
+ pub parent: AudioNodeOptions,
+ pub pan: f32,
+}
+
+impl StereoPannerNode {
+ // https://webaudio.github.io/web-audio-api/#dom-stereopannernode-stereopannernode
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: StereoPannerOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, &options)
+ }
+
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &StereoPannerOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // Create the node and allocate memory
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ pan: AudioParam::create(
+ cx.vm(),
+ context,
+ None,
+ options.pan,
+ -1.,
+ 1.,
+ AutomationRate::ARate,
+ FixedAutomationRate::No,
+ ),
+ });
+ node.node.set_this(AnyAudioNode::StereoPannerNode(node));
+ node.node.event_target().set_owner(node);
+ node.pan.set_owner(AnyAudioNode::StereoPannerNode(node));
+
+ // Default options for channel count and interpretation
+ // https://webaudio.github.io/web-audio-api/#stereopannernode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::ClampedMax,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to no
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_stereo_panner(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ Arc::as_ptr(node.pan.render_param()),
+ ))
+ });
+ Ok(node)
+ }
+
+ pub(crate) fn pan(&self, _: &mut CallContext) -> WebIdlResult<Ref<AudioParam>> {
+ Ok(self.pan)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
+ pub(crate) fn set_channel_count_override(&self, _: &mut CallContext, channel_count: u32) -> WebIdlResult<()> {
+ // https://webaudio.github.io/web-audio-api/#audionode-channelcount-constraints
+ // The channel count cannot be greater than two, and a NotSupportedError exception MUST be thrown for any attempt to change it to a value greater than two.
+ if channel_count > 2 {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"StereoPannerNode does not support channel count greater than 2"),
+ ));
+ }
+
+ self.node.set_channel_count_impl(channel_count)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
+ pub(crate) fn set_channel_count_mode_override(
+ &self,
+ _: &mut CallContext,
+ mode: ChannelCountMode,
+ ) -> WebIdlResult<()> {
+ // https://webaudio.github.io/web-audio-api/#audionode-channelcountmode-constraints
+ // The channel count mode cannot be set to "max", and a NotSupportedError exception MUST be thrown for any attempt to set it to "max".
+ if mode == ChannelCountMode::Max {
+ return Err(Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_ascii(b"StereoPannerNode does not support 'max' as channelCountMode."),
+ ));
+ }
+
+ // If the mode is valid, call the base class implementation
+ self.node.set_channel_count_mode_impl(mode)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/wave_shaper_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/wave_shaper_node.rs
new file mode 100644
index 00000000000..7029a245575
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/wave_shaper_node.rs
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::Cell;
+use std::cell::RefCell;
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, Trace};
+use libjs_rust::api::{TypedArrayBase, TypedArrayKind, create_typed_array};
+use libweb_rust::web_audio::control_message::ControlMessage;
+use libweb_rust::web_audio::rendering::audio_data::WaveShaperCurve;
+use libweb_rust::web_audio::rendering::node_message::{NodeMessage, SetWaveShaperParameters};
+use libweb_rust::web_audio::rendering::render_nodes::web_audio_node_create_wave_shaper;
+
+use super::audio_array::{copy_float32_array, float32_array_length, overwrite_float32_array};
+use super::audio_node::{
+ AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,
+};
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
+use crate::bindings::event_target::{CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+pub(crate) use libweb_rust::web_audio::rendering::node_message::OverSampleType;
+
+// https://webaudio.github.io/web-audio-api/#WaveShaperNode
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WaveShaperNode {
+ node: AudioNode,
+
+ // https://webaudio.github.io/web-audio-api/#dom-waveshapernode-curve
+ curve: Cell<Option<Gc<TypedArrayBase>>>,
+
+ // When this attribute is set, an internal copy of the curve is created by the WaveShaperNode.
+ #[gc(untraced)]
+ curve_copy: RefCell<Option<Arc<WaveShaperCurve>>>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-waveshapernode-curve-set-slot
+ curve_set: Cell<bool>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-waveshapernode-oversample
+ #[gc(untraced)]
+ oversample: Cell<OverSampleType>,
+}
+
+impl Inherits<AudioNode> for WaveShaperNode {
+ fn parent(&self) -> &AudioNode {
+ &self.node
+ }
+}
+
+impl Wrappable for WaveShaperNode {
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.node.cpp_parent()
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(node: Ref<Self>) {
+ node.node.finalize_node();
+ }
+}
+
+impl GetTheParent for WaveShaperNode {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+pub(crate) struct WaveShaperOptions {
+ pub parent: AudioNodeOptions,
+ pub curve: Option<Vec<f32>>,
+ pub oversample: OverSampleType,
+}
+
+impl WaveShaperNode {
+ pub(crate) fn create(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: &WaveShaperOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // When the constructor is called with a BaseAudioContext c and an option object option, the user agent MUST
+ // initialize the AudioNode this, with context and options as arguments.
+ let node = allocate(cx.vm(), |defer_gc| Self {
+ node: AudioNode::new(defer_gc, context, 2),
+ curve: Cell::new(None),
+ curve_copy: RefCell::new(None),
+ curve_set: Cell::new(false),
+ oversample: Cell::new(OverSampleType::None),
+ });
+ node.node.set_this(AnyAudioNode::WaveShaperNode(node));
+ node.node.event_target().set_owner(node);
+
+ // https://webaudio.github.io/web-audio-api/#WaveShaperNode
+ let default_options = AudioNodeDefaultOptions {
+ channel_count: 2,
+ channel_count_mode: ChannelCountMode::Max,
+ channel_interpretation: ChannelInterpretation::Speakers,
+ };
+
+ // FIXME: Set tail-time to yes when the oversample attribute is "2x" or "4x".
+ node.node
+ .initialize_audio_node_options(cx, &options.parent, &default_options)?;
+ node.node.queue_render_node_creation(unsafe {
+ Box::from_raw(web_audio_node_create_wave_shaper(
+ node.node.node_id(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ ))
+ });
+ node.oversample.set(options.oversample);
+
+ // Also, let [[curve set]] be an internal slot of this WaveShaperNode. Initialize this slot to false. If options is
+ // given and specifies a curve, set [[curve set]] to true.
+ // NB: Setting the curve attribute to the curve of options sets [[curve set]] to true.
+ if let Some(curve) = &options.curve {
+ let array = create_typed_array(cx.vm(), context.realm(), TypedArrayKind::Float32Array, curve.len())?;
+ overwrite_float32_array(&array, curve);
+ node.set_curve(cx, Some(array))?;
+ } else {
+ node.send_parameters_to_render_node();
+ }
+ Ok(node)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-waveshapernode-waveshapernode
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ context: AnyBaseAudioContext,
+ options: WaveShaperOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, context, &options)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-waveshapernode-curve
+ pub(crate) fn set_curve(&self, _: &mut CallContext, new_curve: Option<Gc<TypedArrayBase>>) -> WebIdlResult<()> {
+ // A InvalidStateError MUST be thrown if this attribute is set with a Float32Array that has a length less than 2.
+ if new_curve.is_some_and(|curve| float32_array_length(&curve) < 2) {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"The curve must have at least two values"),
+ ));
+ }
+
+ // To set the curve attribute, execute these steps:
+ // 1. Let new curve be a Float32Array to be assigned to curve or null. .
+ // 2. If new curve is not null and [[curve set]] is true, throw an InvalidStateError and abort these steps.
+ if new_curve.is_some() && self.curve_set.get() {
+ return Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"The curve has already been set"),
+ ));
+ }
+
+ // 3. If new curve is not null, set [[curve set]] to true.
+ if new_curve.is_some() {
+ self.curve_set.set(true);
+ }
+
+ // 4. Assign new curve to the curve attribute.
+ self.curve.set(new_curve);
+
+ // When this attribute is set, an internal copy of the curve is created by the WaveShaperNode. Subsequent
+ // modifications of the contents of the array used to set the attribute therefore have no effect.
+ *self.curve_copy.borrow_mut() = new_curve.map(|curve| {
+ Arc::new(WaveShaperCurve {
+ values: copy_float32_array(&curve),
+ })
+ });
+ self.send_parameters_to_render_node();
+ Ok(())
+ }
+
+ pub(crate) fn curve(&self, _: &mut CallContext) -> WebIdlResult<Option<Gc<TypedArrayBase>>> {
+ Ok(self.curve.get())
+ }
+
+ pub(crate) fn oversample(&self, _: &mut CallContext) -> WebIdlResult<OverSampleType> {
+ Ok(self.oversample.get())
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-waveshapernode-oversample
+ pub(crate) fn set_oversample(&self, _: &mut CallContext, value: OverSampleType) -> WebIdlResult<()> {
+ self.oversample.set(value);
+ self.send_parameters_to_render_node();
+ Ok(())
+ }
+
+ fn send_parameters_to_render_node(&self) {
+ self.node
+ .context_value()
+ .queue_control_message(ControlMessage::NodeMessage(NodeMessage::SetWaveShaperParameters(
+ SetWaveShaperParameters {
+ node_id: self.node.node_id(),
+ curve: self.curve_copy.borrow().clone(),
+ oversample: self.oversample.get(),
+ },
+ )));
+ }
+}
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index b21d7e34d75..dba124b7191 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -925,41 +925,18 @@ set(SOURCES
WebLocks/NavigatorLocks.cpp
WebAssembly/WebAssembly.cpp
WebAudio/AnalyserNode.cpp
- WebAudio/AudioParamMap.cpp
WebAudio/AudioWorklet.cpp
WebAudio/AudioWorkletGlobalScope.cpp
WebAudio/AudioWorkletNode.cpp
WebAudio/AudioWorkletProcessor.cpp
- WebAudio/AudioArray.cpp
- WebAudio/AudioBuffer.cpp
- WebAudio/AudioBufferSourceNode.cpp
WebAudio/AudioContext.cpp
- WebAudio/AudioDestinationNode.cpp
- WebAudio/AudioListener.cpp
- WebAudio/AudioNode.cpp
- WebAudio/AudioParam.cpp
WebAudio/AudioParamTimeline.cpp
- WebAudio/AudioProcessingEvent.cpp
- WebAudio/AudioScheduledSourceNode.cpp
WebAudio/BaseAudioContext.cpp
- WebAudio/BiquadFilterNode.cpp
- WebAudio/ChannelMergerNode.cpp
- WebAudio/ChannelSplitterNode.cpp
- WebAudio/ConstantSourceNode.cpp
WebAudio/ControlMessageQueue.cpp
- WebAudio/ConvolverNode.cpp
- WebAudio/DelayNode.cpp
- WebAudio/DynamicsCompressorNode.cpp
- WebAudio/GainNode.cpp
- WebAudio/IIRFilterNode.cpp
WebAudio/MediaElementAudioSourceNode.cpp
WebAudio/MediaStreamAudioDestinationNode.cpp
WebAudio/MediaStreamAudioSourceNode.cpp
- WebAudio/OfflineAudioCompletionEvent.cpp
WebAudio/OfflineAudioContext.cpp
- WebAudio/OscillatorNode.cpp
- WebAudio/PannerNode.cpp
- WebAudio/PeriodicWave.cpp
WebAudio/Rendering/AnalyserRenderNode.cpp
WebAudio/Rendering/AudioData.cpp
WebAudio/Rendering/AudioBus.cpp
@@ -978,8 +955,6 @@ set(SOURCES
WebAudio/Rendering/ScriptProcessorPipe.cpp
WebAudio/Rendering/ScriptProcessorRenderNode.cpp
WebAudio/ScriptProcessorNode.cpp
- WebAudio/StereoPannerNode.cpp
- WebAudio/WaveShaperNode.cpp
WebDriver/Actions.cpp
WebDriver/BiDi/BiDi.cpp
WebDriver/BiDi/BrowsingContext.cpp
diff --git a/Libraries/LibWeb/HTML/EventLoop/Task.h b/Libraries/LibWeb/HTML/EventLoop/Task.h
index f78ded65aaf..f299f6e830a 100644
--- a/Libraries/LibWeb/HTML/EventLoop/Task.h
+++ b/Libraries/LibWeb/HTML/EventLoop/Task.h
@@ -9,6 +9,7 @@
#include <AK/DistinctNumeric.h>
#include <AK/IntrusiveList.h>
#include <AK/RefCounted.h>
+#include <AK/kmalloc.h>
#include <LibGC/CellAllocator.h>
#include <LibJS/Heap/Cell.h>
#include <LibWeb/Export.h>
@@ -149,6 +150,8 @@ public:
};
struct WEB_API UniqueTaskSource {
+ AK_ALLOC_WITH_KMALLOC;
+
UniqueTaskSource();
~UniqueTaskSource();
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/analyser_render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/analyser_render_node.rs
index 743dbe0e5b2..e5e8af0539b 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/analyser_render_node.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/analyser_render_node.rs
@@ -59,8 +59,10 @@ impl NodeProcessor for AnalyserRenderNode {
}
}
+/// # Safety
+/// The ring handle and callbacks must refer to the same live LibAudio ring.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_analyser(
+pub unsafe extern "C" fn web_audio_node_create_analyser(
node_id: u64,
quantum_size: usize,
ring: FfiSharedCppObject,
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_frame_ring.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_frame_ring.rs
index b2f6cda72d3..5f2ab8e0d4f 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_frame_ring.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_frame_ring.rs
@@ -18,7 +18,7 @@ pub struct AudioFrameRingCallbacks {
pub try_push: unsafe extern "C" fn(*mut c_void, ak::Span<'_, f32>) -> usize,
}
-pub(crate) struct AudioFrameRing {
+pub struct AudioFrameRing {
pub owner: SharedCppObject,
pub callbacks: AudioFrameRingCallbacks,
}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe.rs
index 6d22c5b4177..6fb287e13e4 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe.rs
@@ -37,15 +37,15 @@ pub struct Config {
}
#[repr(C)]
-pub struct WorkletPipeConfig {
+pub struct WorkletPipeConfig<'a> {
pub quantum_size: usize,
pub input_count: u32,
pub output_count: u32,
- pub input_channel_capacity: ak::Span<'static, u32>,
- pub output_channel_capacity: ak::Span<'static, u32>,
+ pub input_channel_capacity: ak::Span<'a, u32>,
+ pub output_channel_capacity: ak::Span<'a, u32>,
pub output_channel_count_matches_input: bool,
pub param_count: u32,
- pub param_is_a_rate: ak::Span<'static, bool>,
+ pub param_is_a_rate: ak::Span<'a, bool>,
pub ring_capacity: usize,
pub prime_level: usize,
}
@@ -274,7 +274,12 @@ impl AudioWorkletPipe {
.store(tail.wrapping_sub(target_occupancy), Ordering::Release);
}
- pub(crate) unsafe fn prime_outputs_with_silence(&self, count: usize) {
+ /// Pushes `count` silent, processor-active output quanta. Called on the control thread before the pipe is handed
+ /// to the render node, so the audio thread has a burst worth of lookahead before the first processed quantum.
+ ///
+ /// # Safety
+ /// The caller must be the sole producer of the output ring.
+ pub unsafe fn prime_outputs_with_silence(&self, count: usize) {
for _i in 0..count {
let pushed = unsafe {
self.try_push_output(|slot| {
@@ -406,14 +411,14 @@ impl AudioWorkletPipe {
}
}
-#[unsafe(no_mangle)]
-pub(crate) extern "C" fn web_audio_worklet_pipe_ring_sizing(
- device_latency_ms: u32,
- sample_rate: f32,
- quantum_size: usize,
- ring_capacity: *mut usize,
- prime_level: *mut usize,
-) {
+pub struct RingSizing {
+ pub ring_capacity: usize,
+ pub prime_level: usize,
+}
+
+// The renderer produces a device buffer's worth of quanta in one burst, so lookahead must cover a full burst plus
+// scheduling margin. At the 100 ms, 48 kHz defaults this is 38 quanta, a prime level of 48, and capacity 64.
+pub fn ring_sizing_for_device_latency(device_latency_ms: u32, sample_rate: f32, quantum_size: usize) -> RingSizing {
assert!(sample_rate > 0.);
assert!(quantum_size > 0);
let burst_quanta =
@@ -423,15 +428,32 @@ pub(crate) extern "C" fn web_audio_worklet_pipe_ring_sizing(
while capacity < prime + (burst_quanta / 4).max(1) {
capacity *= 2;
}
+ RingSizing {
+ ring_capacity: capacity,
+ prime_level: prime,
+ }
+}
+
+/// # Safety
+/// Both output pointers must point to writable `usize` slots.
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_ring_sizing(
+ device_latency_ms: u32,
+ sample_rate: f32,
+ quantum_size: usize,
+ ring_capacity: *mut usize,
+ prime_level: *mut usize,
+) {
+ let sizing = ring_sizing_for_device_latency(device_latency_ms, sample_rate, quantum_size);
unsafe {
- *ring_capacity = capacity;
- *prime_level = prime;
+ *ring_capacity = sizing.ring_capacity;
+ *prime_level = sizing.prime_level;
}
}
#[unsafe(no_mangle)]
pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_create(
- config: WorkletPipeConfig,
+ config: WorkletPipeConfig<'_>,
callbacks: PipeCallbacks,
) -> *const AudioWorkletPipe {
let config = Config {
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_render_node.rs
index 0b0a1be507c..0d3cb6439c6 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_render_node.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_render_node.rs
@@ -105,8 +105,10 @@ impl NodeProcessor for AudioWorkletRenderNode {
}
}
+/// # Safety
+/// The pipe and parameter pointers must name live `Arc` allocations for the call.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_audio_worklet(
+pub unsafe extern "C" fn web_audio_node_create_audio_worklet(
node_id: u64,
input_count: usize,
output_count: usize,
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/biquad_coefficients.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/biquad_coefficients.rs
index 55cd72eb0fc..e361f4cbb90 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/biquad_coefficients.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/biquad_coefficients.rs
@@ -7,7 +7,7 @@
use ak::math;
-#[derive(Clone, Copy)]
+#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum BiquadFilterType {
Lowpass,
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/media_stream_source_render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/media_stream_source_render_node.rs
index 188743d53d9..057d0653c73 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/media_stream_source_render_node.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/media_stream_source_render_node.rs
@@ -72,8 +72,10 @@ impl NodeProcessor for MediaStreamSourceRenderNode {
}
}
+/// # Safety
+/// The callbacks must accept the ring handles supplied in later node messages.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_media_stream_source(
+pub unsafe extern "C" fn web_audio_node_create_media_stream_source(
node_id: u64,
quantum_size: usize,
callbacks: AudioFrameRingCallbacks,
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 cb16bf45510..20cc61f36f7 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs
@@ -1824,7 +1824,7 @@ use crate::web_audio::control_message::clone_arc;
use ak::Span;
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_destination(
+pub extern "C" fn web_audio_node_create_destination(
node_id: u64,
quantum_size: usize,
channel_count: usize,
@@ -1835,8 +1835,10 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_destination(
node_handle(data, DestinationRenderNode)
}
+/// # Safety
+/// Parameter pointers must name live `Arc` allocations for the duration of the call.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_gain(
+pub unsafe extern "C" fn web_audio_node_create_gain(
node_id: u64,
quantum_size: usize,
gain: *const RenderAudioParam,
@@ -1851,8 +1853,10 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_gain(
)
}
+/// # Safety
+/// Parameter pointers must name live `Arc` allocations for the duration of the call.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_constant_source(
+pub unsafe extern "C" fn web_audio_node_create_constant_source(
node_id: u64,
quantum_size: usize,
offset: *const RenderAudioParam,
@@ -1868,8 +1872,10 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_constant_source(
)
}
+/// # Safety
+/// Parameter pointers must name live `Arc` allocations for the duration of the call.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_oscillator(
+pub unsafe extern "C" fn web_audio_node_create_oscillator(
node_id: u64,
quantum_size: usize,
frequency: *const RenderAudioParam,
@@ -1892,8 +1898,10 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_oscillator(
)
}
+/// # Safety
+/// Parameter pointers must name live `Arc` allocations for the duration of the call.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_audio_buffer_source(
+pub unsafe extern "C" fn web_audio_node_create_audio_buffer_source(
node_id: u64,
quantum_size: usize,
playback_rate: *const RenderAudioParam,
@@ -1921,8 +1929,10 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_audio_buffer_source(
)
}
+/// # Safety
+/// Parameter pointers must name live `Arc` allocations for the duration of the call.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_delay(
+pub unsafe extern "C" fn web_audio_node_create_delay(
node_id: u64,
quantum_size: usize,
delay_time: *const RenderAudioParam,
@@ -1941,8 +1951,10 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_delay(
)
}
+/// # Safety
+/// Parameter pointers must name live `Arc` allocations for the duration of the call.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_stereo_panner(
+pub unsafe extern "C" fn web_audio_node_create_stereo_panner(
node_id: u64,
quantum_size: usize,
pan: *const RenderAudioParam,
@@ -1959,7 +1971,7 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_stereo_panner(
}
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_channel_splitter(
+pub extern "C" fn web_audio_node_create_channel_splitter(
node_id: u64,
quantum_size: usize,
number_of_outputs: usize,
@@ -1972,7 +1984,7 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_channel_splitter(
}
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_channel_merger(
+pub extern "C" fn web_audio_node_create_channel_merger(
node_id: u64,
quantum_size: usize,
number_of_inputs: usize,
@@ -1983,8 +1995,10 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_channel_merger(
node_handle(data, ChannelMergerRenderNode)
}
+/// # Safety
+/// Parameter pointers must name live `Arc` allocations for the duration of the call.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_biquad_filter(
+pub unsafe extern "C" fn web_audio_node_create_biquad_filter(
node_id: u64,
quantum_size: usize,
frequency: *const RenderAudioParam,
@@ -2011,7 +2025,7 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_biquad_filter(
}
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_iir_filter(
+pub extern "C" fn web_audio_node_create_iir_filter(
node_id: u64,
quantum_size: usize,
feedforward: Span<'_, f64>,
@@ -2032,10 +2046,7 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_iir_filter(
}
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_wave_shaper(
- node_id: u64,
- quantum_size: usize,
-) -> *mut NodeHandle {
+pub extern "C" fn web_audio_node_create_wave_shaper(node_id: u64, quantum_size: usize) -> *mut NodeHandle {
let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
node_handle(
data,
@@ -2050,7 +2061,7 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_wave_shaper(
}
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_convolver(node_id: u64, quantum_size: usize) -> *mut NodeHandle {
+pub extern "C" fn web_audio_node_create_convolver(node_id: u64, quantum_size: usize) -> *mut NodeHandle {
let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
data.channel_count_mode.set(ChannelCountMode::ClampedMax);
node_handle(
@@ -2070,8 +2081,10 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_convolver(node_id: u64, qu
)
}
+/// # Safety
+/// Parameter pointers must name live `Arc` allocations for the duration of the call.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_panner(
+pub unsafe extern "C" fn web_audio_node_create_panner(
node_id: u64,
quantum_size: usize,
params: Span<'_, *const RenderAudioParam>,
@@ -2109,10 +2122,7 @@ pub(crate) unsafe extern "C" fn web_audio_node_create_panner(
}
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_passthrough(
- node_id: u64,
- quantum_size: usize,
-) -> *mut NodeHandle {
+pub extern "C" fn web_audio_node_create_passthrough(node_id: u64, quantum_size: usize) -> *mut NodeHandle {
let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
node_handle(data, PassthroughRenderNode)
}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_pipe.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_pipe.rs
index dfe71f5339f..d68a1bcba7b 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_pipe.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_pipe.rs
@@ -69,7 +69,9 @@ impl ScriptProcessorPipe {
}
}
- pub(crate) unsafe fn input_channel(&self, block: usize, channel: usize) -> (*mut f32, usize) {
+ /// # Safety
+ /// The caller must own the block until it finishes accessing the samples.
+ pub unsafe fn input_channel(&self, block: usize, channel: usize) -> (*mut f32, usize) {
assert!(block < self.config.block_count);
assert!(channel < self.config.input_channel_count);
let offset = (block * self.config.input_channel_count + channel) * self.config.buffer_size;
@@ -77,7 +79,9 @@ impl ScriptProcessorPipe {
(unsafe { samples.add(offset) }, self.config.buffer_size)
}
- pub(crate) unsafe fn output_channel(&self, block: usize, channel: usize) -> (*mut f32, usize) {
+ /// # Safety
+ /// The caller must own the block until it finishes accessing the samples.
+ pub unsafe fn output_channel(&self, block: usize, channel: usize) -> (*mut f32, usize) {
assert!(block < self.config.block_count);
assert!(channel < self.config.output_channel_count);
let offset = (block * self.config.output_channel_count + channel) * self.config.buffer_size;
@@ -127,7 +131,9 @@ impl ScriptProcessorPipe {
}
}
- pub(crate) unsafe fn hand_block_back_to_rendering_thread(&self, block: usize, has_output: bool) {
+ /// # Safety
+ /// The control thread must own the block and have finished accessing its samples.
+ pub unsafe fn hand_block_back_to_rendering_thread(&self, block: usize, has_output: bool) {
unsafe {
*self.blocks[block].has_output.get() = has_output;
}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_render_node.rs
index fffdf1e13d8..75c38ba16dc 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_render_node.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_render_node.rs
@@ -83,8 +83,10 @@ impl NodeProcessor for ScriptProcessorRenderNode {
}
}
+/// # Safety
+/// The pipe pointer must name a live `Arc` allocation for the call.
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_node_create_script_processor(
+pub unsafe extern "C" fn web_audio_node_create_script_processor(
node_id: u64,
quantum_size: usize,
pipe: *const ScriptProcessorPipe,
diff --git a/Libraries/LibWeb/WebAudio/AnalyserNode.cpp b/Libraries/LibWeb/WebAudio/AnalyserNode.cpp
index 6bb382f3d54..7295f1cd05a 100644
--- a/Libraries/LibWeb/WebAudio/AnalyserNode.cpp
+++ b/Libraries/LibWeb/WebAudio/AnalyserNode.cpp
@@ -1,404 +1,28 @@
/*
* Copyright (c) 2024, Noah Bright <[email protected]>
* Copyright (c) 2025, Tim Ledbetter <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Array.h>
-#include <AK/ByteBuffer.h>
-#include <AK/Math.h>
-#include <AK/Vector.h>
#include <LibAudio/SpscAudioFrameRing.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/WebAudio/AnalyserNode.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/Rendering/AnalyserRenderNode.h>
-#include <LibWeb/WebAudio/Rendering/FFT.h>
-#include <LibWeb/WebIDL/Buffers.h>
-#include <LibWeb/WebIDL/DOMException.h>
-#include <math.h>
+#include <LibWeb/WebAudio/RustFFI.h>
namespace Web::WebAudio {
-GC_DEFINE_ALLOCATOR(AnalyserNode);
-
-AnalyserNode::AnalyserNode(GC::Ref<BaseAudioContext> context, AnalyserOptions const& options)
- : AudioNode(context)
- , m_fft_size(options.fft_size)
- , m_max_decibels(options.max_decibels)
- , m_min_decibels(options.min_decibels)
- , m_smoothing_time_constant(options.smoothing_time_constant)
-{
-}
-
-AnalyserNode::~AnalyserNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<AnalyserNode>> AnalyserNode::create(GC::Ref<BaseAudioContext> context, AnalyserOptions const& options)
-{
- // When the constructor is called with a BaseAudioContext c and an option object option, the user agent
- // MUST initialize the AudioNode this, with context and options as arguments.
-
- auto node = GC::Heap::the().allocate<AnalyserNode>(context, options);
- node->set_fft_size_without_validation(options.fft_size);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#AnalyserNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count_mode = ChannelCountMode::Max;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- default_options.channel_count = 2;
- // FIXME: Set tail-time to no
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- node->m_history.resize(MAX_FFT_SIZE);
- node->m_time_domain_ring = adopt_ref(*new Audio::SpscAudioFrameRing(MAX_FFT_SIZE, 1));
- node->queue_render_node_creation(make<Rendering::AnalyserRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(), *node->m_time_domain_ring));
-
- return node;
-}
-
-void AnalyserNode::drain_time_domain_ring()
-{
- if (!m_time_domain_ring)
- return;
-
- // Ring pops are destructive, so everything the render thread has produced is folded into
- // the control-side history of the last MAX_FFT_SIZE sample-frames. Keeping the full
- // maximum window around means growing fftSize immediately exposes older data, as the
- // spec requires.
- Array<float, 1024> chunk;
- while (true) {
- auto frame_count = m_time_domain_ring->try_pop(chunk.span());
- if (frame_count == 0)
- break;
- for (size_t frame = 0; frame < frame_count; ++frame) {
- m_history[m_history_write_index] = chunk[frame];
- m_history_write_index = (m_history_write_index + 1) % m_history.size();
- }
- m_history_valid_frames = min(m_history.size(), m_history_valid_frames + frame_count);
- }
-}
-
-// https://webaudio.github.io/web-audio-api/#current-time-domain-data
-Vector<f32> AnalyserNode::current_time_domain_data()
-{
- // 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.
- drain_time_domain_ring();
-
- // The most recent fftSize frames are used for the down-mixing operation.
- Vector<f32> result;
- result.resize(m_fft_size);
- auto frames_available = min(static_cast<size_t>(m_fft_size), m_history_valid_frames);
- for (size_t frame = 0; frame < frames_available; ++frame) {
- auto history_index = (m_history_write_index + m_history.size() - frames_available + frame) % m_history.size();
- result[m_fft_size - frames_available + frame] = m_history[history_index];
- }
- return result;
-}
-
-// https://webaudio.github.io/web-audio-api/#blackman-window
-Vector<f32> AnalyserNode::apply_a_blackman_window(Vector<f32> const& x) const
+extern "C" RustFFI::FfiSharedCppObject web_audio_analyser_create_ring(RustFFI::AudioFrameRingCallbacks*);
+RustFFI::FfiSharedCppObject web_audio_analyser_create_ring(RustFFI::AudioFrameRingCallbacks* callbacks)
{
- f32 const a = 0.16;
- f32 const a0 = 0.5f * (1 - a);
- f32 const a1 = 0.5;
- f32 const a2 = a * 0.5f;
- unsigned long const N = m_fft_size;
-
- auto w = [&](unsigned long n) {
- return a0 - a1 * AK::cos(2 * AK::Pi<f32> * (f32)n / (f32)N) + a2 * AK::cos(4 * AK::Pi<f32> * (f32)n / (f32)N);
- };
-
- Vector<f32> x_hat;
- x_hat.resize(m_fft_size);
-
- // FIXME: Naive
- for (unsigned long i = 0; i < m_fft_size; i++) {
- x_hat[i] = x[i] * w(i);
+ auto* ring = new Audio::SpscAudioFrameRing(32768, 1);
+ *callbacks = {
+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->channel_count(); },
+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->frames_available(); },
+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->frames_free(); },
+ [](void* ring, Span<float> samples) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->try_pop(samples); },
+ [](void* ring, ReadonlySpan<float> samples) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->try_push(samples); },
};
-
- return x_hat;
-}
-
-// https://webaudio.github.io/web-audio-api/#fourier-transform
-//
-// Returns `bin_count` (= fftSize / 2) magnitude values normalized by fftSize, per the spec's
-// `(1/N) * |X[k]|` convention. The caller is expected to have applied a window already.
-static Vector<f32> apply_a_fourier_transform(Rendering::FFT const& fft, Vector<f32> const& input, size_t bin_count)
-{
- Vector<f32> magnitudes;
- magnitudes.resize(bin_count);
- if (input.is_empty())
- return magnitudes;
-
- auto n = input.size();
- Vector<float> re;
- Vector<float> im;
- re.resize(n);
- im.resize(n);
- for (size_t i = 0; i < n; ++i)
- re[i] = input[i];
-
- fft.transform(re, im);
-
- auto inv_n = 1.0f / static_cast<float>(n);
- for (size_t k = 0; k < bin_count && k < n; ++k)
- magnitudes[k] = AK::sqrt(re[k] * re[k] + im[k] * im[k]) * inv_n;
-
- return magnitudes;
-}
-
-// https://webaudio.github.io/web-audio-api/#smoothing-over-time
-Vector<f32> AnalyserNode::smoothing_over_time(Vector<f32> const& current_block)
-{
- // 1. Let X^−1[k] be the result of this operation on the previous block. The previous block is defined as being
- // the buffer computed by the previous smoothing over time operation, or an array of N zeros if this is the
- // first time we are smoothing over time.
- if (m_previous_block.size() != current_block.size()) {
- m_previous_block.clear();
- m_previous_block.resize(current_block.size());
- }
-
- // 2. Let τ be the value of the smoothingTimeConstant attribute for this AnalyserNode.
- auto tau = static_cast<f32>(m_smoothing_time_constant);
-
- // 3. Let X[k] be the result of applying a Fourier transform of the current block.
- Vector<f32> result;
- result.resize(current_block.size());
-
- // 4. Then the smoothed value, X^[k], is computed by X^[k] = τ * X^−1[k] + (1 − τ) * |X[k]|
- // If X^[k] is NaN, positive infinity or negative infinity, set X^[k] = 0.
- for (size_t i = 0; i < current_block.size(); ++i) {
- auto smoothed = tau * m_previous_block[i] + (1.0f - tau) * AK::fabs(current_block[i]);
- if (!isfinite(smoothed))
- smoothed = 0.0f;
- result[i] = smoothed;
- }
-
- m_previous_block = result;
- return result;
-}
-
-// https://webaudio.github.io/web-audio-api/#conversion-to-db
-Vector<f32> AnalyserNode::conversion_to_dB(Vector<f32> const& X_hat) const
-{
- // Y[k] = 20 log10 X^[k] for k = 0,…,N−1
- Vector<f32> result;
- result.ensure_capacity(X_hat.size());
- for (auto x : X_hat) {
- // NB: 20 * log10(0) is -∞. The byte-domain conversion clamps this later.
- if (x > 0.0f)
- result.unchecked_append(20.0f * AK::log10(x));
- else
- result.unchecked_append(-AK::Infinity<f32>);
- }
- return result;
-}
-
-// https://webaudio.github.io/web-audio-api/#current-frequency-data
-Vector<f32> AnalyserNode::current_frequency_data()
-{
- // If another call to getFloatFrequencyData() or getByteFrequencyData() occurs within the same render quantum
- // as a previous call, the current frequency data is not updated with the same data. Instead, the previously
- // computed data is returned.
- // AD-HOC: The control thread cannot observe render quantum boundaries directly; the context's currentTime,
- // which advances as quanta are rendered, stands in for the quantum stamp.
- auto current_time = context()->current_time();
- if (m_frequency_data_cache_time == current_time)
- return m_cached_frequency_data;
-
- // 1. Compute the current time-domain data.
- auto time_domain_data = current_time_domain_data();
-
- // 2. Apply a Blackman window to the time domain input data.
- auto windowed_input = apply_a_blackman_window(time_domain_data);
-
- // 3. Apply a Fourier transform to the windowed time domain input data to get real and imaginary frequency data.
- auto frequency_domain_data = apply_a_fourier_transform(*m_fft, windowed_input, frequency_bin_count());
-
- // 4. Smooth over time the frequency domain data.
- auto smoothed_data = smoothing_over_time(frequency_domain_data);
-
- // 5. Convert to dB.
- auto result = conversion_to_dB(smoothed_data);
-
- m_cached_frequency_data = result;
- m_frequency_data_cache_time = current_time;
- return result;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-analysernode-getfloatfrequencydata
-WebIDL::ExceptionOr<void> AnalyserNode::get_float_frequency_data(GC::Ref<JS::Float32Array> array)
-{
- // Write the current frequency data into array. If array has fewer elements than the frequencyBinCount,
- // the excess elements will be dropped. If array has more elements than the frequencyBinCount, the
- // excess elements will be ignored. The most recent fftSize frames are used in computing the frequency data.
- auto const frequency_data = current_frequency_data();
-
- auto record = JS::make_typed_array_with_buffer_witness_record(*array, JS::ArrayBuffer::Order::SeqCst);
- if (JS::is_typed_array_out_of_bounds(record))
- return {};
- auto floats_to_write = min(static_cast<size_t>(JS::typed_array_length(record)), static_cast<size_t>(frequency_bin_count()));
- array->viewed_array_buffer()->overwrite(array->byte_offset(), frequency_data.data(), floats_to_write * sizeof(float));
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-analysernode-getbytefrequencydata
-WebIDL::ExceptionOr<void> AnalyserNode::get_byte_frequency_data(GC::Ref<JS::Uint8Array> array)
-{
- Vector<f32> dB_data = current_frequency_data();
- Vector<u8> byte_data;
- byte_data.ensure_capacity(dB_data.size());
-
- // For getByteFrequencyData(), the 𝑌[𝑘] is clipped to lie between minDecibels and maxDecibels
- // and then scaled to fit in an unsigned byte such that minDecibels is represented by the
- // value 0 and maxDecibels is represented by the value 255.
- f32 delta_dB = m_max_decibels - m_min_decibels;
- for (auto x : dB_data) {
- x = max(x, m_min_decibels);
- x = min(x, m_max_decibels);
-
- byte_data.unchecked_append(static_cast<u8>(255 * (x - m_min_decibels) / delta_dB));
- }
-
- // Write the current frequency data into array. If array’s byte length is less than frequencyBinCount,
- // the excess elements will be dropped. If array’s byte length is greater than the frequencyBinCount ,
- // the excess elements will be ignored. The most recent fftSize frames are used in computing the frequency data.
- auto record = JS::make_typed_array_with_buffer_witness_record(*array, JS::ArrayBuffer::Order::SeqCst);
- if (JS::is_typed_array_out_of_bounds(record))
- return {};
- auto bytes_to_write = min(static_cast<size_t>(JS::typed_array_length(record)), static_cast<size_t>(frequency_bin_count()));
- array->viewed_array_buffer()->overwrite(array->byte_offset(), byte_data.data(), bytes_to_write);
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-analysernode-getfloattimedomaindata
-WebIDL::ExceptionOr<void> AnalyserNode::get_float_time_domain_data(GC::Ref<JS::Float32Array> array)
-{
- // Write the current time-domain data (waveform data) into array. If array has fewer elements than the
- // value of fftSize, the excess elements will be dropped. If array has more elements than the value of
- // fftSize, the excess elements will be ignored. The most recent fftSize frames are written (after downmixing).
-
- Vector<f32> time_domain_data = current_time_domain_data();
-
- auto record = JS::make_typed_array_with_buffer_witness_record(*array, JS::ArrayBuffer::Order::SeqCst);
- if (JS::is_typed_array_out_of_bounds(record))
- return {};
- auto floats_to_write = min(static_cast<size_t>(JS::typed_array_length(record)), static_cast<size_t>(fft_size()));
- array->viewed_array_buffer()->overwrite(array->byte_offset(), time_domain_data.data(), floats_to_write * sizeof(float));
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-analysernode-getbytetimedomaindata
-WebIDL::ExceptionOr<void> AnalyserNode::get_byte_time_domain_data(GC::Ref<JS::Uint8Array> array)
-{
- // Write the current time-domain data (waveform data) into array. If array’s byte length is less than
- // fftSize, the excess elements will be dropped. If array’s byte length is greater than the fftSize,
- // the excess elements will be ignored. The most recent fftSize frames are used in computing the byte data.
-
- Vector<f32> time_domain_data = current_time_domain_data();
- VERIFY(time_domain_data.size() == m_fft_size);
-
- Vector<u8> byte_data;
- byte_data.ensure_capacity(m_fft_size);
-
- for (size_t i = 0; i < m_fft_size; i++) {
- auto x = 128 * (1 + time_domain_data[i]);
- x = max(x, 0);
- x = min(x, 255);
- byte_data.unchecked_append(static_cast<u8>(x));
- }
-
- auto record = JS::make_typed_array_with_buffer_witness_record(*array, JS::ArrayBuffer::Order::SeqCst);
- if (JS::is_typed_array_out_of_bounds(record))
- return {};
- auto bytes_to_write = min(static_cast<size_t>(JS::typed_array_length(record)), static_cast<size_t>(fft_size()));
- array->viewed_array_buffer()->overwrite(array->byte_offset(), byte_data.data(), bytes_to_write);
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize
-void AnalyserNode::set_fft_size_without_validation(unsigned long fft_size)
-{
- // reset previous block to 0s
- m_previous_block = Vector<f32>();
- m_previous_block.resize(fft_size / 2);
-
- m_frequency_data_cache_time = {};
-
- m_fft_size = fft_size;
- m_fft = make<Rendering::FFT>(fft_size);
-
- // Note that increasing fftSize does mean that the current time-domain data must be expanded
- // 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.
-}
-
-WebIDL::ExceptionOr<void> AnalyserNode::set_fft_size(unsigned long fft_size)
-{
- if (fft_size < 32 || fft_size > MAX_FFT_SIZE || !is_power_of_two(fft_size))
- return WebIDL::IndexSizeError::create("Analyser node fftSize not a power of 2 between 32 and 32768"_utf16);
-
- set_fft_size_without_validation(fft_size);
-
- return {};
-}
-
-WebIDL::ExceptionOr<void> AnalyserNode::set_max_decibels(double max_decibels)
-{
- if (m_min_decibels >= max_decibels)
- return WebIDL::IndexSizeError::create("Analyser node minDecibels greater than maxDecibels"_utf16);
- m_max_decibels = max_decibels;
- return {};
-}
-
-WebIDL::ExceptionOr<void> AnalyserNode::set_min_decibels(double min_decibels)
-{
- if (min_decibels >= m_max_decibels)
- return WebIDL::IndexSizeError::create("Analyser node minDecibels greater than maxDecibels"_utf16);
-
- m_min_decibels = min_decibels;
- return {};
-}
-
-WebIDL::ExceptionOr<void> AnalyserNode::set_smoothing_time_constant(double smoothing_time_constant)
-{
- if (smoothing_time_constant > 1.0 || smoothing_time_constant < 0.0)
- return WebIDL::IndexSizeError::create("Analyser node smoothingTimeConstant not between 0.0 and 1.0"_utf16);
-
- m_smoothing_time_constant = smoothing_time_constant;
- return {};
-}
-
-WebIDL::ExceptionOr<void> AnalyserNode::validate_options(AnalyserOptions const& options)
-{
- if (options.min_decibels >= options.max_decibels)
- return WebIDL::IndexSizeError::create("Analyser node minDecibels greater than maxDecibels"_utf16);
-
- if (options.smoothing_time_constant > 1.0 || options.smoothing_time_constant < 0.0)
- return WebIDL::IndexSizeError::create("Analyser node smoothingTimeConstant not between 0.0 and 1.0"_utf16);
-
- if (options.fft_size < 32 || options.fft_size > MAX_FFT_SIZE || !is_power_of_two(options.fft_size))
- return WebIDL::IndexSizeError::create("Analyser node fftSize not a power of 2 between 32 and 32768"_utf16);
-
- return {};
-}
-
-WebIDL::ExceptionOr<GC::Ref<AnalyserNode>> AnalyserNode::create_for_constructor(GC::Ref<BaseAudioContext> context, AnalyserOptions const& options)
-{
- TRY(validate_options(options));
- return create(context, options);
+ return { ring, [](void* ring) { static_cast<Audio::SpscAudioFrameRing*>(ring)->ref(); }, [](void* ring) { static_cast<Audio::SpscAudioFrameRing*>(ring)->unref(); } };
}
}
diff --git a/Libraries/LibWeb/WebAudio/AnalyserNode.h b/Libraries/LibWeb/WebAudio/AnalyserNode.h
deleted file mode 100644
index 70bdc6922bd..00000000000
--- a/Libraries/LibWeb/WebAudio/AnalyserNode.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (c) 2024, Noah Bright <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/OwnPtr.h>
-#include <AK/RefPtr.h>
-#include <AK/Vector.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/AnalyserNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/Rendering/FFT.h>
-#include <LibWeb/WebIDL/Buffers.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Media {
-
-class SpscAudioFrameRing;
-
-}
-
-namespace Web::WebAudio {
-
-using AnalyserOptions = Bindings::AnalyserOptions;
-
-// https://webaudio.github.io/web-audio-api/#AnalyserNode
-class AnalyserNode : public AudioNode {
- WEB_WRAPPABLE(AnalyserNode, AudioNode);
- GC_DECLARE_ALLOCATOR(AnalyserNode);
-
-public:
- virtual ~AnalyserNode() override;
-
- virtual WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- virtual WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- WebIDL::ExceptionOr<void> get_float_frequency_data(GC::Ref<JS::Float32Array>);
- WebIDL::ExceptionOr<void> get_byte_frequency_data(GC::Ref<JS::Uint8Array>);
- WebIDL::ExceptionOr<void> get_float_time_domain_data(GC::Ref<JS::Float32Array>);
- WebIDL::ExceptionOr<void> get_byte_time_domain_data(GC::Ref<JS::Uint8Array>);
-
- unsigned long fft_size() const { return m_fft_size; }
- unsigned long frequency_bin_count() const { return m_fft_size / 2; }
- double max_decibels() const { return m_max_decibels; }
- double min_decibels() const { return m_min_decibels; }
- double smoothing_time_constant() const { return m_smoothing_time_constant; }
-
- WebIDL::ExceptionOr<void> set_fft_size(unsigned long);
- WebIDL::ExceptionOr<void> set_max_decibels(double);
- WebIDL::ExceptionOr<void> set_min_decibels(double);
- WebIDL::ExceptionOr<void> set_smoothing_time_constant(double);
-
- static WebIDL::ExceptionOr<GC::Ref<AnalyserNode>> create(GC::Ref<BaseAudioContext>, AnalyserOptions const& = {});
- static WebIDL::ExceptionOr<void> validate_options(AnalyserOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<AnalyserNode>> create_for_constructor(GC::Ref<BaseAudioContext>, AnalyserOptions const& = {});
-
-protected:
- AnalyserNode(GC::Ref<BaseAudioContext>, AnalyserOptions const& = {});
-
-private:
- // https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize
- // The maximum allowed fftSize; the node must keep this many past sample-frames around so
- // that growing fftSize immediately exposes older data.
- static constexpr unsigned long MAX_FFT_SIZE = 32768;
-
- unsigned long m_fft_size;
- OwnPtr<Rendering::FFT> m_fft;
- double m_max_decibels;
- double m_min_decibels;
- double m_smoothing_time_constant;
-
- void set_fft_size_without_validation(unsigned long);
-
- void drain_time_domain_ring();
-
- // https://webaudio.github.io/web-audio-api/#current-frequency-data
- Vector<f32> current_frequency_data();
-
- // https://webaudio.github.io/web-audio-api/#current-time-domain-data
- Vector<f32> current_time_domain_data();
-
- // https://webaudio.github.io/web-audio-api/#blackman-window
- Vector<f32> apply_a_blackman_window(Vector<f32> const& x) const;
-
- // https://webaudio.github.io/web-audio-api/#smoothing-over-time
- Vector<f32> smoothing_over_time(Vector<f32> const& current_block);
-
- // https://webaudio.github.io/web-audio-api/#previous-block
- Vector<f32> m_previous_block;
-
- // https://webaudio.github.io/web-audio-api/#conversion-to-db
- Vector<f32> conversion_to_dB(Vector<f32> const& X_hat) const;
-
- RefPtr<Audio::SpscAudioFrameRing> m_time_domain_ring;
-
- Vector<f32> m_history;
- size_t m_history_write_index { 0 };
- size_t m_history_valid_frames { 0 };
-
- // Frequency data computed within the current render quantum, per the spec's requirement
- // that repeated getter calls in one quantum return identical data.
- Vector<f32> m_cached_frequency_data;
- Optional<double> m_frequency_data_cache_time;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AnalyserNode.idl b/Libraries/LibWeb/WebAudio/AnalyserNode.idl
index f5dd3d2deb7..f7492b6ce0b 100644
--- a/Libraries/LibWeb/WebAudio/AnalyserNode.idl
+++ b/Libraries/LibWeb/WebAudio/AnalyserNode.idl
@@ -7,7 +7,7 @@ dictionary AnalyserOptions : AudioNodeOptions {
};
// https://webaudio.github.io/web-audio-api/#AnalyserNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface AnalyserNode : AudioNode {
constructor (BaseAudioContext context, optional AnalyserOptions options = {});
undefined getFloatFrequencyData (Float32Array array);
diff --git a/Libraries/LibWeb/WebAudio/AudioArray.cpp b/Libraries/LibWeb/WebAudio/AudioArray.cpp
deleted file mode 100644
index 26df1e682e7..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioArray.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/WebAudio/AudioArray.h>
-
-namespace Web::WebAudio {
-
-// The current element length of a Float32Array, or 0 if it is out of bounds of its backing ArrayBuffer.
-size_t float32_array_length(JS::Float32Array const& array)
-{
- auto record = JS::make_typed_array_with_buffer_witness_record(array, JS::ArrayBuffer::Order::SeqCst);
- if (JS::is_typed_array_out_of_bounds(record))
- return 0;
- return JS::typed_array_length(record);
-}
-
-// Snapshots the live contents of a Float32Array into an owned buffer.
-Vector<float> copy_float32_array(JS::Float32Array const& array)
-{
- auto length = float32_array_length(array);
- Vector<float> values;
- values.resize(length);
- array.viewed_array_buffer()->copy_to(array.byte_offset(), { reinterpret_cast<u8*>(values.data()), length * sizeof(float) });
- return values;
-}
-
-// Overwrites the leading elements of a Float32Array with the given samples.
-void overwrite_float32_array(JS::Float32Array& array, ReadonlySpan<float> values)
-{
- array.viewed_array_buffer()->overwrite(array.byte_offset(), values.data(), values.size() * sizeof(float));
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioArray.h b/Libraries/LibWeb/WebAudio/AudioArray.h
deleted file mode 100644
index 357a0db9d74..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioArray.h
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Span.h>
-#include <AK/Vector.h>
-#include <LibJS/Forward.h>
-
-namespace Web::WebAudio {
-
-// Utilities for moving sample data in and out of the Float32Arrays exposed by the Web Audio API. A Float32Array's
-// contents can change from JavaScript at any time, so audio data destined for the rendering thread is always snapshotted
-// into an owned buffer first.
-
-size_t float32_array_length(JS::Float32Array const&);
-Vector<float> copy_float32_array(JS::Float32Array const&);
-void overwrite_float32_array(JS::Float32Array&, ReadonlySpan<float>);
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioBuffer.cpp b/Libraries/LibWeb/WebAudio/AudioBuffer.cpp
deleted file mode 100644
index 1845d905114..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioBuffer.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/Realm.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/WebAudio/AudioBuffer.h>
-#include <LibWeb/WebIDL/DOMException.h>
-
-namespace Web::WebAudio {
-
-extern "C" {
-bool web_rust_audio_buffer_create(JSVM*, u32 channels, u32 length, float sample_rate, void**);
-float web_rust_audio_buffer_sample_rate(void*);
-u32 web_rust_audio_buffer_length(void*);
-u32 web_rust_audio_buffer_channel_count(void*);
-bool web_rust_audio_buffer_channel(void*, u32 channel, Bytes*);
-JSCompletion web_rust_audio_buffer_get_channel_data(JSVM*, void* realm, void* buffer, u32 channel);
-void const* web_rust_audio_buffer_acquire_contents(JSVM*, void* buffer);
-}
-
-ErrorOr<GC::Ref<AudioBuffer>> AudioBuffer::create(WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate)
-{
- void* buffer = nullptr;
- if (!web_rust_audio_buffer_create(JS::HostABI::vm_to_abi(JS::VM::the()), number_of_channels, length, sample_rate, &buffer))
- return Error::from_errno(ENOMEM);
- return GC::Ref { *static_cast<AudioBuffer*>(buffer) };
-}
-float AudioBuffer::sample_rate() const { return web_rust_audio_buffer_sample_rate(const_cast<AudioBuffer*>(this)); }
-u32 AudioBuffer::length() const { return web_rust_audio_buffer_length(const_cast<AudioBuffer*>(this)); }
-u32 AudioBuffer::number_of_channels() const { return web_rust_audio_buffer_channel_count(const_cast<AudioBuffer*>(this)); }
-double AudioBuffer::duration() const { return length() / static_cast<double>(sample_rate()); }
-WebIDL::ExceptionOr<Bytes> AudioBuffer::channel_data(WebIDL::UnsignedLong channel)
-{
- Bytes data;
- if (!web_rust_audio_buffer_channel(this, channel, &data))
- return WebIDL::IndexSizeError::create("Channel index is out of range"_utf16);
- return data;
-}
-WebIDL::ExceptionOr<GC::Ref<JS::Float32Array>> AudioBuffer::get_channel_data(JS::Object& relevant_global_object, WebIDL::UnsignedLong channel)
-{
- auto& realm = HTML::relevant_realm(relevant_global_object);
- auto result = TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_audio_buffer_get_channel_data(JS::HostABI::vm_to_abi(realm.vm()), &realm, this, channel)));
- return GC::Ref { static_cast<JS::Float32Array&>(result.as_object()) };
-}
-RefPtr<Rendering::AudioBufferContents> AudioBuffer::acquire_contents()
-{
- auto* contents = web_rust_audio_buffer_acquire_contents(JS::HostABI::vm_to_abi(JS::VM::the()), this);
- if (!contents)
- return nullptr;
- return make_ref_counted<Rendering::AudioBufferContents>(contents, number_of_channels(), sample_rate());
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioBuffer.h b/Libraries/LibWeb/WebAudio/AudioBuffer.h
deleted file mode 100644
index d214334aa80..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioBuffer.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Error.h>
-#include <AK/Span.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/AudioBuffer.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/WebAudio/Rendering/AudioData.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebAudio {
-
-class AudioBuffer final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(AudioBuffer, audio_buffer)
-
-public:
- static ErrorOr<GC::Ref<AudioBuffer>> create(WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate);
- float sample_rate() const;
- WebIDL::UnsignedLong length() const;
- double duration() const;
- WebIDL::UnsignedLong number_of_channels() const;
- WebIDL::ExceptionOr<Bytes> channel_data(WebIDL::UnsignedLong channel);
- WebIDL::ExceptionOr<GC::Ref<JS::Float32Array>> get_channel_data(JS::Object& relevant_global_object, WebIDL::UnsignedLong channel);
- RefPtr<Rendering::AudioBufferContents> acquire_contents();
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioBufferSourceNode.cpp b/Libraries/LibWeb/WebAudio/AudioBufferSourceNode.cpp
deleted file mode 100644
index 5d3db43967a..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioBufferSourceNode.cpp
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * Copyright (c) 2024, Bar Yemini <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/AudioBuffer.h>
-#include <LibWeb/WebAudio/AudioBufferSourceNode.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/AudioScheduledSourceNode.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(AudioBufferSourceNode);
-
-AudioBufferSourceNode::AudioBufferSourceNode(GC::Ref<BaseAudioContext> context, AudioBufferSourceOptions const& options)
- : AudioScheduledSourceNode(context)
- , m_buffer(options.buffer.value_or(nullptr))
- , m_playback_rate(AudioParam::create(context, this, options.playback_rate, NumericLimits<float>::lowest(), NumericLimits<float>::max(), AutomationRate::KRate, AudioParam::FixedAutomationRate::Yes))
- , m_detune(AudioParam::create(context, this, options.detune, NumericLimits<float>::lowest(), NumericLimits<float>::max(), AutomationRate::KRate, AudioParam::FixedAutomationRate::Yes))
- , m_loop(options.loop)
- , m_loop_start(options.loop_start)
- , m_loop_end(options.loop_end)
-{
-}
-
-AudioBufferSourceNode::~AudioBufferSourceNode() = default;
-
-void AudioBufferSourceNode::queue_parameters_update(RefPtr<Rendering::AudioBufferContents> buffer, bool update_buffer)
-{
- context()->queue_control_message(NodeMessage { SetBufferSourceParameters {
- .node_id = node_id(),
- .loop = m_loop,
- .loop_start = m_loop_start,
- .loop_end = m_loop_end,
- .buffer = move(buffer),
- .update_buffer = update_buffer,
- } });
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-buffer
-WebIDL::ExceptionOr<void> AudioBufferSourceNode::set_buffer(GC::Ptr<AudioBuffer> buffer)
-{
- // 1. Let new buffer be the AudioBuffer or null value to be assigned to buffer.
- auto new_buffer = buffer;
-
- // 2. If new buffer is not null and [[buffer set]] is true, throw an InvalidStateError and abort these steps.
- if (new_buffer && m_buffer_set)
- return WebIDL::InvalidStateError::create("Buffer has already been set"_utf16);
-
- // 3. If new buffer is not null, set [[buffer set]] to true.
- if (new_buffer)
- m_buffer_set = true;
-
- // 4. Assign new buffer to the buffer attribute.
- m_buffer = new_buffer;
-
- // 5. If start() has previously been called on this node, perform the operation acquire the content on buffer.
- if (source_started())
- queue_parameters_update(m_buffer ? m_buffer->acquire_contents() : nullptr, true);
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-buffer
-GC::Ptr<AudioBuffer> AudioBufferSourceNode::buffer() const
-{
- return m_buffer;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-playbackrate
-GC::Ref<AudioParam> AudioBufferSourceNode::playback_rate() const
-{
- return m_playback_rate;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-detune
-GC::Ref<AudioParam> AudioBufferSourceNode::detune() const
-{
- return m_detune;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loop
-WebIDL::ExceptionOr<void> AudioBufferSourceNode::set_loop(bool loop)
-{
- m_loop = loop;
- queue_parameters_update();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loop
-bool AudioBufferSourceNode::loop() const
-{
- return m_loop;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loopstart
-WebIDL::ExceptionOr<void> AudioBufferSourceNode::set_loop_start(double loop_start)
-{
- m_loop_start = loop_start;
- queue_parameters_update();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loopstart
-double AudioBufferSourceNode::loop_start() const
-{
- return m_loop_start;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loopend
-WebIDL::ExceptionOr<void> AudioBufferSourceNode::set_loop_end(double loop_end)
-{
- m_loop_end = loop_end;
- queue_parameters_update();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loopend
-double AudioBufferSourceNode::loop_end() const
-{
- return m_loop_end;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-start`
-WebIDL::ExceptionOr<void> AudioBufferSourceNode::start(Optional<double> when, Optional<double> offset, Optional<double> duration)
-{
- // 1. If this AudioBufferSourceNode internal slot [[source started]] is true, an InvalidStateError exception MUST be thrown.
- if (source_started())
- return WebIDL::InvalidStateError::create("AudioBufferSourceNode has already been started"_utf16);
-
- // 2. Check for any errors that must be thrown due to parameter constraints described below. If any exception is thrown during this step, abort those steps.
- // A RangeError exception MUST be thrown if when is negative.
- if (when.has_value() && when.value() < 0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "when must not be negative"_utf16 };
-
- // A RangeError exception MUST be thrown if offset is negative
- if (offset.has_value() && offset.value() < 0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "offset must not be negative"_utf16 };
-
- // A RangeError exception MUST be thrown if duration is negative.
- if (duration.has_value() && duration.value() < 0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "duration must not be negative"_utf16 };
-
- // 3. Set the internal slot [[source started]] on this AudioBufferSourceNode to true.
- set_source_started(true);
-
- // 4. Queue a control message to start the AudioBufferSourceNode, including the parameter values in the message.
- // 5. Acquire the contents of the buffer if the buffer has been set.
- RefPtr<Rendering::AudioBufferContents> contents;
- if (m_buffer)
- contents = m_buffer->acquire_contents();
- context()->queue_control_message(NodeMessage { StartBufferSource {
- .node_id = node_id(),
- .when = when.value_or(0),
- .offset = offset.value_or(0),
- .duration = duration,
- .buffer = move(contents),
- } });
- context()->add_playing_source(*this);
-
- // FIXME: 6. Send a control message to the associated AudioContext to start running its rendering thread only when all the following conditions are met:
-
- return {};
-}
-
-WebIDL::ExceptionOr<GC::Ref<AudioBufferSourceNode>> AudioBufferSourceNode::create(GC::Ref<BaseAudioContext> context, AudioBufferSourceOptions const& options)
-{
- // When the constructor is called with a BaseAudioContext c and an option object option, the user agent
- // MUST initialize the AudioNode this, with context and options as arguments.
-
- auto node = GC::Heap::the().allocate<AudioBufferSourceNode>(context, options);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#AudioBufferSourceNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count = 2;
- default_options.channel_count_mode = ChannelCountMode::Max;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- // FIXME: Set tail-time to no
-
- TRY(node->initialize_audio_node_options(AudioNodeOptions {}, default_options));
-
- node->queue_render_node_creation(make<Rendering::AudioBufferSourceRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(), node->m_playback_rate->render_param(), node->m_detune->render_param()));
- node->queue_parameters_update();
-
- return node;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-audiobuffersourcenode
-WebIDL::ExceptionOr<GC::Ref<AudioBufferSourceNode>> AudioBufferSourceNode::create_for_constructor(GC::Ref<BaseAudioContext> context, AudioBufferSourceOptions const& options)
-{
- return create(context, options);
-}
-
-void AudioBufferSourceNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_buffer);
- visitor.visit(m_playback_rate);
- visitor.visit(m_detune);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioBufferSourceNode.h b/Libraries/LibWeb/WebAudio/AudioBufferSourceNode.h
deleted file mode 100644
index 7cd373eccc0..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioBufferSourceNode.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2024, Bar Yemini <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/AudioBufferSourceNode.h>
-#include <LibWeb/WebAudio/AudioBuffer.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/AudioScheduledSourceNode.h>
-
-namespace Web::WebAudio {
-
-using AudioBufferSourceOptions = Bindings::AudioBufferSourceOptions;
-
-// https://webaudio.github.io/web-audio-api/#AudioBufferSourceNode
-class AudioBufferSourceNode : public AudioScheduledSourceNode {
- WEB_WRAPPABLE(AudioBufferSourceNode, AudioScheduledSourceNode);
- GC_DECLARE_ALLOCATOR(AudioBufferSourceNode);
-
-public:
- virtual ~AudioBufferSourceNode() override;
-
- WebIDL::ExceptionOr<void> set_buffer(GC::Ptr<AudioBuffer>);
- GC::Ptr<AudioBuffer> buffer() const;
- GC::Ref<AudioParam> playback_rate() const;
- GC::Ref<AudioParam> detune() const;
- WebIDL::ExceptionOr<void> set_loop(bool);
- bool loop() const;
- WebIDL::ExceptionOr<void> set_loop_start(double);
- double loop_start() const;
- WebIDL::ExceptionOr<void> set_loop_end(double);
- double loop_end() const;
- WebIDL::UnsignedLong number_of_inputs() override { return 0; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- WebIDL::ExceptionOr<void> start(Optional<double>, Optional<double>, Optional<double>);
-
- static WebIDL::ExceptionOr<GC::Ref<AudioBufferSourceNode>> create(GC::Ref<BaseAudioContext>, AudioBufferSourceOptions const& = {});
- static WebIDL::ExceptionOr<GC::Ref<AudioBufferSourceNode>> create_for_constructor(GC::Ref<BaseAudioContext>, AudioBufferSourceOptions const& = {});
-
-protected:
- AudioBufferSourceNode(GC::Ref<BaseAudioContext>, AudioBufferSourceOptions const& = {});
- virtual void visit_edges(Cell::Visitor&) override;
-
-private:
- void queue_parameters_update(RefPtr<Rendering::AudioBufferContents> = nullptr, bool update_buffer = false);
-
- GC::Ptr<AudioBuffer> m_buffer;
- GC::Ref<AudioParam> m_playback_rate;
- GC::Ref<AudioParam> m_detune;
- bool m_loop { false };
- // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-buffer-set-slot
- bool m_buffer_set { false };
- double m_loop_start { 0.0 };
- double m_loop_end { 0.0 };
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioBufferSourceNode.idl b/Libraries/LibWeb/WebAudio/AudioBufferSourceNode.idl
index 216e21fc70e..51a070954b9 100644
--- a/Libraries/LibWeb/WebAudio/AudioBufferSourceNode.idl
+++ b/Libraries/LibWeb/WebAudio/AudioBufferSourceNode.idl
@@ -8,7 +8,7 @@ dictionary AudioBufferSourceOptions {
};
// https://webaudio.github.io/web-audio-api/#AudioBufferSourceNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface AudioBufferSourceNode : AudioScheduledSourceNode {
constructor(BaseAudioContext context, optional AudioBufferSourceOptions options = {});
attribute AudioBuffer? buffer;
diff --git a/Libraries/LibWeb/WebAudio/AudioContext.cpp b/Libraries/LibWeb/WebAudio/AudioContext.cpp
index 32da77a219c..a9cac0876e2 100644
--- a/Libraries/LibWeb/WebAudio/AudioContext.cpp
+++ b/Libraries/LibWeb/WebAudio/AudioContext.cpp
@@ -1,409 +1,56 @@
/*
* Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
#include <LibMedia/Sinks/AudioOutputFactory.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/DOM/Document.h>
-#include <LibWeb/HTML/HTMLMediaElement.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/Performance.h>
#include <LibWeb/Page/Page.h>
-#include <LibWeb/WebAudio/AudioContext.h>
-#include <LibWeb/WebAudio/AudioDestinationNode.h>
-#include <LibWeb/WebIDL/Promise.h>
-
+#include <LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h>
+#include <LibWeb/WebAudio/RustFFI.h>
namespace Web::WebAudio {
-GC_DEFINE_ALLOCATOR(AudioContext);
-
-WebIDL::ExceptionOr<GC::Ref<AudioContext>> AudioContext::create_for_constructor(JS::Object& relevant_global_object, AudioContextOptions const& context_options)
-{
- auto& window = HTML::relevant_window(relevant_global_object);
- return create_for_constructor(window, HTML::relevant_settings_object(window), context_options);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiocontext-audiocontext
-WebIDL::ExceptionOr<GC::Ref<AudioContext>> AudioContext::create_for_constructor(GC::Ref<DOM::EventTarget> relevant_global_object, HTML::EnvironmentSettingsObject& settings, Optional<AudioContextOptions> const& context_options)
-{
- // If the current settings object’s responsible document is NOT fully active, throw an InvalidStateError and abort these steps.
- // FIXME: Not all settings objects currently return a responsible document.
- // Therefore we only fail this check if responsible document is not null.
- if (!settings.responsible_document() || !settings.responsible_document()->is_fully_active()) {
- return WebIDL::InvalidStateError::create("Document is not fully active"_utf16);
- }
-
- // AD-HOC: The spec doesn't currently require the sample rate to be validated here,
- // but other browsers do perform a check and there is a WPT test that expects this.
- if (context_options.has_value() && context_options->sample_rate.has_value())
- TRY(verify_audio_options_inside_nominal_range(*context_options->sample_rate));
-
- // 1. Let context be a new AudioContext object.
- auto context = GC::Heap::the().allocate<AudioContext>(relevant_global_object);
- context->set_listener(AudioListener::create(context));
- context->m_destination = TRY(AudioDestinationNode::create(context));
-
- // 2. Set a [[control thread state]] to suspended on context.
- context->set_control_state(AudioContextState::Suspended);
-
- // 3. Set a [[rendering thread state]] to suspended on context.
- context->set_rendering_state(AudioContextState::Suspended);
-
- // FIXME: 4. Let messageChannel be a new MessageChannel.
- // FIXME: 5. Let controlSidePort be the value of messageChannel’s port1 attribute.
- // FIXME: 6. Let renderingSidePort be the value of messageChannel’s port2 attribute.
- // FIXME: 7. Let serializedRenderingSidePort be the result of StructuredSerializeWithTransfer(renderingSidePort, « renderingSidePort »).
- // FIXME: 8. Set this audioWorklet's port to controlSidePort.
- // FIXME: 9. Queue a control message to set the MessagePort on the AudioContextGlobalScope, with serializedRenderingSidePort.
-
- // 10. If contextOptions is given, apply the options:
- if (context_options.has_value()) {
- // 1. If sinkId is specified, let sinkId be the value of contextOptions.sinkId and run the following substeps:
-
- // 2. Set the internal latency of context according to contextOptions.latencyHint, as described in latencyHint.
- // FIXME: Determine optimal settings for contextOptions.latencyHint.
-
- // 3: If contextOptions.sampleRate is specified, set the sampleRate of context to this value.
- if (context_options->sample_rate.has_value()) {
- context->set_sample_rate(context_options->sample_rate.value());
- }
- // Otherwise, follow these substeps:
- else {
- // FIXME: 1. If sinkId is the empty string or a type of AudioSinkOptions, use the sample rate of the default output device. Abort these substeps.
- // FIXME: 2. If sinkId is a DOMString, use the sample rate of the output device identified by sinkId. Abort these substeps.
- // If contextOptions.sampleRate differs from the sample rate of the output device, the user agent MUST resample the audio output to match the sample rate of the output device.
- context->set_sample_rate(44100);
- }
- }
-
- // AD-HOC: Ensure a sample rate is always set, even when no options were passed at all.
- if (context->sample_rate() == 0)
- context->set_sample_rate(44100);
-
- // 11. If context is allowed to start, send a control message to start processing.
- // FIXME: The context is currently always allowed to start; this should be gated on sticky activation.
- if (context->m_allowed_to_start) {
- // FIXME: 1. Let document be the current settings object's relevant global object's associated Document.
-
- // 2. Attempt to acquire system resources to use a following audio output device based on [[sink ID]] for
- // rendering.
- auto audio_output_factory = context->relevant_window().page().client().create_audio_output_factory();
- context->m_renderer = Rendering::RealtimeAudioRenderer::create(context->control_message_queue(), context->destination()->node_id(), context->sample_rate(), render_quantum_size(), move(audio_output_factory));
- context->set_renderer_callbacks();
- context->m_renderer->start_rendering();
-
- // 2. Set this [[rendering thread state]] to running on the AudioContext.
- context->set_rendering_state(AudioContextState::Running);
-
- // 3. Queue a media element task to execute the following steps:
- context->queue_a_media_element_task(GC::create_function(GC::Heap::the(), [context]() {
- // 1. Set the state attribute of the AudioContext to "running".
- context->set_control_state(AudioContextState::Running);
-
- // 2. Fire an event named statechange at the AudioContext.
- context->dispatch_event(context->create_associated_event(HTML::EventNames::statechange));
- }));
- }
-
- // 12. Return context.
- return context;
-}
-
-AudioContext::~AudioContext() = default;
-
-void AudioContext::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_pending_resume_promises);
-}
-
-void AudioContext::finalize()
-{
- Base::finalize();
- shutdown_audio_worklet();
- if (m_renderer) {
- m_renderer->stop();
- m_renderer->clear_callbacks();
- }
-}
-
-void AudioContext::document_became_inactive()
-{
- // Release the audio output device and the GC roots held by the renderer's callbacks, so a context belonging to a
- // navigated-away document stops playing and can eventually be collected.
- shutdown_audio_worklet();
- if (m_renderer) {
- m_renderer->stop();
- m_renderer->clear_callbacks();
- }
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-currenttime
-double AudioContext::current_time() const
-{
- // This is the time in seconds of the sample frame immediately following the last sample-frame in the block of
- // audio most recently processed by the context's rendering graph.
- if (m_renderer)
- return m_renderer->frames_rendered() / static_cast<double>(sample_rate());
- return Base::current_time();
-}
-
-// https://www.w3.org/TR/webaudio/#dom-audiocontext-getoutputtimestamp
-AudioTimestamp AudioContext::get_output_timestamp()
-{
- // If the context's rendering graph has not yet processed a block of audio, then
- // getOutputTimestamp call returns an AudioTimestamp instance with both members
- // containing zero.
- if (!m_renderer || m_renderer->frames_rendered() == 0) {
- return {
- .context_time = 0.0,
- .performance_time = 0.0,
- };
- }
- auto& window = relevant_window();
- // FIXME: performanceTime should be the moment the sample frame at contextTime was rendered by the output device.
- // We sample performance.now() when getOutputTimestamp() is called instead of caching a timestamp when the
- // renderer produced that block, so the returned pair does not describe a single output instant.
- return {
- .context_time = m_renderer->output_time_played(),
- .performance_time = window.performance()->now(),
- };
-}
-
-// https://www.w3.org/TR/webaudio/#dom-audiocontext-resume
-WebIDL::ExceptionOr<void> AudioContext::resume(GC::Ref<WebIDL::Promise> promise)
-{
- // 1. If this's relevant global object's associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
- auto const& associated_document = relevant_window().associated_document();
- if (!associated_document.is_fully_active())
- return WebIDL::InvalidStateError::create("Document is not fully active"_utf16);
-
- // 3. If the [[control thread state]] on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
- if (state() == AudioContextState::Closed) {
- WebIDL::reject_promise(promise, WebIDL::InvalidStateError::create("Audio context is already closed."_utf16));
- return {};
- }
-
- // 4. Set [[suspended by user]] to true.
- m_suspended_by_user = true;
-
- // 5. If the context is not allowed to start, append promise to [[pending promises]] and [[pending resume promises]] and abort these steps, returning promise.
- if (m_allowed_to_start) {
- m_pending_promises.append(promise);
- m_pending_resume_promises.append(promise);
- }
-
- // 6. Set the [[control thread state]] on the AudioContext to running.
- set_control_state(AudioContextState::Running);
-
- // 7. Queue a control message to resume the AudioContext.
- // 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.
- if (m_renderer)
- set_renderer_callbacks();
-
- // 7.2: Set the [[rendering thread state]] on the AudioContext to running.
- set_rendering_state(AudioContextState::Running);
-
- // 7.3: Start rendering the audio graph.
- if (!start_rendering_audio_graph()) {
- // 7.4: In case of failure, queue a media element task to execute the following steps:
- queue_a_media_element_task(GC::create_function(GC::Heap::the(), [this]() {
- // 7.4.1: Reject all promises from [[pending resume promises]] in order, then clear [[pending resume promises]].
- for (auto const& promise : m_pending_resume_promises) {
- auto& realm = WebIDL::promise_realm(promise);
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
- WebIDL::reject_promise(promise, JS::js_null());
-
- // 7.4.2: Additionally, remove those promises from [[pending promises]].
- m_pending_promises.remove_first_matching([&promise](auto& pending_promise) {
- return pending_promise == promise;
- });
- }
- m_pending_resume_promises.clear();
- }));
- }
-
- // 7.5: queue a media element task to execute the following steps:
- queue_a_media_element_task(GC::create_function(GC::Heap::the(), [promise, this]() {
- // 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]].
- for (auto const& pending_resume_promise : m_pending_resume_promises) {
- auto& realm = WebIDL::promise_realm(pending_resume_promise);
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
- WebIDL::resolve_promise(pending_resume_promise);
- m_pending_promises.remove_first_matching([&pending_resume_promise](auto& pending_promise) {
- return pending_promise == pending_resume_promise;
- });
- }
- m_pending_resume_promises.clear();
-
- // 7.5.3: Resolve promise.
- auto& realm = WebIDL::promise_realm(promise);
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
- WebIDL::resolve_promise(promise);
-
- // 7.5.4: If the state attribute of the AudioContext is not already "running":
- if (state() != AudioContextState::Running) {
- // 7.5.4.1: Set the state attribute of the AudioContext to "running".
- set_control_state(AudioContextState::Running);
-
- // 7.5.4.2: queue a media element task to fire an event named statechange at the AudioContext.
- queue_a_media_element_task(GC::create_function(GC::Heap::the(), [this]() {
- this->dispatch_event(create_associated_event(HTML::EventNames::statechange));
- }));
- }
- }));
- return {};
-}
-
-// https://www.w3.org/TR/webaudio/#dom-audiocontext-suspend
-WebIDL::ExceptionOr<void> AudioContext::suspend(GC::Ref<WebIDL::Promise> promise)
+extern "C" void web_rust_audio_context_sources_ended(JSVM*, void*, ReadonlySpan<u64>);
+extern "C" RustFFI::FfiSharedCppObject web_audio_realtime_context_create(DOM::EventTarget*, void const*, u64, float);
+extern "C" void web_audio_realtime_context_set_callbacks(Rendering::RealtimeAudioRenderer*, Bindings::RustInterfaceCell*);
+extern "C" double web_audio_realtime_context_performance_now(DOM::EventTarget*);
+RustFFI::FfiSharedCppObject web_audio_realtime_context_create(DOM::EventTarget* global, void const* queue, u64 destination, float sample_rate)
{
- // 1. If this's relevant global object's associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
- auto const& associated_document = relevant_window().associated_document();
- if (!associated_document.is_fully_active())
- return WebIDL::InvalidStateError::create("Document is not fully active"_utf16);
-
- // 3. If the [[control thread state]] on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
- if (state() == AudioContextState::Closed) {
- WebIDL::reject_promise(promise, WebIDL::InvalidStateError::create("Audio context is already closed."_utf16));
- return {};
- }
-
- // 4. Append promise to [[pending promises]].
- m_pending_promises.append(promise);
-
- // 5. Set [[suspended by user]] to true.
- m_suspended_by_user = true;
-
- // 6. Set the [[control thread state]] on the AudioContext to suspended.
- set_control_state(AudioContextState::Suspended);
-
- // 7. Queue a control message to suspend the AudioContext.
- // 7.1: Attempt to release system resources.
- if (m_renderer) {
- m_renderer->suspend();
- m_renderer->clear_callbacks();
- }
-
- // 7.2: Set the [[rendering thread state]] on the AudioContext to suspended.
- set_rendering_state(AudioContextState::Suspended);
-
- // 7.3: queue a media element task to execute the following steps:
- queue_a_media_element_task(GC::create_function(GC::Heap::the(), [promise, this]() {
- auto& realm = WebIDL::promise_realm(promise);
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
-
- // 7.3.1: Resolve promise.
- WebIDL::resolve_promise(promise);
-
- // 7.3.2: If the state attribute of the AudioContext is not already "suspended":
- if (state() != AudioContextState::Suspended) {
- // 7.3.2.1: Set the state attribute of the AudioContext to "suspended".
- set_control_state(AudioContextState::Suspended);
-
- // 7.3.2.2: queue a media element task to fire an event named statechange at the AudioContext.
- queue_a_media_element_task(GC::create_function(GC::Heap::the(), [this]() {
- this->dispatch_event(create_associated_event(HTML::EventNames::statechange));
- }));
- }
- }));
- return {};
+ auto factory = as<HTML::Window>(*global).page().client().create_audio_output_factory();
+ auto renderer = Rendering::RealtimeAudioRenderer::create(queue, NodeID(destination), sample_rate, 128, move(factory));
+ return { &renderer.leak_ref(), [](void* renderer) { static_cast<Rendering::RealtimeAudioRenderer*>(renderer)->ref(); }, [](void* renderer) { static_cast<Rendering::RealtimeAudioRenderer*>(renderer)->unref(); } };
}
-
-// https://www.w3.org/TR/webaudio/#dom-audiocontext-close
-WebIDL::ExceptionOr<void> AudioContext::close(GC::Ref<WebIDL::Promise> promise)
+void web_audio_realtime_context_set_callbacks(Rendering::RealtimeAudioRenderer* renderer, Bindings::RustInterfaceCell* context)
{
- // 1. If this's relevant global object's associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
- auto const& associated_document = relevant_window().associated_document();
- if (!associated_document.is_fully_active())
- return WebIDL::InvalidStateError::create("Document is not fully active"_utf16);
-
- // 3. If the [[control thread state]] flag on the AudioContext is closed reject the promise with InvalidStateError, abort these steps, returning promise.
- if (state() == AudioContextState::Closed) {
- WebIDL::reject_promise(promise, WebIDL::InvalidStateError::create("Audio context is already closed."_utf16));
- return {};
- }
-
- // 4. Set the [[control thread state]] flag on the AudioContext to closed.
- set_control_state(AudioContextState::Closed);
-
- // 5. Queue a control message to close the AudioContext.
- // 5.1: Attempt to release system resources.
- shutdown_audio_worklet();
- if (m_renderer) {
- m_renderer->stop();
- m_renderer->clear_callbacks();
- }
-
- // 5.2: Set the [[rendering thread state]] to "suspended".
- set_rendering_state(AudioContextState::Suspended);
-
- // FIXME: 5.3: If this control message is being run in a reaction to the document being unloaded, abort this algorithm.
-
- // 5.4: queue a media element task to execute the following steps:
- queue_a_media_element_task(GC::create_function(GC::Heap::the(), [promise, this]() {
- auto& realm = WebIDL::promise_realm(promise);
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
-
- // 5.4.1: Resolve promise.
- WebIDL::resolve_promise(promise);
-
- // 5.4.2: If the state attribute of the AudioContext is not already "closed":
- if (state() != AudioContextState::Closed) {
- // 5.4.2.1: Set the state attribute of the AudioContext to "closed".
- set_control_state(AudioContextState::Closed);
- }
-
- // 5.4.2.2: queue a media element task to fire an event named statechange at the AudioContext.
- // FIXME: Attempting to queue another task in here causes an assertion fail at Vector.h:148
- this->dispatch_event(create_associated_event(HTML::EventNames::statechange));
- }));
-
- return {};
-}
-
-bool AudioContext::start_rendering_audio_graph()
-{
- if (m_renderer)
- m_renderer->resume();
- return true;
-}
-
-// The renderer's callback captures a GC root on this context, keeping it alive while it renders. That root is released
-// by clearing the callbacks when the context is suspended, closed, or its document becomes inactive, so this is called
-// again to re-establish it whenever rendering resumes.
-void AudioContext::set_renderer_callbacks()
-{
- VERIFY(m_renderer);
- m_renderer->set_on_sources_ended([self = GC::make_root(*this)](Vector<NodeID> const& ended_nodes) {
- self->handle_ended_sources(ended_nodes);
+ renderer->set_on_sources_ended([context = GC::make_root(*context)](Vector<NodeID> const& nodes) {
+ Vector<u64> ids;
+ ids.ensure_capacity(nodes.size());
+ for (auto node : nodes)
+ ids.unchecked_append(node.value());
+ web_rust_audio_context_sources_ended(JS::HostABI::vm_to_abi(JS::VM::the()), context.ptr(), ids);
});
}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiocontext-createmediaelementsource
-WebIDL::ExceptionOr<GC::Ref<MediaElementAudioSourceNode>> AudioContext::create_media_element_source(GC::Ptr<HTML::HTMLMediaElement> media_element)
-{
- return MediaElementAudioSourceNode::create(*this, *media_element);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiocontext-createmediastreamsource
-WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioSourceNode>> AudioContext::create_media_stream_source(GC::Ptr<MediaCapture::MediaStream> media_stream)
-{
- MediaStreamAudioSourceOptions options { .media_stream = *media_stream };
- return MediaStreamAudioSourceNode::create(*this, options);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audiocontext-createmediastreamdestination
-WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioDestinationNode>> AudioContext::create_media_stream_destination()
-{
- return MediaStreamAudioDestinationNode::create(*this);
-}
+double web_audio_realtime_context_performance_now(DOM::EventTarget* global) { return as<HTML::Window>(*global).performance()->now(); }
+extern "C" void web_audio_realtime_context_start(Rendering::RealtimeAudioRenderer*);
+void web_audio_realtime_context_start(Rendering::RealtimeAudioRenderer* renderer) { renderer->start_rendering(); }
+extern "C" void web_audio_realtime_context_resume(Rendering::RealtimeAudioRenderer*);
+void web_audio_realtime_context_resume(Rendering::RealtimeAudioRenderer* renderer) { renderer->resume(); }
+extern "C" void web_audio_realtime_context_suspend(Rendering::RealtimeAudioRenderer*);
+void web_audio_realtime_context_suspend(Rendering::RealtimeAudioRenderer* renderer) { renderer->suspend(); }
+extern "C" void web_audio_realtime_context_stop(Rendering::RealtimeAudioRenderer*);
+void web_audio_realtime_context_stop(Rendering::RealtimeAudioRenderer* renderer) { renderer->stop(); }
+extern "C" void web_audio_realtime_context_clear_callbacks(Rendering::RealtimeAudioRenderer*);
+void web_audio_realtime_context_clear_callbacks(Rendering::RealtimeAudioRenderer* renderer) { renderer->clear_callbacks(); }
+extern "C" u64 web_audio_realtime_context_frames_rendered(Rendering::RealtimeAudioRenderer*);
+u64 web_audio_realtime_context_frames_rendered(Rendering::RealtimeAudioRenderer* renderer) { return renderer->frames_rendered(); }
+extern "C" double web_audio_realtime_context_output_time(Rendering::RealtimeAudioRenderer*);
+double web_audio_realtime_context_output_time(Rendering::RealtimeAudioRenderer* renderer) { return renderer->output_time_played(); }
}
diff --git a/Libraries/LibWeb/WebAudio/AudioContext.h b/Libraries/LibWeb/WebAudio/AudioContext.h
deleted file mode 100644
index 4eabc201720..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioContext.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (c) 2023, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/AudioContext.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/MediaElementAudioSourceNode.h>
-#include <LibWeb/WebAudio/MediaStreamAudioDestinationNode.h>
-#include <LibWeb/WebAudio/MediaStreamAudioSourceNode.h>
-#include <LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h>
-
-namespace Web::WebAudio {
-
-using AudioContextOptions = Bindings::AudioContextOptions;
-using AudioTimestamp = Bindings::AudioTimestamp;
-
-// https://webaudio.github.io/web-audio-api/#AudioContext
-class AudioContext final : public BaseAudioContext {
- WEB_WRAPPABLE(AudioContext, BaseAudioContext);
- GC_DECLARE_ALLOCATOR(AudioContext);
-
-public:
- static WebIDL::ExceptionOr<GC::Ref<AudioContext>> create_for_constructor(JS::Object&, AudioContextOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<AudioContext>> create_for_constructor(GC::Ref<DOM::EventTarget> relevant_global_object, HTML::EnvironmentSettingsObject&, Optional<AudioContextOptions> const& context_options = {});
-
- virtual ~AudioContext() override;
-
- virtual double current_time() const override;
-
- double base_latency() const { return m_base_latency; }
- double output_latency() const { return m_output_latency; }
- AudioTimestamp get_output_timestamp();
- WebIDL::ExceptionOr<void> resume(GC::Ref<WebIDL::Promise>);
- WebIDL::ExceptionOr<void> suspend(GC::Ref<WebIDL::Promise>);
- WebIDL::ExceptionOr<void> close(GC::Ref<WebIDL::Promise>);
-
- WebIDL::ExceptionOr<GC::Ref<MediaElementAudioSourceNode>> create_media_element_source(GC::Ptr<HTML::HTMLMediaElement>);
- WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioSourceNode>> create_media_stream_source(GC::Ptr<MediaCapture::MediaStream>);
- WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioDestinationNode>> create_media_stream_destination();
-
-private:
- explicit AudioContext(GC::Ref<DOM::EventTarget> relevant_global_object)
- : BaseAudioContext(relevant_global_object)
- {
- }
- virtual void visit_edges(Cell::Visitor&) override;
- virtual void finalize() override;
- virtual void document_became_inactive() override;
-
- double m_base_latency { 0 };
- double m_output_latency { 0 };
-
- bool m_allowed_to_start = true;
- Vector<GC::Ref<WebIDL::Promise>> m_pending_resume_promises;
- bool m_suspended_by_user = false;
-
- RefPtr<Rendering::RealtimeAudioRenderer> m_renderer;
-
- bool start_rendering_audio_graph();
- void set_renderer_callbacks();
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioContext.idl b/Libraries/LibWeb/WebAudio/AudioContext.idl
index b20b4716f48..185309d5e21 100644
--- a/Libraries/LibWeb/WebAudio/AudioContext.idl
+++ b/Libraries/LibWeb/WebAudio/AudioContext.idl
@@ -2,7 +2,7 @@
enum AudioContextLatencyCategory { "balanced", "interactive", "playback" };
// https://webaudio.github.io/web-audio-api/#AudioContext
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface AudioContext : BaseAudioContext {
constructor(optional AudioContextOptions contextOptions = {});
readonly attribute double baseLatency;
diff --git a/Libraries/LibWeb/WebAudio/AudioDestinationNode.cpp b/Libraries/LibWeb/WebAudio/AudioDestinationNode.cpp
deleted file mode 100644
index 21ad1a31fbf..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioDestinationNode.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2024, Bar Yemini <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/AudioContext.h>
-#include <LibWeb/WebAudio/AudioDestinationNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/OfflineAudioContext.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(AudioDestinationNode);
-
-AudioDestinationNode::AudioDestinationNode(GC::Ref<BaseAudioContext> context, WebIDL::UnsignedLong channel_count)
- : AudioNode(context, channel_count)
-{
-}
-
-AudioDestinationNode::~AudioDestinationNode() = default;
-
-// https://webaudio.github.io/web-audio-api/#dom-audiodestinationnode-maxchannelcount
-WebIDL::UnsignedLong AudioDestinationNode::max_channel_count()
-{
- // The maximum number of channels that the channelCount attribute can be set to. An AudioDestinationNode
- // representing the audio hardware end-point (the normal case) can potentially output more than 2 channels of
- // audio if the audio hardware is multi-channel. maxChannelCount is the maximum number of channels that this
- // hardware is capable of supporting.
- // NB: For an OfflineAudioContext, channelCount may not be changed, so the maximum equals the channel count the
- // context was constructed with. For an AudioContext, we follow the recommendation from the spec's privacy
- // considerations that maxChannelCount be set to two (stereo) instead of exposing the audio hardware's
- // actual capabilities.
- if (is<OfflineAudioContext>(*context()))
- return channel_count();
- return 2;
-}
-
-WebIDL::ExceptionOr<GC::Ref<AudioDestinationNode>> AudioDestinationNode::create(GC::Ref<BaseAudioContext> context, WebIDL::UnsignedLong channel_count)
-{
- auto node = GC::Heap::the().allocate<AudioDestinationNode>(context, channel_count);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#AudioDestinationNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count_mode = ChannelCountMode::Explicit;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- default_options.channel_count = channel_count;
- // FIXME: Set tail-time to no
-
- TRY(node->initialize_audio_node_options(AudioNodeOptions {}, default_options));
-
- node->queue_render_node_creation(make<Rendering::DestinationRenderNode>(node->node_id(), channel_count, BaseAudioContext::render_quantum_size()));
-
- return node;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
-WebIDL::ExceptionOr<void> AudioDestinationNode::set_channel_count(WebIDL::UnsignedLong channel_count)
-{
- if (channel_count == this->channel_count())
- return {};
-
- // The behavior depends on whether the destination node is the destination of an AudioContext
- // or OfflineAudioContext:
-
- // AudioContext: The channel count MUST be between 1 and maxChannelCount. An IndexSizeError
- // exception MUST be thrown for any attempt to set the count outside this range.
- // NB: Setting the count to zero throws NotSupportedError through AudioNode's channelCount validation below,
- // taking precedence over the range check here.
- if (is<AudioContext>(*context())) {
- if (channel_count > max_channel_count())
- return WebIDL::IndexSizeError::create("Channel index is out of range"_utf16);
- }
-
- // OfflineAudioContext: This value may not be changed; a NotSupportedError exception MUST be thrown if
- // channelCount is changed to a different value.
- if (is<OfflineAudioContext>(*context()))
- return WebIDL::InvalidStateError::create("Cannot change channel count in an OfflineAudioContext"_utf16);
-
- return AudioNode::set_channel_count(channel_count);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioDestinationNode.h b/Libraries/LibWeb/WebAudio/AudioDestinationNode.h
deleted file mode 100644
index 61970da2e88..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioDestinationNode.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2024, Bar Yemini <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Export.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebAudio {
-
-// https://webaudio.github.io/web-audio-api/#AudioDestinationNode
-class AudioDestinationNode : public AudioNode {
- WEB_WRAPPABLE(AudioDestinationNode, AudioNode);
- GC_DECLARE_ALLOCATOR(AudioDestinationNode);
-
-public:
- virtual ~AudioDestinationNode() override;
-
- WebIDL::UnsignedLong max_channel_count();
- WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
- WebIDL::ExceptionOr<void> set_channel_count(WebIDL::UnsignedLong) override;
-
- static WebIDL::ExceptionOr<GC::Ref<AudioDestinationNode>> create(GC::Ref<BaseAudioContext> context, WebIDL::UnsignedLong channel_count = 2);
-
-protected:
- AudioDestinationNode(GC::Ref<BaseAudioContext>, WebIDL::UnsignedLong channel_count);
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioDestinationNode.idl b/Libraries/LibWeb/WebAudio/AudioDestinationNode.idl
index df530d0020a..9a899f3fcda 100644
--- a/Libraries/LibWeb/WebAudio/AudioDestinationNode.idl
+++ b/Libraries/LibWeb/WebAudio/AudioDestinationNode.idl
@@ -1,5 +1,5 @@
// https://webaudio.github.io/web-audio-api/#AudioDestinationNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface AudioDestinationNode : AudioNode {
readonly attribute unsigned long maxChannelCount;
};
diff --git a/Libraries/LibWeb/WebAudio/AudioListener.cpp b/Libraries/LibWeb/WebAudio/AudioListener.cpp
deleted file mode 100644
index 393a50246dd..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioListener.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/WebAudio/AudioListener.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-
-namespace Web::WebAudio {
-
-extern "C" {
-void* web_rust_audio_listener_create(JSVM*, void* context);
-void* web_rust_audio_listener_param(void*, size_t index);
-}
-GC::Ref<AudioListener> AudioListener::create(GC::Ref<BaseAudioContext> context)
-{
- return *static_cast<AudioListener*>(web_rust_audio_listener_create(JS::HostABI::vm_to_abi(JS::VM::the()), context.ptr()));
-}
-GC::Ref<AudioParam> AudioListener::forward_x() const { return *static_cast<AudioParam*>(web_rust_audio_listener_param(const_cast<AudioListener*>(this), 0)); }
-GC::Ref<AudioParam> AudioListener::forward_y() const { return *static_cast<AudioParam*>(web_rust_audio_listener_param(const_cast<AudioListener*>(this), 1)); }
-GC::Ref<AudioParam> AudioListener::forward_z() const { return *static_cast<AudioParam*>(web_rust_audio_listener_param(const_cast<AudioListener*>(this), 2)); }
-GC::Ref<AudioParam> AudioListener::position_x() const { return *static_cast<AudioParam*>(web_rust_audio_listener_param(const_cast<AudioListener*>(this), 3)); }
-GC::Ref<AudioParam> AudioListener::position_y() const { return *static_cast<AudioParam*>(web_rust_audio_listener_param(const_cast<AudioListener*>(this), 4)); }
-GC::Ref<AudioParam> AudioListener::position_z() const { return *static_cast<AudioParam*>(web_rust_audio_listener_param(const_cast<AudioListener*>(this), 5)); }
-GC::Ref<AudioParam> AudioListener::up_x() const { return *static_cast<AudioParam*>(web_rust_audio_listener_param(const_cast<AudioListener*>(this), 6)); }
-GC::Ref<AudioParam> AudioListener::up_y() const { return *static_cast<AudioParam*>(web_rust_audio_listener_param(const_cast<AudioListener*>(this), 7)); }
-GC::Ref<AudioParam> AudioListener::up_z() const { return *static_cast<AudioParam*>(web_rust_audio_listener_param(const_cast<AudioListener*>(this), 8)); }
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioListener.h b/Libraries/LibWeb/WebAudio/AudioListener.h
deleted file mode 100644
index 58fde1964ac..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioListener.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/AudioListener.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-
-namespace Web::WebAudio {
-
-class AudioListener final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(AudioListener, audio_listener)
-
-public:
- static GC::Ref<AudioListener> create(GC::Ref<BaseAudioContext>);
- GC::Ref<AudioParam> forward_x() const;
- GC::Ref<AudioParam> forward_y() const;
- GC::Ref<AudioParam> forward_z() const;
- GC::Ref<AudioParam> position_x() const;
- GC::Ref<AudioParam> position_y() const;
- GC::Ref<AudioParam> position_z() const;
- GC::Ref<AudioParam> up_x() const;
- GC::Ref<AudioParam> up_y() const;
- GC::Ref<AudioParam> up_z() const;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioNode.cpp b/Libraries/LibWeb/WebAudio/AudioNode.cpp
deleted file mode 100644
index 1b4e939ea8e..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioNode.cpp
+++ /dev/null
@@ -1,380 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2025-2026, Ben Eidson <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/ControlMessage.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(AudioNode);
-
-AudioNode::AudioNode(GC::Ref<BaseAudioContext> context, WebIDL::UnsignedLong channel_count)
- : DOM::EventTarget()
- , m_context(context)
- , m_channel_count(channel_count)
- , m_node_id(context->next_node_id({}))
-
-{
-}
-
-AudioNode::~AudioNode() = default;
-
-// A node that is no longer reachable from script or the audio graph retires
-// its renderer node during finalization while the owning context is alive.
-void AudioNode::finalize()
-{
- Base::finalize();
- m_context->queue_control_message(RemoveNode { m_node_id });
-}
-
-JS::Object& AudioNode::relevant_global_object() const
-{
- return m_context->relevant_global_object();
-}
-
-void AudioNode::queue_render_node_creation(NonnullOwnPtr<Rendering::RenderNode> node)
-{
- context()->queue_control_message(AddNode { move(node) });
-
- // The channel configuration is settled before the render node is created, and the rendering thread ignores
- // messages for nodes it does not know about yet, so it has to be sent again now.
- queue_channel_config_update();
-}
-
-void AudioNode::queue_connection_update()
-{
- Vector<Rendering::RenderNode::OutgoingNodeConnection> node_connections;
- node_connections.ensure_capacity(m_output_connections.size());
- for (auto const& connection : m_output_connections)
- node_connections.unchecked_append({ connection.destination_node->node_id(), connection.output, connection.input });
-
- Vector<Rendering::RenderNode::OutgoingParamConnection> param_connections;
- param_connections.ensure_capacity(m_param_connections.size());
- for (auto const& connection : m_param_connections)
- param_connections.unchecked_append({ connection.destination_param->render_param(), connection.output });
-
- context()->queue_control_message(ReplaceConnections { node_id(), move(node_connections), move(param_connections) });
-}
-
-void AudioNode::queue_channel_config_update()
-{
- context()->queue_control_message(SetChannelConfig { node_id(), m_channel_count, m_channel_count_mode, m_channel_interpretation });
-}
-
-WebIDL::ExceptionOr<void> AudioNode::initialize_audio_node_options(AudioNodeOptions const& given_options, AudioNodeDefaultOptions const& default_options)
-{
- // Set channel count, fallback to default if not provided
- if (given_options.channel_count.has_value()) {
- TRY(set_channel_count(given_options.channel_count.value()));
- } else {
- TRY(set_channel_count(default_options.channel_count));
- }
-
- // Set channel count mode, fallback to default if not provided
- if (given_options.channel_count_mode.has_value()) {
- TRY(set_channel_count_mode(given_options.channel_count_mode.value()));
- } else {
- TRY(set_channel_count_mode(default_options.channel_count_mode));
- }
-
- // Set channel interpretation, fallback to default if not provided
- if (given_options.channel_interpretation.has_value()) {
- TRY(set_channel_interpretation(given_options.channel_interpretation.value()));
- } else {
- TRY(set_channel_interpretation(default_options.channel_interpretation));
- }
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-connect
-WebIDL::ExceptionOr<GC::Ref<AudioNode>> AudioNode::connect(GC::Ref<AudioNode> destination_node, WebIDL::UnsignedLong output, WebIDL::UnsignedLong input)
-{
- AudioNodeConnection output_connection { destination_node, output, input };
-
- // There can only be one connection between a given output of one specific node and a given input of another specific node.
- // Multiple connections with the same termini are ignored.
- for (auto const& existing_connection : m_output_connections) {
- if (existing_connection == output_connection)
- return destination_node;
- }
-
- // If the destination parameter is an AudioNode that has been created using another AudioContext, an InvalidAccessError MUST be thrown.
- if (m_context != destination_node->m_context) {
- return WebIDL::InvalidAccessError::create("Cannot connect to an AudioNode in a different AudioContext"_utf16);
- }
-
- // The output parameter is an index describing which output of the AudioNode from which to connect.
- // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
- if (output >= number_of_outputs()) {
- return WebIDL::IndexSizeError::create(Utf16String::formatted("Output index {} exceeds number of outputs", output));
- }
-
- // The input parameter is an index describing which input of the destination AudioNode to connect to.
- // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
- if (input >= destination_node->number_of_inputs()) {
- return WebIDL::IndexSizeError::create(Utf16String::formatted("Input index '{}' exceeds number of inputs", input));
- }
- // Connect node's output to destination_node input.
- m_output_connections.append(output_connection);
-
- queue_connection_update();
-
- return destination_node;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-connect-destinationparam-output
-WebIDL::ExceptionOr<void> AudioNode::connect(GC::Ref<AudioParam> destination_param, WebIDL::UnsignedLong output)
-{
- AudioParamConnection param_connection { destination_param, output };
-
- // There can only be one connection between a given output of one specific node and a specific AudioParam. Multiple connections
- // with the same termini are ignored.
- for (auto const& existing_connection : m_param_connections) {
- if (existing_connection == param_connection)
- return {};
- }
-
- // If destinationParam belongs to an AudioNode that belongs to a BaseAudioContext that is different from the BaseAudioContext
- // that has created the AudioNode on which this method was called, an InvalidAccessError MUST be thrown.
- if (m_context != destination_param->context()) {
- return WebIDL::InvalidAccessError::create("Cannot connect to an AudioParam in a different AudioContext"_utf16);
- }
-
- // The output parameter is an index describing which output of the AudioNode from which to connect.
- // If the parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
- if (output >= number_of_outputs()) {
- return WebIDL::IndexSizeError::create(Utf16String::formatted("Output index {} exceeds number of outputs", output));
- }
-
- // Connect node's output to destination_param.
- m_param_connections.append(param_connection);
-
- queue_connection_update();
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect
-void AudioNode::disconnect()
-{
- m_output_connections.clear();
- m_param_connections.clear();
-
- queue_connection_update();
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-output
-WebIDL::ExceptionOr<void> AudioNode::disconnect(WebIDL::UnsignedLong output)
-{
- // The output parameter is an index describing which output of the AudioNode to disconnect.
- // It disconnects all outgoing connections from the given output.
- // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
- if (output >= number_of_outputs()) {
- return WebIDL::IndexSizeError::create(Utf16String::formatted("Output index {} exceeds number of outputs", output));
- }
-
- m_output_connections.remove_all_matching([&](AudioNodeConnection& connection) {
- return connection.output == output;
- });
-
- m_param_connections.remove_all_matching([&](AudioParamConnection& connection) {
- return connection.output == output;
- });
-
- queue_connection_update();
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-destinationnode
-WebIDL::ExceptionOr<void> AudioNode::disconnect(GC::Ref<AudioNode> destination_node)
-{
- // The destinationNode parameter is the AudioNode to disconnect.
- // It disconnects all outgoing connections to the given destinationNode.
- auto before = m_output_connections.size();
- m_output_connections.remove_all_matching([&](AudioNodeConnection& connection) {
- return connection.destination_node == destination_node;
- });
- // If there is no connection to the destinationNode, an InvalidAccessError exception MUST be thrown.
- if (m_output_connections.size() == before) {
- return WebIDL::InvalidAccessError::create(Utf16String::formatted("No connection to given AudioNode"));
- }
-
- queue_connection_update();
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-destinationnode-output
-WebIDL::ExceptionOr<void> AudioNode::disconnect(GC::Ref<AudioNode> destination_node, WebIDL::UnsignedLong output)
-{
- // The output parameter is an index describing which output of the AudioNode from which to disconnect.
- // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
- if (output >= number_of_outputs()) {
- return WebIDL::IndexSizeError::create(Utf16String::formatted("Output index {} exceeds number of outputs", output));
- }
-
- // The destinationNode parameter is the AudioNode to disconnect.
- auto before = m_output_connections.size();
- m_output_connections.remove_all_matching([&](AudioNodeConnection& connection) {
- return connection.destination_node == destination_node && connection.output == output;
- });
-
- // If there is no connection to the destinationNode from the given output, an InvalidAccessError exception MUST be thrown.
- if (m_output_connections.size() == before) {
- return WebIDL::InvalidAccessError::create(Utf16String::formatted("No connection from output {} to given AudioNode", output));
- }
-
- queue_connection_update();
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-destinationnode-output-input
-WebIDL::ExceptionOr<void> AudioNode::disconnect(GC::Ref<AudioNode> destination_node, WebIDL::UnsignedLong output, WebIDL::UnsignedLong input)
-{
- // The output parameter is an index describing which output of the AudioNode from which to disconnect.
- // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
- if (output >= number_of_outputs()) {
- return WebIDL::IndexSizeError::create(Utf16String::formatted("Output index {} exceeds number of outputs", output));
- }
-
- // The input parameter is an index describing which input of the destination AudioNode to disconnect.
- // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
- if (input >= destination_node->number_of_inputs()) {
- return WebIDL::IndexSizeError::create(Utf16String::formatted("Input index '{}' exceeds number of inputs", input));
- }
-
- // The destinationNode parameter is the AudioNode to disconnect.
- auto before = m_output_connections.size();
- m_output_connections.remove_all_matching([&](AudioNodeConnection& connection) {
- return connection.destination_node == destination_node && connection.output == output && connection.input == input;
- });
-
- // If there is no connection to the destinationNode from the given output to the given input, an InvalidAccessError exception MUST be thrown.
- if (m_output_connections.size() == before) {
- return WebIDL::InvalidAccessError::create(Utf16String::formatted("No connection from output {} to input {} of given AudioNode", output, input));
- }
-
- queue_connection_update();
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-destinationparam
-WebIDL::ExceptionOr<void> AudioNode::disconnect(GC::Ref<AudioParam> destination_param)
-{
- // The destinationParam parameter is the AudioParam to disconnect.
- auto before = m_param_connections.size();
- m_param_connections.remove_all_matching([&](AudioParamConnection& connection) {
- return connection.destination_param == destination_param;
- });
-
- // If there is no connection to the destinationParam, an InvalidAccessError exception MUST be thrown.
- if (m_param_connections.size() == before) {
- return WebIDL::InvalidAccessError::create(Utf16String::formatted("No connection to given AudioParam"));
- }
-
- queue_connection_update();
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-disconnect-destinationparam-output
-WebIDL::ExceptionOr<void> AudioNode::disconnect(GC::Ref<AudioParam> destination_param, WebIDL::UnsignedLong output)
-{
- // The output parameter is an index describing which output of the AudioNode from which to disconnect.
- // If this parameter is out-of-bounds, an IndexSizeError exception MUST be thrown.
- if (output >= number_of_outputs()) {
- return WebIDL::IndexSizeError::create(Utf16String::formatted("Output index {} exceeds number of outputs", output));
- }
- // The destinationParam parameter is the AudioParam to disconnect.
- auto before = m_param_connections.size();
- m_param_connections.remove_all_matching([&](AudioParamConnection& connection) {
- return connection.destination_param == destination_param && connection.output == output;
- });
-
- // If there is no connection to the destinationParam, an InvalidAccessError exception MUST be thrown.
- if (m_param_connections.size() == before) {
- return WebIDL::InvalidAccessError::create(Utf16String::formatted("No connection from output {} to given AudioParam", output));
- }
-
- queue_connection_update();
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
-WebIDL::ExceptionOr<void> AudioNode::set_channel_count(WebIDL::UnsignedLong channel_count)
-{
- // If this value is set to zero or to a value greater than the implementation’s maximum number
- // of channels the implementation MUST throw a NotSupportedError exception.
- if (channel_count == 0 || channel_count > BaseAudioContext::MAX_NUMBER_OF_CHANNELS)
- return WebIDL::NotSupportedError::create("Invalid channel count"_utf16);
-
- m_channel_count = channel_count;
- queue_channel_config_update();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
-WebIDL::ExceptionOr<void> AudioNode::set_channel_count_mode(ChannelCountMode channel_count_mode)
-{
- m_channel_count_mode = channel_count_mode;
- queue_channel_config_update();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
-ChannelCountMode AudioNode::channel_count_mode()
-{
- return m_channel_count_mode;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelinterpretation
-WebIDL::ExceptionOr<void> AudioNode::set_channel_interpretation(ChannelInterpretation channel_interpretation)
-{
- m_channel_interpretation = channel_interpretation;
- queue_channel_config_update();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelinterpretation
-ChannelInterpretation AudioNode::channel_interpretation()
-{
- return m_channel_interpretation;
-}
-
-void AudioNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_context);
-
- // The Web Audio graph is allowed to keep native nodes alive after their
- // JavaScript references disappear. Keep the corresponding main-world
- // wrapper alive for exactly as long as this native node is reachable.
- if (auto wrapper = cached_main_world_wrapper())
- visitor.visit(*wrapper);
-
- // A node keeps everything it feeds into alive, but not the other way around: "when the note has finished playing,
- // the context will automatically release the reference to the AudioBufferSourceNode, which in turn will release
- // references to any nodes it is connected to, and so on".
- // NB: The context roots every source node that is playing, which is what keeps a subgraph feeding the destination
- // alive for as long as it can still produce sound.
- // FIXME: A node that is still within its tail-time, and a MediaElementAudioSourceNode that is actively processing,
- // should be kept alive by the context in the same way.
- for (auto& conn : m_param_connections)
- visitor.visit(conn.destination_param);
-
- for (auto& conn : m_output_connections)
- visitor.visit(conn.destination_node);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioNode.h b/Libraries/LibWeb/WebAudio/AudioNode.h
deleted file mode 100644
index b8af7d9d737..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioNode.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2025-2026, Ben Eidson <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/NonnullOwnPtr.h>
-#include <AK/Optional.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/AudioNode.h>
-#include <LibWeb/DOM/EventTarget.h>
-#include <LibWeb/WebAudio/Rendering/RenderNode.h>
-#include <LibWeb/WebAudio/Types.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebAudio {
-
-using ChannelCountMode = Bindings::ChannelCountMode;
-using ChannelInterpretation = Bindings::ChannelInterpretation;
-
-struct AudioNodeDefaultOptions {
- WebIDL::UnsignedLong channel_count;
- ChannelCountMode channel_count_mode;
- ChannelInterpretation channel_interpretation;
-};
-
-using AudioNodeOptions = Bindings::AudioNodeOptions;
-
-struct AudioNodeConnection {
- GC::Ref<AudioNode> destination_node;
- WebIDL::UnsignedLong output;
- WebIDL::UnsignedLong input;
-
- bool operator==(AudioNodeConnection const& other) const = default;
-};
-
-struct AudioParamConnection {
- GC::Ref<AudioParam> destination_param;
- WebIDL::UnsignedLong output;
-
- bool operator==(AudioParamConnection const& other) const = default;
-};
-
-// https://webaudio.github.io/web-audio-api/#AudioNode
-class AudioNode : public DOM::EventTarget {
- WEB_WRAPPABLE(AudioNode, DOM::EventTarget);
- GC_DECLARE_ALLOCATOR(AudioNode);
-
-public:
- virtual ~AudioNode() override;
-
- WebIDL::ExceptionOr<GC::Ref<AudioNode>> connect(GC::Ref<AudioNode> destination_node, WebIDL::UnsignedLong output = 0, WebIDL::UnsignedLong input = 0);
- WebIDL::ExceptionOr<void> connect(GC::Ref<AudioParam> destination_param, WebIDL::UnsignedLong output = 0);
-
- void disconnect();
- WebIDL::ExceptionOr<void> disconnect(WebIDL::UnsignedLong output);
- WebIDL::ExceptionOr<void> disconnect(GC::Ref<AudioNode> destination_node);
- WebIDL::ExceptionOr<void> disconnect(GC::Ref<AudioNode> destination_node, WebIDL::UnsignedLong output);
- WebIDL::ExceptionOr<void> disconnect(GC::Ref<AudioNode> destination_node, WebIDL::UnsignedLong output, WebIDL::UnsignedLong input);
- WebIDL::ExceptionOr<void> disconnect(GC::Ref<AudioParam> destination_param);
- WebIDL::ExceptionOr<void> disconnect(GC::Ref<AudioParam> destination_param, WebIDL::UnsignedLong output);
-
- // https://webaudio.github.io/web-audio-api/#dom-audionode-context
- GC::Ref<BaseAudioContext> context()
- {
- // The BaseAudioContext which owns this AudioNode.
- return m_context;
- }
-
- // https://webaudio.github.io/web-audio-api/#dom-audionode-numberofinputs
- virtual WebIDL::UnsignedLong number_of_inputs() = 0;
- // https://webaudio.github.io/web-audio-api/#dom-audionode-numberofoutputs
- virtual WebIDL::UnsignedLong number_of_outputs() = 0;
-
- // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
- virtual WebIDL::ExceptionOr<void> set_channel_count(WebIDL::UnsignedLong);
- virtual WebIDL::UnsignedLong channel_count() const { return m_channel_count; }
-
- virtual WebIDL::ExceptionOr<void> set_channel_count_mode(ChannelCountMode);
- ChannelCountMode channel_count_mode();
- virtual WebIDL::ExceptionOr<void> set_channel_interpretation(ChannelInterpretation);
- ChannelInterpretation channel_interpretation();
-
- WebIDL::ExceptionOr<void> initialize_audio_node_options(AudioNodeOptions const& given_options, AudioNodeDefaultOptions const& default_options);
-
- NodeID node_id() const { return m_node_id; }
- JS::Object& relevant_global_object() const;
-
-protected:
- AudioNode(GC::Ref<BaseAudioContext>, WebIDL::UnsignedLong channel_count = 2);
- void queue_render_node_creation(NonnullOwnPtr<Rendering::RenderNode>);
- virtual void visit_edges(Cell::Visitor&) override;
- virtual void finalize() override;
-
-private:
- void queue_connection_update();
- void queue_channel_config_update();
- GC::Ref<BaseAudioContext> m_context;
- WebIDL::UnsignedLong m_channel_count { 2 };
- ChannelCountMode m_channel_count_mode { ChannelCountMode::Max };
- ChannelInterpretation m_channel_interpretation { ChannelInterpretation::Speakers };
- // Connections from this node's outputs into other AudioNode inputs.
- Vector<AudioNodeConnection> m_output_connections;
- // Connections from this node's outputs into AudioParams.
- Vector<AudioParamConnection> m_param_connections;
- NodeID const m_node_id;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioNode.idl b/Libraries/LibWeb/WebAudio/AudioNode.idl
index c34fb9e1a6f..542b5d91542 100644
--- a/Libraries/LibWeb/WebAudio/AudioNode.idl
+++ b/Libraries/LibWeb/WebAudio/AudioNode.idl
@@ -19,21 +19,21 @@ dictionary AudioNodeOptions {
};
// https://webaudio.github.io/web-audio-api/#AudioNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface AudioNode : EventTarget {
- AudioNode connect(AudioNode destinationNode,
+ [ImplementedAs=connect_to_node] AudioNode connect(AudioNode destinationNode,
optional unsigned long output = 0,
optional unsigned long input = 0);
- undefined connect(AudioParam destinationParam, optional unsigned long output = 0);
- undefined disconnect();
- undefined disconnect(unsigned long output);
- undefined disconnect(AudioNode destinationNode);
- undefined disconnect(AudioNode destinationNode, unsigned long output);
- undefined disconnect(AudioNode destinationNode,
+ [ImplementedAs=connect_to_param] undefined connect(AudioParam destinationParam, optional unsigned long output = 0);
+ [ImplementedAs=disconnect_all] undefined disconnect();
+ [ImplementedAs=disconnect_output] undefined disconnect(unsigned long output);
+ [ImplementedAs=disconnect_node] undefined disconnect(AudioNode destinationNode);
+ [ImplementedAs=disconnect_node_output] undefined disconnect(AudioNode destinationNode, unsigned long output);
+ [ImplementedAs=disconnect_node_output_input] undefined disconnect(AudioNode destinationNode,
unsigned long output,
unsigned long input);
- undefined disconnect(AudioParam destinationParam);
- undefined disconnect(AudioParam destinationParam, unsigned long output);
+ [ImplementedAs=disconnect_param] undefined disconnect(AudioParam destinationParam);
+ [ImplementedAs=disconnect_param_output] undefined disconnect(AudioParam destinationParam, unsigned long output);
readonly attribute BaseAudioContext context;
readonly attribute unsigned long numberOfInputs;
readonly attribute unsigned long numberOfOutputs;
diff --git a/Libraries/LibWeb/WebAudio/AudioParam.cpp b/Libraries/LibWeb/WebAudio/AudioParam.cpp
deleted file mode 100644
index be2405d4c25..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioParam.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/Realm.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-
-namespace Web::WebAudio {
-
-extern "C" {
-void* web_rust_audio_param_create(JSVM*, void* context, void* owner, float default_value, float min_value, float max_value, u8 automation_rate, u8 fixed_rate);
-void* web_rust_audio_param_context(void*);
-JSCompletion web_rust_audio_param_set_value(JSVM*, void* realm, void* param, float value);
-float web_rust_audio_param_intrinsic_value(void*, double time);
-void const* web_rust_audio_param_render_param(void*);
-}
-
-GC::Ref<AudioParam> AudioParam::create(GC::Ref<BaseAudioContext> context, GC::Ptr<AudioNode> owner, float default_value, float min_value, float max_value, AutomationRate automation_rate, FixedAutomationRate fixed_rate)
-{
- return *static_cast<AudioParam*>(web_rust_audio_param_create(JS::HostABI::vm_to_abi(JS::VM::the()), context.ptr(), owner.ptr(), default_value, min_value, max_value, to_underlying(automation_rate), to_underlying(fixed_rate)));
-}
-GC::Ref<BaseAudioContext> AudioParam::context() const { return *static_cast<BaseAudioContext*>(web_rust_audio_param_context(const_cast<AudioParam*>(this))); }
-WebIDL::ExceptionOr<void> AudioParam::set_value(float value)
-{
- auto& vm = JS::VM::the();
- TRY(JS::HostABI::completion_from_abi<void>(web_rust_audio_param_set_value(JS::HostABI::vm_to_abi(vm), vm.current_realm(), this, value)));
- return {};
-}
-float AudioParam::intrinsic_value_at_time(double time) const { return web_rust_audio_param_intrinsic_value(const_cast<AudioParam*>(this), time); }
-NonnullRefPtr<Rendering::RenderAudioParam> AudioParam::render_param() const { return adopt_ref(*new Rendering::RenderAudioParam(web_rust_audio_param_render_param(const_cast<AudioParam*>(this)))); }
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioParam.h b/Libraries/LibWeb/WebAudio/AudioParam.h
deleted file mode 100644
index c3f1b30b3d1..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioParam.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/AudioParam.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/WebAudio/Rendering/RenderNode.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::WebAudio {
-
-using AutomationRate = Bindings::AutomationRate;
-
-class AudioParam final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(AudioParam, audio_param)
-
-public:
- enum class FixedAutomationRate : u8 { No,
- Yes };
- static GC::Ref<AudioParam> create(GC::Ref<BaseAudioContext>, GC::Ptr<AudioNode> owner, float default_value, float min_value, float max_value, AutomationRate, FixedAutomationRate = FixedAutomationRate::No);
- GC::Ref<BaseAudioContext> context() const;
- WebIDL::ExceptionOr<void> set_value(float);
- float intrinsic_value_at_time(double time) const;
- NonnullRefPtr<Rendering::RenderAudioParam> render_param() const;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioParamMap.cpp b/Libraries/LibWeb/WebAudio/AudioParamMap.cpp
deleted file mode 100644
index 131eb9d89ef..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioParamMap.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/AudioParamMap.h>
-
-namespace Web::WebAudio {
-
-extern "C" {
-void* web_rust_audio_param_map_create(JSVM*);
-void web_rust_audio_param_map_set_entry(JSVM*, void* map, FlatPtr key, void* param);
-void web_rust_audio_param_map_values(void* map, void* context, void (*callback)(void*, void*));
-}
-GC::Ref<AudioParamMap> AudioParamMap::create()
-{
- return *static_cast<AudioParamMap*>(web_rust_audio_param_map_create(JS::HostABI::vm_to_abi(JS::VM::the())));
-}
-void AudioParamMap::set_entry(Utf16FlyString key, GC::Ref<AudioParam> value)
-{
- web_rust_audio_param_map_set_entry(JS::HostABI::vm_to_abi(JS::VM::the()), this, key.raw_identity(), value.ptr());
-}
-GC::RootVector<GC::Ref<AudioParam>> AudioParamMap::values() const
-{
- GC::RootVector<GC::Ref<AudioParam>> values;
- web_rust_audio_param_map_values(const_cast<AudioParamMap*>(this), &values, [](void* context, void* param) {
- static_cast<GC::RootVector<GC::Ref<AudioParam>>*>(context)->append(*static_cast<AudioParam*>(param));
- });
- return values;
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioParamMap.h b/Libraries/LibWeb/WebAudio/AudioParamMap.h
deleted file mode 100644
index f7f6614ad50..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioParamMap.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16FlyString.h>
-#include <LibGC/RootVector.h>
-#include <LibWeb/Bindings/AudioParamMap.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::WebAudio {
-
-class WEB_API AudioParamMap final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(AudioParamMap, audio_param_map)
-
-public:
- static GC::Ref<AudioParamMap> create();
- void set_entry(Utf16FlyString key, GC::Ref<AudioParam> value);
- GC::RootVector<GC::Ref<AudioParam>> values() const;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioProcessingEvent.cpp b/Libraries/LibWeb/WebAudio/AudioProcessingEvent.cpp
deleted file mode 100644
index 86ae285d1d4..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioProcessingEvent.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Bindings/RustEventTarget.h>
-#include <LibWeb/WebAudio/AudioProcessingEvent.h>
-
-namespace Web::WebAudio {
-
-extern "C" DOM::Event* web_rust_audio_processing_event_create(JSVM*, void* event, double playback_time, void* input, void* output);
-
-GC::Ref<DOM::Event> AudioProcessingEvent::create(Utf16FlyString const& event_name, AudioProcessingEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
-{
- auto event = Bindings::RustEvent::create(event_name, event_init, time_stamp);
- return *web_rust_audio_processing_event_create(JS::HostABI::vm_to_abi(JS::VM::the()), event.ptr(), event_init.playback_time, event_init.input_buffer.ptr(), event_init.output_buffer.ptr());
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioProcessingEvent.h b/Libraries/LibWeb/WebAudio/AudioProcessingEvent.h
deleted file mode 100644
index c1c683f2210..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioProcessingEvent.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/AudioProcessingEvent.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/DOM/Event.h>
-#include <LibWeb/WebAudio/AudioBuffer.h>
-
-namespace Web::WebAudio {
-
-struct AudioProcessingEventInit : DOM::EventInit {
- GC::Ref<AudioBuffer> input_buffer;
- GC::Ref<AudioBuffer> output_buffer;
- double playback_time;
-};
-
-class AudioProcessingEvent final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(AudioProcessingEvent, audio_processing_event)
-
-public:
- static GC::Ref<DOM::Event> create(Utf16FlyString const& event_name, AudioProcessingEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioScheduledSourceNode.cpp b/Libraries/LibWeb/WebAudio/AudioScheduledSourceNode.cpp
deleted file mode 100644
index a54de7efdcf..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioScheduledSourceNode.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/HTML/EventNames.h>
-#include <LibWeb/WebAudio/AudioScheduledSourceNode.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/ControlMessage.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(AudioScheduledSourceNode);
-
-AudioScheduledSourceNode::AudioScheduledSourceNode(GC::Ref<BaseAudioContext> context)
- : AudioNode(context)
-{
-}
-
-AudioScheduledSourceNode::~AudioScheduledSourceNode() = default;
-
-// https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-onended
-GC::Ptr<WebIDL::CallbackType> AudioScheduledSourceNode::onended()
-{
- return event_handler_attribute(HTML::EventNames::ended);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-onended
-void AudioScheduledSourceNode::set_onended(GC::Ptr<WebIDL::CallbackType> value)
-{
- set_event_handler_attribute(HTML::EventNames::ended, value);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-start
-WebIDL::ExceptionOr<void> AudioScheduledSourceNode::start(double when)
-{
- // 1. If this AudioScheduledSourceNode internal slot [[source started]] is true, an InvalidStateError exception MUST be thrown.
- if (source_started())
- return WebIDL::InvalidStateError::create("AudioScheduledSourceNode source has already started"_utf16);
-
- // 2. Check for any errors that must be thrown due to parameter constraints described below.
- // If any exception is thrown during this step, abort those steps.
- // A RangeError exception MUST be thrown if when is negative.
- if (when < 0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "when must not be negative"_utf16 };
-
- // 3. Set the internal slot [[source started]] on this AudioScheduledSourceNode to true.
- set_source_started(true);
-
- // 4. Queue a control message to start the AudioScheduledSourceNode, including the parameter values in the message.
- context()->queue_control_message(NodeMessage { StartSource { .node_id = node_id(), .when = when } });
- context()->add_playing_source(*this);
-
- // FIXME: 5. Send a control message to the associated AudioContext to start running its rendering thread only when all the following conditions are met:
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-stop
-WebIDL::ExceptionOr<void> AudioScheduledSourceNode::stop(double when)
-{
- // 1. If this AudioScheduledSourceNode internal slot [[source started]] is not true, an InvalidStateError exception MUST be thrown.
- if (!m_source_started)
- return WebIDL::InvalidStateError::create("AudioScheduledSourceNode source has not been started"_utf16);
-
- // 2. Check for any errors that must be thrown due to parameter constraints described below.
- // A RangeError exception MUST be thrown if when is negative.
- if (when < 0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "when must not be negative"_utf16 };
-
- // 3. Queue a control message to stop the AudioScheduledSourceNode, including the parameter values in the message.
- context()->queue_control_message(NodeMessage { StopSource { .node_id = node_id(), .when = when } });
-
- return {};
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioScheduledSourceNode.h b/Libraries/LibWeb/WebAudio/AudioScheduledSourceNode.h
deleted file mode 100644
index 8529a40ea0e..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioScheduledSourceNode.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio {
-
-// https://webaudio.github.io/web-audio-api/#AudioScheduledSourceNode
-class AudioScheduledSourceNode : public AudioNode {
- WEB_WRAPPABLE(AudioScheduledSourceNode, AudioNode);
- GC_DECLARE_ALLOCATOR(AudioScheduledSourceNode);
-
-public:
- virtual ~AudioScheduledSourceNode() override;
-
- GC::Ptr<WebIDL::CallbackType> onended();
- void set_onended(GC::Ptr<WebIDL::CallbackType>);
-
- WebIDL::ExceptionOr<void> start(double when = 0);
- WebIDL::ExceptionOr<void> stop(double when = 0);
-
-protected:
- explicit AudioScheduledSourceNode(GC::Ref<BaseAudioContext>);
-
- bool source_started() const { return m_source_started; }
- void set_source_started(bool started) { m_source_started = started; }
-
-private:
- // https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-source-started-slot
- bool m_source_started { false };
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioScheduledSourceNode.idl b/Libraries/LibWeb/WebAudio/AudioScheduledSourceNode.idl
index 583f3d01a6f..595462e5471 100644
--- a/Libraries/LibWeb/WebAudio/AudioScheduledSourceNode.idl
+++ b/Libraries/LibWeb/WebAudio/AudioScheduledSourceNode.idl
@@ -1,5 +1,5 @@
// https://webaudio.github.io/web-audio-api/#AudioScheduledSourceNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface AudioScheduledSourceNode : AudioNode {
attribute EventHandler onended;
undefined start(optional double when = 0);
diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp b/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp
index 024e9c15efa..d850785e11e 100644
--- a/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp
+++ b/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp
@@ -6,293 +6,116 @@
#include <LibCore/EventLoop.h>
#include <LibGC/Heap.h>
-#include <LibJS/Runtime/AbstractOperations.h>
-#include <LibJS/Runtime/Array.h>
-#include <LibJS/Runtime/FunctionObject.h>
-#include <LibJS/Runtime/Realm.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/HTML/ErrorEvent.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/HTML/MessagePort.h>
#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
+#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/AudioParamMap.h>
#include <LibWeb/WebAudio/AudioWorklet.h>
#include <LibWeb/WebAudio/AudioWorkletGlobalScope.h>
#include <LibWeb/WebAudio/AudioWorkletNode.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.h>
-#include <LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h>
-#include <LibWeb/WebIDL/DOMException.h>
+#include <LibWeb/WebAudio/RustFFI.h>
+#include <LibWeb/WebIDL/ExceptionOrUtils.h>
namespace Web::WebAudio {
-GC_DEFINE_ALLOCATOR(AudioWorkletNode);
-
-// https://webaudio.github.io/web-audio-api/#dom-audioworkletnode-audioworkletnode
-WebIDL::ExceptionOr<GC::Ref<AudioWorkletNode>> AudioWorkletNode::construct_impl(JS::Realm& realm, GC::Ref<BaseAudioContext> context, Utf16String const& name, AudioWorkletNodeOptions const& options)
+using DescriptorCallback = void (*)(void*, FlatPtr, float, float, float, RustFFI::AutomationRate);
+extern "C" bool web_audio_worklet_find_definition(AudioWorklet*, FlatPtr, void*, DescriptorCallback);
+extern "C" AudioWorkletGlobalScope* web_audio_worklet_global_scope(AudioWorklet*);
+extern "C" JS::Realm* web_audio_worklet_scope_realm(AudioWorkletGlobalScope*);
+extern "C" JSCompletion web_audio_worklet_clone_options(JSVM*, JS::Realm*, JS::Realm*, JS::Object*);
+extern "C" RustFFI::FfiSharedCppObject web_audio_worklet_create_pipe(RustFFI::WorkletPipeConfig, float, void const**);
+extern "C" void web_audio_worklet_set_pump(Rendering::AudioWorkletPipe*, AudioWorkletGlobalScope*, u64);
+extern "C" void web_audio_worklet_clear_pump(Rendering::AudioWorkletPipe*);
+extern "C" JS::FunctionObject* web_audio_worklet_processor_constructor(AudioWorkletGlobalScope*, FlatPtr);
+extern "C" void web_audio_worklet_set_pending_port(AudioWorkletGlobalScope*, HTML::MessagePort*);
+extern "C" void web_audio_worklet_clear_pending_data(AudioWorkletGlobalScope*);
+extern "C" void web_audio_worklet_add_processor_slot(AudioWorkletGlobalScope*, u64, JS::Object*, HTML::MessagePort*, AudioWorkletNode*, Rendering::AudioWorkletPipe*, ReadonlySpan<FlatPtr>);
+extern "C" void web_audio_worklet_queue_processor_error(AudioWorkletNode*, DOM::EventTarget*, DOM::EventTarget*, JSValue);
+extern "C" void web_rust_audio_worklet_node_fire_error(AudioWorkletNode*, JSValue);
+
+bool web_audio_worklet_find_definition(AudioWorklet* worklet, FlatPtr name, void* context, DescriptorCallback descriptor_callback)
{
- auto& vm = realm.vm();
-
- // 1. If nodeName does not exist as a key in the BaseAudioContext's node name to parameter descriptor
- // map, throw an InvalidStateError exception and abort these steps.
- auto worklet = context->audio_worklet();
- auto definition = worklet->find_definition(name);
+ auto definition = worklet->find_definition(Utf16String::from_raw(name));
if (!definition.has_value())
- return WebIDL::InvalidStateError::create(Utf16String::formatted("No AudioWorkletProcessor named '{}' is registered", name));
-
- // https://webaudio.github.io/web-audio-api/#configuring-channels-with-audioworkletnodeoptions
- // If both numberOfInputs and numberOfOutputs are zero, throw a NotSupportedError.
- if (options.number_of_inputs == 0 && options.number_of_outputs == 0)
- return WebIDL::NotSupportedError::create("AudioWorkletNode must have at least one input or output"_utf16);
-
- // If outputChannelCount exists: throw an IndexSizeError if its length does not equal numberOfOutputs;
- // throw a NotSupportedError if any entry is zero or greater than the supported maximum.
- if (options.output_channel_count.has_value()) {
- if (options.output_channel_count->size() != options.number_of_outputs)
- return WebIDL::IndexSizeError::create("outputChannelCount length must equal numberOfOutputs"_utf16);
- for (auto channel_count : *options.output_channel_count) {
- if (channel_count == 0 || channel_count > BaseAudioContext::MAX_NUMBER_OF_CHANNELS)
- return WebIDL::NotSupportedError::create("outputChannelCount entries must be between 1 and 32"_utf16);
- }
- }
-
- auto worklet_scope_ptr = worklet->audio_worklet_global_scope();
- VERIFY(worklet_scope_ptr);
- auto& worklet_scope = *worklet_scope_ptr;
-
- // 2. Let node be this value; initialize node's AudioNode base with context and options.
- auto parameter_map = AudioParamMap::create();
- auto node_port = HTML::MessagePort::create(HTML::relevant_realm(context->relevant_global_object()));
- auto node = GC::Heap::the().allocate<AudioWorkletNode>(context, name, options.number_of_inputs, options.number_of_outputs, parameter_map, node_port);
-
- AudioNodeDefaultOptions default_options;
- default_options.channel_count = 2;
- default_options.channel_count_mode = ChannelCountMode::Max;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- TRY(node->initialize_audio_node_options(options, default_options));
-
- // 3. Let map be a new AudioParamMap; for each descriptor in the parameter descriptors, create an
- // AudioParam and append it to map; apply parameterData overrides.
+ return false;
for (auto const& descriptor : definition->parameter_descriptors) {
- auto param = AudioParam::create(context, node, descriptor.default_value, descriptor.min_value, descriptor.max_value, descriptor.automation_rate);
- if (options.parameter_data.has_value()) {
- if (auto it = options.parameter_data->find(descriptor.name); it != options.parameter_data->end())
- TRY(param->set_value(static_cast<float>(it->value)));
- }
- parameter_map->set_entry(descriptor.name, param);
- }
-
- // 4. Let messageChannel be a new MessageChannel (collapsed): node.port and the processor's port are
- // entangled; node.port's message queue is enabled immediately. The processor-side port stays
- // disabled until the processor constructor has returned, so messages posted before (or during)
- // construction are queued and delivered to listeners the constructor registered — even ones added
- // with addEventListener() and no explicit start().
- auto processor_port = HTML::MessagePort::create(worklet_scope.realm());
- node_port->entangle_with(*processor_port);
- node_port->enable();
-
- // 5. Let serializedProcessorOptions be StructuredSerialize(optionsObject's processorOptions).
- // 6-7. (Deserialization happens into the worklet realm when building the processor's options object.)
- auto& worklet_realm = worklet_scope.realm();
- GC::Ptr<JS::Object> cloned_processor_options;
- if (options.processor_options) {
- auto record = TRY(HTML::structured_serialize(vm, options.processor_options, HTML::AllowSharedArrayBuffers::CrossOriginIsolatedOnly));
- auto cloned_value = TRY(HTML::structured_deserialize(vm, record, worklet_realm));
- VERIFY(cloned_value.is_object());
- cloned_processor_options = &cloned_value.as_object();
- }
-
- GC::Ref<JS::Object> options_object = JS::Object::create(worklet_realm, worklet_realm.intrinsics().object_prototype());
- MUST(options_object->create_data_property("numberOfInputs"_utf16_fly_string, JS::Value(options.number_of_inputs)));
- MUST(options_object->create_data_property("numberOfOutputs"_utf16_fly_string, JS::Value(options.number_of_outputs)));
- if (options.output_channel_count.has_value()) {
- auto array = MUST(JS::Array::create(worklet_realm, options.output_channel_count->size()));
- for (size_t i = 0; i < options.output_channel_count->size(); ++i)
- MUST(array->create_data_property(JS::PropertyKey { i }, JS::Value(options.output_channel_count->at(i))));
- MUST(options_object->create_data_property("outputChannelCount"_utf16_fly_string, array));
+ Utf16FlyString key(descriptor.name);
+ descriptor_callback(context, key.raw_identity(), descriptor.default_value, descriptor.min_value, descriptor.max_value, static_cast<RustFFI::AutomationRate>(descriptor.automation_rate));
}
- if (options.parameter_data.has_value()) {
- auto parameter_data_object = JS::Object::create(worklet_realm, worklet_realm.intrinsics().object_prototype());
- for (auto const& entry : *options.parameter_data)
- MUST(parameter_data_object->create_data_property(JS::PropertyKey { Utf16FlyString(entry.key) }, JS::Value(entry.value)));
- MUST(options_object->create_data_property("parameterData"_utf16_fly_string, parameter_data_object));
- }
- // processorOptions is always present; when omitted by the caller, Web Audio specifies an empty object.
- if (cloned_processor_options)
- MUST(options_object->create_data_property("processorOptions"_utf16_fly_string, cloned_processor_options));
- else
- MUST(options_object->create_data_property("processorOptions"_utf16_fly_string, JS::Object::create(worklet_realm, worklet_realm.intrinsics().object_prototype())));
-
- Rendering::AudioWorkletPipe::Config pipe_config;
- pipe_config.quantum_size = BaseAudioContext::render_quantum_size();
- pipe_config.sample_rate = context->sample_rate();
- pipe_config.input_count = options.number_of_inputs;
- pipe_config.output_count = options.number_of_outputs;
- // Reserve space for later input layout changes without allocating on the render thread.
- for (WebIDL::UnsignedLong i = 0; i < options.number_of_inputs; ++i)
- pipe_config.input_channel_capacity.append(BaseAudioContext::MAX_NUMBER_OF_CHANNELS);
- pipe_config.output_channel_count_matches_input = options.number_of_inputs == 1
- && options.number_of_outputs == 1 && !options.output_channel_count.has_value();
- for (WebIDL::UnsignedLong i = 0; i < options.number_of_outputs; ++i) {
- if (options.output_channel_count.has_value())
- pipe_config.output_channel_capacity.append(options.output_channel_count->at(i));
- else
- pipe_config.output_channel_capacity.append(pipe_config.output_channel_count_matches_input ? BaseAudioContext::MAX_NUMBER_OF_CHANNELS : 1u);
- }
- pipe_config.param_count = definition->parameter_descriptors.size();
- for (auto const& descriptor : definition->parameter_descriptors)
- pipe_config.param_is_a_rate.append(descriptor.automation_rate == Bindings::AutomationRate::ARate);
- auto ring_sizing = Rendering::AudioWorkletPipe::Config::ring_sizing_for_device_latency(
- Rendering::RealtimeAudioRenderer::TARGET_LATENCY_MS, context->sample_rate(), pipe_config.quantum_size);
- pipe_config.ring_capacity = ring_sizing.ring_capacity;
- pipe_config.prime_level = ring_sizing.prime_level;
-
- auto pipe = Rendering::AudioWorkletPipe::create(pipe_config, Core::EventLoop::current());
- pipe->prime_outputs_with_silence(pipe_config.prime_level);
- node->m_pipe = pipe;
-
- // The pump trampoline holds the worklet scope via GC::Root (sanctioned non-GC-memory keepalive);
- // it observes ShutDown through the pipe state and unregisters the slot.
- pipe->set_pump_callback([scope_root = GC::make_root(worklet_scope), pipe, node_id = node->node_id()] {
- scope_root->pump(node_id, *pipe);
- });
-
- // Create the render mirror. Channel configuration rides in the constructor (the graph drops
- // SetChannelConfig messages that precede AddNode).
- Vector<NonnullRefPtr<Rendering::RenderAudioParam>> render_params;
- for (auto const& param : parameter_map->values())
- render_params.append(param->render_param());
- node->queue_render_node_creation(make<Rendering::AudioWorkletRenderNode>(node->node_id(),
- options.number_of_inputs, options.number_of_outputs, pipe_config.quantum_size,
- pipe_config.output_channel_capacity,
- node->channel_count(), node->channel_count_mode(), node->channel_interpretation(),
- pipe, move(render_params)));
-
- // FIXME: Implement the spec's actively-processing keep-alive (drop this when the processor's
- // process() return value has been false and inputs are silent). For now a live worklet
- // node stays registered with the context until the context goes away.
- context->add_playing_source(node);
-
- // 8. Queue a control message to invoke the constructor of the corresponding AudioWorkletProcessor.
- // NOTE: The worklet shares the window agent's event loop, so the control message becomes a queued
- // global task on the worklet global; the node constructor returns before user code runs.
- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, worklet_realm.global_object(),
- GC::create_function(realm.heap(), [node, scope = GC::Ref { worklet_scope }, processor_port, options_object] {
- node->invoke_processor_constructor(scope, processor_port, options_object);
- }));
-
- return node;
+ return true;
}
-
-AudioWorkletNode::AudioWorkletNode(GC::Ref<BaseAudioContext> context, Utf16String name, WebIDL::UnsignedLong number_of_inputs, WebIDL::UnsignedLong number_of_outputs, GC::Ref<AudioParamMap> parameter_map, GC::Ref<HTML::MessagePort> port)
- : AudioNode(context)
- , m_name(move(name))
- , m_number_of_inputs(number_of_inputs)
- , m_number_of_outputs(number_of_outputs)
- , m_parameter_map(parameter_map)
- , m_port(port)
+AudioWorkletGlobalScope* web_audio_worklet_global_scope(AudioWorklet* worklet) { return worklet->audio_worklet_global_scope().ptr(); }
+JS::Realm* web_audio_worklet_scope_realm(AudioWorkletGlobalScope* scope) { return &scope->realm(); }
+JSCompletion web_audio_worklet_clone_options(JSVM* vm, JS::Realm* realm, JS::Realm* error_realm, JS::Object* options)
{
+ auto record = HTML::structured_serialize(JS::HostABI::vm_from_abi(vm), options, HTML::AllowSharedArrayBuffers::CrossOriginIsolatedOnly);
+ if (record.is_error())
+ return JS::HostABI::throw_completion_to_abi(WebIDL::exception_to_throw_completion(JS::HostABI::vm_from_abi(vm), *error_realm, record.release_error()).value());
+ auto cloned = HTML::structured_deserialize(JS::HostABI::vm_from_abi(vm), record.value(), *realm);
+ if (cloned.is_error())
+ return JS::HostABI::throw_completion_to_abi(WebIDL::exception_to_throw_completion(JS::HostABI::vm_from_abi(vm), *error_realm, cloned.release_error()).value());
+ return JS::HostABI::normal_completion_to_abi(JS::HostABI::value_to_abi(cloned.release_value()));
}
-
-AudioWorkletNode::~AudioWorkletNode() = default;
-
-// https://webaudio.github.io/web-audio-api/#instantiation-of-audioworkletprocessor
-void AudioWorkletNode::invoke_processor_constructor(GC::Ref<AudioWorkletGlobalScope> scope, GC::Ref<HTML::MessagePort> processor_port, GC::Ref<JS::Object> options_object)
-{
- auto& worklet_realm = scope->realm();
- auto& vm = worklet_realm.vm();
- HTML::TemporaryExecutionContext execution_context { worklet_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
-
- auto const* definition = scope->find_definition(m_name);
- VERIFY(definition);
-
- // 1. Set the pending processor construction data: the processor-side port.
- scope->set_pending_processor_construction_data({ processor_port });
-
- // 2. Construct the processor: Construct(processorCtor, « optionsObject »).
- auto processor_or_error = JS::construct(vm, *definition->constructor, options_object);
-
- // 3. Empty the pending processor construction data slot (a constructor that never chained to
- // super() leaves it populated).
- (void)scope->take_pending_processor_construction_data();
-
- if (processor_or_error.is_error()) {
- m_processor_errored = true;
- m_pipe->set_state(Rendering::AudioWorkletPipe::State::Failed);
- fire_processor_error(processor_or_error.release_error().value());
- return;
- }
-
- m_processor = processor_or_error.release_value();
-
- Vector<Utf16String> parameter_names;
- if (auto synced = context()->audio_worklet()->find_definition(m_name); synced.has_value()) {
- for (auto const& descriptor : synced->parameter_descriptors)
- parameter_names.append(descriptor.name);
- }
- scope->add_processor_slot({
- .node_id = node_id(),
- .processor = *m_processor,
- .processor_port = processor_port,
- .node = GC::Weak<AudioWorkletNode> { *this },
- .pipe = *m_pipe,
- .parameter_names = move(parameter_names),
- });
-
- // 4. Enable the processor-side port's message queue: pending messages posted since node construction
- // are now delivered, after the constructor had its chance to register listeners.
- processor_port->enable();
-}
-
-void AudioWorkletNode::finalize()
+RustFFI::FfiSharedCppObject web_audio_worklet_create_pipe(RustFFI::WorkletPipeConfig config, float sample_rate, void const** native_pipe)
{
- // Allocation-free: the base queues RemoveNode (destroying the render node on the audio thread at
- // the next message drain), and the atomic state store tells the pump to drop the slot.
- if (m_pipe) {
- m_pipe->clear_pump_callback();
- m_pipe->request_shutdown();
- }
- Base::finalize();
+ Rendering::AudioWorkletPipe::Config pipe_config;
+ pipe_config.quantum_size = config.quantum_size;
+ pipe_config.sample_rate = sample_rate;
+ pipe_config.input_count = config.input_count;
+ pipe_config.output_count = config.output_count;
+ for (auto capacity : config.input_channel_capacity)
+ pipe_config.input_channel_capacity.append(capacity);
+ for (auto capacity : config.output_channel_capacity)
+ pipe_config.output_channel_capacity.append(capacity);
+ pipe_config.output_channel_count_matches_input = config.output_channel_count_matches_input;
+ pipe_config.param_count = config.param_count;
+ for (auto is_a_rate : config.param_is_a_rate)
+ pipe_config.param_is_a_rate.append(is_a_rate);
+ pipe_config.ring_capacity = config.ring_capacity;
+ pipe_config.prime_level = config.prime_level;
+ auto pipe = Rendering::AudioWorkletPipe::create(move(pipe_config), Core::EventLoop::current());
+ *native_pipe = pipe->rust_pipe();
+ return { &pipe.leak_ref(), [](void* pipe) { static_cast<Rendering::AudioWorkletPipe*>(pipe)->ref(); }, [](void* pipe) { static_cast<Rendering::AudioWorkletPipe*>(pipe)->unref(); } };
}
-
-void AudioWorkletNode::fire_processor_error(JS::Value error)
+void web_audio_worklet_set_pump(Rendering::AudioWorkletPipe* pipe, AudioWorkletGlobalScope* scope, u64 node_id)
{
- // https://webaudio.github.io/web-audio-api/#dom-audioworkletnode-onprocessorerror
- // "...the processor will queue a task to fire an event named processorerror using ErrorEvent at the
- // associated AudioWorkletNode."
- auto& node_realm = HTML::relevant_realm(context()->relevant_global_object());
- HTML::ErrorEventInit event_init;
- event_init.message = error.to_utf16_string_without_side_effects();
- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, context()->relevant_global_object(),
- GC::create_function(node_realm.heap(), [node = GC::Ref { *this }, event_init = move(event_init)] {
- auto event = HTML::ErrorEvent::create(HTML::EventNames::processorerror, event_init,
- HighResolutionTime::current_high_resolution_time(node->context()->relevant_global_object()));
- node->dispatch_event(event);
- }));
+ pipe->set_pump_callback([scope_root = GC::make_root(*scope), pipe = NonnullRefPtr { *pipe }, node_id = NodeID(node_id)] { scope_root->pump(node_id, *pipe); });
}
-
-void AudioWorkletNode::set_onprocessorerror(WebIDL::CallbackType* event_handler)
+void web_audio_worklet_clear_pump(Rendering::AudioWorkletPipe* pipe) { pipe->clear_pump_callback(); }
+JS::FunctionObject* web_audio_worklet_processor_constructor(AudioWorkletGlobalScope* scope, FlatPtr name)
{
- set_event_handler_attribute(HTML::EventNames::processorerror, event_handler);
+ auto const* definition = scope->find_definition(Utf16String::from_raw(name));
+ VERIFY(definition);
+ return definition->constructor.ptr();
}
-
-WebIDL::CallbackType* AudioWorkletNode::onprocessorerror()
+void web_audio_worklet_set_pending_port(AudioWorkletGlobalScope* scope, HTML::MessagePort* port) { scope->set_pending_processor_construction_data({ *port }); }
+void web_audio_worklet_clear_pending_data(AudioWorkletGlobalScope* scope) { (void)scope->take_pending_processor_construction_data(); }
+void web_audio_worklet_add_processor_slot(AudioWorkletGlobalScope* scope, u64 node_id, JS::Object* processor, HTML::MessagePort* processor_port, AudioWorkletNode* node, Rendering::AudioWorkletPipe* pipe, ReadonlySpan<FlatPtr> raw_names)
{
- return event_handler_attribute(HTML::EventNames::processorerror);
+ Vector<Utf16String> names;
+ names.ensure_capacity(raw_names.size());
+ for (auto raw_name : raw_names)
+ names.unchecked_append(Utf16String::from_raw(raw_name));
+ scope->add_processor_slot({ .node_id = NodeID(node_id), .processor = *processor, .processor_port = *processor_port, .node = GC::Weak<AudioWorkletNode> { *node }, .pipe = *pipe, .parameter_names = move(names) });
}
-
-void AudioWorkletNode::visit_edges(Cell::Visitor& visitor)
+void web_audio_worklet_queue_processor_error(AudioWorkletNode* node, DOM::EventTarget* target, DOM::EventTarget* global, JSValue error)
{
- Base::visit_edges(visitor);
- visitor.visit(m_parameter_map);
- visitor.visit(m_port);
- visitor.visit(m_processor);
+ auto& global_object = HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*global));
+ HTML::ErrorEventInit event_init;
+ event_init.message = JS::HostABI::value_from_abi(error).to_utf16_string_without_side_effects();
+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, global_object,
+ GC::create_function(GC::Heap::the(), [node = GC::make_root(*node), target, global, event_init = move(event_init)] {
+ auto& global_object = HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*global));
+ auto event = HTML::ErrorEvent::create(HTML::EventNames::processorerror, event_init, HighResolutionTime::current_high_resolution_time(global_object));
+ target->dispatch_event(event);
+ }));
}
+void AudioWorkletNode::fire_processor_error(JS::Value error) { web_rust_audio_worklet_node_fire_error(this, JS::HostABI::value_to_abi(error)); }
}
diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletNode.h b/Libraries/LibWeb/WebAudio/AudioWorkletNode.h
index 2f9d58bd3c2..b7e6f579a40 100644
--- a/Libraries/LibWeb/WebAudio/AudioWorkletNode.h
+++ b/Libraries/LibWeb/WebAudio/AudioWorkletNode.h
@@ -6,69 +6,15 @@
#pragma once
-#include <AK/Utf16String.h>
#include <LibWeb/Bindings/AudioWorkletNode.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio::Rendering {
-
-class AudioWorkletPipe;
-
-}
-
+#include <LibWeb/Bindings/RustInterface.h>
namespace Web::WebAudio {
-using AudioWorkletNodeOptions = Bindings::AudioWorkletNodeOptions;
-
-// https://webaudio.github.io/web-audio-api/#AudioWorkletNode
-class WEB_API AudioWorkletNode final : public AudioNode {
- WEB_WRAPPABLE(AudioWorkletNode, AudioNode);
- GC_DECLARE_ALLOCATOR(AudioWorkletNode);
+class WEB_API AudioWorkletNode final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(AudioWorkletNode, audio_worklet_node);
public:
- static WebIDL::ExceptionOr<GC::Ref<AudioWorkletNode>> construct_impl(JS::Realm&, GC::Ref<BaseAudioContext>, Utf16String const& name, AudioWorkletNodeOptions const&);
-
- virtual ~AudioWorkletNode() override;
-
- GC::Ref<AudioParamMap> parameters() const { return m_parameter_map; }
- GC::Ref<HTML::MessagePort> port() const { return m_port; }
-
- void set_onprocessorerror(WebIDL::CallbackType*);
- WebIDL::CallbackType* onprocessorerror();
-
- virtual WebIDL::UnsignedLong number_of_inputs() override { return m_number_of_inputs; }
- virtual WebIDL::UnsignedLong number_of_outputs() override { return m_number_of_outputs; }
-
- void fire_processor_error(JS::Value error);
-
- GC::Ptr<JS::Object> processor() const { return m_processor; }
-
-private:
- AudioWorkletNode(GC::Ref<BaseAudioContext>, Utf16String name, WebIDL::UnsignedLong number_of_inputs, WebIDL::UnsignedLong number_of_outputs, GC::Ref<AudioParamMap>, GC::Ref<HTML::MessagePort> port);
-
- // "invoke processor constructor" — deferred to a queued task so the node constructor returns
- // before user code runs (and pre-constructor port messages queue up for delivery afterwards).
- void invoke_processor_constructor(GC::Ref<AudioWorkletGlobalScope>, GC::Ref<HTML::MessagePort> processor_port, GC::Ref<JS::Object> options_object);
-
- virtual void finalize() override;
- virtual void visit_edges(Cell::Visitor&) override;
-
- // https://webaudio.github.io/web-audio-api/#dom-audioworkletnode-audioworkletnode-context-name-options-name
- Utf16String m_name;
-
- WebIDL::UnsignedLong m_number_of_inputs { 1 };
- WebIDL::UnsignedLong m_number_of_outputs { 1 };
- GC::Ref<AudioParamMap> m_parameter_map;
- GC::Ref<HTML::MessagePort> m_port;
-
- // The user's AudioWorkletProcessor instance (worklet realm). Keeps the processor alive for the
- // lifetime of the node; the render pump reads it through the processor slot registry.
- GC::Ptr<JS::Object> m_processor;
- bool m_processor_errored { false };
-
- RefPtr<Rendering::AudioWorkletPipe> m_pipe;
+ void fire_processor_error(JS::Value);
};
}
diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletNode.idl b/Libraries/LibWeb/WebAudio/AudioWorkletNode.idl
index 845f391978e..934b4784aba 100644
--- a/Libraries/LibWeb/WebAudio/AudioWorkletNode.idl
+++ b/Libraries/LibWeb/WebAudio/AudioWorkletNode.idl
@@ -1,5 +1,5 @@
// https://webaudio.github.io/web-audio-api/#AudioWorkletNode
-[Exposed=Window, SecureContext]
+[Exposed=Window, SecureContext, ImplementedIn=Rust]
interface AudioWorkletNode : AudioNode {
constructor(BaseAudioContext context, DOMString name, optional AudioWorkletNodeOptions options = {});
readonly attribute AudioParamMap parameters;
diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletProcessor.h b/Libraries/LibWeb/WebAudio/AudioWorkletProcessor.h
deleted file mode 100644
index d507595bc5c..00000000000
--- a/Libraries/LibWeb/WebAudio/AudioWorkletProcessor.h
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/AudioWorkletProcessor.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/Export.h>
-
-namespace Web::WebAudio {
-
-class WEB_API AudioWorkletProcessor final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(AudioWorkletProcessor, audio_worklet_processor)
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp b/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp
index 8a5a71480b7..9cb8a6422a2 100644
--- a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp
+++ b/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp
@@ -7,512 +7,118 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/NumericLimits.h>
#include <LibGC/Heap.h>
#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/VM.h>
#include <LibMediaClient/Client.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/DocumentObserver.h>
-#include <LibWeb/DOM/Event.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
-#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/HTML/LocalNavigable.h>
+#include <LibWeb/HTML/Navigable.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/ExceptionReporter.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
-#include <LibWeb/HighResolutionTime/TimeOrigin.h>
-#include <LibWeb/WebAudio/AnalyserNode.h>
-#include <LibWeb/WebAudio/AudioArray.h>
-#include <LibWeb/WebAudio/AudioBuffer.h>
-#include <LibWeb/WebAudio/AudioBufferSourceNode.h>
-#include <LibWeb/WebAudio/AudioDestinationNode.h>
#include <LibWeb/WebAudio/AudioWorklet.h>
#include <LibWeb/WebAudio/AudioWorkletGlobalScope.h>
#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/BiquadFilterNode.h>
-#include <LibWeb/WebAudio/ChannelMergerNode.h>
-#include <LibWeb/WebAudio/ControlMessageQueue.h>
-#include <LibWeb/WebAudio/DynamicsCompressorNode.h>
-#include <LibWeb/WebAudio/GainNode.h>
-#include <LibWeb/WebAudio/MediaStreamAudioSourceNode.h>
-#include <LibWeb/WebAudio/OscillatorNode.h>
-#include <LibWeb/WebAudio/PannerNode.h>
-#include <LibWeb/WebIDL/AbstractOperations.h>
-#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/ExceptionOrUtils.h>
-#include <LibWeb/WebIDL/Promise.h>
namespace Web::WebAudio {
-extern "C" JSCompletion web_audio_verify_buffer_options(void* realm, u32 channels, u32 length, float sample_rate);
-JSCompletion web_audio_verify_buffer_options(void* realm, u32 channels, u32 length, float sample_rate)
-{
- auto& js_realm = *static_cast<JS::Realm*>(realm);
- auto result = BaseAudioContext::verify_audio_options_inside_nominal_range(channels, length, sample_rate);
- if (result.is_exception())
- return JS::HostABI::throw_completion_to_abi(WebIDL::exception_to_throw_completion(js_realm.vm(), js_realm, result.exception()).value());
- return JS::HostABI::normal_completion_to_abi(JS::HostABI::value_to_abi(JS::js_undefined()));
-}
-
-extern "C" double web_audio_context_current_time(BaseAudioContext*);
-extern "C" JS::Realm* web_audio_context_realm(BaseAudioContext*);
-double web_audio_context_current_time(BaseAudioContext* context) { return context->current_time(); }
-JS::Realm* web_audio_context_realm(BaseAudioContext* context) { return &context->relevant_settings_object().realm(); }
-
-static JS::Value audio_buffer(JS::Realm& realm, GC::Ptr<AudioBuffer> buffer)
-{
- if (!buffer)
- return JS::js_null();
- return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, buffer);
-}
-
-static void invoke_audio_buffer_callback(JS::Realm& realm, WebIDL::CallbackType& callback, AudioBuffer& buffer)
-{
- auto completion = WebIDL::invoke_callback(callback, {}, { { audio_buffer(realm, buffer) } });
- if (completion.is_abrupt())
- HTML::report_exception(completion, realm);
-}
-
-static void invoke_error_callback(JS::Realm& realm, WebIDL::CallbackType& callback, WebIDL::DOMException& error)
-{
- auto completion = WebIDL::invoke_callback(callback, {}, { { throw_completion(realm, error).value() } });
- if (completion.is_abrupt())
- HTML::report_exception(completion, realm);
-}
-
-void resolve_audio_buffer_promise(JS::Realm& realm, WebIDL::Promise const& promise, AudioBuffer& buffer)
-{
- WebIDL::resolve_promise(promise, audio_buffer(realm, buffer));
-}
-
-BaseAudioContext::BaseAudioContext(GC::Ref<DOM::EventTarget> relevant_global_object, float sample_rate)
- : DOM::EventTarget()
- , m_sample_rate(sample_rate)
- , m_global_object(relevant_global_object)
- , m_control_message_queue(adopt_ref(*new ControlMessageQueue))
-{
- if (auto* window = as_if<HTML::Window>(*m_global_object)) {
- // FIXME: Also handle the document becoming active again, e.g. when restored from the back/forward cache.
- m_document_observer = DOM::DocumentObserver::create(window->associated_document());
- m_document_observer->set_document_became_inactive([this]() {
- document_became_inactive();
- });
- }
-}
-
-BaseAudioContext::~BaseAudioContext() = default;
-
-void BaseAudioContext::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_destination);
- visitor.visit(m_pending_promises);
- visitor.visit(m_listener);
- visitor.visit(m_global_object);
- visitor.visit(m_document_observer);
- visitor.visit(m_audio_worklet);
- visitor.visit(m_playing_sources);
-
- if (state() == AudioContextState::Closed)
- return;
-
- // INTEROP: Blink keeps a ScriptProcessorNode with audioprocess listeners alive until its context is cleared
- // (ScriptProcessorNode::HasPendingActivity()), whether it is connected or not, so that a node script only
- // reaches through its listener keeps producing audio.
- for (auto& node : m_script_processor_nodes) {
- if (node.has_event_listener(HTML::EventNames::audioprocess))
- visitor.visit(node);
- }
-
- // Keep a source and the nodes it feeds alive while its track is live, even after script drops the source.
- // https://webaudio.github.io/web-audio-api/#AudioNode-actively-processing
- // NB: A muted or disabled track only pauses its source, so it stays alive as well.
- for (auto& source : m_media_stream_sources) {
- if (source.has_live_input_track())
- visitor.visit(source);
- }
-}
-
-void BaseAudioContext::add_playing_source(GC::Ref<AudioNode> node)
-{
- m_playing_sources.set(node->node_id(), node);
-}
-
-void BaseAudioContext::add_script_processor_node(ScriptProcessorNode& node)
-{
- m_script_processor_nodes.set(node);
-}
-
-void BaseAudioContext::add_media_stream_source(MediaStreamAudioSourceNode& source)
-{
- m_media_stream_sources.set(source);
-}
-
-void BaseAudioContext::handle_ended_sources(ReadonlySpan<NodeID> ended_nodes)
-{
- for (auto node_id : ended_nodes) {
- auto node = m_playing_sources.take(node_id);
- if (!node.has_value())
- continue;
- queue_a_media_element_task(GC::create_function(heap(), [node = *node] {
- node->dispatch_event(DOM::Event::create(node->relevant_global_object(), HTML::EventNames::ended));
- }));
- }
+extern "C" float web_rust_audio_context_sample_rate(void const*);
+extern "C" DOM::EventTarget* web_rust_audio_context_global(void const*);
+extern "C" JS::Object* web_rust_audio_context_global_wrapper(void const*);
+extern "C" void web_rust_audio_context_document_inactive(void*);
+extern "C" void web_rust_audio_context_decoded(JSVM*, void*, MediaClient::Client::DecodedAudioData*);
+float BaseAudioContext::sample_rate() const { return web_rust_audio_context_sample_rate(this); }
+GC::Ref<DOM::EventTarget> BaseAudioContext::relevant_global_event_target() const { return *web_rust_audio_context_global(this); }
+JS::Object& BaseAudioContext::relevant_global_object() const { return *web_rust_audio_context_global_wrapper(this); }
+extern "C" HTML::UniqueTaskSource* web_audio_context_create_task_source();
+extern "C" void web_audio_context_destroy_task_source(HTML::UniqueTaskSource*);
+extern "C" void web_audio_context_queue_task(HTML::UniqueTaskSource*, DOM::EventTarget*, GC::Cell*, void (*)(void*, void*));
+extern "C" DOM::DocumentObserver* web_audio_context_observe_document(DOM::EventTarget*, Bindings::RustInterfaceCell*);
+extern "C" JS::Realm* web_audio_context_global_realm(DOM::EventTarget*);
+extern "C" JS::Object* web_audio_context_global_wrapper(DOM::EventTarget*);
+extern "C" bool web_audio_context_document_is_fully_active(DOM::EventTarget*);
+extern "C" bool web_audio_context_responsible_document_is_fully_active(DOM::EventTarget*);
+extern "C" bool web_audio_context_navigable_is_destroyed(DOM::EventTarget*);
+extern "C" AudioWorklet* web_audio_context_get_worklet(BaseAudioContext*);
+extern "C" void web_audio_context_shutdown_worklet(AudioWorklet*);
+extern "C" JS::Object* web_audio_context_wrap_worklet(JS::Realm*, AudioWorklet*);
+extern "C" void web_audio_context_decode(ReadonlyBytes, u32, GC::Cell*);
+extern "C" void web_audio_context_decoded_destroy(MediaClient::Client::DecodedAudioData*);
+extern "C" void web_audio_context_decoded_metadata(MediaClient::Client::DecodedAudioData*, u32*, u64*, u32*);
+extern "C" void web_audio_context_decoded_channel(MediaClient::Client::DecodedAudioData*, u32, ReadonlySpan<float>*);
+extern "C" void web_audio_context_report_exception(JS::Realm*, JSValue);
+HTML::UniqueTaskSource* web_audio_context_create_task_source() { return new HTML::UniqueTaskSource; }
+void web_audio_context_destroy_task_source(HTML::UniqueTaskSource* source) { delete source; }
+void web_audio_context_queue_task(HTML::UniqueTaskSource* source, DOM::EventTarget* global, GC::Cell* cell, void (*invoke)(void*, void*))
+{
+ auto& settings = HTML::relevant_settings_object(HTML::relevant_window_or_worker_global_scope(*global));
+ auto task = HTML::Task::create(source->source, settings.responsible_document(), GC::create_function(GC::Heap::the(), [cell = GC::make_root(*cell), invoke] {
+ invoke(JS::HostABI::vm_to_abi(JS::VM::the()), cell.ptr());
+ }));
+ (void)HTML::main_thread_event_loop().task_queue().add(task);
}
-
-HTML::EnvironmentSettingsObject& BaseAudioContext::relevant_settings_object() const
+DOM::DocumentObserver* web_audio_context_observe_document(DOM::EventTarget* global, Bindings::RustInterfaceCell* context)
{
- return HTML::relevant_settings_object(HTML::relevant_window_or_worker_global_scope(*m_global_object));
+ auto* window = as_if<HTML::Window>(*global);
+ if (!window)
+ return nullptr;
+ // FIXME: Also handle the document becoming active again, e.g. when restored from the back/forward cache.
+ auto observer = DOM::DocumentObserver::create(window->associated_document());
+ observer->set_document_became_inactive([context] { web_rust_audio_context_document_inactive(context); });
+ return observer.ptr();
}
-
-JS::Object& BaseAudioContext::relevant_global_object() const
+JS::Realm* web_audio_context_global_realm(DOM::EventTarget* global) { return &HTML::relevant_settings_object(HTML::relevant_window_or_worker_global_scope(*global)).realm(); }
+JS::Object* web_audio_context_global_wrapper(DOM::EventTarget* global) { return &HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*global)); }
+bool web_audio_context_document_is_fully_active(DOM::EventTarget* global) { return as<HTML::Window>(*global).associated_document().is_fully_active(); }
+bool web_audio_context_responsible_document_is_fully_active(DOM::EventTarget* global)
{
- return HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*m_global_object));
+ auto& settings = HTML::relevant_settings_object(HTML::relevant_window_or_worker_global_scope(*global));
+ return settings.responsible_document() && settings.responsible_document()->is_fully_active();
}
-
-GC::Ref<DOM::Event> BaseAudioContext::create_associated_event(Utf16FlyString const& event_name) const
+bool web_audio_context_navigable_is_destroyed(DOM::EventTarget* global)
{
- return DOM::Event::create(event_name,
- HighResolutionTime::current_high_resolution_time(relevant_global_object()));
+ auto navigable = as<HTML::Window>(*global).navigable();
+ return navigable && navigable->has_been_destroyed();
}
-
-HTML::Window& BaseAudioContext::relevant_window() const
+AudioWorklet* web_audio_context_get_worklet(BaseAudioContext* context) { return AudioWorklet::create(*context).ptr(); }
+void web_audio_context_shutdown_worklet(AudioWorklet* worklet)
{
- auto* window = HTML::window_from_global_object(relevant_global_object());
- VERIFY(window);
- return *window;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-audioworklet
-GC::Ref<AudioWorklet> BaseAudioContext::audio_worklet()
-{
- if (!m_audio_worklet)
- m_audio_worklet = AudioWorklet::create(*this);
- return *m_audio_worklet;
-}
-
-void BaseAudioContext::shutdown_audio_worklet()
-{
- if (!m_audio_worklet)
- return;
- if (auto scope = m_audio_worklet->audio_worklet_global_scope())
+ if (auto scope = worklet->audio_worklet_global_scope())
scope->shutdown_all_slots();
}
-
-void BaseAudioContext::set_onstatechange(WebIDL::CallbackType* event_handler)
-{
- set_event_handler_attribute(HTML::EventNames::statechange, event_handler);
-}
-
-WebIDL::CallbackType* BaseAudioContext::onstatechange()
-{
- return event_handler_attribute(HTML::EventNames::statechange);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createanalyser
-WebIDL::ExceptionOr<GC::Ref<AnalyserNode>> BaseAudioContext::create_analyser()
-{
- return AnalyserNode::create(*this);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbiquadfilter
-WebIDL::ExceptionOr<GC::Ref<BiquadFilterNode>> BaseAudioContext::create_biquad_filter()
+JS::Object* web_audio_context_wrap_worklet(JS::Realm* realm, AudioWorklet* worklet) { return Bindings::wrap(Bindings::host_defined_wrapper_world(*realm), *realm, GC::Ref { *worklet }).ptr(); }
+void web_audio_context_decode(ReadonlyBytes data, u32 sample_rate, GC::Cell* operation)
{
- // Factory method for a BiquadFilterNode representing a second order filter which can be configured as one of several common filter types.
- return BiquadFilterNode::create(*this);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer
-WebIDL::ExceptionOr<GC::Ref<AudioBuffer>> BaseAudioContext::create_buffer(WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate)
-{
- auto& vm = JS::VM::the();
-
- // Creates an AudioBuffer of the given size. The audio data in the buffer will be zero-initialized (silent).
- // A NotSupportedError exception MUST be thrown if any of the arguments is negative, zero, or outside its nominal range.
- TRY(verify_audio_options_inside_nominal_range(number_of_channels, length, sample_rate));
-
- if (length > NumericLimits<i32>::max() / sizeof(float))
- return vm.throw_completion<JS::RangeError>(JS::ErrorType::InvalidLength, "typed array");
-
- return TRY_OR_THROW_OOM(vm, AudioBuffer::create(number_of_channels, length, sample_rate));
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffersource
-WebIDL::ExceptionOr<GC::Ref<AudioBufferSourceNode>> BaseAudioContext::create_buffer_source()
-{
- // Factory method for a AudioBufferSourceNode.
- return AudioBufferSourceNode::create(*this);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createchannelmerger
-WebIDL::ExceptionOr<GC::Ref<ChannelMergerNode>> BaseAudioContext::create_channel_merger(WebIDL::UnsignedLong number_of_inputs)
-{
- ChannelMergerOptions options { {}, number_of_inputs };
-
- TRY(ChannelMergerNode::validate_options(options));
- return ChannelMergerNode::create(*this, options);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createconstantsource
-WebIDL::ExceptionOr<GC::Ref<ConstantSourceNode>> BaseAudioContext::create_constant_source()
-{
- return ConstantSourceNode::create(*this);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createconvolver
-WebIDL::ExceptionOr<GC::Ref<ConvolverNode>> BaseAudioContext::create_convolver()
-{
- return ConvolverNode::create(*this);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createdelay
-WebIDL::ExceptionOr<GC::Ref<DelayNode>> BaseAudioContext::create_delay(double max_delay_time)
-{
- DelayOptions options { {}, {}, max_delay_time };
-
- TRY(DelayNode::validate_options(options));
- return DelayNode::create(*this, options);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createchannelsplitter
-WebIDL::ExceptionOr<GC::Ref<ChannelSplitterNode>> BaseAudioContext::create_channel_splitter(WebIDL::UnsignedLong number_of_outputs)
-{
- ChannelSplitterOptions options { {}, number_of_outputs };
-
- TRY(ChannelSplitterNode::validate_options(options));
- return ChannelSplitterNode::create(*this, options);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createoscillator
-WebIDL::ExceptionOr<GC::Ref<OscillatorNode>> BaseAudioContext::create_oscillator()
-{
- // Factory method for an OscillatorNode.
- return OscillatorNode::create(*this);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createdynamicscompressor
-WebIDL::ExceptionOr<GC::Ref<DynamicsCompressorNode>> BaseAudioContext::create_dynamics_compressor()
-{
- // Factory method for a DynamicsCompressorNode.
- return DynamicsCompressorNode::create(*this);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-creategain
-WebIDL::ExceptionOr<GC::Ref<GainNode>> BaseAudioContext::create_gain()
-{
- // Factory method for GainNode.
- return GainNode::create(*this);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createiirfilter
-WebIDL::ExceptionOr<GC::Ref<IIRFilterNode>> BaseAudioContext::create_iir_filter(Vector<double> const& feedforward, Vector<double> const& feedback)
-{
- // Factory method for an IIRFilterNode representing a general IIR Filter.
- IIRFilterOptions options;
- options.feedforward = feedforward;
- options.feedback = feedback;
- return IIRFilterNode::create(*this, options);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createpanner
-WebIDL::ExceptionOr<GC::Ref<PannerNode>> BaseAudioContext::create_panner()
-{
- // Factory method for a PannerNode.
- return PannerNode::create(*this);
-}
-
-WebIDL::ExceptionOr<GC::Ref<PeriodicWave>> BaseAudioContext::create_periodic_wave(Vector<float> const& real, Vector<float> const& imag, PeriodicWaveConstraints const& constraints)
-{
- PeriodicWaveOptions options;
- options.real = real;
- options.imag = imag;
- options.disable_normalization = constraints.disable_normalization;
-
- return PeriodicWave::create_for_constructor(*this, options);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-decodeaudiodata
-WebIDL::ExceptionOr<void> BaseAudioContext::decode_audio_data(GC::Ref<WebIDL::Promise> promise, ByteBuffer audio_data, GC::Ptr<WebIDL::CallbackType> success_callback, GC::Ptr<WebIDL::CallbackType> error_callback)
-{
- // FIXME: When decodeAudioData is called, the following steps MUST be performed on the control thread:
-
- // 1. If this's relevant global object's associated Document is not fully active then return a
- // promise rejected with "InvalidStateError" DOMException.
- auto const& associated_document = relevant_window().associated_document();
- if (!associated_document.is_fully_active())
- return WebIDL::InvalidStateError::create("The document is not fully active."_utf16);
-
- // 3. Append promise to [[pending promises]] and queue a decoding operation.
- m_pending_promises.append(promise);
- queue_a_decoding_operation(promise, move(audio_data), success_callback, error_callback);
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-decodeaudiodata
-void BaseAudioContext::queue_a_decoding_operation(GC::Ref<JS::PromiseCapability> promise, ByteBuffer audio_data, GC::Ptr<WebIDL::CallbackType> success_callback, GC::Ptr<WebIDL::CallbackType> error_callback)
-{
- // NB: The decoding thread is in the media server, which answers on this thread. Promise settlement and callbacks
- // are posted to the media element task source below.
- if (audio_data.is_empty()) {
- queue_a_media_element_task(GC::create_function(GC::Heap::the(), [this, promise, error_callback] {
- auto& realm = WebIDL::promise_realm(promise);
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
- auto error = WebIDL::EncodingError::create("Unable to decode."_utf16);
- WebIDL::reject_promise(promise, error);
- m_pending_promises.remove_first_matching([&promise](auto& pending_promise) { return pending_promise == promise; });
- if (error_callback)
- invoke_error_callback(realm, *error_callback, error);
- }));
- return;
- }
-
- auto queue_decode_error = [this, promise, error_callback] {
- queue_a_media_element_task(GC::create_function(GC::Heap::the(), [this, promise, error_callback] {
- auto& realm = WebIDL::promise_realm(promise);
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
- auto error = WebIDL::EncodingError::create("Unable to decode."_utf16);
- WebIDL::reject_promise(promise, error);
- m_pending_promises.remove_first_matching([&promise](auto& pending_promise) { return pending_promise == promise; });
- if (error_callback)
- invoke_error_callback(realm, *error_callback, error);
- }));
- };
-
auto media_client = MediaClient::Client::acquire();
if (media_client.is_error()) {
- queue_decode_error();
+ web_rust_audio_context_decoded(JS::HostABI::vm_to_abi(JS::VM::the()), operation, nullptr);
return;
}
-
- // The answer arrives outside any task, so the context and callbacks are rooted until it does.
- media_client.value()->decode_audio_data(audio_data, static_cast<u32>(sample_rate()), [self = GC::Root(*this), promise = GC::Root(promise), success_callback = GC::Root(success_callback), error_callback = GC::Root(error_callback), queue_decode_error = move(queue_decode_error)](Media::DecoderErrorOr<MediaClient::Client::DecodedAudioData> result) {
- if (result.is_error()) {
- queue_decode_error();
- return;
- }
- auto decoded = result.release_value();
- if (decoded.channel_count > NumericLimits<WebIDL::UnsignedLong>::max() || decoded.frame_count > NumericLimits<WebIDL::UnsignedLong>::max()) {
- queue_decode_error();
- return;
- }
-
- self->queue_a_media_element_task(GC::create_function(GC::Heap::the(), [self, promise, decoded = move(decoded), success_callback, queue_decode_error = move(queue_decode_error)] {
- auto buffer = AudioBuffer::create(static_cast<WebIDL::UnsignedLong>(decoded.channel_count), static_cast<WebIDL::UnsignedLong>(decoded.frame_count), decoded.sample_rate);
- if (buffer.is_error()) {
- queue_decode_error();
- return;
- }
- auto decoded_buffer = buffer.release_value();
- for (u32 channel = 0; channel < decoded.channel_count; ++channel) {
- auto channel_data = MUST(decoded_buffer->channel_data(channel));
- auto samples = decoded.channel(channel);
- ReadonlyBytes { reinterpret_cast<u8 const*>(samples.data()), samples.size() * sizeof(float) }.copy_to(channel_data);
- }
-
- auto& promise_realm = WebIDL::promise_realm(*promise);
- HTML::TemporaryExecutionContext context(promise_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
- resolve_audio_buffer_promise(promise_realm, *promise, decoded_buffer);
- self->m_pending_promises.remove_first_matching([&promise](auto& pending_promise) { return pending_promise.ptr() == promise.ptr(); });
- if (success_callback)
- invoke_audio_buffer_callback(promise_realm, *success_callback, decoded_buffer);
- }));
+ media_client.value()->decode_audio_data(data, sample_rate, [operation = GC::make_root(*operation)](Media::DecoderErrorOr<MediaClient::Client::DecodedAudioData> result) {
+ auto* decoded = result.is_error() ? nullptr : new MediaClient::Client::DecodedAudioData(result.release_value());
+ web_rust_audio_context_decoded(JS::HostABI::vm_to_abi(JS::VM::the()), operation.ptr(), decoded);
});
}
-
-WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> BaseAudioContext::decode_audio_data(JS::Realm& realm, GC::Ref<JS::ArrayBuffer> audio_data, GC::Ptr<WebIDL::CallbackType> success_callback, GC::Ptr<WebIDL::CallbackType> error_callback)
+void web_audio_context_decoded_destroy(MediaClient::Client::DecodedAudioData* decoded) { delete decoded; }
+void web_audio_context_decoded_metadata(MediaClient::Client::DecodedAudioData* decoded, u32* channels, u64* frames, u32* sample_rate)
{
- auto promise = WebIDL::create_promise_for(relevant_global_object());
- if (audio_data->is_detached()) {
- auto error = WebIDL::DataCloneError::create("Audio data is detached."_utf16);
- WebIDL::reject_promise(promise, error);
- if (error_callback) {
- queue_a_media_element_task(GC::create_function(GC::Heap::the(), [&realm, error_callback, error] {
- invoke_error_callback(realm, *error_callback, error);
- }));
- }
- return promise;
- }
- auto bytes = TRY_OR_THROW_OOM(realm.vm(), audio_data->copy_to_byte_buffer());
- TRY(JS::detach_array_buffer(realm.vm(), *audio_data));
- TRY(decode_audio_data(promise, move(bytes), success_callback, error_callback));
- return promise;
+ *channels = decoded->channel_count;
+ *frames = decoded->frame_count;
+ *sample_rate = decoded->sample_rate;
}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createscriptprocessor
-WebIDL::ExceptionOr<GC::Ref<ScriptProcessorNode>> BaseAudioContext::create_script_processor(
- WebIDL::UnsignedLong buffer_size,
- WebIDL::UnsignedLong number_of_input_channels,
- WebIDL::UnsignedLong number_of_output_channels)
+void web_audio_context_decoded_channel(MediaClient::Client::DecodedAudioData* decoded, u32 channel, ReadonlySpan<float>* samples)
{
- // The bufferSize parameter determines the buffer size in units of sample-frames. If it’s not passed in, or if the
- // value is 0, then the implementation will choose the best buffer size for the given environment, which will be
- // constant power of 2 throughout the lifetime of the node.
- if (buffer_size == 0)
- buffer_size = ScriptProcessorNode::DEFAULT_BUFFER_SIZE;
-
- TRY(ScriptProcessorNode::validate_options(buffer_size, number_of_input_channels, number_of_output_channels));
- return ScriptProcessorNode::create(*this, buffer_size, number_of_input_channels, number_of_output_channels);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createstereopanner
-WebIDL::ExceptionOr<GC::Ref<StereoPannerNode>> BaseAudioContext::create_stereo_panner()
-{
- // Factory method for a StereoPannerNode.
- return StereoPannerNode::create(*this);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createwaveshaper
-WebIDL::ExceptionOr<GC::Ref<WaveShaperNode>> BaseAudioContext::create_wave_shaper()
-{
- // Factory method for a WaveShaperNode representing a non-linear distortion.
- return WaveShaperNode::create(*this);
-}
-
-WebIDL::ExceptionOr<void> BaseAudioContext::verify_audio_options_inside_nominal_range(float sample_rate)
-{
- if (sample_rate < MIN_SAMPLE_RATE || sample_rate > MAX_SAMPLE_RATE)
- return WebIDL::NotSupportedError::create("Sample rate is outside of allowed range"_utf16);
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer
-WebIDL::ExceptionOr<void> BaseAudioContext::verify_audio_options_inside_nominal_range(WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate)
-{
- // A NotSupportedError exception MUST be thrown if any of the arguments is negative, zero, or outside its nominal range.
-
- if (number_of_channels == 0)
- return WebIDL::NotSupportedError::create("Number of channels must not be '0'"_utf16);
-
- if (number_of_channels > MAX_NUMBER_OF_CHANNELS)
- return WebIDL::NotSupportedError::create("Number of channels is greater than allowed range"_utf16);
-
- if (length == 0)
- return WebIDL::NotSupportedError::create("Length of buffer must be at least 1"_utf16);
-
- TRY(verify_audio_options_inside_nominal_range(sample_rate));
-
- return {};
-}
-
-void BaseAudioContext::queue_a_media_element_task(GC::Ref<GC::Function<void()>> steps)
-{
- // Rendering completion callbacks run from the audio thread, outside any
- // JavaScript execution context. Resolve the task target from this context's
- // associated global rather than consulting the thread-local current ESO.
- auto task = HTML::Task::create(m_media_element_event_task_source.source, relevant_settings_object().responsible_document(), steps);
- (void)HTML::main_thread_event_loop().task_queue().add(task);
+ *samples = decoded->channel(channel);
}
-void BaseAudioContext::queue_control_message(ControlMessage message)
+void web_audio_context_report_exception(JS::Realm* realm, JSValue error)
{
- m_control_message_queue->enqueue(move(message));
- // FIXME: Should signal the rendering thread when implemented
+ HTML::report_exception(JS::throw_completion(JS::HostABI::value_from_abi(error)), *realm);
}
}
diff --git a/Libraries/LibWeb/WebAudio/BaseAudioContext.h b/Libraries/LibWeb/WebAudio/BaseAudioContext.h
index d21c2a886c5..dd09937fe28 100644
--- a/Libraries/LibWeb/WebAudio/BaseAudioContext.h
+++ b/Libraries/LibWeb/WebAudio/BaseAudioContext.h
@@ -2,183 +2,25 @@
* Copyright (c) 2023, Luke Wilde <[email protected]>
* Copyright (c) 2024, Shannon Booth <[email protected]>
* Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
-#include <AK/ByteBuffer.h>
-#include <AK/Function.h>
-#include <LibGC/WeakHashSet.h>
#include <LibWeb/Bindings/BaseAudioContext.h>
-#include <LibWeb/DOM/EventTarget.h>
-#include <LibWeb/WebAudio/AnalyserNode.h>
-#include <LibWeb/WebAudio/AudioListener.h>
-#include <LibWeb/WebAudio/BiquadFilterNode.h>
-#include <LibWeb/WebAudio/ChannelMergerNode.h>
-#include <LibWeb/WebAudio/ChannelSplitterNode.h>
-#include <LibWeb/WebAudio/ConstantSourceNode.h>
-#include <LibWeb/WebAudio/ControlMessage.h>
-#include <LibWeb/WebAudio/ControlMessageQueue.h>
-#include <LibWeb/WebAudio/ConvolverNode.h>
-#include <LibWeb/WebAudio/DelayNode.h>
-#include <LibWeb/WebAudio/IIRFilterNode.h>
-#include <LibWeb/WebAudio/PeriodicWave.h>
-#include <LibWeb/WebAudio/ScriptProcessorNode.h>
-#include <LibWeb/WebAudio/StereoPannerNode.h>
-#include <LibWeb/WebAudio/Types.h>
-#include <LibWeb/WebAudio/WaveShaperNode.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebIDL {
-
-class DOMException;
-
-}
-
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Forward.h>
namespace Web::WebAudio {
-class AudioDestinationNode;
-class AudioWorklet;
-
-using AudioContextState = Bindings::AudioContextState;
-
-// https://webaudio.github.io/web-audio-api/#BaseAudioContext
-class BaseAudioContext : public DOM::EventTarget {
- WEB_WRAPPABLE(BaseAudioContext, DOM::EventTarget);
+class BaseAudioContext : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(BaseAudioContext, base_audio_context);
public:
- static constexpr size_t destination_offset() { return offsetof(BaseAudioContext, m_destination); }
- virtual ~BaseAudioContext() override;
-
- // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer-numberofchannels
- // > An implementation MUST support at least 32 channels.
- // Other browsers appear to only allow 32 channels - so let's limit ourselves to that too.
- static constexpr WebIDL::UnsignedLong MAX_NUMBER_OF_CHANNELS { 32 };
-
- // https://webaudio.github.io/web-audio-api/#sample-rates
- // Implementations MUST support sample rates between 3000 Hz and 768000 Hz, inclusive. A NotSupportedError MUST
- // be thrown if a sample rate outside this range is specified.
- static constexpr float MIN_SAMPLE_RATE { 3000 };
- static constexpr float MAX_SAMPLE_RATE { 768000 };
-
- static WebIDL::UnsignedLong render_quantum_size() { return s_render_quantum_size; }
-
- GC::Ref<AudioDestinationNode> destination() const { return *m_destination; }
- float sample_rate() const { return m_sample_rate; }
- virtual double current_time() const { return 0; }
- GC::Ref<AudioListener> listener() const
- {
- VERIFY(m_listener);
- return *m_listener;
- }
- AudioContextState state() const { return m_control_thread_state; }
- HTML::EnvironmentSettingsObject& relevant_settings_object() const;
+ float sample_rate() const;
+ GC::Ref<DOM::EventTarget> relevant_global_event_target() const;
JS::Object& relevant_global_object() const;
- GC::Ref<DOM::EventTarget> relevant_global_event_target() const { return m_global_object; }
- GC::Ref<DOM::Event> create_associated_event(Utf16FlyString const&) const;
- HTML::Window& relevant_window() const;
-
- // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-audioworklet
- GC::Ref<AudioWorklet> audio_worklet();
-
- // Marks every worklet node's pipe shut down and drops the pump slots; called when the context
- // closes or its document stops being fully active.
- void shutdown_audio_worklet();
-
- // https://webaudio.github.io/web-audio-api/#--nyquist-frequency
- float nyquist_frequency() const { return m_sample_rate / 2; }
-
- void set_onstatechange(WebIDL::CallbackType*);
- WebIDL::CallbackType* onstatechange();
-
- void set_sample_rate(float sample_rate) { m_sample_rate = sample_rate; }
- void set_control_state(AudioContextState state) { m_control_thread_state = state; }
- void set_rendering_state(AudioContextState state) { m_rendering_thread_state = state; }
-
- static WebIDL::ExceptionOr<void> verify_audio_options_inside_nominal_range(float sample_rate);
- static WebIDL::ExceptionOr<void> verify_audio_options_inside_nominal_range(WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate);
-
- WebIDL::ExceptionOr<GC::Ref<AnalyserNode>> create_analyser();
- WebIDL::ExceptionOr<GC::Ref<BiquadFilterNode>> create_biquad_filter();
- WebIDL::ExceptionOr<GC::Ref<AudioBuffer>> create_buffer(WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate);
- WebIDL::ExceptionOr<GC::Ref<AudioBufferSourceNode>> create_buffer_source();
- WebIDL::ExceptionOr<GC::Ref<ChannelMergerNode>> create_channel_merger(WebIDL::UnsignedLong number_of_inputs);
- WebIDL::ExceptionOr<GC::Ref<ConstantSourceNode>> create_constant_source();
- WebIDL::ExceptionOr<GC::Ref<ChannelSplitterNode>> create_channel_splitter(WebIDL::UnsignedLong number_of_outputs);
- WebIDL::ExceptionOr<GC::Ref<ConvolverNode>> create_convolver();
- WebIDL::ExceptionOr<GC::Ref<DelayNode>> create_delay(double max_delay_time = 1);
- WebIDL::ExceptionOr<GC::Ref<OscillatorNode>> create_oscillator();
- WebIDL::ExceptionOr<GC::Ref<DynamicsCompressorNode>> create_dynamics_compressor();
- WebIDL::ExceptionOr<GC::Ref<GainNode>> create_gain();
- WebIDL::ExceptionOr<GC::Ref<IIRFilterNode>> create_iir_filter(Vector<double> const& feedforward, Vector<double> const& feedback);
- WebIDL::ExceptionOr<GC::Ref<PannerNode>> create_panner();
- WebIDL::ExceptionOr<GC::Ref<PeriodicWave>> create_periodic_wave(Vector<float> const& real, Vector<float> const& imag, PeriodicWaveConstraints const& constraints = {});
- WebIDL::ExceptionOr<GC::Ref<ScriptProcessorNode>> create_script_processor(
- WebIDL::UnsignedLong buffer_size,
- WebIDL::UnsignedLong number_of_input_channels,
- WebIDL::UnsignedLong number_of_output_channels);
- WebIDL::ExceptionOr<GC::Ref<StereoPannerNode>> create_stereo_panner();
- WebIDL::ExceptionOr<GC::Ref<WaveShaperNode>> create_wave_shaper();
-
- WebIDL::ExceptionOr<void> decode_audio_data(GC::Ref<WebIDL::Promise>, ByteBuffer, GC::Ptr<WebIDL::CallbackType>, GC::Ptr<WebIDL::CallbackType>);
- WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> decode_audio_data(JS::Realm&, GC::Ref<JS::ArrayBuffer>, GC::Ptr<WebIDL::CallbackType>, GC::Ptr<WebIDL::CallbackType>);
-
- void queue_control_message(ControlMessage);
- NonnullRefPtr<ControlMessageQueue> control_message_queue() const { return m_control_message_queue; }
-
- void add_playing_source(GC::Ref<AudioNode>);
- void add_script_processor_node(ScriptProcessorNode&);
- void add_media_stream_source(MediaStreamAudioSourceNode&);
- void handle_ended_sources(ReadonlySpan<NodeID>);
-
- NodeID next_node_id(Badge<AudioNode>) { return ++m_next_node_id; }
-
-protected:
- explicit BaseAudioContext(GC::Ref<DOM::EventTarget> relevant_global_object, float m_sample_rate = 0);
-
- // Called when the associated document is destroyed or otherwise stops being fully active, so rendering resources
- // can be released.
- virtual void document_became_inactive() { }
-
- void queue_a_media_element_task(GC::Ref<GC::Function<void()>>);
- void set_listener(GC::Ref<AudioListener> listener) { m_listener = listener; }
- virtual void visit_edges(Cell::Visitor&) override;
-
- GC::Ptr<AudioDestinationNode> m_destination;
- Vector<GC::Ref<WebIDL::Promise>> m_pending_promises;
-
-private:
- // https://webaudio.github.io/web-audio-api/#render-quantum-size
- static constexpr WebIDL::UnsignedLong s_render_quantum_size { 128 };
-
- void queue_a_decoding_operation(GC::Ref<JS::PromiseCapability>, ByteBuffer, GC::Ptr<WebIDL::CallbackType>, GC::Ptr<WebIDL::CallbackType>);
-
- u64 m_next_node_id { 0 };
-
- float m_sample_rate { 0 };
-
- GC::Ptr<AudioListener> m_listener;
- GC::Ref<DOM::EventTarget> m_global_object;
-
- AudioContextState m_control_thread_state = AudioContextState::Suspended;
- AudioContextState m_rendering_thread_state = AudioContextState::Suspended;
-
- HTML::UniqueTaskSource m_media_element_event_task_source {};
-
- GC::Ptr<DOM::DocumentObserver> m_document_observer;
-
- GC::Ptr<AudioWorklet> m_audio_worklet;
-
- NonnullRefPtr<ControlMessageQueue> m_control_message_queue;
-
- HashMap<NodeID, GC::Ref<AudioNode>> m_playing_sources;
- GC::WeakHashSet<ScriptProcessorNode> m_script_processor_nodes;
- // Kept alive only while they can still produce audio; see visit_edges().
- GC::WeakHashSet<MediaStreamAudioSourceNode> m_media_stream_sources;
};
-void resolve_audio_buffer_promise(JS::Realm&, WebIDL::Promise const&, AudioBuffer&);
-
}
diff --git a/Libraries/LibWeb/WebAudio/BaseAudioContext.idl b/Libraries/LibWeb/WebAudio/BaseAudioContext.idl
index 247f2ec0a09..353017c98c4 100644
--- a/Libraries/LibWeb/WebAudio/BaseAudioContext.idl
+++ b/Libraries/LibWeb/WebAudio/BaseAudioContext.idl
@@ -6,9 +6,9 @@ callback DecodeErrorCallback = undefined (DOMException error);
callback DecodeSuccessCallback = undefined (AudioBuffer decodedData);
// https://webaudio.github.io/web-audio-api/#BaseAudioContext
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface BaseAudioContext : EventTarget {
- [DirectGetter] readonly attribute AudioDestinationNode destination;
+ readonly attribute AudioDestinationNode destination;
readonly attribute float sampleRate;
readonly attribute double currentTime;
readonly attribute AudioListener listener;
diff --git a/Libraries/LibWeb/WebAudio/BiquadFilterNode.cpp b/Libraries/LibWeb/WebAudio/BiquadFilterNode.cpp
deleted file mode 100644
index 6861ff68b48..00000000000
--- a/Libraries/LibWeb/WebAudio/BiquadFilterNode.cpp
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2024, Bar Yemini <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Math.h>
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/AudioArray.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/BiquadFilterNode.h>
-#include <LibWeb/WebAudio/Rendering/BiquadCoefficients.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(BiquadFilterNode);
-
-BiquadFilterNode::BiquadFilterNode(GC::Ref<BaseAudioContext> context, BiquadFilterOptions const& options)
- : AudioNode(context)
- , m_type(options.type)
- , m_frequency(AudioParam::create(context, this, options.frequency, 0, context->nyquist_frequency(), AutomationRate::ARate))
- , m_detune(AudioParam::create(context, this, options.detune, -1200 * AK::log2(NumericLimits<float>::max()), 1200 * AK::log2(NumericLimits<float>::max()), AutomationRate::ARate))
- , m_q(AudioParam::create(context, this, options.q, NumericLimits<float>::lowest(), NumericLimits<float>::max(), AutomationRate::ARate))
- , m_gain(AudioParam::create(context, this, options.gain, NumericLimits<float>::lowest(), 40 * AK::log10(NumericLimits<float>::max()), AutomationRate::ARate))
-{
-}
-
-BiquadFilterNode::~BiquadFilterNode() = default;
-
-// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-type
-void BiquadFilterNode::set_type(BiquadFilterType type)
-{
- m_type = type;
- context()->queue_control_message(NodeMessage { SetBiquadFilterType { node_id(), type } });
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-type
-BiquadFilterType BiquadFilterNode::type() const
-{
- return m_type;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-frequency
-GC::Ref<AudioParam> BiquadFilterNode::frequency() const
-{
- return m_frequency;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-detune
-GC::Ref<AudioParam> BiquadFilterNode::detune() const
-{
- return m_detune;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-q
-GC::Ref<AudioParam> BiquadFilterNode::q() const
-{
- return m_q;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-gain
-GC::Ref<AudioParam> BiquadFilterNode::gain() const
-{
- return m_gain;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-getfrequencyresponse
-WebIDL::ExceptionOr<void> BiquadFilterNode::get_frequency_response(GC::Ref<JS::Float32Array> frequency_hz, GC::Ref<JS::Float32Array> mag_response, GC::Ref<JS::Float32Array> phase_response)
-{
- auto length = float32_array_length(*frequency_hz);
-
- // If these arrays do not have the same length, an InvalidAccessError MUST be thrown.
- if (float32_array_length(*mag_response) != length || float32_array_length(*phase_response) != length)
- return WebIDL::InvalidAccessError::create(context()->relevant_settings_object().realm(), "Arrays must have the same length"_utf16);
-
- auto frequencies = copy_float32_array(*frequency_hz);
- Vector<float> magnitudes;
- magnitudes.resize(length);
- Vector<float> phases;
- phases.resize(length);
-
- // The filter response is evaluated with the current parameter values at the context's current time.
- auto current_time = context()->current_time();
- auto nyquist_frequency = context()->nyquist_frequency();
- auto frequency = m_frequency->intrinsic_value_at_time(current_time);
- auto detune = m_detune->intrinsic_value_at_time(current_time);
- auto computed_frequency = frequency * AK::exp2(detune / 1200.);
- auto normalized_frequency = clamp(computed_frequency / nyquist_frequency, 0., 1.);
- auto coefficients = Rendering::compute_biquad_coefficients(m_type, normalized_frequency, m_q->intrinsic_value_at_time(current_time), m_gain->intrinsic_value_at_time(current_time));
-
- for (size_t index = 0; index < length; ++index) {
- auto response_frequency = frequencies[index];
-
- // Frequencies outside the nominal range produce NaN in both output arrays.
- if (isnan(response_frequency) || response_frequency < 0 || response_frequency > nyquist_frequency) {
- magnitudes[index] = NAN;
- phases[index] = NAN;
- continue;
- }
- Rendering::biquad_frequency_response(coefficients, response_frequency / nyquist_frequency, magnitudes[index], phases[index]);
- }
-
- overwrite_float32_array(*mag_response, magnitudes);
- overwrite_float32_array(*phase_response, phases);
- return {};
-}
-
-WebIDL::ExceptionOr<GC::Ref<BiquadFilterNode>> BiquadFilterNode::create(GC::Ref<BaseAudioContext> context, BiquadFilterOptions const& options)
-{
- // When the constructor is called with a BaseAudioContext c and an option object option, the user agent
- // MUST initialize the AudioNode this, with context and options as arguments.
- auto node = GC::Heap::the().allocate<BiquadFilterNode>(context, options);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#BiquadFilterNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count_mode = ChannelCountMode::Max;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- default_options.channel_count = 2;
- // FIXME: Set tail-time to yes
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- node->queue_render_node_creation(make<Rendering::BiquadFilterRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(), node->m_frequency->render_param(), node->m_detune->render_param(), node->m_q->render_param(), node->m_gain->render_param()));
- if (options.type != Bindings::BiquadFilterType::Lowpass)
- context->queue_control_message(NodeMessage { SetBiquadFilterType { node->node_id(), options.type } });
-
- return node;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-biquadfilternode
-WebIDL::ExceptionOr<GC::Ref<BiquadFilterNode>> BiquadFilterNode::create_for_constructor(GC::Ref<BaseAudioContext> context, BiquadFilterOptions const& options)
-{
- return create(context, options);
-}
-
-void BiquadFilterNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_frequency);
- visitor.visit(m_detune);
- visitor.visit(m_q);
- visitor.visit(m_gain);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/BiquadFilterNode.h b/Libraries/LibWeb/WebAudio/BiquadFilterNode.h
deleted file mode 100644
index c4be10ace14..00000000000
--- a/Libraries/LibWeb/WebAudio/BiquadFilterNode.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2024, Bar Yemini <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/BiquadFilterNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-
-namespace Web::WebAudio {
-
-using BiquadFilterType = Bindings::BiquadFilterType;
-using BiquadFilterOptions = Bindings::BiquadFilterOptions;
-
-// https://webaudio.github.io/web-audio-api/#BiquadFilterNode
-class BiquadFilterNode : public AudioNode {
- WEB_WRAPPABLE(BiquadFilterNode, AudioNode);
- GC_DECLARE_ALLOCATOR(BiquadFilterNode);
-
-public:
- virtual ~BiquadFilterNode() override;
-
- WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- void set_type(BiquadFilterType);
- BiquadFilterType type() const;
- GC::Ref<AudioParam> frequency() const;
- GC::Ref<AudioParam> detune() const;
- GC::Ref<AudioParam> q() const;
- GC::Ref<AudioParam> gain() const;
- WebIDL::ExceptionOr<void> get_frequency_response(GC::Ref<JS::Float32Array>, GC::Ref<JS::Float32Array>, GC::Ref<JS::Float32Array>);
-
- static WebIDL::ExceptionOr<GC::Ref<BiquadFilterNode>> create(GC::Ref<BaseAudioContext>, BiquadFilterOptions const& = {});
- static WebIDL::ExceptionOr<GC::Ref<BiquadFilterNode>> create_for_constructor(GC::Ref<BaseAudioContext>, BiquadFilterOptions const& = {});
-
-protected:
- BiquadFilterNode(GC::Ref<BaseAudioContext>, BiquadFilterOptions const& = {});
- virtual void visit_edges(Cell::Visitor&) override;
-
-private:
- BiquadFilterType m_type { BiquadFilterType::Lowpass };
-
- // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-frequency
- GC::Ref<AudioParam> m_frequency;
-
- // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-detune
- GC::Ref<AudioParam> m_detune;
-
- // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-q
- GC::Ref<AudioParam> m_q;
-
- // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-gain
- GC::Ref<AudioParam> m_gain;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/BiquadFilterNode.idl b/Libraries/LibWeb/WebAudio/BiquadFilterNode.idl
index c27d0d9cabf..8656c10844d 100644
--- a/Libraries/LibWeb/WebAudio/BiquadFilterNode.idl
+++ b/Libraries/LibWeb/WebAudio/BiquadFilterNode.idl
@@ -17,7 +17,7 @@ dictionary BiquadFilterOptions : AudioNodeOptions {
float gain = 0;
};
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface BiquadFilterNode : AudioNode {
constructor (BaseAudioContext context, optional BiquadFilterOptions options = {});
attribute BiquadFilterType type;
diff --git a/Libraries/LibWeb/WebAudio/ChannelMergerNode.cpp b/Libraries/LibWeb/WebAudio/ChannelMergerNode.cpp
deleted file mode 100644
index 96ef19d6ed8..00000000000
--- a/Libraries/LibWeb/WebAudio/ChannelMergerNode.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/ChannelMergerNode.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(ChannelMergerNode);
-
-ChannelMergerNode::ChannelMergerNode(GC::Ref<BaseAudioContext> context, ChannelMergerOptions const& options)
- : AudioNode(context)
- , m_number_of_inputs(options.number_of_inputs)
-{
-}
-
-ChannelMergerNode::~ChannelMergerNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<ChannelMergerNode>> ChannelMergerNode::create(GC::Ref<BaseAudioContext> context, ChannelMergerOptions const& options)
-{
- auto node = GC::Heap::the().allocate<ChannelMergerNode>(context, options);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#BiquadFilterNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count_mode = ChannelCountMode::Explicit;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- default_options.channel_count = 1;
- // FIXME: Set tail-time to no
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- node->queue_render_node_creation(make<Rendering::ChannelMergerRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(), options.number_of_inputs));
-
- return node;
-}
-
-WebIDL::ExceptionOr<void> ChannelMergerNode::validate_options(ChannelMergerOptions const& options)
-{
- // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createchannelmerger
- // An IndexSizeError exception MUST be thrown if numberOfInputs is less than 1 or is greater
- // than the number of supported channels.
- if (options.number_of_inputs < 1 || options.number_of_inputs > BaseAudioContext::MAX_NUMBER_OF_CHANNELS)
- return WebIDL::IndexSizeError::create("Invalid number of inputs"_utf16);
-
- return {};
-}
-
-WebIDL::ExceptionOr<GC::Ref<ChannelMergerNode>> ChannelMergerNode::create_for_constructor(GC::Ref<BaseAudioContext> context, ChannelMergerOptions const& options)
-{
- TRY(validate_options(options));
- return create(context, options);
-}
-
-// https://webaudio.github.io/web-audio-api/#audionode-channelcount-constraints
-WebIDL::ExceptionOr<void> ChannelMergerNode::set_channel_count(WebIDL::UnsignedLong channel_count)
-{
- // The channel count cannot be changed, and an InvalidStateError exception MUST be thrown for
- // any attempt to change the value.
- if (channel_count != 1)
- return WebIDL::InvalidStateError::create("Channel count cannot be changed"_utf16);
-
- return Base::set_channel_count(channel_count);
-}
-
-WebIDL::ExceptionOr<void> ChannelMergerNode::set_channel_count_mode(ChannelCountMode channel_count_mode)
-{
- // The channel count mode cannot be changed from "explicit" and an InvalidStateError exception
- // MUST be thrown for any attempt to change the value.
- if (channel_count_mode != ChannelCountMode::Explicit)
- return WebIDL::InvalidStateError::create("Channel count mode cannot be changed"_utf16);
-
- return Base::set_channel_count_mode(channel_count_mode);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/ChannelMergerNode.h b/Libraries/LibWeb/WebAudio/ChannelMergerNode.h
deleted file mode 100644
index 98f512364c8..00000000000
--- a/Libraries/LibWeb/WebAudio/ChannelMergerNode.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/ChannelMergerNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio {
-
-using ChannelMergerOptions = Bindings::ChannelMergerOptions;
-
-// https://webaudio.github.io/web-audio-api/#ChannelMergerNode
-class ChannelMergerNode final : public AudioNode {
- WEB_WRAPPABLE(ChannelMergerNode, AudioNode);
- GC_DECLARE_ALLOCATOR(ChannelMergerNode);
-
-public:
- virtual ~ChannelMergerNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<ChannelMergerNode>> create(GC::Ref<BaseAudioContext>, ChannelMergerOptions const& = {});
- static WebIDL::ExceptionOr<void> validate_options(ChannelMergerOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<ChannelMergerNode>> create_for_constructor(GC::Ref<BaseAudioContext>, ChannelMergerOptions const& = {});
-
- WebIDL::UnsignedLong number_of_inputs() override { return m_number_of_inputs; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- // ^AudioNode
- virtual WebIDL::ExceptionOr<void> set_channel_count(WebIDL::UnsignedLong) override;
- virtual WebIDL::ExceptionOr<void> set_channel_count_mode(ChannelCountMode) override;
-
-private:
- ChannelMergerNode(GC::Ref<BaseAudioContext>, ChannelMergerOptions const&);
-
- WebIDL::UnsignedLong m_number_of_inputs;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/ChannelMergerNode.idl b/Libraries/LibWeb/WebAudio/ChannelMergerNode.idl
index 2c3ce744331..0071d31c379 100644
--- a/Libraries/LibWeb/WebAudio/ChannelMergerNode.idl
+++ b/Libraries/LibWeb/WebAudio/ChannelMergerNode.idl
@@ -1,5 +1,5 @@
// https://webaudio.github.io/web-audio-api/#ChannelMergerNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface ChannelMergerNode : AudioNode {
constructor (BaseAudioContext context, optional ChannelMergerOptions options = {});
};
diff --git a/Libraries/LibWeb/WebAudio/ChannelSplitterNode.cpp b/Libraries/LibWeb/WebAudio/ChannelSplitterNode.cpp
deleted file mode 100644
index 8f5e1a39b7b..00000000000
--- a/Libraries/LibWeb/WebAudio/ChannelSplitterNode.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (c) 2025, Tim Ledbetter <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/ChannelSplitterNode.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(ChannelSplitterNode);
-
-ChannelSplitterNode::ChannelSplitterNode(GC::Ref<BaseAudioContext> context, ChannelSplitterOptions const& options)
- : AudioNode(context)
- , m_number_of_outputs(options.number_of_outputs)
-{
-}
-
-ChannelSplitterNode::~ChannelSplitterNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<ChannelSplitterNode>> ChannelSplitterNode::create(GC::Ref<BaseAudioContext> context, ChannelSplitterOptions const& options)
-{
- auto node = GC::Heap::the().allocate<ChannelSplitterNode>(context, options);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#ChannelSplitterNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count_mode = ChannelCountMode::Explicit;
- default_options.channel_interpretation = ChannelInterpretation::Discrete;
- default_options.channel_count = node->number_of_outputs();
- // FIXME: Set tail-time to no
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- node->queue_render_node_creation(make<Rendering::ChannelSplitterRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(), options.number_of_outputs));
-
- return node;
-}
-
-WebIDL::ExceptionOr<void> ChannelSplitterNode::validate_options(ChannelSplitterOptions const& options)
-{
- // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createchannelsplitter
- // An IndexSizeError exception MUST be thrown if numberOfOutputs is less than 1 or is greater than the number of supported channels.
- if (options.number_of_outputs < 1 || options.number_of_outputs > BaseAudioContext::MAX_NUMBER_OF_CHANNELS)
- return WebIDL::IndexSizeError::create("Invalid number of outputs"_utf16);
-
- return {};
-}
-
-WebIDL::ExceptionOr<GC::Ref<ChannelSplitterNode>> ChannelSplitterNode::create_for_constructor(GC::Ref<BaseAudioContext> context, ChannelSplitterOptions const& options)
-{
- TRY(validate_options(options));
- return create(context, options);
-}
-
-WebIDL::ExceptionOr<void> ChannelSplitterNode::set_channel_count(WebIDL::UnsignedLong channel_count)
-{
- // https://webaudio.github.io/web-audio-api/#audionode-channelcount-constraints
- // The channel count cannot be changed, and an InvalidStateError exception MUST be thrown for any attempt to change the value.
- if (channel_count != m_number_of_outputs)
- return WebIDL::InvalidStateError::create("Channel count must be equal to number of outputs"_utf16);
-
- return AudioNode::set_channel_count(channel_count);
-}
-
-WebIDL::ExceptionOr<void> ChannelSplitterNode::set_channel_count_mode(ChannelCountMode channel_count_mode)
-{
- // https://webaudio.github.io/web-audio-api/#audionode-channelcountmode-constraints
- // The channel count mode cannot be changed from "explicit" and an InvalidStateError exception MUST be thrown for any attempt to change the value.
- if (channel_count_mode != ChannelCountMode::Explicit)
- return WebIDL::InvalidStateError::create("Channel count mode must be 'explicit'"_utf16);
-
- return AudioNode::set_channel_count_mode(channel_count_mode);
-}
-
-WebIDL::ExceptionOr<void> ChannelSplitterNode::set_channel_interpretation(ChannelInterpretation channel_interpretation)
-{
- // https://webaudio.github.io/web-audio-api/#audionode-channelinterpretation-constraints
- // The channel interpretation can not be changed from "discrete" and a InvalidStateError exception MUST be thrown for any attempt to change the value.
- if (channel_interpretation != ChannelInterpretation::Discrete)
- return WebIDL::InvalidStateError::create("Channel interpretation must be 'discrete'"_utf16);
-
- return AudioNode::set_channel_interpretation(channel_interpretation);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/ChannelSplitterNode.h b/Libraries/LibWeb/WebAudio/ChannelSplitterNode.h
deleted file mode 100644
index 258737dc95b..00000000000
--- a/Libraries/LibWeb/WebAudio/ChannelSplitterNode.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2025, Tim Ledbetter <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/ChannelSplitterNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio {
-
-using ChannelSplitterOptions = Bindings::ChannelSplitterOptions;
-
-/// https://webaudio.github.io/web-audio-api/#ChannelSplitterNode
-class ChannelSplitterNode final : public AudioNode {
- WEB_WRAPPABLE(ChannelSplitterNode, AudioNode);
- GC_DECLARE_ALLOCATOR(ChannelSplitterNode);
-
-public:
- virtual ~ChannelSplitterNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<ChannelSplitterNode>> create(GC::Ref<BaseAudioContext>, ChannelSplitterOptions const& = {});
- static WebIDL::ExceptionOr<void> validate_options(ChannelSplitterOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<ChannelSplitterNode>> create_for_constructor(GC::Ref<BaseAudioContext>, ChannelSplitterOptions const& = {});
-
- virtual WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- virtual WebIDL::UnsignedLong number_of_outputs() override { return m_number_of_outputs; }
-
- virtual WebIDL::ExceptionOr<void> set_channel_count(WebIDL::UnsignedLong) override;
- virtual WebIDL::ExceptionOr<void> set_channel_count_mode(ChannelCountMode) override;
- virtual WebIDL::ExceptionOr<void> set_channel_interpretation(ChannelInterpretation) override;
-
-private:
- ChannelSplitterNode(GC::Ref<BaseAudioContext>, ChannelSplitterOptions const&);
-
- WebIDL::UnsignedLong m_number_of_outputs;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/ChannelSplitterNode.idl b/Libraries/LibWeb/WebAudio/ChannelSplitterNode.idl
index c8e053e55be..6e2d9e9e86e 100644
--- a/Libraries/LibWeb/WebAudio/ChannelSplitterNode.idl
+++ b/Libraries/LibWeb/WebAudio/ChannelSplitterNode.idl
@@ -1,5 +1,5 @@
// https://webaudio.github.io/web-audio-api/#ChannelSplitterNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface ChannelSplitterNode : AudioNode {
constructor (BaseAudioContext context, optional ChannelSplitterOptions options = {});
};
diff --git a/Libraries/LibWeb/WebAudio/ConstantSourceNode.cpp b/Libraries/LibWeb/WebAudio/ConstantSourceNode.cpp
deleted file mode 100644
index 95ce73e6c0c..00000000000
--- a/Libraries/LibWeb/WebAudio/ConstantSourceNode.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2025, Tim Ledbetter <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/NumericLimits.h>
-#include <LibGC/Heap.h>
-#include <LibWeb/Bindings/ConstantSourceNode.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/ConstantSourceNode.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(ConstantSourceNode);
-
-ConstantSourceNode::ConstantSourceNode(GC::Ref<BaseAudioContext> context, float offset)
- : AudioScheduledSourceNode(context)
- , m_offset(AudioParam::create(context, this, offset, NumericLimits<float>::lowest(), NumericLimits<float>::max(), AutomationRate::ARate))
-{
-}
-
-ConstantSourceNode::~ConstantSourceNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<ConstantSourceNode>> ConstantSourceNode::create(GC::Ref<BaseAudioContext> context, float offset)
-{
- auto node = GC::Heap::the().allocate<ConstantSourceNode>(context, offset);
- node->queue_render_node_creation(make<Rendering::ConstantSourceRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(), node->m_offset->render_param()));
- return node;
-}
-
-WebIDL::ExceptionOr<GC::Ref<ConstantSourceNode>> ConstantSourceNode::create_for_constructor(GC::Ref<BaseAudioContext> context, Bindings::ConstantSourceOptions const& options)
-{
- return create_for_constructor(context, options.offset);
-}
-
-WebIDL::ExceptionOr<GC::Ref<ConstantSourceNode>> ConstantSourceNode::create_for_constructor(GC::Ref<BaseAudioContext> context, float offset)
-{
- return create(context, offset);
-}
-
-void ConstantSourceNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_offset);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/ConstantSourceNode.h b/Libraries/LibWeb/WebAudio/ConstantSourceNode.h
deleted file mode 100644
index 378a5dbfc79..00000000000
--- a/Libraries/LibWeb/WebAudio/ConstantSourceNode.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2025, Tim Ledbetter <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/WebAudio/AudioScheduledSourceNode.h>
-
-namespace Web::Bindings {
-
-struct ConstantSourceOptions;
-
-}
-
-namespace Web::WebAudio {
-
-// https://webaudio.github.io/web-audio-api/#ChannelMergerNode
-class ConstantSourceNode final : public AudioScheduledSourceNode {
- WEB_WRAPPABLE(ConstantSourceNode, AudioScheduledSourceNode);
- GC_DECLARE_ALLOCATOR(ConstantSourceNode);
-
-public:
- static constexpr size_t offset_offset() { return offsetof(ConstantSourceNode, m_offset); }
- virtual ~ConstantSourceNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<ConstantSourceNode>> create(GC::Ref<BaseAudioContext>, float offset = 1);
- static WebIDL::ExceptionOr<GC::Ref<ConstantSourceNode>> create_for_constructor(GC::Ref<BaseAudioContext>, Bindings::ConstantSourceOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<ConstantSourceNode>> create_for_constructor(GC::Ref<BaseAudioContext>, float offset = 1);
-
- virtual WebIDL::UnsignedLong number_of_inputs() override { return 0; }
- virtual WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- GC::Ref<AudioParam const> offset() const { return m_offset; }
-
-private:
- ConstantSourceNode(GC::Ref<BaseAudioContext>, float offset);
- virtual void visit_edges(Cell::Visitor&) override;
-
- // https://webaudio.github.io/web-audio-api/#dom-constantsourcenode-offset
- GC::Ref<AudioParam> m_offset;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/ConstantSourceNode.idl b/Libraries/LibWeb/WebAudio/ConstantSourceNode.idl
index 96cdede5626..acc5157ad7a 100644
--- a/Libraries/LibWeb/WebAudio/ConstantSourceNode.idl
+++ b/Libraries/LibWeb/WebAudio/ConstantSourceNode.idl
@@ -4,7 +4,7 @@ dictionary ConstantSourceOptions {
};
// https://webaudio.github.io/web-audio-api/#ConstantSourceNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface ConstantSourceNode : AudioScheduledSourceNode {
constructor (BaseAudioContext context, optional ConstantSourceOptions options = {});
readonly attribute AudioParam offset;
diff --git a/Libraries/LibWeb/WebAudio/ConvolverNode.cpp b/Libraries/LibWeb/WebAudio/ConvolverNode.cpp
deleted file mode 100644
index b860df0321f..00000000000
--- a/Libraries/LibWeb/WebAudio/ConvolverNode.cpp
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/ConvolverNode.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(ConvolverNode);
-
-ConvolverNode::ConvolverNode(GC::Ref<BaseAudioContext> context, ConvolverOptions const& options)
- : AudioNode(context)
- , m_normalize(!options.disable_normalization)
-{
-}
-
-ConvolverNode::~ConvolverNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<ConvolverNode>> ConvolverNode::create(GC::Ref<BaseAudioContext> context, ConvolverOptions const& options)
-{
- // NB: Creating a node through its factory method is defined to run the same steps as its constructor.
- return create_for_constructor(context, options);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-convolvernode-convolvernode
-WebIDL::ExceptionOr<GC::Ref<ConvolverNode>> ConvolverNode::create_for_constructor(GC::Ref<BaseAudioContext> context, ConvolverOptions const& options)
-{
- // NB: The node and its render node are created up front, so that step 2 has something to hand the impulse
- // response to.
- auto node = GC::Heap::the().allocate<ConvolverNode>(context, options);
- node->queue_render_node_creation(make<Rendering::ConvolverRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size()));
-
- // 1. Set the attributes normalize to the inverse of the value of disableNormalization.
- // NB: Done by the constructor above, so that step 2 already sees the final value.
-
- // 2. If buffer exists, set the buffer attribute to its value.
- if (options.buffer.has_value())
- TRY(node->set_buffer(*options.buffer));
-
- // 3. Let o be new AudioNodeOptions dictionary.
- // 4. If channelCount exists in options, set channelCount on o with the same value.
- // 5. If channelCountMode exists in options, set channelCountMode on o with the same value.
- // 6. If channelInterpretation exists in options, set channelInterpretation on o with the same value.
- // 7. Initialize the AudioNode this, with c and o as argument.
- AudioNodeDefaultOptions default_options;
- default_options.channel_count = 2;
- default_options.channel_count_mode = ChannelCountMode::ClampedMax;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- // FIXME: Set tail-time to yes
- TRY(node->initialize_audio_node_options(options, default_options));
-
- return node;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-convolvernode-buffer
-WebIDL::ExceptionOr<void> ConvolverNode::set_buffer(GC::Ptr<AudioBuffer> buffer)
-{
- // 1. If the buffer number of channels is not 1, 2, 4, or if the sample-rate of the buffer is not the same as the
- // sample-rate of its associated BaseAudioContext, a NotSupportedError MUST be thrown.
- // AD-HOC: The steps do not cover a null buffer, which clears the impulse response and leaves the node silent.
- if (buffer) {
- auto number_of_channels = buffer->number_of_channels();
- if (number_of_channels != 1 && number_of_channels != 2 && number_of_channels != 4)
- return WebIDL::NotSupportedError::create("ConvolverNode buffer must have 1, 2 or 4 channels"_utf16);
-
- if (buffer->sample_rate() != context()->sample_rate())
- return WebIDL::NotSupportedError::create("ConvolverNode buffer must have the same sample rate as its context"_utf16);
- }
-
- m_buffer = buffer;
-
- // 2. Acquire the content of the AudioBuffer.
- // NB: The acquired content is cut into partitions and transformed here, and the delay line that the rendering
- // thread pairs those partitions with is sized and allocated alongside it, so that the rendering thread
- // receives both ready to use and never has to build either during a render quantum.
- RefPtr<Rendering::ConvolverKernel> kernel;
- RefPtr<Rendering::ConvolverDelayLine> delay_line;
- if (buffer) {
- if (auto contents = buffer->acquire_contents())
- kernel = Rendering::ConvolverKernel::create(*contents, BaseAudioContext::render_quantum_size(), m_normalize);
- if (kernel)
- delay_line = Rendering::ConvolverDelayLine::create(*kernel);
- }
-
- context()->queue_control_message(NodeMessage { SetConvolverKernel {
- .node_id = node_id(),
- .kernel = move(kernel),
- .delay_line = move(delay_line),
- } });
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#audionode-channelcount-constraints
-WebIDL::ExceptionOr<void> ConvolverNode::set_channel_count(WebIDL::UnsignedLong channel_count)
-{
- // The channel count cannot be greater than two, and a NotSupportedError exception MUST be thrown for any attempt
- // to change it to a value greater than two.
- if (channel_count > 2)
- return WebIDL::NotSupportedError::create("ConvolverNode does not support channel count greater than 2"_utf16);
-
- return AudioNode::set_channel_count(channel_count);
-}
-
-// https://webaudio.github.io/web-audio-api/#audionode-channelcountmode-constraints
-WebIDL::ExceptionOr<void> ConvolverNode::set_channel_count_mode(ChannelCountMode mode)
-{
- // The channel count mode cannot be set to "max", and a NotSupportedError exception MUST be thrown for any attempt
- // to set it to "max".
- if (mode == ChannelCountMode::Max)
- return WebIDL::NotSupportedError::create("ConvolverNode does not support 'max' as channelCountMode."_utf16);
-
- return AudioNode::set_channel_count_mode(mode);
-}
-
-void ConvolverNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_buffer);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/ConvolverNode.h b/Libraries/LibWeb/WebAudio/ConvolverNode.h
deleted file mode 100644
index b553a8a87a9..00000000000
--- a/Libraries/LibWeb/WebAudio/ConvolverNode.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/ConvolverNode.h>
-#include <LibWeb/WebAudio/AudioBuffer.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio {
-
-using ConvolverOptions = Bindings::ConvolverOptions;
-
-// https://webaudio.github.io/web-audio-api/#ConvolverNode
-class ConvolverNode final : public AudioNode {
- WEB_WRAPPABLE(ConvolverNode, AudioNode);
- GC_DECLARE_ALLOCATOR(ConvolverNode);
-
-public:
- virtual ~ConvolverNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<ConvolverNode>> create(GC::Ref<BaseAudioContext>, ConvolverOptions const& = {});
- static WebIDL::ExceptionOr<GC::Ref<ConvolverNode>> create_for_constructor(GC::Ref<BaseAudioContext>, ConvolverOptions const& = {});
-
- WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- GC::Ptr<AudioBuffer> buffer() const { return m_buffer; }
- WebIDL::ExceptionOr<void> set_buffer(GC::Ptr<AudioBuffer>);
-
- bool normalize() const { return m_normalize; }
- void set_normalize(bool normalize) { m_normalize = normalize; }
-
- WebIDL::ExceptionOr<void> set_channel_count(WebIDL::UnsignedLong) override;
- WebIDL::ExceptionOr<void> set_channel_count_mode(ChannelCountMode) override;
-
-private:
- ConvolverNode(GC::Ref<BaseAudioContext>, ConvolverOptions const&);
- virtual void visit_edges(Cell::Visitor&) override;
-
- // https://webaudio.github.io/web-audio-api/#dom-convolvernode-buffer
- GC::Ptr<AudioBuffer> m_buffer;
-
- // https://webaudio.github.io/web-audio-api/#dom-convolvernode-normalize
- bool m_normalize { true };
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/ConvolverNode.idl b/Libraries/LibWeb/WebAudio/ConvolverNode.idl
index d974e20d3d1..02262817a9c 100644
--- a/Libraries/LibWeb/WebAudio/ConvolverNode.idl
+++ b/Libraries/LibWeb/WebAudio/ConvolverNode.idl
@@ -5,7 +5,7 @@ dictionary ConvolverOptions : AudioNodeOptions {
};
// https://webaudio.github.io/web-audio-api/#ConvolverNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface ConvolverNode : AudioNode {
constructor (BaseAudioContext context, optional ConvolverOptions options = {});
attribute AudioBuffer? buffer;
diff --git a/Libraries/LibWeb/WebAudio/DelayNode.cpp b/Libraries/LibWeb/WebAudio/DelayNode.cpp
deleted file mode 100644
index 35763c195ec..00000000000
--- a/Libraries/LibWeb/WebAudio/DelayNode.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (c) 2025, Tim Ledbetter <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/DelayNode.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(DelayNode);
-
-DelayNode::DelayNode(GC::Ref<BaseAudioContext> context, DelayOptions const& options)
- : AudioNode(context)
- , m_delay_time(AudioParam::create(context, this, options.delay_time, 0, options.max_delay_time, AutomationRate::ARate))
-{
-}
-
-DelayNode::~DelayNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<DelayNode>> DelayNode::create(GC::Ref<BaseAudioContext> context, DelayOptions const& options)
-{
- auto node = GC::Heap::the().allocate<DelayNode>(context, options);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#DelayNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count = 2;
- default_options.channel_count_mode = ChannelCountMode::Max;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- // FIXME: Set tail-time to yes
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- node->queue_render_node_creation(make<Rendering::DelayRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(), node->m_delay_time->render_param(), options.max_delay_time));
-
- return node;
-}
-
-WebIDL::ExceptionOr<void> DelayNode::validate_options(DelayOptions const& options)
-{
- // https://webaudio.github.io/web-audio-api/#dom-delayoptions-maxdelaytime
- // If specified, this value MUST be greater than zero and less than three minutes or a NotSupportedError exception MUST be thrown.
- static constexpr double maximum_delay_time_seconds = 180;
- if (options.max_delay_time <= 0 || options.max_delay_time >= maximum_delay_time_seconds || isnan(options.max_delay_time))
- return WebIDL::NotSupportedError::create("Max delay time must be between 0 and 180 seconds exclusive"_utf16);
-
- return {};
-}
-
-WebIDL::ExceptionOr<GC::Ref<DelayNode>> DelayNode::create_for_constructor(GC::Ref<BaseAudioContext> context, DelayOptions const& options)
-{
- TRY(validate_options(options));
- return create(context, options);
-}
-
-void DelayNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_delay_time);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/DelayNode.h b/Libraries/LibWeb/WebAudio/DelayNode.h
deleted file mode 100644
index c721301934e..00000000000
--- a/Libraries/LibWeb/WebAudio/DelayNode.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2025, Tim Ledbetter <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/DelayNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio {
-
-using DelayOptions = Bindings::DelayOptions;
-
-// https://webaudio.github.io/web-audio-api/#DelayNode
-class DelayNode final : public AudioNode {
- WEB_WRAPPABLE(DelayNode, AudioNode);
- GC_DECLARE_ALLOCATOR(DelayNode);
-
-public:
- static constexpr size_t delay_time_offset() { return offsetof(DelayNode, m_delay_time); }
- virtual ~DelayNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<DelayNode>> create(GC::Ref<BaseAudioContext>, DelayOptions const& = {});
- static WebIDL::ExceptionOr<void> validate_options(DelayOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<DelayNode>> create_for_constructor(GC::Ref<BaseAudioContext>, DelayOptions const& = {});
-
- virtual WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- virtual WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- GC::Ref<AudioParam const> delay_time() const { return m_delay_time; }
-
-private:
- DelayNode(GC::Ref<BaseAudioContext>, DelayOptions const&);
- virtual void visit_edges(Cell::Visitor&) override;
-
- // https://webaudio.github.io/web-audio-api/#dom-delaynode-delaytime
- GC::Ref<AudioParam> m_delay_time;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/DelayNode.idl b/Libraries/LibWeb/WebAudio/DelayNode.idl
index 28e6689f6f6..bb2cc46c449 100644
--- a/Libraries/LibWeb/WebAudio/DelayNode.idl
+++ b/Libraries/LibWeb/WebAudio/DelayNode.idl
@@ -5,7 +5,7 @@ dictionary DelayOptions : AudioNodeOptions {
};
// https://webaudio.github.io/web-audio-api/#DelayNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface DelayNode : AudioNode {
constructor (BaseAudioContext context, optional DelayOptions options = {});
readonly attribute AudioParam delayTime;
diff --git a/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.cpp b/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.cpp
deleted file mode 100644
index 569000e2a7a..00000000000
--- a/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/DynamicsCompressorNode.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(DynamicsCompressorNode);
-
-DynamicsCompressorNode::~DynamicsCompressorNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<DynamicsCompressorNode>> DynamicsCompressorNode::create(GC::Ref<BaseAudioContext> context, DynamicsCompressorOptions const& options)
-{
- // Create the node and allocate memory
- auto node = GC::Heap::the().allocate<DynamicsCompressorNode>(context, options);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#DynamicsCompressorNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count_mode = ChannelCountMode::ClampedMax;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- default_options.channel_count = 2;
- // FIXME: Set tail-time to yes
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- // FIXME: Implement actual dynamics compression; for now the signal passes through unchanged.
- node->queue_render_node_creation(make<Rendering::PassthroughRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size()));
-
- return node;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-dynamicscompressornode
-WebIDL::ExceptionOr<GC::Ref<DynamicsCompressorNode>> DynamicsCompressorNode::create_for_constructor(GC::Ref<BaseAudioContext> context, DynamicsCompressorOptions const& options)
-{
- return create(context, options);
-}
-
-DynamicsCompressorNode::DynamicsCompressorNode(GC::Ref<BaseAudioContext> context, DynamicsCompressorOptions const& options)
- : AudioNode(context)
- , m_threshold(AudioParam::create(context, this, options.threshold, -100, 0, AutomationRate::KRate, AudioParam::FixedAutomationRate::Yes))
- , m_knee(AudioParam::create(context, this, options.knee, 0, 40, AutomationRate::KRate, AudioParam::FixedAutomationRate::Yes))
- , m_ratio(AudioParam::create(context, this, options.ratio, 1, 20, AutomationRate::KRate, AudioParam::FixedAutomationRate::Yes))
- , m_attack(AudioParam::create(context, this, options.attack, 0, 1, AutomationRate::KRate, AudioParam::FixedAutomationRate::Yes))
- , m_release(AudioParam::create(context, this, options.release, 0, 1, AutomationRate::KRate, AudioParam::FixedAutomationRate::Yes))
-{
-}
-
-void DynamicsCompressorNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_threshold);
- visitor.visit(m_knee);
- visitor.visit(m_ratio);
- visitor.visit(m_attack);
- visitor.visit(m_release);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
-WebIDL::ExceptionOr<void> DynamicsCompressorNode::set_channel_count_mode(ChannelCountMode mode)
-{
- if (mode == ChannelCountMode::Max) {
- // Return a NotSupportedError if 'max' is used
- return WebIDL::NotSupportedError::create("DynamicsCompressorNode does not support 'max' as channelCountMode."_utf16);
- }
-
- // If the mode is valid, call the base class implementation
- return AudioNode::set_channel_count_mode(mode);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
-WebIDL::ExceptionOr<void> DynamicsCompressorNode::set_channel_count(WebIDL::UnsignedLong channel_count)
-{
- if (channel_count > 2) {
- return WebIDL::NotSupportedError::create("DynamicsCompressorNode does not support channel count greater than 2"_utf16);
- }
-
- return AudioNode::set_channel_count(channel_count);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.h b/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.h
deleted file mode 100644
index e33bf1dcf87..00000000000
--- a/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/DynamicsCompressorNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio {
-
-using DynamicsCompressorOptions = Bindings::DynamicsCompressorOptions;
-
-// https://webaudio.github.io/web-audio-api/#DynamicsCompressorNode
-class DynamicsCompressorNode : public AudioNode {
- WEB_WRAPPABLE(DynamicsCompressorNode, AudioNode);
- GC_DECLARE_ALLOCATOR(DynamicsCompressorNode);
-
-public:
- static constexpr size_t threshold_offset() { return offsetof(DynamicsCompressorNode, m_threshold); }
- static constexpr size_t knee_offset() { return offsetof(DynamicsCompressorNode, m_knee); }
- static constexpr size_t ratio_offset() { return offsetof(DynamicsCompressorNode, m_ratio); }
- static constexpr size_t attack_offset() { return offsetof(DynamicsCompressorNode, m_attack); }
- static constexpr size_t release_offset() { return offsetof(DynamicsCompressorNode, m_release); }
- virtual ~DynamicsCompressorNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<DynamicsCompressorNode>> create(GC::Ref<BaseAudioContext>, DynamicsCompressorOptions const& = {});
- static WebIDL::ExceptionOr<GC::Ref<DynamicsCompressorNode>> create_for_constructor(GC::Ref<BaseAudioContext>, DynamicsCompressorOptions const& = {});
-
- WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- GC::Ref<AudioParam const> threshold() const { return m_threshold; }
- GC::Ref<AudioParam const> knee() const { return m_knee; }
- GC::Ref<AudioParam const> ratio() const { return m_ratio; }
- GC::Ref<AudioParam const> attack() const { return m_attack; }
- GC::Ref<AudioParam const> release() const { return m_release; }
- float reduction() const { return m_reduction; }
-
- WebIDL::ExceptionOr<void> set_channel_count_mode(ChannelCountMode) override;
- WebIDL::ExceptionOr<void> set_channel_count(WebIDL::UnsignedLong) override;
-
-protected:
- DynamicsCompressorNode(GC::Ref<BaseAudioContext>, DynamicsCompressorOptions const& = {});
- virtual void visit_edges(Cell::Visitor&) override;
-
-private:
- // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-threshold
- GC::Ref<AudioParam> m_threshold;
-
- // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-knee
- GC::Ref<AudioParam> m_knee;
-
- // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-ratio
- GC::Ref<AudioParam> m_ratio;
-
- // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-attack
- GC::Ref<AudioParam> m_attack;
-
- // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-release
- GC::Ref<AudioParam> m_release;
-
- // https://webaudio.github.io/web-audio-api/#dom-dynamicscompressornode-internal-reduction-slot
- float m_reduction { 0 }; // [[internal reduction]]
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.idl b/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.idl
index 3d8f14548a5..827ca49cfc5 100644
--- a/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.idl
+++ b/Libraries/LibWeb/WebAudio/DynamicsCompressorNode.idl
@@ -8,7 +8,7 @@ dictionary DynamicsCompressorOptions : AudioNodeOptions {
};
// https://webaudio.github.io/web-audio-api/#DynamicsCompressorNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface DynamicsCompressorNode : AudioNode {
constructor(BaseAudioContext context,
optional DynamicsCompressorOptions options = {});
diff --git a/Libraries/LibWeb/WebAudio/GainNode.cpp b/Libraries/LibWeb/WebAudio/GainNode.cpp
deleted file mode 100644
index 56588da59b1..00000000000
--- a/Libraries/LibWeb/WebAudio/GainNode.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/NumericLimits.h>
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/GainNode.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(GainNode);
-
-GainNode::~GainNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<GainNode>> GainNode::create(GC::Ref<BaseAudioContext> context, GainOptions const& options)
-{
- // Create the node and allocate memory
- auto node = GC::Heap::the().allocate<GainNode>(context, options);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#GainNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count_mode = ChannelCountMode::Max;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- default_options.channel_count = 2;
- // FIXME: Set tail-time to no
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- node->queue_render_node_creation(make<Rendering::GainRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(), node->m_gain->render_param()));
-
- return node;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-gainnode-gainnode
-WebIDL::ExceptionOr<GC::Ref<GainNode>> GainNode::create_for_constructor(GC::Ref<BaseAudioContext> context, GainOptions const& options)
-{
- return create(context, options);
-}
-
-GainNode::GainNode(GC::Ref<BaseAudioContext> context, GainOptions const& options)
- : AudioNode(context)
- , m_gain(AudioParam::create(context, this, options.gain, NumericLimits<float>::lowest(), NumericLimits<float>::max(), AutomationRate::ARate))
-{
-}
-
-void GainNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_gain);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/GainNode.h b/Libraries/LibWeb/WebAudio/GainNode.h
deleted file mode 100644
index 58e650a7500..00000000000
--- a/Libraries/LibWeb/WebAudio/GainNode.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/GainNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio {
-
-using GainOptions = Bindings::GainOptions;
-
-// https://webaudio.github.io/web-audio-api/#GainNode
-class GainNode : public AudioNode {
- WEB_WRAPPABLE(GainNode, AudioNode);
- GC_DECLARE_ALLOCATOR(GainNode);
-
-public:
- static constexpr size_t gain_offset() { return offsetof(GainNode, m_gain); }
- virtual ~GainNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<GainNode>> create(GC::Ref<BaseAudioContext>, GainOptions const& = {});
- static WebIDL::ExceptionOr<GC::Ref<GainNode>> create_for_constructor(GC::Ref<BaseAudioContext>, GainOptions const& = {});
-
- WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- GC::Ref<AudioParam const> gain() const { return m_gain; }
-
-protected:
- GainNode(GC::Ref<BaseAudioContext>, GainOptions const& = {});
- virtual void visit_edges(Cell::Visitor&) override;
-
-private:
- // https://webaudio.github.io/web-audio-api/#dom-gainnode-gain
- GC::Ref<AudioParam> m_gain;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/GainNode.idl b/Libraries/LibWeb/WebAudio/GainNode.idl
index d131bd9486e..8582d796c97 100644
--- a/Libraries/LibWeb/WebAudio/GainNode.idl
+++ b/Libraries/LibWeb/WebAudio/GainNode.idl
@@ -4,7 +4,7 @@ dictionary GainOptions : AudioNodeOptions {
};
// https://webaudio.github.io/web-audio-api/#GainNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface GainNode : AudioNode {
constructor(BaseAudioContext context, optional GainOptions options = {});
readonly attribute AudioParam gain;
diff --git a/Libraries/LibWeb/WebAudio/IIRFilterNode.cpp b/Libraries/LibWeb/WebAudio/IIRFilterNode.cpp
deleted file mode 100644
index 428855ee050..00000000000
--- a/Libraries/LibWeb/WebAudio/IIRFilterNode.cpp
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Math.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/WebAudio/AudioArray.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/IIRFilterNode.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-#include <LibWeb/WebIDL/DOMException.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(IIRFilterNode);
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createiirfilter
-static constexpr size_t max_coefficient_count = 20;
-
-IIRFilterNode::IIRFilterNode(GC::Ref<BaseAudioContext> context, Vector<double> feedforward, Vector<double> feedback)
- : AudioNode(context)
- , m_feedforward(move(feedforward))
- , m_feedback(move(feedback))
-{
-}
-
-IIRFilterNode::~IIRFilterNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<IIRFilterNode>> IIRFilterNode::create(GC::Ref<BaseAudioContext> context, IIRFilterOptions const& options)
-{
- // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createiirfilter
- // feedforward: An array of the feedforward (numerator) coefficients for the transfer function of the IIR filter.
- // The maximum length of this array is 20. If all of the values are zero, an InvalidStateError MUST be thrown. A
- // NotSupportedError MUST be thrown if the array length is 0 or greater than 20.
- // feedback: An array of the feedback (denominator) coefficients for the transfer function of the IIR filter. The
- // maximum length of this array is 20. If the first element of the array is 0, an InvalidStateError MUST be thrown.
- // A NotSupportedError MUST be thrown if the array length is 0 or greater than 20.
- auto const& feedforward = options.feedforward;
- auto const& feedback = options.feedback;
- if (feedforward.is_empty() || feedforward.size() > max_coefficient_count)
- return WebIDL::NotSupportedError::create("The number of feedforward coefficients must be between 1 and 20"_utf16);
- if (feedback.is_empty() || feedback.size() > max_coefficient_count)
- return WebIDL::NotSupportedError::create("The number of feedback coefficients must be between 1 and 20"_utf16);
- if (all_of(feedforward, [](double coefficient) { return coefficient == 0; }))
- return WebIDL::InvalidStateError::create("At least one feedforward coefficient must not be zero"_utf16);
- if (feedback.first() == 0)
- return WebIDL::InvalidStateError::create("The first feedback coefficient must not be zero"_utf16);
-
- // https://webaudio.github.io/web-audio-api/#IIRFilterNode-filter-definition
- // NB: Dividing every coefficient by a_0 gives the same transfer function with a_0 = 1, which the filter uses.
- auto a0 = feedback.first();
- Vector<double> normalized_feedforward;
- normalized_feedforward.ensure_capacity(feedforward.size());
- for (auto coefficient : feedforward)
- normalized_feedforward.unchecked_append(coefficient / a0);
- Vector<double> normalized_feedback;
- normalized_feedback.ensure_capacity(feedback.size());
- for (auto coefficient : feedback)
- normalized_feedback.unchecked_append(coefficient / a0);
-
- // When the constructor is called with a BaseAudioContext c and an option object option, the user agent MUST
- // initialize the AudioNode this, with context and options as arguments.
- auto node = GC::Heap::the().allocate<IIRFilterNode>(context, normalized_feedforward, normalized_feedback);
-
- // https://webaudio.github.io/web-audio-api/#IIRFilterNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count_mode = ChannelCountMode::Max;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- default_options.channel_count = 2;
- // FIXME: Set tail-time to yes
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- node->queue_render_node_creation(make<Rendering::IIRFilterRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(), move(normalized_feedforward), move(normalized_feedback)));
-
- return node;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-iirfilternode-iirfilternode
-WebIDL::ExceptionOr<GC::Ref<IIRFilterNode>> IIRFilterNode::create_for_constructor(GC::Ref<BaseAudioContext> context, IIRFilterOptions const& options)
-{
- return create(context, options);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-iirfilternode-getfrequencyresponse
-WebIDL::ExceptionOr<void> IIRFilterNode::get_frequency_response(GC::Ref<JS::Float32Array> frequency_hz, GC::Ref<JS::Float32Array> mag_response, GC::Ref<JS::Float32Array> phase_response)
-{
- // Given the current filter parameter settings, synchronously calculates the frequency response for the specified
- // frequencies. The three parameters MUST be Float32Arrays of the same length, or an InvalidAccessError MUST be
- // thrown.
- auto length = float32_array_length(*frequency_hz);
- if (float32_array_length(*mag_response) != length || float32_array_length(*phase_response) != length)
- return WebIDL::InvalidAccessError::create(context()->relevant_settings_object().realm(), "Arrays must have the same length"_utf16);
-
- auto frequencies = copy_float32_array(*frequency_hz);
- Vector<float> magnitudes;
- magnitudes.resize(length);
- Vector<float> phases;
- phases.resize(length);
-
- auto nyquist_frequency = context()->nyquist_frequency();
-
- // https://webaudio.github.io/web-audio-api/#IIRFilterNode-filter-definition
- // NB: H(z) = (sum_{m=0}^{M} b_m z^{-m}) / (sum_{n=0}^{N} a_n z^{-n}), evaluated at z = e^{j omega}. A polynomial in
- // z^-1 is evaluated with Horner's method, from the coefficient of its highest power down.
- struct ComplexNumber {
- double real { 0 };
- double imaginary { 0 };
- };
- auto evaluate = [](ReadonlySpan<double> coefficients, ComplexNumber z_inverse) {
- ComplexNumber result;
- for (size_t index = coefficients.size(); index-- > 0;) {
- result = {
- result.real * z_inverse.real - result.imaginary * z_inverse.imaginary + coefficients[index],
- result.real * z_inverse.imaginary + result.imaginary * z_inverse.real,
- };
- }
- return result;
- };
-
- for (size_t index = 0; index < length; ++index) {
- double frequency = frequencies[index];
-
- // If a value in the frequencyHz parameter is not within [0, sampleRate/2], where sampleRate is the value of
- // the sampleRate property of the AudioContext, the corresponding value at the same index of the magResponse
- // and phaseResponse arrays MUST be NaN.
- if (isnan(frequency) || frequency < 0 || frequency > nyquist_frequency) {
- magnitudes[index] = NAN;
- phases[index] = NAN;
- continue;
- }
-
- double omega = AK::Pi<double> * frequency / nyquist_frequency;
- ComplexNumber z_inverse { AK::cos(omega), -AK::sin(omega) };
- auto numerator = evaluate(m_feedforward, z_inverse);
- auto denominator = evaluate(m_feedback, z_inverse);
- auto denominator_magnitude_squared = denominator.real * denominator.real + denominator.imaginary * denominator.imaginary;
- ComplexNumber response {
- (numerator.real * denominator.real + numerator.imaginary * denominator.imaginary) / denominator_magnitude_squared,
- (numerator.imaginary * denominator.real - numerator.real * denominator.imaginary) / denominator_magnitude_squared,
- };
- magnitudes[index] = static_cast<float>(AK::hypot(response.real, response.imaginary));
- phases[index] = static_cast<float>(AK::atan2(response.imaginary, response.real));
- }
-
- overwrite_float32_array(*mag_response, magnitudes);
- overwrite_float32_array(*phase_response, phases);
- return {};
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/IIRFilterNode.h b/Libraries/LibWeb/WebAudio/IIRFilterNode.h
deleted file mode 100644
index 8e5e045b11d..00000000000
--- a/Libraries/LibWeb/WebAudio/IIRFilterNode.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Vector.h>
-#include <LibWeb/Bindings/IIRFilterNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio {
-
-using IIRFilterOptions = Bindings::IIRFilterOptions;
-
-// https://webaudio.github.io/web-audio-api/#IIRFilterNode
-class IIRFilterNode final : public AudioNode {
- WEB_WRAPPABLE(IIRFilterNode, AudioNode);
- GC_DECLARE_ALLOCATOR(IIRFilterNode);
-
-public:
- virtual ~IIRFilterNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<IIRFilterNode>> create(GC::Ref<BaseAudioContext>, IIRFilterOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<IIRFilterNode>> create_for_constructor(GC::Ref<BaseAudioContext>, IIRFilterOptions const&);
-
- WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- WebIDL::ExceptionOr<void> get_frequency_response(GC::Ref<JS::Float32Array> frequency_hz, GC::Ref<JS::Float32Array> mag_response, GC::Ref<JS::Float32Array> phase_response);
-
-private:
- IIRFilterNode(GC::Ref<BaseAudioContext>, Vector<double> feedforward, Vector<double> feedback);
-
- // The coefficients, divided by the first feedback coefficient.
- Vector<double> m_feedforward;
- Vector<double> m_feedback;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/IIRFilterNode.idl b/Libraries/LibWeb/WebAudio/IIRFilterNode.idl
index 22fe6f6f249..b01a2cdf976 100644
--- a/Libraries/LibWeb/WebAudio/IIRFilterNode.idl
+++ b/Libraries/LibWeb/WebAudio/IIRFilterNode.idl
@@ -5,7 +5,7 @@ dictionary IIRFilterOptions : AudioNodeOptions {
};
// https://webaudio.github.io/web-audio-api/#IIRFilterNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface IIRFilterNode : AudioNode {
constructor (BaseAudioContext context, IIRFilterOptions options);
undefined getFrequencyResponse (Float32Array frequencyHz, Float32Array magResponse, Float32Array phaseResponse);
diff --git a/Libraries/LibWeb/WebAudio/MediaElementAudioSourceNode.cpp b/Libraries/LibWeb/WebAudio/MediaElementAudioSourceNode.cpp
index 3512e13e9de..4392e4083e3 100644
--- a/Libraries/LibWeb/WebAudio/MediaElementAudioSourceNode.cpp
+++ b/Libraries/LibWeb/WebAudio/MediaElementAudioSourceNode.cpp
@@ -1,46 +1,19 @@
/*
* Copyright (c) 2025, Tim Ledbetter <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
-#include <LibWeb/Bindings/MediaElementAudioSourceNode.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/HTML/HTMLMediaElement.h>
-#include <LibWeb/WebAudio/AudioContext.h>
-#include <LibWeb/WebAudio/MediaElementAudioSourceNode.h>
-
namespace Web::WebAudio {
-GC_DEFINE_ALLOCATOR(MediaElementAudioSourceNode);
-
-MediaElementAudioSourceNode::MediaElementAudioSourceNode(GC::Ref<AudioContext> context, GC::Ref<HTML::HTMLMediaElement> media_element)
- : AudioNode(context)
- , m_media_element(media_element)
-{
-}
-
-MediaElementAudioSourceNode::~MediaElementAudioSourceNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<MediaElementAudioSourceNode>> MediaElementAudioSourceNode::create(GC::Ref<AudioContext> context, GC::Ref<HTML::HTMLMediaElement> media_element)
-{
- return GC::Heap::the().allocate<MediaElementAudioSourceNode>(context, media_element);
-}
-
-WebIDL::ExceptionOr<GC::Ref<MediaElementAudioSourceNode>> MediaElementAudioSourceNode::create_for_constructor(GC::Ref<AudioContext> context, GC::Ref<HTML::HTMLMediaElement> media_element)
-{
- return create(context, media_element);
-}
-
-WebIDL::ExceptionOr<GC::Ref<MediaElementAudioSourceNode>> MediaElementAudioSourceNode::create_for_constructor(GC::Ref<AudioContext> context, Bindings::MediaElementAudioSourceOptions const& options)
-{
- return create_for_constructor(context, *options.media_element);
-}
-
-void MediaElementAudioSourceNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_media_element);
-}
+extern "C" HTML::HTMLMediaElement* web_audio_media_element_from_wrapper(JS::Object*);
+extern "C" JS::Object* web_audio_media_element_wrap(JS::Realm*, HTML::HTMLMediaElement*);
+HTML::HTMLMediaElement* web_audio_media_element_from_wrapper(JS::Object* object) { return Bindings::impl_from<HTML::HTMLMediaElement>(object); }
+JS::Object* web_audio_media_element_wrap(JS::Realm* realm, HTML::HTMLMediaElement* object) { return Bindings::wrap(Bindings::host_defined_wrapper_world(*realm), *realm, GC::Ref { *object }).ptr(); }
}
diff --git a/Libraries/LibWeb/WebAudio/MediaElementAudioSourceNode.h b/Libraries/LibWeb/WebAudio/MediaElementAudioSourceNode.h
deleted file mode 100644
index 557151b12eb..00000000000
--- a/Libraries/LibWeb/WebAudio/MediaElementAudioSourceNode.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2025, Tim Ledbetter <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibGC/Forward.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::Bindings {
-
-struct MediaElementAudioSourceOptions;
-
-}
-
-namespace Web::WebAudio {
-
-// https://webaudio.github.io/web-audio-api/#MediaElementAudioSourceNode
-class MediaElementAudioSourceNode final : public AudioNode {
- WEB_WRAPPABLE(MediaElementAudioSourceNode, AudioNode);
- GC_DECLARE_ALLOCATOR(MediaElementAudioSourceNode);
-
-public:
- static constexpr size_t media_element_offset() { return offsetof(MediaElementAudioSourceNode, m_media_element); }
- virtual ~MediaElementAudioSourceNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<MediaElementAudioSourceNode>> create(GC::Ref<AudioContext>, GC::Ref<HTML::HTMLMediaElement>);
- static WebIDL::ExceptionOr<GC::Ref<MediaElementAudioSourceNode>> create_for_constructor(GC::Ref<AudioContext>, GC::Ref<HTML::HTMLMediaElement>);
- static WebIDL::ExceptionOr<GC::Ref<MediaElementAudioSourceNode>> create_for_constructor(GC::Ref<AudioContext>, Bindings::MediaElementAudioSourceOptions const&);
-
- virtual WebIDL::UnsignedLong number_of_inputs() override { return 0; }
- virtual WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- GC::Ref<HTML::HTMLMediaElement> media_element() const { return m_media_element; }
-
-private:
- MediaElementAudioSourceNode(GC::Ref<AudioContext>, GC::Ref<HTML::HTMLMediaElement>);
- virtual void visit_edges(Cell::Visitor&) override;
-
- GC::Ref<HTML::HTMLMediaElement> m_media_element;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/MediaElementAudioSourceNode.idl b/Libraries/LibWeb/WebAudio/MediaElementAudioSourceNode.idl
index 68a4c9d64d9..efc5932877f 100644
--- a/Libraries/LibWeb/WebAudio/MediaElementAudioSourceNode.idl
+++ b/Libraries/LibWeb/WebAudio/MediaElementAudioSourceNode.idl
@@ -4,8 +4,8 @@ dictionary MediaElementAudioSourceOptions {
};
// https://webaudio.github.io/web-audio-api/#MediaElementAudioSourceNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface MediaElementAudioSourceNode : AudioNode {
constructor (AudioContext context, MediaElementAudioSourceOptions options);
- [DirectGetter, SameObject] readonly attribute HTMLMediaElement mediaElement;
+ [SameObject] readonly attribute HTMLMediaElement mediaElement;
};
diff --git a/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.cpp b/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.cpp
index 85647539e59..a0bde0e8c03 100644
--- a/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.cpp
+++ b/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.cpp
@@ -4,74 +4,53 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibAudio/SpscAudioFrameRing.h>
#include <LibCore/EventLoop.h>
-#include <LibGC/Heap.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/MediaCapture/MediaStream.h>
#include <LibWeb/MediaCapture/MediaStreamTrack.h>
-#include <LibWeb/WebAudio/AudioContext.h>
-#include <LibWeb/WebAudio/MediaStreamAudioDestinationNode.h>
-
+#include <LibWeb/WebAudio/Rendering/MediaStreamDestinationRenderNode.h>
+#include <LibWeb/WebAudio/RustFFI.h>
namespace Web::WebAudio {
-GC_DEFINE_ALLOCATOR(MediaStreamAudioDestinationNode);
-
-MediaStreamAudioDestinationNode::MediaStreamAudioDestinationNode(GC::Ref<AudioContext> context, GC::Ref<MediaCapture::MediaStream> stream, GC::Ref<MediaCapture::MediaStreamTrack> track)
- : AudioNode(context)
- , m_stream(stream)
- , m_track(track)
-{
-}
-
-MediaStreamAudioDestinationNode::~MediaStreamAudioDestinationNode() = default;
-
-// https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiodestinationnode-mediastreamaudiodestinationnode
-WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioDestinationNode>> MediaStreamAudioDestinationNode::create(GC::Ref<AudioContext> context, AudioNodeOptions const& options)
+extern "C" void web_audio_media_destination_create_stream(MediaCapture::MediaStream**, MediaCapture::MediaStreamTrack**);
+extern "C" RustFFI::FfiSharedCppObject web_audio_media_destination_create_state(MediaCapture::MediaStreamTrack*, u64, u32, u32, void**);
+extern "C" void web_audio_media_destination_clear_drain(Rendering::MediaStreamDestinationSharedState*);
+extern "C" JS::Object* web_audio_media_destination_wrap_stream(JS::Realm*, MediaCapture::MediaStream*);
+void web_audio_media_destination_create_stream(MediaCapture::MediaStream** out_stream, MediaCapture::MediaStreamTrack** out_track)
{
- // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiodestinationnode-stream
- // A MediaStream containing a single MediaStreamTrack with the same number of channels as
- // the node itself, and whose kind attribute has the value "audio".
- // NB: The track is deviceless — it carries no deviceId, so registering audio sinks on it
- // never opens a capture stream; it is fed exclusively by this node's render node.
auto track = MediaCapture::MediaStreamTrack::create(Bindings::MediaStreamTrackKind::Audio, "MediaStreamAudioDestinationNode"_utf16);
auto stream = MediaCapture::MediaStream::create();
stream->add_track(track);
-
- // 1. Initialize the AudioNode this, with context and options as arguments.
- auto node = GC::Heap::the().allocate<MediaStreamAudioDestinationNode>(context, stream, track);
-
- // https://webaudio.github.io/web-audio-api/#MediaStreamAudioDestinationNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count = 2;
- default_options.channel_count_mode = ChannelCountMode::Explicit;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- TRY(node->initialize_audio_node_options(options, default_options));
-
+ *out_stream = stream.ptr();
+ *out_track = track.ptr();
+}
+RustFFI::FfiSharedCppObject web_audio_media_destination_create_state(MediaCapture::MediaStreamTrack* track, u64 node_id, u32 channel_count, u32 sample_rate, void** render_node)
+{
// Advertise the delivery format in the track's settings so downstream consumers (e.g. a
// MediaStreamAudioSourceNode built on this track) can size their pipelines for it.
// FIXME: Changing the node's channelCount after construction should change the track's
// channel count as well; the ring's layout is currently fixed at creation.
- auto sample_rate = static_cast<u32>(context->sample_rate());
MediaCapture::MediaTrackSettings settings;
settings.sample_rate = sample_rate;
- settings.channel_count = node->channel_count();
+ settings.channel_count = channel_count;
track->set_settings(move(settings));
// The renderer produces audio in bursts of up to ~100 ms (its device buffer target), and
// the control thread drains on a deferred-invoke cadence after each burst; 8192 frames
// (~170 ms at 48 kHz) absorb a full burst plus scheduling jitter.
static constexpr size_t ring_capacity_in_frames = 8192;
- auto ring = adopt_ref(*new Audio::SpscAudioFrameRing(ring_capacity_in_frames, node->channel_count()));
- node->m_shared_state = adopt_ref(*new Rendering::MediaStreamDestinationSharedState(move(ring)));
+ auto ring = adopt_ref(*new Audio::SpscAudioFrameRing(ring_capacity_in_frames, channel_count));
+ auto shared_state = adopt_ref(*new Rendering::MediaStreamDestinationSharedState(move(ring)));
// The drain callback runs (and is later cleared) exclusively on the control thread; it is
// the only place a GC root crosses into the shared state, so the render thread never
// touches GC-managed memory.
- node->m_shared_state->drain = [track = GC::make_root(track), ring = node->m_shared_state->ring, sample_rate, chunk = Vector<float>()]() mutable {
+ shared_state->drain = [track = GC::make_root(*track), ring = shared_state->ring, sample_rate, chunk = Vector<float>()]() mutable {
// Forward the rendered audio to the track in render-quantum-sized chunks — the
// granularity real-time consumers pace themselves against.
auto channel_count = ring->channel_count();
- chunk.resize(BaseAudioContext::render_quantum_size() * channel_count);
+ chunk.resize(128 * channel_count);
while (true) {
auto frame_count = ring->try_pop(chunk);
if (frame_count == 0)
@@ -80,33 +59,11 @@ WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioDestinationNode>> MediaStreamAudioDe
}
};
- node->queue_render_node_creation(make<Rendering::MediaStreamDestinationRenderNode>(
- node->node_id(), BaseAudioContext::render_quantum_size(), node->channel_count(),
- *node->m_shared_state, Core::EventLoop::current()));
-
- return node;
-}
-
-WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioDestinationNode>> MediaStreamAudioDestinationNode::create_for_constructor(GC::Ref<AudioContext> context, AudioNodeOptions const& options)
-{
- return create(context, options);
-}
-
-void MediaStreamAudioDestinationNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_stream);
- visitor.visit(m_track);
-}
-
-void MediaStreamAudioDestinationNode::finalize()
-{
- // Drop the drain callback — and with it the GC root it holds on the track — on the
- // control thread. Any drain the render node still has queued becomes a no-op.
- if (m_shared_state)
- m_shared_state->drain = nullptr;
-
- Base::finalize();
+ Rendering::MediaStreamDestinationRenderNode node(NodeID(node_id), 128, channel_count, shared_state, Core::EventLoop::current());
+ *render_node = node.release_rust_node();
+ return { &shared_state.leak_ref(), [](void* state) { static_cast<Rendering::MediaStreamDestinationSharedState*>(state)->ref(); }, [](void* state) { static_cast<Rendering::MediaStreamDestinationSharedState*>(state)->unref(); } };
}
+void web_audio_media_destination_clear_drain(Rendering::MediaStreamDestinationSharedState* state) { state->drain = nullptr; }
+JS::Object* web_audio_media_destination_wrap_stream(JS::Realm* realm, MediaCapture::MediaStream* stream) { return Bindings::wrap(Bindings::host_defined_wrapper_world(*realm), *realm, GC::Ref { *stream }).ptr(); }
}
diff --git a/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.h b/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.h
deleted file mode 100644
index 818b6b1dec4..00000000000
--- a/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/RefPtr.h>
-#include <LibWeb/Bindings/MediaStreamAudioDestinationNode.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/Rendering/MediaStreamDestinationRenderNode.h>
-
-namespace Web::WebAudio {
-
-// https://webaudio.github.io/web-audio-api/#MediaStreamAudioDestinationNode
-class MediaStreamAudioDestinationNode final : public AudioNode {
- WEB_WRAPPABLE(MediaStreamAudioDestinationNode, AudioNode);
- GC_DECLARE_ALLOCATOR(MediaStreamAudioDestinationNode);
-
-public:
- virtual ~MediaStreamAudioDestinationNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioDestinationNode>> create(GC::Ref<AudioContext>, AudioNodeOptions const& = {});
- static WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioDestinationNode>> create_for_constructor(GC::Ref<AudioContext>, AudioNodeOptions const& = {});
-
- virtual WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- virtual WebIDL::UnsignedLong number_of_outputs() override { return 0; }
-
- // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiodestinationnode-stream
- GC::Ref<MediaCapture::MediaStream> stream() const { return m_stream; }
-
-private:
- MediaStreamAudioDestinationNode(GC::Ref<AudioContext>, GC::Ref<MediaCapture::MediaStream>, GC::Ref<MediaCapture::MediaStreamTrack>);
-
- virtual void visit_edges(Cell::Visitor&) override;
- virtual void finalize() override;
-
- // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiodestinationnode-stream
- GC::Ref<MediaCapture::MediaStream> m_stream;
-
- GC::Ref<MediaCapture::MediaStreamTrack> m_track;
-
- RefPtr<Rendering::MediaStreamDestinationSharedState> m_shared_state;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.idl b/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.idl
index c3f048302b3..a332419dd3e 100644
--- a/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.idl
+++ b/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.idl
@@ -1,5 +1,5 @@
// https://webaudio.github.io/web-audio-api/#MediaStreamAudioDestinationNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface MediaStreamAudioDestinationNode : AudioNode {
constructor (AudioContext context, optional AudioNodeOptions options = {});
readonly attribute MediaStream stream;
diff --git a/Libraries/LibWeb/WebAudio/MediaStreamAudioSourceNode.cpp b/Libraries/LibWeb/WebAudio/MediaStreamAudioSourceNode.cpp
index 5a8d3b7b426..ff2f08135c1 100644
--- a/Libraries/LibWeb/WebAudio/MediaStreamAudioSourceNode.cpp
+++ b/Libraries/LibWeb/WebAudio/MediaStreamAudioSourceNode.cpp
@@ -4,23 +4,21 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/QuickSort.h>
#include <LibAudio/SpscAudioFrameRing.h>
-#include <LibGC/Heap.h>
+#include <LibJS/Runtime/Realm.h>
#include <LibMedia/FFmpeg/FFmpegAudioConverter.h>
#include <LibMediaCodecs/AudioBlock.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/MediaCapture/MediaStream.h>
#include <LibWeb/MediaCapture/MediaStreamTrack.h>
-#include <LibWeb/WebAudio/AudioContext.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/MediaStreamAudioSourceNode.h>
-#include <LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.h>
-#include <LibWeb/WebIDL/DOMException.h>
-
+#include <LibWeb/WebAudio/RustFFI.h>
namespace Web::WebAudio {
-GC_DEFINE_ALLOCATOR(MediaStreamAudioSourceNode);
-
+extern "C" MediaCapture::MediaStream* web_audio_media_source_stream_from_wrapper(JS::Object*);
+extern "C" JS::Object* web_audio_media_source_stream_wrap(JS::Realm*, MediaCapture::MediaStream*);
+MediaCapture::MediaStream* web_audio_media_source_stream_from_wrapper(JS::Object* object) { return Bindings::impl_from<MediaCapture::MediaStream>(object); }
+JS::Object* web_audio_media_source_stream_wrap(JS::Realm* realm, MediaCapture::MediaStream* object) { return Bindings::wrap(Bindings::host_defined_wrapper_world(*realm), *realm, GC::Ref { *object }).ptr(); }
// Drop whole incoming blocks that cannot fit so the producer never mutates the consumer index.
static void push_frames_if_enough_room(Audio::SpscAudioFrameRing& ring, ReadonlySpan<float> interleaved_samples)
{
@@ -32,78 +30,48 @@ static void push_frames_if_enough_room(Audio::SpscAudioFrameRing& ring, Readonly
VERIFY(frames_pushed == frame_count);
}
-MediaStreamAudioSourceNode::MediaStreamAudioSourceNode(GC::Ref<AudioContext> context, MediaStreamAudioSourceOptions const& options)
- : AudioNode(context)
- , m_media_stream(*options.media_stream)
+extern "C" void web_audio_media_source_audio_tracks(MediaCapture::MediaStream*, void*, void (*)(void*, void*));
+extern "C" bool web_audio_media_source_track_id_less(MediaCapture::MediaStreamTrack*, MediaCapture::MediaStreamTrack*);
+extern "C" u32 web_audio_media_source_track_channels(MediaCapture::MediaStreamTrack*);
+extern "C" bool web_audio_media_source_has_live_track(MediaCapture::MediaStreamTrack*);
+extern "C" RustFFI::FfiSharedCppObject web_audio_media_source_ring(u32);
+extern "C" void web_audio_media_source_ring_callbacks(RustFFI::AudioFrameRingCallbacks*);
+extern "C" RustFFI::FfiSharedCppObject web_audio_media_source_attach(MediaCapture::MediaStreamTrack*, Audio::SpscAudioFrameRing*, float);
+extern "C" void web_audio_media_source_detach(MediaCapture::MediaStreamTrack*, MediaCapture::AudioFrameSink*);
+void web_audio_media_source_audio_tracks(MediaCapture::MediaStream* stream, void* context, void (*callback)(void*, void*))
{
+ for (auto track : stream->get_audio_tracks())
+ callback(context, track.ptr());
}
-
-MediaStreamAudioSourceNode::~MediaStreamAudioSourceNode() = default;
-
-// https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiosourcenode-mediastreamaudiosourcenode
-WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioSourceNode>> MediaStreamAudioSourceNode::create(GC::Ref<AudioContext> context, MediaStreamAudioSourceOptions const& options)
+bool web_audio_media_source_track_id_less(MediaCapture::MediaStreamTrack* a, MediaCapture::MediaStreamTrack* b) { return a->id() < b->id(); }
+u32 web_audio_media_source_track_channels(MediaCapture::MediaStreamTrack* track) { return track->channel_count(); }
+bool web_audio_media_source_has_live_track(MediaCapture::MediaStreamTrack* track) { return track->track_ready_state() == MediaCapture::MediaStreamTrackState::Live; }
+RustFFI::FfiSharedCppObject web_audio_media_source_ring(u32 channels)
{
- // 1. If the mediaStream member of options does not reference a MediaStream that has at least one MediaStreamTrack
- // whose kind attribute has the value "audio", throw an InvalidStateError and abort these steps. Else, let this
- // stream be inputStream.
- auto audio_tracks = options.media_stream->get_audio_tracks();
- if (audio_tracks.is_empty())
- return WebIDL::InvalidStateError::create("MediaStream has no audio tracks"_utf16);
-
- // 2. Let tracks be the list of all MediaStreamTracks of inputStream that have a kind of "audio".
- // 3. Sort the elements in tracks based on their id attribute using an ordering on sequences of code unit values.
- quick_sort(audio_tracks, [](auto const& a, auto const& b) { return a->id() < b->id(); });
-
- // 4. Initialize the AudioNode this, with context and options as arguments.
- auto node = GC::Heap::the().allocate<MediaStreamAudioSourceNode>(context, options);
-
- // https://webaudio.github.io/web-audio-api/#MediaStreamAudioSourceNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count = 2;
- default_options.channel_count_mode = ChannelCountMode::Max;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- TRY(node->initialize_audio_node_options({}, default_options));
-
- // 5. Set an internal slot [[input track]] on this MediaStreamAudioSourceNode to be the first element of tracks.
- // This is the track used as the input audio for this MediaStreamAudioSourceNode.
- node->m_input_track = audio_tracks.first();
-
- node->queue_render_node_creation(make<Rendering::MediaStreamSourceRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size()));
- node->attach_input_track();
- context->add_media_stream_source(*node);
-
- return node;
+ return { new Audio::SpscAudioFrameRing(3 * 960, channels), [](void* ring) { static_cast<Audio::SpscAudioFrameRing*>(ring)->ref(); }, [](void* ring) { static_cast<Audio::SpscAudioFrameRing*>(ring)->unref(); } };
}
-
-WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioSourceNode>> MediaStreamAudioSourceNode::create_for_constructor(GC::Ref<AudioContext> context, MediaStreamAudioSourceOptions const& options)
+void web_audio_media_source_ring_callbacks(RustFFI::AudioFrameRingCallbacks* callbacks)
{
- return create(context, options);
+ *callbacks = {
+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->channel_count(); },
+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->frames_available(); },
+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->frames_free(); },
+ [](void* ring, Span<float> samples) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->try_pop(samples); },
+ [](void* ring, ReadonlySpan<float> samples) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->try_push(samples); },
+ };
}
-
-void MediaStreamAudioSourceNode::attach_input_track()
+RustFFI::FfiSharedCppObject web_audio_media_source_attach(MediaCapture::MediaStreamTrack* track, Audio::SpscAudioFrameRing* ring, float sample_rate)
{
- VERIFY(m_input_track);
-
- // The ring must absorb at least one PulseAudio fragment (960 frames, 20 ms at 48 kHz) per
- // push; three fragments of headroom (rounded up to 4096 frames by the ring) keep the
- // producer ahead of render-thread scheduling jitter without accumulating latency, since
- // the render node drains a quantum at a time and holds the steady-state fill near one
- // fragment.
- static constexpr size_t ring_capacity_in_frames = 3 * 960;
- auto channel_count = m_input_track->channel_count() == 1 ? 1u : 2u;
- m_ring = adopt_ref(*new Audio::SpscAudioFrameRing(ring_capacity_in_frames, channel_count));
-
- context()->queue_control_message(NodeMessage { SetMediaStreamSourceRing { node_id(), m_ring, channel_count } });
-
+ auto channel_count = ring->channel_count();
auto converter = Media::FFmpeg::FFmpegAudioConverter::try_create();
if (converter.is_error())
- return;
+ return { nullptr, [](void*) { }, [](void*) { } };
auto channel_map = channel_count == 1 ? Audio::ChannelMap::mono() : Audio::ChannelMap::stereo();
- if (converter.value()->set_output_sample_specification(Audio::SampleSpecification(static_cast<u32>(context()->sample_rate()), channel_map)).is_error())
- return;
+ if (converter.value()->set_output_sample_specification(Audio::SampleSpecification(static_cast<u32>(sample_rate), channel_map)).is_error())
+ return { nullptr, [](void*) { }, [](void*) { } };
- m_sink = adopt_ref(*new MediaCapture::AudioFrameSink);
- m_sink->on_frames = [ring = m_ring, converter = converter.release_value(), frames_received = u64 { 0 }, scratch = Vector<float>()](float const* samples, size_t frame_count, u8 channels, u32 sample_rate) mutable {
+ auto sink = adopt_ref(*new MediaCapture::AudioFrameSink);
+ sink->on_frames = [ring = NonnullRefPtr { *ring }, converter = converter.release_value(), frames_received = u64 { 0 }, scratch = Vector<float>()](float const* samples, size_t frame_count, u8 channels, u32 sample_rate) mutable {
// Own the conversion state and reference only the ring, never the GC-managed source node.
if (frame_count == 0 || channels == 0 || sample_rate == 0)
return;
@@ -132,29 +100,9 @@ void MediaStreamAudioSourceNode::attach_input_track()
push_frames_if_enough_room(*ring, scratch);
}
};
- m_input_track->add_audio_sink(*m_sink);
-}
-
-bool MediaStreamAudioSourceNode::has_live_input_track() const
-{
- return m_input_track && m_input_track->track_ready_state() == MediaCapture::MediaStreamTrackState::Live;
-}
-
-void MediaStreamAudioSourceNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_media_stream);
- visitor.visit(m_input_track);
-}
-
-void MediaStreamAudioSourceNode::finalize()
-{
- Base::finalize();
-
- // NB: Finalizers run before any dead cell is destroyed, so detaching from the input track
- // is safe even when the track is collected in the same garbage collection cycle.
- if (m_input_track && m_sink)
- m_input_track->remove_audio_sink(*m_sink);
+ track->add_audio_sink(*sink);
+ return { &sink.leak_ref(), [](void* sink) { static_cast<MediaCapture::AudioFrameSink*>(sink)->ref(); }, [](void* sink) { static_cast<MediaCapture::AudioFrameSink*>(sink)->unref(); } };
}
+void web_audio_media_source_detach(MediaCapture::MediaStreamTrack* track, MediaCapture::AudioFrameSink* sink) { track->remove_audio_sink(*sink); }
}
diff --git a/Libraries/LibWeb/WebAudio/MediaStreamAudioSourceNode.h b/Libraries/LibWeb/WebAudio/MediaStreamAudioSourceNode.h
deleted file mode 100644
index c5a9ec09a46..00000000000
--- a/Libraries/LibWeb/WebAudio/MediaStreamAudioSourceNode.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/RefPtr.h>
-#include <LibWeb/Bindings/MediaStreamAudioSourceNode.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Audio {
-
-class SpscAudioFrameRing;
-
-}
-
-namespace Web::MediaCapture {
-
-struct AudioFrameSink;
-
-}
-
-namespace Web::WebAudio {
-
-using MediaStreamAudioSourceOptions = Bindings::MediaStreamAudioSourceOptions;
-
-// https://webaudio.github.io/web-audio-api/#MediaStreamAudioSourceNode
-class MediaStreamAudioSourceNode final : public AudioNode {
- WEB_WRAPPABLE(MediaStreamAudioSourceNode, AudioNode);
- GC_DECLARE_ALLOCATOR(MediaStreamAudioSourceNode);
-
-public:
- virtual ~MediaStreamAudioSourceNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioSourceNode>> create(GC::Ref<AudioContext>, MediaStreamAudioSourceOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<MediaStreamAudioSourceNode>> create_for_constructor(GC::Ref<AudioContext>, MediaStreamAudioSourceOptions const&);
-
- virtual WebIDL::UnsignedLong number_of_inputs() override { return 0; }
- virtual WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiosourcenode-mediastream
- GC::Ref<MediaCapture::MediaStream> media_stream() const { return m_media_stream; }
-
- bool has_live_input_track() const;
-
-private:
- MediaStreamAudioSourceNode(GC::Ref<AudioContext>, MediaStreamAudioSourceOptions const&);
-
- virtual void visit_edges(Cell::Visitor&) override;
- virtual void finalize() override;
-
- void attach_input_track();
-
- // https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiosourcenode-mediastream
- GC::Ref<MediaCapture::MediaStream> m_media_stream;
-
- // [[input track]]: the first audio track of the input stream, ordered by track id.
- GC::Ptr<MediaCapture::MediaStreamTrack> m_input_track;
-
- // Carries the track's audio from the producing thread to the render thread; the sink is
- // registered on the input track and only ever references the ring, never this GC node.
- RefPtr<Audio::SpscAudioFrameRing> m_ring;
- RefPtr<MediaCapture::AudioFrameSink> m_sink;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/MediaStreamAudioSourceNode.idl b/Libraries/LibWeb/WebAudio/MediaStreamAudioSourceNode.idl
index 3950588d05d..9c6798748e3 100644
--- a/Libraries/LibWeb/WebAudio/MediaStreamAudioSourceNode.idl
+++ b/Libraries/LibWeb/WebAudio/MediaStreamAudioSourceNode.idl
@@ -4,7 +4,7 @@ dictionary MediaStreamAudioSourceOptions {
};
// https://webaudio.github.io/web-audio-api/#MediaStreamAudioSourceNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface MediaStreamAudioSourceNode : AudioNode {
constructor (AudioContext context, MediaStreamAudioSourceOptions options);
[SameObject] readonly attribute MediaStream mediaStream;
diff --git a/Libraries/LibWeb/WebAudio/OfflineAudioCompletionEvent.cpp b/Libraries/LibWeb/WebAudio/OfflineAudioCompletionEvent.cpp
deleted file mode 100644
index 3b597238cc7..00000000000
--- a/Libraries/LibWeb/WebAudio/OfflineAudioCompletionEvent.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Bindings/RustEventTarget.h>
-#include <LibWeb/WebAudio/OfflineAudioCompletionEvent.h>
-
-namespace Web::WebAudio {
-
-extern "C" DOM::Event* web_rust_offline_audio_completion_event_create(JSVM*, void* event, void* buffer);
-
-GC::Ref<DOM::Event> OfflineAudioCompletionEvent::create(Utf16FlyString const& event_name, OfflineAudioCompletionEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)
-{
- auto event = Bindings::RustEvent::create(event_name, event_init, time_stamp);
- return *web_rust_offline_audio_completion_event_create(JS::HostABI::vm_to_abi(JS::VM::the()), event.ptr(), event_init.rendered_buffer.ptr());
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/OfflineAudioCompletionEvent.h b/Libraries/LibWeb/WebAudio/OfflineAudioCompletionEvent.h
deleted file mode 100644
index 5afeebf78cc..00000000000
--- a/Libraries/LibWeb/WebAudio/OfflineAudioCompletionEvent.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2025, Luke Wilde <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/OfflineAudioCompletionEvent.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/DOM/Event.h>
-#include <LibWeb/WebAudio/AudioBuffer.h>
-
-namespace Web::WebAudio {
-
-struct OfflineAudioCompletionEventInit : DOM::EventInit {
- GC::Ref<AudioBuffer> rendered_buffer;
-};
-
-class OfflineAudioCompletionEvent final : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(OfflineAudioCompletionEvent, offline_audio_completion_event)
-
-public:
- static GC::Ref<DOM::Event> create(Utf16FlyString const& event_name, OfflineAudioCompletionEventInit const&, HighResolutionTime::DOMHighResTimeStamp);
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/OfflineAudioContext.cpp b/Libraries/LibWeb/WebAudio/OfflineAudioContext.cpp
index 0c4a1b665de..0727f04a8dc 100644
--- a/Libraries/LibWeb/WebAudio/OfflineAudioContext.cpp
+++ b/Libraries/LibWeb/WebAudio/OfflineAudioContext.cpp
@@ -1,331 +1,54 @@
/*
* Copyright (c) 2024, Shannon Booth <[email protected]>
* Copyright (c) 2025, Ben Eidson <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/DOM/Event.h>
-#include <LibWeb/HTML/EventNames.h>
-#include <LibWeb/HTML/LocalNavigable.h>
-#include <LibWeb/HTML/Navigable.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
-#include <LibWeb/HTML/Window.h>
-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
-#include <LibWeb/HighResolutionTime/TimeOrigin.h>
-#include <LibWeb/WebAudio/AudioBuffer.h>
-#include <LibWeb/WebAudio/AudioDestinationNode.h>
-#include <LibWeb/WebAudio/OfflineAudioCompletionEvent.h>
-#include <LibWeb/WebAudio/OfflineAudioContext.h>
-
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h>
+#include <LibWeb/WebAudio/RustFFI.h>
+#include <LibWeb/WebIDL/Promise.h>
namespace Web::WebAudio {
-GC_DEFINE_ALLOCATOR(OfflineAudioContext);
-
-WebIDL::ExceptionOr<GC::Ref<OfflineAudioContext>> OfflineAudioContext::create_for_constructor(JS::Object& relevant_global_object, OfflineAudioContextOptions const& context_options)
-{
- return create_for_constructor(HTML::relevant_window(relevant_global_object), context_options);
-}
-
-WebIDL::ExceptionOr<GC::Ref<OfflineAudioContext>> OfflineAudioContext::create_for_constructor(JS::Object& relevant_global_object, WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate)
-{
- return create_for_constructor(HTML::relevant_window(relevant_global_object), number_of_channels, length, sample_rate);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-offlineaudiocontext
-WebIDL::ExceptionOr<GC::Ref<OfflineAudioContext>> OfflineAudioContext::create_for_constructor(GC::Ref<DOM::EventTarget> relevant_global_object, OfflineAudioContextOptions const& context_options)
-{
- // AD-HOC: This spec text is currently only mentioned in the constructor overload that takes separate arguments,
- // but these parameters should be validated for both constructors.
- // A NotSupportedError exception MUST be thrown if any of the arguments is negative, zero, or outside its nominal range.
- TRY(verify_audio_options_inside_nominal_range(context_options.number_of_channels, context_options.length, context_options.sample_rate));
-
- // Let c be a new OfflineAudioContext object. Initialize c as follows:
- auto c = GC::Heap::the().allocate<OfflineAudioContext>(relevant_global_object, context_options.number_of_channels, context_options.length, context_options.sample_rate);
- c->set_listener(AudioListener::create(c));
-
- // 1. Set the [[control thread state]] for c to "suspended".
- c->set_control_state(AudioContextState::Suspended);
-
- // 2. Set the [[rendering thread state]] for c to "suspended".
- c->set_rendering_state(AudioContextState::Suspended);
-
- // FIXME: 3. Determine the [[render quantum size]] for this OfflineAudioContext, based on the value of the renderSizeHint:
-
- // 4. Construct an AudioDestinationNode with its channelCount set to contextOptions.numberOfChannels.
- c->m_destination = TRY(AudioDestinationNode::create(c, context_options.number_of_channels));
-
- // FIXME: 5. Let messageChannel be a new MessageChannel.
- // FIXME: 6. Let controlSidePort be the value of messageChannel’s port1 attribute.
- // FIXME: 7. Let renderingSidePort be the value of messageChannel’s port2 attribute.
- // FIXME: 8. Let serializedRenderingSidePort be the result of StructuredSerializeWithTransfer(renderingSidePort, « renderingSidePort »).
- // FIXME: 9. Set this audioWorklet's port to controlSidePort.
- // FIXME: 10. Queue a control message to set the MessagePort on the AudioContextGlobalScope, with serializedRenderingSidePort.
-
- return c;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-offlineaudiocontext-numberofchannels-length-samplerate
-WebIDL::ExceptionOr<GC::Ref<OfflineAudioContext>> OfflineAudioContext::create_for_constructor(
- GC::Ref<DOM::EventTarget> relevant_global_object,
- WebIDL::UnsignedLong number_of_channels,
- WebIDL::UnsignedLong length,
- float sample_rate)
-{
- OfflineAudioContextOptions options {};
- options.number_of_channels = number_of_channels;
- options.length = length;
- options.sample_rate = sample_rate;
- return create_for_constructor(relevant_global_object, options);
-}
-
-OfflineAudioContext::~OfflineAudioContext() = default;
-
-// https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-startrendering
-WebIDL::ExceptionOr<void> OfflineAudioContext::start_rendering(GC::Ref<WebIDL::Promise> promise)
-{
- // 1. If this’s relevant global object’s associated Document is not fully active then return a promise rejected with "InvalidStateError" DOMException.
- auto& window = relevant_window();
- auto const& associated_document = window.associated_document();
-
- if (!associated_document.is_fully_active())
- return WebIDL::InvalidStateError::create("Document is not fully active"_utf16);
-
- // AD-HOC: Not in spec explicitly, but this should account for detached iframes too. See /the-offlineaudiocontext-interface/startrendering-after-discard.html WPT.
- auto navigable = window.navigable();
- if (navigable && navigable->has_been_destroyed())
- return WebIDL::InvalidStateError::create("The iframe has been detached"_utf16);
-
- // 2. If the [[rendering started]] slot on the OfflineAudioContext is true, return a rejected promise with InvalidStateError, and abort these steps.
- if (m_rendering_started) {
- WebIDL::reject_promise(promise, WebIDL::InvalidStateError::create("Rendering is already started"_utf16));
- return {};
- }
-
- // 3. Set the [[rendering started]] slot of the OfflineAudioContext to true.
- m_rendering_started = true;
-
- // 5. Create a new AudioBuffer, with a number of channels, length and sample rate equal respectively to the
- // numberOfChannels, length and sampleRate values passed to this instance’s constructor in the contextOptions
- // parameter.
- auto buffer_result = create_buffer(m_number_of_channels, length(), sample_rate());
-
- // 6. If an exception was thrown during the preceding AudioBuffer constructor call, reject promise with this exception.
- if (buffer_result.is_exception()) {
- WebIDL::reject_promise_with_exception(promise, buffer_result.release_error());
- return {};
- }
-
- // Assign this buffer to an internal slot [[rendered buffer]] in the OfflineAudioContext.
- m_rendered_buffer = buffer_result.release_value();
-
- // 7. Otherwise, in the case that the buffer was successfully constructed, begin offline rendering.
- begin_offline_rendering(promise);
-
- // 8. Append promise to [[pending promises]].
- m_pending_promises.append(promise);
-
- return {};
-}
-
-void OfflineAudioContext::begin_offline_rendering(GC::Ref<WebIDL::Promise> promise)
-{
- // 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.
- m_renderer = Rendering::OfflineAudioRenderer::create(control_message_queue(), destination()->node_id(), m_number_of_channels, m_length, sample_rate(), render_quantum_size());
- m_renderer->set_on_complete([self = GC::make_root(this), promise = GC::make_root(promise)] {
- self->finish_rendering(*promise);
- });
- m_renderer->set_on_suspended([self = GC::make_root(this)](double suspend_time) {
- self->handle_suspended(suspend_time);
- });
- m_renderer->set_on_sources_ended([self = GC::make_root(this)](Vector<NodeID> const& ended_nodes) {
- self->handle_ended_sources(ended_nodes);
+extern "C" void web_rust_audio_context_sources_ended(JSVM*, void*, ReadonlySpan<u64>);
+extern "C" void web_rust_offline_audio_context_complete(JSVM*, void*, void*);
+extern "C" void web_rust_offline_audio_context_suspended(JSVM*, void*, double);
+extern "C" RustFFI::FfiSharedCppObject web_audio_offline_context_create(void const*, u64, u32, u32, float);
+extern "C" void web_audio_offline_context_set_callbacks(Rendering::OfflineAudioRenderer*, Bindings::RustInterfaceCell*, JS::PromiseCapability*);
+extern "C" bool web_audio_offline_context_request_suspend(Rendering::OfflineAudioRenderer*, u64);
+extern "C" void web_audio_offline_context_channel(Rendering::OfflineAudioRenderer*, size_t, ReadonlySpan<float>*);
+RustFFI::FfiSharedCppObject web_audio_offline_context_create(void const* queue, u64 destination, u32 channels, u32 length, float sample_rate)
+{
+ auto renderer = Rendering::OfflineAudioRenderer::create(queue, NodeID(destination), channels, length, sample_rate, 128);
+ return { &renderer.leak_ref(), [](void* renderer) { static_cast<Rendering::OfflineAudioRenderer*>(renderer)->ref(); }, [](void* renderer) { static_cast<Rendering::OfflineAudioRenderer*>(renderer)->unref(); } };
+}
+void web_audio_offline_context_set_callbacks(Rendering::OfflineAudioRenderer* renderer, Bindings::RustInterfaceCell* context, JS::PromiseCapability* promise)
+{
+ renderer->set_on_complete([context = GC::make_root(*context), promise = GC::make_root(*promise)] { web_rust_offline_audio_context_complete(JS::HostABI::vm_to_abi(JS::VM::the()), context.ptr(), promise.ptr()); });
+ renderer->set_on_suspended([context = GC::make_root(*context)](double time) { web_rust_offline_audio_context_suspended(JS::HostABI::vm_to_abi(JS::VM::the()), context.ptr(), time); });
+ renderer->set_on_sources_ended([context = GC::make_root(*context)](Vector<NodeID> const& nodes) {
+ Vector<u64> ids;
+ ids.ensure_capacity(nodes.size());
+ for (auto node : nodes)
+ ids.unchecked_append(node.value());
+ web_rust_audio_context_sources_ended(JS::HostABI::vm_to_abi(JS::VM::the()), context.ptr(), ids);
});
- for (auto const& [frame, suspend_promise] : m_suspend_promises)
- m_renderer->request_suspend(frame);
-
- // AD-HOC: Other engines transition the context to "running" once rendering starts.
- set_control_state(Bindings::AudioContextState::Running);
- set_rendering_state(Bindings::AudioContextState::Running);
- queue_a_statechange_event();
-
- m_renderer->start_rendering();
-}
-
-void OfflineAudioContext::finish_rendering(GC::Ref<WebIDL::Promise> promise)
-{
- // NB: Copy the rendered samples into [[rendered buffer]].
- auto const& rendered_channels = m_renderer->rendered_channels();
- for (size_t channel_index = 0; channel_index < rendered_channels.size(); ++channel_index) {
- auto channel_data = MUST(m_rendered_buffer->get_channel_data(relevant_global_object(), channel_index));
- auto const& samples = rendered_channels[channel_index];
- channel_data->viewed_array_buffer()->overwrite(channel_data->byte_offset(), samples.data(), samples.size() * sizeof(float));
- }
-
- // AD-HOC: Other engines transition the context to "closed" once rendering completes.
- set_control_state(Bindings::AudioContextState::Closed);
- set_rendering_state(Bindings::AudioContextState::Closed);
- queue_a_statechange_event();
-
- // NB: Break the reference cycle between the renderer's callbacks and this context.
- m_renderer->clear_callbacks();
-
- // 4: Once the rendering is complete, queue a media element task to execute the following steps:
- queue_a_media_element_task(GC::create_function(GC::Heap::the(), [promise, this]() {
- auto& realm = WebIDL::promise_realm(promise);
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
-
- // 4.1 Resolve the promise created by startRendering() with [[rendered buffer]].
- resolve_audio_buffer_promise(realm, promise, *this->m_rendered_buffer);
-
- // AD-HOC: Remove resolved promise from [[pending promises]]
- // https://github.com/WebAudio/web-audio-api/issues/2648
- m_pending_promises.remove_all_matching([promise](GC::Ref<WebIDL::Promise> const& p) {
- return p.ptr() == promise.ptr();
- });
-
- // 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]].
- queue_a_media_element_task(GC::create_function(GC::Heap::the(), [this]() {
- OfflineAudioCompletionEventInit event_init { {}, *this->m_rendered_buffer };
- auto event = OfflineAudioCompletionEvent::create(HTML::EventNames::complete, event_init, HighResolutionTime::current_high_resolution_time(relevant_global_object()));
- this->dispatch_event(event);
- }));
- }));
-}
-
-void OfflineAudioContext::handle_suspended(double suspend_time)
-{
- set_control_state(Bindings::AudioContextState::Suspended);
- set_rendering_state(Bindings::AudioContextState::Suspended);
-
- auto frame = static_cast<u64>(AK::round(suspend_time * sample_rate()));
- // Suspensions take effect at the beginning of the first render quantum at
- // or after the requested time. Keep the promise keyed by that same frame
- // so the rendering-thread callback can resolve it when it reaches the
- // boundary.
- frame = ((frame + render_quantum_size() - 1) / render_quantum_size()) * render_quantum_size();
- auto suspend_promise = m_suspend_promises.take(frame);
- queue_a_media_element_task(GC::create_function(heap(), [this, suspend_promise]() {
- auto& realm = HTML::relevant_realm(this->relevant_global_object());
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
- if (suspend_promise.has_value())
- WebIDL::resolve_promise(*suspend_promise);
- this->dispatch_event(DOM::Event::create(this->relevant_global_object(), HTML::EventNames::statechange));
- }));
-}
-
-void OfflineAudioContext::queue_a_statechange_event()
-{
- queue_a_media_element_task(GC::create_function(heap(), [this]() {
- this->dispatch_event(DOM::Event::create(this->relevant_global_object(), HTML::EventNames::statechange));
- }));
-}
-
-WebIDL::ExceptionOr<void> OfflineAudioContext::resume()
-{
- if (!m_renderer || state() != AudioContextState::Suspended)
- return WebIDL::InvalidStateError::create("The OfflineAudioContext is not suspended"_utf16);
-
- m_renderer->resume();
- set_control_state(AudioContextState::Running);
- set_rendering_state(AudioContextState::Running);
- queue_a_statechange_event();
- return {};
-}
-
-WebIDL::ExceptionOr<void> OfflineAudioContext::resume(GC::Ref<WebIDL::Promise> promise)
-{
- auto result = resume();
- if (result.is_error()) {
- WebIDL::reject_promise_with_exception(promise, result.release_error());
- return {};
- }
- WebIDL::resolve_promise(promise);
- return {};
-}
-
-WebIDL::ExceptionOr<void> OfflineAudioContext::suspend(double suspend_time)
-{
- (void)suspend_time;
- return WebIDL::InvalidStateError::create("OfflineAudioContext::suspend() requires a promise"_utf16);
-}
-
-WebIDL::ExceptionOr<void> OfflineAudioContext::suspend(double suspend_time, GC::Ref<WebIDL::Promise> promise)
-{
- if (!isfinite(suspend_time) || suspend_time < 0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Suspend time must be a finite, non-negative number"_utf16 };
-
- auto frame = static_cast<u64>(AK::round(suspend_time * sample_rate()));
- frame = ((frame + render_quantum_size() - 1) / render_quantum_size()) * render_quantum_size();
- if (frame >= m_length)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Suspend time must be less than the duration of the context"_utf16 };
- if (m_suspend_promises.contains(frame))
- return WebIDL::InvalidStateError::create("A suspension is already scheduled at this time"_utf16);
-
- m_suspend_promises.set(frame, promise);
- if (m_renderer && !m_renderer->request_suspend(frame)) {
- m_suspend_promises.remove(frame);
- return WebIDL::InvalidStateError::create("The rendering thread has already passed the requested suspend time"_utf16);
- }
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-currenttime
-double OfflineAudioContext::current_time() const
-{
- // This is the time in seconds of the sample frame immediately following the last sample-frame in the block of
- // audio most recently processed by the context's rendering graph.
- if (m_renderer)
- return m_renderer->frames_rendered() / static_cast<double>(sample_rate());
- return Base::current_time();
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-length
-WebIDL::UnsignedLong OfflineAudioContext::length() const
-{
- // The size of the buffer in sample-frames. This is the same as the value of the length parameter for the constructor.
- return m_length;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-oncomplete
-GC::Ptr<WebIDL::CallbackType> OfflineAudioContext::oncomplete()
-{
- return event_handler_attribute(HTML::EventNames::complete);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-oncomplete
-void OfflineAudioContext::set_oncomplete(GC::Ptr<WebIDL::CallbackType> value)
-{
- set_event_handler_attribute(HTML::EventNames::complete, value);
-}
-
-void OfflineAudioContext::document_became_inactive()
-{
- if (m_renderer) {
- m_renderer->stop();
- m_renderer->clear_callbacks();
- }
-}
-
-OfflineAudioContext::OfflineAudioContext(GC::Ref<DOM::EventTarget> relevant_global_object, WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate)
- : BaseAudioContext(relevant_global_object, sample_rate)
- , m_length(length)
- , m_number_of_channels(number_of_channels)
-{
-}
-
-void OfflineAudioContext::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_rendered_buffer);
- visitor.visit(m_suspend_promises);
}
+bool web_audio_offline_context_request_suspend(Rendering::OfflineAudioRenderer* renderer, u64 frame) { return renderer->request_suspend(frame); }
+void web_audio_offline_context_channel(Rendering::OfflineAudioRenderer* renderer, size_t channel, ReadonlySpan<float>* samples) { *samples = renderer->rendered_channels()[channel]; }
+extern "C" void web_audio_offline_context_start(Rendering::OfflineAudioRenderer*);
+void web_audio_offline_context_start(Rendering::OfflineAudioRenderer* renderer) { renderer->start_rendering(); }
+extern "C" void web_audio_offline_context_resume(Rendering::OfflineAudioRenderer*);
+void web_audio_offline_context_resume(Rendering::OfflineAudioRenderer* renderer) { renderer->resume(); }
+extern "C" void web_audio_offline_context_stop(Rendering::OfflineAudioRenderer*);
+void web_audio_offline_context_stop(Rendering::OfflineAudioRenderer* renderer) { renderer->stop(); }
+extern "C" void web_audio_offline_context_clear_callbacks(Rendering::OfflineAudioRenderer*);
+void web_audio_offline_context_clear_callbacks(Rendering::OfflineAudioRenderer* renderer) { renderer->clear_callbacks(); }
+extern "C" u64 web_audio_offline_context_frames_rendered(Rendering::OfflineAudioRenderer*);
+u64 web_audio_offline_context_frames_rendered(Rendering::OfflineAudioRenderer* renderer) { return renderer->frames_rendered(); }
}
diff --git a/Libraries/LibWeb/WebAudio/OfflineAudioContext.h b/Libraries/LibWeb/WebAudio/OfflineAudioContext.h
deleted file mode 100644
index 27f12e74cf3..00000000000
--- a/Libraries/LibWeb/WebAudio/OfflineAudioContext.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2025, Ben Eidson <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/OfflineAudioContext.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h>
-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebAudio {
-
-using OfflineAudioContextOptions = Bindings::OfflineAudioContextOptions;
-
-// https://webaudio.github.io/web-audio-api/#OfflineAudioContext
-class OfflineAudioContext final : public BaseAudioContext {
- WEB_WRAPPABLE(OfflineAudioContext, BaseAudioContext);
- GC_DECLARE_ALLOCATOR(OfflineAudioContext);
-
-public:
- static WebIDL::ExceptionOr<GC::Ref<OfflineAudioContext>> create_for_constructor(JS::Object&, OfflineAudioContextOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<OfflineAudioContext>> create_for_constructor(JS::Object&, WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate);
- static WebIDL::ExceptionOr<GC::Ref<OfflineAudioContext>> create_for_constructor(GC::Ref<DOM::EventTarget> relevant_global_object, OfflineAudioContextOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<OfflineAudioContext>> create_for_constructor(
- GC::Ref<DOM::EventTarget> relevant_global_object,
- WebIDL::UnsignedLong number_of_channels,
- WebIDL::UnsignedLong length,
- float sample_rate);
-
- virtual ~OfflineAudioContext() override;
-
- WebIDL::ExceptionOr<void> start_rendering(GC::Ref<WebIDL::Promise>);
- WebIDL::ExceptionOr<void> resume();
- WebIDL::ExceptionOr<void> resume(GC::Ref<WebIDL::Promise>);
- WebIDL::ExceptionOr<void> suspend(double suspend_time);
- WebIDL::ExceptionOr<void> suspend(double suspend_time, GC::Ref<WebIDL::Promise>);
-
- WebIDL::UnsignedLong length() const;
-
- virtual double current_time() const override;
-
- GC::Ptr<WebIDL::CallbackType> oncomplete();
- void set_oncomplete(GC::Ptr<WebIDL::CallbackType>);
-
-private:
- OfflineAudioContext(GC::Ref<DOM::EventTarget> relevant_global_object, WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate);
- virtual void visit_edges(Cell::Visitor&) override;
- virtual void document_became_inactive() override;
-
- WebIDL::UnsignedLong m_length {};
- WebIDL::UnsignedLong m_number_of_channels {};
- bool m_rendering_started { false };
-
- GC::Ptr<AudioBuffer> m_rendered_buffer;
-
- RefPtr<Rendering::OfflineAudioRenderer> m_renderer;
-
- // https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-suspend, keyed by suspend frame.
- HashMap<u64, GC::Ref<WebIDL::Promise>> m_suspend_promises;
-
- void begin_offline_rendering(GC::Ref<WebIDL::Promise> promise);
- void finish_rendering(GC::Ref<WebIDL::Promise> promise);
- void handle_suspended(double suspend_time);
- void queue_a_statechange_event();
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/OfflineAudioContext.idl b/Libraries/LibWeb/WebAudio/OfflineAudioContext.idl
index 43a7bd0e7f5..fc88fd668c2 100644
--- a/Libraries/LibWeb/WebAudio/OfflineAudioContext.idl
+++ b/Libraries/LibWeb/WebAudio/OfflineAudioContext.idl
@@ -8,10 +8,10 @@ dictionary OfflineAudioContextOptions {
};
// https://webaudio.github.io/web-audio-api/#OfflineAudioContext
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface OfflineAudioContext : BaseAudioContext {
- constructor(OfflineAudioContextOptions contextOptions);
- constructor(unsigned long numberOfChannels, unsigned long length, float sampleRate);
+ [ImplementedAs=construct_options] constructor(OfflineAudioContextOptions contextOptions);
+ [ImplementedAs=construct_channels] constructor(unsigned long numberOfChannels, unsigned long length, float sampleRate);
// FIXME: startRendering is missing the chunkSize parameter.
[CreatesPromise] Promise<AudioBuffer> startRendering();
[CreatesPromise] Promise<undefined> resume();
diff --git a/Libraries/LibWeb/WebAudio/OscillatorNode.cpp b/Libraries/LibWeb/WebAudio/OscillatorNode.cpp
deleted file mode 100644
index f21bf9de350..00000000000
--- a/Libraries/LibWeb/WebAudio/OscillatorNode.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2025, Tim Ledbetter <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Math.h>
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/OscillatorNode.h>
-#include <LibWeb/WebAudio/PeriodicWave.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(OscillatorNode);
-
-OscillatorNode::~OscillatorNode() = default;
-
-void OscillatorNode::queue_waveform_update()
-{
- RefPtr<Rendering::PeriodicWaveData> periodic_wave;
- if (m_periodic_wave)
- periodic_wave = m_periodic_wave->render_data();
-
- context()->queue_control_message(NodeMessage { SetOscillatorWaveform {
- .node_id = node_id(),
- .type = m_type,
- .periodic_wave = move(periodic_wave),
- } });
-}
-
-WebIDL::ExceptionOr<GC::Ref<OscillatorNode>> OscillatorNode::create(GC::Ref<BaseAudioContext> context, OscillatorOptions const& options)
-{
- auto node = GC::Heap::the().allocate<OscillatorNode>(context, options);
-
- if (options.type == OscillatorType::Custom)
- node->set_periodic_wave(options.periodic_wave);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#OscillatorNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count = 2;
- default_options.channel_count_mode = ChannelCountMode::Max;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- // FIXME: Set tail-time to no
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- node->queue_render_node_creation(make<Rendering::OscillatorRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(), node->m_frequency->render_param(), node->m_detune->render_param()));
- node->queue_waveform_update();
-
- return node;
-}
-
-WebIDL::ExceptionOr<void> OscillatorNode::validate_options(OscillatorOptions const& options)
-{
- if (options.type == OscillatorType::Custom && !options.periodic_wave)
- return WebIDL::InvalidStateError::create("Oscillator node type 'custom' requires PeriodicWave to be provided"_utf16);
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-oscillatornode-oscillatornode
-WebIDL::ExceptionOr<GC::Ref<OscillatorNode>> OscillatorNode::create_for_constructor(GC::Ref<BaseAudioContext> context, OscillatorOptions const& options)
-{
- TRY(validate_options(options));
- return create(context, options);
-}
-
-OscillatorNode::OscillatorNode(GC::Ref<BaseAudioContext> context, OscillatorOptions const& options)
- : AudioScheduledSourceNode(context)
- , m_type(options.type)
- , m_frequency(AudioParam::create(context, this, options.frequency, -context->nyquist_frequency(), context->nyquist_frequency(), AutomationRate::ARate))
- , m_detune(AudioParam::create(context, this, options.detune, -1200 * AK::log2(NumericLimits<float>::max()), 1200 * AK::log2(NumericLimits<float>::max()), AutomationRate::ARate))
-{
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-oscillatornode-type
-OscillatorType OscillatorNode::type() const
-{
- return m_type;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-oscillatornode-type
-WebIDL::ExceptionOr<void> OscillatorNode::set_type(OscillatorType type)
-{
- if (type == OscillatorType::Custom && m_type != OscillatorType::Custom)
- return WebIDL::InvalidStateError::create("Oscillator node type cannot be changed to 'custom'"_utf16);
-
- // FIXME: An appropriate PeriodicWave should be set here based on the given type.
- set_periodic_wave(nullptr);
-
- m_type = type;
- queue_waveform_update();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-oscillatornode-setperiodicwave
-void OscillatorNode::set_periodic_wave(GC::Ptr<PeriodicWave> periodic_wave)
-{
- m_periodic_wave = periodic_wave;
- m_type = OscillatorType::Custom;
- queue_waveform_update();
-}
-
-void OscillatorNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_frequency);
- visitor.visit(m_detune);
- visitor.visit(m_periodic_wave);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/OscillatorNode.h b/Libraries/LibWeb/WebAudio/OscillatorNode.h
deleted file mode 100644
index fb1c4d204de..00000000000
--- a/Libraries/LibWeb/WebAudio/OscillatorNode.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/OscillatorNode.h>
-#include <LibWeb/WebAudio/AudioScheduledSourceNode.h>
-
-namespace Web::WebAudio {
-
-using OscillatorType = Bindings::OscillatorType;
-using OscillatorOptions = Bindings::OscillatorOptions;
-
-// https://webaudio.github.io/web-audio-api/#OscillatorNode
-class OscillatorNode : public AudioScheduledSourceNode {
- WEB_WRAPPABLE(OscillatorNode, AudioScheduledSourceNode);
- GC_DECLARE_ALLOCATOR(OscillatorNode);
-
-public:
- static constexpr size_t frequency_offset() { return offsetof(OscillatorNode, m_frequency); }
- static constexpr size_t detune_offset() { return offsetof(OscillatorNode, m_detune); }
- virtual ~OscillatorNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<OscillatorNode>> create(GC::Ref<BaseAudioContext>, OscillatorOptions const& = {});
- static WebIDL::ExceptionOr<void> validate_options(OscillatorOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<OscillatorNode>> create_for_constructor(GC::Ref<BaseAudioContext>, OscillatorOptions const& = {});
-
- OscillatorType type() const;
- WebIDL::ExceptionOr<void> set_type(OscillatorType);
-
- void set_periodic_wave(GC::Ptr<PeriodicWave>);
-
- GC::Ref<AudioParam const> frequency() const { return m_frequency; }
- GC::Ref<AudioParam const> detune() const { return m_detune; }
-
- WebIDL::UnsignedLong number_of_inputs() override { return 0; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
-protected:
- OscillatorNode(GC::Ref<BaseAudioContext>, OscillatorOptions const& = {});
- virtual void visit_edges(Cell::Visitor&) override;
-
-private:
- void queue_waveform_update();
-
- // https://webaudio.github.io/web-audio-api/#dom-oscillatornode-type
- OscillatorType m_type { OscillatorType::Sine };
-
- // https://webaudio.github.io/web-audio-api/#dom-oscillatornode-frequency
- GC::Ref<AudioParam> m_frequency;
-
- // https://webaudio.github.io/web-audio-api/#dom-oscillatornode-detune
- GC::Ref<AudioParam> m_detune;
-
- GC::Ptr<PeriodicWave> m_periodic_wave;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/OscillatorNode.idl b/Libraries/LibWeb/WebAudio/OscillatorNode.idl
index 9a2af70c1a4..2daa720a85a 100644
--- a/Libraries/LibWeb/WebAudio/OscillatorNode.idl
+++ b/Libraries/LibWeb/WebAudio/OscillatorNode.idl
@@ -16,7 +16,7 @@ dictionary OscillatorOptions : AudioNodeOptions {
};
// https://webaudio.github.io/web-audio-api/#OscillatorNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface OscillatorNode : AudioScheduledSourceNode {
constructor(BaseAudioContext context, optional OscillatorOptions options = {});
attribute OscillatorType type;
diff --git a/Libraries/LibWeb/WebAudio/PannerNode.cpp b/Libraries/LibWeb/WebAudio/PannerNode.cpp
deleted file mode 100644
index fba503d2006..00000000000
--- a/Libraries/LibWeb/WebAudio/PannerNode.cpp
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/AudioListener.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/PannerNode.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(PannerNode);
-
-PannerNode::~PannerNode() = default;
-
-void PannerNode::queue_panner_parameters_update()
-{
- context()->queue_control_message(NodeMessage { SetPannerParameters {
- .node_id = node_id(),
- .panning_model = m_panning_model,
- .distance_model = m_distance_model,
- .ref_distance = m_ref_distance,
- .max_distance = m_max_distance,
- .rolloff_factor = m_rolloff_factor,
- .cone_inner_angle = m_cone_inner_angle,
- .cone_outer_angle = m_cone_outer_angle,
- .cone_outer_gain = m_cone_outer_gain,
- } });
-}
-
-WebIDL::ExceptionOr<GC::Ref<PannerNode>> PannerNode::create(GC::Ref<BaseAudioContext> context, PannerOptions const& options)
-{
- // Create the node and allocate memory
- auto node = GC::Heap::the().allocate<PannerNode>(context, options);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#PannerNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count_mode = ChannelCountMode::ClampedMax;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- default_options.channel_count = 2;
- // FIXME: Set tail-time to maybe
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- auto const& listener = context->listener();
- node->queue_render_node_creation(make<Rendering::PannerRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(),
- Rendering::PannerRenderNode::Params {
- node->m_position_x->render_param(),
- node->m_position_y->render_param(),
- node->m_position_z->render_param(),
- node->m_orientation_x->render_param(),
- node->m_orientation_y->render_param(),
- node->m_orientation_z->render_param(),
- },
- Rendering::PannerRenderNode::ListenerParams {
- listener->position_x()->render_param(),
- listener->position_y()->render_param(),
- listener->position_z()->render_param(),
- listener->forward_x()->render_param(),
- listener->forward_y()->render_param(),
- listener->forward_z()->render_param(),
- listener->up_x()->render_param(),
- listener->up_y()->render_param(),
- listener->up_z()->render_param(),
- }));
- node->queue_panner_parameters_update();
-
- return node;
-}
-
-WebIDL::ExceptionOr<void> PannerNode::validate_options(PannerOptions const& options)
-{
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-refdistance
- // A RangeError exception MUST be thrown if this is set to a negative value.
- if (options.ref_distance < 0.0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "refDistance cannot be negative"_utf16 };
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-rollofffactor
- // A RangeError exception MUST be thrown if this is set to a negative value.
- if (options.rolloff_factor < 0.0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "rolloffFactor cannot be negative"_utf16 };
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-maxdistance
- // A RangeError exception MUST be thrown if this is set to a non-positive value.
- if (options.max_distance <= 0.0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "maxDistance must be positive"_utf16 };
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-coneoutergain
- // It is a linear value (not dB) in the range [0, 1]. An InvalidStateError MUST be thrown if the parameter is outside this range.
- if (options.cone_outer_gain < 0.0 || options.cone_outer_gain > 1.0)
- return WebIDL::InvalidStateError::create("coneOuterGain must be in the range of [0, 1]"_utf16);
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-pannernode-pannernode
-WebIDL::ExceptionOr<GC::Ref<PannerNode>> PannerNode::create_for_constructor(GC::Ref<BaseAudioContext> context, PannerOptions const& options)
-{
- TRY(validate_options(options));
- return create(context, options);
-}
-
-PannerNode::PannerNode(GC::Ref<BaseAudioContext> context, PannerOptions const& options)
- : AudioNode(context)
- , m_panning_model(options.panning_model)
- , m_position_x(AudioParam::create(context, this, options.position_x, NumericLimits<float>::lowest(), NumericLimits<float>::max(), AutomationRate::ARate))
- , m_position_y(AudioParam::create(context, this, options.position_y, NumericLimits<float>::lowest(), NumericLimits<float>::max(), AutomationRate::ARate))
- , m_position_z(AudioParam::create(context, this, options.position_z, NumericLimits<float>::lowest(), NumericLimits<float>::max(), AutomationRate::ARate))
- , m_orientation_x(AudioParam::create(context, this, options.orientation_x, NumericLimits<float>::lowest(), NumericLimits<float>::max(), AutomationRate::ARate))
- , m_orientation_y(AudioParam::create(context, this, options.orientation_y, NumericLimits<float>::lowest(), NumericLimits<float>::max(), AutomationRate::ARate))
- , m_orientation_z(AudioParam::create(context, this, options.orientation_z, NumericLimits<float>::lowest(), NumericLimits<float>::max(), AutomationRate::ARate))
- , m_distance_model(options.distance_model)
- , m_ref_distance(options.ref_distance)
- , m_max_distance(options.max_distance)
- , m_rolloff_factor(options.rolloff_factor)
- , m_cone_inner_angle(options.cone_inner_angle)
- , m_cone_outer_angle(options.cone_outer_angle)
- , m_cone_outer_gain(options.cone_outer_gain)
-{
-}
-
-void PannerNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_position_x);
- visitor.visit(m_position_y);
- visitor.visit(m_position_z);
- visitor.visit(m_orientation_x);
- visitor.visit(m_orientation_y);
- visitor.visit(m_orientation_z);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-pannernode-panningmodel
-void PannerNode::set_panning_model(PanningModelType value)
-{
- m_panning_model = value;
- queue_panner_parameters_update();
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-pannernode-distancemodel
-void PannerNode::set_distance_model(DistanceModelType value)
-{
- m_distance_model = value;
- queue_panner_parameters_update();
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-pannernode-refdistance
-WebIDL::ExceptionOr<void> PannerNode::set_ref_distance(double value)
-{
- // A RangeError exception MUST be thrown if this is set to a negative value.
- if (value < 0.0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "refDistance cannot be negative"_utf16 };
-
- m_ref_distance = value;
- queue_panner_parameters_update();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-pannernode-maxdistance
-WebIDL::ExceptionOr<void> PannerNode::set_max_distance(double value)
-{
- // A RangeError exception MUST be thrown if this is set to a non-positive value.
- if (value <= 0.0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "maxDistance must be positive"_utf16 };
-
- m_max_distance = value;
- queue_panner_parameters_update();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-pannernode-rollofffactor
-WebIDL::ExceptionOr<void> PannerNode::set_rolloff_factor(double value)
-{
- // A RangeError exception MUST be thrown if this is set to a negative value.
- if (value < 0.0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "rolloffFactor cannot be negative"_utf16 };
-
- m_rolloff_factor = value;
- queue_panner_parameters_update();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-pannernode-coneoutergain
-WebIDL::ExceptionOr<void> PannerNode::set_cone_outer_gain(double value)
-{
- // It is a linear value (not dB) in the range [0, 1]. An InvalidStateError MUST be thrown if the parameter is outside this range.
- if (value < 0.0 || value > 1.0)
- return WebIDL::InvalidStateError::create("coneOuterGain must be in the range of [0, 1]"_utf16);
-
- m_cone_outer_gain = value;
- queue_panner_parameters_update();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-pannernode-setposition
-WebIDL::ExceptionOr<void> PannerNode::set_position(float x, float y, float z)
-{
- // This method is DEPRECATED. It is equivalent to setting positionX.value, positionY.value, and positionZ.value
- // attribute directly with the x, y and z parameters, respectively.
- // Consequently, if any of the positionX, positionY, and positionZ AudioParams have an automation curve set using
- // setValueCurveAtTime() at the time this method is called, a NotSupportedError MUST be thrown.
- TRY(m_position_x->set_value(x));
- TRY(m_position_y->set_value(y));
- TRY(m_position_z->set_value(z));
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-pannernode-setorientation
-WebIDL::ExceptionOr<void> PannerNode::set_orientation(float x, float y, float z)
-{
- // This method is DEPRECATED. It is equivalent to setting orientationX.value, orientationY.value, and
- // orientationZ.value attribute directly, with the x, y and z parameters, respectively.
- // Consequently, if any of the orientationX, orientationY, and orientationZ AudioParams have an automation curve set
- // using setValueCurveAtTime() at the time this method is called, a NotSupportedError MUST be thrown.
- TRY(m_orientation_x->set_value(x));
- TRY(m_orientation_y->set_value(y));
- TRY(m_orientation_z->set_value(z));
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
-WebIDL::ExceptionOr<void> PannerNode::set_channel_count_mode(ChannelCountMode mode)
-{
- if (mode == ChannelCountMode::Max) {
- return WebIDL::NotSupportedError::create("PannerNode does not support 'max' as channelCountMode."_utf16);
- }
-
- return AudioNode::set_channel_count_mode(mode);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
-WebIDL::ExceptionOr<void> PannerNode::set_channel_count(WebIDL::UnsignedLong channel_count)
-{
- if (channel_count > 2) {
- return WebIDL::NotSupportedError::create("PannerNode does not support channel count greater than 2"_utf16);
- }
-
- return AudioNode::set_channel_count(channel_count);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/PannerNode.h b/Libraries/LibWeb/WebAudio/PannerNode.h
deleted file mode 100644
index aaef46d4160..00000000000
--- a/Libraries/LibWeb/WebAudio/PannerNode.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (c) 2024, Luke Wilde <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/PannerNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio {
-
-using DistanceModelType = Bindings::DistanceModelType;
-using PanningModelType = Bindings::PanningModelType;
-using PannerOptions = Bindings::PannerOptions;
-
-// https://webaudio.github.io/web-audio-api/#PannerNode
-class PannerNode final : public AudioNode {
- WEB_WRAPPABLE(PannerNode, AudioNode);
- GC_DECLARE_ALLOCATOR(PannerNode);
-
-public:
- static constexpr size_t position_x_offset() { return offsetof(PannerNode, m_position_x); }
- static constexpr size_t position_y_offset() { return offsetof(PannerNode, m_position_y); }
- static constexpr size_t position_z_offset() { return offsetof(PannerNode, m_position_z); }
- static constexpr size_t orientation_x_offset() { return offsetof(PannerNode, m_orientation_x); }
- static constexpr size_t orientation_y_offset() { return offsetof(PannerNode, m_orientation_y); }
- static constexpr size_t orientation_z_offset() { return offsetof(PannerNode, m_orientation_z); }
- virtual ~PannerNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<PannerNode>> create(GC::Ref<BaseAudioContext>, PannerOptions const& = {});
- static WebIDL::ExceptionOr<void> validate_options(PannerOptions const&);
- static WebIDL::ExceptionOr<GC::Ref<PannerNode>> create_for_constructor(GC::Ref<BaseAudioContext>, PannerOptions const& = {});
-
- WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- GC::Ref<AudioParam const> position_x() const { return m_position_x; }
- GC::Ref<AudioParam const> position_y() const { return m_position_y; }
- GC::Ref<AudioParam const> position_z() const { return m_position_z; }
- GC::Ref<AudioParam const> orientation_x() const { return m_orientation_x; }
- GC::Ref<AudioParam const> orientation_y() const { return m_orientation_y; }
- GC::Ref<AudioParam const> orientation_z() const { return m_orientation_z; }
-
- PanningModelType panning_model() const { return m_panning_model; }
- void set_panning_model(PanningModelType);
-
- DistanceModelType distance_model() const { return m_distance_model; }
- void set_distance_model(DistanceModelType);
-
- double ref_distance() const { return m_ref_distance; }
- WebIDL::ExceptionOr<void> set_ref_distance(double);
-
- double max_distance() const { return m_max_distance; }
- WebIDL::ExceptionOr<void> set_max_distance(double);
-
- double rolloff_factor() const { return m_rolloff_factor; }
- WebIDL::ExceptionOr<void> set_rolloff_factor(double);
-
- double cone_inner_angle() const { return m_cone_inner_angle; }
- void set_cone_inner_angle(double value)
- {
- m_cone_inner_angle = value;
- queue_panner_parameters_update();
- }
-
- double cone_outer_angle() const { return m_cone_outer_angle; }
- void set_cone_outer_angle(double value)
- {
- m_cone_outer_angle = value;
- queue_panner_parameters_update();
- }
-
- double cone_outer_gain() const { return m_cone_outer_gain; }
- WebIDL::ExceptionOr<void> set_cone_outer_gain(double);
-
- void queue_panner_parameters_update();
-
- WebIDL::ExceptionOr<void> set_position(float x, float y, float z);
- WebIDL::ExceptionOr<void> set_orientation(float x, float y, float z);
-
- // ^AudioNode
- virtual WebIDL::ExceptionOr<void> set_channel_count(WebIDL::UnsignedLong) override;
- virtual WebIDL::ExceptionOr<void> set_channel_count_mode(ChannelCountMode) override;
-
-protected:
- PannerNode(GC::Ref<BaseAudioContext>, PannerOptions const& = {});
- virtual void visit_edges(Cell::Visitor&) override;
-
-private:
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-panningmodel
- PanningModelType m_panning_model { PanningModelType::Equalpower };
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-positionx
- GC::Ref<AudioParam> m_position_x;
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-positiony
- GC::Ref<AudioParam> m_position_y;
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-positionz
- GC::Ref<AudioParam> m_position_z;
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-orientationx
- GC::Ref<AudioParam> m_orientation_x;
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-orientationy
- GC::Ref<AudioParam> m_orientation_y;
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-orientationz
- GC::Ref<AudioParam> m_orientation_z;
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-distancemodel
- DistanceModelType m_distance_model { DistanceModelType::Inverse };
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-refdistance
- double m_ref_distance { 1.0 };
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-maxdistance
- double m_max_distance { 10000.0 };
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-rollofffactor
- double m_rolloff_factor { 1.0 };
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-coneinnerangle
- double m_cone_inner_angle { 360.0 };
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-coneouterangle
- double m_cone_outer_angle { 360.0 };
-
- // https://webaudio.github.io/web-audio-api/#dom-pannernode-coneoutergain
- double m_cone_outer_gain { 0.0 };
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/PannerNode.idl b/Libraries/LibWeb/WebAudio/PannerNode.idl
index 579b698877a..11741d7a2b8 100644
--- a/Libraries/LibWeb/WebAudio/PannerNode.idl
+++ b/Libraries/LibWeb/WebAudio/PannerNode.idl
@@ -30,7 +30,7 @@ dictionary PannerOptions : AudioNodeOptions {
};
// https://webaudio.github.io/web-audio-api/#PannerNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface PannerNode : AudioNode {
constructor(BaseAudioContext context, optional PannerOptions options = {});
attribute PanningModelType panningModel;
diff --git a/Libraries/LibWeb/WebAudio/PeriodicWave.cpp b/Libraries/LibWeb/WebAudio/PeriodicWave.cpp
deleted file mode 100644
index 479aedbbcce..00000000000
--- a/Libraries/LibWeb/WebAudio/PeriodicWave.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2025, Tim Ledbetter <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/Realm.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/WebAudio/PeriodicWave.h>
-
-namespace Web::WebAudio {
-
-extern "C" {
-JSCompletion web_rust_periodic_wave_create(JSVM*, void* realm, bool, ReadonlySpan<float>, bool, ReadonlySpan<float>, bool, void**);
-void const* web_rust_periodic_wave_render_data(void* cell, bool* normalize);
-}
-
-WebIDL::ExceptionOr<GC::Ref<PeriodicWave>> PeriodicWave::create_for_constructor(GC::Ref<BaseAudioContext>, PeriodicWaveOptions const& options)
-{
- auto& vm = JS::VM::the();
- void* wave = nullptr;
- TRY(JS::HostABI::completion_from_abi<void>(web_rust_periodic_wave_create(JS::HostABI::vm_to_abi(vm), vm.current_realm(), options.real.has_value(), options.real.has_value() ? options.real->span() : ReadonlySpan<float> {}, options.imag.has_value(), options.imag.has_value() ? options.imag->span() : ReadonlySpan<float> {}, options.disable_normalization, &wave)));
- return GC::Ref { *static_cast<PeriodicWave*>(wave) };
-}
-
-NonnullRefPtr<Rendering::PeriodicWaveData> PeriodicWave::render_data() const
-{
- bool normalize;
- auto* data = web_rust_periodic_wave_render_data(const_cast<PeriodicWave*>(this), &normalize);
- return make_ref_counted<Rendering::PeriodicWaveData>(data, normalize);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/PeriodicWave.h b/Libraries/LibWeb/WebAudio/PeriodicWave.h
deleted file mode 100644
index 00ca357d1f5..00000000000
--- a/Libraries/LibWeb/WebAudio/PeriodicWave.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/Vector.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/PeriodicWave.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/WebAudio/Rendering/AudioData.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::WebAudio {
-
-class BaseAudioContext;
-
-using PeriodicWaveConstraints = Bindings::PeriodicWaveConstraints;
-struct PeriodicWaveOptions : PeriodicWaveConstraints {
- Optional<Vector<float>> real;
- Optional<Vector<float>> imag;
-};
-
-// https://webaudio.github.io/web-audio-api/#PeriodicWave
-class PeriodicWave : public Bindings::RustInterfaceCell {
- WEB_RUST_INTERFACE(PeriodicWave, periodic_wave)
-
-public:
- static WebIDL::ExceptionOr<GC::Ref<PeriodicWave>> create_for_constructor(GC::Ref<BaseAudioContext>, PeriodicWaveOptions const&);
- NonnullRefPtr<Rendering::PeriodicWaveData> render_data() const;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp b/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp
index 14b36ef5d52..117f7a152b4 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp
@@ -18,12 +18,12 @@ struct OfflineAudioRendererCallbacks : AtomicRefCounted<OfflineAudioRendererCall
Function<void(Vector<NodeID> const&)> on_sources_ended;
};
-NonnullRefPtr<OfflineAudioRenderer> OfflineAudioRenderer::create(NonnullRefPtr<ControlMessageQueue> control_message_queue, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size)
+NonnullRefPtr<OfflineAudioRenderer> OfflineAudioRenderer::create(void const* control_message_queue, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size)
{
- return adopt_ref(*new OfflineAudioRenderer(move(control_message_queue), destination_node_id, number_of_channels, length, sample_rate, quantum_size));
+ return adopt_ref(*new OfflineAudioRenderer(control_message_queue, destination_node_id, number_of_channels, length, sample_rate, quantum_size));
}
-OfflineAudioRenderer::OfflineAudioRenderer(NonnullRefPtr<ControlMessageQueue> control_message_queue, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size)
+OfflineAudioRenderer::OfflineAudioRenderer(void const* control_message_queue, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size)
: m_callbacks(adopt_ref(*new OfflineAudioRendererCallbacks))
{
RustFFI::RendererCallbacks callbacks {
@@ -51,7 +51,7 @@ OfflineAudioRenderer::OfflineAudioRenderer(NonnullRefPtr<ControlMessageQueue> co
callbacks.on_sources_ended(nodes);
},
};
- m_renderer = RustFFI::web_audio_offline_renderer_create(control_message_queue->rust_queue(), destination_node_id.value(), number_of_channels, length, sample_rate, quantum_size, callbacks);
+ m_renderer = RustFFI::web_audio_offline_renderer_create(control_message_queue, destination_node_id.value(), number_of_channels, length, sample_rate, quantum_size, callbacks);
m_rendered_channels.resize(number_of_channels);
for (size_t channel = 0; channel < number_of_channels; ++channel)
RustFFI::web_audio_offline_renderer_channel(m_renderer, channel, &m_rendered_channels[channel]);
diff --git a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h b/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h
index a46e8d89c98..a5d9e6911ac 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h
+++ b/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h
@@ -38,7 +38,7 @@ struct OfflineAudioRendererCallbacks;
class WEB_API OfflineAudioRenderer final : public AtomicRefCounted<OfflineAudioRenderer> {
public:
- static NonnullRefPtr<OfflineAudioRenderer> create(NonnullRefPtr<ControlMessageQueue>, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size);
+ static NonnullRefPtr<OfflineAudioRenderer> create(void const*, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size);
~OfflineAudioRenderer();
@@ -66,7 +66,7 @@ public:
Vector<ReadonlySpan<float>> const& rendered_channels() const { return m_rendered_channels; }
private:
- OfflineAudioRenderer(NonnullRefPtr<ControlMessageQueue>, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size);
+ OfflineAudioRenderer(void const*, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size);
NonnullRefPtr<OfflineAudioRendererCallbacks> m_callbacks;
void const* m_renderer { nullptr };
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp b/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp
index cb170163622..74e4f7a5c88 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp
@@ -17,12 +17,12 @@ struct RealtimeAudioRendererCallbacks : AtomicRefCounted<RealtimeAudioRendererCa
Function<void(Vector<NodeID> const&)> on_sources_ended;
};
-NonnullRefPtr<RealtimeAudioRenderer> RealtimeAudioRenderer::create(NonnullRefPtr<ControlMessageQueue> control_message_queue, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory> audio_output_factory)
+NonnullRefPtr<RealtimeAudioRenderer> RealtimeAudioRenderer::create(void const* control_message_queue, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory> audio_output_factory)
{
- return adopt_ref(*new RealtimeAudioRenderer(move(control_message_queue), destination_node_id, sample_rate, quantum_size, move(audio_output_factory)));
+ return adopt_ref(*new RealtimeAudioRenderer(control_message_queue, destination_node_id, sample_rate, quantum_size, move(audio_output_factory)));
}
-RealtimeAudioRenderer::RealtimeAudioRenderer(NonnullRefPtr<ControlMessageQueue> control_message_queue, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory> audio_output_factory)
+RealtimeAudioRenderer::RealtimeAudioRenderer(void const* control_message_queue, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory> audio_output_factory)
: m_callbacks(adopt_ref(*new RealtimeAudioRendererCallbacks))
, m_audio_output_factory(move(audio_output_factory))
{
@@ -43,7 +43,7 @@ RealtimeAudioRenderer::RealtimeAudioRenderer(NonnullRefPtr<ControlMessageQueue>
callbacks.on_sources_ended(nodes);
},
};
- m_renderer = RustFFI::web_audio_realtime_renderer_create(control_message_queue->rust_queue(), destination_node_id.value(), sample_rate, quantum_size, callbacks);
+ m_renderer = RustFFI::web_audio_realtime_renderer_create(control_message_queue, destination_node_id.value(), sample_rate, quantum_size, callbacks);
}
RealtimeAudioRenderer::~RealtimeAudioRenderer() { RustFFI::web_audio_realtime_renderer_destroy(m_renderer); }
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h b/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h
index 2eccad0bd38..66064d853c7 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h
+++ b/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h
@@ -38,7 +38,7 @@ public:
// renderer's burst size, which this constant determines.
static constexpr u32 TARGET_LATENCY_MS = 100;
- static NonnullRefPtr<RealtimeAudioRenderer> create(NonnullRefPtr<ControlMessageQueue>, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory>);
+ static NonnullRefPtr<RealtimeAudioRenderer> create(void const*, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory>);
~RealtimeAudioRenderer();
// The callback below is set on the control thread before rendering starts and is always invoked on the control
@@ -57,7 +57,7 @@ public:
double output_time_played() const;
private:
- RealtimeAudioRenderer(NonnullRefPtr<ControlMessageQueue>, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory>);
+ RealtimeAudioRenderer(void const*, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory>);
void prepare_to_start_rendering();
void set_playback_stream(NonnullRefPtr<Audio::PlaybackStream>);
diff --git a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp
index acd34c9e949..04b5cbb4770 100644
--- a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp
+++ b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp
@@ -1,231 +1,33 @@
/*
* Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include "BaseAudioContext.h"
-
-#include <AK/GenericShorthands.h>
#include <LibCore/EventLoop.h>
-#include <LibGC/Heap.h>
#include <LibGC/Weak.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/HTML/EventNames.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
-#include <LibWeb/HTML/Window.h>
-#include <LibWeb/HighResolutionTime/TimeOrigin.h>
-#include <LibWeb/WebAudio/AudioBuffer.h>
-#include <LibWeb/WebAudio/AudioProcessingEvent.h>
-#include <LibWeb/WebAudio/OfflineAudioContext.h>
-#include <LibWeb/WebAudio/Rendering/AudioWorkletPipe.h>
-#include <LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h>
-#include <LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.h>
-#include <LibWeb/WebAudio/ScriptProcessorNode.h>
+#include <LibWeb/WebAudio/RustFFI.h>
namespace Web::WebAudio {
-GC_DEFINE_ALLOCATOR(ScriptProcessorNode);
-
-ScriptProcessorNode::ScriptProcessorNode(GC::Ref<BaseAudioContext> context,
- u8 number_of_input_channels, u8 number_of_output_channels)
- : AudioNode(context, number_of_input_channels)
- , m_number_of_input_channels(number_of_input_channels)
- , m_number_of_output_channels(number_of_output_channels)
-{
-}
-
-ScriptProcessorNode::~ScriptProcessorNode() = default;
-
-// Other engines have a latency of two buffers. A realtime context needs more when the device pulls a burst of audio
-// that is longer than a buffer, since script cannot run in the middle of a burst.
-static size_t block_count_for_context(BaseAudioContext const& context, size_t buffer_size)
-{
- if (is<OfflineAudioContext>(context))
- return 2;
- auto quantum_size = BaseAudioContext::render_quantum_size();
- auto lookahead_frames = Rendering::AudioWorkletPipe::Config::ring_sizing_for_device_latency(
- Rendering::RealtimeAudioRenderer::TARGET_LATENCY_MS, context.sample_rate(), quantum_size)
- .prime_level
- * quantum_size;
- return max(ceil_div(lookahead_frames, buffer_size) + 1, 2uz);
-}
-
-WebIDL::ExceptionOr<GC::Ref<ScriptProcessorNode>> ScriptProcessorNode::create(
- GC::Ref<BaseAudioContext> context,
- WebIDL::Long buffer_size,
- WebIDL::UnsignedLong number_of_input_channels,
- WebIDL::UnsignedLong number_of_output_channels)
+extern "C" void web_rust_script_processor_process(JSVM*, void*, size_t, u64);
+extern "C" RustFFI::FfiSharedCppObject web_audio_script_processor_create_pipe(Bindings::RustInterfaceCell*, RustFFI::ScriptProcessorPipeConfig, void const**);
+extern "C" void web_audio_script_processor_clear_callback(Rendering::ScriptProcessorPipe*);
+RustFFI::FfiSharedCppObject web_audio_script_processor_create_pipe(Bindings::RustInterfaceCell* node, RustFFI::ScriptProcessorPipeConfig config, void const** native_pipe)
{
- auto script_processor_node = GC::Heap::the().allocate<ScriptProcessorNode>(context,
- static_cast<u8>(number_of_input_channels), static_cast<u8>(number_of_output_channels));
-
- script_processor_node->set_buffer_size_without_validation(buffer_size);
-
- // https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
- // The channel count mode cannot be changed from "explicit" and an NotSupportedError exception MUST be thrown for
- // any attempt to change the value.
- TRY(script_processor_node->set_channel_count_mode(ChannelCountMode::Explicit));
-
- Rendering::ScriptProcessorPipe::Config pipe_config {
- .buffer_size = static_cast<size_t>(buffer_size),
- .input_channel_count = number_of_input_channels,
- .output_channel_count = number_of_output_channels,
- .block_count = block_count_for_context(context, buffer_size),
- .waits_for_processing = is<OfflineAudioContext>(*context),
- };
- auto pipe = Rendering::ScriptProcessorPipe::create(pipe_config, Core::EventLoop::current());
- pipe->set_process_callback([node = GC::Weak { *script_processor_node }](size_t block, u64 start_frame) {
+ auto pipe = Rendering::ScriptProcessorPipe::create({ config.buffer_size, config.input_channel_count, config.output_channel_count, config.block_count, config.waits_for_processing }, Core::EventLoop::current());
+ pipe->set_process_callback([node = GC::Weak { *node }](size_t block, u64 start_frame) {
if (node)
- node->process_block(block, start_frame);
+ web_rust_script_processor_process(JS::HostABI::vm_to_abi(JS::VM::the()), node.ptr().ptr(), block, start_frame);
});
- script_processor_node->m_pipe = pipe;
- context->add_script_processor_node(*script_processor_node);
- script_processor_node->queue_render_node_creation(make<Rendering::ScriptProcessorRenderNode>(
- script_processor_node->node_id(), BaseAudioContext::render_quantum_size(), move(pipe)));
-
- return script_processor_node;
-}
-
-void ScriptProcessorNode::finalize()
-{
- if (m_pipe) {
- m_pipe->clear_process_callback();
- m_pipe->shut_down();
- }
- Base::finalize();
-}
-
-void ScriptProcessorNode::process_block(size_t block, u64 start_frame)
-{
- auto& pipe = *m_pipe;
- auto const& config = pipe.config();
-
- if (!context()->relevant_window().associated_document().is_fully_active()) {
- pipe.hand_block_back_to_rendering_thread(block, false);
- return;
- }
-
- auto as_samples = [](Bytes bytes) {
- return Span<float> { reinterpret_cast<float*>(bytes.data()), bytes.size() / sizeof(float) };
- };
-
- auto sample_rate = context()->sample_rate();
- auto input_buffer = MUST(AudioBuffer::create(config.input_channel_count, config.buffer_size, sample_rate));
- for (size_t channel = 0; channel < config.input_channel_count; ++channel)
- pipe.input_channel(block, channel).copy_to(as_samples(MUST(input_buffer->channel_data(channel))));
- auto output_buffer = MUST(AudioBuffer::create(config.output_channel_count, config.buffer_size, sample_rate));
-
- auto playback_time = (start_frame + config.block_count * config.buffer_size) / static_cast<double>(sample_rate);
-
- {
- HTML::TemporaryExecutionContext execution_context { HTML::relevant_realm(relevant_global_object()), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
- AudioProcessingEventInit event_init { {}, input_buffer, output_buffer, playback_time };
- auto event = AudioProcessingEvent::create(HTML::EventNames::audioprocess, event_init, HighResolutionTime::current_high_resolution_time(relevant_global_object()));
- dispatch_event(event);
- }
-
- // https://webaudio.github.io/web-audio-api/#acquire-the-content
- // When the dispatch of an AudioProcessingEvent completes, it acquires the contents of its outputBuffer.
- auto output = output_buffer->acquire_contents();
- if (!output) {
- pipe.hand_block_back_to_rendering_thread(block, false);
- return;
- }
- for (size_t channel = 0; channel < config.output_channel_count; ++channel)
- output->channels[channel].copy_to(pipe.output_channel(block, channel));
- pipe.hand_block_back_to_rendering_thread(block, true);
-}
-
-WebIDL::ExceptionOr<void> ScriptProcessorNode::validate_options(
- WebIDL::Long buffer_size,
- WebIDL::UnsignedLong number_of_input_channels,
- WebIDL::UnsignedLong number_of_output_channels)
-{
- // https://webaudio.github.io/web-audio-api/#ScriptProcessorNode
- // It is invalid for both numberOfInputChannels and numberOfOutputChannels to be zero. In this case an
- // IndexSizeError MUST be thrown.
- if (number_of_input_channels == 0 && number_of_output_channels == 0) {
- return WebIDL::IndexSizeError::create(
- "Number of input and output channels cannot both be zero in a ScriptProcessorNode"_utf16);
- }
-
- // This parameter determines the number of channels for this node’s input. The default value is 2. Values of up to
- // 32 must be supported. A NotSupportedError must be thrown if the number of channels is not supported.
- if (number_of_input_channels > BaseAudioContext::MAX_NUMBER_OF_CHANNELS)
- return WebIDL::NotSupportedError::create("Invalid number of input channels"_utf16);
-
- // This parameter determines the number of channels for this node’s output. The default value is 2. Values of up to
- // 32 must be supported. A NotSupportedError must be thrown if the number of channels is not supported.
- if (number_of_output_channels > BaseAudioContext::MAX_NUMBER_OF_CHANNELS)
- return WebIDL::NotSupportedError::create("Invalid number of output channels"_utf16);
-
- // The size of the buffer (in sample-frames) which needs to be processed each time audioprocess is fired. Legal
- // values are (256, 512, 1024, 2048, 4096, 8192, 16384).
- //
- // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createscriptprocessor
- // If the value of this parameter is not one of the allowed power-of-2 values listed above, an IndexSizeError MUST
- // be thrown.
- if (!first_is_one_of(buffer_size, 256, 512, 1024, 2048, 4096, 8192, 16384))
- return WebIDL::IndexSizeError::create("Unsupported buffer size for a ScriptProcessorNode"_utf16);
-
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#ScriptProcessorNode
-WebIDL::UnsignedLong ScriptProcessorNode::channel_count() const
-{
- // This is the number of channels specified when constructing this node.
- return m_number_of_input_channels;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
-WebIDL::ExceptionOr<void> ScriptProcessorNode::set_channel_count(WebIDL::UnsignedLong)
-{
- // ScriptProcessorNode: The channel count cannot be changed, and an NotSupportedError exception MUST be thrown for
- // any attempt to change the value.
- return WebIDL::InvalidStateError::create("Cannot modify channel count in a ScriptProcessorNode"_utf16);
-}
-
-WebIDL::ExceptionOr<void> ScriptProcessorNode::set_channel_count_mode(ChannelCountMode channel_count_mode)
-{
- // https://webaudio.github.io/web-audio-api/#audionode-channelcountmode-constraints
- // ScriptProcessorNode: The channel count mode cannot be changed from "explicit" and an NotSupportedError exception
- // MUST be thrown for any attempt to change the value.
- if (channel_count_mode != ChannelCountMode::Explicit)
- return WebIDL::InvalidStateError::create("Channel count mode must be 'explicit'"_utf16);
-
- return AudioNode::set_channel_count_mode(channel_count_mode);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-scriptprocessornode-onaudioprocess
-GC::Ptr<WebIDL::CallbackType> ScriptProcessorNode::onaudioprocess()
-{
- return event_handler_attribute(HTML::EventNames::audioprocess);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-scriptprocessornode-onaudioprocess
-void ScriptProcessorNode::set_onaudioprocess(GC::Ptr<WebIDL::CallbackType> value)
-{
- set_event_handler_attribute(HTML::EventNames::audioprocess, value);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-scriptprocessornode-buffersize
-WebIDL::ExceptionOr<void> ScriptProcessorNode::set_buffer_size(WebIDL::Long buffer_size)
-{
- // The size of the buffer (in sample-frames) which needs to be processed each time audioprocess is fired. Legal
- // values are (256, 512, 1024, 2048, 4096, 8192, 16384).
-
- // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createscriptprocessor
- // If the value of this parameter is not one of the allowed power-of-2 values listed above, an IndexSizeError MUST
- // be thrown.
- if (!first_is_one_of(buffer_size, 256, 512, 1024, 2048, 4096, 8192, 16384))
- return WebIDL::IndexSizeError::create("Unsupported buffer size for a ScriptProcessorNode"_utf16);
-
- m_buffer_size = buffer_size;
- return {};
+ *native_pipe = pipe->rust_pipe();
+ return { &pipe.leak_ref(), [](void* pipe) { static_cast<Rendering::ScriptProcessorPipe*>(pipe)->ref(); }, [](void* pipe) { static_cast<Rendering::ScriptProcessorPipe*>(pipe)->unref(); } };
}
+void web_audio_script_processor_clear_callback(Rendering::ScriptProcessorPipe* pipe) { pipe->clear_process_callback(); }
}
diff --git a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.h b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.h
deleted file mode 100644
index ee78799c342..00000000000
--- a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/RefPtr.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio::Rendering {
-
-class ScriptProcessorPipe;
-
-}
-
-namespace Web::WebAudio {
-
-// https://webaudio.github.io/web-audio-api/#ScriptProcessorNode
-class ScriptProcessorNode final : public AudioNode {
- WEB_WRAPPABLE(ScriptProcessorNode, AudioNode);
- GC_DECLARE_ALLOCATOR(ScriptProcessorNode);
-
-public:
- static constexpr WebIDL::Long DEFAULT_BUFFER_SIZE = 1024;
-
- virtual ~ScriptProcessorNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<ScriptProcessorNode>> create(
- GC::Ref<BaseAudioContext>,
- WebIDL::Long buffer_size,
- WebIDL::UnsignedLong number_of_input_channels,
- WebIDL::UnsignedLong number_of_output_channel);
- static WebIDL::ExceptionOr<void> validate_options(
- WebIDL::Long buffer_size,
- WebIDL::UnsignedLong number_of_input_channels,
- WebIDL::UnsignedLong number_of_output_channel);
-
- // ^AudioNode
- virtual WebIDL::UnsignedLong channel_count() const override;
- virtual WebIDL::ExceptionOr<void> set_channel_count(WebIDL::UnsignedLong) override;
- virtual WebIDL::ExceptionOr<void> set_channel_count_mode(ChannelCountMode) override;
- virtual WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- virtual WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- GC::Ptr<WebIDL::CallbackType> onaudioprocess();
- void set_onaudioprocess(GC::Ptr<WebIDL::CallbackType>);
-
- WebIDL::Long buffer_size() const { return m_buffer_size; }
- WebIDL::ExceptionOr<void> set_buffer_size(WebIDL::Long buffer_size);
-
-private:
- ScriptProcessorNode(GC::Ref<BaseAudioContext>, u8 number_of_input_channels, u8 number_of_output_channels);
-
- virtual void finalize() override;
-
- void set_buffer_size_without_validation(WebIDL::Long buffer_size) { m_buffer_size = buffer_size; }
- void process_block(size_t block, u64 start_frame);
-
- RefPtr<Rendering::ScriptProcessorPipe> m_pipe;
- WebIDL::Long m_buffer_size { 0 };
- u8 m_number_of_input_channels { 0 };
- u8 m_number_of_output_channels { 0 };
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.idl b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.idl
index d00fed8ae72..f2e5156cf14 100644
--- a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.idl
+++ b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.idl
@@ -1,5 +1,5 @@
// https://webaudio.github.io/web-audio-api/#ScriptProcessorNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface ScriptProcessorNode : AudioNode {
attribute EventHandler onaudioprocess;
readonly attribute long bufferSize;
diff --git a/Libraries/LibWeb/WebAudio/StereoPannerNode.cpp b/Libraries/LibWeb/WebAudio/StereoPannerNode.cpp
deleted file mode 100644
index f5682cd95f7..00000000000
--- a/Libraries/LibWeb/WebAudio/StereoPannerNode.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) 2025, Tim Ledbetter <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/AudioParam.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-#include <LibWeb/WebAudio/StereoPannerNode.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(StereoPannerNode);
-
-StereoPannerNode::~StereoPannerNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<StereoPannerNode>> StereoPannerNode::create(GC::Ref<BaseAudioContext> context, StereoPannerOptions const& options)
-{
- // Create the node and allocate memory
- auto node = GC::Heap::the().allocate<StereoPannerNode>(context, options);
-
- // Default options for channel count and interpretation
- // https://webaudio.github.io/web-audio-api/#stereopannernode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count_mode = ChannelCountMode::ClampedMax;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- default_options.channel_count = 2;
- // FIXME: Set tail-time to no
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- node->queue_render_node_creation(make<Rendering::StereoPannerRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size(), node->m_pan->render_param()));
-
- return node;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-stereopannernode-stereopannernode
-WebIDL::ExceptionOr<GC::Ref<StereoPannerNode>> StereoPannerNode::create_for_constructor(GC::Ref<BaseAudioContext> context, StereoPannerOptions const& options)
-{
- return create(context, options);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelcountmode
-WebIDL::ExceptionOr<void> StereoPannerNode::set_channel_count_mode(ChannelCountMode mode)
-{
- // https://webaudio.github.io/web-audio-api/#audionode-channelcountmode-constraints
- // The channel count mode cannot be set to "max", and a NotSupportedError exception MUST be thrown for any attempt to set it to "max".
- if (mode == ChannelCountMode::Max) {
- return WebIDL::NotSupportedError::create("StereoPannerNode does not support 'max' as channelCountMode."_utf16);
- }
-
- // If the mode is valid, call the base class implementation
- return AudioNode::set_channel_count_mode(mode);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audionode-channelcount
-WebIDL::ExceptionOr<void> StereoPannerNode::set_channel_count(WebIDL::UnsignedLong channel_count)
-{
- // https://webaudio.github.io/web-audio-api/#audionode-channelcount-constraints
- // The channel count cannot be greater than two, and a NotSupportedError exception MUST be thrown for any attempt to change it to a value greater than two.
- if (channel_count > 2) {
- return WebIDL::NotSupportedError::create("StereoPannerNode does not support channel count greater than 2"_utf16);
- }
-
- return AudioNode::set_channel_count(channel_count);
-}
-
-StereoPannerNode::StereoPannerNode(GC::Ref<BaseAudioContext> context, StereoPannerOptions const& options)
- : AudioNode(context)
- , m_pan(AudioParam::create(context, this, options.pan, -1, 1, AutomationRate::ARate))
-{
-}
-
-void StereoPannerNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_pan);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/StereoPannerNode.h b/Libraries/LibWeb/WebAudio/StereoPannerNode.h
deleted file mode 100644
index 1985208588a..00000000000
--- a/Libraries/LibWeb/WebAudio/StereoPannerNode.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2025, Tim Ledbetter <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/StereoPannerNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-
-namespace Web::WebAudio {
-
-using StereoPannerOptions = Bindings::StereoPannerOptions;
-
-// https://webaudio.github.io/web-audio-api/#stereopannernode
-class StereoPannerNode : public AudioNode {
- WEB_WRAPPABLE(StereoPannerNode, AudioNode);
- GC_DECLARE_ALLOCATOR(StereoPannerNode);
-
-public:
- static constexpr size_t pan_offset() { return offsetof(StereoPannerNode, m_pan); }
- virtual ~StereoPannerNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<StereoPannerNode>> create(GC::Ref<BaseAudioContext>, StereoPannerOptions const& = {});
- static WebIDL::ExceptionOr<GC::Ref<StereoPannerNode>> create_for_constructor(GC::Ref<BaseAudioContext>, StereoPannerOptions const& = {});
-
- WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- WebIDL::ExceptionOr<void> set_channel_count_mode(ChannelCountMode) override;
- WebIDL::ExceptionOr<void> set_channel_count(WebIDL::UnsignedLong) override;
-
- GC::Ref<AudioParam const> pan() const { return m_pan; }
-
-protected:
- StereoPannerNode(GC::Ref<BaseAudioContext>, StereoPannerOptions const& = {});
- virtual void visit_edges(Cell::Visitor&) override;
-
-private:
- // https://webaudio.github.io/web-audio-api/#dom-stereopannernode-pan
- GC::Ref<AudioParam> m_pan;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/StereoPannerNode.idl b/Libraries/LibWeb/WebAudio/StereoPannerNode.idl
index 623ab72ac89..fa357ad78a6 100644
--- a/Libraries/LibWeb/WebAudio/StereoPannerNode.idl
+++ b/Libraries/LibWeb/WebAudio/StereoPannerNode.idl
@@ -4,7 +4,7 @@ dictionary StereoPannerOptions : AudioNodeOptions {
};
// https://webaudio.github.io/web-audio-api/#stereopannernode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface StereoPannerNode : AudioNode {
constructor (BaseAudioContext context, optional StereoPannerOptions options = {});
readonly attribute AudioParam pan;
diff --git a/Libraries/LibWeb/WebAudio/WaveShaperNode.cpp b/Libraries/LibWeb/WebAudio/WaveShaperNode.cpp
deleted file mode 100644
index dd9d036671f..00000000000
--- a/Libraries/LibWeb/WebAudio/WaveShaperNode.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/TypedArray.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/WebAudio/AudioArray.h>
-#include <LibWeb/WebAudio/BaseAudioContext.h>
-#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-#include <LibWeb/WebAudio/WaveShaperNode.h>
-#include <LibWeb/WebIDL/DOMException.h>
-
-namespace Web::WebAudio {
-
-GC_DEFINE_ALLOCATOR(WaveShaperNode);
-
-WaveShaperNode::WaveShaperNode(GC::Ref<BaseAudioContext> context)
- : AudioNode(context)
-{
-}
-
-WaveShaperNode::~WaveShaperNode() = default;
-
-WebIDL::ExceptionOr<GC::Ref<WaveShaperNode>> WaveShaperNode::create(GC::Ref<BaseAudioContext> context, WaveShaperOptions const& options)
-{
- // When the constructor is called with a BaseAudioContext c and an option object option, the user agent MUST
- // initialize the AudioNode this, with context and options as arguments.
- auto node = GC::Heap::the().allocate<WaveShaperNode>(context);
-
- // https://webaudio.github.io/web-audio-api/#WaveShaperNode
- AudioNodeDefaultOptions default_options;
- default_options.channel_count_mode = ChannelCountMode::Max;
- default_options.channel_interpretation = ChannelInterpretation::Speakers;
- default_options.channel_count = 2;
- // FIXME: Set tail-time to yes when the oversample attribute is "2x" or "4x".
-
- TRY(node->initialize_audio_node_options(options, default_options));
-
- node->queue_render_node_creation(make<Rendering::WaveShaperRenderNode>(node->node_id(), BaseAudioContext::render_quantum_size()));
-
- node->m_oversample = options.oversample;
-
- // Also, let [[curve set]] be an internal slot of this WaveShaperNode. Initialize this slot to false. If options is
- // given and specifies a curve, set [[curve set]] to true.
- // NB: Setting the curve attribute to the curve of options sets [[curve set]] to true.
- if (options.curve.has_value()) {
- auto& realm = HTML::relevant_realm(node->relevant_global_object());
- auto const& curve = *options.curve;
- auto array = TRY(JS::Float32Array::create(realm, curve.size()));
- overwrite_float32_array(*array, curve);
- TRY(node->set_curve(array));
- } else {
- node->send_parameters_to_render_node();
- }
-
- return node;
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-waveshapernode-waveshapernode
-WebIDL::ExceptionOr<GC::Ref<WaveShaperNode>> WaveShaperNode::create_for_constructor(GC::Ref<BaseAudioContext> context, WaveShaperOptions const& options)
-{
- return create(context, options);
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-waveshapernode-curve
-WebIDL::ExceptionOr<void> WaveShaperNode::set_curve(GC::Ptr<JS::Float32Array> new_curve)
-{
- // A InvalidStateError MUST be thrown if this attribute is set with a Float32Array that has a length less than 2.
- if (new_curve && float32_array_length(*new_curve) < 2)
- return WebIDL::InvalidStateError::create("The curve must have at least two values"_utf16);
-
- // To set the curve attribute, execute these steps:
- // 1. Let new curve be a Float32Array to be assigned to curve or null. .
- // 2. If new curve is not null and [[curve set]] is true, throw an InvalidStateError and abort these steps.
- if (new_curve && m_curve_set)
- return WebIDL::InvalidStateError::create("The curve has already been set"_utf16);
-
- // 3. If new curve is not null, set [[curve set]] to true.
- if (new_curve)
- m_curve_set = true;
-
- // 4. Assign new curve to the curve attribute.
- m_curve = new_curve;
-
- // When this attribute is set, an internal copy of the curve is created by the WaveShaperNode. Subsequent
- // modifications of the contents of the array used to set the attribute therefore have no effect.
- if (new_curve)
- m_curve_copy = adopt_ref(*new Rendering::WaveShaperCurve(copy_float32_array(*new_curve)));
- else
- m_curve_copy = nullptr;
- send_parameters_to_render_node();
- return {};
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-waveshapernode-oversample
-void WaveShaperNode::set_oversample(OverSampleType oversample)
-{
- m_oversample = oversample;
- send_parameters_to_render_node();
-}
-
-void WaveShaperNode::send_parameters_to_render_node()
-{
- context()->queue_control_message(NodeMessage { SetWaveShaperParameters {
- .node_id = node_id(),
- .curve = m_curve_copy,
- .oversample = m_oversample,
- } });
-}
-
-void WaveShaperNode::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_curve);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAudio/WaveShaperNode.h b/Libraries/LibWeb/WebAudio/WaveShaperNode.h
deleted file mode 100644
index 054065673b4..00000000000
--- a/Libraries/LibWeb/WebAudio/WaveShaperNode.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/WaveShaperNode.h>
-#include <LibWeb/WebAudio/AudioNode.h>
-#include <LibWeb/WebAudio/Rendering/AudioData.h>
-
-namespace Web::WebAudio {
-
-using OverSampleType = Bindings::OverSampleType;
-using WaveShaperOptions = Bindings::WaveShaperOptions;
-
-// https://webaudio.github.io/web-audio-api/#WaveShaperNode
-class WaveShaperNode final : public AudioNode {
- WEB_WRAPPABLE(WaveShaperNode, AudioNode);
- GC_DECLARE_ALLOCATOR(WaveShaperNode);
-
-public:
- virtual ~WaveShaperNode() override;
-
- static WebIDL::ExceptionOr<GC::Ref<WaveShaperNode>> create(GC::Ref<BaseAudioContext>, WaveShaperOptions const& = {});
- static WebIDL::ExceptionOr<GC::Ref<WaveShaperNode>> create_for_constructor(GC::Ref<BaseAudioContext>, WaveShaperOptions const& = {});
-
- WebIDL::UnsignedLong number_of_inputs() override { return 1; }
- WebIDL::UnsignedLong number_of_outputs() override { return 1; }
-
- GC::Ptr<JS::Float32Array> curve() const { return m_curve; }
- WebIDL::ExceptionOr<void> set_curve(GC::Ptr<JS::Float32Array>);
-
- OverSampleType oversample() const { return m_oversample; }
- void set_oversample(OverSampleType);
-
-private:
- explicit WaveShaperNode(GC::Ref<BaseAudioContext>);
-
- virtual void visit_edges(Cell::Visitor&) override;
-
- void send_parameters_to_render_node();
-
- // https://webaudio.github.io/web-audio-api/#dom-waveshapernode-curve
- GC::Ptr<JS::Float32Array> m_curve;
- // When this attribute is set, an internal copy of the curve is created by the WaveShaperNode.
- RefPtr<Rendering::WaveShaperCurve> m_curve_copy;
-
- // https://webaudio.github.io/web-audio-api/#dom-waveshapernode-curve-set-slot
- bool m_curve_set { false };
-
- // https://webaudio.github.io/web-audio-api/#dom-waveshapernode-oversample
- OverSampleType m_oversample { OverSampleType::None };
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/WaveShaperNode.idl b/Libraries/LibWeb/WebAudio/WaveShaperNode.idl
index 2a83236d7f4..f9d4bbaea96 100644
--- a/Libraries/LibWeb/WebAudio/WaveShaperNode.idl
+++ b/Libraries/LibWeb/WebAudio/WaveShaperNode.idl
@@ -12,7 +12,7 @@ dictionary WaveShaperOptions : AudioNodeOptions {
};
// https://webaudio.github.io/web-audio-api/#WaveShaperNode
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface WaveShaperNode : AudioNode {
constructor (BaseAudioContext context, optional WaveShaperOptions options = {});
attribute Float32Array? curve;