Skip to content

Truly independent web browser

LibWeb: Let WebAudio contexts own their Rust renderers

Shannon Bootha361b30140ac
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs
index bb971012332..eadfc9d8239 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs
@@ -8,12 +8,14 @@
use std::cell::{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::{GcRefCell, Trace, Value, Vm};
+use libjs_rust::api::{CellRoot, EmbedderCell, GcRefCell, Trace, Value, Vm};
use libweb_rust::web_audio::control_message::FfiSharedCppObject;
use libweb_rust::web_audio::rendering::node_message::SharedCppObject;
+use libweb_rust::web_audio::rendering::realtime_audio_renderer::{RealtimeAudioRenderer, RealtimeAudioRendererClient};
use super::audio_destination_node::AudioDestinationNode;
use super::audio_listener::AudioListener;
@@ -27,7 +29,7 @@ use crate::bindings::cpp_cell::CppCell;
use crate::bindings::event_target::{CppEventTarget, GetTheParent};
use crate::bindings::global_object::window_from_global_object;
use crate::bindings::interface::with_temporary_execution_context_and_callbacks;
-use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, Wrapped, allocate};
use crate::bindings::promise::{
WebIdlPromise, promise_realm, reject_promise, reject_promise_with_exception, resolve_promise,
};
@@ -68,7 +70,7 @@ pub(crate) struct AudioContext {
pending_resume_promises: GcRefCell<Vec<WebIdlPromise>>,
suspended_by_user: Cell<bool>,
#[gc(untraced)]
- renderer: RefCell<Option<SharedCppObject>>,
+ renderer: RefCell<Option<Arc<RealtimeAudioRenderer>>>,
}
impl Inherits<BaseAudioContext> for AudioContext {
@@ -87,10 +89,8 @@ impl Wrappable for AudioContext {
fn finalize(context: Ref<Self>) {
context.context.shutdown_audio_worklet();
if let Some(renderer) = &*context.renderer.borrow() {
- unsafe {
- web_audio_realtime_context_stop(renderer.pointer);
- web_audio_realtime_context_clear_callbacks(renderer.pointer);
- }
+ renderer.stop();
+ renderer.set_client(None);
}
}
}
@@ -102,23 +102,23 @@ impl GetTheParent for AudioContext {
}
unsafe extern "C" {
- fn web_audio_realtime_context_create(
- global: *mut c_void,
- queue: *const c_void,
- destination: u64,
- sample_rate: f32,
- ) -> FfiSharedCppObject;
- fn web_audio_realtime_context_set_callbacks(renderer: *mut c_void, context: *mut c_void);
- fn web_audio_realtime_context_start(renderer: *mut c_void);
- fn web_audio_realtime_context_resume(renderer: *mut c_void);
- fn web_audio_realtime_context_suspend(renderer: *mut c_void);
- fn web_audio_realtime_context_stop(renderer: *mut c_void);
- fn web_audio_realtime_context_clear_callbacks(renderer: *mut c_void);
- fn web_audio_realtime_context_frames_rendered(renderer: *mut c_void) -> u64;
- fn web_audio_realtime_context_output_time(renderer: *mut c_void) -> f64;
+ fn web_audio_output_factory_create(global: *mut c_void) -> FfiSharedCppObject;
fn web_audio_realtime_context_performance_now(global: *mut c_void) -> f64;
}
+struct RendererClient {
+ vm: NonNull<Vm>,
+ context: CellRoot<EmbedderCell<Wrapped<AudioContext>>>,
+}
+
+impl RealtimeAudioRendererClient for RendererClient {
+ fn sources_ended(&self, nodes: &[u64]) {
+ // SAFETY: The VM of the control thread outlives its audio contexts.
+ let vm = unsafe { self.vm.as_ref() };
+ self.context.cell().context.handle_ended_sources(vm, nodes);
+ }
+}
+
impl AudioContext {
fn this(&self) -> Ref<Self> {
let AnyBaseAudioContext::AudioContext(context) = self.context.this() else {
@@ -214,21 +214,21 @@ impl AudioContext {
// FIXME: 1. Let document be the current settings object's relevant global object's associated Document.
// 2. Attempt to acquire system resources to use a following audio output device based on [[sink ID]] for
// rendering.
- let renderer = unsafe {
- web_audio_realtime_context_create(
- context.context.global_event_target().as_ptr(),
- Arc::as_ptr(context.context.control_message_queue()).cast(),
- context.context.destination_value().parent().node_id(),
- context.context.sample_rate_value(),
- )
- };
- *context.renderer.borrow_mut() = Some(SharedCppObject {
- pointer: renderer.pointer,
- retain: renderer.retain,
- release: renderer.release,
- });
- context.set_renderer_callbacks();
- unsafe { web_audio_realtime_context_start(renderer.pointer) };
+ let factory = unsafe { web_audio_output_factory_create(context.context.global_event_target().as_ptr()) };
+ let renderer = RealtimeAudioRenderer::new(
+ Arc::clone(context.context.control_message_queue()),
+ context.context.destination_value().parent().node_id(),
+ context.context.sample_rate_value(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ SharedCppObject {
+ pointer: factory.pointer,
+ retain: factory.retain,
+ release: factory.release,
+ },
+ );
+ *context.renderer.borrow_mut() = Some(Arc::clone(&renderer));
+ context.set_renderer_client(cx.vm());
+ renderer.start_rendering();
// 2. Set this [[rendering thread state]] to running on the AudioContext.
context.context.set_rendering_state(AudioContextState::Running);
@@ -254,10 +254,8 @@ impl AudioContext {
// navigated-away document stops playing and can eventually be collected.
self.context.shutdown_audio_worklet();
if let Some(renderer) = &*self.renderer.borrow() {
- unsafe {
- web_audio_realtime_context_stop(renderer.pointer);
- web_audio_realtime_context_clear_callbacks(renderer.pointer);
- }
+ renderer.stop();
+ renderer.set_client(None);
}
}
@@ -266,8 +264,7 @@ impl AudioContext {
// This is the time in seconds of the sample frame immediately following the last sample-frame in the block of
// audio most recently processed by the context's rendering graph.
if let Some(renderer) = &*self.renderer.borrow() {
- return unsafe { web_audio_realtime_context_frames_rendered(renderer.pointer) } as f64
- / f64::from(self.context.sample_rate_value());
+ return renderer.frames_rendered() as f64 / f64::from(self.context.sample_rate_value());
}
0.
}
@@ -283,10 +280,11 @@ impl AudioContext {
// https://www.w3.org/TR/webaudio/#dom-audiocontext-getoutputtimestamp
pub(crate) fn get_output_timestamp(&self, _: &mut CallContext) -> WebIdlResult<AudioTimestamp> {
let renderer = self.renderer.borrow();
- if renderer
- .as_ref()
- .is_none_or(|renderer| unsafe { web_audio_realtime_context_frames_rendered(renderer.pointer) } == 0)
- {
+
+ // If the context's rendering graph has not yet processed a block of audio, then
+ // getOutputTimestamp call returns an AudioTimestamp instance with both members
+ // containing zero.
+ if renderer.as_ref().is_none_or(|renderer| renderer.frames_rendered() == 0) {
return Ok(AudioTimestamp {
context_time: Some(0.),
performance_time: Some(0.),
@@ -297,7 +295,7 @@ impl AudioContext {
// We sample performance.now() when getOutputTimestamp() is called instead of caching a timestamp when the
// renderer produced that block, so the returned pair does not describe a single output instant.
Ok(AudioTimestamp {
- context_time: Some(unsafe { web_audio_realtime_context_output_time(renderer.as_ref().unwrap().pointer) }),
+ context_time: Some(renderer.as_ref().unwrap().output_time_played()),
performance_time: Some(unsafe {
web_audio_realtime_context_performance_now(self.context.global_event_target().as_ptr())
}),
@@ -348,7 +346,7 @@ impl AudioContext {
// 7.1: Attempt to acquire system resources.
// NB: The renderer acquires system resources and starts rendering in a single resume, performed in step 7.3.
if self.renderer.borrow().is_some() {
- self.set_renderer_callbacks();
+ self.set_renderer_client(vm);
}
// 7.2: Set the [[rendering thread state]] on the AudioContext to running.
@@ -450,10 +448,8 @@ impl AudioContext {
fn run_control_message_to_suspend(&self, vm: &Vm, promise: WebIdlPromise) {
// 7.1: Attempt to release system resources.
if let Some(renderer) = &*self.renderer.borrow() {
- unsafe {
- web_audio_realtime_context_suspend(renderer.pointer);
- web_audio_realtime_context_clear_callbacks(renderer.pointer);
- }
+ renderer.suspend();
+ renderer.set_client(None);
}
// 7.2: Set the [[rendering thread state]] on the AudioContext to suspended.
@@ -515,10 +511,8 @@ impl AudioContext {
// 5.1: Attempt to release system resources.
self.context.shutdown_audio_worklet();
if let Some(renderer) = &*self.renderer.borrow() {
- unsafe {
- web_audio_realtime_context_stop(renderer.pointer);
- web_audio_realtime_context_clear_callbacks(renderer.pointer);
- }
+ renderer.stop();
+ renderer.set_client(None);
}
// 5.2: Set the [[rendering thread state]] to "suspended".
@@ -546,16 +540,23 @@ impl AudioContext {
fn start_rendering_audio_graph(&self) -> bool {
if let Some(renderer) = &*self.renderer.borrow() {
- unsafe { web_audio_realtime_context_resume(renderer.pointer) };
+ renderer.resume();
}
true
}
- fn set_renderer_callbacks(&self) {
- let renderer = self.renderer.borrow();
- unsafe {
- web_audio_realtime_context_set_callbacks(renderer.as_ref().unwrap().pointer, cell_into_abi(self.this()));
- };
+ // The renderer's callback captures a GC root on this context, keeping it alive while it renders. That root is released
+ // by clearing the callbacks when the context is suspended, closed, or its document becomes inactive, so this is called
+ // again to re-establish it whenever rendering resumes.
+ fn set_renderer_client(&self, vm: &Vm) {
+ self.renderer
+ .borrow()
+ .as_ref()
+ .unwrap()
+ .set_client(Some(Rc::new(RendererClient {
+ vm: NonNull::from(vm),
+ context: CellRoot::new(self.this()),
+ })));
}
// https://webaudio.github.io/web-audio-api/#dom-audiocontext-createmediaelementsource
@@ -584,12 +585,3 @@ impl AudioContext {
MediaStreamAudioDestinationNode::create(cx, self.this(), &AudioNodeOptions::default())
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_audio_context_sources_ended(
- vm: &Vm,
- cell: *mut c_void,
- ids: ak::Span<'_, u64>,
-) {
- unsafe { AnyBaseAudioContext::from_abi(cell) }.handle_ended_sources(vm, ids.as_slice());
-}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs
index 6369952ae89..eae1fe08c0d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs
@@ -11,12 +11,12 @@
use std::cell::{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::{GcRefCell, Trace, Value, Vm};
-use libweb_rust::web_audio::control_message::FfiSharedCppObject;
-use libweb_rust::web_audio::rendering::node_message::SharedCppObject;
+use libjs_rust::api::{CellRoot, EmbedderCell, GcRefCell, PromiseCapability, Trace, Value, Vm};
+use libweb_rust::web_audio::rendering::offline_audio_renderer::{OfflineAudioRenderer, OfflineAudioRendererClient};
use super::audio_array::overwrite_float32_array;
use super::audio_buffer::AudioBuffer;
@@ -29,11 +29,9 @@ use crate::bindings::cpp_cell::CppCell;
use crate::bindings::event_target::{CppEvent, CppEventTarget, GetTheParent};
use crate::bindings::global_object::window_from_global_object;
use crate::bindings::interface::{
- Inherits, Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, with_temporary_execution_context_and_callbacks,
-};
-use crate::bindings::promise::{
- WebIdlPromise, promise_from_abi, promise_realm, reject_promise_with_exception, resolve_promise,
+ Inherits, Ref, Wrappable, Wrapped, allocate, with_temporary_execution_context_and_callbacks,
};
+use crate::bindings::promise::{WebIdlPromise, promise_realm, reject_promise_with_exception, resolve_promise};
use crate::bindings::{CallContext, Exception, WebIdlResult};
pub(crate) struct OfflineAudioContextOptions {
@@ -52,7 +50,9 @@ pub(crate) struct OfflineAudioContext {
rendering_started: Cell<bool>,
rendered_buffer: Cell<Option<Ref<AudioBuffer>>>,
#[gc(untraced)]
- renderer: RefCell<Option<SharedCppObject>>,
+ renderer: RefCell<Option<Arc<OfflineAudioRenderer>>>,
+
+ // https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-suspend, keyed by suspend frame.
suspend_promises: GcRefCell<Vec<(u64, WebIdlPromise)>>,
}
@@ -74,22 +74,33 @@ impl GetTheParent for OfflineAudioContext {
}
}
-unsafe extern "C" {
- fn web_audio_offline_context_create(
- queue: *const c_void,
- destination: u64,
- channels: u32,
- length: u32,
- sample_rate: f32,
- ) -> FfiSharedCppObject;
- fn web_audio_offline_context_set_callbacks(renderer: *mut c_void, context: *mut c_void, promise: *mut c_void);
- fn web_audio_offline_context_start(renderer: *mut c_void);
- fn web_audio_offline_context_resume(renderer: *mut c_void);
- fn web_audio_offline_context_stop(renderer: *mut c_void);
- fn web_audio_offline_context_clear_callbacks(renderer: *mut c_void);
- fn web_audio_offline_context_request_suspend(renderer: *mut c_void, frame: u64) -> bool;
- fn web_audio_offline_context_frames_rendered(renderer: *mut c_void) -> u64;
- fn web_audio_offline_context_channel(renderer: *mut c_void, channel: usize, samples: *mut ak::Span<'_, f32>);
+struct RendererClient {
+ vm: NonNull<Vm>,
+ context: CellRoot<EmbedderCell<Wrapped<OfflineAudioContext>>>,
+ promise: CellRoot<PromiseCapability>,
+}
+
+impl RendererClient {
+ fn vm(&self) -> &Vm {
+ // SAFETY: The VM of the control thread outlives its audio contexts.
+ unsafe { self.vm.as_ref() }
+ }
+}
+
+impl OfflineAudioRendererClient for RendererClient {
+ fn rendering_suspended(&self, suspend_time: f64) {
+ self.context.cell().handle_suspended(self.vm(), suspend_time);
+ }
+
+ fn rendering_completed(&self, rendered_channels: &[Vec<f32>]) {
+ self.context
+ .cell()
+ .finish_rendering(self.vm(), self.promise.cell(), rendered_channels);
+ }
+
+ fn sources_ended(&self, nodes: &[u64]) {
+ self.context.cell().context.handle_ended_sources(self.vm(), nodes);
+ }
}
impl OfflineAudioContext {
@@ -244,60 +255,48 @@ impl OfflineAudioContext {
// 1: Given the current connections and scheduled changes, start rendering length sample-frames of audio into [[rendered buffer]]
// 2: For every render quantum, check and suspend rendering if necessary.
// 3: If a suspended context is resumed, continue to render the buffer.
- let renderer = unsafe {
- web_audio_offline_context_create(
- Arc::as_ptr(self.context.control_message_queue()).cast(),
- self.context.destination_value().parent().node_id(),
- self.number_of_channels,
- self.length,
- self.context.sample_rate_value(),
- )
- };
- *self.renderer.borrow_mut() = Some(SharedCppObject {
- pointer: renderer.pointer,
- retain: renderer.retain,
- release: renderer.release,
- });
- unsafe {
- web_audio_offline_context_set_callbacks(
- renderer.pointer,
- cell_into_abi(self.this()),
- promise.as_ptr().cast(),
- );
- };
+ let renderer = OfflineAudioRenderer::new(
+ Arc::clone(self.context.control_message_queue()),
+ self.context.destination_value().parent().node_id(),
+ self.number_of_channels as usize,
+ self.length as usize,
+ self.context.sample_rate_value(),
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
+ );
+ *self.renderer.borrow_mut() = Some(Arc::clone(&renderer));
+ renderer.set_client(Some(Rc::new(RendererClient {
+ vm: NonNull::from(vm),
+ context: CellRoot::new(self.this()),
+ promise: CellRoot::new(promise),
+ })));
for (frame, _) in &*self.suspend_promises.borrow() {
- unsafe { web_audio_offline_context_request_suspend(renderer.pointer, *frame) };
+ renderer.request_suspend(*frame);
}
// AD-HOC: Other engines transition the context to "running" once rendering starts.
self.context.set_control_state(AudioContextState::Running);
self.context.set_rendering_state(AudioContextState::Running);
self.queue_a_statechange_event(vm);
- unsafe { web_audio_offline_context_start(renderer.pointer) };
+ renderer.start_rendering();
}
- fn finish_rendering(&self, vm: &Vm, promise: WebIdlPromise) {
+ fn finish_rendering(&self, vm: &Vm, promise: WebIdlPromise, rendered_channels: &[Vec<f32>]) {
+ // NB: Copy the rendered samples into [[rendered buffer]].
let buffer = self.rendered_buffer.get().expect("offline rendering has a buffer");
let mut cx = CallContext::new(vm, self.context.realm());
for channel_index in 0..self.number_of_channels {
let channel_data = AudioBuffer::get_channel_data(&buffer, &mut cx, channel_index)
.unwrap_or_else(|_| panic!("the rendered channel exists"));
- let mut samples = ak::Span::default();
- unsafe {
- web_audio_offline_context_channel(
- self.renderer.borrow().as_ref().unwrap().pointer,
- channel_index as usize,
- &raw mut samples,
- );
- };
- overwrite_float32_array(&channel_data, samples.as_slice());
+ overwrite_float32_array(&channel_data, &rendered_channels[channel_index as usize]);
}
// AD-HOC: Other engines transition the context to "closed" once rendering completes.
self.context.set_control_state(AudioContextState::Closed);
self.context.set_rendering_state(AudioContextState::Closed);
self.queue_a_statechange_event(vm);
- unsafe { web_audio_offline_context_clear_callbacks(self.renderer.borrow().as_ref().unwrap().pointer) };
+
+ // NB: Break the reference cycle between the renderer's callbacks and this context.
+ self.renderer.borrow().as_ref().unwrap().set_client(None);
// 4: Once the rendering is complete, queue a media element task to execute the following steps:
self.context
@@ -396,7 +395,8 @@ impl OfflineAudioContext {
);
return Ok(());
}
- unsafe { web_audio_offline_context_resume(self.renderer.borrow().as_ref().unwrap().pointer) };
+ self.renderer.borrow().as_ref().unwrap().resume();
+
// 4. Set the [[control thread state]] flag on the OfflineAudioContext to running.
self.context.set_control_state(AudioContextState::Running);
self.context.set_rendering_state(AudioContextState::Running);
@@ -432,7 +432,7 @@ impl OfflineAudioContext {
}
self.suspend_promises.borrow_mut(cx.vm()).push((frame, promise));
if let Some(renderer) = &*self.renderer.borrow() {
- if !unsafe { web_audio_offline_context_request_suspend(renderer.pointer, frame) } {
+ if !renderer.request_suspend(frame) {
self.suspend_promises
.borrow_mut(cx.vm())
.retain(|entry| entry.0 != frame);
@@ -450,8 +450,7 @@ impl OfflineAudioContext {
// This is the time in seconds of the sample frame immediately following the last sample-frame in the block of
// audio most recently processed by the context's rendering graph.
if let Some(renderer) = &*self.renderer.borrow() {
- return unsafe { web_audio_offline_context_frames_rendered(renderer.pointer) } as f64
- / f64::from(self.context.sample_rate_value());
+ return renderer.frames_rendered() as f64 / f64::from(self.context.sample_rate_value());
}
0.
}
@@ -464,26 +463,8 @@ impl OfflineAudioContext {
pub(crate) fn document_became_inactive(&self) {
if let Some(renderer) = &*self.renderer.borrow() {
- unsafe {
- web_audio_offline_context_stop(renderer.pointer);
- web_audio_offline_context_clear_callbacks(renderer.pointer);
- }
+ renderer.stop();
+ renderer.set_client(None);
}
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_offline_audio_context_complete(
- vm: &Vm,
- cell: *mut c_void,
- promise: *mut c_void,
-) {
- let context: Ref<OfflineAudioContext> = unsafe { cell_from_abi(cell) };
- context.finish_rendering(vm, unsafe { promise_from_abi(promise) });
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_offline_audio_context_suspended(vm: &Vm, cell: *mut c_void, time: f64) {
- let context: Ref<OfflineAudioContext> = unsafe { cell_from_abi(cell) };
- context.handle_suspended(vm, time);
-}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/script_processor_node.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/script_processor_node.rs
index d560b8dc46b..468aa66d42d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/script_processor_node.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/script_processor_node.rs
@@ -9,14 +9,16 @@ 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::Trace;
use libjs_rust::api::Vm;
-use libweb_rust::web_audio::control_message::FfiSharedCppObject;
-use libweb_rust::web_audio::rendering::node_message::SharedCppObject;
-use libweb_rust::web_audio::rendering::script_processor_pipe::{ScriptProcessorPipe, ScriptProcessorPipeConfig};
+use libjs_rust::api::{EmbedderCell, GcWeak};
+use libweb_rust::web_audio::rendering::script_processor_pipe::{
+ ScriptProcessorPipe, ScriptProcessorPipeClient, ScriptProcessorPipeConfig,
+};
use libweb_rust::web_audio::rendering::script_processor_render_node::create_script_processor_render_node;
use super::audio_buffer::AudioBuffer;
@@ -25,8 +27,8 @@ use super::audio_processing_event::AudioProcessingEvent;
use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
use crate::bindings::event_target::CppEvent;
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::with_temporary_execution_context_and_callbacks;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, Wrapped, allocate};
use crate::bindings::{CallContext, Exception, WebIdlResult};
// https://webaudio.github.io/web-audio-api/#ScriptProcessorNode
@@ -36,8 +38,6 @@ pub(crate) struct ScriptProcessorNode {
node: AudioNode,
#[gc(untraced)]
pipe: RefCell<Option<Arc<ScriptProcessorPipe>>>,
- #[gc(untraced)]
- pipe_service: RefCell<Option<SharedCppObject>>,
buffer_size: Cell<i32>,
number_of_input_channels: u8,
number_of_output_channels: u8,
@@ -57,10 +57,8 @@ impl Wrappable for ScriptProcessorNode {
const FINALIZES: bool = true;
fn finalize(node: Ref<Self>) {
- if let Some(service) = &*node.pipe_service.borrow() {
- unsafe { web_audio_script_processor_clear_callback(service.pointer) };
- }
if let Some(pipe) = &*node.pipe.borrow() {
+ pipe.set_client(None);
pipe.shut_down();
}
node.node.finalize_node();
@@ -73,13 +71,18 @@ impl GetTheParent for ScriptProcessorNode {
}
}
-unsafe extern "C" {
- fn web_audio_script_processor_create_pipe(
- node: *mut c_void,
- config: ScriptProcessorPipeConfig,
- pipe: *mut *const c_void,
- ) -> FfiSharedCppObject;
- fn web_audio_script_processor_clear_callback(service: *mut c_void);
+struct PipeClient {
+ vm: NonNull<Vm>,
+ node: GcWeak<EmbedderCell<Wrapped<ScriptProcessorNode>>>,
+}
+
+impl ScriptProcessorPipeClient for PipeClient {
+ fn process(&self, block: usize, start_frame: u64) {
+ if let Some(node) = self.node.get() {
+ // SAFETY: The VM of the control thread outlives its audio nodes.
+ node.process_block(unsafe { self.vm.as_ref() }, block, start_frame);
+ }
+ }
}
// Other engines have a latency of two buffers. A realtime context needs more when the device pulls a burst of audio
@@ -114,7 +117,6 @@ impl ScriptProcessorNode {
number_of_output_channels: number_of_output_channels as u8,
buffer_size: Cell::new(0),
pipe: RefCell::new(None),
- pipe_service: RefCell::new(None),
});
script_processor_node
.node
@@ -136,24 +138,11 @@ impl ScriptProcessorNode {
block_count: block_count_for_context(context, buffer_size as usize),
waits_for_processing: matches!(context, AnyBaseAudioContext::OfflineAudioContext(_)),
};
- let mut native_pipe = std::ptr::null();
- let service = unsafe {
- web_audio_script_processor_create_pipe(
- cell_into_abi(script_processor_node),
- pipe_config,
- &raw mut native_pipe,
- )
- };
- let native_pipe = native_pipe.cast::<ScriptProcessorPipe>();
- unsafe {
- Arc::increment_strong_count(native_pipe);
- }
- let pipe = unsafe { Arc::from_raw(native_pipe) };
- *script_processor_node.pipe_service.borrow_mut() = Some(SharedCppObject {
- pointer: service.pointer,
- retain: service.retain,
- release: service.release,
- });
+ let pipe = ScriptProcessorPipe::new(pipe_config);
+ pipe.set_client(Some(Rc::new(PipeClient {
+ vm: NonNull::from(cx.vm()),
+ node: GcWeak::new(cx.vm().heap(), script_processor_node),
+ })));
*script_processor_node.pipe.borrow_mut() = Some(Arc::clone(&pipe));
context.add_script_processor_node(cx.vm(), script_processor_node);
script_processor_node
@@ -321,14 +310,3 @@ impl ScriptProcessorNode {
self.node.set_channel_count_mode_impl(channel_count_mode)
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_rust_script_processor_process(
- vm: &Vm,
- cell: *mut c_void,
- block: usize,
- start_frame: u64,
-) {
- let node: Ref<ScriptProcessorNode> = unsafe { cell_from_abi(cell) };
- node.process_block(vm, block, start_frame);
-}
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index ade6794afb1..3df8d8cec2a 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -934,12 +934,7 @@ set(SOURCES
WebAudio/MediaElementAudioSourceNode.cpp
WebAudio/MediaStreamAudioDestinationNode.cpp
WebAudio/MediaStreamAudioSourceNode.cpp
- WebAudio/OfflineAudioContext.cpp
WebAudio/Rendering/AudioWorkletPipe.cpp
- WebAudio/Rendering/OfflineAudioRenderer.cpp
- WebAudio/Rendering/RealtimeAudioRenderer.cpp
- WebAudio/Rendering/ScriptProcessorPipe.cpp
- WebAudio/ScriptProcessorNode.cpp
WebDriver/Actions.cpp
WebDriver/BiDi/BiDi.cpp
WebDriver/BiDi/BrowsingContext.cpp
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index 8e269c6e793..053581385cf 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -2473,8 +2473,6 @@ fn main() -> Result<(), Box<dyn Error>> {
"NodeHandle",
"ControlMessageQueue",
"AudioWorkletPipe",
- "ScriptProcessorPipe",
- "OfflineAudioRenderer",
"RealtimeAudioRenderer",
] {
web_audio_config.export.rename.insert(name.into(), "void".into());
@@ -2496,11 +2494,9 @@ fn main() -> Result<(), Box<dyn Error>> {
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/script_processor_pipe.rs"),
- manifest_dir.join("src/web_audio/rendering/renderer_callbacks.rs"),
- manifest_dir.join("src/web_audio/rendering/offline_audio_renderer.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"),
],
&out_dir,
Path::new("WebAudio/RustFFI.h"),
diff --git a/Libraries/LibWeb/Rust/src/web_audio/control_thread.rs b/Libraries/LibWeb/Rust/src/web_audio/control_thread.rs
new file mode 100644
index 00000000000..1f1637b20be
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/web_audio/control_thread.rs
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::cell::RefCell;
+use std::ffi::c_void;
+use std::mem::ManuallyDrop;
+use std::ptr::NonNull;
+use std::thread::{self, ThreadId};
+
+unsafe extern "C" {
+ fn web_audio_current_event_loop() -> *mut c_void;
+ fn web_audio_deferred_invoke(event_loop: *mut c_void, task: *mut c_void, invoke: unsafe extern "C" fn(*mut c_void));
+}
+
+#[derive(Clone, Copy)]
+pub struct ControlThread {
+ event_loop: NonNull<c_void>,
+}
+
+// SAFETY: Core::EventLoop::deferred_invoke() may be called from any thread, and the control thread's event loop
+// outlives its audio contexts.
+unsafe impl Send for ControlThread {}
+unsafe impl Sync for ControlThread {}
+
+impl ControlThread {
+ pub fn current() -> Self {
+ Self {
+ event_loop: NonNull::new(unsafe { web_audio_current_event_loop() }).expect("the thread has an event loop"),
+ }
+ }
+
+ pub fn post<F: FnOnce() + Send + 'static>(self, task: F) {
+ unsafe extern "C" fn invoke<F: FnOnce()>(task: *mut c_void) {
+ let task = unsafe { Box::from_raw(task.cast::<F>()) };
+ task();
+ }
+ let task = Box::into_raw(Box::new(task));
+ unsafe {
+ web_audio_deferred_invoke(self.event_loop.as_ptr(), task.cast(), invoke::<F>);
+ }
+ }
+}
+
+pub struct ControlThreadCell<T> {
+ thread: ThreadId,
+ value: ManuallyDrop<RefCell<T>>,
+}
+
+// SAFETY: Every use of the value checks that it is on the thread that created the cell, and the value is only dropped
+// there.
+unsafe impl<T> Send for ControlThreadCell<T> {}
+unsafe impl<T> Sync for ControlThreadCell<T> {}
+
+impl<T> ControlThreadCell<T> {
+ pub fn new(value: T) -> Self {
+ Self {
+ thread: thread::current().id(),
+ value: ManuallyDrop::new(RefCell::new(value)),
+ }
+ }
+
+ fn value(&self) -> &RefCell<T> {
+ assert_eq!(
+ thread::current().id(),
+ self.thread,
+ "only the control thread uses this state"
+ );
+ &self.value
+ }
+
+ pub fn replace(&self, value: T) -> T {
+ self.value().replace(value)
+ }
+}
+
+impl<T: Clone> ControlThreadCell<T> {
+ pub fn get(&self) -> T {
+ self.value().borrow().clone()
+ }
+}
+
+impl<T> Drop for ControlThreadCell<T> {
+ fn drop(&mut self) {
+ if thread::current().id() == self.thread {
+ unsafe { ManuallyDrop::drop(&mut self.value) };
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/mod.rs b/Libraries/LibWeb/Rust/src/web_audio/mod.rs
index 43b9b1e62df..e34d032f037 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/mod.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/mod.rs
@@ -8,4 +8,5 @@
pub mod audio_param_timeline;
pub mod control_message;
pub mod control_message_queue;
+pub mod control_thread;
pub mod rendering;
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs
index 0b1357c21a2..eab47cedeb0 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs
@@ -20,7 +20,6 @@ mod tests;
pub mod offline_audio_renderer;
pub mod realtime_audio_renderer;
-pub mod renderer_callbacks;
pub mod audio_worklet_pipe;
pub mod pipe_callbacks;
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/offline_audio_renderer.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/offline_audio_renderer.rs
index a71fb133494..39ff0e72efd 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/offline_audio_renderer.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/offline_audio_renderer.rs
@@ -9,15 +9,20 @@
use std::cell::UnsafeCell;
use std::collections::HashSet;
-use std::ffi::c_void;
+use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use super::render_graph::RenderGraph;
use super::render_node::RenderContext;
-use super::renderer_callbacks::{CallbackService, RendererCallbacks};
-use crate::web_audio::control_message::clone_arc;
use crate::web_audio::control_message_queue::ControlMessageQueue;
+use crate::web_audio::control_thread::{ControlThread, ControlThreadCell};
+
+pub trait OfflineAudioRendererClient {
+ fn rendering_suspended(&self, suspend_time: f64);
+ fn rendering_completed(&self, rendered_channels: &[Vec<f32>]);
+ fn sources_ended(&self, nodes: &[u64]);
+}
#[derive(Default)]
struct SuspensionState {
@@ -31,6 +36,10 @@ struct SuspensionState {
shutting_down: bool,
}
+// Renders an OfflineAudioContext's graph on a dedicated rendering thread, which is created when rendering starts and
+// exits once the last render quantum has been processed. Progress is reported back to the control thread by posting
+// events to the main thread's event loop.
+// https://webaudio.github.io/web-audio-api/#OfflineAudioContext
pub struct OfflineAudioRenderer {
control_message_queue: Arc<ControlMessageQueue>,
destination_node_id: u64,
@@ -38,7 +47,8 @@ pub struct OfflineAudioRenderer {
length: usize,
sample_rate: f32,
quantum_size: usize,
- callbacks: CallbackService,
+ control_thread: ControlThread,
+ client: ControlThreadCell<Option<Rc<dyn OfflineAudioRendererClient>>>,
thread: UnsafeCell<Option<std::thread::Thread>>,
graph: UnsafeCell<RenderGraph>,
rendered_channels: UnsafeCell<Vec<Vec<f32>>>,
@@ -56,44 +66,45 @@ enum Notification {
SourcesEnded(Vec<u64>),
}
-struct ControlTask {
- renderer: Arc<OfflineAudioRenderer>,
- notification: Notification,
-}
-
impl OfflineAudioRenderer {
- fn new(
+ pub fn new(
control_message_queue: Arc<ControlMessageQueue>,
destination_node_id: u64,
number_of_channels: usize,
length: usize,
sample_rate: f32,
quantum_size: usize,
- callbacks: CallbackService,
- ) -> Self {
+ ) -> Arc<Self> {
let mut rendered_channels = Vec::new();
rendered_channels.resize_with(number_of_channels, Vec::new);
for channel in &mut rendered_channels {
channel.resize(length, 0.);
}
- Self {
+ Arc::new(Self {
control_message_queue,
destination_node_id,
number_of_channels,
length,
sample_rate,
quantum_size,
- callbacks,
+ control_thread: ControlThread::current(),
+ client: ControlThreadCell::new(None),
thread: UnsafeCell::new(None),
graph: UnsafeCell::new(RenderGraph::default()),
rendered_channels: UnsafeCell::new(rendered_channels),
frames_rendered: AtomicU64::new(0),
suspend_mutex: Mutex::new(SuspensionState::default()),
resume_signal: Condvar::new(),
- }
+ })
}
- unsafe fn start_rendering(self: &Arc<Self>) {
+ /// The callbacks below are set on the control thread before rendering starts and are always invoked on the control
+ /// thread. They are cleared once rendering completes to break the reference cycle with the context.
+ pub fn set_client(&self, client: Option<Rc<dyn OfflineAudioRendererClient>>) {
+ self.client.replace(client);
+ }
+
+ pub fn start_rendering(self: &Arc<Self>) {
assert!(unsafe { &*self.thread.get() }.is_none());
unsafe { &mut *self.graph.get() }.set_destination(self.destination_node_id);
let renderer = Arc::clone(self);
@@ -109,13 +120,16 @@ impl OfflineAudioRenderer {
drop(thread);
}
- fn stop(&self) {
+ /// Ends rendering without completing it, unblocking the rendering thread if it is waiting in a suspension.
+ pub fn stop(&self) {
let mut state = self.suspend_mutex.lock().unwrap();
state.shutting_down = true;
self.resume_signal.notify_all();
}
- fn request_suspend(&self, frame: u64) -> bool {
+ /// Registers a suspension at the given render quantum boundary. Returns false if the rendering thread already
+ /// looked for suspensions at that boundary.
+ pub fn request_suspend(&self, frame: u64) -> bool {
let mut state = self.suspend_mutex.lock().unwrap();
if frame < state.next_suspend_check_frame {
return false;
@@ -124,35 +138,31 @@ impl OfflineAudioRenderer {
true
}
- fn resume(&self) {
+ pub fn resume(&self) {
let mut state = self.suspend_mutex.lock().unwrap();
state.suspended = false;
self.resume_signal.notify_all();
}
+ pub fn frames_rendered(&self) -> u64 {
+ self.frames_rendered.load(Ordering::SeqCst)
+ }
+
fn post_to_control_thread(self: &Arc<Self>, notification: Notification) {
- unsafe extern "C" fn invoke(context: *mut c_void) {
- let task = unsafe { Box::from_raw(context.cast::<ControlTask>()) };
- let callbacks = &task.renderer.callbacks;
- match &task.notification {
- Notification::Complete => unsafe {
- (callbacks.callbacks.on_complete)(callbacks.owner.pointer);
- },
- Notification::Suspended(time) => unsafe {
- (callbacks.callbacks.on_suspended)(callbacks.owner.pointer, *time);
- },
- Notification::SourcesEnded(nodes) => unsafe {
- (callbacks.callbacks.on_sources_ended)(callbacks.owner.pointer, ak::Span::new(nodes));
- },
+ let renderer = Arc::clone(self);
+ self.control_thread.post(move || {
+ let Some(client) = renderer.client.get() else {
+ return;
+ };
+ match notification {
+ Notification::Complete => {
+ // SAFETY: The rendering thread posts the completion after its last write.
+ client.rendering_completed(unsafe { &*renderer.rendered_channels.get() });
+ }
+ Notification::Suspended(time) => client.rendering_suspended(time),
+ Notification::SourcesEnded(nodes) => client.sources_ended(&nodes),
}
- }
- let task = Box::into_raw(Box::new(ControlTask {
- renderer: Arc::clone(self),
- notification,
- }));
- unsafe {
- self.callbacks.post(task.cast(), invoke);
- }
+ });
}
fn render_thread_main(self: &Arc<Self>) {
@@ -211,73 +221,3 @@ impl OfflineAudioRenderer {
self.post_to_control_thread(Notification::Complete);
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_offline_renderer_create(
- queue: *const ControlMessageQueue,
- destination_node_id: u64,
- number_of_channels: usize,
- length: usize,
- sample_rate: f32,
- quantum_size: usize,
- callbacks: RendererCallbacks,
-) -> *const OfflineAudioRenderer {
- Arc::into_raw(Arc::new(OfflineAudioRenderer::new(
- unsafe { clone_arc(queue) },
- destination_node_id,
- number_of_channels,
- length,
- sample_rate,
- quantum_size,
- unsafe { CallbackService::new(callbacks) },
- )))
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_offline_renderer_destroy(renderer: *const OfflineAudioRenderer) {
- drop(unsafe { Arc::from_raw(renderer) });
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_offline_renderer_start(renderer: *const OfflineAudioRenderer) {
- let renderer = unsafe { clone_arc(renderer) };
- unsafe {
- renderer.start_rendering();
- }
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_offline_renderer_stop(renderer: *const OfflineAudioRenderer) {
- unsafe { &*renderer }.stop();
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_offline_renderer_resume(renderer: *const OfflineAudioRenderer) {
- unsafe { &*renderer }.resume();
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_offline_renderer_request_suspend(
- renderer: *const OfflineAudioRenderer,
- frame: u64,
-) -> bool {
- unsafe { &*renderer }.request_suspend(frame)
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_offline_renderer_frames_rendered(
- renderer: *const OfflineAudioRenderer,
-) -> u64 {
- unsafe { &*renderer }.frames_rendered.load(Ordering::SeqCst)
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_offline_renderer_channel(
- renderer: *const OfflineAudioRenderer,
- channel: usize,
- output: *mut ak::Span<'static, f32>,
-) {
- unsafe {
- *output = ak::Span::new(&(&*(*renderer).rendered_channels.get())[channel]);
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/pipe_callbacks.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/pipe_callbacks.rs
index bd71992abac..8b51fbe809b 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/pipe_callbacks.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/pipe_callbacks.rs
@@ -15,7 +15,6 @@ pub struct PipeCallbacks {
pub service: FfiSharedCppObject,
pub post_task: unsafe extern "C" fn(*mut c_void, *mut c_void, unsafe extern "C" fn(*mut c_void)),
pub on_wakeup: unsafe extern "C" fn(*mut c_void),
- pub on_process: unsafe extern "C" fn(*mut c_void, usize, u64) -> bool,
}
pub(crate) struct CallbackService {
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/realtime_audio_renderer.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/realtime_audio_renderer.rs
index 4f93a3344db..fcc4e9996aa 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/realtime_audio_renderer.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/realtime_audio_renderer.rs
@@ -8,15 +8,29 @@
#![allow(clippy::needless_range_loop, clippy::manual_memcpy)]
use std::cell::UnsafeCell;
use std::ffi::c_void;
-use std::sync::Arc;
+use std::rc::Rc;
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering, fence};
+use std::sync::{Arc, Mutex};
use super::audio_bus::AudioBus;
+use super::node_message::SharedCppObject;
use super::render_graph::RenderGraph;
use super::render_node::RenderContext;
-use super::renderer_callbacks::{CallbackService, RendererCallbacks};
-use crate::web_audio::control_message::clone_arc;
+use crate::web_audio::control_message::{FfiSharedCppObject, clone_arc};
use crate::web_audio::control_message_queue::ControlMessageQueue;
+use crate::web_audio::control_thread::{ControlThread, ControlThreadCell};
+
+unsafe extern "C" {
+ fn web_audio_output_open(factory: *mut c_void, renderer: *const c_void);
+ fn web_audio_output_resume(stream: *mut c_void);
+ fn web_audio_output_drain_and_suspend(stream: *mut c_void);
+ fn web_audio_output_discard_and_suspend(stream: *mut c_void);
+ fn web_audio_monotonic_now_nanoseconds() -> i64;
+}
+
+pub trait RealtimeAudioRendererClient {
+ fn sources_ended(&self, nodes: &[u64]);
+}
// The output buffer most recently handed to the stream, and when its first frame plays.
#[derive(Default)]
@@ -71,12 +85,19 @@ struct RenderState {
pending_samples: Vec<f32>,
}
+// Renders an AudioContext's graph in real time, pulled by the audio output device: the playback stream's data request
+// callback runs on the platform's audio thread and renders just enough render quanta to fill the device's buffer.
+// Progress is reported back to the control thread by posting events to the main thread's event loop.
+// https://webaudio.github.io/web-audio-api/#AudioContext
pub struct RealtimeAudioRenderer {
control_message_queue: Arc<ControlMessageQueue>,
destination_node_id: u64,
sample_rate: f32,
quantum_size: usize,
- callbacks: CallbackService,
+ audio_output_factory: SharedCppObject,
+ playback_stream: Mutex<Option<SharedCppObject>>,
+ control_thread: ControlThread,
+ client: ControlThreadCell<Option<Rc<dyn RealtimeAudioRendererClient>>>,
frames_rendered: AtomicU64,
suspended: AtomicBool,
shutting_down: AtomicBool,
@@ -88,25 +109,23 @@ pub struct RealtimeAudioRenderer {
// SAFETY: Only the audio thread mutates render state after the suspended stream's device configuration is recorded.
unsafe impl Send for RealtimeAudioRenderer {}
unsafe impl Sync for RealtimeAudioRenderer {}
-struct ControlTask {
- renderer: Arc<RealtimeAudioRenderer>,
- ended_nodes: Vec<u64>,
-}
-
impl RealtimeAudioRenderer {
- fn new(
+ pub fn new(
queue: Arc<ControlMessageQueue>,
destination_node_id: u64,
sample_rate: f32,
quantum_size: usize,
- callbacks: CallbackService,
- ) -> Self {
- Self {
+ audio_output_factory: SharedCppObject,
+ ) -> Arc<Self> {
+ Arc::new(Self {
control_message_queue: queue,
destination_node_id,
sample_rate,
quantum_size,
- callbacks,
+ audio_output_factory,
+ playback_stream: Mutex::new(None),
+ control_thread: ControlThread::current(),
+ client: ControlThreadCell::new(None),
frames_rendered: AtomicU64::new(0),
suspended: AtomicBool::new(false),
shutting_down: AtomicBool::new(false),
@@ -121,10 +140,87 @@ impl RealtimeAudioRenderer {
playhead: 0.,
pending_samples: Vec::new(),
}),
+ })
+ }
+
+ /// The callback is set on the control thread before rendering starts and is always invoked on the control thread. It
+ /// is cleared when the context closes to break the reference cycle with the context.
+ pub fn set_client(&self, client: Option<Rc<dyn RealtimeAudioRendererClient>>) {
+ self.client.replace(client);
+ }
+
+ pub fn start_rendering(self: &Arc<Self>) {
+ assert!(self.playback_stream.lock().unwrap().is_none());
+ unsafe { &mut *self.state.get() }
+ .graph
+ .set_destination(self.destination_node_id);
+
+ // The stream is created in a suspended state so the device configuration can be recorded before the first data
+ // request callback runs on the audio thread.
+ unsafe { web_audio_output_open(self.audio_output_factory.pointer, Arc::as_ptr(self).cast()) };
+ }
+
+ fn set_playback_stream(self: &Arc<Self>, stream: SharedCppObject, channel_count: usize, sample_rate: u32) {
+ if self.shutting_down.load(Ordering::SeqCst) {
+ unsafe { web_audio_output_discard_and_suspend(stream.pointer) };
+ return;
+ }
+ let state = unsafe { &mut *self.state.get() };
+ state.device_channel_count = channel_count;
+ self.device_sample_rate.store(sample_rate, Ordering::Relaxed);
+ state.device_bus = Some(Box::new(AudioBus::new(channel_count, self.quantum_size)));
+
+ // When the device sample rate differs from the context's, the rendered audio is resampled by advancing
+ // through the rendered frames at this rate.
+ state.playhead_step = f64::from(self.sample_rate) / f64::from(sample_rate);
+ *self.playback_stream.lock().unwrap() = Some(stream.clone());
+ if !self.suspended.load(Ordering::SeqCst) {
+ unsafe { web_audio_output_resume(stream.pointer) };
}
}
- fn output_time_played(&self, now_nanoseconds: i64) -> f64 {
+ fn playback_stream(&self) -> Option<SharedCppObject> {
+ self.playback_stream.lock().unwrap().clone()
+ }
+
+ // The device went away with the process behind it: a new stream picks the graph up where it stands.
+ fn output_lost(self: &Arc<Self>) {
+ if self.shutting_down.load(Ordering::SeqCst) {
+ return;
+ }
+ *self.playback_stream.lock().unwrap() = None;
+ self.start_rendering();
+ }
+
+ pub fn resume(&self) {
+ self.suspended.store(false, Ordering::SeqCst);
+ if let Some(stream) = self.playback_stream() {
+ unsafe { web_audio_output_resume(stream.pointer) };
+ }
+ }
+
+ pub fn suspend(&self) {
+ self.suspended.store(true, Ordering::SeqCst);
+ if let Some(stream) = self.playback_stream() {
+ unsafe { web_audio_output_drain_and_suspend(stream.pointer) };
+ }
+ }
+
+ pub fn stop(&self) {
+ self.shutting_down.store(true, Ordering::SeqCst);
+ let stream = self.playback_stream.lock().unwrap().take();
+ if let Some(stream) = stream {
+ unsafe { web_audio_output_discard_and_suspend(stream.pointer) };
+ }
+ }
+
+ pub fn frames_rendered(&self) -> u64 {
+ self.frames_rendered.load(Ordering::SeqCst)
+ }
+
+ /// The amount of audio the output device has played so far, in seconds.
+ pub fn output_time_played(&self) -> f64 {
+ let now_nanoseconds = unsafe { web_audio_monotonic_now_nanoseconds() };
let maybe_anchor = self.output_anchor.read();
let device_sample_rate = self.device_sample_rate.load(Ordering::Relaxed);
if maybe_anchor.is_none() || device_sample_rate == 0 {
@@ -214,66 +310,24 @@ impl RealtimeAudioRenderer {
.fetch_add(self.quantum_size as u64, Ordering::SeqCst);
let ended_nodes = state.graph.take_ended_nodes();
if !ended_nodes.is_empty() {
- unsafe extern "C" fn invoke(context: *mut c_void) {
- let task = unsafe { Box::from_raw(context.cast::<ControlTask>()) };
- let callbacks = &task.renderer.callbacks;
- unsafe {
- (callbacks.callbacks.on_sources_ended)(callbacks.owner.pointer, ak::Span::new(&task.ended_nodes));
+ let renderer = Arc::clone(self);
+ self.control_thread.post(move || {
+ if let Some(client) = renderer.client.get() {
+ client.sources_ended(&ended_nodes);
}
- }
- let task = Box::into_raw(Box::new(ControlTask {
- renderer: Arc::clone(self),
- ended_nodes,
- }));
- unsafe {
- self.callbacks.post(task.cast(), invoke);
- }
+ });
}
}
}
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_create(
- queue: *const ControlMessageQueue,
- destination_node_id: u64,
- sample_rate: f32,
- quantum_size: usize,
- callbacks: RendererCallbacks,
-) -> *const RealtimeAudioRenderer {
- Arc::into_raw(Arc::new(RealtimeAudioRenderer::new(
- unsafe { clone_arc(queue) },
- destination_node_id,
- sample_rate,
- quantum_size,
- unsafe { CallbackService::new(callbacks) },
- )))
+pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_retain(renderer: *const RealtimeAudioRenderer) {
+ unsafe { Arc::increment_strong_count(renderer) };
}
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_destroy(renderer: *const RealtimeAudioRenderer) {
- drop(unsafe { Arc::from_raw(renderer) });
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_prepare(renderer: *const RealtimeAudioRenderer) {
- let renderer = unsafe { &*renderer };
- unsafe { &mut *renderer.state.get() }
- .graph
- .set_destination(renderer.destination_node_id);
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_configure(
- renderer: *const RealtimeAudioRenderer,
- channel_count: usize,
- sample_rate: u32,
-) {
- let renderer = unsafe { &*renderer };
- let state = unsafe { &mut *renderer.state.get() };
- state.device_channel_count = channel_count;
- renderer.device_sample_rate.store(sample_rate, Ordering::Relaxed);
- state.device_bus = Some(Box::new(AudioBus::new(channel_count, renderer.quantum_size)));
- state.playhead_step = f64::from(renderer.sample_rate) / f64::from(sample_rate);
+pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_release(renderer: *const RealtimeAudioRenderer) {
+ unsafe { Arc::decrement_strong_count(renderer) };
}
#[unsafe(no_mangle)]
@@ -287,43 +341,18 @@ pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_fill(
}
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_frames_rendered(
+pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_output_opened(
renderer: *const RealtimeAudioRenderer,
-) -> u64 {
- unsafe { &*renderer }.frames_rendered.load(Ordering::SeqCst)
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_output_time(
- renderer: *const RealtimeAudioRenderer,
- now_nanoseconds: i64,
-) -> f64 {
- unsafe { &*renderer }.output_time_played(now_nanoseconds)
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_set_suspended(
- renderer: *const RealtimeAudioRenderer,
- suspended: bool,
+ stream: FfiSharedCppObject,
+ channel_count: usize,
+ sample_rate: u32,
) {
- unsafe { &*renderer }.suspended.store(suspended, Ordering::SeqCst);
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_is_suspended(
- renderer: *const RealtimeAudioRenderer,
-) -> bool {
- unsafe { &*renderer }.suspended.load(Ordering::SeqCst)
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_stop(renderer: *const RealtimeAudioRenderer) {
- unsafe { &*renderer }.shutting_down.store(true, Ordering::SeqCst);
+ let renderer = unsafe { clone_arc(renderer) };
+ let stream = unsafe { stream.acquire() }.expect("an opened output has a stream");
+ renderer.set_playback_stream(stream, channel_count, sample_rate);
}
#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_is_shutting_down(
- renderer: *const RealtimeAudioRenderer,
-) -> bool {
- unsafe { &*renderer }.shutting_down.load(Ordering::SeqCst)
+pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_output_lost(renderer: *const RealtimeAudioRenderer) {
+ unsafe { clone_arc(renderer) }.output_lost();
}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/renderer_callbacks.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/renderer_callbacks.rs
deleted file mode 100644
index 67795042ef8..00000000000
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/renderer_callbacks.rs
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-use std::ffi::c_void;
-
-use ak::Span;
-
-use super::node_message::SharedCppObject;
-use crate::web_audio::control_message::FfiSharedCppObject;
-
-#[derive(Clone, Copy)]
-#[repr(C)]
-pub struct RendererCallbacks {
- pub service: FfiSharedCppObject,
- pub post_task: unsafe extern "C" fn(*mut c_void, *mut c_void, unsafe extern "C" fn(*mut c_void)),
- pub on_complete: unsafe extern "C" fn(*mut c_void),
- pub on_suspended: unsafe extern "C" fn(*mut c_void, f64),
- pub on_sources_ended: unsafe extern "C" fn(*mut c_void, Span<'_, u64>),
-}
-
-pub(crate) struct CallbackService {
- pub owner: SharedCppObject,
- pub callbacks: RendererCallbacks,
-}
-
-// SAFETY: The service is atomically reference-counted, and callbacks run on its control-thread event loop.
-unsafe impl Send for CallbackService {}
-unsafe impl Sync for CallbackService {}
-impl CallbackService {
- pub(crate) unsafe fn new(callbacks: RendererCallbacks) -> Self {
- Self {
- owner: unsafe { callbacks.service.acquire() }.unwrap(),
- callbacks,
- }
- }
-
- pub(crate) unsafe fn post(&self, context: *mut c_void, invoke: unsafe extern "C" fn(*mut c_void)) {
- unsafe {
- (self.callbacks.post_task)(self.owner.pointer, context, invoke);
- }
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_pipe.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_pipe.rs
index f99b59f60fb..550d7669800 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_pipe.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_pipe.rs
@@ -6,14 +6,17 @@
*/
use std::cell::UnsafeCell;
-use std::ffi::c_void;
+use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
-use super::pipe_callbacks::{CallbackService, PipeCallbacks};
+use crate::web_audio::control_thread::{ControlThread, ControlThreadCell};
+
+pub trait ScriptProcessorPipeClient {
+ fn process(&self, block: usize, start_frame: u64);
+}
#[derive(Clone, Copy)]
-#[repr(C)]
pub struct ScriptProcessorPipeConfig {
pub buffer_size: usize,
pub input_channel_count: usize,
@@ -33,7 +36,8 @@ pub struct ScriptProcessorPipe {
input_samples: Box<[UnsafeCell<f32>]>,
output_samples: Box<[UnsafeCell<f32>]>,
blocks: Box<[Block]>,
- callbacks: CallbackService,
+ control_thread: ControlThread,
+ client: ControlThreadCell<Option<Rc<dyn ScriptProcessorPipeClient>>>,
mutex: Mutex<()>,
block_returned: Condvar,
is_shut_down: AtomicBool,
@@ -42,17 +46,15 @@ pub struct ScriptProcessorPipe {
// SAFETY: A block's acquire/release ownership flag transfers exclusive access to its sample ranges and output flag.
unsafe impl Send for ScriptProcessorPipe {}
unsafe impl Sync for ScriptProcessorPipe {}
-struct ProcessTask {
- pipe: Arc<ScriptProcessorPipe>,
- block: usize,
- start_frame: u64,
-}
-
impl ScriptProcessorPipe {
- fn new(config: ScriptProcessorPipeConfig, callbacks: CallbackService) -> Self {
+ // Moves a ScriptProcessorNode's blocks of buffer_size frames between the rendering thread and the control thread. The
+ // render node cycles through block_count blocks, so a block's output plays block_count blocks after its input was
+ // captured. A block the control thread has not handed back in time renders silence and drops its input, unless the
+ // rendering thread waits for processing.
+ pub fn new(config: ScriptProcessorPipeConfig) -> Arc<Self> {
assert!(config.buffer_size > 0);
assert!(config.block_count >= 2);
- Self {
+ Arc::new(Self {
config,
input_samples: (0..config.block_count * config.input_channel_count * config.buffer_size)
.map(|_| UnsafeCell::new(0.))
@@ -61,11 +63,16 @@ impl ScriptProcessorPipe {
.map(|_| UnsafeCell::new(0.))
.collect(),
blocks: (0..config.block_count).map(|_| Block::default()).collect(),
- callbacks,
+ control_thread: ControlThread::current(),
+ client: ControlThreadCell::new(None),
mutex: Mutex::new(()),
block_returned: Condvar::new(),
is_shut_down: AtomicBool::new(false),
- }
+ })
+ }
+
+ pub fn set_client(&self, client: Option<Rc<dyn ScriptProcessorPipeClient>>) {
+ self.client.replace(client);
}
/// # Safety
@@ -100,27 +107,14 @@ impl ScriptProcessorPipe {
self.blocks[block]
.is_owned_by_control_thread
.store(true, Ordering::Release);
- unsafe extern "C" fn invoke(task: *mut c_void) {
- let task = unsafe { Box::from_raw(task.cast::<ProcessTask>()) };
- let pipe = &task.pipe;
- let processed = !pipe.is_shut_down()
- && unsafe {
- (pipe.callbacks.callbacks.on_process)(pipe.callbacks.owner.pointer, task.block, task.start_frame)
- };
- if !processed {
- unsafe {
- pipe.hand_block_back_to_rendering_thread(task.block, false);
- }
+ let pipe = Arc::clone(self);
+ self.control_thread.post(move || {
+ let client = if pipe.is_shut_down() { None } else { pipe.client.get() };
+ match client {
+ Some(client) => client.process(block, start_frame),
+ None => unsafe { pipe.hand_block_back_to_rendering_thread(block, false) },
}
- }
- let task = Box::into_raw(Box::new(ProcessTask {
- pipe: Arc::clone(self),
- block,
- start_frame,
- }));
- unsafe {
- self.callbacks.post(task.cast(), invoke);
- }
+ });
if !self.config.waits_for_processing {
return;
}
@@ -155,18 +149,3 @@ impl ScriptProcessorPipe {
self.is_shut_down.load(Ordering::Acquire)
}
}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_script_pipe_create(
- config: ScriptProcessorPipeConfig,
- callbacks: PipeCallbacks,
-) -> *const ScriptProcessorPipe {
- Arc::into_raw(Arc::new(ScriptProcessorPipe::new(config, unsafe {
- CallbackService::new(callbacks)
- })))
-}
-
-#[unsafe(no_mangle)]
-pub(crate) unsafe extern "C" fn web_audio_script_pipe_destroy(pipe: *const ScriptProcessorPipe) {
- drop(unsafe { Arc::from_raw(pipe) });
-}
diff --git a/Libraries/LibWeb/WebAudio/AudioContext.cpp b/Libraries/LibWeb/WebAudio/AudioContext.cpp
index a9cac0876e2..c1d4cb88a00 100644
--- a/Libraries/LibWeb/WebAudio/AudioContext.cpp
+++ b/Libraries/LibWeb/WebAudio/AudioContext.cpp
@@ -1,56 +1,77 @@
/*
* Copyright (c) 2023, Luke Wilde <[email protected]>
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
+#include <AK/AtomicRefCounted.h>
+#include <AK/Time.h>
+#include <LibAudio/PlaybackStream.h>
#include <LibMedia/Sinks/AudioOutputFactory.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/DOM/Document.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/Performance.h>
#include <LibWeb/Page/Page.h>
-#include <LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h>
#include <LibWeb/WebAudio/RustFFI.h>
+
namespace Web::WebAudio {
-extern "C" void web_rust_audio_context_sources_ended(JSVM*, void*, ReadonlySpan<u64>);
-extern "C" RustFFI::FfiSharedCppObject web_audio_realtime_context_create(DOM::EventTarget*, void const*, u64, float);
-extern "C" void web_audio_realtime_context_set_callbacks(Rendering::RealtimeAudioRenderer*, Bindings::RustInterfaceCell*);
+static constexpr u32 TARGET_LATENCY_MS = 100;
+
+extern "C" RustFFI::FfiSharedCppObject web_audio_output_factory_create(DOM::EventTarget*);
extern "C" double web_audio_realtime_context_performance_now(DOM::EventTarget*);
-RustFFI::FfiSharedCppObject web_audio_realtime_context_create(DOM::EventTarget* global, void const* queue, u64 destination, float sample_rate)
+
+RustFFI::FfiSharedCppObject web_audio_output_factory_create(DOM::EventTarget* global)
{
auto factory = as<HTML::Window>(*global).page().client().create_audio_output_factory();
- auto renderer = Rendering::RealtimeAudioRenderer::create(queue, NodeID(destination), sample_rate, 128, move(factory));
- return { &renderer.leak_ref(), [](void* renderer) { static_cast<Rendering::RealtimeAudioRenderer*>(renderer)->ref(); }, [](void* renderer) { static_cast<Rendering::RealtimeAudioRenderer*>(renderer)->unref(); } };
+ return { &factory.leak_ref(), [](void* factory) { static_cast<Media::AudioOutputFactory*>(factory)->ref(); }, [](void* factory) { static_cast<Media::AudioOutputFactory*>(factory)->unref(); } };
}
-void web_audio_realtime_context_set_callbacks(Rendering::RealtimeAudioRenderer* renderer, Bindings::RustInterfaceCell* context)
+
+// Keeps the renderer alive for the callbacks of its stream.
+class RendererReference final : public AtomicRefCounted<RendererReference> {
+public:
+ explicit RendererReference(void const* renderer)
+ : m_renderer(renderer)
+ {
+ RustFFI::web_audio_realtime_renderer_retain(m_renderer);
+ }
+
+ ~RendererReference() { RustFFI::web_audio_realtime_renderer_release(m_renderer); }
+
+ void const* renderer() const { return m_renderer; }
+
+private:
+ void const* m_renderer { nullptr };
+};
+
+void RustFFI::web_audio_output_open(void* factory, void const* renderer)
{
- renderer->set_on_sources_ended([context = GC::make_root(*context)](Vector<NodeID> const& nodes) {
- Vector<u64> ids;
- ids.ensure_capacity(nodes.size());
- for (auto node : nodes)
- ids.unchecked_append(node.value());
- web_rust_audio_context_sources_ended(JS::HostABI::vm_to_abi(JS::VM::the()), context.ptr(), ids);
+ auto reference = adopt_ref(*new RendererReference(renderer));
+ auto promise = static_cast<Media::AudioOutputFactory*>(factory)->open_output(Audio::OutputState::Suspended, TARGET_LATENCY_MS, [reference](Span<float> buffer, MonotonicTime buffer_starts_playing_at) {
+ return buffer.trim(RustFFI::web_audio_realtime_renderer_fill(reference->renderer(), buffer, buffer_starts_playing_at.nanoseconds()));
});
+ promise->when_resolved([reference](NonnullRefPtr<Audio::PlaybackStream>& stream) {
+ stream->on_output_lost = [reference] { RustFFI::web_audio_realtime_renderer_output_lost(reference->renderer()); };
+ auto specification = stream->sample_specification();
+ RustFFI::FfiSharedCppObject shared_stream { stream.ptr(), [](void* stream) { static_cast<Audio::PlaybackStream*>(stream)->ref(); }, [](void* stream) { static_cast<Audio::PlaybackStream*>(stream)->unref(); } };
+ RustFFI::web_audio_realtime_renderer_output_opened(reference->renderer(), shared_stream, specification.channel_count(), specification.sample_rate());
+ });
+}
+
+void RustFFI::web_audio_output_resume(void* stream)
+{
+ static_cast<Audio::PlaybackStream*>(stream)->resume()->when_rejected([](auto&&) { });
+}
+void RustFFI::web_audio_output_drain_and_suspend(void* stream)
+{
+ static_cast<Audio::PlaybackStream*>(stream)->drain_buffer_and_suspend()->when_rejected([](auto&&) { });
+}
+void RustFFI::web_audio_output_discard_and_suspend(void* stream)
+{
+ static_cast<Audio::PlaybackStream*>(stream)->discard_buffer_and_suspend()->when_rejected([](auto&&) { });
}
+i64 RustFFI::web_audio_monotonic_now_nanoseconds() { return MonotonicTime::now().nanoseconds(); }
double web_audio_realtime_context_performance_now(DOM::EventTarget* global) { return as<HTML::Window>(*global).performance()->now(); }
-extern "C" void web_audio_realtime_context_start(Rendering::RealtimeAudioRenderer*);
-void web_audio_realtime_context_start(Rendering::RealtimeAudioRenderer* renderer) { renderer->start_rendering(); }
-extern "C" void web_audio_realtime_context_resume(Rendering::RealtimeAudioRenderer*);
-void web_audio_realtime_context_resume(Rendering::RealtimeAudioRenderer* renderer) { renderer->resume(); }
-extern "C" void web_audio_realtime_context_suspend(Rendering::RealtimeAudioRenderer*);
-void web_audio_realtime_context_suspend(Rendering::RealtimeAudioRenderer* renderer) { renderer->suspend(); }
-extern "C" void web_audio_realtime_context_stop(Rendering::RealtimeAudioRenderer*);
-void web_audio_realtime_context_stop(Rendering::RealtimeAudioRenderer* renderer) { renderer->stop(); }
-extern "C" void web_audio_realtime_context_clear_callbacks(Rendering::RealtimeAudioRenderer*);
-void web_audio_realtime_context_clear_callbacks(Rendering::RealtimeAudioRenderer* renderer) { renderer->clear_callbacks(); }
-extern "C" u64 web_audio_realtime_context_frames_rendered(Rendering::RealtimeAudioRenderer*);
-u64 web_audio_realtime_context_frames_rendered(Rendering::RealtimeAudioRenderer* renderer) { return renderer->frames_rendered(); }
-extern "C" double web_audio_realtime_context_output_time(Rendering::RealtimeAudioRenderer*);
-double web_audio_realtime_context_output_time(Rendering::RealtimeAudioRenderer* renderer) { return renderer->output_time_played(); }
}
diff --git a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp b/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp
index 9cb8a6422a2..a211496a957 100644
--- a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp
+++ b/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp
@@ -7,6 +7,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibCore/EventLoop.h>
#include <LibGC/Heap.h>
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/VM.h>
@@ -24,6 +25,7 @@
#include <LibWeb/WebAudio/AudioWorklet.h>
#include <LibWeb/WebAudio/AudioWorkletGlobalScope.h>
#include <LibWeb/WebAudio/BaseAudioContext.h>
+#include <LibWeb/WebAudio/RustFFI.h>
namespace Web::WebAudio {
@@ -52,6 +54,11 @@ extern "C" void web_audio_context_decoded_destroy(MediaClient::Client::DecodedAu
extern "C" void web_audio_context_decoded_metadata(MediaClient::Client::DecodedAudioData*, u32*, u64*, u32*);
extern "C" void web_audio_context_decoded_channel(MediaClient::Client::DecodedAudioData*, u32, ReadonlySpan<float>*);
extern "C" void web_audio_context_report_exception(JS::Realm*, JSValue);
+void* RustFFI::web_audio_current_event_loop() { return &Core::EventLoop::current(); }
+void RustFFI::web_audio_deferred_invoke(void* event_loop, void* task, void (*invoke)(void*))
+{
+ static_cast<Core::EventLoop*>(event_loop)->deferred_invoke([task, invoke] { invoke(task); });
+}
HTML::UniqueTaskSource* web_audio_context_create_task_source() { return new HTML::UniqueTaskSource; }
void web_audio_context_destroy_task_source(HTML::UniqueTaskSource* source) { delete source; }
void web_audio_context_queue_task(HTML::UniqueTaskSource* source, DOM::EventTarget* global, GC::Cell* cell, void (*invoke)(void*, void*))
diff --git a/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.cpp b/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.cpp
index a4a393d0fc9..3d18073d05a 100644
--- a/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.cpp
+++ b/Libraries/LibWeb/WebAudio/MediaStreamAudioDestinationNode.cpp
@@ -50,7 +50,6 @@ static void* create_render_node(u64 node_id, size_t quantum_size, size_t channel
if (shared_state.drain)
shared_state.drain();
},
- [](void*, size_t, u64) { return false; },
};
return RustFFI::web_audio_node_create_media_stream_destination(node_id, quantum_size, channel_count,
{ shared_state->ring.ptr(), [](void* ring) { static_cast<Audio::SpscAudioFrameRing*>(ring)->ref(); }, [](void* ring) { static_cast<Audio::SpscAudioFrameRing*>(ring)->unref(); } },
diff --git a/Libraries/LibWeb/WebAudio/OfflineAudioContext.cpp b/Libraries/LibWeb/WebAudio/OfflineAudioContext.cpp
deleted file mode 100644
index 0727f04a8dc..00000000000
--- a/Libraries/LibWeb/WebAudio/OfflineAudioContext.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2024, Shannon Booth <[email protected]>
- * Copyright (c) 2025, Ben Eidson <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h>
-#include <LibWeb/WebAudio/RustFFI.h>
-#include <LibWeb/WebIDL/Promise.h>
-namespace Web::WebAudio {
-
-extern "C" void web_rust_audio_context_sources_ended(JSVM*, void*, ReadonlySpan<u64>);
-extern "C" void web_rust_offline_audio_context_complete(JSVM*, void*, void*);
-extern "C" void web_rust_offline_audio_context_suspended(JSVM*, void*, double);
-extern "C" RustFFI::FfiSharedCppObject web_audio_offline_context_create(void const*, u64, u32, u32, float);
-extern "C" void web_audio_offline_context_set_callbacks(Rendering::OfflineAudioRenderer*, Bindings::RustInterfaceCell*, JS::PromiseCapability*);
-extern "C" bool web_audio_offline_context_request_suspend(Rendering::OfflineAudioRenderer*, u64);
-extern "C" void web_audio_offline_context_channel(Rendering::OfflineAudioRenderer*, size_t, ReadonlySpan<float>*);
-RustFFI::FfiSharedCppObject web_audio_offline_context_create(void const* queue, u64 destination, u32 channels, u32 length, float sample_rate)
-{
- auto renderer = Rendering::OfflineAudioRenderer::create(queue, NodeID(destination), channels, length, sample_rate, 128);
- return { &renderer.leak_ref(), [](void* renderer) { static_cast<Rendering::OfflineAudioRenderer*>(renderer)->ref(); }, [](void* renderer) { static_cast<Rendering::OfflineAudioRenderer*>(renderer)->unref(); } };
-}
-void web_audio_offline_context_set_callbacks(Rendering::OfflineAudioRenderer* renderer, Bindings::RustInterfaceCell* context, JS::PromiseCapability* promise)
-{
- renderer->set_on_complete([context = GC::make_root(*context), promise = GC::make_root(*promise)] { web_rust_offline_audio_context_complete(JS::HostABI::vm_to_abi(JS::VM::the()), context.ptr(), promise.ptr()); });
- renderer->set_on_suspended([context = GC::make_root(*context)](double time) { web_rust_offline_audio_context_suspended(JS::HostABI::vm_to_abi(JS::VM::the()), context.ptr(), time); });
- renderer->set_on_sources_ended([context = GC::make_root(*context)](Vector<NodeID> const& nodes) {
- Vector<u64> ids;
- ids.ensure_capacity(nodes.size());
- for (auto node : nodes)
- ids.unchecked_append(node.value());
- web_rust_audio_context_sources_ended(JS::HostABI::vm_to_abi(JS::VM::the()), context.ptr(), ids);
- });
-}
-bool web_audio_offline_context_request_suspend(Rendering::OfflineAudioRenderer* renderer, u64 frame) { return renderer->request_suspend(frame); }
-void web_audio_offline_context_channel(Rendering::OfflineAudioRenderer* renderer, size_t channel, ReadonlySpan<float>* samples) { *samples = renderer->rendered_channels()[channel]; }
-extern "C" void web_audio_offline_context_start(Rendering::OfflineAudioRenderer*);
-void web_audio_offline_context_start(Rendering::OfflineAudioRenderer* renderer) { renderer->start_rendering(); }
-extern "C" void web_audio_offline_context_resume(Rendering::OfflineAudioRenderer*);
-void web_audio_offline_context_resume(Rendering::OfflineAudioRenderer* renderer) { renderer->resume(); }
-extern "C" void web_audio_offline_context_stop(Rendering::OfflineAudioRenderer*);
-void web_audio_offline_context_stop(Rendering::OfflineAudioRenderer* renderer) { renderer->stop(); }
-extern "C" void web_audio_offline_context_clear_callbacks(Rendering::OfflineAudioRenderer*);
-void web_audio_offline_context_clear_callbacks(Rendering::OfflineAudioRenderer* renderer) { renderer->clear_callbacks(); }
-extern "C" u64 web_audio_offline_context_frames_rendered(Rendering::OfflineAudioRenderer*);
-u64 web_audio_offline_context_frames_rendered(Rendering::OfflineAudioRenderer* renderer) { return renderer->frames_rendered(); }
-
-}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.cpp b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.cpp
index b1cf79336ca..6ea14990412 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.cpp
@@ -39,7 +39,6 @@ AudioWorkletPipe::AudioWorkletPipe(Config config, Core::EventLoop& event_loop)
if (callbacks.pump_callback)
callbacks.pump_callback();
},
- [](void*, size_t, u64) { return false; },
};
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);
diff --git a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp b/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp
deleted file mode 100644
index 7f67fef1148..00000000000
--- a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCore/EventLoop.h>
-#include <LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h>
-#include <LibWeb/WebAudio/RustFFI.h>
-
-namespace Web::WebAudio::Rendering {
-
-struct OfflineAudioRendererCallbacks : AtomicRefCounted<OfflineAudioRendererCallbacks> {
- Core::EventLoop& event_loop { Core::EventLoop::current() };
- Function<void()> on_complete;
- Function<void(double)> on_suspended;
- Function<void(Vector<NodeID> const&)> on_sources_ended;
-};
-
-NonnullRefPtr<OfflineAudioRenderer> OfflineAudioRenderer::create(void const* control_message_queue, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size)
-{
- return adopt_ref(*new OfflineAudioRenderer(control_message_queue, destination_node_id, number_of_channels, length, sample_rate, quantum_size));
-}
-
-OfflineAudioRenderer::OfflineAudioRenderer(void const* control_message_queue, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size)
- : m_callbacks(adopt_ref(*new OfflineAudioRendererCallbacks))
-{
- RustFFI::RendererCallbacks callbacks {
- { m_callbacks.ptr(), [](void* service) { static_cast<OfflineAudioRendererCallbacks*>(service)->ref(); }, [](void* service) { static_cast<OfflineAudioRendererCallbacks*>(service)->unref(); } },
- [](void* service, void* task, void (*invoke)(void*)) {
- static_cast<OfflineAudioRendererCallbacks*>(service)->event_loop.deferred_invoke([task, invoke] { invoke(task); });
- },
- [](void* service) {
- auto& callbacks = *static_cast<OfflineAudioRendererCallbacks*>(service);
- if (callbacks.on_complete)
- callbacks.on_complete();
- },
- [](void* service, double time) {
- auto& callbacks = *static_cast<OfflineAudioRendererCallbacks*>(service);
- if (callbacks.on_suspended)
- callbacks.on_suspended(time);
- },
- [](void* service, ReadonlySpan<u64> ids) {
- auto& callbacks = *static_cast<OfflineAudioRendererCallbacks*>(service);
- if (!callbacks.on_sources_ended)
- return;
- Vector<NodeID> nodes;
- for (auto id : ids)
- nodes.append(NodeID { id });
- callbacks.on_sources_ended(nodes);
- },
- };
- m_renderer = RustFFI::web_audio_offline_renderer_create(control_message_queue, destination_node_id.value(), number_of_channels, length, sample_rate, quantum_size, callbacks);
- m_rendered_channels.resize(number_of_channels);
- for (size_t channel = 0; channel < number_of_channels; ++channel)
- RustFFI::web_audio_offline_renderer_channel(m_renderer, channel, &m_rendered_channels[channel]);
-}
-
-OfflineAudioRenderer::~OfflineAudioRenderer() { RustFFI::web_audio_offline_renderer_destroy(m_renderer); }
-void OfflineAudioRenderer::set_on_complete(Function<void()> callback) { m_callbacks->on_complete = move(callback); }
-void OfflineAudioRenderer::set_on_suspended(Function<void(double)> callback) { m_callbacks->on_suspended = move(callback); }
-void OfflineAudioRenderer::set_on_sources_ended(Function<void(Vector<NodeID> const&)> callback) { m_callbacks->on_sources_ended = move(callback); }
-void OfflineAudioRenderer::clear_callbacks()
-{
- m_callbacks->on_complete = nullptr;
- m_callbacks->on_suspended = nullptr;
- m_callbacks->on_sources_ended = nullptr;
-}
-void OfflineAudioRenderer::start_rendering() { RustFFI::web_audio_offline_renderer_start(m_renderer); }
-void OfflineAudioRenderer::stop() { RustFFI::web_audio_offline_renderer_stop(m_renderer); }
-bool OfflineAudioRenderer::request_suspend(u64 frame) { return RustFFI::web_audio_offline_renderer_request_suspend(m_renderer, frame); }
-void OfflineAudioRenderer::resume() { RustFFI::web_audio_offline_renderer_resume(m_renderer); }
-u64 OfflineAudioRenderer::frames_rendered() const { return RustFFI::web_audio_offline_renderer_frames_rendered(m_renderer); }
-
-}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h b/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h
deleted file mode 100644
index ca8234e9d53..00000000000
--- a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[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/ConditionVariable.h>
-#include <AK/Function.h>
-#include <AK/HashTable.h>
-#include <AK/Mutex.h>
-#include <AK/NonnullRefPtr.h>
-#include <AK/RefPtr.h>
-#include <AK/Vector.h>
-#include <LibThreading/Thread.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/WebAudio/Types.h>
-
-namespace Core {
-
-class EventLoop;
-
-}
-
-namespace Web::WebAudio::Rendering {
-
-// Renders an OfflineAudioContext's graph on a dedicated rendering thread, which is created when rendering starts and
-// exits once the last render quantum has been processed. Progress is reported back to the control thread by posting
-// events to the main thread's event loop.
-// https://webaudio.github.io/web-audio-api/#OfflineAudioContext
-struct OfflineAudioRendererCallbacks;
-
-class WEB_API OfflineAudioRenderer final : public AtomicRefCounted<OfflineAudioRenderer> {
-public:
- static NonnullRefPtr<OfflineAudioRenderer> create(void const*, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size);
-
- ~OfflineAudioRenderer();
-
- // The callbacks below are set on the control thread before rendering starts and are always invoked on the control
- // thread. They are cleared once rendering completes to break the reference cycle with the context.
- void set_on_complete(Function<void()>);
- void set_on_suspended(Function<void(double suspend_time)>);
- void set_on_sources_ended(Function<void(Vector<NodeID> const&)>);
- void clear_callbacks();
-
- void start_rendering();
-
- // Ends rendering without completing it, unblocking the rendering thread if it is waiting in a suspension.
- void stop();
-
- // Registers a suspension at the given render quantum boundary. Returns false if the rendering thread already
- // looked for suspensions at that boundary.
- bool request_suspend(u64 frame);
- void resume();
-
- u64 frames_rendered() const;
-
- // Only safe to access on the control thread after the completion callback was invoked.
- Vector<ReadonlySpan<float>> const& rendered_channels() const { return m_rendered_channels; }
-
-private:
- OfflineAudioRenderer(void const*, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size);
-
- NonnullRefPtr<OfflineAudioRendererCallbacks> m_callbacks;
- void const* m_renderer { nullptr };
- Vector<ReadonlySpan<float>> m_rendered_channels;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp b/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp
deleted file mode 100644
index 74e4f7a5c88..00000000000
--- a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCore/EventLoop.h>
-#include <LibMedia/Sinks/AudioOutputFactory.h>
-#include <LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h>
-#include <LibWeb/WebAudio/RustFFI.h>
-
-namespace Web::WebAudio::Rendering {
-
-struct RealtimeAudioRendererCallbacks : AtomicRefCounted<RealtimeAudioRendererCallbacks> {
- Core::EventLoop& event_loop { Core::EventLoop::current() };
- Function<void(Vector<NodeID> const&)> on_sources_ended;
-};
-
-NonnullRefPtr<RealtimeAudioRenderer> RealtimeAudioRenderer::create(void const* control_message_queue, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory> audio_output_factory)
-{
- return adopt_ref(*new RealtimeAudioRenderer(control_message_queue, destination_node_id, sample_rate, quantum_size, move(audio_output_factory)));
-}
-
-RealtimeAudioRenderer::RealtimeAudioRenderer(void const* control_message_queue, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory> audio_output_factory)
- : m_callbacks(adopt_ref(*new RealtimeAudioRendererCallbacks))
- , m_audio_output_factory(move(audio_output_factory))
-{
- RustFFI::RendererCallbacks callbacks {
- { m_callbacks.ptr(), [](void* service) { static_cast<RealtimeAudioRendererCallbacks*>(service)->ref(); }, [](void* service) { static_cast<RealtimeAudioRendererCallbacks*>(service)->unref(); } },
- [](void* service, void* task, void (*invoke)(void*)) {
- static_cast<RealtimeAudioRendererCallbacks*>(service)->event_loop.deferred_invoke([task, invoke] { invoke(task); });
- },
- [](void*) { },
- [](void*, double) { },
- [](void* service, ReadonlySpan<u64> ids) {
- auto& callbacks = *static_cast<RealtimeAudioRendererCallbacks*>(service);
- if (!callbacks.on_sources_ended)
- return;
- Vector<NodeID> nodes;
- for (auto id : ids)
- nodes.append(NodeID { id });
- callbacks.on_sources_ended(nodes);
- },
- };
- m_renderer = RustFFI::web_audio_realtime_renderer_create(control_message_queue, destination_node_id.value(), sample_rate, quantum_size, callbacks);
-}
-
-RealtimeAudioRenderer::~RealtimeAudioRenderer() { RustFFI::web_audio_realtime_renderer_destroy(m_renderer); }
-
-// The callback is set on the control thread before rendering starts and is always invoked on the control thread. It
-// is cleared when the context closes to break the reference cycle with the context.
-void RealtimeAudioRenderer::set_on_sources_ended(Function<void(Vector<NodeID> const&)> on_sources_ended)
-{
- m_callbacks->on_sources_ended = move(on_sources_ended);
-}
-
-void RealtimeAudioRenderer::clear_callbacks()
-{
- m_callbacks->on_sources_ended = nullptr;
-}
-
-void RealtimeAudioRenderer::start_rendering()
-{
- prepare_to_start_rendering();
-
- // The stream is created in a suspended state so the device configuration can be recorded before the first data
- // request callback runs on the audio thread.
- auto promise = m_audio_output_factory->open_output(Audio::OutputState::Suspended, TARGET_LATENCY_MS, [self = NonnullRefPtr(*this)](Span<float> buffer, MonotonicTime buffer_starts_playing_at) { return self->fill_output_buffer(buffer, buffer_starts_playing_at); });
- promise->when_resolved([self = NonnullRefPtr(*this)](NonnullRefPtr<Audio::PlaybackStream>& stream) {
- self->set_playback_stream(stream);
- });
-}
-
-void RealtimeAudioRenderer::prepare_to_start_rendering()
-{
- VERIFY(!m_playback_stream);
- RustFFI::web_audio_realtime_renderer_prepare(m_renderer);
-}
-
-void RealtimeAudioRenderer::set_playback_stream(NonnullRefPtr<Audio::PlaybackStream> stream)
-{
- if (RustFFI::web_audio_realtime_renderer_is_shutting_down(m_renderer)) {
- stream->discard_buffer_and_suspend()->when_rejected([](auto&&) { });
- return;
- }
- auto specification = stream->sample_specification();
- RustFFI::web_audio_realtime_renderer_configure(m_renderer, specification.channel_count(), specification.sample_rate());
- m_playback_stream = stream;
- // The device went away with the process behind it: a new stream picks the graph up where it stands.
- stream->on_output_lost = [self = NonnullRefPtr(*this)] {
- if (RustFFI::web_audio_realtime_renderer_is_shutting_down(self->m_renderer))
- return;
- self->m_playback_stream = nullptr;
- self->start_rendering();
- };
-
- if (!RustFFI::web_audio_realtime_renderer_is_suspended(m_renderer))
- stream->resume()->when_rejected([](auto&&) { });
-}
-
-void RealtimeAudioRenderer::resume()
-{
- RustFFI::web_audio_realtime_renderer_set_suspended(m_renderer, false);
- if (m_playback_stream)
- m_playback_stream->resume()->when_rejected([](auto&&) { });
-}
-
-void RealtimeAudioRenderer::suspend()
-{
- RustFFI::web_audio_realtime_renderer_set_suspended(m_renderer, true);
- if (m_playback_stream)
- m_playback_stream->drain_buffer_and_suspend()->when_rejected([](auto&&) { });
-}
-
-void RealtimeAudioRenderer::stop()
-{
- RustFFI::web_audio_realtime_renderer_stop(m_renderer);
- if (m_playback_stream) {
- m_playback_stream->discard_buffer_and_suspend()->when_rejected([](auto&&) { });
- m_playback_stream = nullptr;
- }
-}
-
-double RealtimeAudioRenderer::output_time_played() const
-{
- return RustFFI::web_audio_realtime_renderer_output_time(m_renderer, MonotonicTime::now().nanoseconds());
-}
-
-ReadonlySpan<float> RealtimeAudioRenderer::fill_output_buffer(Span<float> buffer, MonotonicTime buffer_starts_playing_at)
-{
- auto count = RustFFI::web_audio_realtime_renderer_fill(m_renderer, buffer, buffer_starts_playing_at.nanoseconds());
- return buffer.trim(count);
-}
-
-u64 RealtimeAudioRenderer::frames_rendered() const { return RustFFI::web_audio_realtime_renderer_frames_rendered(m_renderer); }
-
-}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h b/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h
deleted file mode 100644
index 8c2cbbcb53a..00000000000
--- a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[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/Function.h>
-#include <AK/NonnullRefPtr.h>
-#include <AK/OwnPtr.h>
-#include <AK/RefPtr.h>
-#include <AK/SeqLock.h>
-#include <AK/Time.h>
-#include <AK/Vector.h>
-#include <LibAudio/PlaybackStream.h>
-#include <LibCore/Forward.h>
-#include <LibMedia/Forward.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/WebAudio/Types.h>
-
-namespace Web::WebAudio::Rendering {
-
-// Renders an AudioContext's graph in real time, pulled by the audio output device: the playback stream's data request
-// callback runs on the platform's audio thread and renders just enough render quanta to fill the device's buffer.
-// Progress is reported back to the control thread by posting events to the main thread's event loop.
-// https://webaudio.github.io/web-audio-api/#AudioContext
-struct RealtimeAudioRendererCallbacks;
-
-class WEB_API RealtimeAudioRenderer final : public AtomicRefCounted<RealtimeAudioRenderer> {
-public:
- // Device-buffer latency target. Public because AudioWorkletPipe derives its lookahead from the
- // renderer's burst size, which this constant determines.
- static constexpr u32 TARGET_LATENCY_MS = 100;
-
- static NonnullRefPtr<RealtimeAudioRenderer> create(void const*, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory>);
- ~RealtimeAudioRenderer();
-
- // The callback below is set on the control thread before rendering starts and is always invoked on the control
- // thread. It is cleared when the context closes to break the reference cycle with the context.
- void set_on_sources_ended(Function<void(Vector<NodeID> const&)>);
- void clear_callbacks();
-
- void start_rendering();
- void resume();
- void suspend();
- void stop();
-
- u64 frames_rendered() const;
-
- // The amount of audio the output device has played so far, in seconds.
- double output_time_played() const;
-
-private:
- RealtimeAudioRenderer(void const*, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory>);
-
- void prepare_to_start_rendering();
- void set_playback_stream(NonnullRefPtr<Audio::PlaybackStream>);
- ReadonlySpan<float> fill_output_buffer(Span<float>, MonotonicTime buffer_starts_playing_at);
-
- NonnullRefPtr<RealtimeAudioRendererCallbacks> m_callbacks;
- NonnullRefPtr<Media::AudioOutputFactory> m_audio_output_factory;
- RefPtr<Audio::PlaybackStream> m_playback_stream;
- void const* m_renderer { nullptr };
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.cpp b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.cpp
deleted file mode 100644
index 3d73d7a5cf1..00000000000
--- a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCore/EventLoop.h>
-#include <LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h>
-#include <LibWeb/WebAudio/RustFFI.h>
-
-namespace Web::WebAudio::Rendering {
-
-struct ScriptProcessorPipeCallbacks : AtomicRefCounted<ScriptProcessorPipeCallbacks> {
- explicit ScriptProcessorPipeCallbacks(Core::EventLoop& loop)
- : event_loop(loop)
- {
- }
- Core::EventLoop& event_loop;
- Function<void(size_t, u64)> process_callback;
-};
-
-NonnullRefPtr<ScriptProcessorPipe> ScriptProcessorPipe::create(Config config, Core::EventLoop& event_loop)
-{
- return adopt_ref(*new ScriptProcessorPipe(move(config), event_loop));
-}
-
-ScriptProcessorPipe::ScriptProcessorPipe(Config config, Core::EventLoop& event_loop)
- : m_callbacks(adopt_ref(*new ScriptProcessorPipeCallbacks(event_loop)))
-{
- RustFFI::PipeCallbacks callbacks {
- { m_callbacks.ptr(), [](void* service) { static_cast<ScriptProcessorPipeCallbacks*>(service)->ref(); }, [](void* service) { static_cast<ScriptProcessorPipeCallbacks*>(service)->unref(); } },
- [](void* service, void* task, void (*invoke)(void*)) {
- static_cast<ScriptProcessorPipeCallbacks*>(service)->event_loop.deferred_invoke([task, invoke] { invoke(task); });
- },
- [](void*) { },
- [](void* service, size_t block, u64 start_frame) {
- auto& callbacks = *static_cast<ScriptProcessorPipeCallbacks*>(service);
- if (!callbacks.process_callback)
- return false;
- callbacks.process_callback(block, start_frame);
- return true;
- },
- };
- RustFFI::ScriptProcessorPipeConfig native_config { config.buffer_size, config.input_channel_count, config.output_channel_count, config.block_count, config.waits_for_processing };
- m_pipe = RustFFI::web_audio_script_pipe_create(native_config, callbacks);
-}
-
-ScriptProcessorPipe::~ScriptProcessorPipe() { RustFFI::web_audio_script_pipe_destroy(m_pipe); }
-void ScriptProcessorPipe::set_process_callback(Function<void(size_t, u64)> callback) { m_callbacks->process_callback = move(callback); }
-void ScriptProcessorPipe::clear_process_callback() { m_callbacks->process_callback = nullptr; }
-
-}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h
deleted file mode 100644
index a2fd7c1e571..00000000000
--- a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/AtomicRefCounted.h>
-#include <AK/Function.h>
-#include <AK/NonnullRefPtr.h>
-#include <AK/Types.h>
-#include <LibCore/Forward.h>
-#include <LibWeb/Export.h>
-
-namespace Web::WebAudio::Rendering {
-
-struct ScriptProcessorPipeCallbacks;
-
-class WEB_API ScriptProcessorPipe final : public AtomicRefCounted<ScriptProcessorPipe> {
-public:
- struct Config {
- size_t buffer_size { 0 };
- size_t input_channel_count { 0 };
- size_t output_channel_count { 0 };
- size_t block_count { 0 };
- bool waits_for_processing { false };
- };
-
- static NonnullRefPtr<ScriptProcessorPipe> create(Config, Core::EventLoop& control_thread_event_loop);
-
- ~ScriptProcessorPipe();
- void const* rust_pipe() const { return m_pipe; }
-
- void set_process_callback(Function<void(size_t block, u64 start_frame)>);
- void clear_process_callback();
-
-private:
- ScriptProcessorPipe(Config, Core::EventLoop& control_thread_event_loop);
-
- NonnullRefPtr<ScriptProcessorPipeCallbacks> m_callbacks;
- void const* m_pipe { nullptr };
-};
-
-}
diff --git a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp
deleted file mode 100644
index 04b5cbb4770..00000000000
--- a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCore/EventLoop.h>
-#include <LibGC/Weak.h>
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Bindings/RustInterface.h>
-#include <LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h>
-#include <LibWeb/WebAudio/RustFFI.h>
-
-namespace Web::WebAudio {
-
-extern "C" void web_rust_script_processor_process(JSVM*, void*, size_t, u64);
-extern "C" RustFFI::FfiSharedCppObject web_audio_script_processor_create_pipe(Bindings::RustInterfaceCell*, RustFFI::ScriptProcessorPipeConfig, void const**);
-extern "C" void web_audio_script_processor_clear_callback(Rendering::ScriptProcessorPipe*);
-RustFFI::FfiSharedCppObject web_audio_script_processor_create_pipe(Bindings::RustInterfaceCell* node, RustFFI::ScriptProcessorPipeConfig config, void const** native_pipe)
-{
- auto pipe = Rendering::ScriptProcessorPipe::create({ config.buffer_size, config.input_channel_count, config.output_channel_count, config.block_count, config.waits_for_processing }, Core::EventLoop::current());
- pipe->set_process_callback([node = GC::Weak { *node }](size_t block, u64 start_frame) {
- if (node)
- web_rust_script_processor_process(JS::HostABI::vm_to_abi(JS::VM::the()), node.ptr().ptr(), block, start_frame);
- });
- *native_pipe = pipe->rust_pipe();
- return { &pipe.leak_ref(), [](void* pipe) { static_cast<Rendering::ScriptProcessorPipe*>(pipe)->ref(); }, [](void* pipe) { static_cast<Rendering::ScriptProcessorPipe*>(pipe)->unref(); } };
-}
-void web_audio_script_processor_clear_callback(Rendering::ScriptProcessorPipe* pipe) { pipe->clear_process_callback(); }
-
-}