Truly independent web browser
LibWeb: Port WebAudio DSP helpers to Rust
Shannon Booth0a0296cf6d65
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex cacfd5394bd..a5376b7704c 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -1129,6 +1129,7 @@ sync_rust_crate_ffi_headers(FFI_HEADERSHTML/Parser/RustFFI.hRustFFI.h+ WebAudio/RustFFI.hSVG/ParserRustFFI.hSelectorRustFFI.hStyleValueRustFFI.hdiff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rsindex 01d85a1a84e..97224fb20eb 100644--- a/Libraries/LibWeb/Rust/build.rs+++ b/Libraries/LibWeb/Rust/build.rs@@ -2467,6 +2467,25 @@ fn main() -> Result<(), Box<dyn Error>> {let base_config = cbindgen::Config::from_file(manifest_dir.join("cbindgen.toml"))?;+ let mut web_audio_config = base_config.clone();+ web_audio_config.namespaces = Some(vec!["Web".into(), "WebAudio".into(), "RustFFI".into()]);+ for name in ["FFT", "AudioBus", "ConvolverKernel", "ConvolverDelayLine"] {+ web_audio_config.export.rename.insert(name.into(), "void".into());+ web_audio_config.export.exclude.push(name.into());+ }+ web_audio_config.export.exclude.push("MAX_CHANNEL_COUNT".into());+ generate_ffi_header(+ web_audio_config,+ &[+ manifest_dir.join("src/web_audio/rendering/fft.rs"),+ manifest_dir.join("src/web_audio/rendering/biquad_coefficients.rs"),+ manifest_dir.join("src/web_audio/rendering/audio_bus.rs"),+ manifest_dir.join("src/web_audio/rendering/convolver_kernel.rs"),+ ],+ &out_dir,+ Path::new("WebAudio/RustFFI.h"),+ );+// CSS tokenizer header — namespace Web::CSS::Parser::FFI, CSS types only.let mut css_config = base_config.clone();css_config.namespaces = Some(vec![diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rsindex f0006afa05c..3da16449952 100644--- a/Libraries/LibWeb/Rust/src/lib.rs+++ b/Libraries/LibWeb/Rust/src/lib.rs@@ -33,6 +33,7 @@ pub(crate) mod stage;pub(crate) mod stage_thread;pub(crate) mod style_layout_pool;pub(crate) mod svg;+pub mod web_audio;// What libweb_bindings_rust, whose interfaces are implemented in Rust, uses of this crate.pub use css::font_feature_values::FontFeatureValuesRuleKind;diff --git a/Libraries/LibWeb/Rust/src/web_audio/mod.rs b/Libraries/LibWeb/Rust/src/web_audio/mod.rsnew file mode 100644index 00000000000..2a92c0c2bd4--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/mod.rs@@ -0,0 +1,8 @@+/*+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++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.rsnew file mode 100644index 00000000000..4f772a8f974--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs@@ -0,0 +1,306 @@+/*+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use ak::{Span, SpanMut};++const LEFT: usize = 0;+const RIGHT: usize = 1;+const CENTER: usize = 2;+const SURROUND_LEFT: usize = 4;+const SURROUND_RIGHT: usize = 5;++// A block of audio samples for a single render quantum, holding one buffer of frames per channel.+pub struct AudioBus {+ channels: Vec<Vec<f32>>,+ frame_count: usize,+}++impl AudioBus {+ pub fn new(channel_count: usize, frame_count: usize) -> Self {+ let mut bus = Self {+ channels: Vec::new(),+ frame_count,+ };+ bus.set_channel_count(channel_count);+ bus+ }++ pub fn channel_count(&self) -> usize {+ self.channels.len()+ }++ pub fn frame_count(&self) -> usize {+ self.frame_count+ }++ pub fn channel(&self, index: usize) -> &[f32] {+ &self.channels[index]+ }++ pub fn channel_mut(&mut self, index: usize) -> &mut [f32] {+ &mut self.channels[index]+ }++ pub fn zero(&mut self) {+ for channel in &mut self.channels {+ channel.fill(0.);+ }+ }++ pub fn is_silent(&self) -> bool {+ !self+ .channels+ .iter()+ .any(|channel| channel.iter().any(|&sample| sample != 0.))+ }++ pub fn set_channel_count(&mut self, channel_count: usize) {+ if self.channels.len() == channel_count {+ return;+ }+ self.channels.resize_with(channel_count, Vec::new);+ for channel in &mut self.channels {+ channel.resize(self.frame_count, 0.);+ }+ }++ pub fn copy_from(&mut self, source: &Self) {+ assert_eq!(source.frame_count(), self.frame_count());+ self.set_channel_count(source.channel_count());+ for channel_index in 0..self.channels.len() {+ self.channels[channel_index].clone_from(&source.channels[channel_index]);+ }+ }++ // https://webaudio.github.io/web-audio-api/#channel-up-mixing-and-down-mixing+ pub fn sum_from(&mut self, source: &Self, speakers: bool) {+ assert_eq!(source.frame_count(), self.frame_count());+ if speakers {+ self.sum_from_speakers(source);+ } else {+ self.sum_from_discrete(source);+ }+ }++ // https://webaudio.github.io/web-audio-api/#UpMix-sub and https://webaudio.github.io/web-audio-api/#down-mix+ fn sum_from_speakers(&mut self, source: &Self) {+ let source_channels = source.channel_count();+ let destination_channels = self.channel_count();++ let mut sum_channel = |destination_index: usize, source_index: usize, gain: f32| {+ let destination_span = &mut self.channels[destination_index];+ let source_span = source.channel(source_index);+ for frame in 0..self.frame_count {+ destination_span[frame] += source_span[frame] * gain;+ }+ };++ if source_channels == destination_channels {+ for channel_index in 0..source_channels {+ sum_channel(channel_index, channel_index, 1.);+ }+ return;+ }++ // NB: Up-mixing: mono/stereo/quad sources into stereo, quad or 5.1 destinations.+ if source_channels == 1 && destination_channels == 2 {+ // 1 -> 2: output.L = input, output.R = input+ sum_channel(LEFT, 0, 1.);+ sum_channel(RIGHT, 0, 1.);+ return;+ }+ if source_channels == 1 && destination_channels == 4 {+ // 1 -> 4: output.L = input, output.R = input, output.SL = 0, output.SR = 0+ sum_channel(LEFT, 0, 1.);+ sum_channel(RIGHT, 0, 1.);+ return;+ }+ if source_channels == 1 && destination_channels == 6 {+ // 1 -> 5.1: output.C = input, all other channels silent+ sum_channel(CENTER, 0, 1.);+ return;+ }+ if source_channels == 2 && destination_channels == 4 {+ // 2 -> 4: output.L = input.L, output.R = input.R, surround channels silent+ sum_channel(LEFT, LEFT, 1.);+ sum_channel(RIGHT, RIGHT, 1.);+ return;+ }+ if source_channels == 2 && destination_channels == 6 {+ // 2 -> 5.1: output.L = input.L, output.R = input.R, all other channels silent+ sum_channel(LEFT, LEFT, 1.);+ sum_channel(RIGHT, RIGHT, 1.);+ return;+ }+ if source_channels == 4 && destination_channels == 6 {+ // 4 -> 5.1: output.L = input.L, output.R = input.R, output.SL = input.SL, output.SR = input.SR+ sum_channel(LEFT, LEFT, 1.);+ sum_channel(RIGHT, RIGHT, 1.);+ sum_channel(SURROUND_LEFT, 2, 1.);+ sum_channel(SURROUND_RIGHT, 3, 1.);+ return;+ }++ // NB: Down-mixing: stereo/quad/5.1 sources into mono, stereo or quad destinations.+ if source_channels == 2 && destination_channels == 1 {+ // 2 -> 1: output = 0.5 * (input.L + input.R)+ sum_channel(0, LEFT, 0.5);+ sum_channel(0, RIGHT, 0.5);+ return;+ }+ if source_channels == 4 && destination_channels == 1 {+ // 4 -> 1: output = 0.25 * (input.L + input.R + input.SL + input.SR)+ for channel_index in 0..4 {+ sum_channel(0, channel_index, 0.25);+ }+ return;+ }+ if source_channels == 6 && destination_channels == 1 {+ // 5.1 -> 1: output = sqrt(0.5) * (input.L + input.R) + input.C + 0.5 * (input.SL + input.SR)+ sum_channel(0, LEFT, std::f32::consts::FRAC_1_SQRT_2);+ sum_channel(0, RIGHT, std::f32::consts::FRAC_1_SQRT_2);+ sum_channel(0, CENTER, 1.);+ sum_channel(0, SURROUND_LEFT, 0.5);+ sum_channel(0, SURROUND_RIGHT, 0.5);+ return;+ }+ if source_channels == 4 && destination_channels == 2 {+ // 4 -> 2: output.L = 0.5 * (input.L + input.SL), output.R = 0.5 * (input.R + input.SR)+ sum_channel(LEFT, LEFT, 0.5);+ sum_channel(LEFT, 2, 0.5);+ sum_channel(RIGHT, RIGHT, 0.5);+ sum_channel(RIGHT, 3, 0.5);+ return;+ }+ if source_channels == 6 && destination_channels == 2 {+ // 5.1 -> 2: output.L = input.L + sqrt(0.5) * (input.C + input.SL),+ // output.R = input.R + sqrt(0.5) * (input.C + input.SR)+ sum_channel(LEFT, LEFT, 1.);+ sum_channel(LEFT, CENTER, std::f32::consts::FRAC_1_SQRT_2);+ sum_channel(LEFT, SURROUND_LEFT, std::f32::consts::FRAC_1_SQRT_2);+ sum_channel(RIGHT, RIGHT, 1.);+ sum_channel(RIGHT, CENTER, std::f32::consts::FRAC_1_SQRT_2);+ sum_channel(RIGHT, SURROUND_RIGHT, std::f32::consts::FRAC_1_SQRT_2);+ return;+ }+ if source_channels == 6 && destination_channels == 4 {+ // 5.1 -> 4: output.L = input.L + sqrt(0.5) * input.C, output.R = input.R + sqrt(0.5) * input.C,+ // output.SL = input.SL, output.SR = input.SR+ sum_channel(LEFT, LEFT, 1.);+ sum_channel(LEFT, CENTER, std::f32::consts::FRAC_1_SQRT_2);+ sum_channel(RIGHT, RIGHT, 1.);+ sum_channel(RIGHT, CENTER, std::f32::consts::FRAC_1_SQRT_2);+ sum_channel(2, SURROUND_LEFT, 1.);+ sum_channel(3, SURROUND_RIGHT, 1.);+ return;+ }++ // NB: All other layout combinations fall back to discrete mixing.+ self.sum_from_discrete(source);+ }++ // https://webaudio.github.io/web-audio-api/#dom-channelinterpretation-discrete+ fn sum_from_discrete(&mut self, source: &Self) {+ // Up-mix by filling channels until they run out then zero out remaining channels. Down-mix by filling as many+ // channels as possible, then dropping remaining channels.+ let channels_to_sum = source.channel_count().min(self.channel_count());+ for channel_index in 0..channels_to_sum {+ let destination_span = &mut self.channels[channel_index];+ let source_span = source.channel(channel_index);+ for frame in 0..self.frame_count {+ destination_span[frame] += source_span[frame];+ }+ }+ }+}++#[unsafe(no_mangle)]+pub(crate) extern "C" fn web_audio_bus_create(channel_count: usize, frame_count: usize) -> *mut AudioBus {+ Box::into_raw(Box::new(AudioBus::new(channel_count, frame_count)))+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_bus_destroy(bus: *mut AudioBus) {+ if !bus.is_null() {+ drop(unsafe { Box::from_raw(bus) });+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_bus_clone(bus: *const AudioBus) -> *mut AudioBus {+ let source = unsafe { &*bus };+ let mut copy = AudioBus::new(0, source.frame_count());+ copy.copy_from(source);+ Box::into_raw(Box::new(copy))+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_bus_channel_count(bus: *const AudioBus) -> usize {+ unsafe { &*bus }.channel_count()+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_bus_frame_count(bus: *const AudioBus) -> usize {+ unsafe { &*bus }.frame_count()+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_bus_channel(+ bus: *const AudioBus,+ index: usize,+ output: *mut Span<'static, f32>,+) {+ unsafe {+ *output = Span::new((&*bus).channel(index));+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_bus_channel_mut(+ bus: *mut AudioBus,+ index: usize,+ output: *mut SpanMut<'static, f32>,+) {+ unsafe {+ *output = SpanMut::new((&mut *bus).channel_mut(index));+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_bus_zero(bus: *mut AudioBus) {+ unsafe { &mut *bus }.zero();+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_bus_is_silent(bus: *const AudioBus) -> bool {+ unsafe { &*bus }.is_silent()+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_bus_set_channel_count(bus: *mut AudioBus, channel_count: usize) {+ unsafe { &mut *bus }.set_channel_count(channel_count);+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_bus_copy_from(bus: *mut AudioBus, source: *const AudioBus) {+ if !std::ptr::eq(bus, source) {+ unsafe { &mut *bus }.copy_from(unsafe { &*source });+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_bus_sum_from(bus: *mut AudioBus, source: *const AudioBus, speakers: bool) {+ if std::ptr::eq(bus, source) {+ for channel in &mut unsafe { &mut *bus }.channels {+ for sample in channel {+ *sample += *sample;+ }+ }+ } else {+ unsafe { &mut *bus }.sum_from(unsafe { &*source }, speakers);+ }+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/biquad_coefficients.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/biquad_coefficients.rsnew file mode 100644index 00000000000..55cd72eb0fc--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/biquad_coefficients.rs@@ -0,0 +1,193 @@+/*+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use ak::math;++#[derive(Clone, Copy)]+#[repr(u8)]+pub enum BiquadFilterType {+ Lowpass,+ Highpass,+ Bandpass,+ Lowshelf,+ Highshelf,+ Peaking,+ Notch,+ Allpass,+}++// Normalized biquad transfer function coefficients, with a0 divided out.+// https://webaudio.github.io/web-audio-api/#filters-characteristics+#[derive(Clone, Copy)]+#[repr(C)]+pub struct BiquadCoefficients {+ pub b0: f64,+ pub b1: f64,+ pub b2: f64,+ pub a1: f64,+ pub a2: f64,+}++// Computes filter coefficients from the BiquadFilterNode's computed parameter values. frequency is expected to already+// include the detune factor and be given as a fraction of the Nyquist frequency, in the range [0, 1].+// https://webaudio.github.io/web-audio-api/#filters-characteristics+#[allow(unused_assignments)]+pub fn compute_biquad_coefficients(+ filter_type: BiquadFilterType,+ normalized_frequency: f64,+ q: f64,+ gain_db: f64,+) -> BiquadCoefficients {+ let omega = std::f64::consts::PI * normalized_frequency;+ let sin_omega = math::sin(omega);+ let cos_omega = math::cos(omega);+ let a = math::pow(10., gain_db / 40.);++ let mut b0 = 1.0;+ let mut b1 = 0.0;+ let mut b2 = 0.0;+ let mut a0 = 1.0;+ let mut a1 = 0.0;+ let mut a2 = 0.0;++ match filter_type {+ BiquadFilterType::Lowpass => {+ // NB: For lowpass and highpass filters, Q is interpreted as being in dB.+ let alpha_q_db = sin_omega / (2. * math::pow(10., q / 20.));+ b0 = (1. - cos_omega) / 2.;+ b1 = 1. - cos_omega;+ b2 = b0;+ a0 = 1. + alpha_q_db;+ a1 = -2. * cos_omega;+ a2 = 1. - alpha_q_db;+ }+ BiquadFilterType::Highpass => {+ let alpha_q_db = sin_omega / (2. * math::pow(10., q / 20.));+ b0 = (1. + cos_omega) / 2.;+ b1 = -(1. + cos_omega);+ b2 = b0;+ a0 = 1. + alpha_q_db;+ a1 = -2. * cos_omega;+ a2 = 1. - alpha_q_db;+ }+ BiquadFilterType::Bandpass => {+ let alpha_q = if q > 0. { sin_omega / (2. * q) } else { 1. };+ b0 = alpha_q;+ b1 = 0.;+ b2 = -alpha_q;+ a0 = 1. + alpha_q;+ a1 = -2. * cos_omega;+ a2 = 1. - alpha_q;+ }+ BiquadFilterType::Notch => {+ let alpha_q = if q > 0. { sin_omega / (2. * q) } else { 1. };+ b0 = 1.;+ b1 = -2. * cos_omega;+ b2 = 1.;+ a0 = 1. + alpha_q;+ a1 = b1;+ a2 = 1. - alpha_q;+ }+ BiquadFilterType::Allpass => {+ let alpha_q = if q > 0. { sin_omega / (2. * q) } else { 1. };+ b0 = 1. - alpha_q;+ b1 = -2. * cos_omega;+ b2 = 1. + alpha_q;+ a0 = 1. + alpha_q;+ a1 = b1;+ a2 = 1. - alpha_q;+ }+ BiquadFilterType::Peaking => {+ let alpha_q = if q > 0. { sin_omega / (2. * q) } else { 1. };+ b0 = 1. + alpha_q * a;+ b1 = -2. * cos_omega;+ b2 = 1. - alpha_q * a;+ a0 = 1. + alpha_q / a;+ a1 = b1;+ a2 = 1. - alpha_q / a;+ }+ BiquadFilterType::Lowshelf => {+ // NB: For the shelf filters, α_S uses a shelf slope S of 1.+ let alpha_s = sin_omega / 2. * 2.0_f64.sqrt();+ let two_sqrt_a_alpha_s = 2. * a.sqrt() * alpha_s;+ b0 = a * ((a + 1.) - (a - 1.) * cos_omega + two_sqrt_a_alpha_s);+ b1 = 2. * a * ((a - 1.) - (a + 1.) * cos_omega);+ b2 = a * ((a + 1.) - (a - 1.) * cos_omega - two_sqrt_a_alpha_s);+ a0 = (a + 1.) + (a - 1.) * cos_omega + two_sqrt_a_alpha_s;+ a1 = -2. * ((a - 1.) + (a + 1.) * cos_omega);+ a2 = (a + 1.) + (a - 1.) * cos_omega - two_sqrt_a_alpha_s;+ }+ BiquadFilterType::Highshelf => {+ let alpha_s = sin_omega / 2. * 2.0_f64.sqrt();+ let two_sqrt_a_alpha_s = 2. * a.sqrt() * alpha_s;+ b0 = a * ((a + 1.) + (a - 1.) * cos_omega + two_sqrt_a_alpha_s);+ b1 = -2. * a * ((a - 1.) + (a + 1.) * cos_omega);+ b2 = a * ((a + 1.) + (a - 1.) * cos_omega - two_sqrt_a_alpha_s);+ a0 = (a + 1.) - (a - 1.) * cos_omega + two_sqrt_a_alpha_s;+ a1 = 2. * ((a - 1.) - (a + 1.) * cos_omega);+ a2 = (a + 1.) - (a - 1.) * cos_omega - two_sqrt_a_alpha_s;+ }+ }++ BiquadCoefficients {+ b0: b0 / a0,+ b1: b1 / a0,+ b2: b2 / a0,+ a1: a1 / a0,+ a2: a2 / a0,+ }+}++// Evaluates the transfer function's magnitude and phase at the given frequency, given as a fraction of the Nyquist+// frequency in the range [0, 1].+// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-getfrequencyresponse+pub fn biquad_frequency_response(coefficients: &BiquadCoefficients, normalized_frequency: f64) -> (f32, f32) {+ // NB: The response is evaluated at z = e^(jω) with ω = π * normalized_frequency:+ // H(z) = (b0 + b1 z^-1 + b2 z^-2) / (1 + a1 z^-1 + a2 z^-2)+ let omega = std::f64::consts::PI * normalized_frequency;+ let cos_omega = math::cos(omega);+ let sin_omega = math::sin(omega);+ let cos_2_omega = math::cos(2. * omega);+ let sin_2_omega = math::sin(2. * omega);+ let numerator_real = coefficients.b0 + coefficients.b1 * cos_omega + coefficients.b2 * cos_2_omega;+ let numerator_imaginary = -(coefficients.b1 * sin_omega + coefficients.b2 * sin_2_omega);+ let denominator_real = 1. + coefficients.a1 * cos_omega + coefficients.a2 * cos_2_omega;+ let denominator_imaginary = -(coefficients.a1 * sin_omega + coefficients.a2 * sin_2_omega);+ let denominator_magnitude_squared =+ denominator_real * denominator_real + denominator_imaginary * denominator_imaginary;+ let response_real = (numerator_real * denominator_real + numerator_imaginary * denominator_imaginary)+ / denominator_magnitude_squared;+ let response_imaginary = (numerator_imaginary * denominator_real - numerator_real * denominator_imaginary)+ / denominator_magnitude_squared;+ let magnitude = (response_real * response_real + response_imaginary * response_imaginary).sqrt() as f32;+ let phase = math::atan2(response_imaginary, response_real) as f32;+ (magnitude, phase)+}++#[unsafe(no_mangle)]+pub(crate) extern "C" fn web_audio_compute_biquad_coefficients(+ filter_type: BiquadFilterType,+ normalized_frequency: f64,+ q: f64,+ gain_db: f64,+) -> BiquadCoefficients {+ compute_biquad_coefficients(filter_type, normalized_frequency, q, gain_db)+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_biquad_frequency_response(+ coefficients: *const BiquadCoefficients,+ normalized_frequency: f64,+ magnitude: *mut f32,+ phase: *mut f32,+) {+ let response = biquad_frequency_response(unsafe { &*coefficients }, normalized_frequency);+ unsafe {+ *magnitude = response.0;+ *phase = response.1;+ }+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/convolver_kernel.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/convolver_kernel.rsnew file mode 100644index 00000000000..e4f656b66ae--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/convolver_kernel.rs@@ -0,0 +1,323 @@+/*+ * 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)]++use std::sync::Arc;++use ak::{Span, SpanMut};++use super::fft::{FFT, FFTDirection};++pub struct AudioBufferContents<'a> {+ pub channels: &'a [Span<'a, f32>],+ pub sample_rate: f32,+}++impl AudioBufferContents<'_> {+ pub fn length(&self) -> usize {+ self.channels.first().map_or(0, |channel| channel.as_slice().len())+ }+}++struct Channel {+ head: Vec<f32>,+ real: Vec<f32>,+ imag: Vec<f32>,+}++// An impulse response prepared for convolution on the rendering thread, built on the control thread when a+// ConvolverNode's buffer is set so the rendering thread never has to transform a whole impulse response in a single+// quantum.+//+// The first partition is kept in the time domain: it is the one that carries the quietest part of the output, where the+// round-off of a transform round trip is most audible. Everything after it is cut into equally sized partitions and+// transformed. Only the first half of each partition's spectrum plus the Nyquist bin is stored; the remaining bins+// follow from the Hermitian symmetry of the transform of a real signal.+// https://webaudio.github.io/web-audio-api/#ConvolverNode+pub struct ConvolverKernel {+ channels: Vec<Channel>,+ partition_count: usize,+ bin_count: usize,+}++// https://webaudio.github.io/web-audio-api/#dom-convolvernode-normalize+fn calculate_normalization_scale(contents: &AudioBufferContents<'_>) -> f32 {+ const GAIN_CALIBRATION: f64 = 0.00125;+ const GAIN_CALIBRATION_SAMPLE_RATE: f64 = 44100.;+ const MIN_POWER: f64 = 0.000125;++ // Normalize by RMS power.+ let mut power = 0.;+ for samples in contents.channels {+ for &sample in samples.as_slice() {+ power += f64::from(sample) * f64::from(sample);+ }+ }+ power = (power / (contents.channels.len() * contents.length()) as f64).sqrt();++ // Protect against accidental overload.+ if !power.is_finite() || power < MIN_POWER {+ power = MIN_POWER;+ }++ let mut scale = 1. / power;++ // Calibrate to make perceived volume same as unprocessed.+ scale *= GAIN_CALIBRATION;++ // Scale depends on sample-rate.+ if contents.sample_rate != 0. {+ scale *= GAIN_CALIBRATION_SAMPLE_RATE / f64::from(contents.sample_rate);+ }++ // True-stereo compensation.+ if contents.channels.len() == 4 {+ scale *= 0.5;+ }++ scale as f32+}++impl ConvolverKernel {+ pub fn create(contents: &AudioBufferContents<'_>, partition_size: usize, normalize: bool) -> Option<Arc<Self>> {+ let length = contents.length();+ if length == 0 {+ return None;+ }++ let scale = if normalize {+ calculate_normalization_scale(contents)+ } else {+ 1.+ };++ // Each partition is zero-padded to twice its length so that the cyclic convolution of the transform produces the+ // linear convolution the rendering thread is after.+ let transform_size = 2 * partition_size;+ let bin_count = partition_size + 1;+ let partition_count = if length > partition_size {+ (length - partition_size).div_ceil(partition_size)+ } else {+ 0+ };++ let fft = FFT::new(transform_size);+ let mut real = vec![0.; transform_size];+ let mut imag = vec![0.; transform_size];++ let mut channels = Vec::with_capacity(contents.channels.len());+ for samples in contents.channels {+ let samples = samples.as_slice();+ let mut channel = Channel {+ head: vec![0.; partition_size],+ real: vec![0.; partition_count * bin_count],+ imag: vec![0.; partition_count * bin_count],+ };++ for frame in 0..partition_size.min(length) {+ channel.head[frame] = samples[frame] * scale;+ }++ for partition in 0..partition_count {+ let offset = (partition + 1) * partition_size;+ let frames_in_partition = partition_size.min(length - offset);+ for frame in 0..frames_in_partition {+ real[frame] = samples[offset + frame] * scale;+ }+ for frame in frames_in_partition..transform_size {+ real[frame] = 0.;+ }+ for frame in 0..transform_size {+ imag[frame] = 0.;+ }++ fft.transform(&mut real, &mut imag, FFTDirection::Forward);++ for bin in 0..bin_count {+ channel.real[partition * bin_count + bin] = real[bin];+ channel.imag[partition * bin_count + bin] = imag[bin];+ }+ }++ channels.push(channel);+ }++ Some(Arc::new(Self {+ channels,+ partition_count,+ bin_count,+ }))+ }++ pub fn channel_count(&self) -> usize {+ self.channels.len()+ }++ // The number of partitions that are held in the frequency domain, which excludes the time-domain head.+ pub fn partition_count(&self) -> usize {+ self.partition_count+ }++ pub fn bin_count(&self) -> usize {+ self.bin_count+ }++ pub fn head(&self, channel: usize) -> &[f32] {+ &self.channels[channel].head+ }++ pub fn partition_real(&self, channel: usize, partition: usize) -> &[f32] {+ &self.channels[channel].real[partition * self.bin_count..(partition + 1) * self.bin_count]+ }++ pub fn partition_imag(&self, channel: usize, partition: usize) -> &[f32] {+ &self.channels[channel].imag[partition * self.bin_count..(partition + 1) * self.bin_count]+ }+}++// The ring of input spectra a ConvolverRenderNode multiplies with the kernel's partitions, one slot per partition plus+// one for the window written in the current quantum. It is sized after the kernel, so it is allocated here on the+// 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],+}++impl ConvolverDelayLine {+ // The input to a ConvolverNode is mono or stereo and cannot be increased.+ // https://webaudio.github.io/web-audio-api/#ConvolverNode+ pub const MAX_CHANNEL_COUNT: usize = 2;++ 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()]);+ Self { length, real, imag }+ }++ pub fn length(&self) -> usize {+ self.length+ }++ pub fn real(&mut self, channel: usize) -> &mut [f32] {+ &mut self.real[channel]+ }++ pub fn imag(&mut self, channel: usize) -> &mut [f32] {+ &mut self.imag[channel]+ }+}++#[unsafe(no_mangle)]+pub(crate) extern "C" fn web_audio_convolver_kernel_create(+ channels: Span<'_, Span<'_, f32>>,+ sample_rate: f32,+ partition_size: usize,+ normalize: bool,+) -> *const ConvolverKernel {+ let contents = AudioBufferContents {+ channels: channels.as_slice(),+ sample_rate,+ };+ ConvolverKernel::create(&contents, partition_size, normalize).map_or(std::ptr::null(), Arc::into_raw)+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_convolver_kernel_destroy(kernel: *const ConvolverKernel) {+ drop(unsafe { Arc::from_raw(kernel) });+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_convolver_kernel_channel_count(kernel: *const ConvolverKernel) -> usize {+ unsafe { &*kernel }.channel_count()+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_convolver_kernel_partition_count(kernel: *const ConvolverKernel) -> usize {+ unsafe { &*kernel }.partition_count()+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_convolver_kernel_bin_count(kernel: *const ConvolverKernel) -> usize {+ unsafe { &*kernel }.bin_count()+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_convolver_kernel_head(+ kernel: *const ConvolverKernel,+ channel: usize,+ output: *mut Span<'static, f32>,+) {+ unsafe {+ *output = Span::new((&*kernel).head(channel));+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_convolver_kernel_partition_real(+ kernel: *const ConvolverKernel,+ channel: usize,+ partition: usize,+ output: *mut Span<'static, f32>,+) {+ unsafe {+ *output = Span::new((&*kernel).partition_real(channel, partition));+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_convolver_kernel_partition_imag(+ kernel: *const ConvolverKernel,+ channel: usize,+ partition: usize,+ output: *mut Span<'static, f32>,+) {+ unsafe {+ *output = Span::new((&*kernel).partition_imag(channel, partition));+ }+}++#[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 })))+}++#[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) });+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_convolver_delay_line_length(delay_line: *const ConvolverDelayLine) -> usize {+ unsafe { &*delay_line }.length()+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_convolver_delay_line_real(+ delay_line: *mut ConvolverDelayLine,+ channel: usize,+ output: *mut SpanMut<'static, f32>,+) {+ unsafe {+ *output = SpanMut::new((&mut *delay_line).real(channel));+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_convolver_delay_line_imag(+ delay_line: *mut ConvolverDelayLine,+ channel: usize,+ output: *mut SpanMut<'static, f32>,+) {+ unsafe {+ *output = SpanMut::new((&mut *delay_line).imag(channel));+ }+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/fft.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/fft.rsnew file mode 100644index 00000000000..1b446df8724--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/fft.rs@@ -0,0 +1,114 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use ak::{SpanMut, math};++#[derive(Clone, Copy, PartialEq, Eq)]+#[repr(u8)]+pub enum FFTDirection {+ Forward,+ Inverse,+}++pub struct FFT {+ size: usize,+ twiddle_real: Vec<f32>,+ twiddle_imag: Vec<f32>,+}++impl FFT {+ // Radix-2 Cooley-Tukey FFT of a fixed power-of-two size. The twiddle factors depend only on that size, so they are+ // computed once here and shared by every transform.+ pub fn new(size: usize) -> Self {+ assert!(size != 0 && (size & (size - 1)) == 0);++ let mut twiddle_real = vec![0.; size / 2];+ let mut twiddle_imag = vec![0.; size / 2];+ for index in 0..size / 2 {+ let angle = -2. * std::f64::consts::PI * index as f64 / size as f64;+ twiddle_real[index] = math::cos(angle) as f32;+ twiddle_imag[index] = math::sin(angle) as f32;+ }+ Self {+ size,+ twiddle_real,+ twiddle_imag,+ }+ }++ pub fn size(&self) -> usize {+ self.size+ }++ // Both spans must hold exactly `size()` samples. The inverse transform includes the 1/N scaling.+ pub fn transform(&self, re: &mut [f32], im: &mut [f32], direction: FFTDirection) {+ assert!(re.len() == self.size && im.len() == self.size);++ let mut j = 0;+ for i in 1..self.size {+ let mut bit = self.size >> 1;+ while j & bit != 0 {+ j ^= bit;+ bit >>= 1;+ }+ j ^= bit;+ if i < j {+ re.swap(i, j);+ im.swap(i, j);+ }+ }++ let twiddle_sign = if direction == FFTDirection::Forward { 1. } else { -1. };+ let mut len = 2;+ while len <= self.size {+ let half = len >> 1;+ let twiddle_stride = self.size / len;+ for i in (0..self.size).step_by(len) {+ for k in 0..half {+ let w_re = self.twiddle_real[k * twiddle_stride];+ let w_im = self.twiddle_imag[k * twiddle_stride] * twiddle_sign;+ let u_re = re[i + k];+ let u_im = im[i + k];+ let v_re = re[i + k + half] * w_re - im[i + k + half] * w_im;+ let v_im = re[i + k + half] * w_im + im[i + k + half] * w_re;+ re[i + k] = u_re + v_re;+ im[i + k] = u_im + v_im;+ re[i + k + half] = u_re - v_re;+ im[i + k + half] = u_im - v_im;+ }+ }+ len <<= 1;+ }++ if direction == FFTDirection::Inverse {+ let inverse_size = 1. / self.size as f32;+ for i in 0..self.size {+ re[i] *= inverse_size;+ im[i] *= inverse_size;+ }+ }+ }+}++#[unsafe(no_mangle)]+pub(crate) extern "C" fn web_audio_fft_create(size: usize) -> *mut FFT {+ Box::into_raw(Box::new(FFT::new(size)))+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_fft_destroy(fft: *mut FFT) {+ drop(unsafe { Box::from_raw(fft) });+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_fft_transform(+ fft: *const FFT,+ re: SpanMut<'_, f32>,+ im: SpanMut<'_, f32>,+ direction: FFTDirection,+) {+ unsafe { &*fft }.transform(re.into_slice(), im.into_slice(), direction);+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rsnew file mode 100644index 00000000000..6a755aa6a78--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs@@ -0,0 +1,14 @@+/*+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++pub mod audio_bus;+pub mod biquad_coefficients;+pub mod convolver_kernel;+pub mod fft;++#[cfg(test)]+mod tests;diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/tests.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/tests.rsnew file mode 100644index 00000000000..7e460bc5059--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/tests.rs@@ -0,0 +1,28 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use super::audio_bus::AudioBus;++#[test]+fn bus_channel_resize_and_copy_preserve_samples() {+ let mut bus = AudioBus::new(2, 4);+ bus.channel_mut(0).fill(1.);+ bus.channel_mut(1).fill(2.);+ bus.set_channel_count(4);+ assert_eq!(bus.channel(0), &[1.; 4]);+ assert_eq!(bus.channel(1), &[2.; 4]);+ assert_eq!(bus.channel(2), &[0.; 4]);+ let mut copy = AudioBus::new(0, 4);+ copy.copy_from(&bus);+ bus.zero();+ assert!(bus.is_silent());+ assert!(!copy.is_silent());+ assert_eq!(copy.channel(1), &[2.; 4]);+ copy.set_channel_count(1);+ copy.set_channel_count(2);+ assert_eq!(copy.channel(0), &[1.; 4]);+ assert_eq!(copy.channel(1), &[0.; 4]);+}diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioBus.cpp b/Libraries/LibWeb/WebAudio/Rendering/AudioBus.cppindex e22db19f158..4c0f5039927 100644--- a/Libraries/LibWeb/WebAudio/Rendering/AudioBus.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioBus.cpp@@ -1,200 +1,102 @@/** Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/AnyOf.h>-#include <AK/Math.h>+#include <AK/StdLibExtras.h>#include <LibWeb/WebAudio/Rendering/AudioBus.h>+#include <LibWeb/WebAudio/RustFFI.h>namespace Web::WebAudio::Rendering {-// https://webaudio.github.io/web-audio-api/#ChannelLayouts-// Speakers channel layouts exist for mono, stereo, quad and 5.1; all other channel counts use discrete mixing.-enum SpeakerChannel : u8 {- Left = 0,- Right = 1,- Center = 2,- LFE = 3,- SurroundLeft = 4,- SurroundRight = 5,-};-AudioBus::AudioBus(size_t channel_count, size_t frame_count)- : m_frame_count(frame_count)+ : m_bus(RustFFI::web_audio_bus_create(channel_count, frame_count)){- set_channel_count(channel_count);}-void AudioBus::zero()+AudioBus::AudioBus(AudioBus const& other)+ : m_bus(RustFFI::web_audio_bus_clone(other.m_bus)){- for (auto& channel : m_channels)- channel.span().fill(0.f);}-bool AudioBus::is_silent() const+AudioBus::AudioBus(AudioBus&& other)+ : m_bus(exchange(other.m_bus, nullptr)){- return !any_of(m_channels, [](auto const& channel) {- return any_of(channel, [](auto sample) { return sample != 0.f; });- });}-// Changes the number of channels; sample data is not preserved.-void AudioBus::set_channel_count(size_t channel_count)+AudioBus& AudioBus::operator=(AudioBus const& other){- if (m_channels.size() == channel_count)- return;- m_channels.resize(channel_count);- for (auto& channel : m_channels)- channel.resize(m_frame_count);+ if (this != &other) {+ auto* copy = RustFFI::web_audio_bus_clone(other.m_bus);+ RustFFI::web_audio_bus_destroy(m_bus);+ m_bus = copy;+ }+ return *this;}-void AudioBus::copy_from(AudioBus const& source)+AudioBus& AudioBus::operator=(AudioBus&& other){- VERIFY(source.frame_count() == frame_count());- set_channel_count(source.channel_count());- for (size_t channel_index = 0; channel_index < m_channels.size(); ++channel_index)- m_channels[channel_index] = source.m_channels[channel_index];+ if (this != &other) {+ RustFFI::web_audio_bus_destroy(m_bus);+ m_bus = exchange(other.m_bus, nullptr);+ }+ return *this;}-// https://webaudio.github.io/web-audio-api/#channel-up-mixing-and-down-mixing-void AudioBus::sum_from(AudioBus const& source, Bindings::ChannelInterpretation channel_interpretation)+AudioBus::~AudioBus(){- VERIFY(source.frame_count() == frame_count());- if (channel_interpretation == Bindings::ChannelInterpretation::Speakers)- sum_from_speakers(source);- else- sum_from_discrete(source);+ RustFFI::web_audio_bus_destroy(m_bus);}-// https://webaudio.github.io/web-audio-api/#UpMix-sub and https://webaudio.github.io/web-audio-api/#down-mix-void AudioBus::sum_from_speakers(AudioBus const& source)+size_t AudioBus::channel_count() const{- auto source_channels = source.channel_count();- auto destination_channels = channel_count();-- auto sum_channel = [&](size_t destination_index, size_t source_index, float gain = 1.f) {- auto destination_span = channel(destination_index);- auto source_span = source.channel(source_index);- for (size_t frame = 0; frame < m_frame_count; ++frame)- destination_span[frame] += source_span[frame] * gain;- };-- if (source_channels == destination_channels) {- for (size_t channel_index = 0; channel_index < source_channels; ++channel_index)- sum_channel(channel_index, channel_index);- return;- }+ return RustFFI::web_audio_bus_channel_count(m_bus);+}- // NB: Up-mixing: mono/stereo/quad sources into stereo, quad or 5.1 destinations.- if (source_channels == 1 && destination_channels == 2) {- // 1 -> 2: output.L = input, output.R = input- sum_channel(Left, 0);- sum_channel(Right, 0);- return;- }- if (source_channels == 1 && destination_channels == 4) {- // 1 -> 4: output.L = input, output.R = input, output.SL = 0, output.SR = 0- sum_channel(Left, 0);- sum_channel(Right, 0);- return;- }- if (source_channels == 1 && destination_channels == 6) {- // 1 -> 5.1: output.C = input, all other channels silent- sum_channel(Center, 0);- return;- }- if (source_channels == 2 && destination_channels == 4) {- // 2 -> 4: output.L = input.L, output.R = input.R, surround channels silent- sum_channel(Left, Left);- sum_channel(Right, Right);- return;- }- if (source_channels == 2 && destination_channels == 6) {- // 2 -> 5.1: output.L = input.L, output.R = input.R, all other channels silent- sum_channel(Left, Left);- sum_channel(Right, Right);- return;- }- if (source_channels == 4 && destination_channels == 6) {- // 4 -> 5.1: output.L = input.L, output.R = input.R, output.SL = input.SL, output.SR = input.SR- sum_channel(Left, Left);- sum_channel(Right, Right);- sum_channel(SurroundLeft, 2);- sum_channel(SurroundRight, 3);- return;- }+size_t AudioBus::frame_count() const+{+ return RustFFI::web_audio_bus_frame_count(m_bus);+}- // NB: Down-mixing: stereo/quad/5.1 sources into mono, stereo or quad destinations.- if (source_channels == 2 && destination_channels == 1) {- // 2 -> 1: output = 0.5 * (input.L + input.R)- sum_channel(0, Left, 0.5f);- sum_channel(0, Right, 0.5f);- return;- }- if (source_channels == 4 && destination_channels == 1) {- // 4 -> 1: output = 0.25 * (input.L + input.R + input.SL + input.SR)- for (size_t channel_index = 0; channel_index < 4; ++channel_index)- sum_channel(0, channel_index, 0.25f);- return;- }- if (source_channels == 6 && destination_channels == 1) {- // 5.1 -> 1: output = sqrt(0.5) * (input.L + input.R) + input.C + 0.5 * (input.SL + input.SR)- sum_channel(0, Left, AK::Sqrt1_2<float>);- sum_channel(0, Right, AK::Sqrt1_2<float>);- sum_channel(0, Center);- sum_channel(0, SurroundLeft, 0.5f);- sum_channel(0, SurroundRight, 0.5f);- return;- }- if (source_channels == 4 && destination_channels == 2) {- // 4 -> 2: output.L = 0.5 * (input.L + input.SL), output.R = 0.5 * (input.R + input.SR)- sum_channel(Left, Left, 0.5f);- sum_channel(Left, 2, 0.5f);- sum_channel(Right, Right, 0.5f);- sum_channel(Right, 3, 0.5f);- return;- }- if (source_channels == 6 && destination_channels == 2) {- // 5.1 -> 2: output.L = input.L + sqrt(0.5) * (input.C + input.SL),- // output.R = input.R + sqrt(0.5) * (input.C + input.SR)- sum_channel(Left, Left);- sum_channel(Left, Center, AK::Sqrt1_2<float>);- sum_channel(Left, SurroundLeft, AK::Sqrt1_2<float>);- sum_channel(Right, Right);- sum_channel(Right, Center, AK::Sqrt1_2<float>);- sum_channel(Right, SurroundRight, AK::Sqrt1_2<float>);- return;- }- if (source_channels == 6 && destination_channels == 4) {- // 5.1 -> 4: output.L = input.L + sqrt(0.5) * input.C, output.R = input.R + sqrt(0.5) * input.C,- // output.SL = input.SL, output.SR = input.SR- sum_channel(Left, Left);- sum_channel(Left, Center, AK::Sqrt1_2<float>);- sum_channel(Right, Right);- sum_channel(Right, Center, AK::Sqrt1_2<float>);- sum_channel(2, SurroundLeft);- sum_channel(3, SurroundRight);- return;- }+Span<float> AudioBus::channel(size_t index)+{+ Span<float> samples;+ RustFFI::web_audio_bus_channel_mut(m_bus, index, &samples);+ return samples;+}- // NB: All other layout combinations fall back to discrete mixing.- sum_from_discrete(source);+ReadonlySpan<float> AudioBus::channel(size_t index) const+{+ ReadonlySpan<float> samples;+ RustFFI::web_audio_bus_channel(m_bus, index, &samples);+ return samples;}-// https://webaudio.github.io/web-audio-api/#dom-channelinterpretation-discrete-void AudioBus::sum_from_discrete(AudioBus const& source)+void AudioBus::zero(){- // Up-mix by filling channels until they run out then zero out remaining channels. Down-mix by filling as many- // channels as possible, then dropping remaining channels.- auto channels_to_sum = min(source.channel_count(), channel_count());- for (size_t channel_index = 0; channel_index < channels_to_sum; ++channel_index) {- auto destination_span = channel(channel_index);- auto source_span = source.channel(channel_index);- for (size_t frame = 0; frame < m_frame_count; ++frame)- destination_span[frame] += source_span[frame];- }+ RustFFI::web_audio_bus_zero(m_bus);+}++bool AudioBus::is_silent() const+{+ return RustFFI::web_audio_bus_is_silent(m_bus);+}++void AudioBus::set_channel_count(size_t channel_count)+{+ RustFFI::web_audio_bus_set_channel_count(m_bus, channel_count);+}++void AudioBus::copy_from(AudioBus const& source)+{+ RustFFI::web_audio_bus_copy_from(m_bus, source.m_bus);+}++void AudioBus::sum_from(AudioBus const& source, Bindings::ChannelInterpretation interpretation)+{+ RustFFI::web_audio_bus_sum_from(m_bus, source.m_bus, interpretation == Bindings::ChannelInterpretation::Speakers);}}diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioBus.h b/Libraries/LibWeb/WebAudio/Rendering/AudioBus.hindex 2416fb994d2..6dfae344f44 100644--- a/Libraries/LibWeb/WebAudio/Rendering/AudioBus.h+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioBus.h@@ -1,5 +1,6 @@/** Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/@@ -7,7 +8,6 @@#pragma once#include <AK/Span.h>-#include <AK/Vector.h>#include <LibWeb/Bindings/AudioNode.h>#include <LibWeb/Export.h>@@ -19,27 +19,27 @@ public:AK_ALLOC_WITH_KMALLOC;AudioBus(size_t channel_count, size_t frame_count);+ AudioBus(AudioBus const&);+ AudioBus(AudioBus&&);+ AudioBus& operator=(AudioBus const&);+ AudioBus& operator=(AudioBus&&);+ ~AudioBus();- size_t channel_count() const { return m_channels.size(); }- size_t frame_count() const { return m_frame_count; }+ size_t channel_count() const;+ size_t frame_count() const;- Span<float> channel(size_t index) { return m_channels[index]; }- ReadonlySpan<float> channel(size_t index) const { return m_channels[index]; }+ Span<float> channel(size_t index);+ ReadonlySpan<float> channel(size_t index) const;void zero();bool is_silent() const;void set_channel_count(size_t);void copy_from(AudioBus const&);- // https://webaudio.github.io/web-audio-api/#channel-up-mixing-and-down-mixingvoid sum_from(AudioBus const& source, Bindings::ChannelInterpretation);private:- void sum_from_speakers(AudioBus const& source);- void sum_from_discrete(AudioBus const& source);-- Vector<Vector<float>> m_channels;- size_t m_frame_count { 0 };+ void* m_bus { nullptr };};}diff --git a/Libraries/LibWeb/WebAudio/Rendering/BiquadCoefficients.cpp b/Libraries/LibWeb/WebAudio/Rendering/BiquadCoefficients.cppindex b40801330c1..1d281b952d6 100644--- a/Libraries/LibWeb/WebAudio/Rendering/BiquadCoefficients.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/BiquadCoefficients.cpp@@ -1,144 +1,33 @@/** Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Math.h>#include <LibWeb/WebAudio/Rendering/BiquadCoefficients.h>+#include <LibWeb/WebAudio/RustFFI.h>namespace Web::WebAudio::Rendering {-// https://webaudio.github.io/web-audio-api/#filters-characteristicsBiquadCoefficients compute_biquad_coefficients(Bindings::BiquadFilterType type, double normalized_frequency, double q, double gain_db){- auto omega = AK::Pi<double> * normalized_frequency;- auto sin_omega = AK::sin(omega);- auto cos_omega = AK::cos(omega);- auto a = AK::pow(10., gain_db / 40.);-- double b0 = 1;- double b1 = 0;- double b2 = 0;- double a0 = 1;- double a1 = 0;- double a2 = 0;-- switch (type) {- case Bindings::BiquadFilterType::Lowpass: {- // NB: For lowpass and highpass filters, Q is interpreted as being in dB.- auto alpha_q_db = sin_omega / (2 * AK::pow(10., q / 20.));- b0 = (1 - cos_omega) / 2;- b1 = 1 - cos_omega;- b2 = b0;- a0 = 1 + alpha_q_db;- a1 = -2 * cos_omega;- a2 = 1 - alpha_q_db;- break;- }- case Bindings::BiquadFilterType::Highpass: {- auto alpha_q_db = sin_omega / (2 * AK::pow(10., q / 20.));- b0 = (1 + cos_omega) / 2;- b1 = -(1 + cos_omega);- b2 = b0;- a0 = 1 + alpha_q_db;- a1 = -2 * cos_omega;- a2 = 1 - alpha_q_db;- break;- }- case Bindings::BiquadFilterType::Bandpass: {- auto alpha_q = q > 0 ? sin_omega / (2 * q) : 1;- b0 = alpha_q;- b1 = 0;- b2 = -alpha_q;- a0 = 1 + alpha_q;- a1 = -2 * cos_omega;- a2 = 1 - alpha_q;- break;- }- case Bindings::BiquadFilterType::Notch: {- auto alpha_q = q > 0 ? sin_omega / (2 * q) : 1;- b0 = 1;- b1 = -2 * cos_omega;- b2 = 1;- a0 = 1 + alpha_q;- a1 = b1;- a2 = 1 - alpha_q;- break;- }- case Bindings::BiquadFilterType::Allpass: {- auto alpha_q = q > 0 ? sin_omega / (2 * q) : 1;- b0 = 1 - alpha_q;- b1 = -2 * cos_omega;- b2 = 1 + alpha_q;- a0 = 1 + alpha_q;- a1 = b1;- a2 = 1 - alpha_q;- break;- }- case Bindings::BiquadFilterType::Peaking: {- auto alpha_q = q > 0 ? sin_omega / (2 * q) : 1;- b0 = 1 + alpha_q * a;- b1 = -2 * cos_omega;- b2 = 1 - alpha_q * a;- a0 = 1 + alpha_q / a;- a1 = b1;- a2 = 1 - alpha_q / a;- break;- }- case Bindings::BiquadFilterType::Lowshelf: {- // NB: For the shelf filters, α_S uses a shelf slope S of 1.- auto alpha_s = sin_omega / 2 * AK::sqrt(2.);- auto two_sqrt_a_alpha_s = 2 * AK::sqrt(a) * alpha_s;- b0 = a * ((a + 1) - (a - 1) * cos_omega + two_sqrt_a_alpha_s);- b1 = 2 * a * ((a - 1) - (a + 1) * cos_omega);- b2 = a * ((a + 1) - (a - 1) * cos_omega - two_sqrt_a_alpha_s);- a0 = (a + 1) + (a - 1) * cos_omega + two_sqrt_a_alpha_s;- a1 = -2 * ((a - 1) + (a + 1) * cos_omega);- a2 = (a + 1) + (a - 1) * cos_omega - two_sqrt_a_alpha_s;- break;- }- case Bindings::BiquadFilterType::Highshelf: {- auto alpha_s = sin_omega / 2 * AK::sqrt(2.);- auto two_sqrt_a_alpha_s = 2 * AK::sqrt(a) * alpha_s;- b0 = a * ((a + 1) + (a - 1) * cos_omega + two_sqrt_a_alpha_s);- b1 = -2 * a * ((a - 1) + (a + 1) * cos_omega);- b2 = a * ((a + 1) + (a - 1) * cos_omega - two_sqrt_a_alpha_s);- a0 = (a + 1) - (a - 1) * cos_omega + two_sqrt_a_alpha_s;- a1 = 2 * ((a - 1) - (a + 1) * cos_omega);- a2 = (a + 1) - (a - 1) * cos_omega - two_sqrt_a_alpha_s;- break;- }- }-- return BiquadCoefficients {- .b0 = b0 / a0,- .b1 = b1 / a0,- .b2 = b2 / a0,- .a1 = a1 / a0,- .a2 = a2 / a0,- };+ static_assert(to_underlying(Bindings::BiquadFilterType::Lowpass) == to_underlying(RustFFI::BiquadFilterType::Lowpass));+ static_assert(to_underlying(Bindings::BiquadFilterType::Highpass) == to_underlying(RustFFI::BiquadFilterType::Highpass));+ static_assert(to_underlying(Bindings::BiquadFilterType::Bandpass) == to_underlying(RustFFI::BiquadFilterType::Bandpass));+ static_assert(to_underlying(Bindings::BiquadFilterType::Lowshelf) == to_underlying(RustFFI::BiquadFilterType::Lowshelf));+ static_assert(to_underlying(Bindings::BiquadFilterType::Highshelf) == to_underlying(RustFFI::BiquadFilterType::Highshelf));+ static_assert(to_underlying(Bindings::BiquadFilterType::Peaking) == to_underlying(RustFFI::BiquadFilterType::Peaking));+ static_assert(to_underlying(Bindings::BiquadFilterType::Notch) == to_underlying(RustFFI::BiquadFilterType::Notch));+ static_assert(to_underlying(Bindings::BiquadFilterType::Allpass) == to_underlying(RustFFI::BiquadFilterType::Allpass));+ auto coefficients = RustFFI::web_audio_compute_biquad_coefficients(static_cast<RustFFI::BiquadFilterType>(type), normalized_frequency, q, gain_db);+ return { coefficients.b0, coefficients.b1, coefficients.b2, coefficients.a1, coefficients.a2 };}-// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-getfrequencyresponsevoid biquad_frequency_response(BiquadCoefficients const& coefficients, double normalized_frequency, float& magnitude, float& phase){- // NB: The response is evaluated at z = e^(jω) with ω = π * normalized_frequency:- // H(z) = (b0 + b1 z^-1 + b2 z^-2) / (1 + a1 z^-1 + a2 z^-2)- auto omega = AK::Pi<double> * normalized_frequency;- auto cos_omega = AK::cos(omega);- auto sin_omega = AK::sin(omega);- auto cos_2_omega = AK::cos(2 * omega);- auto sin_2_omega = AK::sin(2 * omega);- auto numerator_real = coefficients.b0 + coefficients.b1 * cos_omega + coefficients.b2 * cos_2_omega;- auto numerator_imaginary = -(coefficients.b1 * sin_omega + coefficients.b2 * sin_2_omega);- auto denominator_real = 1 + coefficients.a1 * cos_omega + coefficients.a2 * cos_2_omega;- auto denominator_imaginary = -(coefficients.a1 * sin_omega + coefficients.a2 * sin_2_omega);- auto denominator_magnitude_squared = denominator_real * denominator_real + denominator_imaginary * denominator_imaginary;- auto response_real = (numerator_real * denominator_real + numerator_imaginary * denominator_imaginary) / denominator_magnitude_squared;- auto response_imaginary = (numerator_imaginary * denominator_real - numerator_real * denominator_imaginary) / denominator_magnitude_squared;- magnitude = static_cast<float>(AK::sqrt(response_real * response_real + response_imaginary * response_imaginary));- phase = static_cast<float>(AK::atan2(response_imaginary, response_real));+ RustFFI::BiquadCoefficients rust_coefficients { coefficients.b0, coefficients.b1, coefficients.b2, coefficients.a1, coefficients.a2 };+ RustFFI::web_audio_biquad_frequency_response(&rust_coefficients, normalized_frequency, &magnitude, &phase);}}diff --git a/Libraries/LibWeb/WebAudio/Rendering/BiquadCoefficients.h b/Libraries/LibWeb/WebAudio/Rendering/BiquadCoefficients.hindex b590763e301..01580aa5ef9 100644--- a/Libraries/LibWeb/WebAudio/Rendering/BiquadCoefficients.h+++ b/Libraries/LibWeb/WebAudio/Rendering/BiquadCoefficients.h@@ -1,5 +1,6 @@/** Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/diff --git a/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.cpp b/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.cppindex 7bf59de6c98..17fc0a47227 100644--- a/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.cpp@@ -1,117 +1,95 @@/** Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Math.h>#include <LibWeb/WebAudio/Rendering/ConvolverKernel.h>-#include <LibWeb/WebAudio/Rendering/FFT.h>+#include <LibWeb/WebAudio/RustFFI.h>namespace Web::WebAudio::Rendering {-// https://webaudio.github.io/web-audio-api/#dom-convolvernode-normalize-static float calculate_normalization_scale(AudioBufferContents const& contents)+RefPtr<ConvolverKernel> ConvolverKernel::create(AudioBufferContents const& contents, size_t partition_size, bool normalize){- static constexpr double gain_calibration = 0.00125;- static constexpr double gain_calibration_sample_rate = 44100;- static constexpr double min_power = 0.000125;-- // Normalize by RMS power.- double power = 0;- for (auto const& samples : contents.channels) {- for (auto sample : samples)- power += static_cast<double>(sample) * sample;- }- power = AK::sqrt(power / (contents.channels.size() * contents.length()));-- // Protect against accidental overload.- if (!__builtin_isfinite(power) || power < min_power)- power = min_power;-- auto scale = 1 / power;+ Vector<ReadonlySpan<float>> channels;+ channels.ensure_capacity(contents.channels.size());+ for (auto const& channel : contents.channels)+ channels.unchecked_append(channel.span());+ auto const* kernel = RustFFI::web_audio_convolver_kernel_create(channels.span(), contents.sample_rate, partition_size, normalize);+ if (!kernel)+ return nullptr;+ return adopt_ref(*new ConvolverKernel(kernel));+}- // Calibrate to make perceived volume same as unprocessed.- scale *= gain_calibration;+ConvolverKernel::~ConvolverKernel()+{+ RustFFI::web_audio_convolver_kernel_destroy(m_kernel);+}- // Scale depends on sample-rate.- if (contents.sample_rate != 0)- scale *= gain_calibration_sample_rate / contents.sample_rate;+size_t ConvolverKernel::channel_count() const+{+ return RustFFI::web_audio_convolver_kernel_channel_count(m_kernel);+}- // True-stereo compensation.- if (contents.channels.size() == 4)- scale *= 0.5;+size_t ConvolverKernel::partition_count() const+{+ return RustFFI::web_audio_convolver_kernel_partition_count(m_kernel);+}- return static_cast<float>(scale);+size_t ConvolverKernel::bin_count() const+{+ return RustFFI::web_audio_convolver_kernel_bin_count(m_kernel);}-RefPtr<ConvolverKernel> ConvolverKernel::create(AudioBufferContents const& contents, size_t partition_size, bool normalize)+ReadonlySpan<float> ConvolverKernel::head(size_t channel) const{- auto length = contents.length();- if (length == 0)- return nullptr;+ ReadonlySpan<float> samples;+ RustFFI::web_audio_convolver_kernel_head(m_kernel, channel, &samples);+ return samples;+}- auto scale = normalize ? calculate_normalization_scale(contents) : 1.f;+ReadonlySpan<float> ConvolverKernel::partition_real(size_t channel, size_t partition) const+{+ ReadonlySpan<float> samples;+ RustFFI::web_audio_convolver_kernel_partition_real(m_kernel, channel, partition, &samples);+ return samples;+}- // Each partition is zero-padded to twice its length so that the cyclic convolution of the transform produces the- // linear convolution the rendering thread is after.- auto transform_size = 2 * partition_size;- auto bin_count = partition_size + 1;- auto partition_count = length > partition_size ? ceil_div(length - partition_size, partition_size) : 0;+ReadonlySpan<float> ConvolverKernel::partition_imag(size_t channel, size_t partition) const+{+ ReadonlySpan<float> samples;+ RustFFI::web_audio_convolver_kernel_partition_imag(m_kernel, channel, partition, &samples);+ return samples;+}- FFT fft { transform_size };- Vector<float> real;- Vector<float> imag;- real.resize(transform_size);- imag.resize(transform_size);+NonnullRefPtr<ConvolverDelayLine> ConvolverDelayLine::create(ConvolverKernel const& kernel)+{+ return adopt_ref(*new ConvolverDelayLine(RustFFI::web_audio_convolver_delay_line_create(kernel.m_kernel)));+}- Vector<Channel> channels;- channels.ensure_capacity(contents.channels.size());- for (auto const& samples : contents.channels) {- Channel channel;- channel.head.resize(partition_size);- channel.real.resize(partition_count * bin_count);- channel.imag.resize(partition_count * bin_count);-- for (size_t frame = 0; frame < min(partition_size, length); ++frame)- channel.head[frame] = samples[frame] * scale;-- for (size_t partition = 0; partition < partition_count; ++partition) {- auto offset = (partition + 1) * partition_size;- auto frames_in_partition = min(partition_size, length - offset);- for (size_t frame = 0; frame < frames_in_partition; ++frame)- real[frame] = samples[offset + frame] * scale;- for (size_t frame = frames_in_partition; frame < transform_size; ++frame)- real[frame] = 0;- for (size_t frame = 0; frame < transform_size; ++frame)- imag[frame] = 0;-- fft.transform(real, imag);-- for (size_t bin = 0; bin < bin_count; ++bin) {- channel.real[partition * bin_count + bin] = real[bin];- channel.imag[partition * bin_count + bin] = imag[bin];- }- }-- channels.unchecked_append(move(channel));- }-- return adopt_ref(*new ConvolverKernel(move(channels), partition_count, bin_count));+ConvolverDelayLine::~ConvolverDelayLine()+{+ RustFFI::web_audio_convolver_delay_line_destroy(m_delay_line);}-NonnullRefPtr<ConvolverDelayLine> ConvolverDelayLine::create(ConvolverKernel const& kernel)+size_t ConvolverDelayLine::length() const{- auto length = kernel.partition_count() + 1;+ return RustFFI::web_audio_convolver_delay_line_length(m_delay_line);+}- Array<FixedArray<float>, MAX_CHANNEL_COUNT> real;- Array<FixedArray<float>, MAX_CHANNEL_COUNT> imag;- for (size_t channel = 0; channel < MAX_CHANNEL_COUNT; ++channel) {- real[channel] = MUST(FixedArray<float>::create(length * kernel.bin_count()));- imag[channel] = MUST(FixedArray<float>::create(length * kernel.bin_count()));- }+Span<float> ConvolverDelayLine::real(size_t channel)+{+ Span<float> samples;+ RustFFI::web_audio_convolver_delay_line_real(m_delay_line, channel, &samples);+ return samples;+}- return adopt_ref(*new ConvolverDelayLine(length, move(real), move(imag)));+Span<float> ConvolverDelayLine::imag(size_t channel)+{+ Span<float> samples;+ RustFFI::web_audio_convolver_delay_line_imag(m_delay_line, channel, &samples);+ return samples;}}diff --git a/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.h b/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.hindex f7463d5aa4c..8c96201170e 100644--- a/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.h+++ b/Libraries/LibWeb/WebAudio/Rendering/ConvolverKernel.h@@ -1,99 +1,61 @@/** 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/AtomicRefCounted.h>-#include <AK/FixedArray.h>#include <AK/NonnullRefPtr.h>#include <AK/RefPtr.h>#include <AK/Span.h>-#include <AK/Vector.h>#include <LibWeb/WebAudio/Rendering/AudioData.h>namespace Web::WebAudio::Rendering {-// An impulse response prepared for convolution on the rendering thread, built on the control thread when a-// ConvolverNode's buffer is set so the rendering thread never has to transform a whole impulse response in a single-// quantum.-//-// The first partition is kept in the time domain: it is the one that carries the quietest part of the output, where the-// round-off of a transform round trip is most audible. Everything after it is cut into equally sized partitions and-// transformed. Only the first half of each partition's spectrum plus the Nyquist bin is stored; the remaining bins-// follow from the Hermitian symmetry of the transform of a real signal.-// https://webaudio.github.io/web-audio-api/#ConvolverNodeclass ConvolverKernel : public AtomicRefCounted<ConvolverKernel> {public:static RefPtr<ConvolverKernel> create(AudioBufferContents const&, size_t partition_size, bool normalize);+ ~ConvolverKernel();- size_t channel_count() const { return m_channels.size(); }-- // The number of partitions that are held in the frequency domain, which excludes the time-domain head.- size_t partition_count() const { return m_partition_count; }- size_t bin_count() const { return m_bin_count; }-- ReadonlySpan<float> head(size_t channel) const { return m_channels[channel].head; }-- ReadonlySpan<float> partition_real(size_t channel, size_t partition) const- {- return m_channels[channel].real.span().slice(partition * m_bin_count, m_bin_count);- }-- ReadonlySpan<float> partition_imag(size_t channel, size_t partition) const- {- return m_channels[channel].imag.span().slice(partition * m_bin_count, m_bin_count);- }+ size_t channel_count() const;+ size_t partition_count() const;+ size_t bin_count() const;+ ReadonlySpan<float> head(size_t channel) const;+ ReadonlySpan<float> partition_real(size_t channel, size_t partition) const;+ ReadonlySpan<float> partition_imag(size_t channel, size_t partition) const;private:- struct Channel {- Vector<float> head;- Vector<float> real;- Vector<float> imag;- };+ friend class ConvolverDelayLine;- ConvolverKernel(Vector<Channel> channels, size_t partition_count, size_t bin_count)- : m_channels(move(channels))- , m_partition_count(partition_count)- , m_bin_count(bin_count)+ explicit ConvolverKernel(void const* kernel)+ : m_kernel(kernel){}- Vector<Channel> m_channels;- size_t m_partition_count { 0 };- size_t m_bin_count { 0 };+ void const* m_kernel { nullptr };};-// The ring of input spectra a ConvolverRenderNode multiplies with the kernel's partitions, one slot per partition plus-// one for the window written in the current quantum. It is sized after the kernel, so it is allocated here on the-// control thread and handed over together with the kernel, keeping allocation off the rendering thread.class ConvolverDelayLine : public AtomicRefCounted<ConvolverDelayLine> {public:- // The input to a ConvolverNode is mono or stereo and cannot be increased.- // https://webaudio.github.io/web-audio-api/#ConvolverNodestatic constexpr size_t MAX_CHANNEL_COUNT = 2;static NonnullRefPtr<ConvolverDelayLine> create(ConvolverKernel const&);+ ~ConvolverDelayLine();- size_t length() const { return m_length; }-- Span<float> real(size_t channel) { return m_real[channel].span(); }- Span<float> imag(size_t channel) { return m_imag[channel].span(); }+ size_t length() const;+ Span<float> real(size_t channel);+ Span<float> imag(size_t channel);private:- ConvolverDelayLine(size_t length, Array<FixedArray<float>, MAX_CHANNEL_COUNT> real, Array<FixedArray<float>, MAX_CHANNEL_COUNT> imag)- : m_length(length)- , m_real(move(real))- , m_imag(move(imag))+ explicit ConvolverDelayLine(void* delay_line)+ : m_delay_line(delay_line){}- size_t m_length { 0 };- Array<FixedArray<float>, MAX_CHANNEL_COUNT> m_real;- Array<FixedArray<float>, MAX_CHANNEL_COUNT> m_imag;+ void* m_delay_line { nullptr };};}diff --git a/Libraries/LibWeb/WebAudio/Rendering/FFT.cpp b/Libraries/LibWeb/WebAudio/Rendering/FFT.cppindex 0c5db71217d..03354dd0939 100644--- a/Libraries/LibWeb/WebAudio/Rendering/FFT.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/FFT.cpp@@ -4,70 +4,27 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Math.h>#include <LibWeb/WebAudio/Rendering/FFT.h>+#include <LibWeb/WebAudio/RustFFI.h>namespace Web::WebAudio::Rendering {-// Radix-2 Cooley-Tukey FFT of a fixed power-of-two size. The twiddle factors depend only on that size, so they are-// computed once here and shared by every transform.FFT::FFT(size_t size): m_size(size)+ , m_fft(RustFFI::web_audio_fft_create(size)){- VERIFY(size != 0 && (size & (size - 1)) == 0);+}- m_twiddle_real = MUST(FixedArray<float>::create(size / 2));- m_twiddle_imag = MUST(FixedArray<float>::create(size / 2));- for (size_t index = 0; index < size / 2; ++index) {- auto angle = -2. * AK::Pi<double> * static_cast<double>(index) / static_cast<double>(size);- m_twiddle_real[index] = static_cast<float>(AK::cos(angle));- m_twiddle_imag[index] = static_cast<float>(AK::sin(angle));- }+FFT::~FFT()+{+ RustFFI::web_audio_fft_destroy(m_fft);}-// Both spans must hold exactly `size()` samples. The inverse transform includes the 1/N scaling.void FFT::transform(Span<float> re, Span<float> im, FFTDirection direction) const{- VERIFY(re.size() == m_size && im.size() == m_size);-- for (size_t i = 1, j = 0; i < m_size; ++i) {- size_t bit = m_size >> 1;- for (; j & bit; bit >>= 1)- j ^= bit;- j ^= bit;- if (i < j) {- AK::swap(re[i], re[j]);- AK::swap(im[i], im[j]);- }- }-- auto twiddle_sign = direction == FFTDirection::Forward ? 1.f : -1.f;- for (size_t len = 2; len <= m_size; len <<= 1) {- auto half = len >> 1;- auto twiddle_stride = m_size / len;- for (size_t i = 0; i < m_size; i += len) {- for (size_t k = 0; k < half; ++k) {- auto w_re = m_twiddle_real[k * twiddle_stride];- auto w_im = m_twiddle_imag[k * twiddle_stride] * twiddle_sign;- auto u_re = re[i + k];- auto u_im = im[i + k];- auto v_re = re[i + k + half] * w_re - im[i + k + half] * w_im;- auto v_im = re[i + k + half] * w_im + im[i + k + half] * w_re;- re[i + k] = u_re + v_re;- im[i + k] = u_im + v_im;- re[i + k + half] = u_re - v_re;- im[i + k + half] = u_im - v_im;- }- }- }-- if (direction == FFTDirection::Inverse) {- auto inverse_size = 1.f / static_cast<float>(m_size);- for (size_t i = 0; i < m_size; ++i) {- re[i] *= inverse_size;- im[i] *= inverse_size;- }- }+ static_assert(to_underlying(FFTDirection::Forward) == to_underlying(RustFFI::FFTDirection::Forward));+ static_assert(to_underlying(FFTDirection::Inverse) == to_underlying(RustFFI::FFTDirection::Inverse));+ RustFFI::web_audio_fft_transform(m_fft, re, im, static_cast<RustFFI::FFTDirection>(direction));}}diff --git a/Libraries/LibWeb/WebAudio/Rendering/FFT.h b/Libraries/LibWeb/WebAudio/Rendering/FFT.hindex e2568845159..e73336c415a 100644--- a/Libraries/LibWeb/WebAudio/Rendering/FFT.h+++ b/Libraries/LibWeb/WebAudio/Rendering/FFT.h@@ -6,7 +6,7 @@#pragma once-#include <AK/FixedArray.h>+#include <AK/Noncopyable.h>#include <AK/Span.h>namespace Web::WebAudio::Rendering {@@ -18,9 +18,11 @@ enum class FFTDirection {class FFT {public:+ AK_MAKE_NONCOPYABLE(FFT);AK_ALLOC_WITH_KMALLOC;explicit FFT(size_t size);+ ~FFT();size_t size() const { return m_size; }@@ -28,8 +30,7 @@ public:private:size_t m_size { 0 };- FixedArray<float> m_twiddle_real;- FixedArray<float> m_twiddle_imag;+ void* m_fft { nullptr };};}