Truly independent web browser
LibWeb: Port AudioBuffer to a Rust interface
Shannon Boothec5defeea098
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer.rsnew file mode 100644index 00000000000..1aad0274191--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_buffer.rs@@ -0,0 +1,596 @@+/*+ * Copyright (c) 2024, Shannon Booth <[email protected]>+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#![allow(+ clippy::needless_range_loop,+ clippy::collapsible_if,+ reason = "preserve the C++ channel and cache traversal order"+)]++use std::cell::RefCell;+use std::ffi::c_void;+use std::ptr::NonNull;+use std::sync::Arc;++use ak::Utf16String;+use libjs_rust::api::{+ ArrayBuffer, ArrayBufferOrder, ArrayBufferShared, DataBlock, EmbedderCell, ErrorKind, ErrorType,+ ExternalPrimitiveStorage, ForeignCellSlot, Gc, GcWeak, RawNativeFunctionResult, Trace, TypedArrayBase,+ TypedArrayKind, Value, Vm, create_typed_array_on_buffer, detach_array_buffer,+ make_typed_array_with_buffer_witness_record,+};+use libjs_rust::api::{OutOfMemory, OwnedBackingStore};+use libjs_rust::api::{is_typed_array_out_of_bounds, typed_array_byte_length};+use libweb_rust::web_audio::rendering::audio_data::AudioBufferContents;++use crate::bindings::interface::{Ref, Wrappable, Wrapped, allocate, cell_from_abi, cell_into_abi, realm_arguments};+use crate::bindings::{CallContext, Exception, WebIdlResult};++pub(crate) struct AudioBufferOptions {+ pub(crate) number_of_channels: u32,+ pub(crate) length: u32,+ pub(crate) sample_rate: f32,+}++// The sample data lives in the primitive storage cage, so an out-of-bounds access through a channel's Float32Array+// is masked back into the cage instead of reaching memory outside it. The AudioBuffer owns the storage, and the+// ArrayBuffer handed to script holds an owner edge back to the AudioBuffer, so the storage outlives every view.+struct Channel {+ data: OwnedBackingStore,+}++// https://webaudio.github.io/web-audio-api/#AudioBuffer+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct AudioBuffer {+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-number-of-channels-slot+ // The number of audio channels for this AudioBuffer, which is an unsigned long.+ //+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-internal-data-slot+ // A data block holding the audio sample data.+ #[gc(untraced)]+ channels: RefCell<Vec<Channel>>, // [[internal data]] / [[number_of_channels]]+ // https://webaudio.github.io/web-audio-api/#audio-buffer-copying+ #[gc(untraced)]+ contents: RefCell<Option<Arc<AudioBufferContents>>>,++ // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-length-slot+ // The length of each channel of this AudioBuffer, which is an unsigned long.+ length: u32, // [[length]]+ // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-sample-rate-slot+ // The sample-rate, in Hz, of this AudioBuffer, a float.+ sample_rate: f32, // [[sample rate]]+}++impl Wrappable for AudioBuffer {+ const OWNS_EXTERNAL_MEMORY: bool = true;++ fn external_memory_size(&self) -> usize {+ let channels = self.channels.borrow();+ let mut size = channels.capacity() * size_of::<Channel>();+ for channel in &*channels {+ size = size.saturating_add(channel.data.capacity());+ }+ size+ }+}++// The ArrayBuffer is tracked next to the view because it can outlive it: script is free to keep `array.buffer` and+// drop the array. The buffer is what projects the channel's storage, so it is the one that decides how long that+// storage must stay put, and the one that has to be detached when the content is acquired.+struct AudioBufferChannelView {+ view: GcWeak<TypedArrayBase>,+ array_buffer: GcWeak<ArrayBuffer>,+}++struct AudioBufferChannelDataCacheEntry {+ buffer: GcWeak<EmbedderCell<Wrapped<AudioBuffer>>>,+ channel: u32,+ views: Vec<AudioBufferChannelView>,+}++thread_local! { static AUDIO_BUFFER_CHANNEL_DATA_CACHES: RefCell<Vec<AudioBufferChannelDataCacheEntry>> = const { RefCell::new(Vec::new()) }; }+fn prune_audio_buffer_channel_data_caches(caches: &mut Vec<AudioBufferChannelDataCacheEntry>) {+ caches.retain(|entry| entry.buffer.get().is_some());+}++fn cache_for<'a>(+ caches: &'a mut Vec<AudioBufferChannelDataCacheEntry>,+ vm: &Vm,+ buffer: Ref<AudioBuffer>,+ channel: u32,+) -> &'a mut AudioBufferChannelDataCacheEntry {+ prune_audio_buffer_channel_data_caches(caches);+ for index in 0..caches.len() {+ if caches[index].buffer.get() == Some(buffer) && caches[index].channel == channel {+ return &mut caches[index];+ }+ }+ caches.push(AudioBufferChannelDataCacheEntry {+ buffer: GcWeak::new(vm.heap(), buffer),+ channel,+ views: Vec::new(),+ });+ caches.last_mut().unwrap()+}++fn prune_live_channel_views(views: &mut Vec<AudioBufferChannelView>) {+ views.retain(|entry| entry.array_buffer.get().is_some());+}++unsafe extern "C" {+ fn web_audio_verify_buffer_options(+ realm: *mut c_void,+ number_of_channels: u32,+ length: u32,+ sample_rate: f32,+ ) -> RawNativeFunctionResult;+}++impl AudioBuffer {+ pub(crate) fn construct(cx: &mut CallContext, options: AudioBufferOptions) -> WebIdlResult<Ref<Self>> {+ let vm = cx.vm();++ // 1. If any of the values in options lie outside its nominal range, throw a NotSupportedError exception and abort the following steps.+ unsafe {+ web_audio_verify_buffer_options(+ cx.realm().as_ptr().cast(),+ options.number_of_channels,+ options.length,+ options.sample_rate,+ )+ }+ .into_completion()?;+ if options.length as usize > i32::MAX as usize / size_of::<f32>() {+ return Err(vm+ .throw_completion::<()>(ErrorKind::RangeError, ErrorType::InvalidLength, &[&"typed array"])+ .unwrap_err()+ .into());+ }++ // 2. Let b be a new AudioBuffer object.+ // 3. Respectively assign the values of the attributes numberOfChannels, length, sampleRate of the AudioBufferOptions passed in the+ // constructor to the internal slots [[number of channels]], [[length]], [[sample rate]].+ // 4. Set the internal slot [[internal data]] of this AudioBuffer to the result of calling CreateByteDataBlock([[length]] * [[number of channels]]).+ Self::create(vm, options.number_of_channels, options.length, options.sample_rate).map_err(|_| {+ vm.throw_completion::<()>(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])+ .unwrap_err()+ .into()+ })+ }++ pub(crate) fn create(+ vm: &Vm,+ number_of_channels: u32,+ length: u32,+ sample_rate: f32,+ ) -> Result<Ref<Self>, OutOfMemory> {+ let buffer = allocate(vm, |_| Self {+ channels: RefCell::new(Vec::new()),+ contents: RefCell::new(None),+ length,+ sample_rate,+ });+ let channel_byte_length = length as usize * size_of::<f32>();+ let mut channels = buffer.channels.borrow_mut();+ channels+ .try_reserve_exact(number_of_channels as usize)+ .map_err(|_| OutOfMemory)?;+ for _i in 0..number_of_channels {+ channels.push(Channel {+ data: OwnedBackingStore::create_zeroed(channel_byte_length)?,+ });+ }+ drop(channels);+ vm.heap().did_allocate_external_memory(buffer.external_memory_size());+ Ok(buffer)+ }++ // https://webaudio.github.io/web-audio-api/#acquire-the-content+ pub(crate) fn acquire_contents(this: Ref<Self>, vm: &Vm) -> Option<Arc<AudioBufferContents>> {+ // NB: m_contents is non-null exactly while the channel arrays are detached because step 4 below has not run yet.+ // The snapshot then still holds the buffer's content and script has had no way to modify it, so it can be+ // handed out again as-is. This is what makes a sequence of acquisitions with no intervening getChannelData(),+ // e.g. one AudioBuffer played by many AudioBufferSourceNodes, free of allocations and copying.+ // https://webaudio.github.io/web-audio-api/#audio-buffer-copying+ if let Some(contents) = &*this.contents.borrow() {+ return Some(Arc::clone(contents));+ }++ // 1. If any of the AudioBuffer's ArrayBuffers are detached, return true, abort these steps, and return a+ // zero-length channel data buffer to the invoker.+ let detached = AUDIO_BUFFER_CHANNEL_DATA_CACHES.with_borrow(|caches| {+ for cache in caches {+ if cache.buffer.get() != Some(this) {+ continue;+ }+ for entry in &cache.views {+ if entry.array_buffer.get().is_some_and(|buffer| buffer.is_detached()) {+ return true;+ }+ }+ }+ false+ });+ if detached {+ return None;+ }++ // 2. Detach all ArrayBuffers for arrays previously returned by getChannelData() on this AudioBuffer.+ // 3. Retain the underlying [[internal data]] from those ArrayBuffers and return references to them to the invoker.+ let mut channels = Vec::with_capacity(this.channels.borrow().len());+ for channel in &*this.channels.borrow() {+ let mut samples = vec![0_f32; this.length as usize];+ if !samples.is_empty() {+ unsafe {+ std::ptr::copy_nonoverlapping(+ channel.data.data(),+ samples.as_mut_ptr().cast::<u8>(),+ samples.len() * size_of::<f32>(),+ );+ }+ }+ channels.push(samples);+ }+ AUDIO_BUFFER_CHANNEL_DATA_CACHES.with_borrow(|caches| {+ for cache in caches {+ if cache.buffer.get() != Some(this) {+ continue;+ }+ for entry in &cache.views {+ if let Some(array_buffer) = entry.array_buffer.get() {+ detach_array_buffer(vm, array_buffer, None).expect("channel ArrayBuffers can be detached");+ }+ }+ }+ });+ *this.contents.borrow_mut() = Some(Arc::new(AudioBufferContents {+ channels,+ sample_rate: this.sample_rate,+ }));+ vm.heap()+ .did_allocate_external_memory(this.channels.borrow().len() * this.length as usize * size_of::<f32>());++ // 4. Attach ArrayBuffers containing copies of the data to the AudioBuffer, to be returned by the next call to+ // getChannelData().+ // NB: Performed lazily by attach_acquired_channels().+ this.contents.borrow().clone()+ }++ // https://webaudio.github.io/web-audio-api/#audio-buffer-copying+ pub(crate) fn attach_acquired_channels(this: Ref<Self>) {+ // The pending final step of acquiring this buffer's content: fresh arrays holding a copy of the acquired sample+ // data are attached the first time script reaches for the channel data again. Whoever acquired the content keeps+ // using the snapshot, so writes through the new arrays cannot change what is already playing.+ let mut contents = this.contents.borrow_mut();+ let Some(snapshot) = &*contents else {+ return;+ };+ let channels = this.channels.borrow();+ assert_eq!(snapshot.channels.len(), channels.len());+ for i in 0..channels.len() {+ let samples = &snapshot.channels[i];+ if !samples.is_empty() {+ unsafe {+ std::ptr::copy_nonoverlapping(+ samples.as_ptr().cast::<u8>(),+ channels[i].data.data(),+ samples.len() * size_of::<f32>(),+ );+ }+ }+ }+ *contents = None;++ // Every view of the storage was detached when the content was acquired, and the storage needs fresh views over it.+ // So, drop the cached ones instead of handing a detached array back to the next caller.+ AUDIO_BUFFER_CHANNEL_DATA_CACHES.with_borrow_mut(|caches| {+ for cache in caches {+ if cache.buffer.get() == Some(this) {+ cache.views.clear();+ }+ }+ });+ }++ // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-samplerate+ pub(crate) fn sample_rate(&self, _: &mut CallContext) -> WebIdlResult<f32> {+ // The sample-rate for the PCM audio data in samples per second. This MUST return the value of [[sample rate]].+ Ok(self.sample_rate)+ }++ // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-length+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {+ // Length of the PCM audio data in sample-frames. This MUST return the value of [[length]].+ Ok(self.length)+ }++ // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-duration+ pub(crate) fn duration(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ // Duration of the PCM audio data in seconds.+ // This is computed from the [[sample rate]] and the [[length]] of the AudioBuffer by performing a division between the [[length]] and the [[sample rate]].+ Ok(f64::from(self.length) / f64::from(self.sample_rate))+ }++ // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-numberofchannels+ pub(crate) fn number_of_channels(&self, _: &mut CallContext) -> WebIdlResult<u32> {+ // The number of discrete audio channels. This MUST return the value of [[number of channels]].+ Ok(self.channels.borrow().len() as u32)+ }++ pub(crate) fn channel_data(&self, channel: u32) -> WebIdlResult<(*mut u8, usize)> {+ let channels = self.channels.borrow();+ if channel as usize >= channels.len() {+ return Err(Exception::index_size_error(Utf16String::from_ascii(+ b"Channel index is out of range",+ )));+ }+ let data = &channels[channel as usize].data;+ Ok((data.data(), data.size()))+ }++ // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-getchanneldata+ pub(crate) fn get_channel_data(+ this: &Ref<Self>,+ cx: &mut CallContext,+ channel: u32,+ ) -> WebIdlResult<Gc<TypedArrayBase>> {+ if channel as usize >= this.channels.borrow().len() {+ return Err(Exception::index_size_error(Utf16String::from_ascii(+ b"Channel index is out of range",+ )));+ }++ // This is where the deferred final step of acquiring the content runs: script is reaching for the channel data+ // again, so the copies of the acquired samples become this buffer's internal data before anything reads them.+ Self::attach_acquired_channels(*this);+ let realm = cx.realm();+ AUDIO_BUFFER_CHANNEL_DATA_CACHES.with_borrow_mut(|caches| {+ let cache = cache_for(caches, cx.vm(), *this, channel);+ prune_live_channel_views(&mut cache.views);+ for entry in &cache.views {+ if let Some(view) = entry.view.get() {+ if view.shape().realm() == realm {+ return Ok(view);+ }+ }+ }++ // The ArrayBuffer projects this AudioBuffer's channel storage instead of owning a copy of it, and names the+ // AudioBuffer as the owner of that storage. The GC then traces the AudioBuffer through the ArrayBuffer, so the+ // samples cannot be freed while script still holds a view of them.+ let channels = this.channels.borrow();+ let channel_storage = &channels[channel as usize].data;+ let owner = ForeignCellSlot::empty();+ unsafe {+ owner.set(NonNull::new(cell_into_abi(*this)));+ }+ let storage = ExternalPrimitiveStorage::new(owner, channel_storage.handle(), Some(channel_storage.size()));+ let array_buffer = ArrayBuffer::create_from_data_block(+ cx.vm(),+ realm,+ DataBlock::external(storage, ArrayBufferShared::No),+ );+ let view = create_typed_array_on_buffer(+ cx.vm(),+ realm,+ TypedArrayKind::Float32Array,+ this.length as usize,+ array_buffer,+ );+ cache.views.try_reserve(1).map_err(|_| {+ cx.vm()+ .throw_completion::<()>(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])+ .unwrap_err()+ })?;+ cache.views.push(AudioBufferChannelView {+ view: GcWeak::new(cx.vm().heap(), view),+ array_buffer: GcWeak::new(cx.vm().heap(), array_buffer),+ });+ Ok(view)+ })+ }++ // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-copyfromchannel+ pub(crate) fn copy_from_channel(+ &self,+ cx: &mut CallContext,+ destination: Gc<TypedArrayBase>,+ channel_number: u32,+ buffer_offset: u32,+ ) -> WebIdlResult<()> {+ // The copyFromChannel() method copies the samples from the specified channel of the AudioBuffer to the destination array.+ //+ // Let buffer be the AudioBuffer with Nb frames, let Nf be the number of elements in the destination array, and k be the value+ // of bufferOffset. Then the number of frames copied from buffer to destination is max(0,min(Nb−k,Nf)). If this is less than Nf,+ // then the remaining elements of destination are not modified.+ let vm = cx.vm();+ if destination.viewed_array_buffer().is_shared_array_buffer() {+ return Err(vm+ .throw_completion::<()>(ErrorKind::TypeError, ErrorType::SharedArrayBuffer, &[&"Float32Array"])+ .unwrap_err()+ .into());+ }+ if destination.viewed_array_buffer().is_detached() {+ return Ok(());+ }+ let channels = self.channels.borrow();+ if channel_number as usize >= channels.len() {+ return Err(Exception::index_size_error(Utf16String::from_ascii(+ b"Channel index is out of range",+ )));+ }+ let channel = &channels[channel_number as usize];+ let channel_length = self.length as usize;+ if buffer_offset as usize >= channel_length {+ return Ok(());+ }+ let destination_record = make_typed_array_with_buffer_witness_record(&destination, ArrayBufferOrder::SeqCst);+ let destination_length = if is_typed_array_out_of_bounds(&destination_record) {+ 0+ } else {+ typed_array_byte_length(&destination_record) / size_of::<f32>()+ };+ let count = destination_length.min(channel_length - buffer_offset as usize);+ let destination_bytes = destination.viewed_array_buffer();+ if count != 0 {+ destination_bytes.with_data_block(|destination_block| unsafe {+ std::ptr::copy(+ channel+ .data+ .data()+ .wrapping_add(buffer_offset as usize * size_of::<f32>()),+ destination_block.data_at(destination.byte_offset()),+ count * size_of::<f32>(),+ );+ });+ }+ Ok(())+ }++ // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-copytochannel+ pub(crate) fn copy_to_channel(+ this: &Ref<Self>,+ cx: &mut CallContext,+ source: Gc<TypedArrayBase>,+ channel_number: u32,+ buffer_offset: u32,+ ) -> WebIdlResult<()> {+ // The copyToChannel() method copies the samples to the specified channel of the AudioBuffer from the source array.+ //+ // A UnknownError may be thrown if source cannot be copied to the buffer.+ //+ // Let buffer be the AudioBuffer with Nb frames, let Nf be the number of elements in the source array, and k be the value+ // of bufferOffset. Then the number of frames copied from source to the buffer is max(0,min(Nb−k,Nf)). If this is less than Nf,+ // then the remaining elements of buffer are not modified.+ let vm = cx.vm();+ if source.viewed_array_buffer().is_shared_array_buffer() {+ return Err(vm+ .throw_completion::<()>(ErrorKind::TypeError, ErrorType::SharedArrayBuffer, &[&"Float32Array"])+ .unwrap_err()+ .into());+ }+ if source.viewed_array_buffer().is_detached() {+ return Ok(());+ }+ if channel_number as usize >= this.channels.borrow().len() {+ return Err(Exception::index_size_error(Utf16String::from_ascii(+ b"Channel index is out of range",+ )));+ }+ Self::attach_acquired_channels(*this);+ let channels = this.channels.borrow();+ let channel = &channels[channel_number as usize];+ let channel_length = this.length as usize;+ if buffer_offset as usize >= channel_length {+ return Ok(());+ }+ let source_record = make_typed_array_with_buffer_witness_record(&source, ArrayBufferOrder::SeqCst);+ let source_length = if is_typed_array_out_of_bounds(&source_record) {+ 0+ } else {+ typed_array_byte_length(&source_record) / size_of::<f32>()+ };+ let count = source_length.min(channel_length - buffer_offset as usize);+ let source_bytes = source.viewed_array_buffer();+ if count != 0 {+ source_bytes.with_data_block(|source_block| unsafe {+ std::ptr::copy(+ source_block.data_at(source.byte_offset()),+ channel+ .data+ .data()+ .wrapping_add(buffer_offset as usize * size_of::<f32>()),+ count * size_of::<f32>(),+ );+ });+ }+ Ok(())+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_rust_audio_buffer_create(+ vm: &Vm,+ channels: u32,+ length: u32,+ sample_rate: f32,+ output: *mut *mut c_void,+) -> bool {+ match AudioBuffer::create(vm, channels, length, sample_rate) {+ Ok(buffer) => {+ unsafe {+ *output = cell_into_abi(buffer);+ }+ true+ }+ Err(_) => false,+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_rust_audio_buffer_sample_rate(cell: *mut c_void) -> f32 {+ let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };+ buffer.sample_rate+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_rust_audio_buffer_length(cell: *mut c_void) -> u32 {+ let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };+ buffer.length+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_rust_audio_buffer_channel_count(cell: *mut c_void) -> u32 {+ let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };+ buffer.channels.borrow().len() as u32+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_rust_audio_buffer_channel(+ cell: *mut c_void,+ channel: u32,+ output: *mut ak::SpanMut<'static, u8>,+) -> bool {+ let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };+ match buffer.channel_data(channel) {+ Ok((pointer, length)) => {+ unsafe {+ *output = ak::SpanMut::new(ak::slice_from_raw_parts_mut(pointer, length));+ }+ true+ }+ Err(_) => false,+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_rust_audio_buffer_get_channel_data(+ vm: *mut c_void,+ realm: *mut c_void,+ cell: *mut c_void,+ channel: u32,+) -> RawNativeFunctionResult {+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };+ let mut cx = CallContext::new(vm, realm);+ RawNativeFunctionResult::from_completion(+ AudioBuffer::get_channel_data(&buffer, &mut cx, channel)+ .map(|view| Value::from_object(view.upcast::<libjs_rust::api::Object>()))+ .map_err(|error| error.throw(&cx)),+ )+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_rust_audio_buffer_acquire_contents(+ vm: &Vm,+ cell: *mut c_void,+) -> *const AudioBufferContents {+ let buffer: Ref<AudioBuffer> = unsafe { cell_from_abi(cell) };+ AudioBuffer::acquire_contents(buffer, vm).map_or(std::ptr::null(), Arc::into_raw)+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/mod.rsindex f10033ef65b..62bb0fe3200 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/mod.rs@@ -4,4 +4,5 @@* SPDX-License-Identifier: BSD-2-Clause*/+pub(crate) mod audio_buffer;pub(crate) mod periodic_wave;diff --git a/Libraries/LibWeb/WebAudio/AudioBuffer.cpp b/Libraries/LibWeb/WebAudio/AudioBuffer.cppindex 4d4d8a1d2fa..1845d905114 100644--- a/Libraries/LibWeb/WebAudio/AudioBuffer.cpp+++ b/Libraries/LibWeb/WebAudio/AudioBuffer.cpp@@ -1,338 +1,61 @@/** Copyright (c) 2024, Shannon Booth <[email protected]>* Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/NeverDestroyed.h>-#include <AK/NumericLimits.h>-#include <LibGC/Heap.h>-#include <LibGC/WeakInlines.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/Completion.h>-#include <LibJS/Runtime/ExternalMemory.h>-#include <LibJS/Runtime/Object.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/Realm.h>#include <LibJS/Runtime/TypedArray.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/WebAudio/AudioArray.h>#include <LibWeb/WebAudio/AudioBuffer.h>-#include <LibWeb/WebAudio/BaseAudioContext.h>#include <LibWeb/WebIDL/DOMException.h>namespace Web::WebAudio {-GC_DEFINE_ALLOCATOR(AudioBuffer);--// The ArrayBuffer is tracked next to the view because it can outlive it: script is free to keep `array.buffer` and-// drop the array. The buffer is what projects the channel's storage, so it is the one that decides how long that-// storage must stay put, and the one that has to be detached when the content is acquired.-struct AudioBufferChannelView {- GC::Weak<JS::Float32Array> view;- GC::Weak<JS::ArrayBuffer> array_buffer;-};--struct AudioBufferChannelDataCacheEntry {- GC::Weak<AudioBuffer> buffer;- WebIDL::UnsignedLong channel { 0 };- Vector<AudioBufferChannelView> views;-};--static Vector<AudioBufferChannelDataCacheEntry>& audio_buffer_channel_data_caches()-{- static NeverDestroyed<Vector<AudioBufferChannelDataCacheEntry>> caches;- return *caches;-}--static void prune_audio_buffer_channel_data_caches()-{- audio_buffer_channel_data_caches().remove_all_matching([](auto const& entry) {- return !entry.buffer;- });-}--static AudioBufferChannelDataCacheEntry& cache_for(AudioBuffer& buffer, WebIDL::UnsignedLong channel)-{- auto& caches = audio_buffer_channel_data_caches();- prune_audio_buffer_channel_data_caches();-- for (auto& entry : caches) {- if (entry.buffer.ptr() == GC::Ref { buffer } && entry.channel == channel)- return entry;- }-- caches.append({ buffer, channel, {} });- return caches.last();-}--static void prune_live_channel_views(Vector<AudioBufferChannelView>& live_channel_views)-{- live_channel_views.remove_all_matching([](auto const& entry) { return !entry.array_buffer; });-}--WebIDL::ExceptionOr<GC::Ref<AudioBuffer>> AudioBuffer::create_for_constructor(JS::Object& relevant_global_object, AudioBufferOptions const& options)-{- auto& vm = relevant_global_object.vm();-- // 1. If any of the values in options lie outside its nominal range, throw a NotSupportedError exception and abort the following steps.- TRY(BaseAudioContext::verify_audio_options_inside_nominal_range(options.number_of_channels, options.length, options.sample_rate));-- if (options.length > NumericLimits<i32>::max() / sizeof(float))- return vm.throw_completion<JS::RangeError>(JS::ErrorType::InvalidLength, "typed array");-- // 2. Let b be a new AudioBuffer object.- // 3. Respectively assign the values of the attributes numberOfChannels, length, sampleRate of the AudioBufferOptions passed in the- // constructor to the internal slots [[number of channels]], [[length]], [[sample rate]].- // 4. Set the internal slot [[internal data]] of this AudioBuffer to the result of calling CreateByteDataBlock([[length]] * [[number of channels]]).- return TRY_OR_THROW_OOM(vm, create(options.number_of_channels, options.length, options.sample_rate));+extern "C" {+bool web_rust_audio_buffer_create(JSVM*, u32 channels, u32 length, float sample_rate, void**);+float web_rust_audio_buffer_sample_rate(void*);+u32 web_rust_audio_buffer_length(void*);+u32 web_rust_audio_buffer_channel_count(void*);+bool web_rust_audio_buffer_channel(void*, u32 channel, Bytes*);+JSCompletion web_rust_audio_buffer_get_channel_data(JSVM*, void* realm, void* buffer, u32 channel);+void const* web_rust_audio_buffer_acquire_contents(JSVM*, void* buffer);}ErrorOr<GC::Ref<AudioBuffer>> AudioBuffer::create(WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate){- AudioBufferOptions options {};- options.number_of_channels = number_of_channels;- options.length = length;- options.sample_rate = sample_rate;-- auto buffer = GC::Heap::the().allocate<AudioBuffer>(options);-- auto channel_byte_length = static_cast<size_t>(options.length) * sizeof(float);- TRY(buffer->m_channels.try_ensure_capacity(options.number_of_channels));- for (WebIDL::UnsignedLong i = 0; i < options.number_of_channels; ++i)- buffer->m_channels.unchecked_append({ TRY(JS::DataBlock::OwnedBackingStore::create_zeroed(channel_byte_length)) });- GC::Heap::the().did_allocate_external_memory(buffer->external_memory_size());-- return buffer;-}--AudioBuffer::~AudioBuffer() = default;--// https://webaudio.github.io/web-audio-api/#acquire-the-content-RefPtr<Rendering::AudioBufferContents> AudioBuffer::acquire_contents()-{- // NB: m_contents is non-null exactly while the channel arrays are detached because step 4 below has not run yet.- // The snapshot then still holds the buffer's content and script has had no way to modify it, so it can be- // handed out again as-is. This is what makes a sequence of acquisitions with no intervening getChannelData(),- // e.g. one AudioBuffer played by many AudioBufferSourceNodes, free of allocations and copying.- // https://webaudio.github.io/web-audio-api/#audio-buffer-copying- if (m_contents)- return m_contents;-- // 1. If any of the AudioBuffer's ArrayBuffers are detached, return true, abort these steps, and return a- // zero-length channel data buffer to the invoker.- for (auto const& cache : audio_buffer_channel_data_caches()) {- if (cache.buffer.ptr() != GC::Ref { *this })- continue;- for (auto const& entry : cache.views) {- if (entry.array_buffer && entry.array_buffer->is_detached())- return nullptr;- }- }-- // 2. Detach all ArrayBuffers for arrays previously returned by getChannelData() on this AudioBuffer.- // 3. Retain the underlying [[internal data]] from those ArrayBuffers and return references to them to the invoker.- Vector<Vector<float>> channels;- channels.ensure_capacity(m_channels.size());- for (auto const& channel : m_channels) {- Vector<float> samples;- samples.resize(m_length);- ReadonlyBytes { channel.data.data(), channel.data.size() }.copy_to({ reinterpret_cast<u8*>(samples.data()), samples.size() * sizeof(float) });- channels.unchecked_append(move(samples));- }- for (auto& cache : audio_buffer_channel_data_caches()) {- if (cache.buffer.ptr() != GC::Ref { *this })- continue;- for (auto const& entry : cache.views) {- if (entry.array_buffer)- MUST(JS::detach_array_buffer(vm(), *entry.array_buffer));- }- }- m_contents = make_ref_counted<Rendering::AudioBufferContents>(move(channels), m_sample_rate);- GC::Heap::the().did_allocate_external_memory(m_channels.size() * m_length * sizeof(float));-- // 4. Attach ArrayBuffers containing copies of the data to the AudioBuffer, to be returned by the next call to- // getChannelData().- // NB: Performed lazily by attach_acquired_channels().-- return m_contents;-}--// https://webaudio.github.io/web-audio-api/#audio-buffer-copying-void AudioBuffer::attach_acquired_channels()-{- // The pending final step of acquiring this buffer's content: fresh arrays holding a copy of the acquired sample- // data are attached the first time script reaches for the channel data again. Whoever acquired the content keeps- // using the snapshot, so writes through the new arrays cannot change what is already playing.- if (!m_contents)- return;-- VERIFY(m_contents->channels.size() == m_channels.size());- for (size_t i = 0; i < m_channels.size(); ++i) {- auto const& samples = m_contents->channels[i];- auto& data = m_channels[i].data;- ReadonlyBytes { reinterpret_cast<u8 const*>(samples.data()), samples.size() * sizeof(float) }.copy_to({ data.data(), data.size() });- }-- m_contents = nullptr;-- // Every view of the storage was detached when the content was acquired, and the storage needs fresh views over it.- // So, drop the cached ones instead of handing a detached array back to the next caller.- for (auto& cache : audio_buffer_channel_data_caches()) {- if (cache.buffer.ptr() == GC::Ref { *this })- cache.views.clear();- }-}--// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-samplerate-float AudioBuffer::sample_rate() const-{- // The sample-rate for the PCM audio data in samples per second. This MUST return the value of [[sample rate]].- return m_sample_rate;+ void* buffer = nullptr;+ if (!web_rust_audio_buffer_create(JS::HostABI::vm_to_abi(JS::VM::the()), number_of_channels, length, sample_rate, &buffer))+ return Error::from_errno(ENOMEM);+ return GC::Ref { *static_cast<AudioBuffer*>(buffer) };}--// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-length-WebIDL::UnsignedLong AudioBuffer::length() const-{- // Length of the PCM audio data in sample-frames. This MUST return the value of [[length]].- return m_length;-}--// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-duration-double AudioBuffer::duration() const-{- // Duration of the PCM audio data in seconds.- // This is computed from the [[sample rate]] and the [[length]] of the AudioBuffer by performing a division between the [[length]] and the [[sample rate]].- return m_length / static_cast<double>(m_sample_rate);-}--// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-numberofchannels-WebIDL::UnsignedLong AudioBuffer::number_of_channels() const-{- // The number of discrete audio channels. This MUST return the value of [[number of channels]].- return m_channels.size();-}-+float AudioBuffer::sample_rate() const { return web_rust_audio_buffer_sample_rate(const_cast<AudioBuffer*>(this)); }+u32 AudioBuffer::length() const { return web_rust_audio_buffer_length(const_cast<AudioBuffer*>(this)); }+u32 AudioBuffer::number_of_channels() const { return web_rust_audio_buffer_channel_count(const_cast<AudioBuffer*>(this)); }+double AudioBuffer::duration() const { return length() / static_cast<double>(sample_rate()); }WebIDL::ExceptionOr<Bytes> AudioBuffer::channel_data(WebIDL::UnsignedLong channel){- if (channel >= m_channels.size())+ Bytes data;+ if (!web_rust_audio_buffer_channel(this, channel, &data))return WebIDL::IndexSizeError::create("Channel index is out of range"_utf16);-- auto& data = m_channels[channel].data;- return Bytes { data.data(), data.size() };+ return data;}--// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-getchanneldataWebIDL::ExceptionOr<GC::Ref<JS::Float32Array>> AudioBuffer::get_channel_data(JS::Object& relevant_global_object, WebIDL::UnsignedLong channel){- if (channel >= m_channels.size())- return WebIDL::IndexSizeError::create("Channel index is out of range"_utf16);-- // This is where the deferred final step of acquiring the content runs: script is reaching for the channel data- // again, so the copies of the acquired samples become this buffer's internal data before anything reads them.- attach_acquired_channels();-- auto& relevant_global_realm = HTML::relevant_realm(relevant_global_object);- auto& cache = cache_for(*this, channel);-- prune_live_channel_views(cache.views);- for (auto& entry : cache.views) {- if (entry.view && &entry.view->shape().realm() == &relevant_global_realm)- return GC::Ref { *entry.view };- }-- // The ArrayBuffer projects this AudioBuffer's channel storage instead of owning a copy of it, and names the- // AudioBuffer as the owner of that storage. The GC then traces the AudioBuffer through the ArrayBuffer, so the- // samples cannot be freed while script still holds a view of them.- auto& channel_storage = m_channels[channel].data;- JS::DataBlock::ExternalPrimitiveStorage storage { GC::Ref<GC::Cell> { *this }, channel_storage.handle(), channel_storage.size() };- auto array_buffer = JS::ArrayBuffer::create(relevant_global_realm, JS::DataBlock { move(storage), JS::DataBlock::Shared::No });- auto view = JS::Float32Array::create(relevant_global_realm, length(), array_buffer);- TRY_OR_THROW_OOM(relevant_global_object.vm(), cache.views.try_append({ view, array_buffer }));- return view;+ auto& realm = HTML::relevant_realm(relevant_global_object);+ auto result = TRY(JS::HostABI::completion_from_abi<JS::Value>(web_rust_audio_buffer_get_channel_data(JS::HostABI::vm_to_abi(realm.vm()), &realm, this, channel)));+ return GC::Ref { static_cast<JS::Float32Array&>(result.as_object()) };}--// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-copyfromchannel-WebIDL::ExceptionOr<void> AudioBuffer::copy_from_channel(GC::Root<JS::Float32Array> const& destination, WebIDL::UnsignedLong channel_number, WebIDL::UnsignedLong buffer_offset) const-{- // The copyFromChannel() method copies the samples from the specified channel of the AudioBuffer to the destination array.- //- // Let buffer be the AudioBuffer with Nb frames, let Nf be the number of elements in the destination array, and k be the value- // of bufferOffset. Then the number of frames copied from buffer to destination is max(0,min(Nb−k,Nf)). If this is less than Nf,- // then the remaining elements of destination are not modified.- auto& vm = JS::VM::the();-- if (destination->viewed_array_buffer()->is_shared_array_buffer())- return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer, "Float32Array");- if (destination->viewed_array_buffer()->is_detached())- return {};-- if (channel_number >= m_channels.size())- return WebIDL::IndexSizeError::create("Channel index is out of range"_utf16);-- auto& channel = m_channels[channel_number];- ReadonlySpan<float> channel_data { reinterpret_cast<float const*>(channel.data.data()), m_length };- auto channel_length = channel_data.size();- if (buffer_offset >= channel_length)- return {};-- auto destination_length = float32_array_length(*destination);- auto count = min(destination_length, channel_length - buffer_offset);- auto destination_bytes = destination->viewed_array_buffer();- channel_data.slice(buffer_offset, count).copy_to({ reinterpret_cast<float*>(destination_bytes->data_at(destination->byte_offset())), count });-- return {};-}--// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-copytochannel-WebIDL::ExceptionOr<void> AudioBuffer::copy_to_channel(GC::Root<JS::Float32Array> const& source, WebIDL::UnsignedLong channel_number, WebIDL::UnsignedLong buffer_offset)-{- // The copyToChannel() method copies the samples to the specified channel of the AudioBuffer from the source array.- //- // A UnknownError may be thrown if source cannot be copied to the buffer.- //- // Let buffer be the AudioBuffer with Nb frames, let Nf be the number of elements in the source array, and k be the value- // of bufferOffset. Then the number of frames copied from source to the buffer is max(0,min(Nb−k,Nf)). If this is less than Nf,- // then the remaining elements of buffer are not modified.- auto& vm = JS::VM::the();-- if (source->viewed_array_buffer()->is_shared_array_buffer())- return vm.throw_completion<JS::TypeError>(JS::ErrorType::SharedArrayBuffer, "Float32Array");- if (source->viewed_array_buffer()->is_detached())- return {};-- if (channel_number >= m_channels.size())- return WebIDL::IndexSizeError::create("Channel index is out of range"_utf16);-- attach_acquired_channels();-- auto& channel = m_channels[channel_number];- Span<float> channel_data { reinterpret_cast<float*>(channel.data.data()), m_length };- auto channel_length = channel_data.size();- if (buffer_offset >= channel_length)- return {};-- auto source_length = float32_array_length(*source);- auto count = min(source_length, channel_length - buffer_offset);- auto source_bytes = source->viewed_array_buffer();- source_bytes->with_readonly_bytes(source->byte_offset(), count * sizeof(float), [&](ReadonlyBytes bytes) {- bytes.copy_to({ reinterpret_cast<u8*>(channel_data.data() + buffer_offset), bytes.size() });- });-- return {};-}--AudioBuffer::AudioBuffer(AudioBufferOptions const& options)- : m_length(options.length)- , m_sample_rate(options.sample_rate)-{-}--size_t AudioBuffer::external_memory_size() const+RefPtr<Rendering::AudioBufferContents> AudioBuffer::acquire_contents(){- auto size = JS::saturating_add_external_memory_size(Base::external_memory_size(), JS::vector_external_memory_size(m_channels));- for (auto const& channel : m_channels)- size = JS::saturating_add_external_memory_size(size, channel.data.capacity());- return size;+ auto* contents = web_rust_audio_buffer_acquire_contents(JS::HostABI::vm_to_abi(JS::VM::the()), this);+ if (!contents)+ return nullptr;+ return make_ref_counted<Rendering::AudioBufferContents>(contents, number_of_channels(), sample_rate());}}diff --git a/Libraries/LibWeb/WebAudio/AudioBuffer.h b/Libraries/LibWeb/WebAudio/AudioBuffer.hindex 5173d4c511f..d214334aa80 100644--- a/Libraries/LibWeb/WebAudio/AudioBuffer.h+++ b/Libraries/LibWeb/WebAudio/AudioBuffer.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*/@@ -8,73 +9,27 @@#include <AK/Error.h>#include <AK/Span.h>-#include <AK/Vector.h>#include <LibJS/Forward.h>-#include <LibJS/Runtime/ArrayBuffer.h>#include <LibWeb/Bindings/AudioBuffer.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/WebAudio/Rendering/AudioData.h>-#include <LibWeb/WebIDL/Buffers.h>#include <LibWeb/WebIDL/ExceptionOr.h>#include <LibWebCommon/WebIDL/Types.h>namespace Web::WebAudio {-using AudioBufferOptions = Bindings::AudioBufferOptions;--// https://webaudio.github.io/web-audio-api/#AudioBuffer-class AudioBuffer final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(AudioBuffer, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(AudioBuffer);+class AudioBuffer final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(AudioBuffer, audio_buffer)public:- static WebIDL::ExceptionOr<GC::Ref<AudioBuffer>> create_for_constructor(JS::Object&, AudioBufferOptions const&);static ErrorOr<GC::Ref<AudioBuffer>> create(WebIDL::UnsignedLong number_of_channels, WebIDL::UnsignedLong length, float sample_rate);-- virtual ~AudioBuffer() override;-float sample_rate() const;WebIDL::UnsignedLong length() const;double duration() const;WebIDL::UnsignedLong number_of_channels() const;WebIDL::ExceptionOr<Bytes> channel_data(WebIDL::UnsignedLong channel);WebIDL::ExceptionOr<GC::Ref<JS::Float32Array>> get_channel_data(JS::Object& relevant_global_object, WebIDL::UnsignedLong channel);- WebIDL::ExceptionOr<void> copy_from_channel(GC::Root<JS::Float32Array> const&, WebIDL::UnsignedLong channel_number, WebIDL::UnsignedLong buffer_offset = 0) const;- WebIDL::ExceptionOr<void> copy_to_channel(GC::Root<JS::Float32Array> const&, WebIDL::UnsignedLong channel_number, WebIDL::UnsignedLong buffer_offset = 0);-- // https://webaudio.github.io/web-audio-api/#acquire-the-contentRefPtr<Rendering::AudioBufferContents> acquire_contents();- void attach_acquired_channels();--private:- // The sample data lives in the primitive storage cage, so an out-of-bounds access through a channel's Float32Array- // is masked back into the cage instead of reaching memory outside it. The AudioBuffer owns the storage, and the- // ArrayBuffer handed to script holds an owner edge back to the AudioBuffer, so the storage outlives every view.- struct Channel {- JS::DataBlock::OwnedBackingStore data;- };-- explicit AudioBuffer(AudioBufferOptions const&);-- virtual size_t external_memory_size() const override;-- // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-number-of-channels-slot- // The number of audio channels for this AudioBuffer, which is an unsigned long.- //- // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-internal-data-slot- // A data block holding the audio sample data.- Vector<Channel> m_channels; // [[internal data]] / [[number_of_channels]]-- // https://webaudio.github.io/web-audio-api/#audio-buffer-copying- RefPtr<Rendering::AudioBufferContents> m_contents;-- // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-length-slot- // The length of each channel of this AudioBuffer, which is an unsigned long.- WebIDL::UnsignedLong m_length {}; // [[length]]-- // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-sample-rate-slot- // The sample-rate, in Hz, of this AudioBuffer, a float.- float m_sample_rate {}; // [[sample rate]]};}diff --git a/Libraries/LibWeb/WebAudio/AudioBuffer.idl b/Libraries/LibWeb/WebAudio/AudioBuffer.idlindex 04c47e5010e..98d2cbd1be3 100644--- a/Libraries/LibWeb/WebAudio/AudioBuffer.idl+++ b/Libraries/LibWeb/WebAudio/AudioBuffer.idl@@ -6,7 +6,7 @@ dictionary AudioBufferOptions {};// https://webaudio.github.io/web-audio-api/#AudioBuffer-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface AudioBuffer {constructor (AudioBufferOptions options);readonly attribute float sampleRate;diff --git a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp b/Libraries/LibWeb/WebAudio/BaseAudioContext.cppindex 81351be77f9..f5a88a96bca 100644--- a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp+++ b/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp@@ -2,12 +2,14 @@* Copyright (c) 2023, Luke Wilde <[email protected]>* Copyright (c) 2024, Shannon Booth <[email protected]>* Copyright (c) 2024, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/#include <AK/NumericLimits.h>#include <LibGC/Heap.h>+#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/ArrayBuffer.h>#include <LibJS/Runtime/VM.h>#include <LibMediaClient/Client.h>@@ -46,6 +48,16 @@namespace Web::WebAudio {+extern "C" JSCompletion web_audio_verify_buffer_options(void* realm, u32 channels, u32 length, float sample_rate);+JSCompletion web_audio_verify_buffer_options(void* realm, u32 channels, u32 length, float sample_rate)+{+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto result = BaseAudioContext::verify_audio_options_inside_nominal_range(channels, length, sample_rate);+ if (result.is_exception())+ return JS::HostABI::throw_completion_to_abi(WebIDL::exception_to_throw_completion(js_realm.vm(), js_realm, result.exception()).value());+ return JS::HostABI::normal_completion_to_abi(JS::HostABI::value_to_abi(JS::js_undefined()));+}+static JS::Value audio_buffer(JS::Realm& realm, GC::Ptr<AudioBuffer> buffer){if (!buffer)diff --git a/Libraries/LibWeb/WebAudio/OfflineAudioCompletionEvent.idl b/Libraries/LibWeb/WebAudio/OfflineAudioCompletionEvent.idlindex 0143b024013..00f82cacd28 100644--- a/Libraries/LibWeb/WebAudio/OfflineAudioCompletionEvent.idl+++ b/Libraries/LibWeb/WebAudio/OfflineAudioCompletionEvent.idl@@ -2,7 +2,7 @@[Exposed=Window]interface OfflineAudioCompletionEvent : Event {constructor(DOMString type, OfflineAudioCompletionEventInit eventInitDict);- [DirectGetter] readonly attribute AudioBuffer renderedBuffer;+ readonly attribute AudioBuffer renderedBuffer;};// https://webaudio.github.io/web-audio-api/#OfflineAudioCompletionEventInitdiff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioData.cpp b/Libraries/LibWeb/WebAudio/Rendering/AudioData.cppindex 0c9200bf4f4..633014dcf3a 100644--- a/Libraries/LibWeb/WebAudio/Rendering/AudioData.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioData.cpp@@ -20,6 +20,14 @@ AudioBufferContents::AudioBufferContents(Vector<Vector<float>> samples, float rafor (size_t i = 0; i < samples.size(); ++i)RustFFI::web_audio_buffer_contents_channel(m_data, i, &channels[i]);}+AudioBufferContents::AudioBufferContents(void const* data, size_t channel_count, float rate)+ : sample_rate(rate)+ , m_data(data)+{+ channels.resize(channel_count);+ for (size_t i = 0; i < channel_count; ++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){diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioData.h b/Libraries/LibWeb/WebAudio/Rendering/AudioData.hindex 2244f00d436..6924bfcef04 100644--- a/Libraries/LibWeb/WebAudio/Rendering/AudioData.h+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioData.h@@ -13,6 +13,7 @@ namespace Web::WebAudio::Rendering {struct AudioBufferContents : public AtomicRefCounted<AudioBufferContents> {AudioBufferContents(Vector<Vector<float>> channels, float sample_rate);+ AudioBufferContents(void const* data, size_t channel_count, 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); }