Skip to content

Truly independent web browser

LibWeb: Port PeriodicWave to a Rust interface

Shannon Booth61d9dbc26ad5
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index fac8c144518..c4b13aa254a 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -208,6 +208,11 @@ pub(crate) mod webrtc;
)]
pub(crate) mod xhr;
+#[cfg(not(test))]
+#[cfg_attr(not(web_idl_bindings), allow(dead_code))]
+#[allow(clippy::unnecessary_wraps)]
+pub(crate) mod web_audio;
+
// The generators of the build script, whose tests run with those of the crate.
#[cfg(test)]
#[path = "../generate/webgl_constants.rs"]
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/mod.rs
new file mode 100644
index 00000000000..f10033ef65b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/mod.rs
@@ -0,0 +1,7 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+pub(crate) mod periodic_wave;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/periodic_wave.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/periodic_wave.rs
new file mode 100644
index 00000000000..b225f346ab2
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/periodic_wave.rs
@@ -0,0 +1,223 @@
+/*
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2025, Tim Ledbetter <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#![allow(
+ clippy::unnecessary_unwrap,
+ reason = "preserve the C++ constructor's explicit option cases"
+)]
+
+use std::cell::RefCell;
+use std::ffi::c_void;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{ErrorKind, ErrorType, RawNativeFunctionResult, Trace, Value, Vm};
+use libweb_rust::web_audio::rendering::audio_data::PeriodicWaveData;
+
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, realm_arguments};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+pub(crate) struct PeriodicWaveConstraints {
+ pub(crate) disable_normalization: bool,
+}
+
+pub(crate) struct PeriodicWaveOptions {
+ pub(crate) parent: PeriodicWaveConstraints,
+ pub(crate) real: Option<Vec<f32>>,
+ pub(crate) imag: Option<Vec<f32>>,
+}
+
+struct State {
+ real: Vec<f32>,
+ imag: Vec<f32>,
+ normalize: bool,
+}
+
+// https://webaudio.github.io/web-audio-api/#PeriodicWave
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct PeriodicWave {
+ #[gc(untraced)]
+ state: RefCell<State>,
+}
+
+impl Wrappable for PeriodicWave {
+ const OWNS_EXTERNAL_MEMORY: bool = true;
+
+ fn external_memory_size(&self) -> usize {
+ let state = self.state.borrow();
+ (state.real.capacity() * size_of::<f32>()).saturating_add(state.imag.capacity() * size_of::<f32>())
+ }
+}
+
+fn copy_float_vector(vm: &Vm, source: &[f32]) -> WebIdlResult<Vec<f32>> {
+ let mut vector = Vec::new();
+ vector.try_reserve_exact(source.len()).map_err(|_| {
+ Exception::from(
+ vm.throw_completion::<()>(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])
+ .unwrap_err(),
+ )
+ })?;
+ vector.extend_from_slice(source);
+ Ok(vector)
+}
+
+fn zeroed_float_vector(vm: &Vm, size: usize) -> WebIdlResult<Vec<f32>> {
+ let mut vector = Vec::new();
+ vector.try_reserve_exact(size).map_err(|_| {
+ Exception::from(
+ vm.throw_completion::<()>(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])
+ .unwrap_err(),
+ )
+ })?;
+ vector.resize(size, 0.);
+ Ok(vector)
+}
+
+impl PeriodicWave {
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ _context: CppInterface,
+ options: PeriodicWaveOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ Self::create(cx, options)
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dom-periodicwave-periodicwave
+ pub(crate) fn create(cx: &mut CallContext, options: PeriodicWaveOptions) -> WebIdlResult<Ref<Self>> {
+ let vm = cx.vm();
+
+ // 1. Let p be a new PeriodicWave object. Let [[real]] and [[imag]] be two internal slots of type Float32Array, and let [[normalize]] be an internal slot.
+ let p = allocate(vm, |_| Self {
+ state: RefCell::new(State {
+ real: Vec::new(),
+ imag: Vec::new(),
+ normalize: true,
+ }),
+ });
+ let mut state = p.state.borrow_mut();
+
+ // 2. Process options according to one of the following cases:
+ {
+ // 1. If both options.real and options.imag are present
+ if options.real.is_some() && options.imag.is_some() {
+ // 1. If the lengths of options.real and options.imag are different or if either length is less than 2, throw an IndexSizeError and abort this algorithm.
+ if options.real.as_ref().unwrap().len() != options.imag.as_ref().unwrap().len()
+ || options.real.as_ref().unwrap().len() < 2
+ {
+ return Err(Exception::index_size_error(Utf16String::from_ascii(
+ b"Real and imaginary arrays must have the same length and contain at least 2 elements",
+ )));
+ }
+
+ // 2. Set [[real]] and [[imag]] to new arrays with the same length as options.real.
+ // 3. Copy all elements from options.real to [[real]] and options.imag to [[imag]].
+ state.real = copy_float_vector(vm, options.real.as_ref().unwrap())?;
+ state.imag = copy_float_vector(vm, options.imag.as_ref().unwrap())?;
+ }
+ // 2. If only options.real is present
+ else if let Some(real) = &options.real {
+ // 1. If length of options.real is less than 2, throw an IndexSizeError and abort this algorithm
+ if real.len() < 2 {
+ return Err(Exception::index_size_error(Utf16String::from_ascii(
+ b"Real array must contain at least 2 elements",
+ )));
+ }
+
+ // 2. Set [[real]] and [[imag]] to arrays with the same length as options.real
+ // 3. Copy options.real to [[real]] and set [[imag]] to all zeros.
+ state.real = copy_float_vector(vm, real)?;
+ state.imag = zeroed_float_vector(vm, real.len())?;
+ }
+ // 3. If only options.imag is present
+ else if let Some(imag) = &options.imag {
+ // 1. If length of options.imag is less than 2, throw an IndexSizeError and abort this algorithm.
+ if imag.len() < 2 {
+ return Err(Exception::index_size_error(Utf16String::from_ascii(
+ b"Imaginary array must contain at least 2 elements",
+ )));
+ }
+
+ // 2. Set [[real]] and [[imag]] to arrays with the same length as options.imag.
+ // 3. Copy options.imag to [[imag]] and set [[real]] to all zeros.
+ state.real = zeroed_float_vector(vm, imag.len())?;
+ state.imag = copy_float_vector(vm, imag)?;
+ }
+ // 4. Otherwise
+ else {
+ // 1. Set [[real]] and [[imag]] to zero-filled arrays of length 2.
+ state.real = zeroed_float_vector(vm, 2)?;
+ state.imag = zeroed_float_vector(vm, 2)?;
+
+ // 2. Set element at index 1 of [[imag]] to 1.
+ state.imag[1] = 1.;
+ }
+ }
+
+ // 3. Set element at index 0 of both [[real]] and [[imag]] to 0. (This sets the DC component to 0.)
+ state.real[0] = 0.;
+ state.imag[0] = 0.;
+
+ // 4. Initialize [[normalize]] to the inverse of the disableNormalization attribute of the PeriodicWaveConstraints on the PeriodicWaveOptions.
+ state.normalize = !options.parent.disable_normalization;
+ drop(state);
+
+ // 5. Return p.
+ Ok(p)
+ }
+
+ pub(crate) fn render_data(&self) -> Arc<PeriodicWaveData> {
+ let state = self.state.borrow();
+ Arc::new(PeriodicWaveData {
+ real: state.real.clone(),
+ imag: state.imag.clone(),
+ normalize: state.normalize,
+ })
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_periodic_wave_create(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ has_real: bool,
+ real: ak::Span<'_, f32>,
+ has_imag: bool,
+ imag: ak::Span<'_, f32>,
+ disable_normalization: bool,
+ output: *mut *mut c_void,
+) -> RawNativeFunctionResult {
+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };
+ let mut cx = CallContext::new(vm, realm);
+ let options = PeriodicWaveOptions {
+ parent: PeriodicWaveConstraints { disable_normalization },
+ real: has_real.then(|| real.as_slice().to_vec()),
+ imag: has_imag.then(|| imag.as_slice().to_vec()),
+ };
+ let result = PeriodicWave::create(&mut cx, options).map(|wave| {
+ unsafe {
+ *output = cell_into_abi(wave);
+ }
+ Value::UNDEFINED
+ });
+ RawNativeFunctionResult::from_completion(result.map_err(|exception| exception.throw(&cx)))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_rust_periodic_wave_render_data(
+ cell: *mut c_void,
+ normalize: *mut bool,
+) -> *const PeriodicWaveData {
+ let wave: Ref<PeriodicWave> = unsafe { cell_from_abi(cell) };
+ let data = wave.render_data();
+ unsafe {
+ *normalize = data.normalize;
+ }
+ Arc::into_raw(data)
+}
diff --git a/Libraries/LibWeb/WebAudio/PeriodicWave.cpp b/Libraries/LibWeb/WebAudio/PeriodicWave.cpp
index 0f83f65a1e8..479aedbbcce 100644
--- a/Libraries/LibWeb/WebAudio/PeriodicWave.cpp
+++ b/Libraries/LibWeb/WebAudio/PeriodicWave.cpp
@@ -1,115 +1,36 @@
/*
* Copyright (c) 2024, Shannon Booth <[email protected]>
* Copyright (c) 2025, Tim Ledbetter <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ExternalMemory.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/WebAudio/PeriodicWave.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::WebAudio {
-GC_DEFINE_ALLOCATOR(PeriodicWave);
-
-static ErrorOr<Vector<float>> copy_float_vector(ReadonlySpan<float> source)
-{
- Vector<float> vector;
- TRY(vector.try_append(source.data(), source.size()));
- return vector;
-}
-
-static ErrorOr<Vector<float>> zeroed_float_vector(size_t size)
-{
- Vector<float> vector;
- TRY(vector.try_resize(size));
- return vector;
+extern "C" {
+JSCompletion web_rust_periodic_wave_create(JSVM*, void* realm, bool, ReadonlySpan<float>, bool, ReadonlySpan<float>, bool, void**);
+void const* web_rust_periodic_wave_render_data(void* cell, bool* normalize);
}
-// https://webaudio.github.io/web-audio-api/#dom-periodicwave-periodicwave
WebIDL::ExceptionOr<GC::Ref<PeriodicWave>> PeriodicWave::create_for_constructor(GC::Ref<BaseAudioContext>, PeriodicWaveOptions const& options)
{
auto& vm = JS::VM::the();
-
- // 1. Let p be a new PeriodicWave object. Let [[real]] and [[imag]] be two internal slots of type Float32Array, and let [[normalize]] be an internal slot.
- auto p = GC::Heap::the().allocate<PeriodicWave>();
-
- // 2. Process options according to one of the following cases:
- {
- // 1. If both options.real and options.imag are present
- if (options.real.has_value() && options.imag.has_value()) {
- // 1. If the lengths of options.real and options.imag are different or if either length is less than 2, throw an IndexSizeError and abort this algorithm.
- if (options.real.value().size() != options.imag.value().size() || options.real.value().size() < 2)
- return WebIDL::IndexSizeError::create("Real and imaginary arrays must have the same length and contain at least 2 elements"_utf16);
-
- // 2. Set [[real]] and [[imag]] to new arrays with the same length as options.real.
- // 3. Copy all elements from options.real to [[real]] and options.imag to [[imag]].
- p->m_real = TRY_OR_THROW_OOM(vm, copy_float_vector(*options.real));
- p->m_imag = TRY_OR_THROW_OOM(vm, copy_float_vector(*options.imag));
- }
- // 2. If only options.real is present
- else if (options.real.has_value()) {
- // 1. If length of options.real is less than 2, throw an IndexSizeError and abort this algorithm
- if (options.real.value().size() < 2)
- return WebIDL::IndexSizeError::create("Real array must contain at least 2 elements"_utf16);
-
- // 2. Set [[real]] and [[imag]] to arrays with the same length as options.real
- // 3. Copy options.real to [[real]] and set [[imag]] to all zeros.
- p->m_real = TRY_OR_THROW_OOM(vm, copy_float_vector(*options.real));
- p->m_imag = TRY_OR_THROW_OOM(vm, zeroed_float_vector(options.real->size()));
- }
- // 3. If only options.imag is present
- else if (options.imag.has_value()) {
- // 1. If length of options.imag is less than 2, throw an IndexSizeError and abort this algorithm.
- if (options.imag.value().size() < 2)
- return WebIDL::IndexSizeError::create("Imaginary array must contain at least 2 elements"_utf16);
-
- // 2. Set [[real]] and [[imag]] to arrays with the same length as options.imag.
- // 3. Copy options.imag to [[imag]] and set [[real]] to all zeros.
- p->m_real = TRY_OR_THROW_OOM(vm, zeroed_float_vector(options.imag->size()));
- p->m_imag = TRY_OR_THROW_OOM(vm, copy_float_vector(*options.imag));
- }
- // 4. Otherwise
- else {
- // 1. Set [[real]] and [[imag]] to zero-filled arrays of length 2.
- p->m_real = TRY_OR_THROW_OOM(vm, zeroed_float_vector(2));
- p->m_imag = TRY_OR_THROW_OOM(vm, zeroed_float_vector(2));
-
- // 2. Set element at index 1 of [[imag]] to 1.
- p->m_imag[1] = 1;
- }
- }
-
- // 3. Set element at index 0 of both [[real]] and [[imag]] to 0. (This sets the DC component to 0.)
- p->m_real[0] = 0;
- p->m_imag[0] = 0;
-
- // 4. Initialize [[normalize]] to the inverse of the disableNormalization attribute of the PeriodicWaveConstraints on the PeriodicWaveOptions.
- p->m_normalize = !options.disable_normalization;
-
- // 5. Return p.
- return p;
-}
-
-PeriodicWave::PeriodicWave()
-{
+ void* wave = nullptr;
+ TRY(JS::HostABI::completion_from_abi<void>(web_rust_periodic_wave_create(JS::HostABI::vm_to_abi(vm), vm.current_realm(), options.real.has_value(), options.real.has_value() ? options.real->span() : ReadonlySpan<float> {}, options.imag.has_value(), options.imag.has_value() ? options.imag->span() : ReadonlySpan<float> {}, options.disable_normalization, &wave)));
+ return GC::Ref { *static_cast<PeriodicWave*>(wave) };
}
NonnullRefPtr<Rendering::PeriodicWaveData> PeriodicWave::render_data() const
{
- return make_ref_counted<Rendering::PeriodicWaveData>(m_real, m_imag, m_normalize);
-}
-
-PeriodicWave::~PeriodicWave() = default;
-
-size_t PeriodicWave::external_memory_size() const
-{
- auto size = JS::saturating_add_external_memory_size(Base::external_memory_size(), JS::vector_external_memory_size(m_real));
- size = JS::saturating_add_external_memory_size(size, JS::vector_external_memory_size(m_imag));
- return size;
+ bool normalize;
+ auto* data = web_rust_periodic_wave_render_data(const_cast<PeriodicWave*>(this), &normalize);
+ return make_ref_counted<Rendering::PeriodicWaveData>(data, normalize);
}
}
diff --git a/Libraries/LibWeb/WebAudio/PeriodicWave.h b/Libraries/LibWeb/WebAudio/PeriodicWave.h
index b7e5de891d7..00ca357d1f5 100644
--- a/Libraries/LibWeb/WebAudio/PeriodicWave.h
+++ b/Libraries/LibWeb/WebAudio/PeriodicWave.h
@@ -1,5 +1,6 @@
/*
* Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -10,7 +11,7 @@
#include <AK/Vector.h>
#include <LibJS/Forward.h>
#include <LibWeb/Bindings/PeriodicWave.h>
-#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/WebAudio/Rendering/AudioData.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
@@ -19,28 +20,18 @@ namespace Web::WebAudio {
class BaseAudioContext;
using PeriodicWaveConstraints = Bindings::PeriodicWaveConstraints;
-using PeriodicWaveOptions = Bindings::PeriodicWaveOptions;
+struct PeriodicWaveOptions : PeriodicWaveConstraints {
+ Optional<Vector<float>> real;
+ Optional<Vector<float>> imag;
+};
// https://webaudio.github.io/web-audio-api/#PeriodicWave
-class PeriodicWave : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(PeriodicWave, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(PeriodicWave);
+class PeriodicWave : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(PeriodicWave, periodic_wave)
public:
static WebIDL::ExceptionOr<GC::Ref<PeriodicWave>> create_for_constructor(GC::Ref<BaseAudioContext>, PeriodicWaveOptions const&);
-
- PeriodicWave();
- virtual ~PeriodicWave() override;
-
NonnullRefPtr<Rendering::PeriodicWaveData> render_data() const;
-
-protected:
- virtual size_t external_memory_size() const override;
-
-private:
- Vector<float> m_real;
- Vector<float> m_imag;
- bool m_normalize { true };
};
}
diff --git a/Libraries/LibWeb/WebAudio/PeriodicWave.idl b/Libraries/LibWeb/WebAudio/PeriodicWave.idl
index 57a8c62b077..46c240c9a45 100644
--- a/Libraries/LibWeb/WebAudio/PeriodicWave.idl
+++ b/Libraries/LibWeb/WebAudio/PeriodicWave.idl
@@ -10,7 +10,7 @@ dictionary PeriodicWaveOptions : PeriodicWaveConstraints {
};
// https://webaudio.github.io/web-audio-api/#PeriodicWave
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface PeriodicWave {
constructor(BaseAudioContext context, optional PeriodicWaveOptions options = {});
};
diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioData.cpp b/Libraries/LibWeb/WebAudio/Rendering/AudioData.cpp
index 3be3d06efde..0c9200bf4f4 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/AudioData.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioData.cpp
@@ -34,6 +34,13 @@ PeriodicWaveData::PeriodicWaveData(Vector<float> real_values, Vector<float> imag
RustFFI::web_audio_periodic_wave_data_real(m_data, &real);
RustFFI::web_audio_periodic_wave_data_imag(m_data, &imag);
}
+PeriodicWaveData::PeriodicWaveData(void const* data, bool should_normalize)
+ : normalize(should_normalize)
+ , m_data(data)
+{
+ 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 0b997430e03..2244f00d436 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/AudioData.h
+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioData.h
@@ -34,6 +34,7 @@ private:
};
struct PeriodicWaveData : public AtomicRefCounted<PeriodicWaveData> {
PeriodicWaveData(Vector<float> real, Vector<float> imag, bool normalize);
+ PeriodicWaveData(void const* data, bool normalize);
~PeriodicWaveData();
void const* rust_data() const { return m_data; }
ReadonlySpan<float> real;