Skip to content

Truly independent web browser

LibWeb: Port the WebAudio render graph and main nodes to Rust

Shannon Booth53ac80e9d535
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index a5376b7704c..b21d7e34d75 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -961,6 +961,7 @@ set(SOURCES
WebAudio/PannerNode.cpp
WebAudio/PeriodicWave.cpp
WebAudio/Rendering/AnalyserRenderNode.cpp
+ WebAudio/Rendering/AudioData.cpp
WebAudio/Rendering/AudioBus.cpp
WebAudio/Rendering/AudioWorkletPipe.cpp
WebAudio/Rendering/AudioWorkletRenderNode.cpp
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index 7d7ce14e032..67b1f8c6901 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -2476,6 +2476,14 @@ fn main() -> Result<(), Box<dyn Error>> {
"ConvolverDelayLine",
"AudioParamTimeline",
"RenderAudioParam",
+ "RenderGraph",
+ "NodeHandle",
+ "AudioBufferContents",
+ "PeriodicWaveData",
+ "WaveShaperCurve",
+ "ControlMessage",
+ "ControlMessageQueue",
+ "ControlMessages",
] {
web_audio_config.export.rename.insert(name.into(), "void".into());
web_audio_config.export.exclude.push(name.into());
@@ -2496,6 +2504,12 @@ fn main() -> Result<(), Box<dyn Error>> {
manifest_dir.join("src/web_audio/rendering/audio_bus.rs"),
manifest_dir.join("src/web_audio/rendering/convolver_kernel.rs"),
manifest_dir.join("src/web_audio/rendering/render_node.rs"),
+ manifest_dir.join("src/web_audio/rendering/render_graph.rs"),
+ manifest_dir.join("src/web_audio/rendering/render_nodes.rs"),
+ manifest_dir.join("src/web_audio/rendering/node_message.rs"),
+ manifest_dir.join("src/web_audio/rendering/audio_data.rs"),
+ manifest_dir.join("src/web_audio/control_message.rs"),
+ manifest_dir.join("src/web_audio/control_message_queue.rs"),
],
&out_dir,
Path::new("WebAudio/RustFFI.h"),
diff --git a/Libraries/LibWeb/Rust/src/web_audio/control_message.rs b/Libraries/LibWeb/Rust/src/web_audio/control_message.rs
new file mode 100644
index 00000000000..840bb6e7ae8
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/web_audio/control_message.rs
@@ -0,0 +1,306 @@
+/*
+ * Copyright (c) 2025-2026, Ben Eidson <[email protected]>
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::rendering::node_message::NodeMessage;
+use super::rendering::render_node::{
+ ChannelCountMode, ChannelInterpretation, NodeHandle, OutgoingNodeConnection, OutgoingParamConnection,
+};
+
+// Transfers a freshly constructed render node to the rendering thread.
+pub struct AddNode {
+ pub node: Box<NodeHandle>,
+}
+
+// Retires the render node of an AudioNode that is no longer alive on the control thread. The rendering loop only
+// considers "the set of all nodes created by this BaseAudioContext, and still alive", so a node that was garbage
+// collected must leave the render graph as well.
+// https://webaudio.github.io/web-audio-api/#rendering-loop
+pub struct RemoveNode {
+ pub node_id: u64,
+}
+
+// Replaces the source node's outgoing connections with a full snapshot taken after a connect() or disconnect() call.
+pub struct ReplaceConnections {
+ pub source: u64,
+ pub node_connections: Vec<OutgoingNodeConnection>,
+ pub param_connections: Vec<OutgoingParamConnection>,
+}
+
+pub struct SetChannelConfig {
+ pub node_id: u64,
+ pub channel_count: usize,
+ pub channel_count_mode: ChannelCountMode,
+ pub channel_interpretation: ChannelInterpretation,
+}
+
+// https://webaudio.github.io/web-audio-api/#control-message
+pub enum ControlMessage {
+ AddNode(AddNode),
+ RemoveNode(RemoveNode),
+ ReplaceConnections(ReplaceConnections),
+ SetChannelConfig(SetChannelConfig),
+ NodeMessage(NodeMessage),
+}
+
+use super::rendering::audio_data::{AudioBufferContents, PeriodicWaveData, WaveShaperCurve};
+use super::rendering::biquad_coefficients::BiquadFilterType;
+use super::rendering::convolver_kernel::{ConvolverDelayLine, ConvolverKernel};
+use super::rendering::node_message::*;
+use super::rendering::render_node::RenderAudioParam;
+use ak::Span;
+
+pub struct ControlMessages {
+ pub messages: Vec<ControlMessage>,
+}
+
+use std::ffi::c_void;
+use std::sync::Arc;
+
+pub(crate) unsafe fn clone_arc<T>(pointer: *const T) -> Arc<T> {
+ unsafe {
+ Arc::increment_strong_count(pointer);
+ Arc::from_raw(pointer)
+ }
+}
+
+unsafe fn clone_optional_arc<T>(pointer: *const T) -> Option<Arc<T>> {
+ if pointer.is_null() {
+ None
+ } else {
+ Some(unsafe { clone_arc(pointer) })
+ }
+}
+
+#[repr(C)]
+pub struct FfiOutgoingParamConnection {
+ pub destination: *const RenderAudioParam,
+ pub output_index: usize,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct FfiSharedCppObject {
+ pub pointer: *mut c_void,
+ pub retain: unsafe extern "C" fn(*mut c_void),
+ pub release: unsafe extern "C" fn(*mut c_void),
+}
+
+impl FfiSharedCppObject {
+ unsafe fn acquire(self) -> Option<SharedCppObject> {
+ if self.pointer.is_null() {
+ return None;
+ }
+ unsafe {
+ (self.retain)(self.pointer);
+ }
+ Some(SharedCppObject {
+ pointer: self.pointer,
+ retain: self.retain,
+ release: self.release,
+ })
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_message_add_node(node: *mut NodeHandle) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::AddNode(AddNode {
+ node: unsafe { Box::from_raw(node) },
+ })))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_message_remove_node(node_id: u64) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::RemoveNode(RemoveNode { node_id })))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_message_replace_connections(
+ source: u64,
+ node_connections: Span<'_, OutgoingNodeConnection>,
+ param_connections: Span<'_, FfiOutgoingParamConnection>,
+) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::ReplaceConnections(ReplaceConnections {
+ source,
+ node_connections: node_connections.as_slice().to_vec(),
+ param_connections: param_connections
+ .as_slice()
+ .iter()
+ .map(|connection| OutgoingParamConnection {
+ destination: unsafe { clone_arc(connection.destination) },
+ output_index: connection.output_index,
+ })
+ .collect(),
+ })))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_message_set_channel_config(
+ node_id: u64,
+ channel_count: usize,
+ channel_count_mode: ChannelCountMode,
+ channel_interpretation: ChannelInterpretation,
+) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::SetChannelConfig(SetChannelConfig {
+ node_id,
+ channel_count,
+ channel_count_mode,
+ channel_interpretation,
+ })))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_message_start_source(node_id: u64, when: f64) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::NodeMessage(NodeMessage::StartSource(
+ StartSource { node_id, when },
+ ))))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_message_stop_source(node_id: u64, when: f64) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::NodeMessage(NodeMessage::StopSource(
+ StopSource { node_id, when },
+ ))))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_message_start_buffer_source(
+ node_id: u64,
+ when: f64,
+ offset: f64,
+ has_duration: bool,
+ duration: f64,
+ buffer: *const AudioBufferContents,
+) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::NodeMessage(NodeMessage::StartBufferSource(
+ StartBufferSource {
+ node_id,
+ when,
+ offset,
+ duration: has_duration.then_some(duration),
+ buffer: unsafe { clone_optional_arc(buffer) },
+ },
+ ))))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_message_set_buffer_source_parameters(
+ node_id: u64,
+ r#loop: bool,
+ loop_start: f64,
+ loop_end: f64,
+ buffer: *const AudioBufferContents,
+ update_buffer: bool,
+) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::NodeMessage(
+ NodeMessage::SetBufferSourceParameters(SetBufferSourceParameters {
+ node_id,
+ r#loop,
+ loop_start,
+ loop_end,
+ buffer: unsafe { clone_optional_arc(buffer) },
+ update_buffer,
+ }),
+ )))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_message_set_oscillator_waveform(
+ node_id: u64,
+ r#type: OscillatorType,
+ periodic_wave: *const PeriodicWaveData,
+) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::NodeMessage(
+ NodeMessage::SetOscillatorWaveform(SetOscillatorWaveform {
+ node_id,
+ r#type,
+ periodic_wave: unsafe { clone_optional_arc(periodic_wave) },
+ }),
+ )))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_message_set_biquad_filter_type(
+ node_id: u64,
+ r#type: BiquadFilterType,
+) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::NodeMessage(NodeMessage::SetBiquadFilterType(
+ SetBiquadFilterType { node_id, r#type },
+ ))))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_message_set_convolver_kernel(
+ node_id: u64,
+ kernel: *const ConvolverKernel,
+ delay_line: *const ConvolverDelayLine,
+) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::NodeMessage(NodeMessage::SetConvolverKernel(
+ SetConvolverKernel {
+ node_id,
+ kernel: unsafe { clone_optional_arc(kernel) },
+ delay_line: unsafe { clone_optional_arc(delay_line) },
+ },
+ ))))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_message_set_panner_parameters(
+ node_id: u64,
+ panning_model: PanningModelType,
+ distance_model: DistanceModelType,
+ ref_distance: f64,
+ max_distance: f64,
+ rolloff_factor: f64,
+ cone_inner_angle: f64,
+ cone_outer_angle: f64,
+ cone_outer_gain: f64,
+) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::NodeMessage(NodeMessage::SetPannerParameters(
+ SetPannerParameters {
+ node_id,
+ panning_model,
+ distance_model,
+ ref_distance,
+ max_distance,
+ rolloff_factor,
+ cone_inner_angle,
+ cone_outer_angle,
+ cone_outer_gain,
+ },
+ ))))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_message_set_wave_shaper_parameters(
+ node_id: u64,
+ curve: *const WaveShaperCurve,
+ oversample: OverSampleType,
+) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::NodeMessage(
+ NodeMessage::SetWaveShaperParameters(SetWaveShaperParameters {
+ node_id,
+ curve: unsafe { clone_optional_arc(curve) },
+ oversample,
+ }),
+ )))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_message_set_media_stream_source_ring(
+ node_id: u64,
+ ring: FfiSharedCppObject,
+ channel_count: u32,
+) -> *mut ControlMessage {
+ Box::into_raw(Box::new(ControlMessage::NodeMessage(
+ NodeMessage::SetMediaStreamSourceRing(SetMediaStreamSourceRing {
+ node_id,
+ ring: unsafe { ring.acquire() },
+ channel_count,
+ }),
+ )))
+}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/control_message_queue.rs b/Libraries/LibWeb/Rust/src/web_audio/control_message_queue.rs
new file mode 100644
index 00000000000..8b45cacd897
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/web_audio/control_message_queue.rs
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2025, Ben Eidson <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::sync::Mutex;
+
+use super::control_message::{ControlMessage, ControlMessages};
+
+// https://webaudio.github.io/web-audio-api/#control-message-queue
+#[derive(Default)]
+pub struct ControlMessageQueue {
+ messages: Mutex<Vec<ControlMessage>>,
+}
+
+impl ControlMessageQueue {
+ // Called by the control thread.
+ pub fn enqueue(&self, message: ControlMessage) {
+ let mut messages = self.messages.lock().unwrap();
+ messages.push(message);
+ }
+
+ // Called by the rendering thread.
+ pub fn drain(&self) -> Vec<ControlMessage> {
+ let mut messages = self.messages.lock().unwrap();
+ std::mem::take(&mut *messages)
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_control_queue_create() -> *mut ControlMessageQueue {
+ Box::into_raw(Box::new(ControlMessageQueue::default()))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_control_queue_destroy(queue: *mut ControlMessageQueue) {
+ drop(unsafe { Box::from_raw(queue) });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_control_queue_enqueue(
+ queue: *const ControlMessageQueue,
+ message: *mut ControlMessage,
+) {
+ unsafe { &*queue }.enqueue(*unsafe { Box::from_raw(message) });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_control_queue_drain(
+ queue: *const ControlMessageQueue,
+) -> *mut ControlMessages {
+ Box::into_raw(Box::new(ControlMessages {
+ messages: unsafe { &*queue }.drain(),
+ }))
+}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/mod.rs b/Libraries/LibWeb/Rust/src/web_audio/mod.rs
index fa6467f7e96..43b9b1e62df 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/mod.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/mod.rs
@@ -6,4 +6,6 @@
*/
pub mod audio_param_timeline;
+pub mod control_message;
+pub mod control_message_queue;
pub mod rendering;
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs
index 4f772a8f974..98f23ed5865 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs
@@ -45,6 +45,13 @@ impl AudioBus {
&mut self.channels[index]
}
+ pub(crate) unsafe fn channel_pointer(bus: *mut Self, index: usize) -> (*mut f32, usize) {
+ let channels = unsafe { &raw mut (*bus).channels };
+ assert!(index < unsafe { (*channels).len() });
+ let channel = unsafe { (*channels).as_mut_ptr().add(index) };
+ unsafe { ((*channel).as_mut_ptr(), (*channel).len()) }
+ }
+
pub fn zero(&mut self) {
for channel in &mut self.channels {
channel.fill(0.);
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_data.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_data.rs
new file mode 100644
index 00000000000..9fc837c1c52
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_data.rs
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::sync::Arc;
+
+use ak::Span;
+
+pub struct AudioBufferContents {
+ pub channels: Vec<Vec<f32>>,
+ pub sample_rate: f32,
+}
+
+impl AudioBufferContents {
+ pub fn length(&self) -> usize {
+ self.channels.first().map_or(0, Vec::len)
+ }
+
+ pub fn duration(&self) -> f64 {
+ self.length() as f64 / f64::from(self.sample_rate)
+ }
+}
+
+// An immutable snapshot of a PeriodicWave's Fourier coefficients.
+// https://webaudio.github.io/web-audio-api/#PeriodicWave
+pub struct PeriodicWaveData {
+ pub real: Vec<f32>,
+ pub imag: Vec<f32>,
+ pub normalize: bool,
+}
+
+// An immutable copy of a WaveShaperNode's curve.
+// https://webaudio.github.io/web-audio-api/#dom-waveshapernode-curve
+pub struct WaveShaperCurve {
+ pub values: Vec<f32>,
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_buffer_contents_create(
+ channels: Span<'_, Span<'_, f32>>,
+ sample_rate: f32,
+) -> *const AudioBufferContents {
+ Arc::into_raw(Arc::new(AudioBufferContents {
+ channels: channels
+ .as_slice()
+ .iter()
+ .map(|channel| channel.as_slice().to_vec())
+ .collect(),
+ sample_rate,
+ }))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_buffer_contents_destroy(contents: *const AudioBufferContents) {
+ drop(unsafe { Arc::from_raw(contents) });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_buffer_contents_channel(
+ contents: *const AudioBufferContents,
+ channel: usize,
+ output: *mut Span<'static, f32>,
+) {
+ unsafe {
+ *output = Span::new(&(&*contents).channels[channel]);
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_periodic_wave_data_create(
+ real: Span<'_, f32>,
+ imag: Span<'_, f32>,
+ normalize: bool,
+) -> *const PeriodicWaveData {
+ Arc::into_raw(Arc::new(PeriodicWaveData {
+ real: real.as_slice().to_vec(),
+ imag: imag.as_slice().to_vec(),
+ normalize,
+ }))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_periodic_wave_data_destroy(data: *const PeriodicWaveData) {
+ drop(unsafe { Arc::from_raw(data) });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_periodic_wave_data_real(
+ data: *const PeriodicWaveData,
+ output: *mut Span<'static, f32>,
+) {
+ unsafe {
+ *output = Span::new(&(&*data).real);
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_periodic_wave_data_imag(
+ data: *const PeriodicWaveData,
+ output: *mut Span<'static, f32>,
+) {
+ unsafe {
+ *output = Span::new(&(&*data).imag);
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_wave_shaper_curve_create(values: Span<'_, f32>) -> *const WaveShaperCurve {
+ Arc::into_raw(Arc::new(WaveShaperCurve {
+ values: values.as_slice().to_vec(),
+ }))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_wave_shaper_curve_destroy(curve: *const WaveShaperCurve) {
+ drop(unsafe { Arc::from_raw(curve) });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_wave_shaper_curve_values(
+ curve: *const WaveShaperCurve,
+ output: *mut Span<'static, f32>,
+) {
+ unsafe {
+ *output = Span::new(&(&*curve).values);
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/convolver_kernel.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/convolver_kernel.rs
index e4f656b66ae..6a96ddd42c2 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/convolver_kernel.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/convolver_kernel.rs
@@ -7,6 +7,7 @@
#![allow(clippy::needless_range_loop)]
+use std::cell::UnsafeCell;
use std::sync::Arc;
use ak::{Span, SpanMut};
@@ -185,10 +186,13 @@ impl ConvolverKernel {
// control thread and handed over together with the kernel, keeping allocation off the rendering thread.
pub struct ConvolverDelayLine {
length: usize,
- real: [Vec<f32>; Self::MAX_CHANNEL_COUNT],
- imag: [Vec<f32>; Self::MAX_CHANNEL_COUNT],
+ real: [UnsafeCell<Vec<f32>>; Self::MAX_CHANNEL_COUNT],
+ imag: [UnsafeCell<Vec<f32>>; Self::MAX_CHANNEL_COUNT],
}
+// SAFETY: Delay-line samples are only accessed by the rendering thread after transfer.
+unsafe impl Send for ConvolverDelayLine {}
+unsafe impl Sync for ConvolverDelayLine {}
impl ConvolverDelayLine {
// The input to a ConvolverNode is mono or stereo and cannot be increased.
// https://webaudio.github.io/web-audio-api/#ConvolverNode
@@ -196,21 +200,31 @@ impl ConvolverDelayLine {
pub fn create(kernel: &ConvolverKernel) -> Self {
let length = kernel.partition_count() + 1;
- let real = std::array::from_fn(|_| vec![0.; length * kernel.bin_count()]);
- let imag = std::array::from_fn(|_| vec![0.; length * kernel.bin_count()]);
+ let real = std::array::from_fn(|_| UnsafeCell::new(vec![0.; length * kernel.bin_count()]));
+ let imag = std::array::from_fn(|_| UnsafeCell::new(vec![0.; length * kernel.bin_count()]));
Self { length, real, imag }
}
+ #[allow(clippy::mut_from_ref)]
+ pub(crate) unsafe fn real_shared(&self, channel: usize) -> &mut [f32] {
+ unsafe { &mut *self.real[channel].get() }
+ }
+
+ #[allow(clippy::mut_from_ref)]
+ pub(crate) unsafe fn imag_shared(&self, channel: usize) -> &mut [f32] {
+ unsafe { &mut *self.imag[channel].get() }
+ }
+
pub fn length(&self) -> usize {
self.length
}
pub fn real(&mut self, channel: usize) -> &mut [f32] {
- &mut self.real[channel]
+ self.real[channel].get_mut()
}
pub fn imag(&mut self, channel: usize) -> &mut [f32] {
- &mut self.imag[channel]
+ self.imag[channel].get_mut()
}
}
@@ -286,13 +300,13 @@ pub(crate) unsafe extern "C" fn web_audio_convolver_kernel_partition_imag(
#[unsafe(no_mangle)]
pub(crate) unsafe extern "C" fn web_audio_convolver_delay_line_create(
kernel: *const ConvolverKernel,
-) -> *mut ConvolverDelayLine {
- Box::into_raw(Box::new(ConvolverDelayLine::create(unsafe { &*kernel })))
+) -> *const ConvolverDelayLine {
+ Arc::into_raw(Arc::new(ConvolverDelayLine::create(unsafe { &*kernel })))
}
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_convolver_delay_line_destroy(delay_line: *mut ConvolverDelayLine) {
- drop(unsafe { Box::from_raw(delay_line) });
+pub(crate) unsafe extern "C" fn web_audio_convolver_delay_line_destroy(delay_line: *const ConvolverDelayLine) {
+ drop(unsafe { Arc::from_raw(delay_line) });
}
#[unsafe(no_mangle)]
@@ -302,22 +316,22 @@ pub(crate) unsafe extern "C" fn web_audio_convolver_delay_line_length(delay_line
#[unsafe(no_mangle)]
pub(crate) unsafe extern "C" fn web_audio_convolver_delay_line_real(
- delay_line: *mut ConvolverDelayLine,
+ delay_line: *const ConvolverDelayLine,
channel: usize,
output: *mut SpanMut<'static, f32>,
) {
unsafe {
- *output = SpanMut::new((&mut *delay_line).real(channel));
+ *output = SpanMut::new((&*delay_line).real_shared(channel));
}
}
#[unsafe(no_mangle)]
pub(crate) unsafe extern "C" fn web_audio_convolver_delay_line_imag(
- delay_line: *mut ConvolverDelayLine,
+ delay_line: *const ConvolverDelayLine,
channel: usize,
output: *mut SpanMut<'static, f32>,
) {
unsafe {
- *output = SpanMut::new((&mut *delay_line).imag(channel));
+ *output = SpanMut::new((&*delay_line).imag_shared(channel));
}
}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs
index 3c2bf13f217..e5a70daef02 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs
@@ -9,7 +9,11 @@ pub mod audio_bus;
pub mod biquad_coefficients;
pub mod convolver_kernel;
pub mod fft;
+pub mod node_message;
+pub mod render_graph;
pub mod render_node;
+pub mod audio_data;
+pub mod render_nodes;
#[cfg(test)]
mod tests;
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/node_message.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/node_message.rs
new file mode 100644
index 00000000000..18e6bc2aaee
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/node_message.rs
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2025-2026, Ben Eidson <[email protected]>
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::ffi::c_void;
+use std::sync::Arc;
+
+use super::biquad_coefficients::BiquadFilterType;
+use super::convolver_kernel::{ConvolverDelayLine, ConvolverKernel};
+
+pub use super::audio_data::{AudioBufferContents, PeriodicWaveData, WaveShaperCurve};
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum OscillatorType {
+ Sine,
+ Square,
+ Sawtooth,
+ Triangle,
+ Custom,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum DistanceModelType {
+ Linear,
+ Inverse,
+ Exponential,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum PanningModelType {
+ Equalpower,
+ HRTF,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum OverSampleType {
+ None,
+ _2x,
+ _4x,
+}
+
+pub struct StartSource {
+ pub node_id: u64,
+ pub when: f64,
+}
+
+pub struct StopSource {
+ pub node_id: u64,
+ pub when: f64,
+}
+
+// Starts an AudioBufferSourceNode, transferring the acquired buffer contents along with the playback range.
+pub struct StartBufferSource {
+ pub node_id: u64,
+ pub when: f64,
+ pub offset: f64,
+ pub duration: Option<f64>,
+ pub buffer: Option<Arc<AudioBufferContents>>,
+}
+
+// Updates an AudioBufferSourceNode's loop parameters, and its buffer if it was assigned after the node started.
+pub struct SetBufferSourceParameters {
+ pub node_id: u64,
+ pub r#loop: bool,
+ pub loop_start: f64,
+ pub loop_end: f64,
+ pub buffer: Option<Arc<AudioBufferContents>>,
+ pub update_buffer: bool,
+}
+
+pub struct SetOscillatorWaveform {
+ pub node_id: u64,
+ pub r#type: OscillatorType,
+ pub periodic_wave: Option<Arc<PeriodicWaveData>>,
+}
+
+pub struct SetBiquadFilterType {
+ pub node_id: u64,
+ pub r#type: BiquadFilterType,
+}
+
+pub struct SetConvolverKernel {
+ pub node_id: u64,
+ pub kernel: Option<Arc<ConvolverKernel>>,
+ pub delay_line: Option<Arc<ConvolverDelayLine>>,
+}
+
+#[derive(Clone, Copy)]
+pub struct SetPannerParameters {
+ pub node_id: u64,
+ 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,
+}
+
+impl Default for SetPannerParameters {
+ fn default() -> Self {
+ Self {
+ node_id: 0,
+ panning_model: PanningModelType::Equalpower,
+ distance_model: DistanceModelType::Inverse,
+ ref_distance: 1.,
+ max_distance: 10000.,
+ rolloff_factor: 1.,
+ cone_inner_angle: 360.,
+ cone_outer_angle: 360.,
+ cone_outer_gain: 0.,
+ }
+ }
+}
+
+pub struct SetWaveShaperParameters {
+ pub node_id: u64,
+ pub curve: Option<Arc<WaveShaperCurve>>,
+ pub oversample: OverSampleType,
+}
+
+// Attaches the ring buffer that carries a MediaStreamTrack's audio into a
+// MediaStreamAudioSourceNode's render node. Shipped as a message rather than a constructor
+// argument so the ring can be replaced without rebuilding the render node.
+pub struct SetMediaStreamSourceRing {
+ pub node_id: u64,
+ pub ring: Option<SharedCppObject>,
+ pub channel_count: u32,
+}
+
+pub struct SharedCppObject {
+ pub pointer: *mut c_void,
+ pub retain: unsafe extern "C" fn(*mut c_void),
+ pub release: unsafe extern "C" fn(*mut c_void),
+}
+
+// SAFETY: These handles own references to C++ objects whose reference counts are atomic.
+unsafe impl Send for SharedCppObject {}
+unsafe impl Sync for SharedCppObject {}
+impl Clone for SharedCppObject {
+ fn clone(&self) -> Self {
+ unsafe {
+ (self.retain)(self.pointer);
+ }
+ Self {
+ pointer: self.pointer,
+ retain: self.retain,
+ release: self.release,
+ }
+ }
+}
+
+impl Drop for SharedCppObject {
+ fn drop(&mut self) {
+ unsafe {
+ (self.release)(self.pointer);
+ }
+ }
+}
+
+// A control message that updates the state of a single render node.
+pub enum NodeMessage {
+ SetBiquadFilterType(SetBiquadFilterType),
+ SetBufferSourceParameters(SetBufferSourceParameters),
+ SetConvolverKernel(SetConvolverKernel),
+ SetMediaStreamSourceRing(SetMediaStreamSourceRing),
+ SetOscillatorWaveform(SetOscillatorWaveform),
+ SetPannerParameters(SetPannerParameters),
+ SetWaveShaperParameters(SetWaveShaperParameters),
+ StartBufferSource(StartBufferSource),
+ StartSource(StartSource),
+ StopSource(StopSource),
+}
+
+pub fn node_message_target(message: &NodeMessage) -> u64 {
+ match message {
+ NodeMessage::SetBiquadFilterType(value) => value.node_id,
+ NodeMessage::SetBufferSourceParameters(value) => value.node_id,
+ NodeMessage::SetConvolverKernel(value) => value.node_id,
+ NodeMessage::SetMediaStreamSourceRing(value) => value.node_id,
+ NodeMessage::SetOscillatorWaveform(value) => value.node_id,
+ NodeMessage::SetPannerParameters(value) => value.node_id,
+ NodeMessage::SetWaveShaperParameters(value) => value.node_id,
+ NodeMessage::StartBufferSource(value) => value.node_id,
+ NodeMessage::StartSource(value) => value.node_id,
+ NodeMessage::StopSource(value) => value.node_id,
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_graph.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_graph.rs
new file mode 100644
index 00000000000..3cda4712a8c
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_graph.rs
@@ -0,0 +1,442 @@
+/*
+ * Copyright (c) 2018-2025, Andreas Kling <[email protected]>
+ * Copyright (c) 2023, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::Cell;
+
+use super::audio_bus::AudioBus;
+use super::node_message::node_message_target;
+use super::render_node::{NodeHandle, RenderContext};
+use crate::web_audio::control_message::{ControlMessage, ControlMessages};
+
+// The rendering thread's mirror of the audio graph. Nodes and connections are added and updated exclusively through
+// control messages, which are applied at the start of each render quantum.
+// https://webaudio.github.io/web-audio-api/#rendering-loop
+pub struct RenderGraph {
+ nodes: NodeMap,
+ destination_id: u64,
+ current_quantum: Cell<u64>,
+ incoming_connections_dirty: Cell<bool>,
+}
+
+impl Default for RenderGraph {
+ fn default() -> Self {
+ Self {
+ nodes: NodeMap::default(),
+ destination_id: 0,
+ current_quantum: Cell::new(0),
+ incoming_connections_dirty: Cell::new(false),
+ }
+ }
+}
+
+impl RenderGraph {
+ pub fn apply_control_messages(&mut self, messages: Vec<ControlMessage>) {
+ for message in messages {
+ match message {
+ ControlMessage::AddNode(add_node) => {
+ let node_id = add_node.node.data().node_id;
+ self.nodes.insert(node_id, add_node.node);
+ self.incoming_connections_dirty.set(true);
+ }
+ ControlMessage::RemoveNode(remove_node) => {
+ if self.nodes.remove(&remove_node.node_id).is_some() {
+ self.incoming_connections_dirty.set(true);
+ }
+ }
+ ControlMessage::ReplaceConnections(replace_connections) => {
+ if let Some(source_node) = self.node(replace_connections.source) {
+ unsafe {
+ source_node.data().set_outgoing_connections(
+ replace_connections.node_connections,
+ replace_connections.param_connections,
+ );
+ }
+ self.incoming_connections_dirty.set(true);
+ }
+ }
+ ControlMessage::SetChannelConfig(config) => {
+ if let Some(target_node) = self.node(config.node_id) {
+ target_node.data().channel_count.set(config.channel_count);
+ target_node.data().channel_count_mode.set(config.channel_count_mode);
+ target_node
+ .data()
+ .channel_interpretation
+ .set(config.channel_interpretation);
+ }
+ }
+ ControlMessage::NodeMessage(node_message) => {
+ if let Some(target_node) = self.node(node_message_target(&node_message)) {
+ unsafe {
+ target_node.node.handle_message(&node_message);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Renders a single quantum by pulling the destination node and any active source nodes.
+ pub fn render_quantum(&self, context: &RenderContext) {
+ self.current_quantum.set(self.current_quantum.get().wrapping_add(1));
+ if self.incoming_connections_dirty.get() {
+ unsafe {
+ self.rebuild_incoming_connections();
+ }
+ self.incoming_connections_dirty.set(false);
+ }
+
+ // Pull the destination first so the main graph is processed in dependency order; then process any remaining nodes
+ // so unconnected sources still advance their playback state and report ended events.
+ if let Some(destination_node) = self.destination() {
+ self.pull_output(destination_node.data().node_id, 0, context);
+ }
+ for (&node_id, graph_node) in self.nodes.iter() {
+ if graph_node.data().output_count() > 0 {
+ self.pull_output(node_id, 0, context);
+ }
+ }
+ }
+
+ // Returns the source node's output bus, processing the node first if it has not been processed in this quantum.
+ // Re-entrant pulls caused by cycles return the output rendered in the previous quantum.
+ pub fn pull_output(&self, source: u64, output_index: usize, context: &RenderContext) -> *mut AudioBus {
+ let Some(source_node) = self.node(source) else {
+ return std::ptr::null_mut();
+ };
+ let data = source_node.data();
+ if output_index >= data.output_count() {
+ return std::ptr::null_mut();
+ }
+
+ if data.processed_quantum.get() != self.current_quantum.get() {
+ // A re-entrant pull means this node is part of a cycle; its output bus still holds the previous quantum's
+ // samples, which effectively inserts one render quantum of delay into the cycle.
+ if data.is_processing.get() {
+ return unsafe { data.output(output_index) };
+ }
+
+ data.is_processing.set(true);
+ unsafe {
+ source_node.node.process(self, context);
+ }
+ data.is_processing.set(false);
+ data.processed_quantum.set(self.current_quantum.get());
+ }
+ unsafe { data.output(output_index) }
+ }
+
+ pub fn node(&self, node_id: u64) -> Option<&NodeHandle> {
+ self.nodes.get(&node_id)
+ }
+
+ pub fn set_destination(&mut self, node_id: u64) {
+ self.destination_id = node_id;
+ }
+
+ pub fn destination(&self) -> Option<&NodeHandle> {
+ self.node(self.destination_id)
+ }
+
+ // Drains the set of nodes that stopped playing since the last call and retires their permanently silent render nodes.
+ pub fn take_ended_nodes(&mut self) -> Vec<u64> {
+ let mut ended_nodes = Vec::new();
+ for (&node_id, graph_node) in self.nodes.iter() {
+ if unsafe { graph_node.node.take_ended_notification() } {
+ ended_nodes.push(node_id);
+ }
+ }
+ for node_id in &ended_nodes {
+ self.nodes.remove(node_id);
+ }
+ if !ended_nodes.is_empty() {
+ self.incoming_connections_dirty.set(true);
+ }
+ ended_nodes
+ }
+
+ unsafe fn rebuild_incoming_connections(&self) {
+ for graph_node in self.nodes.values() {
+ let data = graph_node.data();
+ for input_index in 0..data.input_count() {
+ (unsafe { &mut *data.input_connections.get() })[input_index].clear();
+ }
+ graph_node.node.for_each_param(&mut |param| unsafe {
+ param.clear_inputs();
+ });
+ }
+ for (&node_id, graph_node) in self.nodes.iter() {
+ let data = graph_node.data();
+ for connection in unsafe { &*data.outgoing_node_connections.get() } {
+ if let Some(destination_node) = self.node(connection.destination)
+ && connection.input_index < destination_node.data().input_count()
+ {
+ (unsafe { &mut *destination_node.data().input_connections.get() })[connection.input_index].push(
+ super::render_node::Connection {
+ source: node_id,
+ output_index: connection.output_index,
+ },
+ );
+ }
+ }
+ for connection in unsafe { &*data.outgoing_param_connections.get() } {
+ unsafe {
+ connection.destination.add_input(node_id, connection.output_index);
+ }
+ }
+ }
+ }
+}
+
+#[derive(Default)]
+struct NodeMap {
+ buckets: Vec<Option<(u64, Box<NodeHandle>)>>,
+ size: usize,
+}
+
+impl NodeMap {
+ fn hash(mut key: u64) -> usize {
+ key ^= key >> 33;
+ key = key.wrapping_mul(0xff51afd7ed558ccd);
+ key ^= key >> 33;
+ key = key.wrapping_mul(0xc4ceb9fe1a85ec53);
+ key ^= key >> 33;
+ key as u32 as usize
+ }
+
+ fn probe_length(&self, key: u64, index: usize) -> usize {
+ index.wrapping_sub(Self::hash(key)) & (self.buckets.len() - 1)
+ }
+
+ fn insert(&mut self, key: u64, value: Box<NodeHandle>) {
+ if (self.size + 1) * 100 >= self.buckets.len() * 70 {
+ let capacity = (self.buckets.len() * 2).max(8);
+ let old_buckets = std::mem::replace(&mut self.buckets, (0..capacity).map(|_| None).collect());
+ self.size = 0;
+ for (key, value) in old_buckets.into_iter().flatten() {
+ self.write_value(key, value);
+ }
+ }
+ self.write_value(key, value);
+ }
+
+ fn write_value(&mut self, mut key: u64, mut value: Box<NodeHandle>) {
+ let mask = self.buckets.len() - 1;
+ let mut index = Self::hash(key) & mask;
+ let mut probe_length = 0;
+ loop {
+ let Some((target_key, _)) = &self.buckets[index] else {
+ self.buckets[index] = Some((key, value));
+ self.size += 1;
+ return;
+ };
+ if *target_key == key {
+ self.buckets[index] = Some((key, value));
+ return;
+ }
+ let target_probe_length = self.probe_length(*target_key, index);
+ if probe_length > target_probe_length {
+ let displaced = self.buckets[index].replace((key, value)).unwrap();
+ (key, value) = displaced;
+ probe_length = target_probe_length;
+ }
+ index = (index + 1) & mask;
+ probe_length += 1;
+ }
+ }
+
+ fn index(&self, key: u64) -> Option<usize> {
+ if self.size == 0 {
+ return None;
+ }
+ let mask = self.buckets.len() - 1;
+ let mut index = Self::hash(key) & mask;
+ let mut probe_length = 0;
+ loop {
+ let (target_key, _) = self.buckets[index].as_ref()?;
+ if *target_key == key {
+ return Some(index);
+ }
+ if probe_length > self.probe_length(*target_key, index) {
+ return None;
+ }
+ index = (index + 1) & mask;
+ probe_length += 1;
+ }
+ }
+
+ fn get(&self, key: &u64) -> Option<&NodeHandle> {
+ self.index(*key)
+ .map(|index| self.buckets[index].as_ref().unwrap().1.as_ref())
+ }
+
+ fn remove(&mut self, key: &u64) -> Option<Box<NodeHandle>> {
+ let mut shift_to_index = self.index(*key)?;
+ let (_, value) = self.buckets[shift_to_index].take().unwrap();
+ self.size -= 1;
+ let mask = self.buckets.len() - 1;
+ loop {
+ let shift_from_index = (shift_to_index + 1) & mask;
+ let Some((next_key, _)) = self.buckets[shift_from_index].as_ref() else {
+ break;
+ };
+ if self.probe_length(*next_key, shift_from_index) == 0 {
+ break;
+ }
+ self.buckets[shift_to_index] = self.buckets[shift_from_index].take();
+ shift_to_index = shift_from_index;
+ }
+ Some(value)
+ }
+
+ fn iter(&self) -> impl Iterator<Item = (&u64, &NodeHandle)> {
+ self.buckets
+ .iter()
+ .filter_map(Option::as_ref)
+ .map(|(key, value)| (key, value.as_ref()))
+ }
+
+ fn values(&self) -> impl Iterator<Item = &NodeHandle> {
+ self.iter().map(|(_, value)| value)
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_graph_create() -> *mut RenderGraph {
+ Box::into_raw(Box::new(RenderGraph::default()))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_graph_destroy(graph: *mut RenderGraph) {
+ drop(unsafe { Box::from_raw(graph) });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_graph_set_destination(graph: *mut RenderGraph, node_id: u64) {
+ unsafe { &mut *graph }.set_destination(node_id);
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_graph_apply_control_messages(
+ graph: *mut RenderGraph,
+ messages: *mut ControlMessages,
+) {
+ unsafe { &mut *graph }.apply_control_messages(unsafe { Box::from_raw(messages) }.messages);
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_graph_render_quantum(
+ graph: *const RenderGraph,
+ context: *const RenderContext,
+) {
+ unsafe { &*graph }.render_quantum(unsafe { &*context });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_graph_pull_output(
+ graph: *const RenderGraph,
+ source: u64,
+ output_index: usize,
+ context: *const RenderContext,
+) -> *mut AudioBus {
+ unsafe { &*graph }.pull_output(source, output_index, unsafe { &*context })
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_graph_destination_output(graph: *const RenderGraph) -> *mut AudioBus {
+ unsafe { &*graph }
+ .destination()
+ .map_or(std::ptr::null_mut(), |node| unsafe { node.data().output(0) })
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_graph_take_ended_nodes(
+ graph: *mut RenderGraph,
+ context: *mut std::ffi::c_void,
+ callback: unsafe extern "C" fn(*mut std::ffi::c_void, ak::Span<'_, u64>),
+) {
+ let ended_nodes = unsafe { &mut *graph }.take_ended_nodes();
+ unsafe {
+ callback(context, ak::Span::new(&ended_nodes));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::web_audio::audio_param_timeline::AudioParamTimeline;
+ use crate::web_audio::control_message::*;
+ use crate::web_audio::control_message_queue::ControlMessageQueue;
+ use crate::web_audio::rendering::node_message::{NodeMessage, StartSource, StopSource};
+ use crate::web_audio::rendering::render_node::{
+ AutomationRate, ChannelCountMode, ChannelInterpretation, OutgoingNodeConnection, RenderAudioParam,
+ };
+ use crate::web_audio::rendering::render_nodes::{
+ web_audio_node_create_constant_source, web_audio_node_create_destination,
+ };
+ use std::sync::Arc;
+
+ #[test]
+ fn control_queue_rendering_and_ended_node_retirement() {
+ let timeline = Arc::new(AudioParamTimeline::new(0.75));
+ let param = Arc::new(RenderAudioParam::new(timeline, -1., 1., AutomationRate::ARate));
+ let queue = ControlMessageQueue::default();
+ queue.enqueue(ControlMessage::SetChannelConfig(SetChannelConfig {
+ node_id: 1,
+ channel_count: 42,
+ channel_count_mode: ChannelCountMode::Explicit,
+ channel_interpretation: ChannelInterpretation::Discrete,
+ }));
+ for id in [1, 3] {
+ let node = unsafe { Box::from_raw(web_audio_node_create_constant_source(id, 4, Arc::as_ptr(&param))) };
+ queue.enqueue(ControlMessage::AddNode(AddNode { node }));
+ queue.enqueue(ControlMessage::NodeMessage(NodeMessage::StartSource(StartSource {
+ node_id: id,
+ when: 1. / 48000.,
+ })));
+ queue.enqueue(ControlMessage::NodeMessage(NodeMessage::StopSource(StopSource {
+ node_id: id,
+ when: 3. / 48000.,
+ })));
+ }
+ let destination = unsafe { Box::from_raw(web_audio_node_create_destination(2, 4, 2)) };
+ queue.enqueue(ControlMessage::AddNode(AddNode { node: destination }));
+ queue.enqueue(ControlMessage::ReplaceConnections(ReplaceConnections {
+ source: 1,
+ node_connections: vec![OutgoingNodeConnection {
+ destination: 2,
+ output_index: 0,
+ input_index: 0,
+ }],
+ param_connections: Vec::new(),
+ }));
+ let mut graph = RenderGraph::default();
+ graph.set_destination(2);
+ graph.apply_control_messages(queue.drain());
+ assert!(queue.drain().is_empty());
+ assert_eq!(graph.node(1).unwrap().data().channel_count.get(), 2);
+ assert_eq!(Arc::strong_count(&param), 3);
+ let mut context = RenderContext {
+ sample_rate: 48000.,
+ quantum_size: 4,
+ quantum_start_frame: 0,
+ };
+ graph.render_quantum(&context);
+ let bus = unsafe { &*graph.destination().unwrap().data().output(0) };
+ assert_eq!(bus.channel(0), &[0., 0.75, 0.75, 0.]);
+ assert_eq!(bus.channel(1), &[0., 0.75, 0.75, 0.]);
+ let mut ended = graph.take_ended_nodes();
+ ended.sort();
+ assert_eq!(ended, [1, 3]);
+ assert_eq!(Arc::strong_count(&param), 1);
+ context.quantum_start_frame = 4;
+ graph.render_quantum(&context);
+ assert!(unsafe { &*graph.destination().unwrap().data().output(0) }.is_silent());
+ assert!(graph.take_ended_nodes().is_empty());
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs
index 80471cf26e7..1aef7685ba5 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs
@@ -72,13 +72,18 @@ unsafe impl Sync for RenderAudioParam {}
pub type PullOutput = unsafe extern "C" fn(*mut c_void, u64, usize, *const RenderContext) -> *const AudioBus;
-struct RenderGraph {
+struct ForeignRenderGraph {
graph: *mut c_void,
pull_output: PullOutput,
}
impl RenderAudioParam {
- fn new(timeline: Arc<AudioParamTimeline>, min_value: f32, max_value: f32, automation_rate: AutomationRate) -> Self {
+ pub(crate) fn new(
+ timeline: Arc<AudioParamTimeline>,
+ min_value: f32,
+ max_value: f32,
+ automation_rate: AutomationRate,
+ ) -> Self {
Self {
timeline,
min_value,
@@ -104,8 +109,8 @@ impl RenderAudioParam {
}
// https://webaudio.github.io/web-audio-api/#computation-of-value
- unsafe fn compute(&self, graph: &RenderGraph, context: &RenderContext, output: &mut [f32]) {
- let state = unsafe { &mut *self.state.get() };
+ pub(crate) unsafe fn compute(&self, graph: &dyn OutputGraph, context: &RenderContext, output: &mut [f32]) {
+ let state = self.state.get();
// 1. paramIntrinsicValue will be calculated at each time, which is either the value set directly to the value
// attribute, or, if there are any automation events with times before or at this time, the value as calculated
@@ -127,22 +132,22 @@ impl RenderAudioParam {
// 3. paramComputedValue is the sum of the paramIntrinsicValue value and the value of the input AudioParam
// buffer. If the sum is NaN, replace the sum with the defaultValue.
- for input in &state.inputs {
- let bus = unsafe { (graph.pull_output)(graph.graph, input.source, input.output_index, context) };
+ for input in unsafe { &(*state).inputs } {
+ let bus = graph.pull_output(input.source, input.output_index, context);
let Some(bus) = (unsafe { bus.as_ref() }) else {
continue;
};
// The AudioParam will take the rendered audio data from any AudioNode output connected to it and convert it to
// mono by down-mixing if it is not already mono.
- if state
- .input_scratch
+ let input_scratch = unsafe { &mut (*state).input_scratch };
+ if input_scratch
.as_ref()
.is_none_or(|scratch| scratch.frame_count() != context.quantum_size)
{
- state.input_scratch = Some(Box::new(AudioBus::new(1, context.quantum_size)));
+ *input_scratch = Some(Box::new(AudioBus::new(1, context.quantum_size)));
}
- let input_scratch = state.input_scratch.as_mut().unwrap();
+ let input_scratch = input_scratch.as_mut().unwrap();
input_scratch.zero();
input_scratch.sum_from(bus, true);
@@ -247,8 +252,408 @@ pub(crate) unsafe extern "C" fn web_audio_render_param_compute(
context: *const RenderContext,
output: SpanMut<'_, f32>,
) {
- let graph = RenderGraph { graph, pull_output };
+ let graph = ForeignRenderGraph { graph, pull_output };
unsafe {
(&*param).compute(&graph, &*context, output.into_slice());
}
}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum ChannelCountMode {
+ Max,
+ ClampedMax,
+ Explicit,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum ChannelInterpretation {
+ Speakers,
+ Discrete,
+}
+
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub struct Connection {
+ pub source: u64,
+ pub output_index: usize,
+}
+
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub struct OutgoingNodeConnection {
+ pub destination: u64,
+ pub output_index: usize,
+ pub input_index: usize,
+}
+
+pub struct OutgoingParamConnection {
+ pub destination: Arc<RenderAudioParam>,
+ pub output_index: usize,
+}
+
+pub struct RenderNodeData {
+ pub node_id: u64,
+ pub channel_count: std::cell::Cell<usize>,
+ pub channel_count_mode: std::cell::Cell<ChannelCountMode>,
+ pub channel_interpretation: std::cell::Cell<ChannelInterpretation>,
+ pub input_connections: UnsafeCell<Vec<Vec<Connection>>>,
+ input_buses: UnsafeCell<Vec<AudioBus>>,
+ pulled_source_buses: UnsafeCell<smallvec::SmallVec<[*const AudioBus; 4]>>,
+ outputs: UnsafeCell<Vec<AudioBus>>,
+ pub outgoing_node_connections: UnsafeCell<Vec<OutgoingNodeConnection>>,
+ pub outgoing_param_connections: UnsafeCell<Vec<OutgoingParamConnection>>,
+
+ // Bookkeeping used by RenderGraph to process every node at most once per render quantum.
+ pub processed_quantum: std::cell::Cell<u64>,
+ pub is_processing: std::cell::Cell<bool>,
+}
+
+// SAFETY: Render-node data is transferred to one rendering thread before it is accessed.
+unsafe impl Send for RenderNodeData {}
+impl RenderNodeData {
+ pub fn new(
+ node_id: u64,
+ input_count: usize,
+ output_count: usize,
+ quantum_size: usize,
+ output_channel_count: usize,
+ ) -> Self {
+ let input_connections = (0..input_count).map(|_| Vec::new()).collect();
+ let mut input_buses = Vec::with_capacity(input_count);
+ for _input_index in 0..input_count {
+ input_buses.push(AudioBus::new(1, quantum_size));
+ }
+ let mut outputs = Vec::with_capacity(output_count);
+ for _output_index in 0..output_count {
+ outputs.push(AudioBus::new(output_channel_count, quantum_size));
+ }
+ Self {
+ node_id,
+ channel_count: std::cell::Cell::new(2),
+ channel_count_mode: std::cell::Cell::new(ChannelCountMode::Max),
+ channel_interpretation: std::cell::Cell::new(ChannelInterpretation::Speakers),
+ input_connections: UnsafeCell::new(input_connections),
+ input_buses: UnsafeCell::new(input_buses),
+ pulled_source_buses: UnsafeCell::new(smallvec::SmallVec::new()),
+ outputs: UnsafeCell::new(outputs),
+ outgoing_node_connections: UnsafeCell::new(Vec::new()),
+ outgoing_param_connections: UnsafeCell::new(Vec::new()),
+ processed_quantum: std::cell::Cell::new(u64::MAX),
+ is_processing: std::cell::Cell::new(false),
+ }
+ }
+
+ pub fn input_count(&self) -> usize {
+ unsafe { &*self.input_connections.get() }.len()
+ }
+
+ pub fn output_count(&self) -> usize {
+ unsafe { &*self.outputs.get() }.len()
+ }
+
+ pub(crate) unsafe fn output(&self, index: usize) -> *mut AudioBus {
+ let outputs = self.outputs.get();
+ assert!(index < unsafe { &*outputs }.len());
+ unsafe { (*outputs).as_mut_ptr().add(index) }
+ }
+
+ pub(crate) unsafe fn set_outgoing_connections(
+ &self,
+ node_connections: Vec<OutgoingNodeConnection>,
+ param_connections: Vec<OutgoingParamConnection>,
+ ) {
+ unsafe {
+ *self.outgoing_node_connections.get() = node_connections;
+ *self.outgoing_param_connections.get() = param_connections;
+ }
+ }
+
+ // Pulls and mixes all connections to the given input into a single bus with the input's computed number of channels.
+ // Unconnected inputs are mixed as a single channel of silence.
+ // https://webaudio.github.io/web-audio-api/#computednumberofchannels
+ pub(crate) unsafe fn pull_input(
+ &self,
+ graph: &super::render_graph::RenderGraph,
+ context: &RenderContext,
+ input_index: usize,
+ ) -> *const AudioBus {
+ let connections = &unsafe { &*self.input_connections.get() }[input_index];
+ let input_bus = unsafe { (*self.input_buses.get()).as_mut_ptr().add(input_index) };
+ let source_buses = unsafe { &mut *self.pulled_source_buses.get() };
+ source_buses.clear();
+ for connection in connections {
+ let bus = graph.pull_output(connection.source, connection.output_index, context);
+ if !bus.is_null() {
+ source_buses.push(bus);
+ }
+ }
+ if source_buses.is_empty() {
+ unsafe {
+ (&mut *input_bus).set_channel_count(1);
+ (&mut *input_bus).zero();
+ }
+ return input_bus;
+ }
+
+ let mut computed_number_of_channels = 0;
+ match self.channel_count_mode.get() {
+ ChannelCountMode::Max | ChannelCountMode::ClampedMax => {
+ // "max": computedNumberOfChannels is the maximum of the number of channels of all connections to an input.
+ // In this mode channelCount is ignored.
+ // "clamped-max": computedNumberOfChannels is determined as for "max" and then clamped to a maximum value of
+ // the given channelCount.
+ for &bus in source_buses.iter() {
+ computed_number_of_channels = computed_number_of_channels.max(unsafe { &*bus }.channel_count());
+ }
+ if self.channel_count_mode.get() == ChannelCountMode::ClampedMax {
+ computed_number_of_channels = computed_number_of_channels.min(self.channel_count.get());
+ }
+ }
+ ChannelCountMode::Explicit => {
+ // "explicit": computedNumberOfChannels is the exact value as specified by the channelCount.
+ computed_number_of_channels = self.channel_count.get();
+ }
+ }
+ unsafe {
+ (&mut *input_bus).set_channel_count(computed_number_of_channels);
+ (&mut *input_bus).zero();
+ }
+ for &bus in source_buses.iter() {
+ unsafe {
+ (&mut *input_bus).sum_from(
+ &*bus,
+ self.channel_interpretation.get() == ChannelInterpretation::Speakers,
+ );
+ }
+ }
+ input_bus
+ }
+}
+
+// Base class for the rendering thread's counterparts of AudioNodes. Render nodes are constructed on the control thread
+// and transferred to the rendering thread through the control message queue; after that, all access happens on the
+// rendering thread.
+pub(crate) trait RenderNode: Send {
+ fn data(&self) -> &RenderNodeData;
+
+ unsafe fn process(&self, graph: &super::render_graph::RenderGraph, context: &RenderContext);
+
+ unsafe fn handle_message(&self, _message: &super::node_message::NodeMessage) {}
+ fn for_each_param(&self, _callback: &mut dyn FnMut(&RenderAudioParam)) {}
+
+ // Returns true exactly once after this node has stopped playing, so the main thread can fire an ended event.
+ unsafe fn take_ended_notification(&self) -> bool {
+ false
+ }
+}
+
+pub struct NodeHandle {
+ pub(crate) node: Box<dyn RenderNode>,
+}
+
+impl NodeHandle {
+ pub fn data(&self) -> &RenderNodeData {
+ self.node.data()
+ }
+}
+
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub struct ExternalNodeCallbacks {
+ pub process: unsafe extern "C" fn(*mut c_void, *const super::render_graph::RenderGraph, *const RenderContext),
+ pub set_ring: unsafe extern "C" fn(*mut c_void, *mut c_void, u32),
+ pub for_each_param:
+ unsafe extern "C" fn(*mut c_void, *mut c_void, unsafe extern "C" fn(*mut c_void, *const RenderAudioParam)),
+ pub ended: unsafe extern "C" fn(*mut c_void) -> bool,
+ pub destroy: unsafe extern "C" fn(*mut c_void),
+}
+
+pub struct ExternalRenderNode {
+ pub data: RenderNodeData,
+ pub cpp_node: *mut c_void,
+ pub callbacks: ExternalNodeCallbacks,
+}
+
+// SAFETY: The C++ node is transferred to the rendering thread together with its Rust base data.
+unsafe impl Send for ExternalRenderNode {}
+impl Drop for ExternalRenderNode {
+ fn drop(&mut self) {
+ unsafe {
+ (self.callbacks.destroy)(self.cpp_node);
+ }
+ }
+}
+
+impl RenderNode for ExternalRenderNode {
+ unsafe fn take_ended_notification(&self) -> bool {
+ unsafe { (self.callbacks.ended)(self.cpp_node) }
+ }
+
+ fn data(&self) -> &RenderNodeData {
+ &self.data
+ }
+
+ unsafe fn process(&self, graph: &super::render_graph::RenderGraph, context: &RenderContext) {
+ unsafe {
+ (self.callbacks.process)(self.cpp_node, graph, context);
+ }
+ }
+
+ unsafe fn handle_message(&self, message: &super::node_message::NodeMessage) {
+ if let super::node_message::NodeMessage::SetMediaStreamSourceRing(message) = message {
+ unsafe {
+ (self.callbacks.set_ring)(
+ self.cpp_node,
+ message.ring.as_ref().map_or(std::ptr::null_mut(), |ring| ring.pointer),
+ message.channel_count,
+ );
+ }
+ }
+ }
+
+ fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {
+ unsafe extern "C" fn call(context: *mut c_void, param: *const RenderAudioParam) {
+ let callback = unsafe { &mut *context.cast::<&mut dyn FnMut(&RenderAudioParam)>() };
+ callback(unsafe { &*param });
+ }
+ let mut callback = callback;
+ unsafe {
+ (self.callbacks.for_each_param)(self.cpp_node, (&raw mut callback).cast(), call);
+ }
+ }
+}
+
+pub trait OutputGraph {
+ fn pull_output(&self, source: u64, output_index: usize, context: &RenderContext) -> *const AudioBus;
+}
+
+impl OutputGraph for ForeignRenderGraph {
+ fn pull_output(&self, source: u64, output_index: usize, context: &RenderContext) -> *const AudioBus {
+ unsafe { (self.pull_output)(self.graph, source, output_index, context) }
+ }
+}
+
+impl OutputGraph for super::render_graph::RenderGraph {
+ fn pull_output(&self, source: u64, output_index: usize, context: &RenderContext) -> *const AudioBus {
+ self.pull_output(source, output_index, context)
+ }
+}
+
+impl RenderAudioParam {
+ pub(crate) unsafe fn clear_inputs(&self) {
+ unsafe { &mut (*self.state.get()).inputs }.clear();
+ }
+
+ pub(crate) unsafe fn add_input(&self, source: u64, output_index: usize) {
+ unsafe { &mut (*self.state.get()).inputs }.push(Input { source, output_index });
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_node_create_external(
+ node_id: u64,
+ input_count: usize,
+ output_count: usize,
+ quantum_size: usize,
+ output_channel_count: usize,
+ cpp_node: *mut c_void,
+ callbacks: ExternalNodeCallbacks,
+) -> *mut NodeHandle {
+ Box::into_raw(Box::new(NodeHandle {
+ node: Box::new(ExternalRenderNode {
+ data: RenderNodeData::new(node_id, input_count, output_count, quantum_size, output_channel_count),
+ cpp_node,
+ callbacks,
+ }),
+ }))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_destroy(node: *mut NodeHandle) {
+ drop(unsafe { Box::from_raw(node) });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_id(node: *const NodeHandle) -> u64 {
+ unsafe { &*node }.data().node_id
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_input_count(node: *const NodeHandle) -> usize {
+ unsafe { &*node }.data().input_count()
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_output_count(node: *const NodeHandle) -> usize {
+ unsafe { &*node }.data().output_count()
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_output(node: *const NodeHandle, index: usize) -> *mut AudioBus {
+ unsafe { (&*node).data().output(index) }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_pull_input(
+ node: *const NodeHandle,
+ graph: *const super::render_graph::RenderGraph,
+ context: *const RenderContext,
+ input_index: usize,
+) -> *const AudioBus {
+ unsafe { (&*node).data().pull_input(&*graph, &*context, input_index) }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_channel_count(node: *const NodeHandle) -> usize {
+ unsafe { &*node }.data().channel_count.get()
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_channel_count_mode(node: *const NodeHandle) -> ChannelCountMode {
+ unsafe { &*node }.data().channel_count_mode.get()
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_channel_interpretation(
+ node: *const NodeHandle,
+) -> ChannelInterpretation {
+ unsafe { &*node }.data().channel_interpretation.get()
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_set_channel_count(node: *const NodeHandle, value: usize) {
+ unsafe { &*node }.data().channel_count.set(value);
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_set_channel_count_mode(
+ node: *const NodeHandle,
+ value: ChannelCountMode,
+) {
+ unsafe { &*node }.data().channel_count_mode.set(value);
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_set_channel_interpretation(
+ node: *const NodeHandle,
+ value: ChannelInterpretation,
+) {
+ unsafe { &*node }.data().channel_interpretation.set(value);
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_has_input_connections(node: *const NodeHandle, input: usize) -> bool {
+ !(unsafe { &*(&*node).data().input_connections.get() })[input].is_empty()
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_outgoing_node_connection_count(node: *const NodeHandle) -> usize {
+ unsafe { &*(&*node).data().outgoing_node_connections.get() }.len()
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_outgoing_param_connection_count(node: *const NodeHandle) -> usize {
+ unsafe { &*(&*node).data().outgoing_param_connections.get() }.len()
+}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs
new file mode 100644
index 00000000000..223bc91a55c
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs
@@ -0,0 +1,2118 @@
+/*
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#![allow(
+ clippy::needless_range_loop,
+ clippy::manual_memcpy,
+ clippy::mut_from_ref,
+ clippy::needless_late_init,
+ clippy::neg_cmp_op_on_partial_ord
+)]
+
+use std::cell::UnsafeCell;
+use std::sync::{Arc, OnceLock};
+
+use ak::math;
+
+use super::audio_bus::AudioBus;
+use super::biquad_coefficients::{BiquadFilterType, compute_biquad_coefficients};
+use super::convolver_kernel::ConvolverKernel;
+use super::fft::{FFT, FFTDirection};
+use super::node_message::*;
+use super::render_graph::RenderGraph;
+use super::render_node::*;
+
+// Additive synthesis of the built-in oscillator waveforms is capped to keep the per-sample cost bounded for very low
+// fundamental frequencies.
+const MAX_OSCILLATOR_HARMONICS: usize = 5000;
+const FRAME_BOUNDARY_SNAPPING_TOLERANCE: f64 = 1. / 2048.;
+const PI: f64 = std::f64::consts::PI;
+
+fn clamp<T: PartialOrd + Copy>(value: T, min: T, max: T) -> T {
+ assert!(max >= min);
+ if value > max {
+ return max;
+ }
+ if value < min {
+ return min;
+ }
+ value
+}
+
+fn cpp_min<T: PartialOrd + Copy>(a: T, b: T) -> T {
+ if b < a { b } else { a }
+}
+
+fn cpp_max<T: PartialOrd + Copy>(a: T, b: T) -> T {
+ if a < b { b } else { a }
+}
+
+struct BusRef(*mut AudioBus);
+
+impl BusRef {
+ unsafe fn channel_count(&self) -> usize {
+ unsafe { &*self.0 }.channel_count()
+ }
+
+ unsafe fn set_channel_count(&self, count: usize) {
+ unsafe { &mut *self.0 }.set_channel_count(count);
+ }
+
+ unsafe fn zero(&self) {
+ unsafe { &mut *self.0 }.zero();
+ }
+
+ unsafe fn is_silent(&self) -> bool {
+ unsafe { &*self.0 }.is_silent()
+ }
+
+ unsafe fn channel(&self, index: usize) -> &[f32] {
+ let (pointer, length) = unsafe { AudioBus::channel_pointer(self.0, index) };
+ unsafe { ak::slice_from_raw_parts(pointer, length) }
+ }
+
+ unsafe fn channel_mut(&self, index: usize) -> &mut [f32] {
+ let (pointer, length) = unsafe { AudioBus::channel_pointer(self.0, index) };
+ unsafe { ak::slice_from_raw_parts_mut(pointer, length) }
+ }
+
+ unsafe fn copy_from(&self, source: &BusRef) {
+ unsafe { &mut *self.0 }.copy_from(unsafe { &*source.0 });
+ }
+
+ unsafe fn sum_from(&self, source: &BusRef, interpretation: ChannelInterpretation) {
+ unsafe { &mut *self.0 }.sum_from(unsafe { &*source.0 }, interpretation == ChannelInterpretation::Speakers);
+ }
+}
+
+trait NodeProcessor: Send {
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext);
+
+ fn handle_message(&mut self, _message: &NodeMessage) {}
+ fn for_each_param(&self, _callback: &mut dyn FnMut(&RenderAudioParam)) {}
+ fn take_ended_notification(&mut self) -> bool {
+ false
+ }
+}
+
+struct NativeRenderNode<T: NodeProcessor> {
+ data: RenderNodeData,
+ processor: UnsafeCell<T>,
+}
+
+impl<T: NodeProcessor> RenderNode for NativeRenderNode<T> {
+ fn data(&self) -> &RenderNodeData {
+ &self.data
+ }
+
+ unsafe fn process(&self, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ (&mut *self.processor.get()).process(&self.data, graph, context);
+ }
+ }
+
+ unsafe fn handle_message(&self, message: &NodeMessage) {
+ unsafe { &mut *self.processor.get() }.handle_message(message);
+ }
+
+ fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {
+ unsafe { &*self.processor.get() }.for_each_param(callback);
+ }
+
+ unsafe fn take_ended_notification(&self) -> bool {
+ unsafe { &mut *self.processor.get() }.take_ended_notification()
+ }
+}
+
+fn node_handle<T: NodeProcessor + 'static>(data: RenderNodeData, processor: T) -> *mut NodeHandle {
+ Box::into_raw(Box::new(NodeHandle {
+ node: Box::new(NativeRenderNode {
+ data,
+ processor: UnsafeCell::new(processor),
+ }),
+ }))
+}
+
+struct PanGains {
+ left: f32,
+ right: f32,
+}
+
+// The equal-power panning curve maps a position in [0, 1] to a left/right gain pair whose squared sum is 1, shared by
+// the StereoPannerNode and the equalpower PannerNode.
+// https://webaudio.github.io/web-audio-api/#stereopanner-algorithm
+fn equal_power_pan_gains(position: f64) -> PanGains {
+ PanGains {
+ left: math::cos(position * PI / 2.) as f32,
+ right: math::sin(position * PI / 2.) as f32,
+ }
+}
+
+// Captures the mixed input signal so the renderer can copy it into the rendered buffer.
+// https://webaudio.github.io/web-audio-api/#AudioDestinationNode
+struct DestinationRenderNode;
+
+impl NodeProcessor for DestinationRenderNode {
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());
+ let destination_output = BusRef(data.output(0));
+ destination_output.set_channel_count(data.channel_count.get());
+ destination_output.zero();
+ destination_output.sum_from(&input, data.channel_interpretation.get());
+ }
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#GainNode
+struct GainRenderNode {
+ gain: Arc<RenderAudioParam>,
+ gain_values: Vec<f32>,
+}
+
+impl NodeProcessor for GainRenderNode {
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());
+ let gain_output = BusRef(data.output(0));
+ gain_output.set_channel_count(input.channel_count());
+ if input.is_silent() {
+ gain_output.zero();
+ return;
+ }
+ self.gain.compute(graph, context, &mut self.gain_values);
+ for channel_index in 0..input.channel_count() {
+ let input_samples = input.channel(channel_index);
+ let output_samples = gain_output.channel_mut(channel_index);
+ for frame in 0..context.quantum_size {
+ output_samples[frame] = input_samples[frame] * self.gain_values[frame];
+ }
+ }
+ }
+ }
+
+ fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {
+ callback(&self.gain);
+ }
+}
+
+// Base class for source nodes that are scheduled with start() and stop().
+// https://webaudio.github.io/web-audio-api/#AudioScheduledSourceNode
+struct ScheduledSourceRenderNode {
+ start_time: Option<f64>,
+ stop_time: f64,
+ start_time_needs_clamping: bool,
+
+ // Playback naturally ran out of content before the scheduled stop time, e.g. a non-looping buffer finished.
+ content_ended: bool,
+ ended: bool,
+ ended_pending: bool,
+}
+
+impl Default for ScheduledSourceRenderNode {
+ fn default() -> Self {
+ Self {
+ start_time: None,
+ stop_time: f64::INFINITY,
+ start_time_needs_clamping: false,
+ content_ended: false,
+ ended: false,
+ ended_pending: false,
+ }
+ }
+}
+
+impl ScheduledSourceRenderNode {
+ // https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-start
+ fn process(&mut self, context: &RenderContext) {
+ // If 0 is passed in for this value or if the value is less than currentTime, then the sound will start playing
+ // immediately.
+ // NB: The start time is clamped to the first render quantum processed after the start message arrived, since the
+ // control thread's currentTime may already have advanced past the scheduled time by then.
+ if self.start_time_needs_clamping {
+ // AD-HOC: Start times built by summing buffer durations may induce rounding error and place the start part
+ // of a frame after the prior buffer's end. Snap starts that are close to a frame boundary onto it
+ // to prevent this from becoming audible in continuous streams.
+ let start_frame = self.start_time.unwrap() * context.sample_rate;
+ let nearest_frame = start_frame.round();
+ if (start_frame - nearest_frame).abs() < FRAME_BOUNDARY_SNAPPING_TOLERANCE {
+ self.start_time = Some(nearest_frame / context.sample_rate);
+ }
+ self.start_time = Some(cpp_max(self.start_time.unwrap(), context.quantum_start_time()));
+ self.start_time_needs_clamping = false;
+ }
+ }
+
+ fn handle_message(&mut self, message: &NodeMessage) {
+ match message {
+ NodeMessage::StartSource(start_source) => {
+ self.start_time = Some(start_source.when);
+ self.start_time_needs_clamping = true;
+ }
+ NodeMessage::StopSource(stop_source) => {
+ self.stop_time = stop_source.when;
+ }
+ _ => {}
+ }
+ }
+
+ fn has_started(&self) -> bool {
+ self.start_time.is_some()
+ }
+
+ fn is_active_at(&self, time: f64) -> bool {
+ self.start_time.is_some_and(|start_time| time >= start_time) && time < self.stop_time && !self.content_ended
+ }
+
+ // Marks this node as ended once the quantum has advanced past the stop time or the content was exhausted.
+ fn update_ended_state(&mut self, context: &RenderContext) {
+ if self.start_time.is_none() || self.ended {
+ return;
+ }
+ let quantum_end_time = context.frame_time(context.quantum_size);
+ if quantum_end_time >= self.stop_time || self.content_ended {
+ self.ended = true;
+ self.ended_pending = true;
+ }
+ }
+
+ fn take_ended_notification(&mut self) -> bool {
+ std::mem::replace(&mut self.ended_pending, false)
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#ConstantSourceNode
+struct ConstantSourceRenderNode {
+ source: ScheduledSourceRenderNode,
+ offset: Arc<RenderAudioParam>,
+ offset_values: Vec<f32>,
+}
+
+impl ConstantSourceRenderNode {
+ unsafe fn process_source(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ self.offset.compute(graph, context, &mut self.offset_values);
+ let output = BusRef(data.output(0));
+ let output_samples = output.channel_mut(0);
+ for frame in 0..context.quantum_size {
+ output_samples[frame] = if self.source.is_active_at(context.frame_time(frame)) {
+ self.offset_values[frame]
+ } else {
+ 0.
+ };
+ }
+ self.source.update_ended_state(context);
+ }
+ }
+}
+
+impl NodeProcessor for ConstantSourceRenderNode {
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ self.source.process(context);
+ unsafe {
+ self.process_source(data, graph, context);
+ }
+ }
+
+ fn handle_message(&mut self, message: &NodeMessage) {
+ self.source.handle_message(message);
+ }
+
+ fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {
+ callback(&self.offset);
+ }
+
+ fn take_ended_notification(&mut self) -> bool {
+ self.source.take_ended_notification()
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#OscillatorNode
+struct OscillatorRenderNode {
+ source: ScheduledSourceRenderNode,
+ frequency: Arc<RenderAudioParam>,
+ detune: Arc<RenderAudioParam>,
+ frequency_values: Vec<f32>,
+ detune_values: Vec<f32>,
+ r#type: OscillatorType,
+ periodic_wave: Option<Arc<PeriodicWaveData>>,
+ periodic_wave_scale: f32,
+ phase: f64,
+}
+
+impl OscillatorRenderNode {
+ // https://webaudio.github.io/web-audio-api/#oscillator-coefficients
+ fn sample_waveform(&self, phase: f64, frequency: f64, nyquist_frequency: f64) -> f32 {
+ match self.r#type {
+ OscillatorType::Sine => math::sin(phase) as f32,
+ OscillatorType::Square => {
+ // b[n] = 2/(nπ) * (1 - cos(nπ))
+ // NB: This is 4/(nπ) for odd n and 0 for even n.
+ let mut harmonic_count = if frequency != 0. {
+ (nyquist_frequency / frequency.abs()) as usize
+ } else {
+ MAX_OSCILLATOR_HARMONICS
+ };
+ harmonic_count = harmonic_count.min(MAX_OSCILLATOR_HARMONICS);
+ let mut value = 0.;
+ for harmonic in (1..=harmonic_count).step_by(2) {
+ let coefficient = 4. / (harmonic as f64 * PI);
+ value += coefficient * math::sin(harmonic as f64 * phase);
+ }
+ value as f32
+ }
+ OscillatorType::Sawtooth => {
+ // b[n] = (-1)^(n+1) * 2/(nπ)
+ let mut harmonic_count = if frequency != 0. {
+ (nyquist_frequency / frequency.abs()) as usize
+ } else {
+ MAX_OSCILLATOR_HARMONICS
+ };
+ harmonic_count = harmonic_count.min(MAX_OSCILLATOR_HARMONICS);
+ let mut value = 0.;
+ for harmonic in 1..=harmonic_count {
+ let mut coefficient = 2. / (harmonic as f64 * PI);
+ if harmonic % 2 == 0 {
+ coefficient = -coefficient;
+ }
+ value += coefficient * math::sin(harmonic as f64 * phase);
+ }
+ value as f32
+ }
+ OscillatorType::Triangle => {
+ // b[n] = 8 * sin(nπ/2) / (nπ)²
+ // NB: This alternates sign for odd n and is 0 for even n.
+ let mut harmonic_count = if frequency != 0. {
+ (nyquist_frequency / frequency.abs()) as usize
+ } else {
+ MAX_OSCILLATOR_HARMONICS
+ };
+ harmonic_count = harmonic_count.min(MAX_OSCILLATOR_HARMONICS);
+ let mut value = 0.;
+ let mut sign = 1.;
+ for harmonic in (1..=harmonic_count).step_by(2) {
+ let coefficient = sign * 8. / ((harmonic * harmonic) as f64 * PI * PI);
+ value += coefficient * math::sin(harmonic as f64 * phase);
+ sign = -sign;
+ }
+ value as f32
+ }
+ OscillatorType::Custom => {
+ let Some(periodic_wave) = &self.periodic_wave else {
+ return 0.;
+ };
+ let harmonic_limit = periodic_wave.real.len();
+ let mut value = 0.;
+ for harmonic_index in 1..harmonic_limit {
+ value += f64::from(periodic_wave.real[harmonic_index]) * math::cos(harmonic_index as f64 * phase)
+ + f64::from(periodic_wave.imag[harmonic_index]) * math::sin(harmonic_index as f64 * phase);
+ }
+ value as f32 * self.periodic_wave_scale
+ }
+ }
+ }
+
+ unsafe fn process_source(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ self.frequency.compute(graph, context, &mut self.frequency_values);
+ self.detune.compute(graph, context, &mut self.detune_values);
+ let nyquist_frequency = context.sample_rate / 2.;
+ let output = BusRef(data.output(0));
+ let output_samples = output.channel_mut(0);
+ for frame in 0..context.quantum_size {
+ if !self.source.is_active_at(context.frame_time(frame)) {
+ output_samples[frame] = 0.;
+ continue;
+ }
+
+ // computedOscFrequency(t) = frequency(t) * pow(2, detune(t) / 1200)
+ // NB: The computed frequency is clamped to the Nyquist frequency.
+ let mut computed_frequency =
+ f64::from(self.frequency_values[frame]) * math::exp2(f64::from(self.detune_values[frame]) / 1200.);
+ computed_frequency = clamp(computed_frequency, -nyquist_frequency, nyquist_frequency);
+ output_samples[frame] = self.sample_waveform(self.phase, computed_frequency, nyquist_frequency);
+ self.phase += 2. * PI * computed_frequency / context.sample_rate;
+ self.phase %= 2. * PI;
+ if self.phase < 0. {
+ self.phase += 2. * PI;
+ }
+ }
+ self.source.update_ended_state(context);
+ }
+ }
+}
+
+impl NodeProcessor for OscillatorRenderNode {
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ self.source.process(context);
+ unsafe {
+ self.process_source(data, graph, context);
+ }
+ }
+
+ fn handle_message(&mut self, message: &NodeMessage) {
+ match message {
+ NodeMessage::SetOscillatorWaveform(set_waveform) => {
+ self.r#type = set_waveform.r#type;
+ self.periodic_wave = set_waveform.periodic_wave.clone();
+
+ // https://webaudio.github.io/web-audio-api/#waveform-normalization
+ // If the internal slot [[normalize]] of this PeriodicWave is true (the default), the waveform defined in
+ // the previous section is normalized so that the maximum value is 1.
+ self.periodic_wave_scale = 1.;
+ if let Some(periodic_wave) = &self.periodic_wave
+ && periodic_wave.normalize
+ {
+ let mut maximum_amplitude = 0_f32;
+ const NORMALIZATION_SAMPLE_COUNT: usize = 4096;
+ for sample_index in 0..NORMALIZATION_SAMPLE_COUNT {
+ let phase = 2. * PI * sample_index as f64 / NORMALIZATION_SAMPLE_COUNT as f64;
+ let mut amplitude = 0_f32;
+ for harmonic in 1..periodic_wave.real.len() {
+ amplitude += periodic_wave.real[harmonic] * math::cos(harmonic as f64 * phase) as f32
+ + periodic_wave.imag[harmonic] * math::sin(harmonic as f64 * phase) as f32;
+ }
+ maximum_amplitude = cpp_max(maximum_amplitude, amplitude.abs());
+ }
+ if maximum_amplitude > 0. {
+ self.periodic_wave_scale = 1. / maximum_amplitude;
+ }
+ }
+ }
+ _ => self.source.handle_message(message),
+ }
+ }
+
+ fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {
+ callback(&self.frequency);
+ callback(&self.detune);
+ }
+
+ fn take_ended_notification(&mut self) -> bool {
+ self.source.take_ended_notification()
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#AudioBufferSourceNode
+struct AudioBufferSourceRenderNode {
+ source: ScheduledSourceRenderNode,
+ playback_rate: Arc<RenderAudioParam>,
+ detune: Arc<RenderAudioParam>,
+ playback_rate_values: Vec<f32>,
+ detune_values: Vec<f32>,
+ buffer: Option<Arc<AudioBufferContents>>,
+ r#loop: bool,
+ loop_start: f64,
+ loop_end: f64,
+ offset: f64,
+ duration: Option<f64>,
+
+ // Playback position within the buffer contents, in buffer sample frames.
+ playhead: f64,
+ playhead_valid: bool,
+ played_time: f64,
+}
+
+impl AudioBufferSourceRenderNode {
+ fn sample_buffer(&self, channel: usize, playhead_frames: f64, loop_start_frame: f64, loop_end_frame: f64) -> f32 {
+ let samples = &self.buffer.as_ref().unwrap().channels[channel];
+ let index = playhead_frames.floor() as i64;
+ let fraction = (playhead_frames - index as f64) as f32;
+ let sample_at = |mut sample_index: i64| -> f32 {
+ // When looping, interpolation across the loop end wraps around to the loop start.
+ if self.r#loop && sample_index >= loop_end_frame as i64 && loop_end_frame > loop_start_frame {
+ sample_index -= (loop_end_frame - loop_start_frame) as i64;
+ }
+ if sample_index < 0 || sample_index >= samples.len() as i64 {
+ return 0.;
+ }
+ samples[sample_index as usize]
+ };
+ if fraction == 0. {
+ return sample_at(index);
+ }
+
+ // Past the last frame there is nothing to interpolate toward, so the slope leading into it is continued instead.
+ if !self.r#loop && index == samples.len() as i64 - 1 {
+ if index == 0 {
+ return sample_at(index);
+ }
+ return sample_at(index) + fraction * (sample_at(index) - sample_at(index - 1));
+ }
+ sample_at(index) + fraction * (sample_at(index + 1) - sample_at(index))
+ }
+
+ // https://webaudio.github.io/web-audio-api/#playback-AudioBufferSourceNode
+ unsafe fn process_source(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ self.playback_rate
+ .compute(graph, context, &mut self.playback_rate_values);
+ self.detune.compute(graph, context, &mut self.detune_values);
+ let source_output = BusRef(data.output(0));
+ source_output.set_channel_count(self.buffer.as_ref().map_or(1, |buffer| buffer.channels.len()));
+ source_output.zero();
+ if self.buffer.is_none() || !self.source.has_started() {
+ self.source.update_ended_state(context);
+ return;
+ }
+
+ // NB: The playback rate is k-rate, so a single computed value is used for the entire quantum. The playhead is
+ // tracked in buffer sample frames so that unity-rate playback of a buffer at the context's sample rate
+ // advances by exactly one frame per rendered frame and reproduces the buffer bit-exactly.
+ let computed_playback_rate =
+ f64::from(self.playback_rate_values[0]) * math::exp2(f64::from(self.detune_values[0]) / 1200.);
+ let buffer = self.buffer.as_ref().unwrap();
+ let buffer_sample_rate = f64::from(buffer.sample_rate);
+ let playhead_increment = computed_playback_rate * buffer_sample_rate / context.sample_rate;
+ let buffer_length = buffer.length() as f64;
+
+ // NB: Determine the effective loop region, in buffer sample frames.
+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loopstart
+ let mut actual_loop_start = 0.;
+ let mut actual_loop_end = buffer_length;
+ if self.r#loop && self.loop_start >= 0. && self.loop_end > 0. && self.loop_start < self.loop_end {
+ actual_loop_start = cpp_min(self.loop_start * buffer_sample_rate, buffer_length);
+ actual_loop_end = cpp_min(self.loop_end * buffer_sample_rate, buffer_length);
+ }
+ for frame in 0..context.quantum_size {
+ let frame_time = context.frame_time(frame);
+ if !self.source.is_active_at(frame_time) {
+ continue;
+ }
+ if !self.playhead_valid {
+ // NB: Playback begins at the given offset, corrected for the source starting between two sample frames.
+ self.playhead = self.offset * buffer_sample_rate;
+ if self.r#loop {
+ self.playhead = cpp_min(self.playhead, actual_loop_end);
+ } else {
+ self.playhead = cpp_min(self.playhead, buffer_length);
+ }
+ self.playhead +=
+ (frame_time - self.source.start_time.unwrap()) * computed_playback_rate * buffer_sample_rate;
+ self.playhead_valid = true;
+ }
+
+ // NB: Compare using a half-frame tolerance since m_played_time accumulates one frame's worth of content at
+ // a time and would otherwise overshoot the duration by up to one frame due to floating-point rounding.
+ let frame_consumption = computed_playback_rate.abs() / context.sample_rate;
+ if self
+ .duration
+ .is_some_and(|duration| self.played_time + frame_consumption / 2. >= duration)
+ {
+ self.source.content_ended = true;
+ continue;
+ }
+ if self.r#loop {
+ let loop_duration = actual_loop_end - actual_loop_start;
+ if loop_duration > 0. {
+ while self.playhead >= actual_loop_end {
+ self.playhead -= loop_duration;
+ }
+ while self.playhead < actual_loop_start && playhead_increment < 0. {
+ self.playhead += loop_duration;
+ }
+ }
+ } else if self.playhead >= buffer_length || (playhead_increment < 0. && self.playhead < 0.) {
+ self.source.content_ended = true;
+ continue;
+ }
+ for channel_index in 0..buffer.channels.len() {
+ source_output.channel_mut(channel_index)[frame] =
+ self.sample_buffer(channel_index, self.playhead, actual_loop_start, actual_loop_end);
+ }
+ self.playhead += playhead_increment;
+ self.played_time += computed_playback_rate.abs() / context.sample_rate;
+ }
+ self.source.update_ended_state(context);
+ }
+ }
+}
+
+impl NodeProcessor for AudioBufferSourceRenderNode {
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ self.source.process(context);
+ unsafe {
+ self.process_source(data, graph, context);
+ }
+ }
+
+ fn handle_message(&mut self, message: &NodeMessage) {
+ match message {
+ NodeMessage::StartBufferSource(start_buffer_source) => {
+ self.source.handle_message(&NodeMessage::StartSource(StartSource {
+ node_id: start_buffer_source.node_id,
+ when: start_buffer_source.when,
+ }));
+ self.offset = start_buffer_source.offset;
+ self.duration = start_buffer_source.duration;
+ if start_buffer_source.buffer.is_some() {
+ self.buffer = start_buffer_source.buffer.clone();
+ }
+ }
+ NodeMessage::SetBufferSourceParameters(set_parameters) => {
+ self.r#loop = set_parameters.r#loop;
+ self.loop_start = set_parameters.loop_start;
+ self.loop_end = set_parameters.loop_end;
+ if set_parameters.update_buffer {
+ self.buffer = set_parameters.buffer.clone();
+ }
+ }
+ _ => self.source.handle_message(message),
+ }
+ }
+
+ fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {
+ callback(&self.playback_rate);
+ callback(&self.detune);
+ }
+
+ fn take_ended_notification(&mut self) -> bool {
+ self.source.take_ended_notification()
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#DelayNode
+struct DelayRenderNode {
+ delay_time: Arc<RenderAudioParam>,
+ delay_values: Vec<f32>,
+ max_delay_time: f64,
+ history: Vec<Vec<f32>>,
+ write_index: usize,
+}
+
+impl NodeProcessor for DelayRenderNode {
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());
+ self.delay_time.compute(graph, context, &mut self.delay_values);
+ let history_length = (self.max_delay_time * context.sample_rate).ceil() as usize + 2;
+ if self.history.len() != input.channel_count()
+ || (!self.history.is_empty() && self.history[0].len() != history_length)
+ {
+ self.history.resize_with(input.channel_count(), Vec::new);
+ for channel_history in &mut self.history {
+ channel_history.clear();
+ channel_history.resize(history_length, 0.);
+ }
+ self.write_index = 0;
+ }
+ let delay_output = BusRef(data.output(0));
+ delay_output.set_channel_count(input.channel_count());
+ for frame in 0..context.quantum_size {
+ let delay_seconds = clamp(f64::from(self.delay_values[frame]), 0., self.max_delay_time);
+ let delay_frames = delay_seconds * context.sample_rate;
+ for channel_index in 0..input.channel_count() {
+ let channel_history = &mut self.history[channel_index];
+ channel_history[self.write_index] = input.channel(channel_index)[frame];
+
+ // Read with linear interpolation to support fractional delays.
+ let mut read_position = self.write_index as f64 - delay_frames;
+ while read_position < 0. {
+ read_position += history_length as f64;
+ }
+ let read_index = read_position as usize;
+ let fraction = (read_position - read_index as f64) as f32;
+ let sample_a = channel_history[read_index % history_length];
+ let sample_b = channel_history[(read_index + 1) % history_length];
+ delay_output.channel_mut(channel_index)[frame] = sample_a + fraction * (sample_b - sample_a);
+ }
+ self.write_index = (self.write_index + 1) % history_length;
+ }
+ }
+ }
+
+ fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {
+ callback(&self.delay_time);
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#StereoPannerNode
+struct StereoPannerRenderNode {
+ pan: Arc<RenderAudioParam>,
+ pan_values: Vec<f32>,
+}
+
+impl NodeProcessor for StereoPannerRenderNode {
+ // https://webaudio.github.io/web-audio-api/#stereopanner-algorithm
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());
+ self.pan.compute(graph, context, &mut self.pan_values);
+ let panner_output = BusRef(data.output(0));
+ panner_output.set_channel_count(2);
+ let output_left = panner_output.channel_mut(0);
+ let output_right = panner_output.channel_mut(1);
+ let input_left = input.channel(0);
+ let input_right = if input.channel_count() > 1 {
+ input.channel(1)
+ } else {
+ input.channel(0)
+ };
+ for frame in 0..context.quantum_size {
+ // Let pan be the computedValue of the pan AudioParam of this StereoPannerNode.
+ // Clamp pan to [-1, 1].
+ let pan = clamp(self.pan_values[frame], -1., 1.);
+
+ // Calculate x by normalizing pan value to [0, 1].
+ let x;
+ if input.channel_count() == 1 {
+ x = f64::from(pan + 1.) / 2.;
+ } else {
+ x = if pan <= 0. { f64::from(pan) + 1. } else { f64::from(pan) };
+ }
+
+ // Left and right gain values are calculated as: gainL = cos(x * π / 2); gainR = sin(x * π / 2);
+ let PanGains {
+ left: gain_left,
+ right: gain_right,
+ } = equal_power_pan_gains(x);
+
+ // For mono input, the stereo output is calculated as: outputL = input * gainL; outputR = input * gainR;
+ // NB: For stereo input, the attenuated channel is mixed into the opposite output channel instead.
+ if input.channel_count() == 1 {
+ output_left[frame] = input_left[frame] * gain_left;
+ output_right[frame] = input_left[frame] * gain_right;
+ } else if pan <= 0. {
+ output_left[frame] = input_left[frame] + input_right[frame] * gain_left;
+ output_right[frame] = input_right[frame] * gain_right;
+ } else {
+ output_left[frame] = input_left[frame] * gain_left;
+ output_right[frame] = input_right[frame] + input_left[frame] * gain_right;
+ }
+ }
+ }
+ }
+
+ fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {
+ callback(&self.pan);
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#ChannelSplitterNode
+struct ChannelSplitterRenderNode;
+
+impl NodeProcessor for ChannelSplitterRenderNode {
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());
+ for output_index in 0..data.output_count() {
+ let output = BusRef(data.output(output_index));
+ let output_samples = output.channel_mut(0);
+ if output_index < input.channel_count() {
+ let input_samples = input.channel(output_index);
+ for frame in 0..context.quantum_size {
+ output_samples[frame] = input_samples[frame];
+ }
+ } else {
+ output_samples.fill(0.);
+ }
+ }
+ }
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#ChannelMergerNode
+struct ChannelMergerRenderNode;
+
+impl NodeProcessor for ChannelMergerRenderNode {
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let merger_output = BusRef(data.output(0));
+ merger_output.set_channel_count(data.input_count());
+ for input_index in 0..data.input_count() {
+ let input = BusRef(data.pull_input(graph, context, input_index).cast_mut());
+ let input_samples = input.channel(0);
+ let output_samples = merger_output.channel_mut(input_index);
+ for frame in 0..context.quantum_size {
+ output_samples[frame] = input_samples[frame];
+ }
+ }
+ }
+ }
+}
+
+#[derive(Default)]
+struct BiquadFilterState {
+ x1: f64,
+ x2: f64,
+ y1: f64,
+ y2: f64,
+}
+
+// https://webaudio.github.io/web-audio-api/#BiquadFilterNode
+struct BiquadFilterRenderNode {
+ frequency: Arc<RenderAudioParam>,
+ detune: Arc<RenderAudioParam>,
+ q: Arc<RenderAudioParam>,
+ gain: Arc<RenderAudioParam>,
+ frequency_values: Vec<f32>,
+ detune_values: Vec<f32>,
+ q_values: Vec<f32>,
+ gain_values: Vec<f32>,
+ r#type: BiquadFilterType,
+ filter_states: Vec<BiquadFilterState>,
+}
+
+impl NodeProcessor for BiquadFilterRenderNode {
+ fn handle_message(&mut self, message: &NodeMessage) {
+ if let NodeMessage::SetBiquadFilterType(set_type) = message {
+ self.r#type = set_type.r#type;
+ }
+ }
+
+ fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {
+ callback(&self.frequency);
+ callback(&self.detune);
+ callback(&self.q);
+ callback(&self.gain);
+ }
+
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());
+ self.frequency.compute(graph, context, &mut self.frequency_values);
+ self.detune.compute(graph, context, &mut self.detune_values);
+ self.q.compute(graph, context, &mut self.q_values);
+ self.gain.compute(graph, context, &mut self.gain_values);
+ if self.filter_states.len() != input.channel_count() {
+ self.filter_states
+ .resize_with(input.channel_count(), BiquadFilterState::default);
+ }
+ let nyquist_frequency = context.sample_rate / 2.;
+ let compute_coefficients_for_frame = |frame: usize| {
+ let computed_frequency =
+ f64::from(self.frequency_values[frame]) * math::exp2(f64::from(self.detune_values[frame]) / 1200.);
+ let normalized_frequency = clamp(computed_frequency / nyquist_frequency, 0., 1.);
+ compute_biquad_coefficients(
+ self.r#type,
+ normalized_frequency,
+ f64::from(self.q_values[frame]),
+ f64::from(self.gain_values[frame]),
+ )
+ };
+ let parameters_changed = |frame: usize| {
+ self.frequency_values[frame] != self.frequency_values[frame - 1]
+ || self.detune_values[frame] != self.detune_values[frame - 1]
+ || self.q_values[frame] != self.q_values[frame - 1]
+ || self.gain_values[frame] != self.gain_values[frame - 1]
+ };
+ let filter_output = BusRef(data.output(0));
+ filter_output.set_channel_count(input.channel_count());
+
+ // AD-HOC: The coefficients are recomputed whenever the computed parameter values change, so a-rate automation is
+ // applied with per-frame resolution while k-rate parameters use a single set of coefficients for the
+ // entire quantum.
+ let mut coefficients = compute_coefficients_for_frame(0);
+ for frame in 0..context.quantum_size {
+ if frame > 0 && parameters_changed(frame) {
+ coefficients = compute_coefficients_for_frame(frame);
+ }
+ for channel_index in 0..input.channel_count() {
+ let state = &mut self.filter_states[channel_index];
+ let x = f64::from(input.channel(channel_index)[frame]);
+ let y = coefficients.b0 * x + coefficients.b1 * state.x1 + coefficients.b2 * state.x2
+ - coefficients.a1 * state.y1
+ - coefficients.a2 * state.y2;
+ state.x2 = state.x1;
+ state.x1 = x;
+ state.y2 = state.y1;
+ state.y1 = y;
+ filter_output.channel_mut(channel_index)[frame] = y as f32;
+ }
+ }
+ }
+ }
+}
+
+// The previous inputs and outputs of the filter for one channel, as ring buffers indexed by the frame number.
+#[derive(Default)]
+struct IIRFilterState {
+ inputs: [f64; 32],
+ outputs: [f64; 32],
+}
+
+// https://webaudio.github.io/web-audio-api/#IIRFilterNode
+struct IIRFilterRenderNode {
+ feedforward: Vec<f64>,
+ feedback: Vec<f64>,
+ filter_states: Vec<IIRFilterState>,
+ position: usize,
+}
+
+impl NodeProcessor for IIRFilterRenderNode {
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());
+
+ // The number of channels of the output always equals the number of channels of the input.
+ let filter_output = BusRef(data.output(0));
+ filter_output.set_channel_count(input.channel_count());
+ if self.filter_states.len() != input.channel_count() {
+ self.filter_states
+ .resize_with(input.channel_count(), IIRFilterState::default);
+ }
+
+ // https://webaudio.github.io/web-audio-api/#IIRFilterNode-filter-definition
+ // sum_{k=0}^{N} a_k y(n-k) = sum_{k=0}^{M} b_k x(n-k), where a_0 is 1 as the coefficients are normalized.
+ const HISTORY_MASK: usize = 31;
+ for channel_index in 0..input.channel_count() {
+ let state = &mut self.filter_states[channel_index];
+ let input_samples = input.channel(channel_index);
+ let output_samples = filter_output.channel_mut(channel_index);
+ let mut position = self.position;
+ for frame in 0..context.quantum_size {
+ let x = f64::from(input_samples[frame]);
+ let mut y = self.feedforward[0] * x;
+ for k in 1..self.feedforward.len() {
+ y += self.feedforward[k] * state.inputs[position.wrapping_sub(k) & HISTORY_MASK];
+ }
+ for k in 1..self.feedback.len() {
+ y -= self.feedback[k] * state.outputs[position.wrapping_sub(k) & HISTORY_MASK];
+ }
+
+ // NB: A decaying output would otherwise settle on subnormal numbers, which are slow to compute with.
+ if y.abs() < f64::MIN_POSITIVE {
+ y = 0.;
+ }
+ state.inputs[position & HISTORY_MASK] = x;
+ state.outputs[position & HISTORY_MASK] = y;
+ output_samples[frame] = y as f32;
+ position = position.wrapping_add(1);
+ }
+ }
+ self.position = self.position.wrapping_add(context.quantum_size);
+ }
+ }
+}
+
+// A lowpass FIR filter that passes the lower half of its band, which is the band of the signal at half its sample
+// rate. Up-sampling by 2 filters the input with zeros between its samples, and down-sampling by 2 keeps every other
+// sample of the filtered signal.
+const HALF_BAND_FILTER_LENGTH: usize = 31;
+
+// NB: The up-sampling and down-sampling filters are not specified. These use a windowed sinc filter whose cutoff is
+// half its band.
+fn half_band_filter_coefficients() -> &'static [f32; HALF_BAND_FILTER_LENGTH] {
+ static COEFFICIENTS: OnceLock<[f32; HALF_BAND_FILTER_LENGTH]> = OnceLock::new();
+ COEFFICIENTS.get_or_init(|| {
+ const LENGTH: usize = HALF_BAND_FILTER_LENGTH;
+ let mut taps = [0.; LENGTH];
+ let mut sum = 0.;
+ for index in 0..LENGTH {
+ let offset = index as f64 - (LENGTH - 1) as f64 / 2.;
+ let sinc = if offset == 0. {
+ 1.
+ } else {
+ math::sin(PI * offset / 2.) / (PI * offset / 2.)
+ };
+ let phase = 2. * PI * index as f64 / (LENGTH - 1) as f64;
+ let blackman_window = 0.42 - 0.5 * math::cos(phase) + 0.08 * math::cos(2. * phase);
+ taps[index] = sinc * blackman_window;
+ sum += taps[index];
+ }
+ let mut result = [0.; LENGTH];
+ for index in 0..LENGTH {
+ result[index] = (taps[index] / sum) as f32;
+ }
+ result
+ })
+}
+
+struct HalfBandFilter {
+ history: [f32; HALF_BAND_FILTER_LENGTH * 2],
+ position: usize,
+}
+
+impl Default for HalfBandFilter {
+ fn default() -> Self {
+ Self {
+ history: [0.; HALF_BAND_FILTER_LENGTH * 2],
+ position: 0,
+ }
+ }
+}
+
+impl HalfBandFilter {
+ fn process(&mut self, sample: f32) -> f32 {
+ let coefficients = half_band_filter_coefficients();
+
+ // NB: Every sample is stored twice, so that the last samples are contiguous wherever the ring buffer starts.
+ self.history[self.position] = sample;
+ self.history[self.position + HALF_BAND_FILTER_LENGTH] = sample;
+ let newest_sample = self.position + HALF_BAND_FILTER_LENGTH;
+ let mut result = 0.;
+ for index in 0..HALF_BAND_FILTER_LENGTH {
+ result += coefficients[index] * self.history[newest_sample - index];
+ }
+ self.position = if self.position + 1 == HALF_BAND_FILTER_LENGTH {
+ 0
+ } else {
+ self.position + 1
+ };
+ result
+ }
+}
+
+#[derive(Default)]
+struct WaveShaperChannelState {
+ up_sampling_filters: [HalfBandFilter; 2],
+ down_sampling_filters: [HalfBandFilter; 2],
+}
+
+// https://webaudio.github.io/web-audio-api/#WaveShaperNode
+struct WaveShaperRenderNode {
+ curve: Option<Arc<WaveShaperCurve>>,
+ oversample: OverSampleType,
+ channel_states: Vec<WaveShaperChannelState>,
+ two_times_samples: Vec<f32>,
+ four_times_samples: Vec<f32>,
+}
+
+impl WaveShaperRenderNode {
+ // https://webaudio.github.io/web-audio-api/#dom-waveshapernode-curve
+ fn shape(&self, sample: f32) -> f32 {
+ // 1. Let x be the input sample, y be the corresponding output of the node, c_k be the k'th element of the curve,
+ // and N be the length of the curve.
+ let curve = &self.curve.as_ref().unwrap().values;
+ let curve_length = curve.len();
+
+ // 2. Let v = (N-1)/2 (x + 1), k = floor(v), f = v - k
+ let v = (curve_length - 1) as f64 / 2. * (f64::from(sample) + 1.);
+
+ // 3. Then y = c_0 if v < 0, c_{N-1} if v >= N - 1, and (1-f) c_k + f c_{k+1} otherwise.
+ // NB: A NaN sample maps to c_0 as well.
+ if !(v >= 0.) {
+ return curve[0];
+ }
+ if v >= (curve_length - 1) as f64 {
+ return *curve.last().unwrap();
+ }
+ let k = v as usize;
+ let f = v - k as f64;
+ ((1. - f) * f64::from(curve[k]) + f * f64::from(curve[k + 1])) as f32
+ }
+
+ fn up_sample(filter: &mut HalfBandFilter, input: &[f32], output: &mut [f32]) {
+ assert_eq!(output.len(), input.len() * 2);
+
+ // NB: The zeros between the samples halve the gain of the filter, which the factor of 2 restores.
+ for index in 0..input.len() {
+ output[2 * index] = 2. * filter.process(input[index]);
+ output[2 * index + 1] = 2. * filter.process(0.);
+ }
+ }
+
+ fn down_sample(filter: &mut HalfBandFilter, input: &[f32], output: &mut [f32]) {
+ assert_eq!(input.len(), output.len() * 2);
+ for index in 0..output.len() {
+ output[index] = filter.process(input[2 * index]);
+ let _ = filter.process(input[2 * index + 1]);
+ }
+ }
+}
+
+impl NodeProcessor for WaveShaperRenderNode {
+ fn handle_message(&mut self, message: &NodeMessage) {
+ if let NodeMessage::SetWaveShaperParameters(parameters) = message {
+ self.curve = parameters.curve.clone();
+ self.oversample = parameters.oversample;
+ }
+ }
+
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());
+
+ // The number of channels of the output always equals the number of channels of the input.
+ let shaper_output = BusRef(data.output(0));
+ shaper_output.set_channel_count(input.channel_count());
+ if self.channel_states.len() != input.channel_count() {
+ self.channel_states
+ .resize_with(input.channel_count(), WaveShaperChannelState::default);
+ }
+ for channel_index in 0..input.channel_count() {
+ let input_samples = &input.channel(channel_index)[..context.quantum_size];
+ let output_samples = &mut shaper_output.channel_mut(channel_index)[..context.quantum_size];
+
+ // Initially the curve attribute is null, which means that the WaveShaperNode will pass its input to its output
+ // without modification.
+ if self.curve.is_none() {
+ output_samples.copy_from_slice(input_samples);
+ continue;
+ }
+ match self.oversample {
+ OverSampleType::None => {
+ // The default value is "none", meaning the curve will be applied directly to the input samples.
+ for frame in 0..context.quantum_size {
+ output_samples[frame] = self.shape(input_samples[frame]);
+ }
+ }
+ OverSampleType::_2x => {
+ // 1. Up-sample the input samples to 2x or 4x the sample-rate of the AudioContext. Thus for each render
+ // quantum, generate twice (for 2x) or four times (for 4x) samples.
+ Self::up_sample(
+ &mut self.channel_states[channel_index].up_sampling_filters[0],
+ input_samples,
+ &mut self.two_times_samples,
+ );
+
+ // 2. Apply the shaping curve.
+ for index in 0..self.two_times_samples.len() {
+ self.two_times_samples[index] = self.shape(self.two_times_samples[index]);
+ }
+
+ // 3. Down-sample the result back to the sample-rate of the AudioContext. Thus taking the previously
+ // processed samples processed samples, generating a single render quantum worth of samples as the
+ // final result.
+ Self::down_sample(
+ &mut self.channel_states[channel_index].down_sampling_filters[0],
+ &self.two_times_samples,
+ output_samples,
+ );
+ }
+ OverSampleType::_4x => {
+ // 1. Up-sample the input samples to 2x or 4x the sample-rate of the AudioContext. Thus for each render
+ // quantum, generate twice (for 2x) or four times (for 4x) samples.
+ Self::up_sample(
+ &mut self.channel_states[channel_index].up_sampling_filters[0],
+ input_samples,
+ &mut self.two_times_samples,
+ );
+ Self::up_sample(
+ &mut self.channel_states[channel_index].up_sampling_filters[1],
+ &self.two_times_samples,
+ &mut self.four_times_samples,
+ );
+
+ // 2. Apply the shaping curve.
+ for index in 0..self.four_times_samples.len() {
+ self.four_times_samples[index] = self.shape(self.four_times_samples[index]);
+ }
+
+ // 3. Down-sample the result back to the sample-rate of the AudioContext. Thus taking the previously
+ // processed samples processed samples, generating a single render quantum worth of samples as the
+ // final result.
+ Self::down_sample(
+ &mut self.channel_states[channel_index].down_sampling_filters[1],
+ &self.four_times_samples,
+ &mut self.two_times_samples,
+ );
+ Self::down_sample(
+ &mut self.channel_states[channel_index].down_sampling_filters[0],
+ &self.two_times_samples,
+ output_samples,
+ );
+ }
+ }
+ }
+ }
+ }
+}
+
+#[derive(Clone, Copy, Default)]
+struct DoubleVector3([f64; 3]);
+
+impl DoubleVector3 {
+ fn dot(self, other: Self) -> f64 {
+ let mut result = 0.;
+ for i in 0..3 {
+ result += self.0[i] * other.0[i];
+ }
+ result
+ }
+
+ fn length(self) -> f64 {
+ self.dot(self).sqrt()
+ }
+
+ fn normalized(self) -> Self {
+ let inverse_length = 1. / self.length();
+ self * inverse_length
+ }
+
+ fn cross(self, other: Self) -> Self {
+ let [x, y, z] = self.0;
+ let [ox, oy, oz] = other.0;
+ Self([y * oz - z * oy, z * ox - x * oz, x * oy - y * ox])
+ }
+}
+
+impl std::ops::Sub for DoubleVector3 {
+ type Output = Self;
+
+ fn sub(self, other: Self) -> Self {
+ Self(std::array::from_fn(|i| self.0[i] - other.0[i]))
+ }
+}
+
+impl std::ops::Mul<f64> for DoubleVector3 {
+ type Output = Self;
+
+ fn mul(self, scalar: f64) -> Self {
+ Self(std::array::from_fn(|i| self.0[i] * scalar))
+ }
+}
+
+// Gfx::DoubleVector3::normalize() divides by the length unconditionally, which would produce NaN components for a zero
+// vector; the spatialization math needs a zero vector to normalize back to a zero vector instead.
+fn safe_normalized(vector: DoubleVector3) -> DoubleVector3 {
+ if vector.length() == 0. {
+ return DoubleVector3::default();
+ }
+ vector.normalized()
+}
+
+// https://webaudio.github.io/web-audio-api/#azimuth-elevation
+fn compute_azimuth(
+ source_position: DoubleVector3,
+ listener_position: DoubleVector3,
+ listener_forward: DoubleVector3,
+ listener_up: DoubleVector3,
+) -> f64 {
+ // Calculate the source-listener vector.
+ let mut source_listener = source_position - listener_position;
+
+ // Handle degenerate case if source and listener are at the same point.
+ if source_listener.length() == 0. {
+ return 0.;
+ }
+ source_listener = source_listener.normalized();
+
+ // Align axes.
+ let listener_right = listener_forward.cross(listener_up);
+
+ // Handle the case where listener's 'up' and 'forward' vectors are linearly dependent, in which case 'right'
+ // cannot be determined.
+ if listener_right.length() == 0. {
+ return 0.;
+ }
+
+ // Determine a unit vector orthogonal to listener's right, forward.
+ let listener_right_norm = listener_right.normalized();
+ let listener_forward_norm = safe_normalized(listener_forward);
+ let up = listener_right_norm.cross(listener_forward_norm);
+ let up_projection = source_listener.dot(up);
+ let mut projected_source = source_listener - up * up_projection;
+ projected_source = safe_normalized(projected_source);
+ let mut azimuth = 180. * math::acos(clamp(projected_source.dot(listener_right_norm), -1., 1.)) / PI;
+
+ // Source in front or behind the listener.
+ let front_back = projected_source.dot(listener_forward_norm);
+ if front_back < 0. {
+ azimuth = 360. - azimuth;
+ }
+
+ // Make azimuth relative to "forward" and not "right" listener vector.
+ // AD-HOC: This is equivalent to the spec's mapping, but lands directly in the range [-180, 180].
+ if azimuth <= 90. {
+ azimuth = 90. - azimuth;
+ } else {
+ azimuth = 450. - azimuth;
+ }
+ if azimuth > 180. {
+ azimuth -= 360.;
+ }
+ azimuth
+}
+
+// https://webaudio.github.io/web-audio-api/#Spatialization-distance-effects
+fn compute_distance_gain(distance: f64, config: &SetPannerParameters) -> f64 {
+ let ref_distance = config.ref_distance;
+ let max_distance = config.max_distance;
+ let rolloff_factor = config.rolloff_factor;
+
+ // AD-HOC: The distance is clamped to the interval spanned by refDistance and maxDistance for every distance
+ // model, matching other engines.
+ let clamped_distance = clamp(
+ distance,
+ cpp_min(ref_distance, max_distance),
+ cpp_max(ref_distance, max_distance),
+ );
+ match config.distance_model {
+ DistanceModelType::Linear => {
+ if ref_distance == max_distance {
+ return 1. - clamp(rolloff_factor, 0., 1.);
+ }
+ 1. - clamp(rolloff_factor, 0., 1.) * (clamped_distance - ref_distance) / (max_distance - ref_distance)
+ }
+ DistanceModelType::Inverse => {
+ if ref_distance + rolloff_factor * (clamped_distance - ref_distance) == 0. {
+ return 1.;
+ }
+ ref_distance / (ref_distance + rolloff_factor * (clamped_distance - ref_distance))
+ }
+ DistanceModelType::Exponential => {
+ if ref_distance == 0. {
+ return 1.;
+ }
+ math::pow(clamped_distance / ref_distance, -rolloff_factor)
+ }
+ }
+}
+
+// https://webaudio.github.io/web-audio-api/#Spatialization-sound-cones
+fn compute_cone_gain(
+ source_position: DoubleVector3,
+ source_orientation: DoubleVector3,
+ listener_position: DoubleVector3,
+ config: &SetPannerParameters,
+) -> f64 {
+ if source_orientation.length() == 0. || (config.cone_inner_angle == 360. && config.cone_outer_angle == 360.) {
+ return 1.;
+ }
+
+ // Normalized source-listener vector.
+ let source_to_listener = safe_normalized(listener_position - source_position);
+ let normalized_source_orientation = source_orientation.normalized();
+
+ // Angle between the source orientation vector and the source-listener vector.
+ let angle = 180. * math::acos(clamp(source_to_listener.dot(normalized_source_orientation), -1., 1.)) / PI;
+ let absolute_angle = angle.abs();
+
+ // Divide by 2 here since API is entire angle (not half-angle).
+ let absolute_inner_angle = config.cone_inner_angle.abs() / 2.;
+ let absolute_outer_angle = config.cone_outer_angle.abs() / 2.;
+ if absolute_angle <= absolute_inner_angle {
+ // No attenuation.
+ return 1.;
+ }
+ if absolute_angle >= absolute_outer_angle {
+ // Max attenuation.
+ return config.cone_outer_gain;
+ }
+
+ // Between inner and outer cones: inner -> outer, x goes from 0 -> 1.
+ let x = (absolute_angle - absolute_inner_angle) / (absolute_outer_angle - absolute_inner_angle);
+ 1. + (config.cone_outer_gain - 1.) * x
+}
+
+// Which impulse response channel is convolved with which input channel, and where the result is summed into.
+// https://webaudio.github.io/web-audio-api/#Convolution-channel-configurations
+#[derive(Clone, Copy, Default)]
+struct Route {
+ input_channel: usize,
+ kernel_channel: usize,
+ output_channel: usize,
+}
+
+// Convolves the input with an impulse response. The head of the impulse response is convolved directly, and the rest
+// through uniformly partitioned overlap-save convolution: every quantum, the window spanning the previous and the
+// current quantum is transformed and pushed into a frequency delay line, whose spectra are then multiplied with the
+// impulse response partitions and summed. That keeps the cost per quantum constant and adds no latency, at the price of
+// transforming a window that is only half new each time.
+// https://webaudio.github.io/web-audio-api/#ConvolverNode
+struct ConvolverRenderNode {
+ fft: FFT,
+ kernel: Option<Arc<ConvolverKernel>>,
+ delay_line: Option<Arc<super::convolver_kernel::ConvolverDelayLine>>,
+
+ // The slot of the delay line that holds the spectrum of the current quantum's window.
+ delay_line_index: usize,
+
+ // The previous and the current quantum's samples for each input channel, which the direct convolution reaches back
+ // into and which the transform consumes as a whole.
+ window: [Vec<f32>; 2],
+ input_channel_count: usize,
+ transform_real: Vec<f32>,
+ transform_imag: Vec<f32>,
+
+ // The partition sums are accumulated in double precision: a long impulse response adds up hundreds of partitions
+ // per bin, and single precision loses too much of the quiet parts of the result.
+ accumulator_real: Vec<f64>,
+ accumulator_imag: Vec<f64>,
+}
+
+// Folds a second channel's history into the first the way down-mixing folds the channels themselves.
+fn average_history(into: &mut [f32], other: &[f32]) {
+ for index in 0..into.len() {
+ into[index] = 0.5 * (into[index] + other[index]);
+ }
+}
+
+impl NodeProcessor for ConvolverRenderNode {
+ fn handle_message(&mut self, message: &NodeMessage) {
+ if let NodeMessage::SetConvolverKernel(set_kernel) = message {
+ self.kernel = set_kernel.kernel.clone();
+ self.delay_line = set_kernel.delay_line.clone();
+ self.delay_line_index = 0;
+ }
+ }
+
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());
+ let convolver_output = BusRef(data.output(0));
+ let input_channel_count = input
+ .channel_count()
+ .min(super::convolver_kernel::ConvolverDelayLine::MAX_CHANNEL_COUNT);
+
+ // Mix the history the same way the input itself is mixed, so that the tail of the impulse response keeps playing
+ // across a change in the number of input channels.
+ // https://webaudio.github.io/web-audio-api/#channel-up-mixing-and-down-mixing
+ if self.input_channel_count == 1 && input_channel_count == 2 {
+ let [left, right] = &mut self.window;
+ right.copy_from_slice(left);
+ if let Some(delay_line) = &self.delay_line {
+ delay_line.real_shared(1).copy_from_slice(delay_line.real_shared(0));
+ delay_line.imag_shared(1).copy_from_slice(delay_line.imag_shared(0));
+ }
+ } else if self.input_channel_count == 2 && input_channel_count == 1 {
+ let [left, right] = &mut self.window;
+ average_history(left, right);
+ if let Some(delay_line) = &self.delay_line {
+ average_history(delay_line.real_shared(0), delay_line.real_shared(1));
+ average_history(delay_line.imag_shared(0), delay_line.imag_shared(1));
+ }
+ }
+ self.input_channel_count = input_channel_count;
+ let partition_size = context.quantum_size;
+ for channel in 0..input_channel_count {
+ // Slide this quantum's samples into the window, dropping the oldest half.
+ let window = &mut self.window[channel];
+ let input_samples = input.channel(channel);
+ for frame in 0..partition_size {
+ window[frame] = window[partition_size + frame];
+ window[partition_size + frame] = input_samples[frame];
+ }
+ }
+ let Some(kernel) = &self.kernel else {
+ convolver_output.set_channel_count(1);
+ convolver_output.zero();
+ return;
+ };
+ let transform_size = self.fft.size();
+ let partition_count = kernel.partition_count();
+ let delay_line = self.delay_line.as_ref().unwrap();
+ let delay_line_length = delay_line.length();
+ let bin_count = kernel.bin_count();
+ if partition_count > 0 {
+ for channel in 0..input_channel_count {
+ let window = &self.window[channel];
+ for frame in 0..transform_size {
+ self.transform_real[frame] = window[frame];
+ self.transform_imag[frame] = 0.;
+ }
+ self.fft.transform(
+ &mut self.transform_real,
+ &mut self.transform_imag,
+ FFTDirection::Forward,
+ );
+ let offset = self.delay_line_index * bin_count;
+ let delay_line_real = &mut delay_line.real_shared(channel)[offset..];
+ let delay_line_imag = &mut delay_line.imag_shared(channel)[offset..];
+ for bin in 0..bin_count {
+ delay_line_real[bin] = self.transform_real[bin];
+ delay_line_imag[bin] = self.transform_imag[bin];
+ }
+ }
+ }
+
+ // https://webaudio.github.io/web-audio-api/#Convolution-channel-configurations
+ let right_channel = if input_channel_count > 1 { 1 } else { 0 };
+ let mut routes = [Route::default(); 4];
+ let mut route_count = 0;
+ match kernel.channel_count() {
+ 1 => {
+ routes[route_count] = Route {
+ input_channel: 0,
+ kernel_channel: 0,
+ output_channel: 0,
+ };
+ route_count += 1;
+ if input_channel_count > 1 {
+ routes[route_count] = Route {
+ input_channel: 1,
+ kernel_channel: 0,
+ output_channel: 1,
+ };
+ route_count += 1;
+ }
+ }
+ 2 => {
+ routes[route_count] = Route {
+ input_channel: 0,
+ kernel_channel: 0,
+ output_channel: 0,
+ };
+ route_count += 1;
+ routes[route_count] = Route {
+ input_channel: right_channel,
+ kernel_channel: 1,
+ output_channel: 1,
+ };
+ route_count += 1;
+ }
+ 4 => {
+ routes[route_count] = Route {
+ input_channel: 0,
+ kernel_channel: 0,
+ output_channel: 0,
+ };
+ route_count += 1;
+ routes[route_count] = Route {
+ input_channel: 0,
+ kernel_channel: 1,
+ output_channel: 1,
+ };
+ route_count += 1;
+ routes[route_count] = Route {
+ input_channel: right_channel,
+ kernel_channel: 2,
+ output_channel: 0,
+ };
+ route_count += 1;
+ routes[route_count] = Route {
+ input_channel: right_channel,
+ kernel_channel: 3,
+ output_channel: 1,
+ };
+ route_count += 1;
+ }
+ _ => unreachable!(),
+ }
+ let output_channel_count = if kernel.channel_count() == 1 && input_channel_count == 1 {
+ 1
+ } else {
+ 2
+ };
+ convolver_output.set_channel_count(output_channel_count);
+ for output_channel in 0..output_channel_count {
+ let output_samples = convolver_output.channel_mut(output_channel);
+ for frame in 0..partition_size {
+ output_samples[frame] = 0.;
+ }
+ for bin in 0..bin_count {
+ self.accumulator_real[bin] = 0.;
+ self.accumulator_imag[bin] = 0.;
+ }
+ for route_index in 0..route_count {
+ let route = routes[route_index];
+ if route.output_channel != output_channel {
+ continue;
+ }
+ let window = &self.window[route.input_channel];
+ let head = kernel.head(route.kernel_channel);
+ for frame in 0..partition_size {
+ let mut sample = 0_f32;
+ for tap in 0..partition_size {
+ sample += head[tap] * window[partition_size + frame - tap];
+ }
+ output_samples[frame] += sample;
+ }
+ let delay_line_real = delay_line.real_shared(route.input_channel);
+ let delay_line_imag = delay_line.imag_shared(route.input_channel);
+ for partition in 0..partition_count {
+ // Partition N of the impulse response pairs up with the window from N + 1 quanta ago.
+ let delay_line_slot =
+ (self.delay_line_index + delay_line_length - partition - 1) % delay_line_length;
+ let input_real = &delay_line_real[delay_line_slot * bin_count..];
+ let input_imag = &delay_line_imag[delay_line_slot * bin_count..];
+ let kernel_real = kernel.partition_real(route.kernel_channel, partition);
+ let kernel_imag = kernel.partition_imag(route.kernel_channel, partition);
+ for bin in 0..bin_count {
+ self.accumulator_real[bin] +=
+ f64::from(input_real[bin] * kernel_real[bin] - input_imag[bin] * kernel_imag[bin]);
+ self.accumulator_imag[bin] +=
+ f64::from(input_real[bin] * kernel_imag[bin] + input_imag[bin] * kernel_real[bin]);
+ }
+ }
+ }
+ if partition_count == 0 {
+ continue;
+ }
+
+ // Restore the bins above Nyquist that the kernel and the delay line leave out.
+ for bin in 0..bin_count {
+ self.transform_real[bin] = self.accumulator_real[bin] as f32;
+ self.transform_imag[bin] = self.accumulator_imag[bin] as f32;
+ }
+ for bin in bin_count..transform_size {
+ self.transform_real[bin] = self.accumulator_real[transform_size - bin] as f32;
+ self.transform_imag[bin] = -self.accumulator_imag[transform_size - bin] as f32;
+ }
+ self.fft.transform(
+ &mut self.transform_real,
+ &mut self.transform_imag,
+ FFTDirection::Inverse,
+ );
+
+ // The first half of the result is where the cyclic convolution wrapped around, and is discarded.
+ for frame in 0..partition_size {
+ output_samples[frame] += self.transform_real[partition_size + frame];
+ }
+ }
+ if partition_count > 0 {
+ self.delay_line_index = (self.delay_line_index + 1) % delay_line_length;
+ }
+ }
+ }
+}
+
+struct PannerParams {
+ position_x: Arc<RenderAudioParam>,
+ position_y: Arc<RenderAudioParam>,
+ position_z: Arc<RenderAudioParam>,
+ orientation_x: Arc<RenderAudioParam>,
+ orientation_y: Arc<RenderAudioParam>,
+ orientation_z: Arc<RenderAudioParam>,
+}
+
+struct ListenerParams {
+ position_x: Arc<RenderAudioParam>,
+ position_y: Arc<RenderAudioParam>,
+ position_z: Arc<RenderAudioParam>,
+ forward_x: Arc<RenderAudioParam>,
+ forward_y: Arc<RenderAudioParam>,
+ forward_z: Arc<RenderAudioParam>,
+ up_x: Arc<RenderAudioParam>,
+ up_y: Arc<RenderAudioParam>,
+ up_z: Arc<RenderAudioParam>,
+}
+
+// https://webaudio.github.io/web-audio-api/#PannerNode
+struct PannerRenderNode {
+ params: PannerParams,
+ listener_params: ListenerParams,
+ config: SetPannerParameters,
+
+ // One buffer of computed values per panner and listener param, in the order of the Params and ListenerParams
+ // struct members.
+ param_values: Vec<Vec<f32>>,
+}
+
+impl NodeProcessor for PannerRenderNode {
+ fn handle_message(&mut self, message: &NodeMessage) {
+ if let NodeMessage::SetPannerParameters(parameters) = message {
+ self.config = *parameters;
+ }
+ }
+
+ fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {
+ callback(&self.params.position_x);
+ callback(&self.params.position_y);
+ callback(&self.params.position_z);
+ callback(&self.params.orientation_x);
+ callback(&self.params.orientation_y);
+ callback(&self.params.orientation_z);
+ }
+
+ // https://webaudio.github.io/web-audio-api/#Spatialization
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());
+ let panner_output = BusRef(data.output(0));
+ panner_output.set_channel_count(2);
+ if input.is_silent() {
+ panner_output.zero();
+ return;
+ }
+ let params = [
+ &self.params.position_x,
+ &self.params.position_y,
+ &self.params.position_z,
+ &self.params.orientation_x,
+ &self.params.orientation_y,
+ &self.params.orientation_z,
+ &self.listener_params.position_x,
+ &self.listener_params.position_y,
+ &self.listener_params.position_z,
+ &self.listener_params.forward_x,
+ &self.listener_params.forward_y,
+ &self.listener_params.forward_z,
+ &self.listener_params.up_x,
+ &self.listener_params.up_y,
+ &self.listener_params.up_z,
+ ];
+ for param_index in 0..params.len() {
+ params[param_index].compute(graph, context, &mut self.param_values[param_index]);
+ }
+ let output_left = panner_output.channel_mut(0);
+ let output_right = panner_output.channel_mut(1);
+ let input_left = input.channel(0);
+ let input_right = if input.channel_count() > 1 {
+ input.channel(1)
+ } else {
+ input.channel(0)
+ };
+ for frame in 0..context.quantum_size {
+ let source_position = DoubleVector3([
+ f64::from(self.param_values[0][frame]),
+ f64::from(self.param_values[1][frame]),
+ f64::from(self.param_values[2][frame]),
+ ]);
+ let source_orientation = DoubleVector3([
+ f64::from(self.param_values[3][frame]),
+ f64::from(self.param_values[4][frame]),
+ f64::from(self.param_values[5][frame]),
+ ]);
+ let listener_position = DoubleVector3([
+ f64::from(self.param_values[6][frame]),
+ f64::from(self.param_values[7][frame]),
+ f64::from(self.param_values[8][frame]),
+ ]);
+ let listener_forward = DoubleVector3([
+ f64::from(self.param_values[9][frame]),
+ f64::from(self.param_values[10][frame]),
+ f64::from(self.param_values[11][frame]),
+ ]);
+ let listener_up = DoubleVector3([
+ f64::from(self.param_values[12][frame]),
+ f64::from(self.param_values[13][frame]),
+ f64::from(self.param_values[14][frame]),
+ ]);
+ let mut azimuth = compute_azimuth(source_position, listener_position, listener_forward, listener_up);
+ let distance = (source_position - listener_position).length();
+ let gain = (compute_distance_gain(distance, &self.config)
+ * compute_cone_gain(source_position, source_orientation, listener_position, &self.config))
+ as f32;
+
+ // https://webaudio.github.io/web-audio-api/#Spatialization-panning-algorithm
+ // The azimuth value is first contained to be within the range [-90, 90].
+ // NB: compute_azimuth() already produces a value in [-180, 180], so only the wrapping step remains.
+ if azimuth < -90. {
+ azimuth = -180. - azimuth;
+ } else if azimuth > 90. {
+ azimuth = 180. - azimuth;
+ }
+ let x;
+ if input.channel_count() == 1 {
+ x = (azimuth + 90.) / 180.;
+ } else {
+ x = if azimuth <= 0. {
+ (azimuth + 90.) / 90.
+ } else {
+ azimuth / 90.
+ };
+ }
+ let PanGains {
+ left: gain_left,
+ right: gain_right,
+ } = equal_power_pan_gains(x);
+ if input.channel_count() == 1 {
+ output_left[frame] = input_left[frame] * gain_left * gain;
+ output_right[frame] = input_left[frame] * gain_right * gain;
+ } else if azimuth <= 0. {
+ output_left[frame] = (input_left[frame] + input_right[frame] * gain_left) * gain;
+ output_right[frame] = input_right[frame] * gain_right * gain;
+ } else {
+ output_left[frame] = input_left[frame] * gain_left * gain;
+ output_right[frame] = (input_right[frame] + input_left[frame] * gain_right) * gain;
+ }
+ }
+ }
+ }
+}
+
+// Passes the input through unchanged; used for nodes whose processing is not implemented yet but which should not
+// silence the signal path, like DynamicsCompressorNode.
+struct PassthroughRenderNode;
+
+impl NodeProcessor for PassthroughRenderNode {
+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {
+ unsafe {
+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());
+ BusRef(data.output(0)).copy_from(&input);
+ }
+ }
+}
+
+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(
+ node_id: u64,
+ quantum_size: usize,
+ channel_count: usize,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, 1, 1, quantum_size, channel_count);
+ data.channel_count.set(channel_count);
+ data.channel_count_mode.set(ChannelCountMode::Explicit);
+ node_handle(data, DestinationRenderNode)
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_create_gain(
+ node_id: u64,
+ quantum_size: usize,
+ gain: *const RenderAudioParam,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ node_handle(
+ data,
+ GainRenderNode {
+ gain: unsafe { clone_arc(gain) },
+ gain_values: vec![0.; quantum_size],
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_create_constant_source(
+ node_id: u64,
+ quantum_size: usize,
+ offset: *const RenderAudioParam,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, 0, 1, quantum_size, 1);
+ node_handle(
+ data,
+ ConstantSourceRenderNode {
+ source: ScheduledSourceRenderNode::default(),
+ offset: unsafe { clone_arc(offset) },
+ offset_values: vec![0.; quantum_size],
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_create_oscillator(
+ node_id: u64,
+ quantum_size: usize,
+ frequency: *const RenderAudioParam,
+ detune: *const RenderAudioParam,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, 0, 1, quantum_size, 1);
+ node_handle(
+ data,
+ OscillatorRenderNode {
+ source: ScheduledSourceRenderNode::default(),
+ frequency: unsafe { clone_arc(frequency) },
+ detune: unsafe { clone_arc(detune) },
+ frequency_values: vec![0.; quantum_size],
+ detune_values: vec![0.; quantum_size],
+ r#type: OscillatorType::Sine,
+ periodic_wave: None,
+ periodic_wave_scale: 1.,
+ phase: 0.,
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_create_audio_buffer_source(
+ node_id: u64,
+ quantum_size: usize,
+ playback_rate: *const RenderAudioParam,
+ detune: *const RenderAudioParam,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, 0, 1, quantum_size, 1);
+ node_handle(
+ data,
+ AudioBufferSourceRenderNode {
+ source: ScheduledSourceRenderNode::default(),
+ playback_rate: unsafe { clone_arc(playback_rate) },
+ detune: unsafe { clone_arc(detune) },
+ playback_rate_values: vec![0.; quantum_size],
+ detune_values: vec![0.; quantum_size],
+ buffer: None,
+ r#loop: false,
+ loop_start: 0.,
+ loop_end: 0.,
+ offset: 0.,
+ duration: None,
+ playhead: 0.,
+ playhead_valid: false,
+ played_time: 0.,
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_create_delay(
+ node_id: u64,
+ quantum_size: usize,
+ delay_time: *const RenderAudioParam,
+ max_delay_time: f64,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ node_handle(
+ data,
+ DelayRenderNode {
+ delay_time: unsafe { clone_arc(delay_time) },
+ delay_values: vec![0.; quantum_size],
+ max_delay_time,
+ history: Vec::new(),
+ write_index: 0,
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_create_stereo_panner(
+ node_id: u64,
+ quantum_size: usize,
+ pan: *const RenderAudioParam,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 2);
+ data.channel_count_mode.set(ChannelCountMode::ClampedMax);
+ node_handle(
+ data,
+ StereoPannerRenderNode {
+ pan: unsafe { clone_arc(pan) },
+ pan_values: vec![0.; quantum_size],
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_create_channel_splitter(
+ node_id: u64,
+ quantum_size: usize,
+ number_of_outputs: usize,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, 1, number_of_outputs, quantum_size, 1);
+ data.channel_count.set(number_of_outputs);
+ data.channel_count_mode.set(ChannelCountMode::Explicit);
+ data.channel_interpretation.set(ChannelInterpretation::Discrete);
+ node_handle(data, ChannelSplitterRenderNode)
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_create_channel_merger(
+ node_id: u64,
+ quantum_size: usize,
+ number_of_inputs: usize,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, number_of_inputs, 1, quantum_size, number_of_inputs);
+ data.channel_count.set(1);
+ data.channel_count_mode.set(ChannelCountMode::Explicit);
+ node_handle(data, ChannelMergerRenderNode)
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_create_biquad_filter(
+ node_id: u64,
+ quantum_size: usize,
+ frequency: *const RenderAudioParam,
+ detune: *const RenderAudioParam,
+ q: *const RenderAudioParam,
+ gain: *const RenderAudioParam,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ node_handle(
+ data,
+ BiquadFilterRenderNode {
+ frequency: unsafe { clone_arc(frequency) },
+ detune: unsafe { clone_arc(detune) },
+ q: unsafe { clone_arc(q) },
+ gain: unsafe { clone_arc(gain) },
+ frequency_values: vec![0.; quantum_size],
+ detune_values: vec![0.; quantum_size],
+ q_values: vec![0.; quantum_size],
+ gain_values: vec![0.; quantum_size],
+ r#type: BiquadFilterType::Lowpass,
+ filter_states: Vec::new(),
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_create_iir_filter(
+ node_id: u64,
+ quantum_size: usize,
+ feedforward: Span<'_, f64>,
+ feedback: Span<'_, f64>,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ assert!(feedforward.as_slice().len() < 32);
+ assert!(feedback.as_slice().len() < 32);
+ node_handle(
+ data,
+ IIRFilterRenderNode {
+ feedforward: feedforward.as_slice().to_vec(),
+ feedback: feedback.as_slice().to_vec(),
+ filter_states: Vec::new(),
+ position: 0,
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe 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,
+ WaveShaperRenderNode {
+ curve: None,
+ oversample: OverSampleType::None,
+ channel_states: Vec::new(),
+ two_times_samples: vec![0.; quantum_size * 2],
+ four_times_samples: vec![0.; quantum_size * 4],
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe 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(
+ data,
+ ConvolverRenderNode {
+ fft: FFT::new(2 * quantum_size),
+ kernel: None,
+ delay_line: None,
+ delay_line_index: 0,
+ window: std::array::from_fn(|_| vec![0.; 2 * quantum_size]),
+ input_channel_count: 0,
+ transform_real: vec![0.; 2 * quantum_size],
+ transform_imag: vec![0.; 2 * quantum_size],
+ accumulator_real: vec![0.; quantum_size + 1],
+ accumulator_imag: vec![0.; quantum_size + 1],
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_node_create_panner(
+ node_id: u64,
+ quantum_size: usize,
+ params: Span<'_, *const RenderAudioParam>,
+) -> *mut NodeHandle {
+ let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 2);
+ data.channel_count_mode.set(ChannelCountMode::ClampedMax);
+ let params = params.as_slice();
+ assert_eq!(params.len(), 15);
+ node_handle(
+ data,
+ PannerRenderNode {
+ params: PannerParams {
+ position_x: unsafe { clone_arc(params[0]) },
+ position_y: unsafe { clone_arc(params[1]) },
+ position_z: unsafe { clone_arc(params[2]) },
+ orientation_x: unsafe { clone_arc(params[3]) },
+ orientation_y: unsafe { clone_arc(params[4]) },
+ orientation_z: unsafe { clone_arc(params[5]) },
+ },
+ listener_params: ListenerParams {
+ position_x: unsafe { clone_arc(params[6]) },
+ position_y: unsafe { clone_arc(params[7]) },
+ position_z: unsafe { clone_arc(params[8]) },
+ forward_x: unsafe { clone_arc(params[9]) },
+ forward_y: unsafe { clone_arc(params[10]) },
+ forward_z: unsafe { clone_arc(params[11]) },
+ up_x: unsafe { clone_arc(params[12]) },
+ up_y: unsafe { clone_arc(params[13]) },
+ up_z: unsafe { clone_arc(params[14]) },
+ },
+ config: SetPannerParameters::default(),
+ param_values: (0..15).map(|_| vec![0.; quantum_size]).collect(),
+ },
+ )
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe 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/WebAudio/ControlMessageQueue.cpp b/Libraries/LibWeb/WebAudio/ControlMessageQueue.cpp
index 29ff824b0f4..44a7888dde8 100644
--- a/Libraries/LibWeb/WebAudio/ControlMessageQueue.cpp
+++ b/Libraries/LibWeb/WebAudio/ControlMessageQueue.cpp
@@ -1,22 +1,80 @@
/*
* Copyright (c) 2025, Ben Eidson <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibWeb/WebAudio/ControlMessageQueue.h>
+#include <LibWeb/WebAudio/RustFFI.h>
namespace Web::WebAudio {
-void ControlMessageQueue::enqueue(ControlMessage message)
+static_assert(to_underlying(Bindings::ChannelCountMode::Max) == to_underlying(RustFFI::ChannelCountMode::Max));
+static_assert(to_underlying(Bindings::ChannelCountMode::ClampedMax) == to_underlying(RustFFI::ChannelCountMode::ClampedMax));
+static_assert(to_underlying(Bindings::ChannelCountMode::Explicit) == to_underlying(RustFFI::ChannelCountMode::Explicit));
+static_assert(to_underlying(Bindings::ChannelInterpretation::Speakers) == to_underlying(RustFFI::ChannelInterpretation::Speakers));
+static_assert(to_underlying(Bindings::ChannelInterpretation::Discrete) == to_underlying(RustFFI::ChannelInterpretation::Discrete));
+static_assert(to_underlying(Bindings::OscillatorType::Sine) == to_underlying(RustFFI::OscillatorType::Sine));
+static_assert(to_underlying(Bindings::OscillatorType::Square) == to_underlying(RustFFI::OscillatorType::Square));
+static_assert(to_underlying(Bindings::OscillatorType::Sawtooth) == to_underlying(RustFFI::OscillatorType::Sawtooth));
+static_assert(to_underlying(Bindings::OscillatorType::Triangle) == to_underlying(RustFFI::OscillatorType::Triangle));
+static_assert(to_underlying(Bindings::OscillatorType::Custom) == to_underlying(RustFFI::OscillatorType::Custom));
+static_assert(to_underlying(Bindings::PanningModelType::Equalpower) == to_underlying(RustFFI::PanningModelType::Equalpower));
+static_assert(to_underlying(Bindings::PanningModelType::HRTF) == to_underlying(RustFFI::PanningModelType::HRTF));
+static_assert(to_underlying(Bindings::DistanceModelType::Linear) == to_underlying(RustFFI::DistanceModelType::Linear));
+static_assert(to_underlying(Bindings::DistanceModelType::Inverse) == to_underlying(RustFFI::DistanceModelType::Inverse));
+static_assert(to_underlying(Bindings::DistanceModelType::Exponential) == to_underlying(RustFFI::DistanceModelType::Exponential));
+static_assert(to_underlying(Bindings::OverSampleType::None) == to_underlying(RustFFI::OverSampleType::None));
+static_assert(to_underlying(Bindings::OverSampleType::_2x) == to_underlying(RustFFI::OverSampleType::_2x));
+static_assert(to_underlying(Bindings::OverSampleType::_4x) == to_underlying(RustFFI::OverSampleType::_4x));
+
+ControlMessageQueue::ControlMessageQueue()
+ : m_queue(RustFFI::web_audio_control_queue_create())
{
- MutexLocker locker(m_mutex);
- m_messages.append(move(message));
}
+ControlMessageQueue::~ControlMessageQueue() { RustFFI::web_audio_control_queue_destroy(m_queue); }
+void* ControlMessageQueue::drain() { return RustFFI::web_audio_control_queue_drain(m_queue); }
-Vector<ControlMessage> ControlMessageQueue::drain()
+void ControlMessageQueue::enqueue(ControlMessage message)
{
- MutexLocker locker(m_mutex);
- return move(m_messages);
+ auto shared_object = []<typename T>(T* pointer) {
+ return RustFFI::FfiSharedCppObject { pointer,
+ [](void* pointer) { static_cast<T*>(pointer)->ref(); },
+ [](void* pointer) { static_cast<T*>(pointer)->unref(); } };
+ };
+ void* rust_message = message.visit(
+ [](AddNode& add_node) -> void* {
+ auto* node = add_node.node.leak_ptr();
+ auto* rust_node = node->release_rust_node();
+ if (!node->is_external())
+ delete node;
+ return RustFFI::web_audio_message_add_node(rust_node);
+ },
+ [](RemoveNode const& value) -> void* { return RustFFI::web_audio_message_remove_node(value.node_id.value()); },
+ [](ReplaceConnections const& value) -> void* {
+ Vector<RustFFI::OutgoingNodeConnection> nodes;
+ for (auto const& connection : value.node_connections)
+ nodes.append({ connection.destination.value(), connection.output_index, connection.input_index });
+ Vector<RustFFI::FfiOutgoingParamConnection> params;
+ for (auto const& connection : value.param_connections)
+ params.append({ connection.destination->rust_param(), connection.output_index });
+ return RustFFI::web_audio_message_replace_connections(value.source.value(), nodes.span(), params.span());
+ },
+ [](SetChannelConfig const& value) -> void* { return RustFFI::web_audio_message_set_channel_config(value.node_id.value(), value.channel_count, static_cast<RustFFI::ChannelCountMode>(value.channel_count_mode), static_cast<RustFFI::ChannelInterpretation>(value.channel_interpretation)); },
+ [&](NodeMessage const& node_message) -> void* {
+ return node_message.visit(
+ [](StartSource const& value) -> void* { return RustFFI::web_audio_message_start_source(value.node_id.value(), value.when); },
+ [](StopSource const& value) -> void* { return RustFFI::web_audio_message_stop_source(value.node_id.value(), value.when); },
+ [](StartBufferSource const& value) -> void* { return RustFFI::web_audio_message_start_buffer_source(value.node_id.value(), value.when, value.offset, value.duration.has_value(), value.duration.value_or(0.), value.buffer ? value.buffer->rust_data() : nullptr); },
+ [](SetBufferSourceParameters const& value) -> void* { return RustFFI::web_audio_message_set_buffer_source_parameters(value.node_id.value(), value.loop, value.loop_start, value.loop_end, value.buffer ? value.buffer->rust_data() : nullptr, value.update_buffer); },
+ [](SetOscillatorWaveform const& value) -> void* { return RustFFI::web_audio_message_set_oscillator_waveform(value.node_id.value(), static_cast<RustFFI::OscillatorType>(value.type), value.periodic_wave ? value.periodic_wave->rust_data() : nullptr); },
+ [](SetBiquadFilterType const& value) -> void* { return RustFFI::web_audio_message_set_biquad_filter_type(value.node_id.value(), static_cast<RustFFI::BiquadFilterType>(value.type)); },
+ [&](SetConvolverKernel const& value) -> void* { return RustFFI::web_audio_message_set_convolver_kernel(value.node_id.value(), value.kernel ? value.kernel->rust_kernel() : nullptr, value.delay_line ? value.delay_line->rust_delay_line() : nullptr); },
+ [](SetPannerParameters const& value) -> void* { return RustFFI::web_audio_message_set_panner_parameters(value.node_id.value(), static_cast<RustFFI::PanningModelType>(value.panning_model), static_cast<RustFFI::DistanceModelType>(value.distance_model), value.ref_distance, value.max_distance, value.rolloff_factor, value.cone_inner_angle, value.cone_outer_angle, value.cone_outer_gain); },
+ [](SetWaveShaperParameters const& value) -> void* { return RustFFI::web_audio_message_set_wave_shaper_parameters(value.node_id.value(), value.curve ? value.curve->rust_data() : nullptr, static_cast<RustFFI::OverSampleType>(value.oversample)); },
+ [&](SetMediaStreamSourceRing const& value) -> void* { return RustFFI::web_audio_message_set_media_stream_source_ring(value.node_id.value(), shared_object(value.ring.ptr()), value.channel_count); });
+ });
+ RustFFI::web_audio_control_queue_enqueue(m_queue, rust_message);
}
}
diff --git a/Libraries/LibWeb/WebAudio/ControlMessageQueue.h b/Libraries/LibWeb/WebAudio/ControlMessageQueue.h
index 3c13fe3c0ed..4230c2cf308 100644
--- a/Libraries/LibWeb/WebAudio/ControlMessageQueue.h
+++ b/Libraries/LibWeb/WebAudio/ControlMessageQueue.h
@@ -17,12 +17,13 @@ namespace Web::WebAudio {
// https://webaudio.github.io/web-audio-api/#control-message-queue
class WEB_API ControlMessageQueue : public AtomicRefCounted<ControlMessageQueue> {
public:
- void enqueue(ControlMessage); // Called by the control thread.
- Vector<ControlMessage> drain(); // Called by the rendering thread.
+ ControlMessageQueue();
+ ~ControlMessageQueue();
+ void enqueue(ControlMessage); // Called by the control thread.
+ void* drain(); // Called by the rendering thread.
private:
- mutable Mutex m_mutex;
- Vector<ControlMessage> m_messages;
+ void* m_queue { nullptr };
};
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioBus.cpp b/Libraries/LibWeb/WebAudio/Rendering/AudioBus.cpp
index 4c0f5039927..862856da91f 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/AudioBus.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioBus.cpp
@@ -23,6 +23,7 @@ AudioBus::AudioBus(AudioBus const& other)
AudioBus::AudioBus(AudioBus&& other)
: m_bus(exchange(other.m_bus, nullptr))
+ , m_owned(other.m_owned)
{
}
@@ -30,8 +31,10 @@ AudioBus& AudioBus::operator=(AudioBus const& other)
{
if (this != &other) {
auto* copy = RustFFI::web_audio_bus_clone(other.m_bus);
- RustFFI::web_audio_bus_destroy(m_bus);
+ if (m_owned)
+ RustFFI::web_audio_bus_destroy(m_bus);
m_bus = copy;
+ m_owned = true;
}
return *this;
}
@@ -39,15 +42,23 @@ AudioBus& AudioBus::operator=(AudioBus const& other)
AudioBus& AudioBus::operator=(AudioBus&& other)
{
if (this != &other) {
- RustFFI::web_audio_bus_destroy(m_bus);
+ if (m_owned)
+ RustFFI::web_audio_bus_destroy(m_bus);
m_bus = exchange(other.m_bus, nullptr);
+ m_owned = other.m_owned;
}
return *this;
}
AudioBus::~AudioBus()
{
- RustFFI::web_audio_bus_destroy(m_bus);
+ if (m_owned)
+ RustFFI::web_audio_bus_destroy(m_bus);
+}
+
+AudioBus AudioBus::borrow(void* bus)
+{
+ return AudioBus(bus);
}
size_t AudioBus::channel_count() const
diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioBus.h b/Libraries/LibWeb/WebAudio/Rendering/AudioBus.h
index cd37957284b..36414f966e5 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/AudioBus.h
+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioBus.h
@@ -33,6 +33,8 @@ public:
void const* rust_bus() const { return m_bus; }
+ static AudioBus borrow(void*);
+
void zero();
bool is_silent() const;
void set_channel_count(size_t);
@@ -41,7 +43,13 @@ public:
void sum_from(AudioBus const& source, Bindings::ChannelInterpretation);
private:
+ explicit AudioBus(void* bus)
+ : m_bus(bus)
+ , m_owned(false)
+ {
+ }
void* m_bus { nullptr };
+ bool m_owned { true };
};
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioData.cpp b/Libraries/LibWeb/WebAudio/Rendering/AudioData.cpp
new file mode 100644
index 00000000000..3be3d06efde
--- /dev/null
+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioData.cpp
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWeb/WebAudio/Rendering/AudioData.h>
+#include <LibWeb/WebAudio/RustFFI.h>
+namespace Web::WebAudio::Rendering {
+
+AudioBufferContents::AudioBufferContents(Vector<Vector<float>> samples, float rate)
+ : sample_rate(rate)
+{
+ Vector<ReadonlySpan<float>> views;
+ for (auto const& channel : samples)
+ views.append(channel.span());
+ m_data = RustFFI::web_audio_buffer_contents_create(views.span(), rate);
+ channels.resize(samples.size());
+ for (size_t i = 0; i < samples.size(); ++i)
+ RustFFI::web_audio_buffer_contents_channel(m_data, i, &channels[i]);
+}
+AudioBufferContents::~AudioBufferContents() { RustFFI::web_audio_buffer_contents_destroy(m_data); }
+WaveShaperCurve::WaveShaperCurve(Vector<float> samples)
+{
+ m_data = RustFFI::web_audio_wave_shaper_curve_create(samples.span());
+ RustFFI::web_audio_wave_shaper_curve_values(m_data, &values);
+}
+WaveShaperCurve::~WaveShaperCurve() { RustFFI::web_audio_wave_shaper_curve_destroy(m_data); }
+PeriodicWaveData::PeriodicWaveData(Vector<float> real_values, Vector<float> imag_values, bool should_normalize)
+ : normalize(should_normalize)
+{
+ m_data = RustFFI::web_audio_periodic_wave_data_create(real_values.span(), imag_values.span(), should_normalize);
+ RustFFI::web_audio_periodic_wave_data_real(m_data, &real);
+ RustFFI::web_audio_periodic_wave_data_imag(m_data, &imag);
+}
+PeriodicWaveData::~PeriodicWaveData() { RustFFI::web_audio_periodic_wave_data_destroy(m_data); }
+
+}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioData.h b/Libraries/LibWeb/WebAudio/Rendering/AudioData.h
index 28f902cc39b..0b997430e03 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/AudioData.h
+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioData.h
@@ -1,57 +1,47 @@
/*
* Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
-
#include <AK/AtomicRefCounted.h>
+#include <AK/Span.h>
#include <AK/Vector.h>
-
namespace Web::WebAudio::Rendering {
-// An immutable snapshot of an AudioBuffer's sample data, created on the control thread when the buffer's content is
-// acquired and shared with the rendering thread.
-// https://webaudio.github.io/web-audio-api/#acquire-the-content
struct AudioBufferContents : public AtomicRefCounted<AudioBufferContents> {
- AudioBufferContents(Vector<Vector<float>> channels, float sample_rate)
- : channels(move(channels))
- , sample_rate(sample_rate)
- {
- }
-
+ AudioBufferContents(Vector<Vector<float>> channels, float sample_rate);
+ ~AudioBufferContents();
size_t length() const { return channels.is_empty() ? 0 : channels.first().size(); }
double duration() const { return length() / static_cast<double>(sample_rate); }
-
- Vector<Vector<float>> channels;
+ void const* rust_data() const { return m_data; }
+ Vector<ReadonlySpan<float>> channels;
float sample_rate { 0 };
-};
-// An immutable copy of a WaveShaperNode's curve.
-// https://webaudio.github.io/web-audio-api/#dom-waveshapernode-curve
+private:
+ void const* m_data { nullptr };
+};
struct WaveShaperCurve : public AtomicRefCounted<WaveShaperCurve> {
- explicit WaveShaperCurve(Vector<float> values)
- : values(move(values))
- {
- }
+ explicit WaveShaperCurve(Vector<float> values);
+ ~WaveShaperCurve();
+ void const* rust_data() const { return m_data; }
+ ReadonlySpan<float> values;
- Vector<float> values;
+private:
+ void const* m_data { nullptr };
};
-
-// An immutable snapshot of a PeriodicWave's Fourier coefficients.
-// https://webaudio.github.io/web-audio-api/#PeriodicWave
struct PeriodicWaveData : public AtomicRefCounted<PeriodicWaveData> {
- PeriodicWaveData(Vector<float> real, Vector<float> imag, bool normalize)
- : real(move(real))
- , imag(move(imag))
- , normalize(normalize)
- {
- }
-
- Vector<float> real;
- Vector<float> imag;
+ PeriodicWaveData(Vector<float> real, Vector<float> imag, bool normalize);
+ ~PeriodicWaveData();
+ void const* rust_data() const { return m_data; }
+ ReadonlySpan<float> real;
+ ReadonlySpan<float> imag;
bool normalize { true };
+
+private:
+ void const* m_data { nullptr };
};
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.cpp
index d2f1e238021..69aa6951906 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.cpp
@@ -50,7 +50,7 @@ void AudioWorkletRenderNode::process(RenderGraph& graph, RenderContext const& co
for (size_t input = 0; input < input_count(); ++input) {
// Unlike the render graph's silent mono bus, an unconnected worklet input
// is represented by an empty channel array in process().
- if (input_connections(input).is_empty()) {
+ if (!has_input_connections(input)) {
slot.actual_channel_count(input) = 0;
continue;
}
@@ -78,7 +78,7 @@ void AudioWorkletRenderNode::process(RenderGraph& graph, RenderContext const& co
bool popped = m_pipe->try_pop_output([&](AudioWorkletPipe::OutputSlotReader const& slot) {
for (size_t output = 0; output < output_count(); ++output) {
- auto& output_bus = this->output(output);
+ auto output_bus = this->output(output);
auto channel_count = min(static_cast<size_t>(slot.actual_channel_count(output)), static_cast<size_t>(m_output_channel_capacities[output]));
output_bus.set_channel_count(max(channel_count, static_cast<size_t>(1)));
output_bus.zero();
diff --git a/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.cpp b/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.cpp
index 17fc0a47227..1b5272cb3a0 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.cpp
@@ -15,7 +15,7 @@ RefPtr<ConvolverKernel> ConvolverKernel::create(AudioBufferContents const& conte
Vector<ReadonlySpan<float>> channels;
channels.ensure_capacity(contents.channels.size());
for (auto const& channel : contents.channels)
- channels.unchecked_append(channel.span());
+ channels.unchecked_append(channel);
auto const* kernel = RustFFI::web_audio_convolver_kernel_create(channels.span(), contents.sample_rate, partition_size, normalize);
if (!kernel)
return nullptr;
diff --git a/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.h b/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.h
index 8c96201170e..4cbd27d4b18 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.h
+++ b/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.h
@@ -20,6 +20,7 @@ public:
static RefPtr<ConvolverKernel> create(AudioBufferContents const&, size_t partition_size, bool normalize);
~ConvolverKernel();
+ void const* rust_kernel() const { return m_kernel; }
size_t channel_count() const;
size_t partition_count() const;
size_t bin_count() const;
@@ -45,17 +46,18 @@ public:
static NonnullRefPtr<ConvolverDelayLine> create(ConvolverKernel const&);
~ConvolverDelayLine();
+ void const* rust_delay_line() const { return m_delay_line; }
size_t length() const;
Span<float> real(size_t channel);
Span<float> imag(size_t channel);
private:
- explicit ConvolverDelayLine(void* delay_line)
+ explicit ConvolverDelayLine(void const* delay_line)
: m_delay_line(delay_line)
{
}
- void* m_delay_line { nullptr };
+ void const* m_delay_line { nullptr };
};
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.cpp
index 14ad193af31..9335af6dcfb 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.cpp
@@ -35,7 +35,7 @@ void MediaStreamSourceRenderNode::handle_message(NodeMessage const& message)
void MediaStreamSourceRenderNode::process(RenderGraph&, RenderContext const& context)
{
- auto& source_output = output(0);
+ auto source_output = output(0);
// The number of channels of the output corresponds to the number of channels of the track.
source_output.set_channel_count(m_channel_count);
diff --git a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp b/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp
index 214c7d40a59..a9918c5f8d2 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp
@@ -128,8 +128,8 @@ intptr_t OfflineAudioRenderer::render_thread_main()
m_graph.render_quantum(context);
// Copy the destination's captured output into the rendered buffer.
- if (auto* destination_node = m_graph.destination()) {
- auto const& destination_output = destination_node->output(0);
+ if (auto maybe_destination_output = m_graph.destination_output(); maybe_destination_output.has_value()) {
+ auto const& destination_output = *maybe_destination_output;
auto frames_to_copy = min(m_quantum_size, m_length - current_frame);
for (size_t channel_index = 0; channel_index < m_number_of_channels; ++channel_index) {
if (channel_index >= destination_output.channel_count())
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp b/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp
index b2f666cc31a..eff50ef54ab 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp
@@ -174,8 +174,8 @@ void RealtimeAudioRenderer::render_quantum_into_pending_samples()
if (m_device_bus) {
auto& device_bus = *m_device_bus;
device_bus.zero();
- if (auto* destination_node = m_graph.destination())
- device_bus.sum_from(destination_node->output(0), Bindings::ChannelInterpretation::Speakers);
+ if (auto destination_output = m_graph.destination_output(); destination_output.has_value())
+ device_bus.sum_from(*destination_output, Bindings::ChannelInterpretation::Speakers);
auto sample_offset = m_pending_samples.size();
m_pending_samples.resize(sample_offset + m_quantum_size * m_device_channel_count);
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.cpp b/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.cpp
index 9e94b1afc9a..f97e3af4695 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.cpp
@@ -6,125 +6,49 @@
*/
#include <LibWeb/WebAudio/Rendering/RenderGraph.h>
-
+#include <LibWeb/WebAudio/RustFFI.h>
namespace Web::WebAudio::Rendering {
-void RenderGraph::apply_control_messages(Vector<ControlMessage> messages)
+RenderGraph::RenderGraph()
+ : m_graph(RustFFI::web_audio_graph_create())
{
- for (auto& message : messages) {
- message.visit(
- [&](AddNode& add_node) {
- auto node_id = add_node.node->node_id();
- m_nodes.set(node_id, move(add_node.node));
- m_incoming_connections_dirty = true;
- },
- [&](RemoveNode const& remove_node) {
- if (m_nodes.remove(remove_node.node_id))
- m_incoming_connections_dirty = true;
- },
- [&](ReplaceConnections& replace_connections) {
- if (auto* source_node = node(replace_connections.source)) {
- source_node->set_outgoing_connections(move(replace_connections.node_connections), move(replace_connections.param_connections));
- m_incoming_connections_dirty = true;
- }
- },
- [&](SetChannelConfig const& config) {
- if (auto* target_node = node(config.node_id)) {
- target_node->set_channel_count(config.channel_count);
- target_node->set_channel_count_mode(config.channel_count_mode);
- target_node->set_channel_interpretation(config.channel_interpretation);
- }
- },
- [&](NodeMessage const& node_message) {
- if (auto* target_node = node(node_message_target(node_message)))
- target_node->handle_message(node_message);
- });
- }
}
-
-// Renders a single quantum by pulling the destination node and any active source nodes.
-void RenderGraph::render_quantum(RenderContext const& context)
+RenderGraph::~RenderGraph()
{
- ++m_current_quantum;
- if (m_incoming_connections_dirty) {
- rebuild_incoming_connections();
- m_incoming_connections_dirty = false;
- }
-
- // Pull the destination first so the main graph is processed in dependency order; then process any remaining nodes
- // so unconnected sources still advance their playback state and report ended events.
- if (auto* destination_node = destination())
- pull_output(destination_node->node_id(), 0, context);
- for (auto& [node_id, graph_node] : m_nodes) {
- if (graph_node->output_count() > 0)
- pull_output(node_id, 0, context);
- }
+ if (m_owned)
+ RustFFI::web_audio_graph_destroy(m_graph);
}
-
-// Returns the source node's output bus, processing the node first if it has not been processed in this quantum.
-// Re-entrant pulls caused by cycles return the output rendered in the previous quantum.
-AudioBus const* RenderGraph::pull_output(NodeID source, size_t output_index, RenderContext const& context)
+void RenderGraph::apply_control_messages(void* messages) { RustFFI::web_audio_graph_apply_control_messages(m_graph, messages); }
+void RenderGraph::set_destination(NodeID node) { RustFFI::web_audio_graph_set_destination(m_graph, node.value()); }
+void RenderGraph::render_quantum(RenderContext const& context)
{
- auto* source_node = node(source);
- if (!source_node || output_index >= source_node->output_count())
- return nullptr;
-
- if (!source_node->processed_in_quantum(m_current_quantum)) {
- // A re-entrant pull means this node is part of a cycle; its output bus still holds the previous quantum's
- // samples, which effectively inserts one render quantum of delay into the cycle.
- if (source_node->is_processing())
- return &source_node->output(output_index);
-
- source_node->set_is_processing(true);
- source_node->process(*this, context);
- source_node->set_is_processing(false);
- source_node->mark_processed_in_quantum(m_current_quantum);
- }
- return &source_node->output(output_index);
+ RustFFI::RenderContext rust_context { context.sample_rate, context.quantum_size, context.quantum_start_frame };
+ RustFFI::web_audio_graph_render_quantum(m_graph, &rust_context);
}
-
-RenderNode* RenderGraph::node(NodeID node_id)
+Optional<AudioBus> RenderGraph::pull_output(NodeID source, size_t output_index, RenderContext const& context)
{
- auto it = m_nodes.find(node_id);
- if (it == m_nodes.end())
- return nullptr;
- return it->value.ptr();
+ RustFFI::RenderContext rust_context { context.sample_rate, context.quantum_size, context.quantum_start_frame };
+ auto* bus = RustFFI::web_audio_graph_pull_output(m_graph, source.value(), output_index, &rust_context);
+ if (!bus)
+ return {};
+ return AudioBus::borrow(bus);
}
-
-// Drains the set of nodes that stopped playing since the last call and retires their permanently silent render nodes.
-Vector<NodeID> RenderGraph::take_ended_nodes()
+Optional<AudioBus> RenderGraph::destination_output()
{
- Vector<NodeID> ended_nodes;
- for (auto& [node_id, graph_node] : m_nodes) {
- if (graph_node->take_ended_notification())
- ended_nodes.append(node_id);
- }
- for (auto node_id : ended_nodes)
- m_nodes.remove(node_id);
- if (!ended_nodes.is_empty())
- m_incoming_connections_dirty = true;
- return ended_nodes;
+ auto* bus = RustFFI::web_audio_graph_destination_output(m_graph);
+ if (!bus)
+ return {};
+ return AudioBus::borrow(bus);
}
-
-void RenderGraph::rebuild_incoming_connections()
+Vector<NodeID> RenderGraph::take_ended_nodes()
{
- for (auto& [node_id, graph_node] : m_nodes) {
- for (size_t input_index = 0; input_index < graph_node->input_count(); ++input_index)
- graph_node->input_connections(input_index).clear_with_capacity();
- graph_node->for_each_param([](RenderAudioParam& param) {
- param.clear_inputs();
- });
- }
-
- for (auto& [node_id, graph_node] : m_nodes) {
- for (auto const& connection : graph_node->outgoing_node_connections()) {
- auto* destination_node = node(connection.destination);
- if (destination_node && connection.input_index < destination_node->input_count())
- destination_node->input_connections(connection.input_index).append({ node_id, connection.output_index });
- }
- for (auto const& connection : graph_node->outgoing_param_connections())
- connection.destination->add_input(node_id, connection.output_index);
- }
+ Vector<NodeID> nodes;
+ RustFFI::web_audio_graph_take_ended_nodes(m_graph, &nodes, [](void* context, ReadonlySpan<u64> ended) {
+ auto& nodes = *static_cast<Vector<NodeID>*>(context);
+ for (auto node : ended)
+ nodes.append(NodeID { node });
+ });
+ return nodes;
}
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.h b/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.h
index 31f06b8af85..39df1e072ec 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.h
+++ b/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.h
@@ -1,51 +1,40 @@
/*
* Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
-
-#include <AK/HashMap.h>
-#include <AK/NonnullOwnPtr.h>
+#include <AK/Optional.h>
#include <AK/Vector.h>
#include <LibWeb/Export.h>
-#include <LibWeb/WebAudio/ControlMessage.h>
#include <LibWeb/WebAudio/Rendering/RenderNode.h>
-#include <LibWeb/WebAudio/Types.h>
-
namespace Web::WebAudio::Rendering {
-// The rendering thread's mirror of the audio graph. Nodes and connections are added and updated exclusively through
-// control messages, which are applied at the start of each render quantum.
-// https://webaudio.github.io/web-audio-api/#rendering-loop
class WEB_API RenderGraph {
AK_MAKE_NONCOPYABLE(RenderGraph);
AK_MAKE_NONMOVABLE(RenderGraph);
public:
- RenderGraph() = default;
-
- void apply_control_messages(Vector<ControlMessage>);
-
+ RenderGraph();
+ RenderGraph(void* graph, bool owned)
+ : m_graph(graph)
+ , m_owned(owned)
+ {
+ }
+ ~RenderGraph();
+ void apply_control_messages(void* messages);
void render_quantum(RenderContext const&);
- AudioBus const* pull_output(NodeID source, size_t output_index, RenderContext const&);
-
- RenderNode* node(NodeID node_id);
-
- void set_destination(NodeID node_id) { m_destination_id = node_id; }
- RenderNode* destination() { return node(m_destination_id); }
-
- // Drains the set of nodes that stopped playing since the last call.
+ Optional<AudioBus> pull_output(NodeID source, size_t output_index, RenderContext const&);
+ Optional<AudioBus> destination_output();
+ void set_destination(NodeID);
Vector<NodeID> take_ended_nodes();
+ void* rust_graph() const { return m_graph; }
private:
- void rebuild_incoming_connections();
-
- HashMap<NodeID, NonnullOwnPtr<RenderNode>> m_nodes;
- NodeID m_destination_id { 0 };
- u64 m_current_quantum { 0 };
- bool m_incoming_connections_dirty { false };
+ void* m_graph { nullptr };
+ bool m_owned { true };
};
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cpp
index 96169636ae7..19ceadfb21a 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cpp
@@ -5,10 +5,9 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibWeb/WebAudio/RustFFI.h>
#include <LibWeb/WebAudio/Rendering/RenderGraph.h>
#include <LibWeb/WebAudio/Rendering/RenderNode.h>
-
+#include <LibWeb/WebAudio/RustFFI.h>
namespace Web::WebAudio::Rendering {
RenderAudioParam::RenderAudioParam(NonnullRefPtr<AudioParamTimeline> timeline, float min_value, float max_value, Bindings::AutomationRate automation_rate)
@@ -48,74 +47,56 @@ void RenderAudioParam::compute(RenderGraph& graph, RenderContext const& context,
RustFFI::RenderContext rust_context { context.sample_rate, context.quantum_size, context.quantum_start_frame };
RustFFI::web_audio_render_param_compute(m_param, &graph, [](void* graph, u64 source, size_t output_index, RustFFI::RenderContext const* context) -> void const* {
RenderContext render_context { context->sample_rate, context->quantum_size, context->quantum_start_frame };
- auto const* bus = static_cast<RenderGraph*>(graph)->pull_output(source, output_index, render_context);
- return bus ? bus->rust_bus() : nullptr;
- }, &rust_context, output);
+ auto bus = static_cast<RenderGraph*>(graph)->pull_output(source, output_index, render_context);
+ return bus.has_value() ? bus->rust_bus() : nullptr; }, &rust_context, output);
}
RenderNode::RenderNode(NodeID node_id, size_t input_count, size_t output_count, size_t quantum_size, size_t output_channel_count)
- : m_node_id(node_id)
+ : m_external(true)
{
- m_input_connections.resize(input_count);
- m_input_buses.ensure_capacity(input_count);
- for (size_t input_index = 0; input_index < input_count; ++input_index)
- m_input_buses.unchecked_append(AudioBus { 1, quantum_size });
- m_outputs.ensure_capacity(output_count);
- for (size_t output_index = 0; output_index < output_count; ++output_index)
- m_outputs.unchecked_append(AudioBus { output_channel_count, quantum_size });
+ m_node = RustFFI::web_audio_node_create_external(node_id.value(), input_count, output_count, quantum_size, output_channel_count, this, {
+ .process = [](void* node, void const* graph, RustFFI::RenderContext const* context) {
+ RenderGraph borrowed_graph(const_cast<void*>(graph), false);
+ RenderContext render_context { context->sample_rate, context->quantum_size, context->quantum_start_frame };
+ static_cast<RenderNode*>(node)->process(borrowed_graph, render_context); },
+ .set_ring = [](void* node, void* ring, u32 channel_count) { static_cast<RenderNode*>(node)->handle_message(NodeMessage { SetMediaStreamSourceRing { {}, static_cast<Audio::SpscAudioFrameRing*>(ring), channel_count } }); },
+ .for_each_param = [](void* node, void* context, void (*callback)(void*, void const*)) { static_cast<RenderNode*>(node)->for_each_param([&](RenderAudioParam& param) { callback(context, param.rust_param()); }); },
+ .ended = [](void* node) { return static_cast<RenderNode*>(node)->take_ended_notification(); },
+ .destroy = [](void* node) { if (static_cast<RenderNode*>(node)->m_transferred) delete static_cast<RenderNode*>(node); },
+ });
}
-
-void RenderNode::set_outgoing_connections(Vector<OutgoingNodeConnection> node_connections, Vector<OutgoingParamConnection> param_connections)
+RenderNode::RenderNode(void* node)
+ : m_node(node)
{
- m_outgoing_node_connections = move(node_connections);
- m_outgoing_param_connections = move(param_connections);
}
-
-// Pulls and mixes all connections to the given input into a single bus with the input's computed number of channels.
-// Unconnected inputs are mixed as a single channel of silence.
-// https://webaudio.github.io/web-audio-api/#computednumberofchannels
-AudioBus const& RenderNode::pull_input(RenderGraph& graph, RenderContext const& context, size_t input_index)
+RenderNode::~RenderNode()
{
- auto& connections = m_input_connections[input_index];
- auto& input_bus = m_input_buses[input_index];
-
- auto& source_buses = m_pulled_source_buses;
- source_buses.clear_with_capacity();
- for (auto const& connection : connections) {
- if (auto const* bus = graph.pull_output(connection.source, connection.output_index, context))
- source_buses.append(bus);
- }
-
- if (source_buses.is_empty()) {
- input_bus.set_channel_count(1);
- input_bus.zero();
- return input_bus;
- }
-
- size_t computed_number_of_channels = 0;
- switch (m_channel_count_mode) {
- case Bindings::ChannelCountMode::Max:
- case Bindings::ChannelCountMode::ClampedMax:
- // "max": computedNumberOfChannels is the maximum of the number of channels of all connections to an input.
- // In this mode channelCount is ignored.
- // "clamped-max": computedNumberOfChannels is determined as for "max" and then clamped to a maximum value of
- // the given channelCount.
- for (auto const* bus : source_buses)
- computed_number_of_channels = max(computed_number_of_channels, bus->channel_count());
- if (m_channel_count_mode == Bindings::ChannelCountMode::ClampedMax)
- computed_number_of_channels = min(computed_number_of_channels, m_channel_count);
- break;
- case Bindings::ChannelCountMode::Explicit:
- // "explicit": computedNumberOfChannels is the exact value as specified by the channelCount.
- computed_number_of_channels = m_channel_count;
- break;
- }
-
- input_bus.set_channel_count(computed_number_of_channels);
- input_bus.zero();
- for (auto const* bus : source_buses)
- input_bus.sum_from(*bus, m_channel_interpretation);
- return input_bus;
+ if (m_owned)
+ RustFFI::web_audio_node_destroy(m_node);
+}
+void* RenderNode::release_rust_node()
+{
+ m_owned = false;
+ m_transferred = true;
+ return m_node;
+}
+NodeID RenderNode::node_id() const { return RustFFI::web_audio_node_id(m_node); }
+size_t RenderNode::input_count() const { return RustFFI::web_audio_node_input_count(m_node); }
+size_t RenderNode::output_count() const { return RustFFI::web_audio_node_output_count(m_node); }
+AudioBus RenderNode::output(size_t index) const { return AudioBus::borrow(RustFFI::web_audio_node_output(m_node, index)); }
+size_t RenderNode::channel_count() const { return RustFFI::web_audio_node_channel_count(m_node); }
+Bindings::ChannelCountMode RenderNode::channel_count_mode() const { return static_cast<Bindings::ChannelCountMode>(RustFFI::web_audio_node_channel_count_mode(m_node)); }
+Bindings::ChannelInterpretation RenderNode::channel_interpretation() const { return static_cast<Bindings::ChannelInterpretation>(RustFFI::web_audio_node_channel_interpretation(m_node)); }
+void RenderNode::set_channel_count(size_t count) { RustFFI::web_audio_node_set_channel_count(m_node, count); }
+void RenderNode::set_channel_count_mode(Bindings::ChannelCountMode mode) { RustFFI::web_audio_node_set_channel_count_mode(m_node, static_cast<RustFFI::ChannelCountMode>(mode)); }
+void RenderNode::set_channel_interpretation(Bindings::ChannelInterpretation interpretation) { RustFFI::web_audio_node_set_channel_interpretation(m_node, static_cast<RustFFI::ChannelInterpretation>(interpretation)); }
+size_t RenderNode::outgoing_node_connection_count() const { return RustFFI::web_audio_node_outgoing_node_connection_count(m_node); }
+size_t RenderNode::outgoing_param_connection_count() const { return RustFFI::web_audio_node_outgoing_param_connection_count(m_node); }
+bool RenderNode::has_input_connections(size_t input) const { return RustFFI::web_audio_node_has_input_connections(m_node, input); }
+AudioBus RenderNode::pull_input(RenderGraph& graph, RenderContext const& context, size_t input_index)
+{
+ RustFFI::RenderContext render_context { context.sample_rate, context.quantum_size, context.quantum_start_frame };
+ return AudioBus::borrow(const_cast<void*>(RustFFI::web_audio_node_pull_input(m_node, graph.rust_graph(), &render_context, input_index)));
}
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.h b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.h
index b7f24e6516e..ffb33be74fe 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.h
+++ b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.h
@@ -6,13 +6,9 @@
*/
#pragma once
-
-#include <AK/Atomic.h>
#include <AK/AtomicRefCounted.h>
#include <AK/Function.h>
#include <AK/NonnullRefPtr.h>
-#include <AK/NumericLimits.h>
-#include <AK/OwnPtr.h>
#include <AK/Vector.h>
#include <LibWeb/Bindings/AudioParam.h>
#include <LibWeb/Export.h>
@@ -20,25 +16,17 @@
#include <LibWeb/WebAudio/Rendering/AudioBus.h>
#include <LibWeb/WebAudio/Rendering/NodeMessage.h>
#include <LibWeb/WebAudio/Types.h>
-
namespace Web::WebAudio::Rendering {
class RenderGraph;
-
-// State for a single render quantum that is passed to every node being processed.
struct RenderContext {
double sample_rate { 0 };
size_t quantum_size { 0 };
u64 quantum_start_frame { 0 };
-
double quantum_start_time() const { return quantum_start_frame / sample_rate; }
double sample_period() const { return 1 / sample_rate; }
double frame_time(size_t frame) const { return (quantum_start_frame + frame) / sample_rate; }
};
-
-// The rendering thread's view of an AudioParam. The automation timeline is shared with the AudioParam on the control
-// thread; input connections are only manipulated by the rendering thread.
-// https://webaudio.github.io/web-audio-api/#computedvalue
class WEB_API RenderAudioParam : public AtomicRefCounted<RenderAudioParam> {
public:
RenderAudioParam(NonnullRefPtr<AudioParamTimeline> timeline, float min_value, float max_value, Bindings::AutomationRate);
@@ -50,6 +38,8 @@ public:
void compute(RenderGraph&, RenderContext const&, Span<float> output);
+ void const* rust_param() const { return m_param; }
+
void clear_inputs();
void add_input(NodeID source, size_t output_index);
@@ -57,40 +47,27 @@ private:
void const* m_param { nullptr };
};
-// Base class for the rendering thread's counterparts of AudioNodes. Render nodes are constructed on the control thread
-// and transferred to the rendering thread through the control message queue; after that, all access happens on the
-// rendering thread.
class WEB_API RenderNode {
AK_MAKE_NONCOPYABLE(RenderNode);
AK_MAKE_NONMOVABLE(RenderNode);
public:
AK_ALLOC_WITH_KMALLOC;
-
RenderNode(NodeID, size_t input_count, size_t output_count, size_t quantum_size, size_t output_channel_count = 1);
- virtual ~RenderNode() = default;
-
- NodeID node_id() const { return m_node_id; }
-
- size_t input_count() const { return m_input_connections.size(); }
- size_t output_count() const { return m_outputs.size(); }
-
- AudioBus& output(size_t index) { return m_outputs[index]; }
- AudioBus const& output(size_t index) const { return m_outputs[index]; }
-
- void set_channel_count(size_t channel_count) { m_channel_count = channel_count; }
- void set_channel_count_mode(Bindings::ChannelCountMode mode) { m_channel_count_mode = mode; }
- void set_channel_interpretation(Bindings::ChannelInterpretation interpretation) { m_channel_interpretation = interpretation; }
- size_t channel_count() const { return m_channel_count; }
- Bindings::ChannelCountMode channel_count_mode() const { return m_channel_count_mode; }
- Bindings::ChannelInterpretation channel_interpretation() const { return m_channel_interpretation; }
-
- struct Connection {
- NodeID source;
- size_t output_index;
- };
- Vector<Connection>& input_connections(size_t input_index) { return m_input_connections[input_index]; }
-
+ virtual ~RenderNode();
+ NodeID node_id() const;
+ size_t input_count() const;
+ size_t output_count() const;
+ AudioBus output(size_t index) const;
+ void set_channel_count(size_t);
+ void set_channel_count_mode(Bindings::ChannelCountMode);
+ void set_channel_interpretation(Bindings::ChannelInterpretation);
+ size_t channel_count() const;
+ Bindings::ChannelCountMode channel_count_mode() const;
+ Bindings::ChannelInterpretation channel_interpretation() const;
+ bool has_input_connections(size_t) const;
+ size_t outgoing_node_connection_count() const;
+ size_t outgoing_param_connection_count() const;
struct OutgoingNodeConnection {
NodeID destination;
size_t output_index;
@@ -100,42 +77,22 @@ public:
NonnullRefPtr<RenderAudioParam> destination;
size_t output_index;
};
- void set_outgoing_connections(Vector<OutgoingNodeConnection> node_connections, Vector<OutgoingParamConnection> param_connections);
- Vector<OutgoingNodeConnection> const& outgoing_node_connections() const { return m_outgoing_node_connections; }
- Vector<OutgoingParamConnection> const& outgoing_param_connections() const { return m_outgoing_param_connections; }
-
- virtual void process(RenderGraph&, RenderContext const&) = 0;
+ virtual void process(RenderGraph&, RenderContext const&) { VERIFY_NOT_REACHED(); }
virtual void handle_message(NodeMessage const&) { }
virtual void for_each_param(Function<void(RenderAudioParam&)> const&) { }
-
- // Returns true exactly once after this node has stopped playing, so the main thread can fire an ended event.
virtual bool take_ended_notification() { return false; }
-
- // Bookkeeping used by RenderGraph to process every node at most once per render quantum.
- bool processed_in_quantum(u64 quantum) const { return m_processed_quantum == quantum; }
- void mark_processed_in_quantum(u64 quantum) { m_processed_quantum = quantum; }
- bool is_processing() const { return m_is_processing; }
- void set_is_processing(bool is_processing) { m_is_processing = is_processing; }
+ void* release_rust_node();
+ bool is_external() const { return m_external; }
protected:
- AudioBus const& pull_input(RenderGraph&, RenderContext const&, size_t input_index);
+ explicit RenderNode(void*);
+ AudioBus pull_input(RenderGraph&, RenderContext const&, size_t input_index);
private:
- NodeID m_node_id;
- size_t m_channel_count { 2 };
- Bindings::ChannelCountMode m_channel_count_mode { Bindings::ChannelCountMode::Max };
- Bindings::ChannelInterpretation m_channel_interpretation { Bindings::ChannelInterpretation::Speakers };
-
- Vector<Vector<Connection>> m_input_connections;
- Vector<AudioBus> m_input_buses;
- Vector<AudioBus const*, 4> m_pulled_source_buses;
- Vector<AudioBus> m_outputs;
-
- Vector<OutgoingNodeConnection> m_outgoing_node_connections;
- Vector<OutgoingParamConnection> m_outgoing_param_connections;
-
- u64 m_processed_quantum { NumericLimits<u64>::max() };
- bool m_is_processing { false };
+ void* m_node { nullptr };
+ bool m_owned { true };
+ bool m_external { false };
+ bool m_transferred { false };
};
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RenderNodes.cpp b/Libraries/LibWeb/WebAudio/Rendering/RenderNodes.cpp
index 692dfee294d..fbf769da8c7 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RenderNodes.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/RenderNodes.cpp
@@ -1,1228 +1,81 @@
/*
* Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Array.h>
-#include <AK/Math.h>
-#include <LibGfx/Vector3.h>
-#include <LibWeb/WebAudio/Rendering/FFT.h>
-#include <LibWeb/WebAudio/Rendering/RenderGraph.h>
#include <LibWeb/WebAudio/Rendering/RenderNodes.h>
-
+#include <LibWeb/WebAudio/RustFFI.h>
namespace Web::WebAudio::Rendering {
-// Additive synthesis of the built-in oscillator waveforms is capped to keep the per-sample cost bounded for very low
-// fundamental frequencies.
-static constexpr size_t MAX_OSCILLATOR_HARMONICS = 5000;
-
-static constexpr double FRAME_BOUNDARY_SNAPPING_TOLERANCE = 1.0 / 2048;
-
-struct PanGains {
- float left { 0 };
- float right { 0 };
-};
-
-// The equal-power panning curve maps a position in [0, 1] to a left/right gain pair whose squared sum is 1, shared by
-// the StereoPannerNode and the equalpower PannerNode.
-// https://webaudio.github.io/web-audio-api/#stereopanner-algorithm
-static PanGains equal_power_pan_gains(double position)
-{
- return {
- static_cast<float>(AK::cos(position * AK::Pi<double> / 2)),
- static_cast<float>(AK::sin(position * AK::Pi<double> / 2)),
- };
-}
-
DestinationRenderNode::DestinationRenderNode(NodeID node_id, size_t channel_count, size_t quantum_size)
- : RenderNode(node_id, 1, 1, quantum_size, channel_count)
+ : RenderNode(RustFFI::web_audio_node_create_destination(node_id.value(), quantum_size, channel_count))
{
- set_channel_count(channel_count);
- set_channel_count_mode(Bindings::ChannelCountMode::Explicit);
}
-
-void DestinationRenderNode::process(RenderGraph& graph, RenderContext const& context)
-{
- auto const& input = pull_input(graph, context, 0);
- auto& destination_output = output(0);
- destination_output.set_channel_count(channel_count());
- destination_output.zero();
- destination_output.sum_from(input, channel_interpretation());
-}
-
GainRenderNode::GainRenderNode(NodeID node_id, size_t quantum_size, NonnullRefPtr<RenderAudioParam> gain)
- : RenderNode(node_id, 1, 1, quantum_size)
- , m_gain(move(gain))
-{
- m_gain_values.resize(quantum_size);
-}
-
-void GainRenderNode::process(RenderGraph& graph, RenderContext const& context)
+ : RenderNode(RustFFI::web_audio_node_create_gain(node_id.value(), quantum_size, gain->rust_param()))
{
- auto const& input = pull_input(graph, context, 0);
- auto& gain_output = output(0);
- gain_output.set_channel_count(input.channel_count());
- if (input.is_silent()) {
- gain_output.zero();
- return;
- }
-
- m_gain->compute(graph, context, m_gain_values);
-
- for (size_t channel_index = 0; channel_index < input.channel_count(); ++channel_index) {
- auto input_samples = input.channel(channel_index);
- auto output_samples = gain_output.channel(channel_index);
- for (size_t frame = 0; frame < context.quantum_size; ++frame)
- output_samples[frame] = input_samples[frame] * m_gain_values[frame];
- }
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-audioscheduledsourcenode-start
-void ScheduledSourceRenderNode::process(RenderGraph& graph, RenderContext const& context)
-{
- // If 0 is passed in for this value or if the value is less than currentTime, then the sound will start playing
- // immediately.
- // NB: The start time is clamped to the first render quantum processed after the start message arrived, since the
- // control thread's currentTime may already have advanced past the scheduled time by then.
- if (m_start_time_needs_clamping) {
- // AD-HOC: Start times built by summing buffer durations may induce rounding error and place the start part
- // of a frame after the prior buffer's end. Snap starts that are close to a frame boundary onto it
- // to prevent this from becoming audible in continuous streams.
- auto start_frame = *m_start_time * context.sample_rate;
- auto nearest_frame = AK::round(start_frame);
- if (AK::abs(start_frame - nearest_frame) < FRAME_BOUNDARY_SNAPPING_TOLERANCE)
- m_start_time = nearest_frame / context.sample_rate;
- m_start_time = max(*m_start_time, context.quantum_start_time());
- m_start_time_needs_clamping = false;
- }
- process_source(graph, context);
-}
-
-void ScheduledSourceRenderNode::handle_message(NodeMessage const& message)
-{
- message.visit(
- [&](StartSource const& start_source) {
- m_start_time = start_source.when;
- m_start_time_needs_clamping = true;
- },
- [&](StopSource const& stop_source) { m_stop_time = stop_source.when; },
- [](auto const&) { });
-}
-
-// Marks this node as ended once the quantum has advanced past the stop time or the content was exhausted.
-void ScheduledSourceRenderNode::update_ended_state(RenderContext const& context)
-{
- if (!m_start_time.has_value() || m_ended)
- return;
- auto quantum_end_time = context.frame_time(context.quantum_size);
- if (quantum_end_time >= m_stop_time || m_content_ended) {
- m_ended = true;
- m_ended_pending = true;
- }
}
-
ConstantSourceRenderNode::ConstantSourceRenderNode(NodeID node_id, size_t quantum_size, NonnullRefPtr<RenderAudioParam> offset)
- : ScheduledSourceRenderNode(node_id, 0, 1, quantum_size)
- , m_offset(move(offset))
-{
- m_offset_values.resize(quantum_size);
-}
-
-void ConstantSourceRenderNode::process_source(RenderGraph& graph, RenderContext const& context)
+ : RenderNode(RustFFI::web_audio_node_create_constant_source(node_id.value(), quantum_size, offset->rust_param()))
{
- m_offset->compute(graph, context, m_offset_values);
- auto output_samples = output(0).channel(0);
- for (size_t frame = 0; frame < context.quantum_size; ++frame)
- output_samples[frame] = is_active_at(context.frame_time(frame)) ? m_offset_values[frame] : 0.f;
- update_ended_state(context);
}
-
OscillatorRenderNode::OscillatorRenderNode(NodeID node_id, size_t quantum_size, NonnullRefPtr<RenderAudioParam> frequency, NonnullRefPtr<RenderAudioParam> detune)
- : ScheduledSourceRenderNode(node_id, 0, 1, quantum_size)
- , m_frequency(move(frequency))
- , m_detune(move(detune))
-{
- m_frequency_values.resize(quantum_size);
- m_detune_values.resize(quantum_size);
-}
-
-void OscillatorRenderNode::handle_message(NodeMessage const& message)
-{
- message.visit(
- [&](SetOscillatorWaveform const& set_waveform) {
- m_type = set_waveform.type;
- m_periodic_wave = set_waveform.periodic_wave;
-
- // https://webaudio.github.io/web-audio-api/#waveform-normalization
- // If the internal slot [[normalize]] of this PeriodicWave is true (the default), the waveform defined in
- // the previous section is normalized so that the maximum value is 1.
- m_periodic_wave_scale = 1.f;
- if (m_periodic_wave && m_periodic_wave->normalize) {
- float maximum_amplitude = 0.f;
- constexpr size_t normalization_sample_count = 4096;
- for (size_t sample_index = 0; sample_index < normalization_sample_count; ++sample_index) {
- auto phase = 2 * AK::Pi<double> * sample_index / normalization_sample_count;
- float amplitude = 0.f;
- for (size_t harmonic = 1; harmonic < m_periodic_wave->real.size(); ++harmonic)
- amplitude += m_periodic_wave->real[harmonic] * static_cast<float>(AK::cos(harmonic * phase))
- + m_periodic_wave->imag[harmonic] * static_cast<float>(AK::sin(harmonic * phase));
- maximum_amplitude = max(maximum_amplitude, AK::abs(amplitude));
- }
- if (maximum_amplitude > 0.f)
- m_periodic_wave_scale = 1.f / maximum_amplitude;
- }
- },
- [&](auto const& other_message) { ScheduledSourceRenderNode::handle_message(other_message); });
-}
-
-// https://webaudio.github.io/web-audio-api/#oscillator-coefficients
-float OscillatorRenderNode::sample_waveform(double phase, double frequency, double nyquist_frequency) const
+ : RenderNode(RustFFI::web_audio_node_create_oscillator(node_id.value(), quantum_size, frequency->rust_param(), detune->rust_param()))
{
- switch (m_type) {
- case Bindings::OscillatorType::Sine:
- return static_cast<float>(AK::sin(phase));
- case Bindings::OscillatorType::Square: {
- // b[n] = 2/(nπ) * (1 - cos(nπ))
- // NB: This is 4/(nπ) for odd n and 0 for even n.
- auto harmonic_count = frequency != 0 ? static_cast<size_t>(nyquist_frequency / AK::abs(frequency)) : MAX_OSCILLATOR_HARMONICS;
- harmonic_count = min(harmonic_count, MAX_OSCILLATOR_HARMONICS);
- double value = 0;
- for (size_t harmonic = 1; harmonic <= harmonic_count; harmonic += 2) {
- auto coefficient = 4 / (harmonic * AK::Pi<double>);
- value += coefficient * AK::sin(harmonic * phase);
- }
- return static_cast<float>(value);
- }
- case Bindings::OscillatorType::Sawtooth: {
- // b[n] = (-1)^(n+1) * 2/(nπ)
- auto harmonic_count = frequency != 0 ? static_cast<size_t>(nyquist_frequency / AK::abs(frequency)) : MAX_OSCILLATOR_HARMONICS;
- harmonic_count = min(harmonic_count, MAX_OSCILLATOR_HARMONICS);
- double value = 0;
- for (size_t harmonic = 1; harmonic <= harmonic_count; ++harmonic) {
- auto coefficient = 2 / (harmonic * AK::Pi<double>);
- if (harmonic % 2 == 0)
- coefficient = -coefficient;
- value += coefficient * AK::sin(harmonic * phase);
- }
- return static_cast<float>(value);
- }
- case Bindings::OscillatorType::Triangle: {
- // b[n] = 8 * sin(nπ/2) / (nπ)²
- // NB: This alternates sign for odd n and is 0 for even n.
- auto harmonic_count = frequency != 0 ? static_cast<size_t>(nyquist_frequency / AK::abs(frequency)) : MAX_OSCILLATOR_HARMONICS;
- harmonic_count = min(harmonic_count, MAX_OSCILLATOR_HARMONICS);
- double value = 0;
- auto sign = 1.;
- for (size_t harmonic = 1; harmonic <= harmonic_count; harmonic += 2) {
- auto coefficient = sign * 8 / (harmonic * harmonic * AK::Pi<double> * AK::Pi<double>);
- value += coefficient * AK::sin(harmonic * phase);
- sign = -sign;
- }
- return static_cast<float>(value);
- }
- case Bindings::OscillatorType::Custom: {
- if (!m_periodic_wave)
- return 0.f;
- auto harmonic_limit = m_periodic_wave->real.size();
- double value = 0;
- for (size_t harmonic_index = 1; harmonic_index < harmonic_limit; ++harmonic_index) {
- value += m_periodic_wave->real[harmonic_index] * AK::cos(harmonic_index * phase)
- + m_periodic_wave->imag[harmonic_index] * AK::sin(harmonic_index * phase);
- }
- return static_cast<float>(value) * m_periodic_wave_scale;
- }
- }
- VERIFY_NOT_REACHED();
-}
-
-void OscillatorRenderNode::process_source(RenderGraph& graph, RenderContext const& context)
-{
- m_frequency->compute(graph, context, m_frequency_values);
- m_detune->compute(graph, context, m_detune_values);
-
- auto nyquist_frequency = context.sample_rate / 2;
- auto output_samples = output(0).channel(0);
- for (size_t frame = 0; frame < context.quantum_size; ++frame) {
- if (!is_active_at(context.frame_time(frame))) {
- output_samples[frame] = 0.f;
- continue;
- }
-
- // computedOscFrequency(t) = frequency(t) * pow(2, detune(t) / 1200)
- // NB: The computed frequency is clamped to the Nyquist frequency.
- auto computed_frequency = m_frequency_values[frame] * AK::exp2(m_detune_values[frame] / 1200.);
- computed_frequency = clamp(computed_frequency, -nyquist_frequency, nyquist_frequency);
-
- output_samples[frame] = sample_waveform(m_phase, computed_frequency, nyquist_frequency);
-
- m_phase += 2 * AK::Pi<double> * computed_frequency / context.sample_rate;
- m_phase = AK::fmod(m_phase, 2 * AK::Pi<double>);
- if (m_phase < 0)
- m_phase += 2 * AK::Pi<double>;
- }
- update_ended_state(context);
}
-
AudioBufferSourceRenderNode::AudioBufferSourceRenderNode(NodeID node_id, size_t quantum_size, NonnullRefPtr<RenderAudioParam> playback_rate, NonnullRefPtr<RenderAudioParam> detune)
- : ScheduledSourceRenderNode(node_id, 0, 1, quantum_size)
- , m_playback_rate(move(playback_rate))
- , m_detune(move(detune))
-{
- m_playback_rate_values.resize(quantum_size);
- m_detune_values.resize(quantum_size);
-}
-
-void AudioBufferSourceRenderNode::handle_message(NodeMessage const& message)
-{
- message.visit(
- [&](StartBufferSource const& start_buffer_source) {
- ScheduledSourceRenderNode::handle_message(NodeMessage { StartSource { start_buffer_source.node_id, start_buffer_source.when } });
- m_offset = start_buffer_source.offset;
- m_duration = start_buffer_source.duration;
- if (start_buffer_source.buffer)
- m_buffer = start_buffer_source.buffer;
- },
- [&](SetBufferSourceParameters const& set_parameters) {
- m_loop = set_parameters.loop;
- m_loop_start = set_parameters.loop_start;
- m_loop_end = set_parameters.loop_end;
- if (set_parameters.update_buffer)
- m_buffer = set_parameters.buffer;
- },
- [&](auto const& other_message) { ScheduledSourceRenderNode::handle_message(other_message); });
-}
-
-float AudioBufferSourceRenderNode::sample_buffer(size_t channel, double playhead_frames, double loop_start_frame, double loop_end_frame) const
+ : RenderNode(RustFFI::web_audio_node_create_audio_buffer_source(node_id.value(), quantum_size, playback_rate->rust_param(), detune->rust_param()))
{
- auto const& samples = m_buffer->channels[channel];
- auto index = static_cast<i64>(AK::floor(playhead_frames));
- auto fraction = static_cast<float>(playhead_frames - index);
-
- auto sample_at = [&](i64 sample_index) -> float {
- // When looping, interpolation across the loop end wraps around to the loop start.
- if (m_loop && sample_index >= static_cast<i64>(loop_end_frame) && loop_end_frame > loop_start_frame)
- sample_index -= static_cast<i64>(loop_end_frame - loop_start_frame);
- if (sample_index < 0 || sample_index >= static_cast<i64>(samples.size()))
- return 0.f;
- return samples[sample_index];
- };
- if (fraction == 0.f)
- return sample_at(index);
- // Past the last frame there is nothing to interpolate toward, so the slope leading into it is continued instead.
- if (!m_loop && index == static_cast<i64>(samples.size()) - 1) {
- if (index == 0)
- return sample_at(index);
- return sample_at(index) + fraction * (sample_at(index) - sample_at(index - 1));
- }
- return sample_at(index) + fraction * (sample_at(index + 1) - sample_at(index));
-}
-
-// https://webaudio.github.io/web-audio-api/#playback-AudioBufferSourceNode
-void AudioBufferSourceRenderNode::process_source(RenderGraph& graph, RenderContext const& context)
-{
- m_playback_rate->compute(graph, context, m_playback_rate_values);
- m_detune->compute(graph, context, m_detune_values);
-
- auto& source_output = output(0);
- source_output.set_channel_count(m_buffer ? m_buffer->channels.size() : 1);
- source_output.zero();
-
- if (!m_buffer || !has_started()) {
- update_ended_state(context);
- return;
- }
-
- // NB: The playback rate is k-rate, so a single computed value is used for the entire quantum. The playhead is
- // tracked in buffer sample frames so that unity-rate playback of a buffer at the context's sample rate
- // advances by exactly one frame per rendered frame and reproduces the buffer bit-exactly.
- auto computed_playback_rate = m_playback_rate_values[0] * AK::exp2(m_detune_values[0] / 1200.);
- auto buffer_sample_rate = static_cast<double>(m_buffer->sample_rate);
- auto playhead_increment = computed_playback_rate * buffer_sample_rate / context.sample_rate;
- auto buffer_length = static_cast<double>(m_buffer->length());
-
- // NB: Determine the effective loop region, in buffer sample frames.
- // https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-loopstart
- auto actual_loop_start = 0.;
- auto actual_loop_end = buffer_length;
- if (m_loop && m_loop_start >= 0 && m_loop_end > 0 && m_loop_start < m_loop_end) {
- actual_loop_start = min(m_loop_start * buffer_sample_rate, buffer_length);
- actual_loop_end = min(m_loop_end * buffer_sample_rate, buffer_length);
- }
-
- for (size_t frame = 0; frame < context.quantum_size; ++frame) {
- auto frame_time = context.frame_time(frame);
- if (!is_active_at(frame_time))
- continue;
-
- if (!m_playhead_valid) {
- // NB: Playback begins at the given offset, corrected for the source starting between two sample frames.
- m_playhead = m_offset * buffer_sample_rate;
- if (m_loop)
- m_playhead = min(m_playhead, actual_loop_end);
- else
- m_playhead = min(m_playhead, buffer_length);
- m_playhead += (frame_time - start_time()) * computed_playback_rate * buffer_sample_rate;
- m_playhead_valid = true;
- }
-
- // NB: Compare using a half-frame tolerance since m_played_time accumulates one frame's worth of content at
- // a time and would otherwise overshoot the duration by up to one frame due to floating-point rounding.
- auto frame_consumption = AK::abs(computed_playback_rate) / context.sample_rate;
- if (m_duration.has_value() && m_played_time + frame_consumption / 2 >= *m_duration) {
- set_content_ended();
- continue;
- }
-
- if (m_loop) {
- auto loop_duration = actual_loop_end - actual_loop_start;
- if (loop_duration > 0) {
- while (m_playhead >= actual_loop_end)
- m_playhead -= loop_duration;
- while (m_playhead < actual_loop_start && playhead_increment < 0)
- m_playhead += loop_duration;
- }
- } else if (m_playhead >= buffer_length || (playhead_increment < 0 && m_playhead < 0)) {
- set_content_ended();
- continue;
- }
-
- for (size_t channel_index = 0; channel_index < m_buffer->channels.size(); ++channel_index)
- source_output.channel(channel_index)[frame] = sample_buffer(channel_index, m_playhead, actual_loop_start, actual_loop_end);
-
- m_playhead += playhead_increment;
- m_played_time += AK::abs(computed_playback_rate) / context.sample_rate;
- }
- update_ended_state(context);
}
-
DelayRenderNode::DelayRenderNode(NodeID node_id, size_t quantum_size, NonnullRefPtr<RenderAudioParam> delay_time, double max_delay_time)
- : RenderNode(node_id, 1, 1, quantum_size)
- , m_delay_time(move(delay_time))
- , m_max_delay_time(max_delay_time)
+ : RenderNode(RustFFI::web_audio_node_create_delay(node_id.value(), quantum_size, delay_time->rust_param(), max_delay_time))
{
- m_delay_values.resize(quantum_size);
-}
-
-void DelayRenderNode::process(RenderGraph& graph, RenderContext const& context)
-{
- auto const& input = pull_input(graph, context, 0);
- m_delay_time->compute(graph, context, m_delay_values);
-
- auto history_length = static_cast<size_t>(AK::ceil(m_max_delay_time * context.sample_rate)) + 2;
- if (m_history.size() != input.channel_count() || (!m_history.is_empty() && m_history.first().size() != history_length)) {
- m_history.resize_and_keep_capacity(input.channel_count());
- for (auto& channel_history : m_history) {
- channel_history.clear_with_capacity();
- channel_history.resize(history_length);
- }
- m_write_index = 0;
- }
-
- auto& delay_output = output(0);
- delay_output.set_channel_count(input.channel_count());
-
- for (size_t frame = 0; frame < context.quantum_size; ++frame) {
- auto delay_seconds = clamp(static_cast<double>(m_delay_values[frame]), 0., m_max_delay_time);
- auto delay_frames = delay_seconds * context.sample_rate;
-
- for (size_t channel_index = 0; channel_index < input.channel_count(); ++channel_index) {
- auto& channel_history = m_history[channel_index];
- channel_history[m_write_index] = input.channel(channel_index)[frame];
-
- // Read with linear interpolation to support fractional delays.
- auto read_position = static_cast<double>(m_write_index) - delay_frames;
- while (read_position < 0)
- read_position += history_length;
- auto read_index = static_cast<size_t>(read_position);
- auto fraction = static_cast<float>(read_position - read_index);
- auto sample_a = channel_history[read_index % history_length];
- auto sample_b = channel_history[(read_index + 1) % history_length];
- delay_output.channel(channel_index)[frame] = sample_a + fraction * (sample_b - sample_a);
- }
- m_write_index = (m_write_index + 1) % history_length;
- }
}
-
StereoPannerRenderNode::StereoPannerRenderNode(NodeID node_id, size_t quantum_size, NonnullRefPtr<RenderAudioParam> pan)
- : RenderNode(node_id, 1, 1, quantum_size, 2)
- , m_pan(move(pan))
-{
- set_channel_count_mode(Bindings::ChannelCountMode::ClampedMax);
- m_pan_values.resize(quantum_size);
-}
-
-// https://webaudio.github.io/web-audio-api/#stereopanner-algorithm
-void StereoPannerRenderNode::process(RenderGraph& graph, RenderContext const& context)
+ : RenderNode(RustFFI::web_audio_node_create_stereo_panner(node_id.value(), quantum_size, pan->rust_param()))
{
- auto const& input = pull_input(graph, context, 0);
- m_pan->compute(graph, context, m_pan_values);
-
- auto& panner_output = output(0);
- panner_output.set_channel_count(2);
- auto output_left = panner_output.channel(0);
- auto output_right = panner_output.channel(1);
-
- auto input_left = input.channel(0);
- auto input_right = input.channel_count() > 1 ? input.channel(1) : input.channel(0);
-
- for (size_t frame = 0; frame < context.quantum_size; ++frame) {
- // Let pan be the computedValue of the pan AudioParam of this StereoPannerNode.
- // Clamp pan to [-1, 1].
- auto pan = clamp(m_pan_values[frame], -1.f, 1.f);
-
- // Calculate x by normalizing pan value to [0, 1].
- double x;
- if (input.channel_count() == 1)
- x = (pan + 1) / 2.;
- else
- x = pan <= 0 ? pan + 1. : pan;
-
- // Left and right gain values are calculated as: gainL = cos(x * π / 2); gainR = sin(x * π / 2);
- auto [gain_left, gain_right] = equal_power_pan_gains(x);
-
- // For mono input, the stereo output is calculated as: outputL = input * gainL; outputR = input * gainR;
- // NB: For stereo input, the attenuated channel is mixed into the opposite output channel instead.
- if (input.channel_count() == 1) {
- output_left[frame] = input_left[frame] * gain_left;
- output_right[frame] = input_left[frame] * gain_right;
- } else if (pan <= 0) {
- output_left[frame] = input_left[frame] + input_right[frame] * gain_left;
- output_right[frame] = input_right[frame] * gain_right;
- } else {
- output_left[frame] = input_left[frame] * gain_left;
- output_right[frame] = input_right[frame] + input_left[frame] * gain_right;
- }
- }
}
-
ChannelSplitterRenderNode::ChannelSplitterRenderNode(NodeID node_id, size_t quantum_size, size_t number_of_outputs)
- : RenderNode(node_id, 1, number_of_outputs, quantum_size)
-{
- set_channel_count(number_of_outputs);
- set_channel_count_mode(Bindings::ChannelCountMode::Explicit);
- set_channel_interpretation(Bindings::ChannelInterpretation::Discrete);
-}
-
-void ChannelSplitterRenderNode::process(RenderGraph& graph, RenderContext const& context)
+ : RenderNode(RustFFI::web_audio_node_create_channel_splitter(node_id.value(), quantum_size, number_of_outputs))
{
- auto const& input = pull_input(graph, context, 0);
- for (size_t output_index = 0; output_index < output_count(); ++output_index) {
- auto output_samples = output(output_index).channel(0);
- if (output_index < input.channel_count()) {
- auto input_samples = input.channel(output_index);
- for (size_t frame = 0; frame < context.quantum_size; ++frame)
- output_samples[frame] = input_samples[frame];
- } else {
- output_samples.fill(0.f);
- }
- }
}
-
ChannelMergerRenderNode::ChannelMergerRenderNode(NodeID node_id, size_t quantum_size, size_t number_of_inputs)
- : RenderNode(node_id, number_of_inputs, 1, quantum_size, number_of_inputs)
-{
- set_channel_count(1);
- set_channel_count_mode(Bindings::ChannelCountMode::Explicit);
-}
-
-void ChannelMergerRenderNode::process(RenderGraph& graph, RenderContext const& context)
+ : RenderNode(RustFFI::web_audio_node_create_channel_merger(node_id.value(), quantum_size, number_of_inputs))
{
- auto& merger_output = output(0);
- merger_output.set_channel_count(input_count());
- for (size_t input_index = 0; input_index < input_count(); ++input_index) {
- auto const& input = pull_input(graph, context, input_index);
- auto input_samples = input.channel(0);
- auto output_samples = merger_output.channel(input_index);
- for (size_t frame = 0; frame < context.quantum_size; ++frame)
- output_samples[frame] = input_samples[frame];
- }
}
-
BiquadFilterRenderNode::BiquadFilterRenderNode(NodeID node_id, size_t quantum_size, NonnullRefPtr<RenderAudioParam> frequency, NonnullRefPtr<RenderAudioParam> detune, NonnullRefPtr<RenderAudioParam> q, NonnullRefPtr<RenderAudioParam> gain)
- : RenderNode(node_id, 1, 1, quantum_size)
- , m_frequency(move(frequency))
- , m_detune(move(detune))
- , m_q(move(q))
- , m_gain(move(gain))
-{
- m_frequency_values.resize(quantum_size);
- m_detune_values.resize(quantum_size);
- m_q_values.resize(quantum_size);
- m_gain_values.resize(quantum_size);
-}
-
-void BiquadFilterRenderNode::handle_message(NodeMessage const& message)
-{
- message.visit(
- [&](SetBiquadFilterType const& set_type) { m_type = set_type.type; },
- [](auto const&) { });
-}
-
-void BiquadFilterRenderNode::process(RenderGraph& graph, RenderContext const& context)
+ : RenderNode(RustFFI::web_audio_node_create_biquad_filter(node_id.value(), quantum_size, frequency->rust_param(), detune->rust_param(), q->rust_param(), gain->rust_param()))
{
- auto const& input = pull_input(graph, context, 0);
- m_frequency->compute(graph, context, m_frequency_values);
- m_detune->compute(graph, context, m_detune_values);
- m_q->compute(graph, context, m_q_values);
- m_gain->compute(graph, context, m_gain_values);
-
- if (m_filter_states.size() != input.channel_count())
- m_filter_states.resize(input.channel_count());
-
- auto nyquist_frequency = context.sample_rate / 2;
- auto compute_coefficients_for_frame = [&](size_t frame) {
- auto computed_frequency = m_frequency_values[frame] * AK::exp2(m_detune_values[frame] / 1200.);
- auto normalized_frequency = clamp(computed_frequency / nyquist_frequency, 0., 1.);
- return compute_biquad_coefficients(m_type, normalized_frequency, m_q_values[frame], m_gain_values[frame]);
- };
- auto parameters_changed = [&](size_t frame) {
- return m_frequency_values[frame] != m_frequency_values[frame - 1]
- || m_detune_values[frame] != m_detune_values[frame - 1]
- || m_q_values[frame] != m_q_values[frame - 1]
- || m_gain_values[frame] != m_gain_values[frame - 1];
- };
-
- auto& filter_output = output(0);
- filter_output.set_channel_count(input.channel_count());
-
- // AD-HOC: The coefficients are recomputed whenever the computed parameter values change, so a-rate automation is
- // applied with per-frame resolution while k-rate parameters use a single set of coefficients for the
- // entire quantum.
- auto coefficients = compute_coefficients_for_frame(0);
- for (size_t frame = 0; frame < context.quantum_size; ++frame) {
- if (frame > 0 && parameters_changed(frame))
- coefficients = compute_coefficients_for_frame(frame);
- for (size_t channel_index = 0; channel_index < input.channel_count(); ++channel_index) {
- auto& state = m_filter_states[channel_index];
- double x = input.channel(channel_index)[frame];
- auto y = coefficients.b0 * x + coefficients.b1 * state.x1 + coefficients.b2 * state.x2
- - coefficients.a1 * state.y1 - coefficients.a2 * state.y2;
- state.x2 = state.x1;
- state.x1 = x;
- state.y2 = state.y1;
- state.y1 = y;
- filter_output.channel(channel_index)[frame] = static_cast<float>(y);
- }
- }
}
-
IIRFilterRenderNode::IIRFilterRenderNode(NodeID node_id, size_t quantum_size, Vector<double> feedforward, Vector<double> feedback)
- : RenderNode(node_id, 1, 1, quantum_size)
- , m_feedforward(move(feedforward))
- , m_feedback(move(feedback))
-{
- VERIFY(m_feedforward.size() < history_size);
- VERIFY(m_feedback.size() < history_size);
-}
-
-void IIRFilterRenderNode::process(RenderGraph& graph, RenderContext const& context)
+ : RenderNode(RustFFI::web_audio_node_create_iir_filter(node_id.value(), quantum_size, feedforward.span(), feedback.span()))
{
- auto const& input = pull_input(graph, context, 0);
-
- // The number of channels of the output always equals the number of channels of the input.
- auto& filter_output = output(0);
- filter_output.set_channel_count(input.channel_count());
- if (m_filter_states.size() != input.channel_count())
- m_filter_states.resize(input.channel_count());
-
- // https://webaudio.github.io/web-audio-api/#IIRFilterNode-filter-definition
- // sum_{k=0}^{N} a_k y(n-k) = sum_{k=0}^{M} b_k x(n-k), where a_0 is 1 as the coefficients are normalized.
- static constexpr size_t history_mask = history_size - 1;
- for (size_t channel_index = 0; channel_index < input.channel_count(); ++channel_index) {
- auto& state = m_filter_states[channel_index];
- auto input_samples = input.channel(channel_index);
- auto output_samples = filter_output.channel(channel_index);
- auto position = m_position;
- for (size_t frame = 0; frame < context.quantum_size; ++frame, ++position) {
- double x = input_samples[frame];
- double y = m_feedforward[0] * x;
- for (size_t k = 1; k < m_feedforward.size(); ++k)
- y += m_feedforward[k] * state.inputs[(position - k) & history_mask];
- for (size_t k = 1; k < m_feedback.size(); ++k)
- y -= m_feedback[k] * state.outputs[(position - k) & history_mask];
- // NB: A decaying output would otherwise settle on subnormal numbers, which are slow to compute with.
- if (AK::fabs(y) < NumericLimits<double>::min_normal())
- y = 0;
- state.inputs[position & history_mask] = x;
- state.outputs[position & history_mask] = y;
- output_samples[frame] = static_cast<float>(y);
- }
- }
- m_position += context.quantum_size;
}
-
WaveShaperRenderNode::WaveShaperRenderNode(NodeID node_id, size_t quantum_size)
- : RenderNode(node_id, 1, 1, quantum_size)
-{
- m_two_times_samples.resize(quantum_size * 2);
- m_four_times_samples.resize(quantum_size * 4);
-}
-
-void WaveShaperRenderNode::handle_message(NodeMessage const& message)
-{
- message.visit(
- [&](SetWaveShaperParameters const& parameters) {
- m_curve = parameters.curve;
- m_oversample = parameters.oversample;
- },
- [](auto const&) { });
-}
-
-// https://webaudio.github.io/web-audio-api/#dom-waveshapernode-curve
-float WaveShaperRenderNode::shape(float sample) const
-{
- // 1. Let x be the input sample, y be the corresponding output of the node, c_k be the k'th element of the curve,
- // and N be the length of the curve.
- auto const& curve = m_curve->values;
- auto curve_length = curve.size();
-
- // 2. Let v = (N-1)/2 (x + 1), k = floor(v), f = v - k
- double v = (curve_length - 1) / 2.0 * (static_cast<double>(sample) + 1);
-
- // 3. Then y = c_0 if v < 0, c_{N-1} if v >= N - 1, and (1-f) c_k + f c_{k+1} otherwise.
- // NB: A NaN sample maps to c_0 as well.
- if (!(v >= 0))
- return curve.first();
- if (v >= curve_length - 1)
- return curve.last();
- auto k = static_cast<size_t>(v);
- double f = v - k;
- return static_cast<float>((1 - f) * curve[k] + f * curve[k + 1]);
-}
-
-// NB: The up-sampling and down-sampling filters are not specified. These use a windowed sinc filter whose cutoff is
-// half its band.
-Array<float, WaveShaperRenderNode::half_band_filter_length> const& WaveShaperRenderNode::half_band_filter_coefficients()
-{
- static auto const coefficients = [] {
- static constexpr size_t length = half_band_filter_length;
- Array<double, length> taps {};
- double sum = 0;
- for (size_t index = 0; index < length; ++index) {
- double offset = static_cast<double>(index) - (length - 1) / 2.0;
- double sinc = offset == 0 ? 1 : AK::sin(AK::Pi<double> * offset / 2) / (AK::Pi<double> * offset / 2);
- double phase = 2 * AK::Pi<double> * index / (length - 1);
- double blackman_window = 0.42 - 0.5 * AK::cos(phase) + 0.08 * AK::cos(2 * phase);
- taps[index] = sinc * blackman_window;
- sum += taps[index];
- }
- Array<float, length> result {};
- for (size_t index = 0; index < length; ++index)
- result[index] = static_cast<float>(taps[index] / sum);
- return result;
- }();
- return coefficients;
-}
-
-float WaveShaperRenderNode::HalfBandFilter::process(float sample)
-{
- auto const& coefficients = half_band_filter_coefficients();
- // NB: Every sample is stored twice, so that the last samples are contiguous wherever the ring buffer starts.
- history[position] = sample;
- history[position + half_band_filter_length] = sample;
- auto const* newest_sample = &history[position + half_band_filter_length];
- float result = 0;
- for (size_t index = 0; index < half_band_filter_length; ++index)
- result += coefficients[index] * *(newest_sample - index);
- position = position + 1 == half_band_filter_length ? 0 : position + 1;
- return result;
-}
-
-void WaveShaperRenderNode::up_sample(HalfBandFilter& filter, ReadonlySpan<float> input, Span<float> output)
-{
- VERIFY(output.size() == input.size() * 2);
- // NB: The zeros between the samples halve the gain of the filter, which the factor of 2 restores.
- for (size_t index = 0; index < input.size(); ++index) {
- output[2 * index] = 2 * filter.process(input[index]);
- output[2 * index + 1] = 2 * filter.process(0);
- }
-}
-
-void WaveShaperRenderNode::down_sample(HalfBandFilter& filter, ReadonlySpan<float> input, Span<float> output)
-{
- VERIFY(input.size() == output.size() * 2);
- for (size_t index = 0; index < output.size(); ++index) {
- output[index] = filter.process(input[2 * index]);
- (void)filter.process(input[2 * index + 1]);
- }
-}
-
-void WaveShaperRenderNode::process(RenderGraph& graph, RenderContext const& context)
-{
- auto const& input = pull_input(graph, context, 0);
-
- // The number of channels of the output always equals the number of channels of the input.
- auto& shaper_output = output(0);
- shaper_output.set_channel_count(input.channel_count());
- if (m_channel_states.size() != input.channel_count())
- m_channel_states.resize(input.channel_count());
-
- for (size_t channel_index = 0; channel_index < input.channel_count(); ++channel_index) {
- auto input_samples = input.channel(channel_index).slice(0, context.quantum_size);
- auto output_samples = shaper_output.channel(channel_index).slice(0, context.quantum_size);
-
- // Initially the curve attribute is null, which means that the WaveShaperNode will pass its input to its output
- // without modification.
- if (!m_curve) {
- input_samples.copy_to(output_samples);
- continue;
- }
-
- auto& state = m_channel_states[channel_index];
- switch (m_oversample) {
- case Bindings::OverSampleType::None:
- // The default value is "none", meaning the curve will be applied directly to the input samples.
- for (size_t frame = 0; frame < context.quantum_size; ++frame)
- output_samples[frame] = shape(input_samples[frame]);
- break;
- case Bindings::OverSampleType::_2x: {
- // 1. Up-sample the input samples to 2x or 4x the sample-rate of the AudioContext. Thus for each render
- // quantum, generate twice (for 2x) or four times (for 4x) samples.
- auto samples = m_two_times_samples.span();
- up_sample(state.up_sampling_filters[0], input_samples, samples);
-
- // 2. Apply the shaping curve.
- for (auto& sample : samples)
- sample = shape(sample);
-
- // 3. Down-sample the result back to the sample-rate of the AudioContext. Thus taking the previously
- // processed samples processed samples, generating a single render quantum worth of samples as the
- // final result.
- down_sample(state.down_sampling_filters[0], samples, output_samples);
- break;
- }
- case Bindings::OverSampleType::_4x: {
- // 1. Up-sample the input samples to 2x or 4x the sample-rate of the AudioContext. Thus for each render
- // quantum, generate twice (for 2x) or four times (for 4x) samples.
- auto two_times_samples = m_two_times_samples.span();
- auto four_times_samples = m_four_times_samples.span();
- up_sample(state.up_sampling_filters[0], input_samples, two_times_samples);
- up_sample(state.up_sampling_filters[1], two_times_samples, four_times_samples);
-
- // 2. Apply the shaping curve.
- for (auto& sample : four_times_samples)
- sample = shape(sample);
-
- // 3. Down-sample the result back to the sample-rate of the AudioContext. Thus taking the previously
- // processed samples processed samples, generating a single render quantum worth of samples as the
- // final result.
- down_sample(state.down_sampling_filters[1], four_times_samples, two_times_samples);
- down_sample(state.down_sampling_filters[0], two_times_samples, output_samples);
- break;
- }
- }
- }
-}
-
-namespace {
-
-// Gfx::DoubleVector3::normalize() divides by the length unconditionally, which would produce NaN components for a zero
-// vector; the spatialization math needs a zero vector to normalize back to a zero vector instead.
-Gfx::DoubleVector3 safe_normalized(Gfx::DoubleVector3 const& vector)
-{
- if (vector.length() == 0)
- return {};
- return vector.normalized();
-}
-
-// https://webaudio.github.io/web-audio-api/#azimuth-elevation
-double compute_azimuth(Gfx::DoubleVector3 const& source_position, Gfx::DoubleVector3 const& listener_position, Gfx::DoubleVector3 const& listener_forward, Gfx::DoubleVector3 const& listener_up)
-{
- // Calculate the source-listener vector.
- auto source_listener = source_position - listener_position;
-
- // Handle degenerate case if source and listener are at the same point.
- if (source_listener.length() == 0)
- return 0;
- source_listener = source_listener.normalized();
-
- // Align axes.
- auto listener_right = listener_forward.cross(listener_up);
-
- // Handle the case where listener's 'up' and 'forward' vectors are linearly dependent, in which case 'right'
- // cannot be determined.
- if (listener_right.length() == 0)
- return 0;
-
- // Determine a unit vector orthogonal to listener's right, forward.
- auto listener_right_norm = listener_right.normalized();
- auto listener_forward_norm = safe_normalized(listener_forward);
- auto up = listener_right_norm.cross(listener_forward_norm);
-
- auto up_projection = source_listener.dot(up);
- auto projected_source = source_listener - up * up_projection;
- projected_source = safe_normalized(projected_source);
-
- auto azimuth = 180 * AK::acos(clamp(projected_source.dot(listener_right_norm), -1., 1.)) / AK::Pi<double>;
-
- // Source in front or behind the listener.
- auto front_back = projected_source.dot(listener_forward_norm);
- if (front_back < 0)
- azimuth = 360 - azimuth;
-
- // Make azimuth relative to "forward" and not "right" listener vector.
- // AD-HOC: This is equivalent to the spec's mapping, but lands directly in the range [-180, 180].
- if (azimuth <= 90)
- azimuth = 90 - azimuth;
- else
- azimuth = 450 - azimuth;
- if (azimuth > 180)
- azimuth -= 360;
- return azimuth;
-}
-
-// https://webaudio.github.io/web-audio-api/#Spatialization-distance-effects
-double compute_distance_gain(double distance, SetPannerParameters const& config)
-{
- auto ref_distance = config.ref_distance;
- auto max_distance = config.max_distance;
- auto rolloff_factor = config.rolloff_factor;
-
- // AD-HOC: The distance is clamped to the interval spanned by refDistance and maxDistance for every distance
- // model, matching other engines.
- auto clamped_distance = clamp(distance, min(ref_distance, max_distance), max(ref_distance, max_distance));
-
- switch (config.distance_model) {
- case Bindings::DistanceModelType::Linear: {
- if (ref_distance == max_distance)
- return 1 - clamp(rolloff_factor, 0., 1.);
- return 1 - clamp(rolloff_factor, 0., 1.) * (clamped_distance - ref_distance) / (max_distance - ref_distance);
- }
- case Bindings::DistanceModelType::Inverse:
- if (ref_distance + rolloff_factor * (clamped_distance - ref_distance) == 0)
- return 1;
- return ref_distance / (ref_distance + rolloff_factor * (clamped_distance - ref_distance));
- case Bindings::DistanceModelType::Exponential:
- if (ref_distance == 0)
- return 1;
- return AK::pow(clamped_distance / ref_distance, -rolloff_factor);
- }
- VERIFY_NOT_REACHED();
-}
-
-// https://webaudio.github.io/web-audio-api/#Spatialization-sound-cones
-double compute_cone_gain(Gfx::DoubleVector3 const& source_position, Gfx::DoubleVector3 const& source_orientation, Gfx::DoubleVector3 const& listener_position, SetPannerParameters const& config)
+ : RenderNode(RustFFI::web_audio_node_create_wave_shaper(node_id.value(), quantum_size))
{
- if (source_orientation.length() == 0 || (config.cone_inner_angle == 360 && config.cone_outer_angle == 360))
- return 1;
-
- // Normalized source-listener vector.
- auto source_to_listener = safe_normalized(listener_position - source_position);
- auto normalized_source_orientation = source_orientation.normalized();
-
- // Angle between the source orientation vector and the source-listener vector.
- auto angle = 180 * AK::acos(clamp(source_to_listener.dot(normalized_source_orientation), -1., 1.)) / AK::Pi<double>;
- auto absolute_angle = AK::abs(angle);
-
- // Divide by 2 here since API is entire angle (not half-angle).
- auto absolute_inner_angle = AK::abs(config.cone_inner_angle) / 2;
- auto absolute_outer_angle = AK::abs(config.cone_outer_angle) / 2;
-
- if (absolute_angle <= absolute_inner_angle) {
- // No attenuation.
- return 1;
- }
- if (absolute_angle >= absolute_outer_angle) {
- // Max attenuation.
- return config.cone_outer_gain;
- }
-
- // Between inner and outer cones: inner -> outer, x goes from 0 -> 1.
- auto x = (absolute_angle - absolute_inner_angle) / (absolute_outer_angle - absolute_inner_angle);
- return 1 + (config.cone_outer_gain - 1) * x;
-}
-
}
-
ConvolverRenderNode::ConvolverRenderNode(NodeID node_id, size_t quantum_size)
- : RenderNode(node_id, 1, 1, quantum_size)
- , m_fft(2 * quantum_size)
- , m_transform_real(MUST(FixedArray<float>::create(2 * quantum_size)))
- , m_transform_imag(MUST(FixedArray<float>::create(2 * quantum_size)))
- , m_accumulator_real(MUST(FixedArray<double>::create(quantum_size + 1)))
- , m_accumulator_imag(MUST(FixedArray<double>::create(quantum_size + 1)))
-{
- set_channel_count_mode(Bindings::ChannelCountMode::ClampedMax);
- for (auto& window : m_window)
- window = MUST(FixedArray<float>::create(2 * quantum_size));
-}
-
-void ConvolverRenderNode::handle_message(NodeMessage const& message)
-{
- if (auto const* set_kernel = message.get_pointer<SetConvolverKernel>()) {
- m_kernel = set_kernel->kernel;
- m_delay_line = set_kernel->delay_line;
- m_delay_line_index = 0;
- }
-}
-
-// Folds a second channel's history into the first the way down-mixing folds the channels themselves.
-static void average_history(Span<float> into, ReadonlySpan<float> other)
-{
- for (size_t index = 0; index < into.size(); ++index)
- into[index] = 0.5f * (into[index] + other[index]);
-}
-
-void ConvolverRenderNode::process(RenderGraph& graph, RenderContext const& context)
-{
- auto const& input = pull_input(graph, context, 0);
- auto& convolver_output = output(0);
-
- auto input_channel_count = min(input.channel_count(), ConvolverDelayLine::MAX_CHANNEL_COUNT);
-
- // Mix the history the same way the input itself is mixed, so that the tail of the impulse response keeps playing
- // across a change in the number of input channels.
- // https://webaudio.github.io/web-audio-api/#channel-up-mixing-and-down-mixing
- if (m_input_channel_count == 1 && input_channel_count == 2) {
- m_window[0].span().copy_to(m_window[1].span());
- if (m_delay_line) {
- m_delay_line->real(0).copy_to(m_delay_line->real(1));
- m_delay_line->imag(0).copy_to(m_delay_line->imag(1));
- }
- } else if (m_input_channel_count == 2 && input_channel_count == 1) {
- average_history(m_window[0].span(), m_window[1].span());
- if (m_delay_line) {
- average_history(m_delay_line->real(0), m_delay_line->real(1));
- average_history(m_delay_line->imag(0), m_delay_line->imag(1));
- }
- }
- m_input_channel_count = input_channel_count;
-
- auto partition_size = context.quantum_size;
- for (size_t channel = 0; channel < input_channel_count; ++channel) {
- // Slide this quantum's samples into the window, dropping the oldest half.
- auto window = m_window[channel].span();
- auto input_samples = input.channel(channel);
- for (size_t frame = 0; frame < partition_size; ++frame) {
- window[frame] = window[partition_size + frame];
- window[partition_size + frame] = input_samples[frame];
- }
- }
-
- if (!m_kernel) {
- convolver_output.set_channel_count(1);
- convolver_output.zero();
- return;
- }
-
- auto transform_size = m_fft.size();
- auto partition_count = m_kernel->partition_count();
- auto delay_line_length = m_delay_line->length();
- auto bin_count = m_kernel->bin_count();
-
- if (partition_count > 0) {
- for (size_t channel = 0; channel < input_channel_count; ++channel) {
- auto window = m_window[channel].span();
- for (size_t frame = 0; frame < transform_size; ++frame) {
- m_transform_real[frame] = window[frame];
- m_transform_imag[frame] = 0;
- }
- m_fft.transform(m_transform_real.span(), m_transform_imag.span());
-
- auto* delay_line_real = m_delay_line->real(channel).data() + m_delay_line_index * bin_count;
- auto* delay_line_imag = m_delay_line->imag(channel).data() + m_delay_line_index * bin_count;
- for (size_t bin = 0; bin < bin_count; ++bin) {
- delay_line_real[bin] = m_transform_real[bin];
- delay_line_imag[bin] = m_transform_imag[bin];
- }
- }
- }
-
- // https://webaudio.github.io/web-audio-api/#Convolution-channel-configurations
- size_t right_channel = input_channel_count > 1 ? 1 : 0;
- Array<Route, 4> routes;
- size_t route_count = 0;
- switch (m_kernel->channel_count()) {
- case 1:
- routes[route_count++] = { 0, 0, 0 };
- if (input_channel_count > 1)
- routes[route_count++] = { 1, 0, 1 };
- break;
- case 2:
- routes[route_count++] = { 0, 0, 0 };
- routes[route_count++] = { right_channel, 1, 1 };
- break;
- case 4:
- routes[route_count++] = { 0, 0, 0 };
- routes[route_count++] = { 0, 1, 1 };
- routes[route_count++] = { right_channel, 2, 0 };
- routes[route_count++] = { right_channel, 3, 1 };
- break;
- default:
- VERIFY_NOT_REACHED();
- }
-
- auto output_channel_count = m_kernel->channel_count() == 1 && input_channel_count == 1 ? 1u : 2u;
- convolver_output.set_channel_count(output_channel_count);
-
- for (size_t output_channel = 0; output_channel < output_channel_count; ++output_channel) {
- auto output_samples = convolver_output.channel(output_channel);
- for (size_t frame = 0; frame < partition_size; ++frame)
- output_samples[frame] = 0;
-
- for (size_t bin = 0; bin < bin_count; ++bin) {
- m_accumulator_real[bin] = 0;
- m_accumulator_imag[bin] = 0;
- }
-
- for (size_t route_index = 0; route_index < route_count; ++route_index) {
- auto route = routes[route_index];
- if (route.output_channel != output_channel)
- continue;
-
- auto window = m_window[route.input_channel].span();
- auto head = m_kernel->head(route.kernel_channel);
- for (size_t frame = 0; frame < partition_size; ++frame) {
- auto sample = 0.f;
- for (size_t tap = 0; tap < partition_size; ++tap)
- sample += head[tap] * window[partition_size + frame - tap];
- output_samples[frame] += sample;
- }
-
- auto const* delay_line_real = m_delay_line->real(route.input_channel).data();
- auto const* delay_line_imag = m_delay_line->imag(route.input_channel).data();
- for (size_t partition = 0; partition < partition_count; ++partition) {
- // Partition N of the impulse response pairs up with the window from N + 1 quanta ago.
- auto delay_line_slot = (m_delay_line_index + delay_line_length - partition - 1) % delay_line_length;
- auto const* input_real = delay_line_real + delay_line_slot * bin_count;
- auto const* input_imag = delay_line_imag + delay_line_slot * bin_count;
- auto const* kernel_real = m_kernel->partition_real(route.kernel_channel, partition).data();
- auto const* kernel_imag = m_kernel->partition_imag(route.kernel_channel, partition).data();
-
- for (size_t bin = 0; bin < bin_count; ++bin) {
- m_accumulator_real[bin] += input_real[bin] * kernel_real[bin] - input_imag[bin] * kernel_imag[bin];
- m_accumulator_imag[bin] += input_real[bin] * kernel_imag[bin] + input_imag[bin] * kernel_real[bin];
- }
- }
- }
-
- if (partition_count == 0)
- continue;
-
- // Restore the bins above Nyquist that the kernel and the delay line leave out.
- for (size_t bin = 0; bin < bin_count; ++bin) {
- m_transform_real[bin] = static_cast<float>(m_accumulator_real[bin]);
- m_transform_imag[bin] = static_cast<float>(m_accumulator_imag[bin]);
- }
- for (size_t bin = bin_count; bin < transform_size; ++bin) {
- m_transform_real[bin] = static_cast<float>(m_accumulator_real[transform_size - bin]);
- m_transform_imag[bin] = static_cast<float>(-m_accumulator_imag[transform_size - bin]);
- }
- m_fft.transform(m_transform_real.span(), m_transform_imag.span(), FFTDirection::Inverse);
-
- // The first half of the result is where the cyclic convolution wrapped around, and is discarded.
- for (size_t frame = 0; frame < partition_size; ++frame)
- output_samples[frame] += m_transform_real[partition_size + frame];
- }
-
- if (partition_count > 0)
- m_delay_line_index = (m_delay_line_index + 1) % delay_line_length;
-}
-
-PannerRenderNode::PannerRenderNode(NodeID node_id, size_t quantum_size, Params params, ListenerParams listener_params)
- : RenderNode(node_id, 1, 1, quantum_size, 2)
- , m_params(move(params))
- , m_listener_params(move(listener_params))
-{
- set_channel_count_mode(Bindings::ChannelCountMode::ClampedMax);
- m_param_values.resize(15);
- for (auto& values : m_param_values)
- values.resize(quantum_size);
-}
-
-void PannerRenderNode::handle_message(NodeMessage const& message)
-{
- message.visit(
- [&](SetPannerParameters const& parameters) { m_config = parameters; },
- [](auto const&) { });
-}
-
-void PannerRenderNode::for_each_param(Function<void(RenderAudioParam&)> const& callback)
+ : RenderNode(RustFFI::web_audio_node_create_convolver(node_id.value(), quantum_size))
{
- callback(*m_params.position_x);
- callback(*m_params.position_y);
- callback(*m_params.position_z);
- callback(*m_params.orientation_x);
- callback(*m_params.orientation_y);
- callback(*m_params.orientation_z);
}
-
-// https://webaudio.github.io/web-audio-api/#Spatialization
-void PannerRenderNode::process(RenderGraph& graph, RenderContext const& context)
-{
- auto const& input = pull_input(graph, context, 0);
- auto& panner_output = output(0);
- panner_output.set_channel_count(2);
- if (input.is_silent()) {
- panner_output.zero();
- return;
- }
-
- Array params {
- m_params.position_x.ptr(), m_params.position_y.ptr(), m_params.position_z.ptr(),
- m_params.orientation_x.ptr(), m_params.orientation_y.ptr(), m_params.orientation_z.ptr(),
- m_listener_params.position_x.ptr(), m_listener_params.position_y.ptr(), m_listener_params.position_z.ptr(),
- m_listener_params.forward_x.ptr(), m_listener_params.forward_y.ptr(), m_listener_params.forward_z.ptr(),
- m_listener_params.up_x.ptr(), m_listener_params.up_y.ptr(), m_listener_params.up_z.ptr()
- };
- for (size_t param_index = 0; param_index < params.size(); ++param_index)
- params[param_index]->compute(graph, context, m_param_values[param_index]);
-
- auto output_left = panner_output.channel(0);
- auto output_right = panner_output.channel(1);
- auto input_left = input.channel(0);
- auto input_right = input.channel_count() > 1 ? input.channel(1) : input.channel(0);
-
- for (size_t frame = 0; frame < context.quantum_size; ++frame) {
- Gfx::DoubleVector3 source_position { m_param_values[0][frame], m_param_values[1][frame], m_param_values[2][frame] };
- Gfx::DoubleVector3 source_orientation { m_param_values[3][frame], m_param_values[4][frame], m_param_values[5][frame] };
- Gfx::DoubleVector3 listener_position { m_param_values[6][frame], m_param_values[7][frame], m_param_values[8][frame] };
- Gfx::DoubleVector3 listener_forward { m_param_values[9][frame], m_param_values[10][frame], m_param_values[11][frame] };
- Gfx::DoubleVector3 listener_up { m_param_values[12][frame], m_param_values[13][frame], m_param_values[14][frame] };
-
- auto azimuth = compute_azimuth(source_position, listener_position, listener_forward, listener_up);
- auto distance = (source_position - listener_position).length();
- auto gain = static_cast<float>(compute_distance_gain(distance, m_config) * compute_cone_gain(source_position, source_orientation, listener_position, m_config));
-
- // https://webaudio.github.io/web-audio-api/#Spatialization-panning-algorithm
- // The azimuth value is first contained to be within the range [-90, 90].
- // NB: compute_azimuth() already produces a value in [-180, 180], so only the wrapping step remains.
- if (azimuth < -90)
- azimuth = -180 - azimuth;
- else if (azimuth > 90)
- azimuth = 180 - azimuth;
-
- double x;
- if (input.channel_count() == 1)
- x = (azimuth + 90) / 180;
- else
- x = azimuth <= 0 ? (azimuth + 90) / 90 : azimuth / 90;
-
- auto [gain_left, gain_right] = equal_power_pan_gains(x);
-
- if (input.channel_count() == 1) {
- output_left[frame] = input_left[frame] * gain_left * gain;
- output_right[frame] = input_left[frame] * gain_right * gain;
- } else if (azimuth <= 0) {
- output_left[frame] = (input_left[frame] + input_right[frame] * gain_left) * gain;
- output_right[frame] = input_right[frame] * gain_right * gain;
- } else {
- output_left[frame] = input_left[frame] * gain_left * gain;
- output_right[frame] = (input_right[frame] + input_left[frame] * gain_right) * gain;
- }
- }
-}
-
PassthroughRenderNode::PassthroughRenderNode(NodeID node_id, size_t quantum_size)
- : RenderNode(node_id, 1, 1, quantum_size)
+ : RenderNode(RustFFI::web_audio_node_create_passthrough(node_id.value(), quantum_size))
{
}
-
-void PassthroughRenderNode::process(RenderGraph& graph, RenderContext const& context)
+PannerRenderNode::PannerRenderNode(NodeID node_id, size_t quantum_size, Params params, ListenerParams listener_params)
+ : RenderNode([&] {
+ Array<void const*, 15> values { params.position_x->rust_param(), params.position_y->rust_param(), params.position_z->rust_param(),
+ params.orientation_x->rust_param(), params.orientation_y->rust_param(), params.orientation_z->rust_param(),
+ listener_params.position_x->rust_param(), listener_params.position_y->rust_param(), listener_params.position_z->rust_param(),
+ listener_params.forward_x->rust_param(), listener_params.forward_y->rust_param(), listener_params.forward_z->rust_param(),
+ listener_params.up_x->rust_param(), listener_params.up_y->rust_param(), listener_params.up_z->rust_param() };
+ return RustFFI::web_audio_node_create_panner(node_id.value(), quantum_size, values.span());
+ }())
{
- auto const& input = pull_input(graph, context, 0);
- output(0).copy_from(input);
}
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RenderNodes.h b/Libraries/LibWeb/WebAudio/Rendering/RenderNodes.h
index 9146d1294a4..749d2a4ca1d 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RenderNodes.h
+++ b/Libraries/LibWeb/WebAudio/Rendering/RenderNodes.h
@@ -1,343 +1,66 @@
/*
* Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
-
-#include <AK/Array.h>
-#include <AK/FixedArray.h>
-#include <AK/Math.h>
-#include <AK/NonnullRefPtr.h>
-#include <AK/Optional.h>
-#include <AK/RefPtr.h>
-#include <AK/Vector.h>
-#include <LibWeb/WebAudio/Rendering/AudioData.h>
-#include <LibWeb/WebAudio/Rendering/BiquadCoefficients.h>
-#include <LibWeb/WebAudio/Rendering/ConvolverKernel.h>
-#include <LibWeb/WebAudio/Rendering/FFT.h>
#include <LibWeb/WebAudio/Rendering/RenderNode.h>
-
namespace Web::WebAudio::Rendering {
-// Captures the mixed input signal so the renderer can copy it into the rendered buffer.
-// https://webaudio.github.io/web-audio-api/#AudioDestinationNode
class DestinationRenderNode final : public RenderNode {
public:
DestinationRenderNode(NodeID, size_t channel_count, size_t quantum_size);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
};
-
-// https://webaudio.github.io/web-audio-api/#GainNode
class GainRenderNode final : public RenderNode {
public:
GainRenderNode(NodeID, size_t quantum_size, NonnullRefPtr<RenderAudioParam> gain);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
- virtual void for_each_param(Function<void(RenderAudioParam&)> const& callback) override { callback(*m_gain); }
-
-private:
- NonnullRefPtr<RenderAudioParam> m_gain;
- Vector<float> m_gain_values;
};
-
-// Base class for source nodes that are scheduled with start() and stop().
-// https://webaudio.github.io/web-audio-api/#AudioScheduledSourceNode
-class ScheduledSourceRenderNode : public RenderNode {
-public:
- using RenderNode::RenderNode;
-
- virtual void process(RenderGraph&, RenderContext const&) override final;
- virtual void handle_message(NodeMessage const&) override;
- virtual bool take_ended_notification() override { return exchange(m_ended_pending, false); }
-
-protected:
- virtual void process_source(RenderGraph&, RenderContext const&) = 0;
-
- bool has_started() const { return m_start_time.has_value(); }
- double start_time() const { return m_start_time.value(); }
- double stop_time() const { return m_stop_time; }
-
- bool is_active_at(double time) const
- {
- return m_start_time.has_value() && time >= *m_start_time && time < m_stop_time && !m_content_ended;
- }
-
- // Playback naturally ran out of content before the scheduled stop time, e.g. a non-looping buffer finished.
- void set_content_ended() { m_content_ended = true; }
- bool content_ended() const { return m_content_ended; }
-
- // Marks this node as ended once the quantum has advanced past the stop time or the content was exhausted.
- void update_ended_state(RenderContext const&);
-
-private:
- Optional<double> m_start_time;
- double m_stop_time { AK::Infinity<double> };
- bool m_start_time_needs_clamping { false };
- bool m_content_ended { false };
- bool m_ended { false };
- bool m_ended_pending { false };
-};
-
-// https://webaudio.github.io/web-audio-api/#ConstantSourceNode
-class ConstantSourceRenderNode final : public ScheduledSourceRenderNode {
+class ConstantSourceRenderNode final : public RenderNode {
public:
ConstantSourceRenderNode(NodeID, size_t quantum_size, NonnullRefPtr<RenderAudioParam> offset);
-
- virtual void process_source(RenderGraph&, RenderContext const&) override;
- virtual void for_each_param(Function<void(RenderAudioParam&)> const& callback) override { callback(*m_offset); }
-
-private:
- NonnullRefPtr<RenderAudioParam> m_offset;
- Vector<float> m_offset_values;
};
-
-// https://webaudio.github.io/web-audio-api/#OscillatorNode
-class OscillatorRenderNode final : public ScheduledSourceRenderNode {
+class OscillatorRenderNode final : public RenderNode {
public:
OscillatorRenderNode(NodeID, size_t quantum_size, NonnullRefPtr<RenderAudioParam> frequency, NonnullRefPtr<RenderAudioParam> detune);
-
- virtual void process_source(RenderGraph&, RenderContext const&) override;
- virtual void handle_message(NodeMessage const&) override;
- virtual void for_each_param(Function<void(RenderAudioParam&)> const& callback) override
- {
- callback(*m_frequency);
- callback(*m_detune);
- }
-
-private:
- float sample_waveform(double phase, double frequency, double nyquist_frequency) const;
-
- NonnullRefPtr<RenderAudioParam> m_frequency;
- NonnullRefPtr<RenderAudioParam> m_detune;
- Vector<float> m_frequency_values;
- Vector<float> m_detune_values;
- Bindings::OscillatorType m_type { Bindings::OscillatorType::Sine };
- RefPtr<PeriodicWaveData> m_periodic_wave;
- float m_periodic_wave_scale { 1.f };
- double m_phase { 0 };
};
-
-// https://webaudio.github.io/web-audio-api/#AudioBufferSourceNode
-class AudioBufferSourceRenderNode final : public ScheduledSourceRenderNode {
+class AudioBufferSourceRenderNode final : public RenderNode {
public:
AudioBufferSourceRenderNode(NodeID, size_t quantum_size, NonnullRefPtr<RenderAudioParam> playback_rate, NonnullRefPtr<RenderAudioParam> detune);
-
- virtual void process_source(RenderGraph&, RenderContext const&) override;
- virtual void handle_message(NodeMessage const&) override;
- virtual void for_each_param(Function<void(RenderAudioParam&)> const& callback) override
- {
- callback(*m_playback_rate);
- callback(*m_detune);
- }
-
-private:
- float sample_buffer(size_t channel, double playhead_frames, double loop_start_frame, double loop_end_frame) const;
-
- NonnullRefPtr<RenderAudioParam> m_playback_rate;
- NonnullRefPtr<RenderAudioParam> m_detune;
- Vector<float> m_playback_rate_values;
- Vector<float> m_detune_values;
-
- RefPtr<AudioBufferContents> m_buffer;
- bool m_loop { false };
- double m_loop_start { 0 };
- double m_loop_end { 0 };
-
- double m_offset { 0 };
- Optional<double> m_duration;
-
- // Playback position within the buffer contents, in buffer sample frames.
- double m_playhead { 0 };
- bool m_playhead_valid { false };
- double m_played_time { 0 };
};
-
-// https://webaudio.github.io/web-audio-api/#DelayNode
class DelayRenderNode final : public RenderNode {
public:
DelayRenderNode(NodeID, size_t quantum_size, NonnullRefPtr<RenderAudioParam> delay_time, double max_delay_time);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
- virtual void for_each_param(Function<void(RenderAudioParam&)> const& callback) override { callback(*m_delay_time); }
-
-private:
- NonnullRefPtr<RenderAudioParam> m_delay_time;
- Vector<float> m_delay_values;
- double m_max_delay_time { 0 };
- Vector<Vector<float>> m_history;
- size_t m_write_index { 0 };
};
-
-// https://webaudio.github.io/web-audio-api/#StereoPannerNode
class StereoPannerRenderNode final : public RenderNode {
public:
StereoPannerRenderNode(NodeID, size_t quantum_size, NonnullRefPtr<RenderAudioParam> pan);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
- virtual void for_each_param(Function<void(RenderAudioParam&)> const& callback) override { callback(*m_pan); }
-
-private:
- NonnullRefPtr<RenderAudioParam> m_pan;
- Vector<float> m_pan_values;
};
-
-// https://webaudio.github.io/web-audio-api/#ChannelSplitterNode
class ChannelSplitterRenderNode final : public RenderNode {
public:
ChannelSplitterRenderNode(NodeID, size_t quantum_size, size_t number_of_outputs);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
};
-
-// https://webaudio.github.io/web-audio-api/#ChannelMergerNode
class ChannelMergerRenderNode final : public RenderNode {
public:
ChannelMergerRenderNode(NodeID, size_t quantum_size, size_t number_of_inputs);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
};
-
-// https://webaudio.github.io/web-audio-api/#BiquadFilterNode
class BiquadFilterRenderNode final : public RenderNode {
public:
BiquadFilterRenderNode(NodeID, size_t quantum_size, NonnullRefPtr<RenderAudioParam> frequency, NonnullRefPtr<RenderAudioParam> detune, NonnullRefPtr<RenderAudioParam> q, NonnullRefPtr<RenderAudioParam> gain);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
- virtual void handle_message(NodeMessage const&) override;
- virtual void for_each_param(Function<void(RenderAudioParam&)> const& callback) override
- {
- callback(*m_frequency);
- callback(*m_detune);
- callback(*m_q);
- callback(*m_gain);
- }
-
-private:
- struct FilterState {
- double x1 { 0 };
- double x2 { 0 };
- double y1 { 0 };
- double y2 { 0 };
- };
-
- NonnullRefPtr<RenderAudioParam> m_frequency;
- NonnullRefPtr<RenderAudioParam> m_detune;
- NonnullRefPtr<RenderAudioParam> m_q;
- NonnullRefPtr<RenderAudioParam> m_gain;
- Vector<float> m_frequency_values;
- Vector<float> m_detune_values;
- Vector<float> m_q_values;
- Vector<float> m_gain_values;
- Bindings::BiquadFilterType m_type { Bindings::BiquadFilterType::Lowpass };
- Vector<FilterState> m_filter_states;
};
-
-// https://webaudio.github.io/web-audio-api/#IIRFilterNode
class IIRFilterRenderNode final : public RenderNode {
public:
IIRFilterRenderNode(NodeID, size_t quantum_size, Vector<double> feedforward, Vector<double> feedback);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
-
-private:
- // The previous inputs and outputs of the filter for one channel, as ring buffers indexed by the frame number.
- static constexpr size_t history_size = 32;
- struct FilterState {
- Array<double, history_size> inputs {};
- Array<double, history_size> outputs {};
- };
-
- Vector<double> m_feedforward;
- Vector<double> m_feedback;
- Vector<FilterState> m_filter_states;
- size_t m_position { 0 };
};
-
-// https://webaudio.github.io/web-audio-api/#WaveShaperNode
class WaveShaperRenderNode final : public RenderNode {
public:
WaveShaperRenderNode(NodeID, size_t quantum_size);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
- virtual void handle_message(NodeMessage const&) override;
-
-private:
- // A lowpass FIR filter that passes the lower half of its band, which is the band of the signal at half its sample
- // rate. Up-sampling by 2 filters the input with zeros between its samples, and down-sampling by 2 keeps every other
- // sample of the filtered signal.
- static constexpr size_t half_band_filter_length = 31;
- struct HalfBandFilter {
- float process(float sample);
-
- Array<float, half_band_filter_length * 2> history {};
- size_t position { 0 };
- };
-
- struct ChannelState {
- Array<HalfBandFilter, 2> up_sampling_filters;
- Array<HalfBandFilter, 2> down_sampling_filters;
- };
-
- static Array<float, half_band_filter_length> const& half_band_filter_coefficients();
- float shape(float sample) const;
- void up_sample(HalfBandFilter&, ReadonlySpan<float> input, Span<float> output);
- void down_sample(HalfBandFilter&, ReadonlySpan<float> input, Span<float> output);
-
- RefPtr<WaveShaperCurve> m_curve;
- Bindings::OverSampleType m_oversample { Bindings::OverSampleType::None };
- Vector<ChannelState> m_channel_states;
- Vector<float> m_two_times_samples;
- Vector<float> m_four_times_samples;
};
-
-// Convolves the input with an impulse response. The head of the impulse response is convolved directly, and the rest
-// through uniformly partitioned overlap-save convolution: every quantum, the window spanning the previous and the
-// current quantum is transformed and pushed into a frequency delay line, whose spectra are then multiplied with the
-// impulse response partitions and summed. That keeps the cost per quantum constant and adds no latency, at the price of
-// transforming a window that is only half new each time.
-// https://webaudio.github.io/web-audio-api/#ConvolverNode
class ConvolverRenderNode final : public RenderNode {
public:
ConvolverRenderNode(NodeID, size_t quantum_size);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
- virtual void handle_message(NodeMessage const&) override;
-
-private:
- // Which impulse response channel is convolved with which input channel, and where the result is summed into.
- // https://webaudio.github.io/web-audio-api/#Convolution-channel-configurations
- struct Route {
- size_t input_channel { 0 };
- size_t kernel_channel { 0 };
- size_t output_channel { 0 };
- };
-
- FFT m_fft;
-
- RefPtr<ConvolverKernel> m_kernel;
- RefPtr<ConvolverDelayLine> m_delay_line;
-
- // The slot of the delay line that holds the spectrum of the current quantum's window.
- size_t m_delay_line_index { 0 };
-
- // The previous and the current quantum's samples for each input channel, which the direct convolution reaches back
- // into and which the transform consumes as a whole.
- Array<FixedArray<float>, ConvolverDelayLine::MAX_CHANNEL_COUNT> m_window;
- size_t m_input_channel_count { 0 };
-
- FixedArray<float> m_transform_real;
- FixedArray<float> m_transform_imag;
-
- // The partition sums are accumulated in double precision: a long impulse response adds up hundreds of partitions
- // per bin, and single precision loses too much of the quiet parts of the result.
- FixedArray<double> m_accumulator_real;
- FixedArray<double> m_accumulator_imag;
};
-
-// https://webaudio.github.io/web-audio-api/#PannerNode
class PannerRenderNode final : public RenderNode {
public:
struct Params {
@@ -359,30 +82,11 @@ public:
NonnullRefPtr<RenderAudioParam> up_y;
NonnullRefPtr<RenderAudioParam> up_z;
};
-
PannerRenderNode(NodeID, size_t quantum_size, Params, ListenerParams);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
- virtual void handle_message(NodeMessage const&) override;
- virtual void for_each_param(Function<void(RenderAudioParam&)> const& callback) override;
-
-private:
- Params m_params;
- ListenerParams m_listener_params;
- SetPannerParameters m_config;
-
- // One buffer of computed values per panner and listener param, in the order of the Params and ListenerParams
- // struct members.
- Vector<Vector<float>> m_param_values;
};
-
-// Passes the input through unchanged; used for nodes whose processing is not implemented yet but which should not
-// silence the signal path, like DynamicsCompressorNode.
class PassthroughRenderNode final : public RenderNode {
public:
PassthroughRenderNode(NodeID, size_t quantum_size);
-
- virtual void process(RenderGraph&, RenderContext const&) override;
};
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.cpp
index c6f3d07f5e2..48b187e2746 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.cpp
@@ -20,7 +20,7 @@ ScriptProcessorRenderNode::~ScriptProcessorRenderNode() = default;
void ScriptProcessorRenderNode::process(RenderGraph& graph, RenderContext const& context)
{
- auto& output_bus = output(0);
+ auto output_bus = output(0);
output_bus.set_channel_count(max(m_pipe->config().output_channel_count, 1uz));
output_bus.zero();
if (m_pipe->is_shut_down())
@@ -29,7 +29,7 @@ void ScriptProcessorRenderNode::process(RenderGraph& graph, RenderContext const&
// https://webaudio.github.io/web-audio-api/#ScriptProcessorNode
// audioprocess events are only dispatched if the ScriptProcessorNode has at least one input or one output
// connected.
- if (input_connections(0).is_empty() && outgoing_node_connections().is_empty() && outgoing_param_connections().is_empty())
+ if (!has_input_connections(0) && outgoing_node_connection_count() == 0 && outgoing_param_connection_count() == 0)
return;
auto const& config = m_pipe->config();
diff --git a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp
index a39b7b13275..acd34c9e949 100644
--- a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp
+++ b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp
@@ -135,7 +135,7 @@ void ScriptProcessorNode::process_block(size_t block, u64 start_frame)
return;
}
for (size_t channel = 0; channel < config.output_channel_count; ++channel)
- output->channels[channel].span().copy_to(pipe.output_channel(block, channel));
+ output->channels[channel].copy_to(pipe.output_channel(block, channel));
pipe.hand_block_back_to_rendering_thread(block, true);
}
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index c4508505e08..7c26e8d0e87 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -150,6 +150,7 @@ RENDER_STATE_ALLOWED = {
"css/style_compute.rs:REMAINING_ORDER",
"css/style_compute.rs:TABLE",
"style_layout_pool.rs:THREAD_COUNT",
+ "web_audio/rendering/render_nodes.rs:COEFFICIENTS",
],
),
**render_state_entries(