Truly independent web browser
LibWeb: Run AudioWorklet processors from the Rust AudioWorkletNode
Shannon Boothdb426d13da3e
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_worklet_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_worklet_node.rsindex 9f200005b15..73b0e1d9a65 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_worklet_node.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_worklet_node.rs@@ -10,20 +10,23 @@ use std::cell::Cell;use std::cell::RefCell;use std::ffi::c_void;use std::ptr::NonNull;+use std::rc::Rc;use std::sync::Arc;use ak::Utf16String;use libjs_rust::api::{- Array, EmbedderClass, EmbedderValue, FunctionObject, Object, PropertyKey, RawNativeFunctionResult, Value, Vm,- construct,+ Array, EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, FunctionObject, GcWeak, MarkedVec, Object,+ PropertyKey, RawNativeFunctionResult, TypedArrayBase, TypedArrayKind, Value, Vm, call, construct,+ create_typed_array,};use libjs_rust::api::{Gc, Realm, Trace};-use libweb_rust::web_audio::control_message::FfiSharedCppObject;-use libweb_rust::web_audio::rendering::audio_worklet_pipe::{AudioWorkletPipe, WorkletPipeConfig, WorkletPipeState};+use libweb_rust::web_audio::rendering::audio_worklet_pipe::{+ AudioWorkletPipe, AudioWorkletPipeClient, Config, WorkletPipeState, ring_sizing_for_device_latency,+};use libweb_rust::web_audio::rendering::audio_worklet_render_node::create_audio_worklet_render_node;-use libweb_rust::web_audio::rendering::node_message::SharedCppObject;use libweb_rust::web_audio::rendering::render_node::RenderAudioParam;+use super::audio_array::{float32_array_length, overwrite_float32_array};use super::audio_node::{AnyAudioNode, AudioNode, AudioNodeDefaultOptions, AudioNodeOptions, ChannelCountMode, ChannelInterpretation,};@@ -32,8 +35,8 @@ use super::audio_param_map::AudioParamMap;use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};use crate::bindings::cpp_cell::CppCell;use crate::bindings::event_target::{CppEventTarget, GetTheParent};-use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};-use crate::bindings::interface::{cell_from_abi, cell_into_abi, with_temporary_execution_context_and_callbacks};+use crate::bindings::interface::{Inherits, Ref, Wrappable, Wrapped, allocate};+use crate::bindings::interface::{cell_into_abi, with_temporary_execution_context_and_callbacks};use crate::bindings::promise::{TaskSource, queue_a_global_task};use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::html::message_port::MessagePort;@@ -49,13 +52,13 @@ pub(crate) struct AudioWorkletNode {number_of_inputs: u32,number_of_outputs: u32,parameter_map: Ref<AudioParamMap>,+ parameter_names: Vec<Utf16String>, // descriptor order; keys for the `parameters` argumentport: Ref<MessagePort>,+ scope: CppCell,processor: Cell<Option<Gc<Object>>>,processor_errored: Cell<bool>,#[gc(untraced)]pipe: RefCell<Option<Arc<AudioWorkletPipe>>>,- #[gc(untraced)]- pipe_service: RefCell<Option<SharedCppObject>>,}impl Inherits<AudioNode> for AudioWorkletNode {@@ -72,10 +75,8 @@ impl Wrappable for AudioWorkletNode {const FINALIZES: bool = true;fn finalize(node: Ref<Self>) {- if let Some(service) = &*node.pipe_service.borrow() {- unsafe { web_audio_worklet_clear_pump(service.pointer) };- }if let Some(pipe) = &*node.pipe.borrow() {+ pipe.set_client(None);pipe.set_state(WorkletPipeState::ShutDown);}node.node.finalize_node();@@ -135,28 +136,29 @@ unsafe extern "C" {error_realm: *mut c_void,options: *mut c_void,) -> RawNativeFunctionResult;- fn web_audio_worklet_create_pipe(- config: WorkletPipeConfig<'_>,- sample_rate: f32,- native_pipe: *mut *const c_void,- ) -> FfiSharedCppObject;- fn web_audio_worklet_set_pump(pipe: *mut c_void, scope: *mut c_void, node_id: u64);- fn web_audio_worklet_clear_pump(pipe: *mut c_void);fn web_audio_worklet_processor_constructor(scope: *mut c_void, name: usize) -> *mut c_void;fn web_audio_worklet_set_pending_port(scope: *mut c_void, port: *mut c_void);fn web_audio_worklet_clear_pending_data(scope: *mut c_void);- fn web_audio_worklet_add_processor_slot(- scope: *mut c_void,- node_id: u64,- processor: *mut c_void,- port: *mut c_void,- node: *mut c_void,- pipe: *mut c_void,- names: ak::Span<'_, usize>,- );+ fn web_audio_worklet_set_current_frame(scope: *mut c_void, current_frame: u64);fn web_audio_worklet_queue_processor_error(node: *mut c_void, target: *mut c_void, global: *mut c_void, error: u64);}+struct PumpClient {+ vm: NonNull<Vm>,++ // weak: the slot must not keep the node alive (see keep-alive notes)+ node: GcWeak<EmbedderCell<Wrapped<AudioWorkletNode>>>,+}++impl AudioWorkletPipeClient for PumpClient {+ fn pump(&self) {+ if let Some(node) = self.node.get() {+ // SAFETY: The VM of the control thread outlives its audio nodes.+ node.pump(unsafe { self.vm.as_ref() });+ }+ }+}+impl AudioWorkletNode {fn this(&self) -> Ref<Self> {let AnyAudioNode::AudioWorkletNode(node) = self.node.this() else {@@ -253,11 +255,12 @@ impl AudioWorkletNode {number_of_inputs: options.number_of_inputs,number_of_outputs: options.number_of_outputs,parameter_map,+ parameter_names: descriptors.iter().map(|descriptor| descriptor.name.clone()).collect(),port: node_port,+ scope: scope.clone(),processor: Cell::new(None),processor_errored: Cell::new(false),pipe: RefCell::new(None),- pipe_service: RefCell::new(None),});node.node.set_this(AnyAudioNode::AudioWorkletNode(node));node.node.event_target().set_owner(node);@@ -415,37 +418,32 @@ impl AudioWorkletNode {for descriptor in &descriptors {param_is_a_rate.push(descriptor.automation_rate == AutomationRate::ARate);}- let sizing = libweb_rust::web_audio::rendering::audio_worklet_pipe::ring_sizing_for_device_latency(+ let sizing = ring_sizing_for_device_latency(100,context.sample_rate_value(),BaseAudioContext::RENDER_QUANTUM_SIZE as usize,);- let config = WorkletPipeConfig {+ let pipe = AudioWorkletPipe::new(Config {quantum_size: BaseAudioContext::RENDER_QUANTUM_SIZE as usize,- input_count: options.number_of_inputs,- output_count: options.number_of_outputs,- input_channel_capacity: ak::Span::new(&input_channel_capacity),- output_channel_capacity: ak::Span::new(&output_channel_capacity),+ input_count: options.number_of_inputs as usize,+ output_count: options.number_of_outputs as usize,+ input_channel_capacity,+ output_channel_capacity: output_channel_capacity.clone(),output_channel_count_matches_input,- param_count: descriptors.len() as u32,- param_is_a_rate: ak::Span::new(¶m_is_a_rate),+ param_count: descriptors.len(),+ param_is_a_rate,ring_capacity: sizing.ring_capacity,prime_level: sizing.prime_level,- };- let mut native_pipe = std::ptr::null();- let service =- unsafe { web_audio_worklet_create_pipe(config, context.sample_rate_value(), &raw mut native_pipe) };- let native_pipe = native_pipe.cast::<AudioWorkletPipe>();- unsafe { Arc::increment_strong_count(native_pipe) };- let pipe = unsafe { Arc::from_raw(native_pipe) };+ });unsafe { pipe.prime_outputs_with_silence(sizing.prime_level) };*node.pipe.borrow_mut() = Some(Arc::clone(&pipe));- *node.pipe_service.borrow_mut() = Some(SharedCppObject {- pointer: service.pointer,- retain: service.retain,- release: service.release,- });- unsafe { web_audio_worklet_set_pump(service.pointer, scope.as_ptr(), node.node.node_id()) };+ pipe.set_client(Some(Rc::new(PumpClient {+ vm: NonNull::from(vm),+ node: GcWeak::new(vm.heap(), node),+ })));++ // Create the render mirror. Channel configuration rides in the constructor (the graph drops+ // SetChannelConfig messages that precede AddNode).let render_params: Vec<Arc<RenderAudioParam>> = parameter_map.values(vm).values()@@ -533,36 +531,242 @@ impl AudioWorkletNode {}};self.processor.set(Some(processor));- let worklet = self.node.context_value().audio_worklet_cell(vm);- let mut names = Vec::<Utf16String>::new();- unsafe extern "C" fn append(context: *mut c_void, name: usize, _: f32, _: f32, _: f32, _: AutomationRate) {- unsafe { &mut *context.cast::<Vec<Utf16String>>() }- .push(unsafe { ak::Utf16FlyString::from_raw_borrowed(name) }.into());- }- unsafe {- web_audio_worklet_find_definition(- worklet.as_ptr(),- self.name.raw_identity(),- (&raw mut names).cast(),- append,- )- };- let raw_names: Vec<usize> = names.iter().map(Utf16String::raw_identity).collect();- unsafe {- web_audio_worklet_add_processor_slot(- scope.as_ptr(),- self.node.node_id(),- processor.as_ptr().cast(),- cell_into_abi(processor_port),- cell_into_abi(self.this()),- self.pipe_service.borrow().as_ref().unwrap().pointer,- ak::Span::new(&raw_names),- );- };+ self.node+ .context_value()+ .add_audio_worklet_pipe(Arc::clone(self.pipe.borrow().as_ref().unwrap()));++ // 4. Enable the processor-side port's message queue: pending messages posted since node construction+ // are now delivered, after the constructor had its chance to register listeners.MessagePort::enable(processor_port, vm);});}+ // Drains one node's input ring, runs its processor's process() per quantum, and pushes the+ // results back. Scheduled (coalesced) by the render thread via the pipe's wakeup callback.+ fn pump(&self, vm: &Vm) {+ let pipe = Arc::clone(self.pipe.borrow().as_ref().expect("a pumped node has a pipe"));++ // Every invocation consumes its scheduled wakeup, including stale callbacks for removed slots.+ pipe.clear_wakeup_flag();+ let Some(processor) = self.processor.get() else {+ return;+ };+ if pipe.state() == WorkletPipeState::ShutDown || self.processor_errored.get() {+ return;+ }++ let realm: Gc<Realm> = unsafe {+ Gc::from_non_null(NonNull::new(web_audio_worklet_scope_realm(self.scope.as_ptr()).cast()).unwrap())+ };++ // Keep one execution context for the batch so its microtask checkpoint runs after all available quanta.+ with_temporary_execution_context_and_callbacks(realm, || {+ let config = &pipe.config;+ loop {+ if pipe.output_occupancy() == config.ring_capacity {+ break;+ }+ let mut processed_one = false;+ let mut pump_failed = false;+ let mut output_full = false;++ let _ = unsafe {+ pipe.try_read_input(|input_slot| {+ processed_one = true;++ // https://webaudio.github.io/web-audio-api/#rendering-loop — currentFrame/currentTime+ // reflect the block being processed.+ web_audio_worklet_set_current_frame(self.scope.as_ptr(), input_slot.start_frame());++ // The processor may detach channel arrays, so they cannot be reused without checking their buffers.+ // FIXME: Reuse arrays that remain attached.+ let build_channel_array =+ |channel_count: usize, fill_channel: &dyn Fn(usize, &TypedArrayBase)| {+ let channels = Array::create(vm, realm, channel_count as u64, None)+ .expect("a channel array is created");+ for channel in 0..channel_count {+ let float32_array = create_typed_array(+ vm,+ realm,+ TypedArrayKind::Float32Array,+ config.quantum_size,+ )+ .expect("a channel's Float32Array is created");+ fill_channel(channel, &float32_array);+ channels+ .create_data_property(+ vm,+ &PropertyKey::from(channel as u32),+ Value::from_object(float32_array),+ None,+ None,+ )+ .expect("a new array accepts a property");+ }+ channels+ };++ let inputs = Array::create(vm, realm, config.input_count as u64, None)+ .expect("the inputs array is created");+ for input in 0..config.input_count {+ let channels = build_channel_array(+ input_slot.actual_channel_count(input) as usize,+ &|channel, float32_array| {+ overwrite_float32_array(float32_array, input_slot.input_channel(input, channel));+ },+ );+ inputs+ .create_data_property(+ vm,+ &PropertyKey::from(input as u32),+ Value::from_object(channels),+ None,+ None,+ )+ .expect("a new array accepts a property");+ }++ let output_channel_count = |output: usize| -> usize {+ if config.output_channel_count_matches_input {+ return (input_slot.actual_channel_count(0) as usize).max(1);+ }+ config.output_channel_capacity[output] as usize+ };+ let outputs = Array::create(vm, realm, config.output_count as u64, None)+ .expect("the outputs array is created");+ let output_channel_arrays = MarkedVec::with_capacity(vm, config.output_count);+ for output in 0..config.output_count {+ let channels = build_channel_array(output_channel_count(output), &|_, _| {});+ output_channel_arrays.push(channels);+ outputs+ .create_data_property(+ vm,+ &PropertyKey::from(output as u32),+ Value::from_object(channels),+ None,+ None,+ )+ .expect("a new array accepts a property");+ }++ let parameters = Object::create(vm, realm, Some(realm.intrinsics().object_prototype(vm)));+ for param_index in 0..config.param_count {+ let block = input_slot.param_block(param_index);+ let float32_array =+ create_typed_array(vm, realm, TypedArrayKind::Float32Array, block.len())+ .expect("a parameter's Float32Array is created");+ overwrite_float32_array(&float32_array, block);+ parameters+ .create_data_property(+ vm,+ &PropertyKey::from_utf16_string(&self.parameter_names[param_index]),+ Value::from_object(float32_array),+ None,+ None,+ )+ .expect("a new parameters object accepts a property");+ }++ // Look up process on the instance each call (spec); a non-callable value fails the node.+ let process_value = match processor.get(vm, &PropertyKey::from_utf8("process")) {+ Ok(value) if value.is_function() => value,+ Ok(_) => {+ pump_failed = true;+ let error = vm+ .throw_completion_with_message::<()>(+ ErrorKind::TypeError,+ "AudioWorkletProcessor.process must be a function".to_string(),+ )+ .unwrap_err();+ self.fire_processor_error(error.value());+ return;+ }+ Err(error) => {+ pump_failed = true;+ self.fire_processor_error(error.value());+ return;+ }+ };++ let process_arguments = [+ Value::from_object(inputs),+ Value::from_object(outputs),+ Value::from_object(parameters),+ ];+ let result = match call(vm, process_value, Value::from_object(processor), &process_arguments) {+ Ok(result) => result,+ Err(error) => {+ pump_failed = true;+ self.fire_processor_error(error.value());+ return;+ }+ };++ if pipe.state() == WorkletPipeState::ShutDown {+ return;+ }++ let processor_active = result.to_boolean();++ // Push the processed quantum back; read outputs defensively (detached → silence).+ let pushed = pipe.try_write_output(|output_slot| {+ output_slot.set_start_frame(input_slot.start_frame());+ output_slot.set_processor_active(processor_active);+ for output in 0..config.output_count {+ let channel_count = output_channel_count(output);+ output_slot.set_actual_channel_count(output, channel_count as u32);+ let channels = output_channel_arrays.get(output).unwrap();+ for channel in 0..channel_count {+ let destination = output_slot.output_channel(output, channel);+ let channel_value = channels+ .get(vm, &PropertyKey::from(channel as u32))+ .expect("a channel array's element is a data property");+ let float32_array = channel_value+ .is_object()+ .then(|| channel_value.as_object().downcast::<TypedArrayBase>())+ .flatten()+ .filter(|array| array.kind() == TypedArrayKind::Float32Array);+ let Some(float32_array) = float32_array.filter(|array| {+ !array.viewed_array_buffer().is_detached()+ && float32_array_length(array) >= config.quantum_size+ }) else {+ destination.fill(0.);+ continue;+ };+ let bytes = ak::slice_from_raw_parts_mut(+ destination.as_mut_ptr().cast::<u8>(),+ size_of_val(destination),+ );+ float32_array+ .viewed_array_buffer()+ .copy_to(float32_array.byte_offset(), bytes);+ }+ }+ });+ if !pushed {+ output_full = true;+ }+ })+ };++ if pump_failed {+ self.processor_errored.set(true);+ pipe.set_state(WorkletPipeState::Failed);+ return;+ }+ if pipe.state() == WorkletPipeState::ShutDown {+ return;+ }+ if output_full {+ break;+ }+ if !processed_one {+ break;+ }+ }+ });+ }+pub(crate) fn fire_processor_error(&self, error: Value) {// https://webaudio.github.io/web-audio-api/#dom-audioworkletnode-onprocessorerror// "...the processor will queue a task to fire an event named processorerror using ErrorEvent at the@@ -593,9 +797,3 @@ impl AudioWorkletNode {self.number_of_outputs}}--#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_rust_audio_worklet_node_fire_error(cell: *mut c_void, error: u64) {- let node: Ref<AudioWorkletNode> = unsafe { cell_from_abi(cell) };- node.fire_processor_error(unsafe { Value::from_raw(error) });-}diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rsindex 626f7d9c0ae..8b238024355 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs@@ -24,6 +24,7 @@ use libjs_rust::api::{};use libweb_rust::web_audio::control_message::ControlMessage;use libweb_rust::web_audio::control_message_queue::ControlMessageQueue;+use libweb_rust::web_audio::rendering::audio_worklet_pipe::{AudioWorkletPipe, WorkletPipeState};#[cfg(web_idl_bindings)]use super::analyser_node::{AnalyserNode, AnalyserOptions};@@ -107,6 +108,9 @@ pub(crate) struct BaseAudioContext {control_message_queue: Arc<ControlMessageQueue>,playing_sources: GcRefCell<Vec<(u64, AnyAudioNode)>>,script_processor_nodes: RefCell<Vec<GcWeak<EmbedderCell<Wrapped<ScriptProcessorNode>>>>>,+ audio_worklet_pipes: RefCell<Vec<Arc<AudioWorkletPipe>>>,++ // Kept alive only while they can still produce audio; see visit_edges().media_stream_sources: RefCell<Vec<GcWeak<EmbedderCell<Wrapped<MediaStreamAudioSourceNode>>>>>,this: Cell<Option<AnyBaseAudioContext>>,}@@ -178,7 +182,6 @@ unsafe extern "C" {fn web_audio_context_document_is_fully_active(global: *mut c_void) -> bool;fn web_audio_context_navigable_is_destroyed(global: *mut c_void) -> bool;fn web_audio_context_get_worklet(cell: *mut c_void) -> *mut c_void;- fn web_audio_context_shutdown_worklet(worklet: *mut c_void);fn web_audio_context_wrap_worklet(realm: *mut c_void, worklet: *mut c_void) -> *mut c_void;}@@ -216,6 +219,7 @@ impl BaseAudioContext {control_message_queue: Arc::new(ControlMessageQueue::default()),playing_sources: GcRefCell::new(Vec::new()),script_processor_nodes: RefCell::new(Vec::new()),+ audio_worklet_pipes: RefCell::new(Vec::new()),media_stream_sources: RefCell::new(Vec::new()),this: Cell::new(None),}@@ -401,9 +405,18 @@ impl BaseAudioContext {Ok(unsafe { CppInterface::from_wrapper(Gc::<Object>::from_non_null(NonNull::new(wrapper.cast()).unwrap())) })}+ pub(crate) fn add_audio_worklet_pipe(&self, pipe: Arc<AudioWorkletPipe>) {+ let mut pipes = self.audio_worklet_pipes.borrow_mut();+ pipes.retain(|pipe| pipe.state() != WorkletPipeState::ShutDown);+ pipes.push(pipe);+ }++ // Marks every worklet node's pipe shut down and drops the pump slots; called when the context+ // closes or its document stops being fully active.pub(crate) fn shutdown_audio_worklet(&self) {- if let Some(worklet) = &*self.audio_worklet.borrow() {- unsafe { web_audio_context_shutdown_worklet(worklet.as_ptr()) };+ for pipe in self.audio_worklet_pipes.take() {+ pipe.set_client(None);+ pipe.set_state(WorkletPipeState::ShutDown);}}diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 3df8d8cec2a..9567e6fe818 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -934,7 +934,6 @@ set(SOURCESWebAudio/MediaElementAudioSourceNode.cppWebAudio/MediaStreamAudioDestinationNode.cppWebAudio/MediaStreamAudioSourceNode.cpp- WebAudio/Rendering/AudioWorkletPipe.cppWebDriver/Actions.cppWebDriver/BiDi/BiDi.cppWebDriver/BiDi/BrowsingContext.cppdiff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rsindex 053581385cf..f54d93a68e9 100644--- a/Libraries/LibWeb/Rust/build.rs+++ b/Libraries/LibWeb/Rust/build.rs@@ -2469,12 +2469,7 @@ fn main() -> Result<(), Box<dyn Error>> {let mut web_audio_config = base_config.clone();web_audio_config.namespaces = Some(vec!["Web".into(), "WebAudio".into(), "RustFFI".into()]);- for name in [- "NodeHandle",- "ControlMessageQueue",- "AudioWorkletPipe",- "RealtimeAudioRenderer",- ] {+ for name in ["NodeHandle", "ControlMessageQueue", "RealtimeAudioRenderer"] {web_audio_config.export.rename.insert(name.into(), "void".into());web_audio_config.export.exclude.push(name.into());}@@ -2493,7 +2488,6 @@ fn main() -> Result<(), Box<dyn Error>> {manifest_dir.join("src/web_audio/rendering/audio_frame_ring.rs"),manifest_dir.join("src/web_audio/rendering/media_stream_destination_render_node.rs"),manifest_dir.join("src/web_audio/rendering/pipe_callbacks.rs"),- manifest_dir.join("src/web_audio/rendering/audio_worklet_pipe.rs"),manifest_dir.join("src/web_audio/rendering/realtime_audio_renderer.rs"),manifest_dir.join("src/web_audio/control_message.rs"),manifest_dir.join("src/web_audio/control_thread.rs"),diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe.rsindex 6fb287e13e4..24c95333edf 100644--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe.rs+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe.rs@@ -6,12 +6,15 @@*/use std::cell::UnsafeCell;-use std::ffi::c_void;+use std::rc::Rc;use std::sync::Arc;use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering};-use super::pipe_callbacks::{CallbackService, PipeCallbacks};-use crate::web_audio::control_message::clone_arc;+use crate::web_audio::control_thread::{ControlThread, ControlThreadCell};++pub trait AudioWorkletPipeClient {+ fn pump(&self);+}pub struct Config {pub quantum_size: usize,@@ -36,21 +39,7 @@ pub struct Config {pub prime_level: usize,}-#[repr(C)]-pub struct WorkletPipeConfig<'a> {- pub quantum_size: usize,- pub input_count: u32,- pub output_count: u32,- pub input_channel_capacity: ak::Span<'a, u32>,- pub output_channel_capacity: ak::Span<'a, u32>,- pub output_channel_count_matches_input: bool,- pub param_count: u32,- pub param_is_a_rate: ak::Span<'a, bool>,- pub ring_capacity: usize,- pub prime_level: usize,-}--#[derive(Clone, Copy, PartialEq, Eq)]+#[derive(Clone, Copy, PartialEq, Eq, Debug)]#[repr(u8)]pub enum WorkletPipeState {Running,@@ -102,7 +91,8 @@ pub struct AudioWorkletPipe {arena: Box<[UnsafeCell<u64>]>,input_ring: Ring,output_ring: Ring,- callbacks: CallbackService,+ control_thread: ControlThread,+ client: ControlThreadCell<Option<Rc<dyn AudioWorkletPipeClient>>>,pump_scheduled: AtomicBool,state: AtomicU8,underrun_count: AtomicU64,@@ -117,7 +107,7 @@ const SLOT_CHANNEL_COUNTS_OFFSET: usize = 12;const SLOT_ALIGNMENT: usize = 64;impl AudioWorkletPipe {- fn new(config: Config, callbacks: CallbackService) -> Self {+ pub fn new(config: Config) -> Arc<Self> {assert!(config.quantum_size > 0);assert_eq!(config.input_channel_capacity.len(), config.input_count);assert_eq!(config.output_channel_capacity.len(), config.output_count);@@ -153,7 +143,7 @@ impl AudioWorkletPipe {let output_slot_stride = (offset + SLOT_ALIGNMENT - 1) & !(SLOT_ALIGNMENT - 1);let output_region_offset = config.ring_capacity * input_slot_stride;let arena_size = output_region_offset + config.ring_capacity * output_slot_stride;- Self {+ Arc::new(Self {ring_index_mask: config.ring_capacity - 1,config,input_slot_stride,@@ -166,12 +156,18 @@ impl AudioWorkletPipe {arena: (0..arena_size / size_of::<u64>()).map(|_| UnsafeCell::new(0)).collect(),input_ring: Ring::default(),output_ring: Ring::default(),- callbacks,+ control_thread: ControlThread::current(),+ client: ControlThreadCell::new(None),pump_scheduled: AtomicBool::new(false),state: AtomicU8::new(WorkletPipeState::Running as u8),underrun_count: AtomicU64::new(0),dropped_input_count: AtomicU64::new(0),- }+ })+ }++ // Accessed only on the control thread, including by deferred wakeups.+ pub fn set_client(&self, client: Option<Rc<dyn AudioWorkletPipeClient>>) {+ self.client.replace(client);}fn input_slot(&self, counter: usize) -> *mut u8 {@@ -310,19 +306,15 @@ impl AudioWorkletPipe {if self.pump_scheduled.swap(true, Ordering::AcqRel) {return;}- unsafe extern "C" fn invoke(task: *mut c_void) {- let pipe = unsafe { Arc::from_raw(task.cast::<AudioWorkletPipe>()) };+ let pipe = Arc::clone(self);+ self.control_thread.post(move || {if pipe.state() == WorkletPipeState::ShutDown {return;}- unsafe {- (pipe.callbacks.callbacks.on_wakeup)(pipe.callbacks.owner.pointer);+ if let Some(client) = pipe.client.get() {+ client.pump();}- }- let task = Arc::into_raw(Arc::clone(self));- unsafe {- self.callbacks.post(task.cast_mut().cast(), invoke);- }+ });}// The pump calls this before draining the input ring, so a burst that lands while the pump is running schedules@@ -347,6 +339,30 @@ impl AudioWorkletPipe {self.state.store(state as u8, Ordering::Release);}+ pub fn underrun_count(&self) -> u64 {+ self.underrun_count.load(Ordering::Relaxed)+ }++ pub fn dropped_input_count(&self) -> u64 {+ self.dropped_input_count.load(Ordering::Relaxed)+ }++ /// # Safety+ /// The caller must be the only consumer of the input ring.+ pub unsafe fn try_read_input(&self, read: impl FnOnce(&InputSlotReader<'_>)) -> bool {+ unsafe { self.try_pop_input(|slot| read(&InputSlotReader { pipe: self, slot })) }+ }++ /// # Safety+ /// The caller must be the only producer of the output ring.+ pub unsafe fn try_write_output(&self, fill: impl FnOnce(&mut OutputSlotWriter<'_>)) -> bool {+ unsafe { self.try_push_output(|slot| fill(&mut OutputSlotWriter { pipe: self, slot })) }+ }++ pub(crate) unsafe fn start_frame(slot: *const u8) -> u64 {+ unsafe { *slot.cast::<u64>() }+ }+pub(crate) unsafe fn set_start_frame(slot: *mut u8, frame: u64) {unsafe {*slot.cast::<u64>() = frame;@@ -434,171 +450,55 @@ pub fn ring_sizing_for_device_latency(device_latency_ms: u32, sample_rate: f32,}}-/// # Safety-/// Both output pointers must point to writable `usize` slots.-#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_ring_sizing(- device_latency_ms: u32,- sample_rate: f32,- quantum_size: usize,- ring_capacity: *mut usize,- prime_level: *mut usize,-) {- let sizing = ring_sizing_for_device_latency(device_latency_ms, sample_rate, quantum_size);- unsafe {- *ring_capacity = sizing.ring_capacity;- *prime_level = sizing.prime_level;- }-}--#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_create(- config: WorkletPipeConfig<'_>,- callbacks: PipeCallbacks,-) -> *const AudioWorkletPipe {- let config = Config {- quantum_size: config.quantum_size,- input_count: config.input_count as usize,- output_count: config.output_count as usize,- input_channel_capacity: config.input_channel_capacity.as_slice().to_vec(),- output_channel_capacity: config.output_channel_capacity.as_slice().to_vec(),- output_channel_count_matches_input: config.output_channel_count_matches_input,- param_count: config.param_count as usize,- param_is_a_rate: config.param_is_a_rate.as_slice().to_vec(),- ring_capacity: config.ring_capacity,- prime_level: config.prime_level,- };- Arc::into_raw(Arc::new(AudioWorkletPipe::new(config, unsafe {- CallbackService::new(callbacks)- })))-}--#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_destroy(pipe: *const AudioWorkletPipe) {- drop(unsafe { Arc::from_raw(pipe) });+pub struct InputSlotReader<'a> {+ pipe: &'a AudioWorkletPipe,+ slot: *mut u8,}-#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_transfer(- pipe: *const AudioWorkletPipe,- output: bool,- push: bool,- context: *mut c_void,- callback: unsafe extern "C" fn(*mut c_void, *mut u8),-) -> bool {- let pipe = unsafe { &*pipe };- let callback = |slot| unsafe {- callback(context, slot);- };- match (output, push) {- (false, true) => unsafe { pipe.try_push_input(callback) },- (false, false) => unsafe { pipe.try_pop_input(callback) },- (true, true) => unsafe { pipe.try_push_output(callback) },- (true, false) => unsafe { pipe.try_pop_output(callback) },+impl InputSlotReader<'_> {+ pub fn start_frame(&self) -> u64 {+ unsafe { AudioWorkletPipe::start_frame(self.slot) }}-}--#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_output_occupancy(pipe: *const AudioWorkletPipe) -> usize {- unsafe { &*pipe }.output_occupancy()-}-#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_discard(pipe: *const AudioWorkletPipe, target: usize) {- unsafe { &*pipe }.discard_outputs_down_to(target);-}--#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_prime(pipe: *const AudioWorkletPipe, count: usize) {- unsafe {- (&*pipe).prime_outputs_with_silence(count);+ pub fn had_gap(&self) -> bool {+ unsafe { AudioWorkletPipe::flag(self.slot) }}-}--#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_request_wakeup(pipe: *const AudioWorkletPipe) {- unsafe { clone_arc(pipe) }.request_wakeup();-}--#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_clear_wakeup(pipe: *const AudioWorkletPipe) {- unsafe { &*pipe }.clear_wakeup_flag();-}-#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_state(pipe: *const AudioWorkletPipe) -> WorkletPipeState {- unsafe { &*pipe }.state()-}--#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_set_state(- pipe: *const AudioWorkletPipe,- state: WorkletPipeState,-) {- unsafe { &*pipe }.set_state(state);-}+ pub fn actual_channel_count(&self, input: usize) -> u32 {+ unsafe { *self.pipe.channel_count(self.slot, false, input) }+ }-#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_counter(pipe: *const AudioWorkletPipe, dropped: bool) -> u64 {- let pipe = unsafe { &*pipe };- if dropped {- pipe.dropped_input_count.load(Ordering::Relaxed)- } else {- pipe.underrun_count.load(Ordering::Relaxed)+ pub fn input_channel(&self, input: usize, channel: usize) -> &[f32] {+ let (samples, length) = unsafe { self.pipe.channel(self.slot, false, input, channel) };+ unsafe { ak::slice_from_raw_parts(samples, length) }}-}-#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_slot_frame(slot: *mut u8) -> *mut u64 {- slot.cast()+ pub fn param_block(&self, param: usize) -> &[f32] {+ let (samples, length) = unsafe { self.pipe.param_block(self.slot, param) };+ unsafe { ak::slice_from_raw_parts(samples, length) }+ }}-#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_slot_flag(slot: *const u8) -> bool {- unsafe { AudioWorkletPipe::flag(slot) }+pub struct OutputSlotWriter<'a> {+ pipe: &'a AudioWorkletPipe,+ slot: *mut u8,}-#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_slot_set_flag(slot: *mut u8, enabled: bool) {- unsafe {- AudioWorkletPipe::set_flag(slot, enabled);+impl OutputSlotWriter<'_> {+ pub fn set_start_frame(&mut self, frame: u64) {+ unsafe { AudioWorkletPipe::set_start_frame(self.slot, frame) };}-}-#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_slot_count(- pipe: *const AudioWorkletPipe,- slot: *mut u8,- output: bool,- index: usize,-) -> *mut u32 {- unsafe { (&*pipe).channel_count(slot, output, index) }-}+ pub fn set_processor_active(&mut self, active: bool) {+ unsafe { AudioWorkletPipe::set_flag(self.slot, active) };+ }-#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_slot_channel(- pipe: *const AudioWorkletPipe,- slot: *mut u8,- output: bool,- index: usize,- channel: usize,- result: *mut ak::SpanMut<'static, f32>,-) {- let (pointer, length) = unsafe { (&*pipe).channel(slot, output, index, channel) };- unsafe {- *result = ak::SpanMut::new(ak::slice_from_raw_parts_mut(pointer, length));+ pub fn set_actual_channel_count(&mut self, output: usize, channel_count: u32) {+ unsafe { *self.pipe.channel_count(self.slot, true, output) = channel_count };}-}-#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_worklet_slot_param(- pipe: *const AudioWorkletPipe,- slot: *mut u8,- param: usize,- result: *mut ak::SpanMut<'static, f32>,-) {- let (pointer, length) = unsafe { (&*pipe).param_block(slot, param) };- unsafe {- *result = ak::SpanMut::new(ak::slice_from_raw_parts_mut(pointer, length));+ pub fn output_channel(&mut self, output: usize, channel: usize) -> &mut [f32] {+ let (samples, length) = unsafe { self.pipe.channel(self.slot, true, output, channel) };+ unsafe { ak::slice_from_raw_parts_mut(samples, length) }}}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe_tests.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe_tests.rsnew file mode 100644index 00000000000..34a79f5d3dc--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe_tests.rs@@ -0,0 +1,591 @@+/*+ * Copyright (c) 2026, Ali Mohammad Pur <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use std::cell::{Cell, RefCell};+use std::collections::VecDeque;+use std::ffi::c_void;+use std::rc::Rc;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex, Weak};+use std::thread;+use std::time::Duration;++use super::audio_worklet_pipe::{+ AudioWorkletPipe, AudioWorkletPipeClient, Config, WorkletPipeState, ring_sizing_for_device_latency,+};++const QUANTUM_SIZE: usize = 128;+const RING_CAPACITY: usize = 64;+const PRIME_LEVEL: usize = 48;+const BURST_QUANTA: usize = 38;++struct PostedTask {+ task: usize,+ invoke: unsafe extern "C" fn(*mut c_void),+}++type EventLoop = Mutex<VecDeque<PostedTask>>;++thread_local! {+ static EVENT_LOOP: &'static EventLoop = Box::leak(Box::default());+}++#[unsafe(no_mangle)]+extern "C" fn web_audio_current_event_loop() -> *mut c_void {+ EVENT_LOOP.with(|event_loop| std::ptr::from_ref::<EventLoop>(event_loop).cast_mut().cast())+}++#[unsafe(no_mangle)]+unsafe extern "C" fn web_audio_deferred_invoke(+ event_loop: *mut c_void,+ task: *mut c_void,+ invoke: unsafe extern "C" fn(*mut c_void),+) {+ let event_loop = unsafe { &*event_loop.cast::<EventLoop>() };+ event_loop.lock().unwrap().push_back(PostedTask {+ task: task as usize,+ invoke,+ });+}++fn run_posted_tasks() {+ loop {+ let task = EVENT_LOOP.with(|event_loop| event_loop.lock().unwrap().pop_front());+ let Some(task) = task else {+ return;+ };+ unsafe { (task.invoke)(task.task as *mut c_void) };+ }+}++fn test_pipe() -> Arc<AudioWorkletPipe> {+ AudioWorkletPipe::new(Config {+ quantum_size: QUANTUM_SIZE,+ input_count: 1,+ output_count: 1,+ input_channel_capacity: vec![2],+ output_channel_capacity: vec![2],+ output_channel_count_matches_input: false,+ param_count: 2,+ param_is_a_rate: vec![true, false],+ ring_capacity: RING_CAPACITY,+ prime_level: PRIME_LEVEL,+ })+}++struct InputSlotWriter<'a> {+ pipe: &'a AudioWorkletPipe,+ slot: *mut u8,+}++impl InputSlotWriter<'_> {+ fn set_start_frame(&mut self, frame: u64) {+ unsafe { AudioWorkletPipe::set_start_frame(self.slot, frame) };+ }++ fn set_had_gap(&mut self, had_gap: bool) {+ unsafe { AudioWorkletPipe::set_flag(self.slot, had_gap) };+ }++ fn set_actual_channel_count(&mut self, input: usize, channel_count: u32) {+ unsafe { *self.pipe.channel_count(self.slot, false, input) = channel_count };+ }++ fn input_channel(&mut self, input: usize, channel: usize) -> &mut [f32] {+ let (samples, length) = unsafe { self.pipe.channel(self.slot, false, input, channel) };+ unsafe { ak::slice_from_raw_parts_mut(samples, length) }+ }++ fn param_block(&mut self, param: usize) -> &mut [f32] {+ let (samples, length) = unsafe { self.pipe.param_block(self.slot, param) };+ unsafe { ak::slice_from_raw_parts_mut(samples, length) }+ }+}++struct OutputSlotReader<'a> {+ pipe: &'a AudioWorkletPipe,+ slot: *mut u8,+}++impl OutputSlotReader<'_> {+ fn start_frame(&self) -> u64 {+ unsafe { AudioWorkletPipe::start_frame(self.slot) }+ }++ fn processor_active(&self) -> bool {+ unsafe { AudioWorkletPipe::flag(self.slot) }+ }++ fn actual_channel_count(&self, output: usize) -> u32 {+ unsafe { *self.pipe.channel_count(self.slot, true, output) }+ }++ fn output_channel(&self, output: usize, channel: usize) -> &[f32] {+ let (samples, length) = unsafe { self.pipe.channel(self.slot, true, output, channel) };+ unsafe { ak::slice_from_raw_parts(samples, length) }+ }+}++fn try_push_input(pipe: &AudioWorkletPipe, fill: impl FnOnce(&mut InputSlotWriter<'_>)) -> bool {+ unsafe { pipe.try_push_input(|slot| fill(&mut InputSlotWriter { pipe, slot })) }+}++fn try_pop_output(pipe: &AudioWorkletPipe, read: impl FnOnce(&OutputSlotReader<'_>)) -> bool {+ unsafe { pipe.try_pop_output(|slot| read(&OutputSlotReader { pipe, slot })) }+}++fn random_sleep(state: &Cell<u32>) {+ let next = state.get().wrapping_mul(1_103_515_245).wrapping_add(12_345);+ state.set(next);+ thread::sleep(Duration::from_millis(u64::from((next >> 16) % 11)));+}++#[test]+fn ring_sizing_matches_renderer_defaults() {+ let sizing = ring_sizing_for_device_latency(100, 48000., 128);+ assert_eq!(sizing.ring_capacity, 64);+ assert_eq!(sizing.prime_level, 48);++ for latency_ms in [10_u32, 20, 50, 100, 200, 500] {+ let sizing = ring_sizing_for_device_latency(latency_ms, 48000., 128);+ let burst = (f64::from(latency_ms) / 1000. * 48000. / 128.).ceil() as usize;+ assert!(sizing.prime_level >= burst);+ assert!(sizing.ring_capacity > sizing.prime_level);+ assert!(sizing.ring_capacity.is_power_of_two());+ }+}++#[test]+fn pops_on_empty_rings_fail() {+ let pipe = test_pipe();++ assert!(!unsafe { pipe.try_read_input(|_| unreachable!()) });+ assert!(!try_pop_output(&pipe, |_| unreachable!()));++ // Only the audio thread's output pops count as underruns; an empty input ring just means the pump caught up.+ assert_eq!(pipe.underrun_count(), 1);+ assert_eq!(pipe.dropped_input_count(), 0);+ assert_eq!(pipe.output_occupancy(), 0);+}++#[test]+fn input_ring_roundtrip_fill_to_capacity_and_overrun() {+ let pipe = test_pipe();++ for i in 0..RING_CAPACITY {+ let pushed = try_push_input(&pipe, |slot| {+ slot.set_start_frame((i * QUANTUM_SIZE) as u64);+ if i == 3 {+ slot.set_had_gap(true);+ }+ slot.set_actual_channel_count(0, (i % 3) as u32);+ for channel in 0..i % 3 {+ let samples = slot.input_channel(0, channel);+ assert_eq!(samples.len(), QUANTUM_SIZE);+ for (frame, sample) in samples.iter_mut().enumerate() {+ *sample = (i * 10 + channel) as f32 + frame as f32 * 0.25;+ }+ }+ assert_eq!(slot.param_block(0).len(), QUANTUM_SIZE);+ assert_eq!(slot.param_block(1).len(), 1);+ for (frame, sample) in slot.param_block(0).iter_mut().enumerate() {+ *sample = i as f32 + frame as f32 * 0.5;+ }+ slot.param_block(1)[0] = i as f32;+ });+ assert!(pushed);+ }++ assert!(!try_push_input(&pipe, |_| unreachable!()));+ assert_eq!(pipe.dropped_input_count(), 1);++ for i in 0..RING_CAPACITY {+ let popped = unsafe {+ pipe.try_read_input(|slot| {+ assert_eq!(slot.start_frame(), (i * QUANTUM_SIZE) as u64);+ assert_eq!(slot.had_gap(), i == 3);+ assert_eq!(slot.actual_channel_count(0), (i % 3) as u32);+ for channel in 0..i % 3 {+ let samples = slot.input_channel(0, channel);+ assert_eq!(samples[0], (i * 10 + channel) as f32);+ assert_eq!(+ samples[QUANTUM_SIZE - 1],+ (i * 10 + channel) as f32 + (QUANTUM_SIZE - 1) as f32 * 0.25+ );+ }+ assert_eq!(slot.param_block(0)[0], i as f32);+ assert_eq!(+ slot.param_block(0)[QUANTUM_SIZE - 1],+ i as f32 + (QUANTUM_SIZE - 1) as f32 * 0.5+ );+ assert_eq!(slot.param_block(1)[0], i as f32);+ })+ };+ assert!(popped);+ }+ assert!(!unsafe { pipe.try_read_input(|_| unreachable!()) });++ // Wrap around into the same storage: flags are cleared on push, so slot 3's gap flag must not leak through.+ for i in 0..RING_CAPACITY {+ assert!(try_push_input(&pipe, |slot| {+ slot.set_start_frame(((RING_CAPACITY + i) * QUANTUM_SIZE) as u64);+ slot.set_actual_channel_count(0, 0);+ }));+ }+ for i in 0..RING_CAPACITY {+ assert!(unsafe {+ pipe.try_read_input(|slot| {+ assert_eq!(slot.start_frame(), ((RING_CAPACITY + i) * QUANTUM_SIZE) as u64);+ assert!(!slot.had_gap());+ })+ });+ }++ assert_eq!(pipe.dropped_input_count(), 1);+ assert_eq!(pipe.underrun_count(), 0);+}++#[test]+fn output_ring_roundtrip() {+ let pipe = test_pipe();++ for i in 0..5 {+ assert!(unsafe {+ pipe.try_write_output(|slot| {+ slot.set_start_frame((i * QUANTUM_SIZE) as u64);+ slot.set_processor_active(i % 2 == 0);+ slot.set_actual_channel_count(0, 2);+ for channel in 0..2 {+ slot.output_channel(0, channel).fill((i * 10 + channel) as f32);+ }+ })+ });+ }+ assert_eq!(pipe.output_occupancy(), 5);++ for i in 0..5 {+ assert!(try_pop_output(&pipe, |slot| {+ assert_eq!(slot.start_frame(), (i * QUANTUM_SIZE) as u64);+ assert_eq!(slot.processor_active(), i % 2 == 0);+ assert_eq!(slot.actual_channel_count(0), 2);+ for channel in 0..2 {+ assert_eq!(slot.output_channel(0, channel)[0], (i * 10 + channel) as f32);+ assert_eq!(+ slot.output_channel(0, channel)[QUANTUM_SIZE - 1],+ (i * 10 + channel) as f32+ );+ }+ }));+ }+ assert_eq!(pipe.underrun_count(), 0);+}++#[test]+fn priming_and_discard_down_to() {+ let pipe = test_pipe();++ unsafe { pipe.prime_outputs_with_silence(PRIME_LEVEL) };+ assert_eq!(pipe.output_occupancy(), PRIME_LEVEL);++ let popped = try_pop_output(&pipe, |slot| {+ assert_eq!(slot.start_frame(), 0);+ assert!(slot.processor_active());+ assert_eq!(slot.actual_channel_count(0), 2);+ for channel in 0..2 {+ assert!(slot.output_channel(0, channel).iter().all(|sample| *sample == 0.));+ }+ });+ assert!(popped);+ assert_eq!(pipe.output_occupancy(), PRIME_LEVEL - 1);++ pipe.discard_outputs_down_to(10);+ assert_eq!(pipe.output_occupancy(), 10);++ pipe.discard_outputs_down_to(20);+ assert_eq!(pipe.output_occupancy(), 10);++ pipe.discard_outputs_down_to(0);+ assert_eq!(pipe.output_occupancy(), 0);+ assert_eq!(pipe.underrun_count(), 0);+}++#[test]+fn state_transitions() {+ let pipe = test_pipe();++ assert_eq!(pipe.state(), WorkletPipeState::Running);+ pipe.set_state(WorkletPipeState::Failed);+ assert_eq!(pipe.state(), WorkletPipeState::Failed);+ pipe.set_state(WorkletPipeState::ShutDown);+ assert_eq!(pipe.state(), WorkletPipeState::ShutDown);+}++struct CountingClient {+ pump_runs: Cell<usize>,+}++impl AudioWorkletPipeClient for CountingClient {+ fn pump(&self) {+ self.pump_runs.set(self.pump_runs.get() + 1);+ }+}++#[test]+fn wakeup_coalescing() {+ let pipe = test_pipe();+ let client = Rc::new(CountingClient {+ pump_runs: Cell::new(0),+ });+ pipe.set_client(Some(client.clone()));++ pipe.request_wakeup();+ pipe.request_wakeup();+ pipe.request_wakeup();++ // Give any (incorrectly) duplicated wakeups a chance to run.+ run_posted_tasks();+ assert_eq!(client.pump_runs.get(), 1);++ pipe.clear_wakeup_flag();+ pipe.request_wakeup();+ run_posted_tasks();+ assert_eq!(client.pump_runs.get(), 2);++ pipe.clear_wakeup_flag();+ pipe.set_state(WorkletPipeState::ShutDown);+ pipe.request_wakeup();+ run_posted_tasks();+ assert_eq!(client.pump_runs.get(), 2);++ pipe.set_client(None);+}++struct GainClient {+ pipe: Weak<AudioWorkletPipe>,+ random: Cell<u32>,+ quanta_processed: Cell<u64>,+}++impl AudioWorkletPipeClient for GainClient {+ fn pump(&self) {+ let pipe = self.pipe.upgrade().unwrap();+ pipe.clear_wakeup_flag();+ random_sleep(&self.random);+ while unsafe {+ pipe.try_read_input(|input| {+ let pushed = pipe.try_write_output(|output| {+ output.set_start_frame(input.start_frame());+ output.set_processor_active(true);+ output.set_actual_channel_count(0, input.actual_channel_count(0));+ let gain = input.param_block(1)[0];+ for channel in 0..input.actual_channel_count(0) as usize {+ let source = input.input_channel(0, channel);+ for (destination, sample) in output.output_channel(0, channel).iter_mut().zip(source) {+ *destination = sample * gain;+ }+ }+ });+ assert!(pushed);+ self.quanta_processed.set(self.quanta_processed.get() + 1);+ })+ } {}+ }+}++#[derive(Default)]+struct ProducerResults {+ popped_stamps: Vec<u64>,+ sample_mismatches: u64,+ failed_output_pops: u64,+ successful_input_pushes: u64,+}++fn run_event_loop_until(done: &AtomicBool) {+ while !done.load(Ordering::SeqCst) {+ run_posted_tasks();+ thread::sleep(Duration::from_millis(5));+ }+ run_posted_tasks();+}++#[test]+fn two_thread_stress() {+ const BURST_COUNT: usize = 20;++ // Primed slots are stamped 0; real quanta start one quantum in.+ const FIRST_STAMP: u64 = QUANTUM_SIZE as u64;++ let pipe = test_pipe();+ unsafe { pipe.prime_outputs_with_silence(PRIME_LEVEL) };+ let client = Rc::new(GainClient {+ pipe: Arc::downgrade(&pipe),+ random: Cell::new(1),+ quanta_processed: Cell::new(0),+ });+ pipe.set_client(Some(client.clone()));++ let producer_done = Arc::new(AtomicBool::new(false));+ let producer = {+ let pipe = Arc::clone(&pipe);+ let producer_done = Arc::clone(&producer_done);+ thread::spawn(move || {+ let mut results = ProducerResults::default();+ results.popped_stamps.reserve(BURST_COUNT * BURST_QUANTA + PRIME_LEVEL);+ let mut next_frame = FIRST_STAMP;+ for _ in 0..BURST_COUNT {+ for _ in 0..BURST_QUANTA {+ let popped = try_pop_output(&pipe, |output| {+ let stamp = output.start_frame();+ results.popped_stamps.push(stamp);++ // Primed slots are silent; processed ones echo the value the producer filled in below.+ for channel in 0..output.actual_channel_count(0) as usize {+ let expected = if stamp == 0 {+ 0.+ } else {+ (stamp / QUANTUM_SIZE as u64 + channel as u64) as f32+ };+ if output.output_channel(0, channel)[0] != expected {+ results.sample_mismatches += 1;+ }+ }+ });+ if !popped {+ results.failed_output_pops += 1;+ }+ let pushed = try_push_input(&pipe, |input| {+ input.set_start_frame(next_frame);+ input.set_actual_channel_count(0, 2);+ for channel in 0..2 {+ input+ .input_channel(0, channel)+ .fill((next_frame / QUANTUM_SIZE as u64 + channel as u64) as f32);+ }+ input.param_block(0).fill(0.5);+ input.param_block(1)[0] = 1.;+ });+ if pushed {+ results.successful_input_pushes += 1;+ }+ next_frame += QUANTUM_SIZE as u64;+ }+ pipe.request_wakeup();+ thread::sleep(Duration::from_millis(100));+ }+ producer_done.store(true, Ordering::SeqCst);+ results+ })+ };++ run_event_loop_until(&producer_done);+ let results = producer.join().unwrap();++ let mut pending_input = 0_u64;+ while unsafe { pipe.try_read_input(|_| pending_input += 1) } {}++ assert_eq!(results.sample_mismatches, 0);+ assert_eq!(+ results.failed_output_pops + results.popped_stamps.len() as u64,+ (BURST_COUNT * BURST_QUANTA) as u64+ );+ assert_eq!(+ results.successful_input_pushes + pipe.dropped_input_count(),+ (BURST_COUNT * BURST_QUANTA) as u64+ );+ assert_eq!(+ client.quanta_processed.get() + pending_input,+ results.successful_input_pushes+ );++ // The FIFO order guarantees all primed (stamp 0) slots come out before any processed quantum, and processed+ // stamps are observed in increasing quantum order.+ let primed_popped = results.popped_stamps.iter().take_while(|stamp| **stamp == 0).count();+ assert!(primed_popped <= PRIME_LEVEL);+ let mut previous_stamp = None;+ for stamp in &results.popped_stamps[primed_popped..] {+ assert!(*stamp >= FIRST_STAMP);+ assert_eq!((stamp - FIRST_STAMP) % QUANTUM_SIZE as u64, 0);+ if let Some(previous_stamp) = previous_stamp {+ assert!(*stamp > previous_stamp);+ }+ previous_stamp = Some(*stamp);+ }++ pipe.set_client(None);+}++struct SilentClient {+ pipe: RefCell<Option<Arc<AudioWorkletPipe>>>,+ quanta_processed: Cell<u64>,+}++impl AudioWorkletPipeClient for SilentClient {+ fn pump(&self) {+ let pipe = self.pipe.borrow().clone().unwrap();+ pipe.clear_wakeup_flag();+ if pipe.state() != WorkletPipeState::Running {+ return;+ }+ while unsafe {+ pipe.try_read_input(|input| {+ let _ = pipe.try_write_output(|output| {+ output.set_start_frame(input.start_frame());+ output.set_processor_active(true);+ output.set_actual_channel_count(0, 0);+ });+ self.quanta_processed.set(self.quanta_processed.get() + 1);+ })+ } {}+ }+}++#[test]+fn teardown_when_producer_drops_its_reference_mid_run() {+ let pipe = test_pipe();+ unsafe { pipe.prime_outputs_with_silence(PRIME_LEVEL) };+ let client = Rc::new(SilentClient {+ pipe: RefCell::new(Some(Arc::clone(&pipe))),+ quanta_processed: Cell::new(0),+ });+ pipe.set_client(Some(client.clone()));++ let producer_done = Arc::new(AtomicBool::new(false));+ let producer = {+ let mut producer_pipe = Some(Arc::clone(&pipe));+ let producer_done = Arc::clone(&producer_done);+ thread::spawn(move || {+ let mut next_frame = QUANTUM_SIZE as u64;+ for _ in 0..3 {+ let pipe = producer_pipe.as_ref().unwrap();+ for _ in 0..BURST_QUANTA {+ try_pop_output(pipe, |_| {});+ let _ = try_push_input(pipe, |input| {+ input.set_start_frame(next_frame);+ input.set_actual_channel_count(0, 0);+ });+ next_frame += QUANTUM_SIZE as u64;+ }+ pipe.request_wakeup();+ thread::sleep(Duration::from_millis(30));+ }+ let pipe = producer_pipe.take().unwrap();+ pipe.set_state(WorkletPipeState::ShutDown);+ drop(pipe);+ producer_done.store(true, Ordering::SeqCst);+ })+ };++ run_event_loop_until(&producer_done);+ producer.join().unwrap();++ assert_eq!(pipe.state(), WorkletPipeState::ShutDown);+ assert_eq!(pipe.dropped_input_count(), 0);+ assert!(client.quanta_processed.get() > 0);++ pipe.set_client(None);+ client.pipe.replace(None);+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rsindex eab47cedeb0..d45c067bb71 100644--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs@@ -22,6 +22,8 @@ pub mod offline_audio_renderer;pub mod realtime_audio_renderer;pub mod audio_worklet_pipe;+#[cfg(test)]+mod audio_worklet_pipe_tests;pub mod pipe_callbacks;pub mod script_processor_pipe;diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletGlobalScope.cpp b/Libraries/LibWeb/WebAudio/AudioWorkletGlobalScope.cppindex df9af3ad523..816918d1853 100644--- a/Libraries/LibWeb/WebAudio/AudioWorkletGlobalScope.cpp+++ b/Libraries/LibWeb/WebAudio/AudioWorkletGlobalScope.cpp@@ -6,18 +6,14 @@#include <LibGC/Heap.h>#include <LibJS/Runtime/AbstractOperations.h>-#include <LibJS/Runtime/Array.h>#include <LibJS/Runtime/Error.h>#include <LibJS/Runtime/FunctionObject.h>#include <LibJS/Runtime/Iterator.h>-#include <LibJS/Runtime/TypedArray.h>#include <LibJS/Runtime/VM.h>#include <LibJS/Runtime/ValueInlines.h>#include <LibWeb/HTML/MessagePort.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/WebAudio/AudioWorklet.h>#include <LibWeb/WebAudio/AudioWorkletGlobalScope.h>-#include <LibWeb/WebAudio/AudioWorkletNode.h>#include <LibWeb/WebIDL/AbstractOperations.h>#include <LibWeb/WebIDL/CallbackType.h>#include <LibWeb/WebIDL/DOMException.h>@@ -167,173 +163,6 @@ void AudioWorkletGlobalScope::set_pending_processor_construction_data(PendingProm_pending_processor_construction_data = move(data);}-void AudioWorkletGlobalScope::add_processor_slot(ProcessorSlot slot)-{- m_processor_slots.set(slot.node_id, move(slot));-}--void AudioWorkletGlobalScope::pump(NodeID node_id, Rendering::AudioWorkletPipe& pipe)-{- // Every invocation consumes its scheduled wakeup, including stale callbacks for removed slots.- pipe.clear_wakeup_flag();- auto it = m_processor_slots.find(node_id);- if (it == m_processor_slots.end())- return;-- if (it->value.pipe->state() == Rendering::AudioWorkletPipe::State::ShutDown) {- m_processor_slots.remove(node_id);- return;- }- if (it->value.failed)- return;-- auto worklet_pipe = it->value.pipe;- auto processor = it->value.processor;- auto node = it->value.node;- auto parameter_names = it->value.parameter_names;-- auto& realm = this->realm();- auto& vm = realm.vm();- // Keep one execution context for the batch so its microtask checkpoint runs after all available quanta.- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- auto const& config = worklet_pipe->config();-- while (true) {- if (worklet_pipe->output_occupancy() == config.ring_capacity)- break;- bool processed_one = false;- bool pump_failed = false;- bool output_full = false;-- (void)worklet_pipe->try_pop_input([&](Rendering::AudioWorkletPipe::InputSlotReader const& input_slot) {- processed_one = true;-- // https://webaudio.github.io/web-audio-api/#rendering-loop — currentFrame/currentTime- // reflect the block being processed.- m_current_frame = input_slot.start_frame();- m_current_time = static_cast<double>(input_slot.start_frame()) / m_sample_rate;-- // The processor may detach channel arrays, so they cannot be reused without checking their buffers.- // FIXME: Reuse arrays that remain attached.- auto build_channel_array = [&](size_t channel_count, auto&& fill_channel) -> GC::Ref<JS::Array> {- auto channels = MUST(JS::Array::create(realm, channel_count));- for (size_t channel = 0; channel < channel_count; ++channel) {- auto float32_array = MUST(JS::Float32Array::create(realm, config.quantum_size));- fill_channel(channel, float32_array);- MUST(channels->create_data_property(JS::PropertyKey { channel }, float32_array));- }- return channels;- };-- auto inputs = MUST(JS::Array::create(realm, config.input_count));- for (size_t input = 0; input < config.input_count; ++input) {- auto channels = build_channel_array(input_slot.actual_channel_count(input), [&](size_t channel, auto& float32_array) {- auto source = input_slot.input_channel(input, channel);- float32_array->viewed_array_buffer()->overwrite(0, source.data(), source.size() * sizeof(float));- });- MUST(inputs->create_data_property(JS::PropertyKey { input }, channels));- }-- auto output_channel_count = [&](size_t output) -> size_t {- if (config.output_channel_count_matches_input)- return max(input_slot.actual_channel_count(0), 1u);- return config.output_channel_capacity[output];- };- auto outputs = MUST(JS::Array::create(realm, config.output_count));- GC::RootVector<GC::Ref<JS::Array>> output_channel_arrays;- output_channel_arrays.ensure_capacity(config.output_count);- for (size_t output = 0; output < config.output_count; ++output) {- auto channels = build_channel_array(output_channel_count(output), [&](size_t, auto&) { });- output_channel_arrays.unchecked_append(channels);- MUST(outputs->create_data_property(JS::PropertyKey { output }, channels));- }-- auto parameters = JS::Object::create(realm, realm.intrinsics().object_prototype());- for (size_t param_index = 0; param_index < config.param_count; ++param_index) {- auto block = input_slot.param_block(param_index);- auto float32_array = MUST(JS::Float32Array::create(realm, block.size()));- float32_array->viewed_array_buffer()->overwrite(0, block.data(), block.size() * sizeof(float));- MUST(parameters->create_data_property(JS::PropertyKey { Utf16FlyString(parameter_names[param_index]) }, float32_array));- }-- // Look up process on the instance each call (spec); a non-callable value fails the node.- auto process_value_or_error = processor->get("process"_utf16_fly_string);- if (process_value_or_error.is_error() || !process_value_or_error.value().is_function()) {- pump_failed = true;- if (auto node_ptr = node.ptr()) {- auto error = process_value_or_error.is_error()- ? process_value_or_error.release_error().value()- : JS::Value { JS::TypeError::create(realm, "AudioWorkletProcessor.process must be a function"_utf16).ptr() };- node_ptr->fire_processor_error(error);- }- return;- }-- auto process_value = process_value_or_error.release_value();- AK::Array<JS::Value, 3> process_arguments { JS::Value { inputs.ptr() }, JS::Value { outputs.ptr() }, JS::Value { parameters.ptr() } };- auto result = JS::call(vm, process_value.as_function(), JS::Value { processor.ptr() },- ReadonlySpan<JS::Value> { process_arguments });- if (result.is_error()) {- pump_failed = true;- if (auto node_ptr = node.ptr())- node_ptr->fire_processor_error(result.release_error().value());- return;- }-- if (worklet_pipe->state() == Rendering::AudioWorkletPipe::State::ShutDown)- return;-- bool processor_active = result.value().to_boolean();-- // Push the processed quantum back; read outputs defensively (detached → silence).- if (!worklet_pipe->try_push_output([&](Rendering::AudioWorkletPipe::OutputSlotWriter& output_slot) {- output_slot.start_frame() = input_slot.start_frame();- output_slot.set_processor_active(processor_active);- for (size_t output = 0; output < config.output_count; ++output) {- auto channel_count = output_channel_count(output);- output_slot.actual_channel_count(output) = channel_count;- for (size_t channel = 0; channel < channel_count; ++channel) {- auto destination = output_slot.output_channel(output, channel);- auto channel_value = MUST(output_channel_arrays[output]->get(JS::PropertyKey { channel }));- auto* float32_array = channel_value.is_object() ? as_if<JS::Float32Array>(channel_value.as_object()) : nullptr;- if (!float32_array || float32_array->viewed_array_buffer()->is_detached()- || float32_array->array_length().length() < config.quantum_size) {- __builtin_memset(destination.data(), 0, destination.size() * sizeof(float));- continue;- }- float32_array->viewed_array_buffer()->copy_to(float32_array->byte_offset(),- Bytes { reinterpret_cast<u8*>(destination.data()), destination.size() * sizeof(float) });- }- }- }))- output_full = true;- });-- if (pump_failed) {- if (auto slot_after_process = m_processor_slots.find(node_id); slot_after_process != m_processor_slots.end())- slot_after_process->value.failed = true;- worklet_pipe->set_state(Rendering::AudioWorkletPipe::State::Failed);- return;- }- if (worklet_pipe->state() == Rendering::AudioWorkletPipe::State::ShutDown)- return;- if (output_full)- break;- if (!processed_one)- break;- }-}--void AudioWorkletGlobalScope::shutdown_all_slots()-{- for (auto& slot : m_processor_slots) {- slot.value.pipe->clear_pump_callback();- slot.value.pipe->request_shutdown();- }- m_processor_slots.clear();-}-void AudioWorkletGlobalScope::visit_edges(Cell::Visitor& visitor){Base::visit_edges(visitor);@@ -343,10 +172,6 @@ void AudioWorkletGlobalScope::visit_edges(Cell::Visitor& visitor)visitor.visit(definition.value.constructor);if (m_pending_processor_construction_data.has_value())visitor.visit(m_pending_processor_construction_data->port);- for (auto& slot : m_processor_slots) {- visitor.visit(slot.value.processor);- visitor.visit(slot.value.processor_port);- }}}diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletGlobalScope.h b/Libraries/LibWeb/WebAudio/AudioWorkletGlobalScope.hindex b9ac19451b4..1c0b2a28237 100644--- a/Libraries/LibWeb/WebAudio/AudioWorkletGlobalScope.h+++ b/Libraries/LibWeb/WebAudio/AudioWorkletGlobalScope.h@@ -8,13 +8,10 @@#include <AK/HashMap.h>#include <AK/Utf16String.h>-#include <LibGC/Weak.h>#include <LibWeb/Bindings/AudioWorkletGlobalScope.h>#include <LibWeb/Export.h>#include <LibWeb/Forward.h>#include <LibWeb/HTML/WorkletGlobalScope.h>-#include <LibWeb/WebAudio/Rendering/AudioWorkletPipe.h>-#include <LibWeb/WebAudio/Types.h>#include <LibWebCommon/WebIDL/Types.h>namespace Web::WebAudio {@@ -62,23 +59,6 @@ public:m_current_time = current_time;}- struct ProcessorSlot {- NodeID node_id { 0 };- GC::Ref<JS::Object> processor;- GC::Ref<HTML::MessagePort> processor_port;- GC::Weak<AudioWorkletNode> node; // weak: the slot must not keep the node alive (see keep-alive notes)- NonnullRefPtr<Rendering::AudioWorkletPipe> pipe;- Vector<Utf16String> parameter_names; // descriptor order; keys for the `parameters` argument- bool failed { false };- };- void add_processor_slot(ProcessorSlot);-- // Drains one node's input ring, runs its processor's process() per quantum, and pushes the- // results back. Scheduled (coalesced) by the render thread via the pipe's wakeup callback.- void pump(NodeID, Rendering::AudioWorkletPipe&);-- void shutdown_all_slots();-// Defined by the generated bindings (installs the AudioWorklet-exposed interfaces and the// global mixin members on the wrapper).virtual void initialize_web_interfaces_impl() override;@@ -93,7 +73,6 @@ private:OrderedHashMap<Utf16String, ProcessorDefinition> m_processor_definitions;Optional<PendingProcessorConstructionData> m_pending_processor_construction_data;- HashMap<NodeID, ProcessorSlot> m_processor_slots;u64 m_current_frame { 0 };double m_current_time { 0 };diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp b/Libraries/LibWeb/WebAudio/AudioWorkletNode.cppindex d850785e11e..2dc563845a8 100644--- a/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp+++ b/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibCore/EventLoop.h>#include <LibGC/Heap.h>#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/VM.h>@@ -29,15 +28,11 @@ extern "C" bool web_audio_worklet_find_definition(AudioWorklet*, FlatPtr, void*,extern "C" AudioWorkletGlobalScope* web_audio_worklet_global_scope(AudioWorklet*);extern "C" JS::Realm* web_audio_worklet_scope_realm(AudioWorkletGlobalScope*);extern "C" JSCompletion web_audio_worklet_clone_options(JSVM*, JS::Realm*, JS::Realm*, JS::Object*);-extern "C" RustFFI::FfiSharedCppObject web_audio_worklet_create_pipe(RustFFI::WorkletPipeConfig, float, void const**);-extern "C" void web_audio_worklet_set_pump(Rendering::AudioWorkletPipe*, AudioWorkletGlobalScope*, u64);-extern "C" void web_audio_worklet_clear_pump(Rendering::AudioWorkletPipe*);extern "C" JS::FunctionObject* web_audio_worklet_processor_constructor(AudioWorkletGlobalScope*, FlatPtr);extern "C" void web_audio_worklet_set_pending_port(AudioWorkletGlobalScope*, HTML::MessagePort*);extern "C" void web_audio_worklet_clear_pending_data(AudioWorkletGlobalScope*);-extern "C" void web_audio_worklet_add_processor_slot(AudioWorkletGlobalScope*, u64, JS::Object*, HTML::MessagePort*, AudioWorkletNode*, Rendering::AudioWorkletPipe*, ReadonlySpan<FlatPtr>);+extern "C" void web_audio_worklet_set_current_frame(AudioWorkletGlobalScope*, u64);extern "C" void web_audio_worklet_queue_processor_error(AudioWorkletNode*, DOM::EventTarget*, DOM::EventTarget*, JSValue);-extern "C" void web_rust_audio_worklet_node_fire_error(AudioWorkletNode*, JSValue);bool web_audio_worklet_find_definition(AudioWorklet* worklet, FlatPtr name, void* context, DescriptorCallback descriptor_callback){@@ -62,32 +57,6 @@ JSCompletion web_audio_worklet_clone_options(JSVM* vm, JS::Realm* realm, JS::Reareturn JS::HostABI::throw_completion_to_abi(WebIDL::exception_to_throw_completion(JS::HostABI::vm_from_abi(vm), *error_realm, cloned.release_error()).value());return JS::HostABI::normal_completion_to_abi(JS::HostABI::value_to_abi(cloned.release_value()));}-RustFFI::FfiSharedCppObject web_audio_worklet_create_pipe(RustFFI::WorkletPipeConfig config, float sample_rate, void const** native_pipe)-{- Rendering::AudioWorkletPipe::Config pipe_config;- pipe_config.quantum_size = config.quantum_size;- pipe_config.sample_rate = sample_rate;- pipe_config.input_count = config.input_count;- pipe_config.output_count = config.output_count;- for (auto capacity : config.input_channel_capacity)- pipe_config.input_channel_capacity.append(capacity);- for (auto capacity : config.output_channel_capacity)- pipe_config.output_channel_capacity.append(capacity);- pipe_config.output_channel_count_matches_input = config.output_channel_count_matches_input;- pipe_config.param_count = config.param_count;- for (auto is_a_rate : config.param_is_a_rate)- pipe_config.param_is_a_rate.append(is_a_rate);- pipe_config.ring_capacity = config.ring_capacity;- pipe_config.prime_level = config.prime_level;- auto pipe = Rendering::AudioWorkletPipe::create(move(pipe_config), Core::EventLoop::current());- *native_pipe = pipe->rust_pipe();- return { &pipe.leak_ref(), [](void* pipe) { static_cast<Rendering::AudioWorkletPipe*>(pipe)->ref(); }, [](void* pipe) { static_cast<Rendering::AudioWorkletPipe*>(pipe)->unref(); } };-}-void web_audio_worklet_set_pump(Rendering::AudioWorkletPipe* pipe, AudioWorkletGlobalScope* scope, u64 node_id)-{- pipe->set_pump_callback([scope_root = GC::make_root(*scope), pipe = NonnullRefPtr { *pipe }, node_id = NodeID(node_id)] { scope_root->pump(node_id, *pipe); });-}-void web_audio_worklet_clear_pump(Rendering::AudioWorkletPipe* pipe) { pipe->clear_pump_callback(); }JS::FunctionObject* web_audio_worklet_processor_constructor(AudioWorkletGlobalScope* scope, FlatPtr name){auto const* definition = scope->find_definition(Utf16String::from_raw(name));@@ -96,14 +65,7 @@ JS::FunctionObject* web_audio_worklet_processor_constructor(AudioWorkletGlobalSc}void web_audio_worklet_set_pending_port(AudioWorkletGlobalScope* scope, HTML::MessagePort* port) { scope->set_pending_processor_construction_data({ *port }); }void web_audio_worklet_clear_pending_data(AudioWorkletGlobalScope* scope) { (void)scope->take_pending_processor_construction_data(); }-void web_audio_worklet_add_processor_slot(AudioWorkletGlobalScope* scope, u64 node_id, JS::Object* processor, HTML::MessagePort* processor_port, AudioWorkletNode* node, Rendering::AudioWorkletPipe* pipe, ReadonlySpan<FlatPtr> raw_names)-{- Vector<Utf16String> names;- names.ensure_capacity(raw_names.size());- for (auto raw_name : raw_names)- names.unchecked_append(Utf16String::from_raw(raw_name));- scope->add_processor_slot({ .node_id = NodeID(node_id), .processor = *processor, .processor_port = *processor_port, .node = GC::Weak<AudioWorkletNode> { *node }, .pipe = *pipe, .parameter_names = move(names) });-}+void web_audio_worklet_set_current_frame(AudioWorkletGlobalScope* scope, u64 current_frame) { scope->set_current_frame_and_time(current_frame, static_cast<double>(current_frame) / scope->sample_rate()); }void web_audio_worklet_queue_processor_error(AudioWorkletNode* node, DOM::EventTarget* target, DOM::EventTarget* global, JSValue error){auto& global_object = HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*global));@@ -116,6 +78,5 @@ void web_audio_worklet_queue_processor_error(AudioWorkletNode* node, DOM::EventTtarget->dispatch_event(event);}));}-void AudioWorkletNode::fire_processor_error(JS::Value error) { web_rust_audio_worklet_node_fire_error(this, JS::HostABI::value_to_abi(error)); }}diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletNode.h b/Libraries/LibWeb/WebAudio/AudioWorkletNode.hindex b7e6f579a40..53839ea0483 100644--- a/Libraries/LibWeb/WebAudio/AudioWorkletNode.h+++ b/Libraries/LibWeb/WebAudio/AudioWorkletNode.h@@ -12,9 +12,6 @@ namespace Web::WebAudio {class WEB_API AudioWorkletNode final : public Bindings::RustInterfaceCell {WEB_RUST_INTERFACE(AudioWorkletNode, audio_worklet_node);--public:- void fire_processor_error(JS::Value);};}diff --git a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp b/Libraries/LibWeb/WebAudio/BaseAudioContext.cppindex a211496a957..60f6c98a79a 100644--- a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp+++ b/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp@@ -23,7 +23,6 @@#include <LibWeb/HTML/Window.h>#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/WebAudio/AudioWorklet.h>-#include <LibWeb/WebAudio/AudioWorkletGlobalScope.h>#include <LibWeb/WebAudio/BaseAudioContext.h>#include <LibWeb/WebAudio/RustFFI.h>@@ -47,7 +46,6 @@ extern "C" bool web_audio_context_document_is_fully_active(DOM::EventTarget*);extern "C" bool web_audio_context_responsible_document_is_fully_active(DOM::EventTarget*);extern "C" bool web_audio_context_navigable_is_destroyed(DOM::EventTarget*);extern "C" AudioWorklet* web_audio_context_get_worklet(BaseAudioContext*);-extern "C" void web_audio_context_shutdown_worklet(AudioWorklet*);extern "C" JS::Object* web_audio_context_wrap_worklet(JS::Realm*, AudioWorklet*);extern "C" void web_audio_context_decode(ReadonlyBytes, u32, GC::Cell*);extern "C" void web_audio_context_decoded_destroy(MediaClient::Client::DecodedAudioData*);@@ -93,11 +91,6 @@ bool web_audio_context_navigable_is_destroyed(DOM::EventTarget* global)return navigable && navigable->has_been_destroyed();}AudioWorklet* web_audio_context_get_worklet(BaseAudioContext* context) { return AudioWorklet::create(*context).ptr(); }-void web_audio_context_shutdown_worklet(AudioWorklet* worklet)-{- if (auto scope = worklet->audio_worklet_global_scope())- scope->shutdown_all_slots();-}JS::Object* web_audio_context_wrap_worklet(JS::Realm* realm, AudioWorklet* worklet) { return Bindings::wrap(Bindings::host_defined_wrapper_world(*realm), *realm, GC::Ref { *worklet }).ptr(); }void web_audio_context_decode(ReadonlyBytes data, u32 sample_rate, GC::Cell* operation){diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.cpp b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.cppdeleted file mode 100644index 6ea14990412..00000000000--- a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.cpp+++ /dev/null@@ -1,171 +0,0 @@-/*- * Copyright (c) 2026, Ali Mohammad Pur <[email protected]>- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCore/EventLoop.h>-#include <LibWeb/WebAudio/Rendering/AudioWorkletPipe.h>-#include <LibWeb/WebAudio/RustFFI.h>--namespace Web::WebAudio::Rendering {--struct AudioWorkletPipeCallbacks : AtomicRefCounted<AudioWorkletPipeCallbacks> {- explicit AudioWorkletPipeCallbacks(Core::EventLoop& loop)- : event_loop(loop)- {- }- Core::EventLoop& event_loop;- Function<void()> pump_callback;-};--NonnullRefPtr<AudioWorkletPipe> AudioWorkletPipe::create(Config config, Core::EventLoop& event_loop)-{- return adopt_ref(*new AudioWorkletPipe(move(config), event_loop));-}--AudioWorkletPipe::AudioWorkletPipe(Config config, Core::EventLoop& event_loop)- : m_config(move(config))- , m_callbacks(adopt_ref(*new AudioWorkletPipeCallbacks(event_loop)))-{- RustFFI::PipeCallbacks callbacks {- { m_callbacks.ptr(), [](void* service) { static_cast<AudioWorkletPipeCallbacks*>(service)->ref(); }, [](void* service) { static_cast<AudioWorkletPipeCallbacks*>(service)->unref(); } },- [](void* service, void* task, void (*invoke)(void*)) {- static_cast<AudioWorkletPipeCallbacks*>(service)->event_loop.deferred_invoke([task, invoke] { invoke(task); });- },- [](void* service) {- auto& callbacks = *static_cast<AudioWorkletPipeCallbacks*>(service);- if (callbacks.pump_callback)- callbacks.pump_callback();- },- };- RustFFI::WorkletPipeConfig native_config { m_config.quantum_size, m_config.input_count, m_config.output_count, m_config.input_channel_capacity.span(), m_config.output_channel_capacity.span(), m_config.output_channel_count_matches_input, m_config.param_count, m_config.param_is_a_rate.span(), m_config.ring_capacity, m_config.prime_level };- m_pipe = RustFFI::web_audio_worklet_pipe_create(native_config, callbacks);-}--AudioWorkletPipe::~AudioWorkletPipe() { RustFFI::web_audio_worklet_pipe_destroy(m_pipe); }-AudioWorkletPipe::Config::RingSizing AudioWorkletPipe::Config::ring_sizing_for_device_latency(u32 latency, float sample_rate, size_t quantum_size)-{- RingSizing sizing;- RustFFI::web_audio_worklet_pipe_ring_sizing(latency, sample_rate, quantum_size, &sizing.ring_capacity, &sizing.prime_level);- return sizing;-}--bool AudioWorkletPipe::try_push_input(Function<void(InputSlotWriter&)> const& callback)-{- struct Context {- AudioWorkletPipe& pipe;- Function<void(InputSlotWriter&)> const& callback;- } context { *this, callback };- return RustFFI::web_audio_worklet_pipe_transfer(m_pipe, false, true, &context, [](void* pointer, u8* slot) {- auto& context = *static_cast<Context*>(pointer);- InputSlotWriter view { context.pipe, slot };- context.callback(view);- });-}--bool AudioWorkletPipe::try_pop_input(Function<void(InputSlotReader const&)> const& callback)-{- struct Context {- AudioWorkletPipe& pipe;- Function<void(InputSlotReader const&)> const& callback;- } context { *this, callback };- return RustFFI::web_audio_worklet_pipe_transfer(m_pipe, false, false, &context, [](void* pointer, u8* slot) {- auto& context = *static_cast<Context*>(pointer);- InputSlotReader view { context.pipe, slot };- context.callback(view);- });-}--bool AudioWorkletPipe::try_push_output(Function<void(OutputSlotWriter&)> const& callback)-{- struct Context {- AudioWorkletPipe& pipe;- Function<void(OutputSlotWriter&)> const& callback;- } context { *this, callback };- return RustFFI::web_audio_worklet_pipe_transfer(m_pipe, true, true, &context, [](void* pointer, u8* slot) {- auto& context = *static_cast<Context*>(pointer);- OutputSlotWriter view { context.pipe, slot };- context.callback(view);- });-}--bool AudioWorkletPipe::try_pop_output(Function<void(OutputSlotReader const&)> const& callback)-{- struct Context {- AudioWorkletPipe& pipe;- Function<void(OutputSlotReader const&)> const& callback;- } context { *this, callback };- return RustFFI::web_audio_worklet_pipe_transfer(m_pipe, true, false, &context, [](void* pointer, u8* slot) {- auto& context = *static_cast<Context*>(pointer);- OutputSlotReader view { context.pipe, slot };- context.callback(view);- });-}--size_t AudioWorkletPipe::output_occupancy() const { return RustFFI::web_audio_worklet_pipe_output_occupancy(m_pipe); }-void AudioWorkletPipe::discard_outputs_down_to(size_t target) { RustFFI::web_audio_worklet_pipe_discard(m_pipe, target); }-void AudioWorkletPipe::prime_outputs_with_silence(size_t count) { RustFFI::web_audio_worklet_pipe_prime(m_pipe, count); }-void AudioWorkletPipe::request_wakeup() { RustFFI::web_audio_worklet_pipe_request_wakeup(m_pipe); }-void AudioWorkletPipe::clear_wakeup_flag() { RustFFI::web_audio_worklet_pipe_clear_wakeup(m_pipe); }-void AudioWorkletPipe::set_pump_callback(Function<void()> callback) { m_callbacks->pump_callback = move(callback); }-void AudioWorkletPipe::clear_pump_callback() { m_callbacks->pump_callback = nullptr; }-AudioWorkletPipe::State AudioWorkletPipe::state() const { return static_cast<State>(RustFFI::web_audio_worklet_pipe_state(m_pipe)); }-void AudioWorkletPipe::set_state(State state) { RustFFI::web_audio_worklet_pipe_set_state(m_pipe, static_cast<RustFFI::WorkletPipeState>(state)); }-u64 AudioWorkletPipe::underrun_count() const { return RustFFI::web_audio_worklet_pipe_counter(m_pipe, false); }-u64 AudioWorkletPipe::dropped_input_count() const { return RustFFI::web_audio_worklet_pipe_counter(m_pipe, true); }--u64& AudioWorkletPipe::InputSlotWriter::start_frame() { return *RustFFI::web_audio_worklet_slot_frame(m_slot); }-void AudioWorkletPipe::InputSlotWriter::set_had_gap(bool value) { RustFFI::web_audio_worklet_slot_set_flag(m_slot, value); }-u32& AudioWorkletPipe::InputSlotWriter::actual_channel_count(size_t index) { return *RustFFI::web_audio_worklet_slot_count(m_pipe.m_pipe, m_slot, false, index); }-Span<float> AudioWorkletPipe::InputSlotWriter::input_channel(size_t index, size_t channel)-{- Span<float> samples;- RustFFI::web_audio_worklet_slot_channel(m_pipe.m_pipe, m_slot, false, index, channel, &samples);- return samples;-}-Span<float> AudioWorkletPipe::InputSlotWriter::param_block(size_t param)-{- Span<float> samples;- RustFFI::web_audio_worklet_slot_param(m_pipe.m_pipe, m_slot, param, &samples);- return samples;-}--u64 AudioWorkletPipe::InputSlotReader::start_frame() const { return *RustFFI::web_audio_worklet_slot_frame(const_cast<u8*>(m_slot)); }-bool AudioWorkletPipe::InputSlotReader::had_gap() const { return RustFFI::web_audio_worklet_slot_flag(m_slot); }-u32 AudioWorkletPipe::InputSlotReader::actual_channel_count(size_t index) const { return *RustFFI::web_audio_worklet_slot_count(m_pipe.m_pipe, const_cast<u8*>(m_slot), false, index); }-ReadonlySpan<float> AudioWorkletPipe::InputSlotReader::input_channel(size_t index, size_t channel) const-{- Span<float> samples;- RustFFI::web_audio_worklet_slot_channel(m_pipe.m_pipe, const_cast<u8*>(m_slot), false, index, channel, &samples);- return samples;-}-ReadonlySpan<float> AudioWorkletPipe::InputSlotReader::param_block(size_t param) const-{- Span<float> samples;- RustFFI::web_audio_worklet_slot_param(m_pipe.m_pipe, const_cast<u8*>(m_slot), param, &samples);- return samples;-}--u64& AudioWorkletPipe::OutputSlotWriter::start_frame() { return *RustFFI::web_audio_worklet_slot_frame(m_slot); }-void AudioWorkletPipe::OutputSlotWriter::set_processor_active(bool value) { RustFFI::web_audio_worklet_slot_set_flag(m_slot, value); }-u32& AudioWorkletPipe::OutputSlotWriter::actual_channel_count(size_t index) { return *RustFFI::web_audio_worklet_slot_count(m_pipe.m_pipe, m_slot, true, index); }-Span<float> AudioWorkletPipe::OutputSlotWriter::output_channel(size_t index, size_t channel)-{- Span<float> samples;- RustFFI::web_audio_worklet_slot_channel(m_pipe.m_pipe, m_slot, true, index, channel, &samples);- return samples;-}--u64 AudioWorkletPipe::OutputSlotReader::start_frame() const { return *RustFFI::web_audio_worklet_slot_frame(const_cast<u8*>(m_slot)); }-bool AudioWorkletPipe::OutputSlotReader::processor_active() const { return RustFFI::web_audio_worklet_slot_flag(m_slot); }-u32 AudioWorkletPipe::OutputSlotReader::actual_channel_count(size_t index) const { return *RustFFI::web_audio_worklet_slot_count(m_pipe.m_pipe, const_cast<u8*>(m_slot), true, index); }-ReadonlySpan<float> AudioWorkletPipe::OutputSlotReader::output_channel(size_t index, size_t channel) const-{- Span<float> samples;- RustFFI::web_audio_worklet_slot_channel(m_pipe.m_pipe, const_cast<u8*>(m_slot), true, index, channel, &samples);- return samples;-}--}diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.h b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.hdeleted file mode 100644index 321590a2157..00000000000--- a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.h+++ /dev/null@@ -1,216 +0,0 @@-/*- * Copyright (c) 2026, Ali Mohammad Pur <[email protected]>- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Atomic.h>-#include <AK/AtomicRefCounted.h>-#include <AK/FixedArray.h>-#include <AK/Function.h>-#include <AK/NonnullRefPtr.h>-#include <AK/Platform.h>-#include <AK/Span.h>-#include <AK/StdLibExtras.h>-#include <AK/Types.h>-#include <AK/Vector.h>-#include <LibCore/Forward.h>-#include <LibWeb/Export.h>--namespace Web::WebAudio::Rendering {--// A lock-free bridge between the realtime render node and the main-thread processor. Two SPSC rings share a-// preallocated arena; underruns render silence and a full input ring drops quanta. Each ring uses acquire/release-// head-tail discipline, and the slot stride is configured at run time.-//-// Per-slot layout; strides are rounded up to 64 bytes so slots start cache-line-aligned relative to the arena:-//-// Input slot Output slot-// u64 start_frame u64 start_frame-// u32 flags (bit 0: gap before this quantum) u32 flags (bit 0: processor active; bit 1: reserved-// u32 actual_channel_count[input_count] for a per-quantum processing-error signal)-// f32 samples[input_channel_capacity[0]][quantum_size] u32 actual_channel_count[output_count]-// ... one sample block per input ... f32 samples[output_channel_capacity[0]][quantum_size]-// f32 param_block[param_count]: quantum_size samples ... one sample block per output ...-// each for a-rate parameters, 1 for k-rate-//-// Slots are accessed in place through the writer/reader views below, which are only valid inside the callback they-// are passed to. A slot's unwritten regions keep stale data from the previous trip around the ring, so a writer-// must set the channel counts it wants a reader to trust; the flags are cleared on every push.-struct AudioWorkletPipeCallbacks;--class WEB_API AudioWorkletPipe final : public AtomicRefCounted<AudioWorkletPipe> {-public:- struct Config {- size_t quantum_size { 0 };- float sample_rate { 0 };- u32 input_count { 0 };- u32 output_count { 0 };- Vector<u32> input_channel_capacity; // Per input: the largest channel count a slot can carry.- Vector<u32> output_channel_capacity; // Per output: the largest channel count a slot can carry.- bool output_channel_count_matches_input { false };- u32 param_count { 0 };- Vector<bool> param_is_a_rate; // Per parameter: a-rate blocks carry quantum_size samples, k-rate blocks one.- size_t ring_capacity { 0 }; // Slots per ring; must be a power of two.- size_t prime_level { 0 }; // Silent output quanta pushed before rendering starts; at most ring_capacity.-- struct RingSizing {- size_t ring_capacity { 0 };- size_t prime_level { 0 };- };- static WEB_API RingSizing ring_sizing_for_device_latency(u32 device_latency_ms, float sample_rate, size_t quantum_size);- };-- enum class State : u8 {- Running,- Failed,- ShutDown,- };-- class InputSlotWriter {- public:- u64& start_frame();- void set_had_gap(bool);- u32& actual_channel_count(size_t input);- Span<float> input_channel(size_t input, size_t channel);- Span<float> param_block(size_t param);-- private:- friend class AudioWorkletPipe;- InputSlotWriter(AudioWorkletPipe const& pipe, u8* slot)- : m_pipe(pipe)- , m_slot(slot)- {- }-- AudioWorkletPipe const& m_pipe;- u8* m_slot { nullptr };- };-- class InputSlotReader {- public:- u64 start_frame() const;- bool had_gap() const;- u32 actual_channel_count(size_t input) const;- ReadonlySpan<float> input_channel(size_t input, size_t channel) const;- ReadonlySpan<float> param_block(size_t param) const;-- private:- friend class AudioWorkletPipe;- InputSlotReader(AudioWorkletPipe const& pipe, u8 const* slot)- : m_pipe(pipe)- , m_slot(slot)- {- }-- AudioWorkletPipe const& m_pipe;- u8 const* m_slot { nullptr };- };-- class OutputSlotWriter {- public:- u64& start_frame();- void set_processor_active(bool);- u32& actual_channel_count(size_t output);- Span<float> output_channel(size_t output, size_t channel);-- private:- friend class AudioWorkletPipe;- OutputSlotWriter(AudioWorkletPipe const& pipe, u8* slot)- : m_pipe(pipe)- , m_slot(slot)- {- }-- AudioWorkletPipe const& m_pipe;- u8* m_slot { nullptr };- };-- class OutputSlotReader {- public:- u64 start_frame() const;- bool processor_active() const;- u32 actual_channel_count(size_t output) const;- ReadonlySpan<float> output_channel(size_t output, size_t channel) const;-- private:- friend class AudioWorkletPipe;- OutputSlotReader(AudioWorkletPipe const& pipe, u8 const* slot)- : m_pipe(pipe)- , m_slot(slot)- {- }-- AudioWorkletPipe const& m_pipe;- u8 const* m_slot { nullptr };- };-- static NonnullRefPtr<AudioWorkletPipe> create(Config, Core::EventLoop& main_thread_event_loop);-- ~AudioWorkletPipe();- void const* rust_pipe() const { return m_pipe; }-- Config const& config() const { return m_config; }-- // Audio-thread side (input producer, output consumer):-- // Fills the next input slot in place. Returns false, and counts a dropped quantum, when the ring is full; the- // caller should then mark the next successful push with set_had_gap() so the processor can tell that quanta- // went missing.- bool try_push_input(Function<void(InputSlotWriter&)> const& fill);-- // Reads the oldest processed quantum. Returns false, and counts an underrun, when none is ready; the caller- // then outputs silence, never blocking the audio callback.- bool try_pop_output(Function<void(OutputSlotReader const&)> const& read);-- size_t output_occupancy() const;-- // Drops the oldest processed quanta until at most target_occupancy remain. After a main-thread stall the pump- // catches up and refills the output ring past the prime level; clamping back down keeps the pipe's added- // latency from ratcheting up permanently.- void discard_outputs_down_to(size_t target_occupancy);-- // Schedules the pump on the main thread's event loop. Coalesced: only the first request after- // clear_wakeup_flag() posts an event, so a device burst of several dozen quanta causes one pump run.- void request_wakeup();-- // Main-thread side (input consumer, output producer):-- bool try_pop_input(Function<void(InputSlotReader const&)> const& read);- bool try_push_output(Function<void(OutputSlotWriter&)> const& fill);-- // Pushes `count` silent, processor-active output quanta. Called on the control thread before the pipe is handed- // to the render node, so the audio thread has a burst worth of lookahead before the first processed quantum.- void prime_outputs_with_silence(size_t count);-- // The pump calls this before draining the input ring, so a burst that lands while the pump is running schedules- // another run instead of being lost.- void clear_wakeup_flag();-- // Accessed only on the control thread, including by deferred wakeups.- void set_pump_callback(Function<void()>);- void clear_pump_callback();-- // Either thread:-- State state() const;- void set_state(State);-- // A single atomic store, so this is safe to call from a GC finalizer on either thread.- void request_shutdown() { set_state(State::ShutDown); }-- u64 underrun_count() const;- u64 dropped_input_count() const;--private:- AudioWorkletPipe(Config, Core::EventLoop& main_thread_event_loop);-- Config m_config;- NonnullRefPtr<AudioWorkletPipeCallbacks> m_callbacks;- void const* m_pipe { nullptr };-};--}diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txtindex cfe1aa83221..0a394715e23 100644--- a/Tests/LibWeb/CMakeLists.txt+++ b/Tests/LibWeb/CMakeLists.txt@@ -12,7 +12,6 @@ ladybird_test_suite(LibWeb)set(TEST_SOURCESBenchmarkDisplayListRecording.cpp- TestAudioWorkletPipe.cppTestBlobBytes.cppTestContentBlocker.cppTestCSSDecodeBytes.cppdiff --git a/Tests/LibWeb/TestAudioWorkletPipe.cpp b/Tests/LibWeb/TestAudioWorkletPipe.cppdeleted file mode 100644index 1ce3d7ffc84..00000000000--- a/Tests/LibWeb/TestAudioWorkletPipe.cpp+++ /dev/null@@ -1,405 +0,0 @@-/*- * Copyright (c) 2026, Ali Mohammad Pur <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Atomic.h>-#include <AK/BuiltinWrappers.h>-#include <AK/Math.h>-#include <AK/Optional.h>-#include <AK/Random.h>-#include <AK/Vector.h>-#include <LibCore/EventLoop.h>-#include <LibCore/System.h>-#include <LibCore/Timer.h>-#include <LibTest/TestCase.h>-#include <LibThreading/Thread.h>-#include <LibWeb/WebAudio/Rendering/AudioWorkletPipe.h>--using Web::WebAudio::Rendering::AudioWorkletPipe;--static constexpr size_t QUANTUM_SIZE = 128;-static constexpr size_t RING_CAPACITY = 64;-static constexpr size_t PRIME_LEVEL = 48;-static constexpr size_t BURST_QUANTA = 38;--static AudioWorkletPipe::Config test_config()-{- return {- .quantum_size = QUANTUM_SIZE,- .sample_rate = 48000.0f,- .input_count = 1,- .output_count = 1,- .input_channel_capacity = { 2 },- .output_channel_capacity = { 2 },- .param_count = 2,- .param_is_a_rate = { true, false },- .ring_capacity = RING_CAPACITY,- .prime_level = PRIME_LEVEL,- };-}--TEST_CASE(ring_sizing_matches_renderer_defaults)-{- auto sizing = AudioWorkletPipe::Config::ring_sizing_for_device_latency(100, 48000.0f, 128);- EXPECT_EQ(sizing.ring_capacity, 64u);- EXPECT_EQ(sizing.prime_level, 48u);-- for (u32 latency_ms : { 10u, 20u, 50u, 100u, 200u, 500u }) {- auto s = AudioWorkletPipe::Config::ring_sizing_for_device_latency(latency_ms, 48000.0f, 128);- auto burst = static_cast<size_t>(AK::ceil(latency_ms / 1000.0 * 48000.0 / 128));- EXPECT(s.prime_level >= burst);- EXPECT(s.ring_capacity > s.prime_level);- EXPECT_EQ(popcount(s.ring_capacity), 1);- }-}--TEST_CASE(pops_on_empty_rings_fail)-{- Core::EventLoop event_loop;- auto pipe = AudioWorkletPipe::create(test_config(), event_loop);-- EXPECT(!pipe->try_pop_input([](auto const&) { VERIFY_NOT_REACHED(); }));- EXPECT(!pipe->try_pop_output([](auto const&) { VERIFY_NOT_REACHED(); }));-- // Only the audio thread's output pops count as underruns; an empty input ring just means the pump caught up.- EXPECT_EQ(pipe->underrun_count(), 1u);- EXPECT_EQ(pipe->dropped_input_count(), 0u);- EXPECT_EQ(pipe->output_occupancy(), 0u);-}--TEST_CASE(input_ring_roundtrip_fill_to_capacity_and_overrun)-{- Core::EventLoop event_loop;- auto pipe = AudioWorkletPipe::create(test_config(), event_loop);-- for (size_t i = 0; i < RING_CAPACITY; ++i) {- bool pushed = pipe->try_push_input([&](AudioWorkletPipe::InputSlotWriter& slot) {- slot.start_frame() = i * QUANTUM_SIZE;- if (i == 3)- slot.set_had_gap(true);- slot.actual_channel_count(0) = static_cast<u32>(i % 3);- for (u32 channel = 0; channel < i % 3; ++channel) {- auto samples = slot.input_channel(0, channel);- EXPECT_EQ(samples.size(), QUANTUM_SIZE);- for (size_t frame = 0; frame < samples.size(); ++frame)- samples[frame] = static_cast<float>(i * 10 + channel) + static_cast<float>(frame) * 0.25f;- }- EXPECT_EQ(slot.param_block(0).size(), QUANTUM_SIZE);- EXPECT_EQ(slot.param_block(1).size(), 1u);- for (size_t frame = 0; frame < QUANTUM_SIZE; ++frame)- slot.param_block(0)[frame] = static_cast<float>(i) + static_cast<float>(frame) * 0.5f;- slot.param_block(1)[0] = static_cast<float>(i);- });- EXPECT(pushed);- }-- EXPECT(!pipe->try_push_input([](auto&) { VERIFY_NOT_REACHED(); }));- EXPECT_EQ(pipe->dropped_input_count(), 1u);-- for (size_t i = 0; i < RING_CAPACITY; ++i) {- bool popped = pipe->try_pop_input([&](AudioWorkletPipe::InputSlotReader const& slot) {- EXPECT_EQ(slot.start_frame(), i * QUANTUM_SIZE);- EXPECT_EQ(slot.had_gap(), i == 3);- EXPECT_EQ(slot.actual_channel_count(0), i % 3);- for (u32 channel = 0; channel < i % 3; ++channel) {- auto samples = slot.input_channel(0, channel);- EXPECT_EQ(samples[0], static_cast<float>(i * 10 + channel));- EXPECT_EQ(samples[QUANTUM_SIZE - 1], static_cast<float>(i * 10 + channel) + (QUANTUM_SIZE - 1) * 0.25f);- }- EXPECT_EQ(slot.param_block(0)[0], static_cast<float>(i));- EXPECT_EQ(slot.param_block(0)[QUANTUM_SIZE - 1], static_cast<float>(i) + (QUANTUM_SIZE - 1) * 0.5f);- EXPECT_EQ(slot.param_block(1)[0], static_cast<float>(i));- });- EXPECT(popped);- }- EXPECT(!pipe->try_pop_input([](auto const&) { VERIFY_NOT_REACHED(); }));-- // Wrap around into the same storage: flags are cleared on push, so slot 3's gap flag must not leak through.- for (size_t i = 0; i < RING_CAPACITY; ++i) {- EXPECT(pipe->try_push_input([&](AudioWorkletPipe::InputSlotWriter& slot) {- slot.start_frame() = (RING_CAPACITY + i) * QUANTUM_SIZE;- slot.actual_channel_count(0) = 0;- }));- }- for (size_t i = 0; i < RING_CAPACITY; ++i) {- EXPECT(pipe->try_pop_input([&](AudioWorkletPipe::InputSlotReader const& slot) {- EXPECT_EQ(slot.start_frame(), (RING_CAPACITY + i) * QUANTUM_SIZE);- EXPECT(!slot.had_gap());- }));- }-- EXPECT_EQ(pipe->dropped_input_count(), 1u);- EXPECT_EQ(pipe->underrun_count(), 0u);-}--TEST_CASE(output_ring_roundtrip)-{- Core::EventLoop event_loop;- auto pipe = AudioWorkletPipe::create(test_config(), event_loop);-- for (size_t i = 0; i < 5; ++i) {- EXPECT(pipe->try_push_output([&](AudioWorkletPipe::OutputSlotWriter& slot) {- slot.start_frame() = i * QUANTUM_SIZE;- slot.set_processor_active(i % 2 == 0);- slot.actual_channel_count(0) = 2;- for (u32 channel = 0; channel < 2; ++channel)- slot.output_channel(0, channel).fill(static_cast<float>(i * 10 + channel));- }));- }- EXPECT_EQ(pipe->output_occupancy(), 5u);-- for (size_t i = 0; i < 5; ++i) {- EXPECT(pipe->try_pop_output([&](AudioWorkletPipe::OutputSlotReader const& slot) {- EXPECT_EQ(slot.start_frame(), i * QUANTUM_SIZE);- EXPECT_EQ(slot.processor_active(), i % 2 == 0);- EXPECT_EQ(slot.actual_channel_count(0), 2u);- for (u32 channel = 0; channel < 2; ++channel) {- EXPECT_EQ(slot.output_channel(0, channel)[0], static_cast<float>(i * 10 + channel));- EXPECT_EQ(slot.output_channel(0, channel)[QUANTUM_SIZE - 1], static_cast<float>(i * 10 + channel));- }- }));- }- EXPECT_EQ(pipe->underrun_count(), 0u);-}--TEST_CASE(priming_and_discard_down_to)-{- Core::EventLoop event_loop;- auto pipe = AudioWorkletPipe::create(test_config(), event_loop);-- pipe->prime_outputs_with_silence(PRIME_LEVEL);- EXPECT_EQ(pipe->output_occupancy(), PRIME_LEVEL);-- bool popped = pipe->try_pop_output([&](AudioWorkletPipe::OutputSlotReader const& slot) {- EXPECT_EQ(slot.start_frame(), 0u);- EXPECT(slot.processor_active());- EXPECT_EQ(slot.actual_channel_count(0), 2u);- for (u32 channel = 0; channel < 2; ++channel) {- for (auto sample : slot.output_channel(0, channel))- EXPECT_EQ(sample, 0.0f);- }- });- EXPECT(popped);- EXPECT_EQ(pipe->output_occupancy(), PRIME_LEVEL - 1);-- pipe->discard_outputs_down_to(10);- EXPECT_EQ(pipe->output_occupancy(), 10u);-- pipe->discard_outputs_down_to(20);- EXPECT_EQ(pipe->output_occupancy(), 10u);-- pipe->discard_outputs_down_to(0);- EXPECT_EQ(pipe->output_occupancy(), 0u);- EXPECT_EQ(pipe->underrun_count(), 0u);-}--TEST_CASE(state_transitions)-{- Core::EventLoop event_loop;- auto pipe = AudioWorkletPipe::create(test_config(), event_loop);-- EXPECT(pipe->state() == AudioWorkletPipe::State::Running);- pipe->set_state(AudioWorkletPipe::State::Failed);- EXPECT(pipe->state() == AudioWorkletPipe::State::Failed);- pipe->request_shutdown();- EXPECT(pipe->state() == AudioWorkletPipe::State::ShutDown);-}--TEST_CASE(wakeup_coalescing)-{- Core::EventLoop event_loop;- auto pipe = AudioWorkletPipe::create(test_config(), event_loop);-- size_t pump_runs = 0;- pipe->set_pump_callback([&] { ++pump_runs; });-- pipe->request_wakeup();- pipe->request_wakeup();- pipe->request_wakeup();- event_loop.spin_until([&] { return pump_runs > 0; });- // Give any (incorrectly) duplicated wakeups a chance to run.- event_loop.pump(Core::EventLoop::WaitMode::PollForEvents);- EXPECT_EQ(pump_runs, 1u);-- pipe->clear_wakeup_flag();- pipe->request_wakeup();- event_loop.spin_until([&] { return pump_runs > 1; });- EXPECT_EQ(pump_runs, 2u);-- pipe->clear_wakeup_flag();- pipe->request_shutdown();- pipe->request_wakeup();- event_loop.pump(Core::EventLoop::WaitMode::PollForEvents);- EXPECT_EQ(pump_runs, 2u);-}--TEST_CASE(two_thread_stress)-{- Core::EventLoop event_loop;- auto config = test_config();- auto pipe = AudioWorkletPipe::create(config, event_loop);- pipe->prime_outputs_with_silence(PRIME_LEVEL);-- static constexpr size_t BURST_COUNT = 20;- static constexpr u64 FIRST_STAMP = QUANTUM_SIZE; // Primed slots are stamped 0; real quanta start one quantum in.-- u64 quanta_processed = 0;- pipe->set_pump_callback([&] {- pipe->clear_wakeup_flag();- MUST(Core::System::sleep_ms(get_random_uniform(11)));- while (pipe->try_pop_input([&](AudioWorkletPipe::InputSlotReader const& input) {- bool pushed = pipe->try_push_output([&](AudioWorkletPipe::OutputSlotWriter& output) {- output.start_frame() = input.start_frame();- output.set_processor_active(true);- output.actual_channel_count(0) = input.actual_channel_count(0);- auto gain = input.param_block(1)[0];- for (u32 channel = 0; channel < input.actual_channel_count(0); ++channel) {- auto source = input.input_channel(0, channel);- auto destination = output.output_channel(0, channel);- for (size_t frame = 0; frame < source.size(); ++frame)- destination[frame] = source[frame] * gain;- }- });- EXPECT(pushed);- ++quanta_processed;- })) { }- });-- IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> producer_done { false };- IGNORE_USE_IN_ESCAPING_LAMBDA Vector<u64> popped_stamps;- popped_stamps.ensure_capacity(BURST_COUNT * BURST_QUANTA + PRIME_LEVEL);- IGNORE_USE_IN_ESCAPING_LAMBDA u64 sample_mismatches = 0;- IGNORE_USE_IN_ESCAPING_LAMBDA u64 failed_output_pops = 0;- IGNORE_USE_IN_ESCAPING_LAMBDA u64 successful_input_pushes = 0;-- auto producer = Threading::Thread::construct("AudioWorkletBurst"sv, [&, producer_pipe = NonnullRefPtr(*pipe)]() -> intptr_t {- u64 next_frame = FIRST_STAMP;- for (size_t burst = 0; burst < BURST_COUNT; ++burst) {- for (size_t quantum = 0; quantum < BURST_QUANTA; ++quantum) {- bool popped = producer_pipe->try_pop_output([&](AudioWorkletPipe::OutputSlotReader const& output) {- auto stamp = output.start_frame();- popped_stamps.unchecked_append(stamp);- // Primed slots are silent; processed ones echo the value the producer filled in below.- for (u32 channel = 0; channel < output.actual_channel_count(0); ++channel) {- auto expected = stamp == 0 ? 0.0f : static_cast<float>(stamp / QUANTUM_SIZE + channel);- if (output.output_channel(0, channel)[0] != expected)- ++sample_mismatches;- }- });- if (!popped)- ++failed_output_pops;- bool pushed = producer_pipe->try_push_input([&](AudioWorkletPipe::InputSlotWriter& input) {- input.start_frame() = next_frame;- input.actual_channel_count(0) = 2;- for (u32 channel = 0; channel < 2; ++channel)- input.input_channel(0, channel).fill(static_cast<float>(next_frame / QUANTUM_SIZE + channel));- input.param_block(0).fill(0.5f);- input.param_block(1)[0] = 1.0f;- });- if (pushed)- ++successful_input_pushes;- next_frame += QUANTUM_SIZE;- }- producer_pipe->request_wakeup();- MUST(Core::System::sleep_ms(100));- }- producer_done.store(true);- return 0;- });- producer->start();-- IGNORE_USE_IN_ESCAPING_LAMBDA Core::EventLoop& loop = event_loop;- auto quit_timer = Core::Timer::create_repeating(AK::Duration::from_milliseconds(25), [&] {- if (producer_done.load())- loop.quit(0);- });- quit_timer->start();- event_loop.exec();- MUST(producer->join());-- u64 pending_input = 0;- while (pipe->try_pop_input([&](AudioWorkletPipe::InputSlotReader const&) {- ++pending_input;- })) { }-- EXPECT_EQ(sample_mismatches, 0u);- EXPECT_EQ(failed_output_pops + popped_stamps.size(), BURST_COUNT * BURST_QUANTA);- EXPECT_EQ(successful_input_pushes + pipe->dropped_input_count(), BURST_COUNT * BURST_QUANTA);- EXPECT_EQ(quanta_processed + pending_input, successful_input_pushes);-- // The FIFO order guarantees all primed (stamp 0) slots come out before any processed quantum, and processed- // stamps are observed in increasing quantum order.- size_t primed_popped = 0;- while (primed_popped < popped_stamps.size() && popped_stamps[primed_popped] == 0)- ++primed_popped;- EXPECT(primed_popped <= PRIME_LEVEL);- Optional<u64> previous_stamp;- for (size_t i = primed_popped; i < popped_stamps.size(); ++i) {- auto stamp = popped_stamps[i];- EXPECT(stamp >= FIRST_STAMP);- EXPECT_EQ((stamp - FIRST_STAMP) % QUANTUM_SIZE, 0u);- if (previous_stamp.has_value())- EXPECT(stamp > previous_stamp.value());- previous_stamp = stamp;- }-}--TEST_CASE(teardown_when_producer_drops_its_reference_mid_run)-{- Core::EventLoop event_loop;- auto config = test_config();- auto pipe = AudioWorkletPipe::create(config, event_loop);- pipe->prime_outputs_with_silence(PRIME_LEVEL);-- u64 quanta_processed = 0;- pipe->set_pump_callback([&] {- pipe->clear_wakeup_flag();- if (pipe->state() != AudioWorkletPipe::State::Running)- return;- while (pipe->try_pop_input([&](AudioWorkletPipe::InputSlotReader const& input) {- (void)pipe->try_push_output([&](AudioWorkletPipe::OutputSlotWriter& output) {- output.start_frame() = input.start_frame();- output.set_processor_active(true);- output.actual_channel_count(0) = 0;- });- ++quanta_processed;- })) { }- });-- IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> producer_done { false };- auto producer = Threading::Thread::construct("AudioWorkletTeardown"sv, [&, producer_pipe = RefPtr<AudioWorkletPipe>(pipe)]() mutable -> intptr_t {- u64 next_frame = QUANTUM_SIZE;- for (size_t burst = 0; burst < 3; ++burst) {- for (size_t quantum = 0; quantum < BURST_QUANTA; ++quantum) {- producer_pipe->try_pop_output([](auto const&) { });- (void)producer_pipe->try_push_input([&](AudioWorkletPipe::InputSlotWriter& input) {- input.start_frame() = next_frame;- input.actual_channel_count(0) = 0;- });- next_frame += QUANTUM_SIZE;- }- producer_pipe->request_wakeup();- MUST(Core::System::sleep_ms(30));- }- producer_pipe->request_shutdown();- producer_pipe = nullptr;- producer_done.store(true);- return 0;- });- producer->start();-- IGNORE_USE_IN_ESCAPING_LAMBDA Core::EventLoop& loop = event_loop;- auto quit_timer = Core::Timer::create_repeating(AK::Duration::from_milliseconds(10), [&] {- if (producer_done.load())- loop.quit(0);- });- quit_timer->start();- event_loop.exec();- MUST(producer->join());-- EXPECT(pipe->state() == AudioWorkletPipe::State::ShutDown);- EXPECT_EQ(pipe->dropped_input_count(), 0u);- EXPECT(quanta_processed > 0);-}