Truly independent web browser
LibWeb: Port WebAudio renderers and pipes to Rust
Shannon Boothc49951640b50
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rsindex 67b1f8c6901..764a27217cf 100644--- a/Libraries/LibWeb/Rust/build.rs+++ b/Libraries/LibWeb/Rust/build.rs@@ -2484,6 +2484,10 @@ fn main() -> Result<(), Box<dyn Error>> {"ControlMessage","ControlMessageQueue","ControlMessages",+ "AudioWorkletPipe",+ "ScriptProcessorPipe",+ "OfflineAudioRenderer",+ "RealtimeAudioRenderer",] {web_audio_config.export.rename.insert(name.into(), "void".into());web_audio_config.export.exclude.push(name.into());@@ -2508,6 +2512,18 @@ fn main() -> Result<(), Box<dyn Error>> {manifest_dir.join("src/web_audio/rendering/render_nodes.rs"),manifest_dir.join("src/web_audio/rendering/node_message.rs"),manifest_dir.join("src/web_audio/rendering/audio_data.rs"),+ manifest_dir.join("src/web_audio/rendering/audio_frame_ring.rs"),+ manifest_dir.join("src/web_audio/rendering/analyser_render_node.rs"),+ manifest_dir.join("src/web_audio/rendering/audio_worklet_render_node.rs"),+ manifest_dir.join("src/web_audio/rendering/script_processor_render_node.rs"),+ manifest_dir.join("src/web_audio/rendering/media_stream_source_render_node.rs"),+ manifest_dir.join("src/web_audio/rendering/media_stream_destination_render_node.rs"),+ manifest_dir.join("src/web_audio/rendering/pipe_callbacks.rs"),+ manifest_dir.join("src/web_audio/rendering/audio_worklet_pipe.rs"),+ manifest_dir.join("src/web_audio/rendering/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_message_queue.rs"),],diff --git a/Libraries/LibWeb/Rust/src/web_audio/control_message.rs b/Libraries/LibWeb/Rust/src/web_audio/control_message.rsindex 840bb6e7ae8..9877342f0f8 100644--- a/Libraries/LibWeb/Rust/src/web_audio/control_message.rs+++ b/Libraries/LibWeb/Rust/src/web_audio/control_message.rs@@ -91,7 +91,7 @@ pub struct FfiSharedCppObject {}impl FfiSharedCppObject {- unsafe fn acquire(self) -> Option<SharedCppObject> {+ pub(crate) unsafe fn acquire(self) -> Option<SharedCppObject> {if self.pointer.is_null() {return None;}diff --git a/Libraries/LibWeb/Rust/src/web_audio/control_message_queue.rs b/Libraries/LibWeb/Rust/src/web_audio/control_message_queue.rsindex 8b45cacd897..7cb141ab2ee 100644--- a/Libraries/LibWeb/Rust/src/web_audio/control_message_queue.rs+++ b/Libraries/LibWeb/Rust/src/web_audio/control_message_queue.rs@@ -5,7 +5,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-use std::sync::Mutex;+use std::sync::{Arc, Mutex};use super::control_message::{ControlMessage, ControlMessages};@@ -30,13 +30,13 @@ impl ControlMessageQueue {}#[unsafe(no_mangle)]-pub(crate) extern "C" fn web_audio_control_queue_create() -> *mut ControlMessageQueue {- Box::into_raw(Box::new(ControlMessageQueue::default()))+pub(crate) extern "C" fn web_audio_control_queue_create() -> *const ControlMessageQueue {+ Arc::into_raw(Arc::new(ControlMessageQueue::default()))}#[unsafe(no_mangle)]-pub(crate) unsafe extern "C" fn web_audio_control_queue_destroy(queue: *mut ControlMessageQueue) {- drop(unsafe { Box::from_raw(queue) });+pub(crate) unsafe extern "C" fn web_audio_control_queue_destroy(queue: *const ControlMessageQueue) {+ drop(unsafe { Arc::from_raw(queue) });}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/analyser_render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/analyser_render_node.rsnew file mode 100644index 00000000000..743dbe0e5b2--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/analyser_render_node.rs@@ -0,0 +1,91 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#![allow(clippy::needless_range_loop)]+use super::audio_frame_ring::{AudioFrameRing, AudioFrameRingCallbacks};+use super::render_graph::RenderGraph;+use super::render_node::*;+use super::render_nodes::{BusRef, NodeProcessor, node_handle};+use crate::web_audio::control_message::FfiSharedCppObject;++// https://webaudio.github.io/web-audio-api/#AnalyserNode+struct AnalyserRenderNode {+ time_domain_ring: AudioFrameRing,+ mono_scratch: Vec<f32>,+ discard_scratch: Vec<f32>,+}++impl NodeProcessor for AnalyserRenderNode {+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {+ unsafe {+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());++ // The AnalyserNode passes its input through unprocessed.+ BusRef(data.output(0)).copy_from(&input);++ // https://webaudio.github.io/web-audio-api/#current-time-domain-data+ // The input signal must be down-mixed to mono as if channelCount is 1, channelCountMode+ // is "max" and channelInterpretation is "speakers".+ // AD-HOC: The down-mix is an unweighted channel average, which matches the speakers rules+ // for mono and stereo input; inputs with more channels would need the weighted+ // speakers down-mix.+ let channel_count = input.channel_count();+ for frame in 0..context.quantum_size {+ let mut sum = 0.;+ for channel_index in 0..channel_count {+ sum += input.channel(channel_index)[frame];+ }+ self.mono_scratch[frame] = if channel_count > 0 {+ sum / channel_count as f32+ } else {+ 0.+ };+ }++ // The ring must always end up holding the most recent samples, so a full ring (the page+ // is not currently polling any of the analyser getters) drops its oldest quantum first.+ // NB: Popping from the producing side bends the SPSC discipline. It can only race with+ // the control thread while the ring is simultaneously full and being drained by a+ // getter, in which case the worst outcome is one repeated or skipped quantum in the+ // analysis window; the ring's masked indices keep the race memory-safe.+ if self.time_domain_ring.frames_free() < context.quantum_size {+ self.time_domain_ring.try_pop(&mut self.discard_scratch);+ }+ self.time_domain_ring.try_push(&self.mono_scratch);+ }+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_node_create_analyser(+ node_id: u64,+ quantum_size: usize,+ ring: FfiSharedCppObject,+ callbacks: AudioFrameRingCallbacks,+) -> *mut NodeHandle {+ let time_domain_ring = AudioFrameRing {+ owner: unsafe { ring.acquire() }.unwrap(),+ callbacks,+ };+ assert_eq!(time_domain_ring.channel_count(), 1);+ let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);++ // NB: The control thread queues SetChannelConfig before AddNode and messages addressed to+ // unknown nodes are dropped, so the constructor must establish the node's channel+ // configuration itself.+ // https://webaudio.github.io/web-audio-api/#AnalyserNode+ data.channel_count.set(2);+ data.channel_count_mode.set(ChannelCountMode::Max);+ data.channel_interpretation.set(ChannelInterpretation::Speakers);+ node_handle(+ data,+ AnalyserRenderNode {+ time_domain_ring,+ mono_scratch: vec![0.; quantum_size],+ discard_scratch: vec![0.; quantum_size],+ },+ )+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_frame_ring.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_frame_ring.rsnew file mode 100644index 00000000000..b2f6cda72d3--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_frame_ring.rs@@ -0,0 +1,46 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use std::ffi::c_void;++use super::node_message::SharedCppObject;++#[derive(Clone, Copy)]+#[repr(C)]+pub struct AudioFrameRingCallbacks {+ pub channel_count: unsafe extern "C" fn(*mut c_void) -> u32,+ pub frames_available: unsafe extern "C" fn(*mut c_void) -> usize,+ pub frames_free: unsafe extern "C" fn(*mut c_void) -> usize,+ pub try_pop: unsafe extern "C" fn(*mut c_void, ak::SpanMut<'_, f32>) -> usize,+ pub try_push: unsafe extern "C" fn(*mut c_void, ak::Span<'_, f32>) -> usize,+}++pub(crate) struct AudioFrameRing {+ pub owner: SharedCppObject,+ pub callbacks: AudioFrameRingCallbacks,+}++impl AudioFrameRing {+ pub fn channel_count(&self) -> u32 {+ unsafe { (self.callbacks.channel_count)(self.owner.pointer) }+ }++ pub fn frames_available(&self) -> usize {+ unsafe { (self.callbacks.frames_available)(self.owner.pointer) }+ }++ pub fn frames_free(&self) -> usize {+ unsafe { (self.callbacks.frames_free)(self.owner.pointer) }+ }++ pub fn try_pop(&self, samples: &mut [f32]) -> usize {+ unsafe { (self.callbacks.try_pop)(self.owner.pointer, ak::SpanMut::new(samples)) }+ }++ pub fn try_push(&self, samples: &[f32]) -> usize {+ unsafe { (self.callbacks.try_push)(self.owner.pointer, ak::Span::new(samples)) }+ }+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe.rsnew file mode 100644index 00000000000..6d22c5b4177--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_pipe.rs@@ -0,0 +1,582 @@+/*+ * Copyright (c) 2026, Ali Mohammad Pur <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use std::cell::UnsafeCell;+use std::ffi::c_void;+use std::sync::Arc;+use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering};++use super::pipe_callbacks::{CallbackService, PipeCallbacks};+use crate::web_audio::control_message::clone_arc;++pub struct Config {+ pub quantum_size: usize,+ pub input_count: usize,+ pub output_count: usize,++ // Per input: the largest channel count a slot can carry.+ pub input_channel_capacity: Vec<u32>,++ // Per output: the largest channel count a slot can carry.+ pub output_channel_capacity: Vec<u32>,+ pub output_channel_count_matches_input: bool,+ pub param_count: usize,++ // Per parameter: a-rate blocks carry quantum_size samples, k-rate blocks one.+ pub param_is_a_rate: Vec<bool>,++ // Slots per ring; must be a power of two.+ pub ring_capacity: usize,++ // Silent output quanta pushed before rendering starts; at most ring_capacity.+ pub prime_level: usize,+}++#[repr(C)]+pub struct WorkletPipeConfig {+ pub quantum_size: usize,+ pub input_count: u32,+ pub output_count: u32,+ pub input_channel_capacity: ak::Span<'static, u32>,+ pub output_channel_capacity: ak::Span<'static, u32>,+ pub output_channel_count_matches_input: bool,+ pub param_count: u32,+ pub param_is_a_rate: ak::Span<'static, bool>,+ pub ring_capacity: usize,+ pub prime_level: usize,+}++#[derive(Clone, Copy, PartialEq, Eq)]+#[repr(u8)]+pub enum WorkletPipeState {+ Running,+ Failed,+ ShutDown,+}++#[repr(align(64))]+#[derive(Default)]+struct Counter(AtomicUsize);++#[derive(Default)]+struct Ring {+ // Producer-owned: the next slot to write.+ tail: Counter,++ // Consumer-owned: the next slot to read.+ head: Counter,+}++// A lock-free bridge between the realtime render node and the main-thread processor. Two SPSC rings share a+// preallocated arena; underruns render silence and a full input ring drops quanta. Each ring uses acquire/release+// head-tail discipline, and the slot stride is configured at run time.+//+// Per-slot layout; strides are rounded up to 64 bytes so slots start cache-line-aligned relative to the arena:+//+// Input slot Output slot+// u64 start_frame u64 start_frame+// u32 flags (bit 0: gap before this quantum) u32 flags (bit 0: processor active; bit 1: reserved+// u32 actual_channel_count[input_count] for a per-quantum processing-error signal)+// f32 samples[input_channel_capacity[0]][quantum_size] u32 actual_channel_count[output_count]+// ... one sample block per input ... f32 samples[output_channel_capacity[0]][quantum_size]+// f32 param_block[param_count]: quantum_size samples ... one sample block per output ...+// each for a-rate parameters, 1 for k-rate+//+// Slots are accessed in place through the writer/reader views below, which are only valid inside the callback they+// are passed to. A slot's unwritten regions keep stale data from the previous trip around the ring, so a writer+// must set the channel counts it wants a reader to trust; the flags are cleared on every push.+pub struct AudioWorkletPipe {+ pub config: Config,+ ring_index_mask: usize,+ input_slot_stride: usize,+ output_slot_stride: usize,+ output_region_offset: usize,+ input_samples_offset: Vec<usize>,+ output_samples_offset: Vec<usize>,+ param_block_offset: Vec<usize>,+ param_block_length: Vec<usize>,+ arena: Box<[UnsafeCell<u64>]>,+ input_ring: Ring,+ output_ring: Ring,+ callbacks: CallbackService,+ pump_scheduled: AtomicBool,+ state: AtomicU8,+ underrun_count: AtomicU64,+ dropped_input_count: AtomicU64,+}++// SAFETY: Each ring transfers its disjoint arena slots between one producer and one consumer with acquire/release counters.+unsafe impl Send for AudioWorkletPipe {}+unsafe impl Sync for AudioWorkletPipe {}+const SLOT_FLAGS_OFFSET: usize = 8;+const SLOT_CHANNEL_COUNTS_OFFSET: usize = 12;+const SLOT_ALIGNMENT: usize = 64;++impl AudioWorkletPipe {+ fn new(config: Config, callbacks: CallbackService) -> Self {+ assert!(config.quantum_size > 0);+ assert_eq!(config.input_channel_capacity.len(), config.input_count);+ assert_eq!(config.output_channel_capacity.len(), config.output_count);+ assert_eq!(config.param_is_a_rate.len(), config.param_count);+ assert!(config.ring_capacity.is_power_of_two());+ assert!(config.prime_level <= config.ring_capacity);+ let channel_bytes = config.quantum_size * size_of::<f32>();+ let mut offset = SLOT_CHANNEL_COUNTS_OFFSET + config.input_count * size_of::<u32>();+ let mut input_samples_offset = Vec::with_capacity(config.input_count);+ for input in 0..config.input_count {+ input_samples_offset.push(offset);+ offset += config.input_channel_capacity[input] as usize * channel_bytes;+ }+ let mut param_block_offset = Vec::with_capacity(config.param_count);+ let mut param_block_length = Vec::with_capacity(config.param_count);+ for param in 0..config.param_count {+ param_block_offset.push(offset);+ let block_length = if config.param_is_a_rate[param] {+ config.quantum_size+ } else {+ 1+ };+ param_block_length.push(block_length);+ offset += block_length * size_of::<f32>();+ }+ let input_slot_stride = (offset + SLOT_ALIGNMENT - 1) & !(SLOT_ALIGNMENT - 1);+ offset = SLOT_CHANNEL_COUNTS_OFFSET + config.output_count * size_of::<u32>();+ let mut output_samples_offset = Vec::with_capacity(config.output_count);+ for output in 0..config.output_count {+ output_samples_offset.push(offset);+ offset += config.output_channel_capacity[output] as usize * channel_bytes;+ }+ let output_slot_stride = (offset + SLOT_ALIGNMENT - 1) & !(SLOT_ALIGNMENT - 1);+ let output_region_offset = config.ring_capacity * input_slot_stride;+ let arena_size = output_region_offset + config.ring_capacity * output_slot_stride;+ Self {+ ring_index_mask: config.ring_capacity - 1,+ config,+ input_slot_stride,+ output_slot_stride,+ output_region_offset,+ input_samples_offset,+ output_samples_offset,+ param_block_offset,+ param_block_length,+ arena: (0..arena_size / size_of::<u64>()).map(|_| UnsafeCell::new(0)).collect(),+ input_ring: Ring::default(),+ output_ring: Ring::default(),+ callbacks,+ pump_scheduled: AtomicBool::new(false),+ state: AtomicU8::new(WorkletPipeState::Running as u8),+ underrun_count: AtomicU64::new(0),+ dropped_input_count: AtomicU64::new(0),+ }+ }++ fn input_slot(&self, counter: usize) -> *mut u8 {+ unsafe {+ self.arena+ .as_ptr()+ .cast::<u8>()+ .cast_mut()+ .add((counter & self.ring_index_mask) * self.input_slot_stride)+ }+ }++ fn output_slot(&self, counter: usize) -> *mut u8 {+ unsafe {+ self.arena+ .as_ptr()+ .cast::<u8>()+ .cast_mut()+ .add(self.output_region_offset + (counter & self.ring_index_mask) * self.output_slot_stride)+ }+ }++ // Fills the next input slot in place. Returns false, and counts a dropped quantum, when the ring is full; the+ // caller should then mark the next successful push with set_had_gap() so the processor can tell that quanta+ // went missing.+ pub(crate) unsafe fn try_push_input(&self, fill: impl FnOnce(*mut u8)) -> bool {+ let tail = self.input_ring.tail.0.load(Ordering::Relaxed);+ if tail.wrapping_sub(self.input_ring.head.0.load(Ordering::Acquire)) == self.config.ring_capacity {+ self.dropped_input_count.fetch_add(1, Ordering::Relaxed);+ return false;+ }+ let slot = self.input_slot(tail);+ unsafe {+ *slot.add(SLOT_FLAGS_OFFSET).cast::<u32>() = 0;+ }+ fill(slot);+ self.input_ring.tail.0.store(tail.wrapping_add(1), Ordering::Release);+ true+ }++ pub(crate) unsafe fn try_pop_input(&self, read: impl FnOnce(*mut u8)) -> bool {+ let head = self.input_ring.head.0.load(Ordering::Relaxed);+ if head == self.input_ring.tail.0.load(Ordering::Acquire) {+ return false;+ }+ read(self.input_slot(head));+ self.input_ring.head.0.store(head.wrapping_add(1), Ordering::Release);+ true+ }++ pub(crate) unsafe fn try_push_output(&self, fill: impl FnOnce(*mut u8)) -> bool {+ let tail = self.output_ring.tail.0.load(Ordering::Relaxed);+ if tail.wrapping_sub(self.output_ring.head.0.load(Ordering::Acquire)) == self.config.ring_capacity {+ return false;+ }+ let slot = self.output_slot(tail);+ unsafe {+ *slot.add(SLOT_FLAGS_OFFSET).cast::<u32>() = 0;+ }+ fill(slot);+ self.output_ring.tail.0.store(tail.wrapping_add(1), Ordering::Release);+ true+ }++ // Reads the oldest processed quantum. Returns false, and counts an underrun, when none is ready; the caller+ // then outputs silence, never blocking the audio callback.+ pub(crate) unsafe fn try_pop_output(&self, read: impl FnOnce(*mut u8)) -> bool {+ let head = self.output_ring.head.0.load(Ordering::Relaxed);+ if head == self.output_ring.tail.0.load(Ordering::Acquire) {+ self.underrun_count.fetch_add(1, Ordering::Relaxed);+ return false;+ }+ read(self.output_slot(head));+ self.output_ring.head.0.store(head.wrapping_add(1), Ordering::Release);+ true+ }++ pub fn output_occupancy(&self) -> usize {+ self.output_ring+ .tail+ .0+ .load(Ordering::Acquire)+ .wrapping_sub(self.output_ring.head.0.load(Ordering::Relaxed))+ }++ // Drops the oldest processed quanta until at most target_occupancy remain. After a main-thread stall the pump+ // catches up and refills the output ring past the prime level; clamping back down keeps the pipe's added+ // latency from ratcheting up permanently.+ pub fn discard_outputs_down_to(&self, target_occupancy: usize) {+ // A consumer-side pop-without-read: advancing the head releases the discarded slots back to the producer. New+ // pushes can only move the tail further along, so the snapshot below never overshoots.+ let head = self.output_ring.head.0.load(Ordering::Relaxed);+ let tail = self.output_ring.tail.0.load(Ordering::Acquire);+ if tail.wrapping_sub(head) <= target_occupancy {+ return;+ }+ self.output_ring+ .head+ .0+ .store(tail.wrapping_sub(target_occupancy), Ordering::Release);+ }++ pub(crate) unsafe fn prime_outputs_with_silence(&self, count: usize) {+ for _i in 0..count {+ let pushed = unsafe {+ self.try_push_output(|slot| {+ Self::set_start_frame(slot, 0);+ Self::set_flag(slot, true);+ for output in 0..self.config.output_count {+ let channel_count = if self.config.output_channel_count_matches_input {+ 1+ } else {+ self.config.output_channel_capacity[output]+ };+ *self.channel_count(slot, true, output) = channel_count;+ for channel in 0..channel_count {+ let (samples, length) = self.channel(slot, true, output, channel as usize);+ ak::slice_from_raw_parts_mut(samples, length).fill(0.);+ }+ }+ })+ };+ assert!(pushed);+ }+ }++ // Schedules the pump on the main thread's event loop. Coalesced: only the first request after+ // clear_wakeup_flag() posts an event, so a device burst of several dozen quanta causes one pump run.+ pub fn request_wakeup(self: &Arc<Self>) {+ // Coalesce a device burst into one main-thread pump instead of posting once per quantum.+ if self.pump_scheduled.swap(true, Ordering::AcqRel) {+ return;+ }+ unsafe extern "C" fn invoke(task: *mut c_void) {+ let pipe = unsafe { Arc::from_raw(task.cast::<AudioWorkletPipe>()) };+ if pipe.state() == WorkletPipeState::ShutDown {+ return;+ }+ unsafe {+ (pipe.callbacks.callbacks.on_wakeup)(pipe.callbacks.owner.pointer);+ }+ }+ let task = Arc::into_raw(Arc::clone(self));+ unsafe {+ self.callbacks.post(task.cast_mut().cast(), invoke);+ }+ }++ // The pump calls this before draining the input ring, so a burst that lands while the pump is running schedules+ // another run instead of being lost.+ pub fn clear_wakeup_flag(&self) {+ // A read-modify-write rather than a plain store: it synchronizes with the audio thread's exchange in+ // request_wakeup(), so whenever that exchange elides a wakeup (returns true), everything the audio thread+ // pushed beforehand is visible to this pump run's drain.+ self.pump_scheduled.swap(false, Ordering::AcqRel);+ }++ pub fn state(&self) -> WorkletPipeState {+ match self.state.load(Ordering::Acquire) {+ 0 => WorkletPipeState::Running,+ 1 => WorkletPipeState::Failed,+ 2 => WorkletPipeState::ShutDown,+ _ => unreachable!(),+ }+ }++ pub fn set_state(&self, state: WorkletPipeState) {+ self.state.store(state as u8, Ordering::Release);+ }++ pub(crate) unsafe fn set_start_frame(slot: *mut u8, frame: u64) {+ unsafe {+ *slot.cast::<u64>() = frame;+ }+ }++ pub(crate) unsafe fn set_flag(slot: *mut u8, enabled: bool) {+ let flags = unsafe { &mut *slot.add(SLOT_FLAGS_OFFSET).cast::<u32>() };+ if enabled {+ *flags |= 1;+ } else {+ *flags &= !1;+ }+ }++ pub(crate) unsafe fn flag(slot: *const u8) -> bool {+ unsafe { *slot.add(SLOT_FLAGS_OFFSET).cast::<u32>() & 1 != 0 }+ }++ pub(crate) unsafe fn channel_count(&self, slot: *mut u8, output: bool, index: usize) -> *mut u32 {+ assert!(+ index+ < if output {+ self.config.output_count+ } else {+ self.config.input_count+ }+ );+ unsafe { slot.add(SLOT_CHANNEL_COUNTS_OFFSET + index * size_of::<u32>()).cast() }+ }++ pub(crate) unsafe fn channel(+ &self,+ slot: *mut u8,+ output: bool,+ index: usize,+ channel: usize,+ ) -> (*mut f32, usize) {+ let (capacity, offsets) = if output {+ (&self.config.output_channel_capacity, &self.output_samples_offset)+ } else {+ (&self.config.input_channel_capacity, &self.input_samples_offset)+ };+ assert!(index < capacity.len());+ assert!(channel < capacity[index] as usize);+ (+ unsafe {+ slot.add(offsets[index])+ .cast::<f32>()+ .add(channel * self.config.quantum_size)+ },+ self.config.quantum_size,+ )+ }++ pub(crate) unsafe fn param_block(&self, slot: *mut u8, param: usize) -> (*mut f32, usize) {+ assert!(param < self.config.param_count);+ (+ unsafe { slot.add(self.param_block_offset[param]).cast() },+ self.param_block_length[param],+ )+ }+}++#[unsafe(no_mangle)]+pub(crate) extern "C" fn web_audio_worklet_pipe_ring_sizing(+ device_latency_ms: u32,+ sample_rate: f32,+ quantum_size: usize,+ ring_capacity: *mut usize,+ prime_level: *mut usize,+) {+ assert!(sample_rate > 0.);+ assert!(quantum_size > 0);+ let burst_quanta =+ (f64::from(device_latency_ms) / 1000. * f64::from(sample_rate) / quantum_size as f64).ceil() as usize;+ let prime = (burst_quanta * 5).div_ceil(4);+ let mut capacity = 1;+ while capacity < prime + (burst_quanta / 4).max(1) {+ capacity *= 2;+ }+ unsafe {+ *ring_capacity = capacity;+ *prime_level = prime;+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_create(+ config: WorkletPipeConfig,+ callbacks: PipeCallbacks,+) -> *const AudioWorkletPipe {+ let config = Config {+ quantum_size: config.quantum_size,+ input_count: config.input_count as usize,+ output_count: config.output_count as usize,+ input_channel_capacity: config.input_channel_capacity.as_slice().to_vec(),+ output_channel_capacity: config.output_channel_capacity.as_slice().to_vec(),+ output_channel_count_matches_input: config.output_channel_count_matches_input,+ param_count: config.param_count as usize,+ param_is_a_rate: config.param_is_a_rate.as_slice().to_vec(),+ ring_capacity: config.ring_capacity,+ prime_level: config.prime_level,+ };+ Arc::into_raw(Arc::new(AudioWorkletPipe::new(config, unsafe {+ CallbackService::new(callbacks)+ })))+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_destroy(pipe: *const AudioWorkletPipe) {+ drop(unsafe { Arc::from_raw(pipe) });+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_transfer(+ pipe: *const AudioWorkletPipe,+ output: bool,+ push: bool,+ context: *mut c_void,+ callback: unsafe extern "C" fn(*mut c_void, *mut u8),+) -> bool {+ let pipe = unsafe { &*pipe };+ let callback = |slot| unsafe {+ callback(context, slot);+ };+ match (output, push) {+ (false, true) => unsafe { pipe.try_push_input(callback) },+ (false, false) => unsafe { pipe.try_pop_input(callback) },+ (true, true) => unsafe { pipe.try_push_output(callback) },+ (true, false) => unsafe { pipe.try_pop_output(callback) },+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_output_occupancy(pipe: *const AudioWorkletPipe) -> usize {+ unsafe { &*pipe }.output_occupancy()+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_discard(pipe: *const AudioWorkletPipe, target: usize) {+ unsafe { &*pipe }.discard_outputs_down_to(target);+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_prime(pipe: *const AudioWorkletPipe, count: usize) {+ unsafe {+ (&*pipe).prime_outputs_with_silence(count);+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_request_wakeup(pipe: *const AudioWorkletPipe) {+ unsafe { clone_arc(pipe) }.request_wakeup();+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_clear_wakeup(pipe: *const AudioWorkletPipe) {+ unsafe { &*pipe }.clear_wakeup_flag();+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_state(pipe: *const AudioWorkletPipe) -> WorkletPipeState {+ unsafe { &*pipe }.state()+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_set_state(+ pipe: *const AudioWorkletPipe,+ state: WorkletPipeState,+) {+ unsafe { &*pipe }.set_state(state);+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_pipe_counter(pipe: *const AudioWorkletPipe, dropped: bool) -> u64 {+ let pipe = unsafe { &*pipe };+ if dropped {+ pipe.dropped_input_count.load(Ordering::Relaxed)+ } else {+ pipe.underrun_count.load(Ordering::Relaxed)+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_slot_frame(slot: *mut u8) -> *mut u64 {+ slot.cast()+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_slot_flag(slot: *const u8) -> bool {+ unsafe { AudioWorkletPipe::flag(slot) }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_slot_set_flag(slot: *mut u8, enabled: bool) {+ unsafe {+ AudioWorkletPipe::set_flag(slot, enabled);+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_slot_count(+ pipe: *const AudioWorkletPipe,+ slot: *mut u8,+ output: bool,+ index: usize,+) -> *mut u32 {+ unsafe { (&*pipe).channel_count(slot, output, index) }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_slot_channel(+ pipe: *const AudioWorkletPipe,+ slot: *mut u8,+ output: bool,+ index: usize,+ channel: usize,+ result: *mut ak::SpanMut<'static, f32>,+) {+ let (pointer, length) = unsafe { (&*pipe).channel(slot, output, index, channel) };+ unsafe {+ *result = ak::SpanMut::new(ak::slice_from_raw_parts_mut(pointer, length));+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_worklet_slot_param(+ pipe: *const AudioWorkletPipe,+ slot: *mut u8,+ param: usize,+ result: *mut ak::SpanMut<'static, f32>,+) {+ let (pointer, length) = unsafe { (&*pipe).param_block(slot, param) };+ unsafe {+ *result = ak::SpanMut::new(ak::slice_from_raw_parts_mut(pointer, length));+ }+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_render_node.rsnew file mode 100644index 00000000000..0b0a1be507c--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_worklet_render_node.rs@@ -0,0 +1,141 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#![allow(clippy::needless_range_loop)]+use std::sync::Arc;++use super::audio_worklet_pipe::{AudioWorkletPipe, WorkletPipeState};+use super::render_graph::RenderGraph;+use super::render_node::*;+use super::render_nodes::{BusRef, NodeProcessor, node_handle};+use crate::web_audio::control_message::clone_arc;++// Script runs on the main-thread pump, `prime_level` quanta behind this render node; this side+// only exchanges preallocated pipe slots and renders silence on underrun.+struct AudioWorkletRenderNode {+ pipe: Arc<AudioWorkletPipe>,+ params: Vec<Arc<RenderAudioParam>>,+ param_scratch: Vec<f32>,+ output_channel_capacities: Vec<u32>,+}++impl NodeProcessor for AudioWorkletRenderNode {+ fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {+ for param in &self.params {+ callback(param);+ }+ }++ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {+ unsafe {+ // A failed (processor threw) or shut-down (node finalized / context closed) worklet renders+ // silence forever; the pump side owns the state transitions.+ if self.pipe.state() != WorkletPipeState::Running {+ for output in 0..data.output_count() {+ BusRef(data.output(output)).zero();+ }+ return;+ }+ self.pipe.try_push_input(|slot| {+ AudioWorkletPipe::set_start_frame(slot, context.quantum_start_frame);+ for input in 0..data.input_count() {+ // Unlike the render graph's silent mono bus, an unconnected worklet input+ // is represented by an empty channel array in process().+ if (&*data.input_connections.get())[input].is_empty() {+ *self.pipe.channel_count(slot, false, input) = 0;+ continue;+ }+ let input_bus = BusRef(data.pull_input(graph, context, input).cast_mut());+ let capacity_channels = self.pipe.config.input_channel_capacity[input];+ let channels_to_copy = input_bus.channel_count().min(capacity_channels as usize);+ *self.pipe.channel_count(slot, false, input) = channels_to_copy as u32;+ for channel in 0..channels_to_copy {+ let (pointer, length) = self.pipe.channel(slot, false, input, channel);+ let destination = ak::slice_from_raw_parts_mut(pointer, length);+ let source = input_bus.channel(channel);+ assert_eq!(destination.len(), source.len());+ destination.copy_from_slice(source);+ }+ }+ for param_index in 0..self.params.len() {+ let (pointer, length) = self.pipe.param_block(slot, param_index);+ let block = ak::slice_from_raw_parts_mut(pointer, length);++ // a-rate params fill the whole block; k-rate blocks are a single value. compute() handles+ // both through the shared timeline + any audio-rate param connections.+ self.param_scratch.resize(block.len(), 0.);+ self.params[param_index].compute(graph, context, &mut self.param_scratch[..block.len()]);+ block.copy_from_slice(&self.param_scratch[..block.len()]);+ }+ });+ self.pipe.request_wakeup();+ let popped = self.pipe.try_pop_output(|slot| {+ for output in 0..data.output_count() {+ let output_bus = BusRef(data.output(output));+ let channel_count = (*self.pipe.channel_count(slot, true, output) as usize)+ .min(self.output_channel_capacities[output] as usize);+ output_bus.set_channel_count(channel_count.max(1));+ output_bus.zero();+ for channel in 0..channel_count {+ let (pointer, length) = self.pipe.channel(slot, true, output, channel);+ let source = ak::slice_from_raw_parts(pointer, length);+ let destination = output_bus.channel_mut(channel);+ let frames = source.len().min(destination.len());+ destination[..frames].copy_from_slice(&source[..frames]);+ }+ }+ });+ if !popped {+ for output in 0..data.output_count() {+ BusRef(data.output(output)).zero();+ }+ return;+ }++ // Latency clamp: after a main-thread stall, the pump refills the output ring past the configured+ // lookahead (the audio side emitted silence meanwhile). Discard the excess so the stall does not+ // permanently ratchet up this node's latency.+ if self.pipe.output_occupancy() > self.pipe.config.prime_level {+ self.pipe.discard_outputs_down_to(self.pipe.config.prime_level);+ }+ }+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_node_create_audio_worklet(+ node_id: u64,+ input_count: usize,+ output_count: usize,+ quantum_size: usize,+ output_channel_capacities: ak::Span<'_, u32>,+ channel_count: usize,+ channel_count_mode: ChannelCountMode,+ channel_interpretation: ChannelInterpretation,+ pipe: *const AudioWorkletPipe,+ params: ak::Span<'_, *const RenderAudioParam>,+) -> *mut NodeHandle {+ let data = RenderNodeData::new(node_id, input_count, output_count, quantum_size, 1);++ // Channel configuration must be set here: the SetChannelConfig messages queued during node+ // construction arrive before our AddNode and are dropped by the graph.+ data.channel_count.set(channel_count);+ data.channel_count_mode.set(channel_count_mode);+ data.channel_interpretation.set(channel_interpretation);+ node_handle(+ data,+ AudioWorkletRenderNode {+ pipe: unsafe { clone_arc(pipe) },+ params: params+ .as_slice()+ .iter()+ .map(|param| unsafe { clone_arc(*param) })+ .collect(),+ param_scratch: vec![0.; quantum_size],+ output_channel_capacities: output_channel_capacities.as_slice().to_vec(),+ },+ )+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/media_stream_destination_render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/media_stream_destination_render_node.rsnew file mode 100644index 00000000000..7700eed1085--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/media_stream_destination_render_node.rs@@ -0,0 +1,118 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#![allow(clippy::needless_range_loop)]+use std::ffi::c_void;+use std::sync::Arc;+use std::sync::atomic::{AtomicBool, Ordering};++use super::audio_bus::AudioBus;+use super::audio_frame_ring::{AudioFrameRing, AudioFrameRingCallbacks};+use super::pipe_callbacks::{CallbackService, PipeCallbacks};+use super::render_graph::RenderGraph;+use super::render_node::*;+use super::render_nodes::{BusRef, NodeProcessor, node_handle};+use crate::web_audio::control_message::FfiSharedCppObject;++// The render thread only touches the ring and pending flag; the control thread owns the drain+// callback so its captured GC roots never cross threads.+struct SharedState {+ ring: AudioFrameRing,++ // Set by the rendering thread when it schedules a drain on the control thread and cleared+ // by the control thread when the drain runs, coalescing the notifications down to one+ // wakeup per rendered burst.+ drain_pending: AtomicBool,+ callbacks: CallbackService,+}++// https://webaudio.github.io/web-audio-api/#MediaStreamAudioDestinationNode+struct MediaStreamDestinationRenderNode {+ shared_state: Arc<SharedState>,+ mix_bus: AudioBus,+ interleaved_scratch: Vec<f32>,+}++impl NodeProcessor for MediaStreamDestinationRenderNode {+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {+ unsafe {+ let input = BusRef(data.pull_input(graph, context, 0).cast_mut());++ // AD-HOC: The spec gives this node zero outputs, but RenderGraph only pulls nodes that+ // have at least one, so the render node exposes its input as a passthrough+ // output. This keeps the node processing every quantum and also makes it audible+ // when a page connects it onward.+ BusRef(data.output(0)).copy_from(&input);++ // Mix the input to the track's channel count and interleave it into the shared ring. If+ // the control thread has stalled and the ring is full, the newest frames are dropped; the+ // consumer resynchronizes when it drains.+ self.mix_bus.zero();+ self.mix_bus.sum_from(+ &*input.0,+ data.channel_interpretation.get() == ChannelInterpretation::Speakers,+ );+ let channel_count = self.mix_bus.channel_count();+ for frame in 0..context.quantum_size {+ for channel_index in 0..channel_count {+ self.interleaved_scratch[frame * channel_count + channel_index] =+ self.mix_bus.channel(channel_index)[frame];+ }+ }+ self.shared_state.ring.try_push(&self.interleaved_scratch);++ // Coalesced render→control notification, following the renderer's ended-sources pattern:+ // at most one queued drain per rendered burst, so the control thread wakes up ~10 times+ // per second rather than once per quantum.+ if !self.shared_state.drain_pending.swap(true, Ordering::AcqRel) {+ unsafe extern "C" fn invoke(task: *mut c_void) {+ let shared_state = unsafe { Arc::from_raw(task.cast::<SharedState>()) };+ shared_state.drain_pending.store(false, Ordering::Release);+ unsafe {+ (shared_state.callbacks.callbacks.on_wakeup)(shared_state.callbacks.owner.pointer);+ }+ }+ let task = Arc::into_raw(Arc::clone(&self.shared_state));+ self.shared_state.callbacks.post(task.cast_mut().cast(), invoke);+ }+ }+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_node_create_media_stream_destination(+ node_id: u64,+ quantum_size: usize,+ channel_count: usize,+ ring: FfiSharedCppObject,+ ring_callbacks: AudioFrameRingCallbacks,+ callbacks: PipeCallbacks,+) -> *mut NodeHandle {+ let data = RenderNodeData::new(node_id, 1, 1, quantum_size, channel_count);++ // NB: The control thread queues SetChannelConfig before AddNode and messages addressed to+ // unknown nodes are dropped, so the constructor must establish the node's channel+ // configuration itself.+ // https://webaudio.github.io/web-audio-api/#MediaStreamAudioDestinationNode+ data.channel_count.set(channel_count);+ data.channel_count_mode.set(ChannelCountMode::Explicit);+ data.channel_interpretation.set(ChannelInterpretation::Speakers);+ node_handle(+ data,+ MediaStreamDestinationRenderNode {+ shared_state: Arc::new(SharedState {+ ring: AudioFrameRing {+ owner: unsafe { ring.acquire() }.unwrap(),+ callbacks: ring_callbacks,+ },+ drain_pending: AtomicBool::new(false),+ callbacks: unsafe { CallbackService::new(callbacks) },+ }),+ mix_bus: AudioBus::new(channel_count, quantum_size),+ interleaved_scratch: vec![0.; quantum_size * channel_count],+ },+ )+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/media_stream_source_render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/media_stream_source_render_node.rsnew file mode 100644index 00000000000..188743d53d9--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/media_stream_source_render_node.rs@@ -0,0 +1,99 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#![allow(clippy::needless_range_loop)]+use super::audio_frame_ring::{AudioFrameRing, AudioFrameRingCallbacks};+use super::node_message::NodeMessage;+use super::render_graph::RenderGraph;+use super::render_node::*;+use super::render_nodes::{BusRef, NodeProcessor, node_handle};++// https://webaudio.github.io/web-audio-api/#MediaStreamAudioSourceNode+struct MediaStreamSourceRenderNode {+ ring: Option<AudioFrameRing>,+ ring_callbacks: AudioFrameRingCallbacks,+ channel_count: u32,+ interleaved_scratch: Vec<f32>,+}++impl NodeProcessor for MediaStreamSourceRenderNode {+ fn handle_message(&mut self, message: &NodeMessage) {+ if let NodeMessage::SetMediaStreamSourceRing(set_ring) = message {+ self.ring = set_ring.ring.as_ref().map(|ring| AudioFrameRing {+ owner: ring.clone(),+ callbacks: self.ring_callbacks,+ });++ // NB: The ring's own channel count wins over the message field so the interleaved+ // stride below can never disagree with the ring's layout.+ self.channel_count = if let Some(ring) = &self.ring {+ ring.channel_count()+ } else {+ set_ring.channel_count.max(1)+ };+ }+ }++ unsafe fn process(&mut self, data: &RenderNodeData, _graph: &RenderGraph, context: &RenderContext) {+ unsafe {+ let source_output = BusRef(data.output(0));++ // The number of channels of the output corresponds to the number of channels of the track.+ source_output.set_channel_count(self.channel_count as usize);+ source_output.zero();+ let Some(ring) = &self.ring else {+ return;+ };++ // Drain the ring sequentially, up to one render quantum. When the producer has not+ // delivered enough frames yet (startup, scheduling jitter), the tail of the quantum stays+ // silent; skipping ahead to "the most recent frames" instead would drift against the+ // producer's cadence and repeat or drop content.+ let frames_to_pop = context.quantum_size.min(ring.frames_available());+ if frames_to_pop == 0 {+ return;+ }+ self.interleaved_scratch+ .resize(frames_to_pop * self.channel_count as usize, 0.);+ let frames_popped = ring.try_pop(&mut self.interleaved_scratch);+ for channel_index in 0..self.channel_count as usize {+ let output_samples = source_output.channel_mut(channel_index);+ for frame in 0..frames_popped {+ output_samples[frame] =+ self.interleaved_scratch[frame * self.channel_count as usize + channel_index];+ }+ }++ // The producer converts track samples to the context's sample rate before filling the ring.+ }+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_node_create_media_stream_source(+ node_id: u64,+ quantum_size: usize,+ callbacks: AudioFrameRingCallbacks,+) -> *mut NodeHandle {+ let data = RenderNodeData::new(node_id, 0, 1, quantum_size, 2);++ // NB: The control thread queues SetChannelConfig before AddNode and messages addressed to+ // unknown nodes are dropped, so the constructor must establish the node's channel+ // configuration itself.+ // https://webaudio.github.io/web-audio-api/#MediaStreamAudioSourceNode+ data.channel_count.set(2);+ data.channel_count_mode.set(ChannelCountMode::Max);+ data.channel_interpretation.set(ChannelInterpretation::Speakers);+ node_handle(+ data,+ MediaStreamSourceRenderNode {+ ring: None,+ ring_callbacks: callbacks,+ channel_count: 1,+ interleaved_scratch: Vec::new(),+ },+ )+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rsindex e5a70daef02..0b1357c21a2 100644--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs@@ -17,3 +17,18 @@ pub mod audio_data;pub mod render_nodes;#[cfg(test)]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;+pub mod script_processor_pipe;++pub mod analyser_render_node;+pub mod audio_frame_ring;+pub mod audio_worklet_render_node;+pub mod media_stream_destination_render_node;+pub mod media_stream_source_render_node;+pub mod script_processor_render_node;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.rsnew file mode 100644index 00000000000..2491a4a56ff--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/offline_audio_renderer.rs@@ -0,0 +1,288 @@+/*+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#![allow(clippy::needless_range_loop, clippy::manual_memcpy)]++use std::cell::UnsafeCell;+use std::collections::HashSet;+use std::ffi::c_void;+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;++#[derive(Default)]+struct SuspensionState {+ suspend_frames: HashSet<u64>,++ // The next render quantum boundary at which the rendering thread will look for a scheduled suspension. It is+ // published under the same lock that guards the suspension set, so a suspension can never be registered for a+ // boundary the rendering thread has already checked.+ next_suspend_check_frame: u64,+ suspended: bool,+ shutting_down: bool,+}++pub struct OfflineAudioRenderer {+ control_message_queue: Arc<ControlMessageQueue>,+ destination_node_id: u64,+ number_of_channels: usize,+ length: usize,+ sample_rate: f32,+ quantum_size: usize,+ callbacks: CallbackService,+ thread: UnsafeCell<Option<std::thread::Thread>>,+ graph: UnsafeCell<RenderGraph>,+ rendered_channels: UnsafeCell<Vec<Vec<f32>>>,+ frames_rendered: AtomicU64,+ suspend_mutex: Mutex<SuspensionState>,+ resume_signal: Condvar,+}++// SAFETY: One render thread owns graph/sample mutations, and suspension/progress use the original synchronization.+unsafe impl Send for OfflineAudioRenderer {}+unsafe impl Sync for OfflineAudioRenderer {}+enum Notification {+ Complete,+ Suspended(f64),+ SourcesEnded(Vec<u64>),+}++struct ControlTask {+ renderer: Arc<OfflineAudioRenderer>,+ notification: Notification,+}++impl OfflineAudioRenderer {+ 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 {+ 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 {+ control_message_queue,+ destination_node_id,+ number_of_channels,+ length,+ sample_rate,+ quantum_size,+ callbacks,+ 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>) {+ assert!(unsafe { &*self.thread.get() }.is_none());+ unsafe { &mut *self.graph.get() }.set_destination(self.destination_node_id);+ let renderer = Arc::clone(self);+ let thread = std::thread::Builder::new()+ .name("OfflineAudioRenderer".into())+ .spawn(move || {+ renderer.render_thread_main();+ })+ .unwrap();+ unsafe {+ *self.thread.get() = Some(thread.thread().clone());+ }+ drop(thread);+ }++ 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 {+ let mut state = self.suspend_mutex.lock().unwrap();+ if frame < state.next_suspend_check_frame {+ return false;+ }+ state.suspend_frames.insert(frame);+ true+ }++ fn resume(&self) {+ let mut state = self.suspend_mutex.lock().unwrap();+ state.suspended = false;+ self.resume_signal.notify_all();+ }++ 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 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>) {+ let mut current_frame = 0_u64;+ while current_frame < self.length as u64 {+ // Suspend rendering if a suspension was scheduled at this render quantum boundary.+ {+ let mut state = self.suspend_mutex.lock().unwrap();+ if state.shutting_down {+ return;+ }+ state.next_suspend_check_frame = current_frame + self.quantum_size as u64;+ if state.suspend_frames.remove(¤t_frame) {+ state.suspended = true;+ let suspend_time = current_frame as f64 / f64::from(self.sample_rate);+ self.post_to_control_thread(Notification::Suspended(suspend_time));+ while state.suspended && !state.shutting_down {+ state = self.resume_signal.wait(state).unwrap();+ }+ if state.shutting_down {+ return;+ }+ }+ }+ let graph = unsafe { &mut *self.graph.get() };+ graph.apply_control_messages(self.control_message_queue.drain());+ let context = RenderContext {+ sample_rate: f64::from(self.sample_rate),+ quantum_size: self.quantum_size,+ quantum_start_frame: current_frame,+ };+ graph.render_quantum(&context);++ // Copy the destination's captured output into the rendered buffer.+ if let Some(destination_node) = graph.destination() {+ let destination_output = unsafe { &*destination_node.data().output(0) };+ let frames_to_copy = self.quantum_size.min(self.length - current_frame as usize);+ let rendered_channels = unsafe { &mut *self.rendered_channels.get() };+ for channel_index in 0..self.number_of_channels {+ if channel_index >= destination_output.channel_count() {+ break;+ }+ let samples = destination_output.channel(channel_index);+ for frame in 0..frames_to_copy {+ rendered_channels[channel_index][current_frame as usize + frame] = samples[frame];+ }+ }+ }+ current_frame += self.quantum_size as u64;+ self.frames_rendered.store(current_frame, Ordering::SeqCst);+ let ended_nodes = graph.take_ended_nodes();+ if !ended_nodes.is_empty() {+ self.post_to_control_thread(Notification::SourcesEnded(ended_nodes));+ }+ }+ 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_started(renderer: *const OfflineAudioRenderer) -> bool {+ unsafe { &*(*renderer).thread.get() }.is_some()+}++#[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.rsnew file mode 100644index 00000000000..bd71992abac--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/pipe_callbacks.rs@@ -0,0 +1,42 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use std::ffi::c_void;++use super::node_message::SharedCppObject;+use crate::web_audio::control_message::FfiSharedCppObject;++#[derive(Clone, Copy)]+#[repr(C)]+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 {+ pub owner: SharedCppObject,+ pub callbacks: PipeCallbacks,+}++// SAFETY: Callback services are atomically reference-counted and invoked on their control-thread event loop.+unsafe impl Send for CallbackService {}+unsafe impl Sync for CallbackService {}+impl CallbackService {+ pub(crate) unsafe fn new(callbacks: PipeCallbacks) -> Self {+ Self {+ owner: unsafe { callbacks.service.acquire() }.unwrap(),+ callbacks,+ }+ }++ pub(crate) unsafe fn post(&self, task: *mut c_void, invoke: unsafe extern "C" fn(*mut c_void)) {+ unsafe {+ (self.callbacks.post_task)(self.owner.pointer, task, invoke);+ }+ }+}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.rsnew file mode 100644index 00000000000..4f93a3344db--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/realtime_audio_renderer.rs@@ -0,0 +1,329 @@+/*+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#![allow(clippy::needless_range_loop, clippy::manual_memcpy)]+use std::cell::UnsafeCell;+use std::ffi::c_void;+use std::sync::Arc;+use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering, fence};++use super::audio_bus::AudioBus;+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;++// The output buffer most recently handed to the stream, and when its first frame plays.+#[derive(Default)]+struct OutputAnchor {+ version: AtomicU64,+ first_frame_index: AtomicU64,+ end_frame_index: AtomicU64,+ plays_at_nanoseconds: AtomicI64,+}++impl OutputAnchor {+ fn store(&self, first_frame_index: u64, end_frame_index: u64, plays_at_nanoseconds: i64) {+ let version = self.version.load(Ordering::Relaxed);+ self.version.store(version.wrapping_add(1), Ordering::Relaxed);+ fence(Ordering::SeqCst);+ self.first_frame_index.store(first_frame_index, Ordering::Relaxed);+ self.end_frame_index.store(end_frame_index, Ordering::Relaxed);+ self.plays_at_nanoseconds.store(plays_at_nanoseconds, Ordering::Relaxed);+ self.version.store(version.wrapping_add(2), Ordering::Release);+ }++ fn read(&self) -> Option<(u64, u64, i64)> {+ for _retry in 0..32 {+ let version_before = self.version.load(Ordering::Acquire);+ if !version_before.is_multiple_of(2) {+ continue;+ }+ let copy = (+ self.first_frame_index.load(Ordering::Relaxed),+ self.end_frame_index.load(Ordering::Relaxed),+ self.plays_at_nanoseconds.load(Ordering::Relaxed),+ );+ fence(Ordering::Acquire);+ let version_after = self.version.load(Ordering::Relaxed);+ if version_before == version_after {+ return Some(copy);+ }+ }+ None+ }+}++// State below is only used on the audio thread, except that the device configuration is recorded on the control+// thread after stream creation, before the first data request callback can run.+struct RenderState {+ graph: RenderGraph,+ device_bus: Option<Box<AudioBus>>,+ device_channel_count: usize,+ frames_output: u64,+ playhead_step: f64,+ playhead: f64,+ pending_samples: Vec<f32>,+}++pub struct RealtimeAudioRenderer {+ control_message_queue: Arc<ControlMessageQueue>,+ destination_node_id: u64,+ sample_rate: f32,+ quantum_size: usize,+ callbacks: CallbackService,+ frames_rendered: AtomicU64,+ suspended: AtomicBool,+ shutting_down: AtomicBool,+ output_anchor: OutputAnchor,+ device_sample_rate: AtomicU32,+ state: UnsafeCell<RenderState>,+}++// 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(+ queue: Arc<ControlMessageQueue>,+ destination_node_id: u64,+ sample_rate: f32,+ quantum_size: usize,+ callbacks: CallbackService,+ ) -> Self {+ Self {+ control_message_queue: queue,+ destination_node_id,+ sample_rate,+ quantum_size,+ callbacks,+ frames_rendered: AtomicU64::new(0),+ suspended: AtomicBool::new(false),+ shutting_down: AtomicBool::new(false),+ output_anchor: OutputAnchor::default(),+ device_sample_rate: AtomicU32::new(0),+ state: UnsafeCell::new(RenderState {+ graph: RenderGraph::default(),+ device_bus: None,+ device_channel_count: 0,+ frames_output: 0,+ playhead_step: 1.,+ playhead: 0.,+ pending_samples: Vec::new(),+ }),+ }+ }++ fn output_time_played(&self, now_nanoseconds: i64) -> f64 {+ 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 {+ return 0.;+ }+ let (first_frame_index, end_frame_index, plays_at_nanoseconds) = maybe_anchor.unwrap();+ let seconds_since_buffer_started = (now_nanoseconds - plays_at_nanoseconds).max(0) as f64 / 1e9;+ let buffer_start_seconds = first_frame_index as f64 / f64::from(device_sample_rate);+ let buffer_end_seconds = end_frame_index as f64 / f64::from(device_sample_rate);+ if buffer_end_seconds < buffer_start_seconds + seconds_since_buffer_started {+ buffer_end_seconds+ } else {+ buffer_start_seconds + seconds_since_buffer_started+ }+ }++ unsafe fn fill_output_buffer(self: &Arc<Self>, buffer: &mut [f32], buffer_starts_playing_at: i64) -> usize {+ let state = unsafe { &mut *self.state.get() };+ if self.shutting_down.load(Ordering::SeqCst) || state.device_channel_count == 0 {+ return 0;+ }+ let channel_count = state.device_channel_count;+ let frames_requested = buffer.len() / channel_count;+ self.output_anchor.store(+ state.frames_output,+ state.frames_output + frames_requested as u64,+ buffer_starts_playing_at,+ );+ state.frames_output += frames_requested as u64;+ for frame in 0..frames_requested {+ let first_frame = state.playhead as usize;+ let fraction = (state.playhead - first_frame as f64) as f32;++ // Interpolation between adjacent rendered frames requires one frame of lookahead.+ while state.pending_samples.len() / channel_count < first_frame + 2 {+ self.render_quantum_into_pending_samples(state);+ }+ for channel in 0..channel_count {+ let mut sample = state.pending_samples[first_frame * channel_count + channel];+ if fraction != 0. {+ let next_sample = state.pending_samples[(first_frame + 1) * channel_count + channel];+ sample += fraction * (next_sample - sample);+ }+ buffer[frame * channel_count + channel] = sample;+ }+ state.playhead += state.playhead_step;+ }++ // Trim rendered frames preceding the playhead. If resampling advances the playhead beyond the rendered frames,+ // carry the remaining offset into the next callback.+ let rendered_frames = state.pending_samples.len() / channel_count;+ let consumed_frames = (state.playhead as usize).min(rendered_frames);+ if consumed_frames > 0 {+ state.pending_samples.drain(..consumed_frames * channel_count);+ state.playhead -= consumed_frames as f64;+ }+ buffer.len()+ }++ fn render_quantum_into_pending_samples(self: &Arc<Self>, state: &mut RenderState) {+ state.graph.apply_control_messages(self.control_message_queue.drain());+ let context = RenderContext {+ sample_rate: f64::from(self.sample_rate),+ quantum_size: self.quantum_size,+ quantum_start_frame: self.frames_rendered.load(Ordering::SeqCst),+ };+ state.graph.render_quantum(&context);++ // Mix the destination's output to the stream's channel layout and append it as interleaved samples.+ if let Some(device_bus) = &mut state.device_bus {+ device_bus.zero();+ if let Some(destination_node) = state.graph.destination() {+ device_bus.sum_from(unsafe { &*destination_node.data().output(0) }, true);+ }+ let sample_offset = state.pending_samples.len();+ state+ .pending_samples+ .resize(sample_offset + self.quantum_size * state.device_channel_count, 0.);+ for frame in 0..self.quantum_size {+ for channel in 0..state.device_channel_count {+ state.pending_samples[sample_offset + frame * state.device_channel_count + channel] =+ device_bus.channel(channel)[frame];+ }+ }+ }+ self.frames_rendered+ .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 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) },+ )))+}++#[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);+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_fill(+ renderer: *const RealtimeAudioRenderer,+ output: ak::SpanMut<'_, f32>,+ plays_at_nanoseconds: i64,+) -> usize {+ let renderer = unsafe { clone_arc(renderer) };+ unsafe { renderer.fill_output_buffer(output.into_slice(), plays_at_nanoseconds) }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_realtime_renderer_frames_rendered(+ 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,+) {+ 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);+}++#[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)+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rsindex 1aef7685ba5..35a19698904 100644--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs@@ -459,72 +459,6 @@ impl NodeHandle {}}-#[derive(Clone, Copy)]-#[repr(C)]-pub struct ExternalNodeCallbacks {- pub process: unsafe extern "C" fn(*mut c_void, *const super::render_graph::RenderGraph, *const RenderContext),- pub set_ring: unsafe extern "C" fn(*mut c_void, *mut c_void, u32),- pub for_each_param:- unsafe extern "C" fn(*mut c_void, *mut c_void, unsafe extern "C" fn(*mut c_void, *const RenderAudioParam)),- pub ended: unsafe extern "C" fn(*mut c_void) -> bool,- pub destroy: unsafe extern "C" fn(*mut c_void),-}--pub struct ExternalRenderNode {- pub data: RenderNodeData,- pub cpp_node: *mut c_void,- pub callbacks: ExternalNodeCallbacks,-}--// SAFETY: The C++ node is transferred to the rendering thread together with its Rust base data.-unsafe impl Send for ExternalRenderNode {}-impl Drop for ExternalRenderNode {- fn drop(&mut self) {- unsafe {- (self.callbacks.destroy)(self.cpp_node);- }- }-}--impl RenderNode for ExternalRenderNode {- unsafe fn take_ended_notification(&self) -> bool {- unsafe { (self.callbacks.ended)(self.cpp_node) }- }-- fn data(&self) -> &RenderNodeData {- &self.data- }-- unsafe fn process(&self, graph: &super::render_graph::RenderGraph, context: &RenderContext) {- unsafe {- (self.callbacks.process)(self.cpp_node, graph, context);- }- }-- unsafe fn handle_message(&self, message: &super::node_message::NodeMessage) {- if let super::node_message::NodeMessage::SetMediaStreamSourceRing(message) = message {- unsafe {- (self.callbacks.set_ring)(- self.cpp_node,- message.ring.as_ref().map_or(std::ptr::null_mut(), |ring| ring.pointer),- message.channel_count,- );- }- }- }-- fn for_each_param(&self, callback: &mut dyn FnMut(&RenderAudioParam)) {- unsafe extern "C" fn call(context: *mut c_void, param: *const RenderAudioParam) {- let callback = unsafe { &mut *context.cast::<&mut dyn FnMut(&RenderAudioParam)>() };- callback(unsafe { &*param });- }- let mut callback = callback;- unsafe {- (self.callbacks.for_each_param)(self.cpp_node, (&raw mut callback).cast(), call);- }- }-}-pub trait OutputGraph {fn pull_output(&self, source: u64, output_index: usize, context: &RenderContext) -> *const AudioBus;}@@ -551,25 +485,6 @@ impl RenderAudioParam {}}-#[unsafe(no_mangle)]-pub(crate) extern "C" fn web_audio_node_create_external(- node_id: u64,- input_count: usize,- output_count: usize,- quantum_size: usize,- output_channel_count: usize,- cpp_node: *mut c_void,- callbacks: ExternalNodeCallbacks,-) -> *mut NodeHandle {- Box::into_raw(Box::new(NodeHandle {- node: Box::new(ExternalRenderNode {- data: RenderNodeData::new(node_id, input_count, output_count, quantum_size, output_channel_count),- cpp_node,- callbacks,- }),- }))-}-#[unsafe(no_mangle)]pub(crate) unsafe extern "C" fn web_audio_node_destroy(node: *mut NodeHandle) {drop(unsafe { Box::from_raw(node) });diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rsindex 223bc91a55c..cb16bf45510 100644--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs@@ -51,18 +51,18 @@ fn cpp_max<T: PartialOrd + Copy>(a: T, b: T) -> T {if a < b { b } else { a }}-struct BusRef(*mut AudioBus);+pub(super) struct BusRef(pub(super) *mut AudioBus);impl BusRef {- unsafe fn channel_count(&self) -> usize {+ pub(super) unsafe fn channel_count(&self) -> usize {unsafe { &*self.0 }.channel_count()}- unsafe fn set_channel_count(&self, count: usize) {+ pub(super) unsafe fn set_channel_count(&self, count: usize) {unsafe { &mut *self.0 }.set_channel_count(count);}- unsafe fn zero(&self) {+ pub(super) unsafe fn zero(&self) {unsafe { &mut *self.0 }.zero();}@@ -70,17 +70,17 @@ impl BusRef {unsafe { &*self.0 }.is_silent()}- unsafe fn channel(&self, index: usize) -> &[f32] {+ pub(super) unsafe fn channel(&self, index: usize) -> &[f32] {let (pointer, length) = unsafe { AudioBus::channel_pointer(self.0, index) };unsafe { ak::slice_from_raw_parts(pointer, length) }}- unsafe fn channel_mut(&self, index: usize) -> &mut [f32] {+ pub(super) unsafe fn channel_mut(&self, index: usize) -> &mut [f32] {let (pointer, length) = unsafe { AudioBus::channel_pointer(self.0, index) };unsafe { ak::slice_from_raw_parts_mut(pointer, length) }}- unsafe fn copy_from(&self, source: &BusRef) {+ pub(super) unsafe fn copy_from(&self, source: &BusRef) {unsafe { &mut *self.0 }.copy_from(unsafe { &*source.0 });}@@ -89,7 +89,7 @@ impl BusRef {}}-trait NodeProcessor: Send {+pub(super) trait NodeProcessor: Send {unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext);fn handle_message(&mut self, _message: &NodeMessage) {}@@ -128,7 +128,7 @@ impl<T: NodeProcessor> RenderNode for NativeRenderNode<T> {}}-fn node_handle<T: NodeProcessor + 'static>(data: RenderNodeData, processor: T) -> *mut NodeHandle {+pub(super) fn node_handle<T: NodeProcessor + 'static>(data: RenderNodeData, processor: T) -> *mut NodeHandle {Box::into_raw(Box::new(NodeHandle {node: Box::new(NativeRenderNode {data,diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/renderer_callbacks.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/renderer_callbacks.rsnew file mode 100644index 00000000000..67795042ef8--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/renderer_callbacks.rs@@ -0,0 +1,45 @@+/*+ * 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.rsnew file mode 100644index 00000000000..dfe71f5339f--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_pipe.rs@@ -0,0 +1,231 @@+/*+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use std::cell::UnsafeCell;+use std::ffi::c_void;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Condvar, Mutex};++use super::pipe_callbacks::{CallbackService, PipeCallbacks};+use crate::web_audio::control_message::clone_arc;++#[derive(Clone, Copy)]+#[repr(C)]+pub struct ScriptProcessorPipeConfig {+ pub buffer_size: usize,+ pub input_channel_count: usize,+ pub output_channel_count: usize,+ pub block_count: usize,+ pub waits_for_processing: bool,+}++#[derive(Default)]+struct Block {+ is_owned_by_control_thread: AtomicBool,+ has_output: UnsafeCell<bool>,+}++pub struct ScriptProcessorPipe {+ pub config: ScriptProcessorPipeConfig,+ input_samples: Box<[UnsafeCell<f32>]>,+ output_samples: Box<[UnsafeCell<f32>]>,+ blocks: Box<[Block]>,+ callbacks: CallbackService,+ mutex: Mutex<()>,+ block_returned: Condvar,+ is_shut_down: AtomicBool,+}++// 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 {+ assert!(config.buffer_size > 0);+ assert!(config.block_count >= 2);+ Self {+ config,+ input_samples: (0..config.block_count * config.input_channel_count * config.buffer_size)+ .map(|_| UnsafeCell::new(0.))+ .collect(),+ output_samples: (0..config.block_count * config.output_channel_count * config.buffer_size)+ .map(|_| UnsafeCell::new(0.))+ .collect(),+ blocks: (0..config.block_count).map(|_| Block::default()).collect(),+ callbacks,+ mutex: Mutex::new(()),+ block_returned: Condvar::new(),+ is_shut_down: AtomicBool::new(false),+ }+ }++ pub(crate) unsafe fn input_channel(&self, block: usize, channel: usize) -> (*mut f32, usize) {+ assert!(block < self.config.block_count);+ assert!(channel < self.config.input_channel_count);+ let offset = (block * self.config.input_channel_count + channel) * self.config.buffer_size;+ let samples = self.input_samples.as_ptr().cast::<f32>().cast_mut();+ (unsafe { samples.add(offset) }, self.config.buffer_size)+ }++ pub(crate) unsafe fn output_channel(&self, block: usize, channel: usize) -> (*mut f32, usize) {+ assert!(block < self.config.block_count);+ assert!(channel < self.config.output_channel_count);+ let offset = (block * self.config.output_channel_count + channel) * self.config.buffer_size;+ let samples = self.output_samples.as_ptr().cast::<f32>().cast_mut();+ (unsafe { samples.add(offset) }, self.config.buffer_size)+ }++ pub(crate) unsafe fn has_output(&self, block: usize) -> bool {+ unsafe { *self.blocks[block].has_output.get() }+ }++ pub fn is_block_owned_by_rendering_thread(&self, block: usize) -> bool {+ !self.blocks[block].is_owned_by_control_thread.load(Ordering::Acquire)+ }++ pub fn hand_block_to_control_thread(self: &Arc<Self>, block: usize, start_frame: u64) {+ 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 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;+ }+ let mut locker = self.mutex.lock().unwrap();+ while !self.is_block_owned_by_rendering_thread(block) && !self.is_shut_down() {+ locker = self.block_returned.wait(locker).unwrap();+ }+ }++ pub(crate) unsafe fn hand_block_back_to_rendering_thread(&self, block: usize, has_output: bool) {+ unsafe {+ *self.blocks[block].has_output.get() = has_output;+ }+ self.blocks[block]+ .is_owned_by_control_thread+ .store(false, Ordering::Release);++ // The lock orders this notification after a waiting rendering thread has checked the block's owner.+ let _locker = self.mutex.lock().unwrap();+ self.block_returned.notify_all();+ }++ pub fn shut_down(&self) {+ self.is_shut_down.store(true, Ordering::Release);+ let _locker = self.mutex.lock().unwrap();+ self.block_returned.notify_all();+ }++ pub fn is_shut_down(&self) -> bool {+ 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) });+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_script_pipe_channel(+ pipe: *const ScriptProcessorPipe,+ output: bool,+ block: usize,+ channel: usize,+ result: *mut ak::SpanMut<'static, f32>,+) {+ let (pointer, length) = if output {+ unsafe { (&*pipe).output_channel(block, channel) }+ } else {+ unsafe { (&*pipe).input_channel(block, channel) }+ };+ unsafe {+ *result = ak::SpanMut::new(ak::slice_from_raw_parts_mut(pointer, length));+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_script_pipe_has_output(+ pipe: *const ScriptProcessorPipe,+ block: usize,+) -> bool {+ unsafe { (&*pipe).has_output(block) }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_script_pipe_is_rendering_owner(+ pipe: *const ScriptProcessorPipe,+ block: usize,+) -> bool {+ unsafe { &*pipe }.is_block_owned_by_rendering_thread(block)+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_script_pipe_to_control(+ pipe: *const ScriptProcessorPipe,+ block: usize,+ frame: u64,+) {+ unsafe { clone_arc(pipe) }.hand_block_to_control_thread(block, frame);+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_script_pipe_to_rendering(+ pipe: *const ScriptProcessorPipe,+ block: usize,+ has_output: bool,+) {+ unsafe {+ (&*pipe).hand_block_back_to_rendering_thread(block, has_output);+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_script_pipe_shutdown(pipe: *const ScriptProcessorPipe) {+ unsafe { &*pipe }.shut_down();+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_script_pipe_is_shutdown(pipe: *const ScriptProcessorPipe) -> bool {+ unsafe { &*pipe }.is_shut_down()+}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_render_node.rsnew file mode 100644index 00000000000..fffdf1e13d8--- /dev/null+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/script_processor_render_node.rs@@ -0,0 +1,105 @@+/*+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#![allow(clippy::needless_range_loop)]+use std::sync::Arc;++use super::render_graph::RenderGraph;+use super::render_node::*;+use super::render_nodes::{BusRef, NodeProcessor, node_handle};+use super::script_processor_pipe::ScriptProcessorPipe;+use crate::web_audio::control_message::clone_arc;++struct ScriptProcessorRenderNode {+ pipe: Arc<ScriptProcessorPipe>,+ block: usize,+ frame_in_block: usize,+ block_start_frame: u64,+ block_is_owned: bool,+}++impl NodeProcessor for ScriptProcessorRenderNode {+ unsafe fn process(&mut self, data: &RenderNodeData, graph: &RenderGraph, context: &RenderContext) {+ unsafe {+ let output_bus = BusRef(data.output(0));+ output_bus.set_channel_count(self.pipe.config.output_channel_count.max(1));+ output_bus.zero();+ if self.pipe.is_shut_down() {+ return;+ }++ // https://webaudio.github.io/web-audio-api/#ScriptProcessorNode+ // audioprocess events are only dispatched if the ScriptProcessorNode has at least one input or one output+ // connected.+ if (&*data.input_connections.get())[0].is_empty()+ && (&*data.outgoing_node_connections.get()).is_empty()+ && (&*data.outgoing_param_connections.get()).is_empty()+ {+ return;+ }+ let config = &self.pipe.config;+ if self.frame_in_block == 0 {+ self.block_start_frame = context.quantum_start_frame;+ self.block_is_owned = self.pipe.is_block_owned_by_rendering_thread(self.block);+ }+ if self.block_is_owned {+ if config.input_channel_count > 0 {+ let input_bus = BusRef(data.pull_input(graph, context, 0).cast_mut());+ for channel in 0..config.input_channel_count {+ let (pointer, length) = self.pipe.input_channel(self.block, channel);+ let destination = &mut ak::slice_from_raw_parts_mut(pointer, length)+ [self.frame_in_block..self.frame_in_block + context.quantum_size];+ if channel < input_bus.channel_count() {+ destination.copy_from_slice(input_bus.channel(channel));+ } else {+ destination.fill(0.);+ }+ }+ }+ if self.pipe.has_output(self.block) {+ for channel in 0..config.output_channel_count {+ let (pointer, length) = self.pipe.output_channel(self.block, channel);+ let source = &ak::slice_from_raw_parts(pointer, length)+ [self.frame_in_block..self.frame_in_block + context.quantum_size];+ output_bus.channel_mut(channel).copy_from_slice(source);+ }+ }+ }+ self.frame_in_block += context.quantum_size;+ if self.frame_in_block < config.buffer_size {+ return;+ }+ if self.block_is_owned {+ self.pipe+ .hand_block_to_control_thread(self.block, self.block_start_frame);+ }+ self.block = (self.block + 1) % config.block_count;+ self.frame_in_block = 0;+ }+ }+}++#[unsafe(no_mangle)]+pub(crate) unsafe extern "C" fn web_audio_node_create_script_processor(+ node_id: u64,+ quantum_size: usize,+ pipe: *const ScriptProcessorPipe,+) -> *mut NodeHandle {+ let pipe = unsafe { clone_arc(pipe) };+ let data = RenderNodeData::new(node_id, 1, 1, quantum_size, pipe.config.output_channel_count.max(1));+ assert!(pipe.config.buffer_size.is_multiple_of(quantum_size));+ node_handle(+ data,+ ScriptProcessorRenderNode {+ pipe,+ block: 0,+ frame_in_block: 0,+ block_start_frame: 0,+ block_is_owned: false,+ },+ )+}diff --git a/Libraries/LibWeb/WebAudio/ControlMessageQueue.cpp b/Libraries/LibWeb/WebAudio/ControlMessageQueue.cppindex 44a7888dde8..4e0b9eaa12e 100644--- a/Libraries/LibWeb/WebAudio/ControlMessageQueue.cpp+++ b/Libraries/LibWeb/WebAudio/ControlMessageQueue.cpp@@ -46,8 +46,7 @@ void ControlMessageQueue::enqueue(ControlMessage message)[](AddNode& add_node) -> void* {auto* node = add_node.node.leak_ptr();auto* rust_node = node->release_rust_node();- if (!node->is_external())- delete node;+ delete node;return RustFFI::web_audio_message_add_node(rust_node);},[](RemoveNode const& value) -> void* { return RustFFI::web_audio_message_remove_node(value.node_id.value()); },diff --git a/Libraries/LibWeb/WebAudio/ControlMessageQueue.h b/Libraries/LibWeb/WebAudio/ControlMessageQueue.hindex 4230c2cf308..e292d68e124 100644--- a/Libraries/LibWeb/WebAudio/ControlMessageQueue.h+++ b/Libraries/LibWeb/WebAudio/ControlMessageQueue.h@@ -20,10 +20,11 @@ public:ControlMessageQueue();~ControlMessageQueue();void enqueue(ControlMessage); // Called by the control thread.- void* drain(); // Called by the rendering thread.+ void const* rust_queue() const { return m_queue; }+ void* drain(); // Called by the rendering thread.private:- void* m_queue { nullptr };+ void const* m_queue { nullptr };};}diff --git a/Libraries/LibWeb/WebAudio/Rendering/AnalyserRenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/AnalyserRenderNode.cppindex 73cbb1bdc34..a2302aabc0e 100644--- a/Libraries/LibWeb/WebAudio/Rendering/AnalyserRenderNode.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/AnalyserRenderNode.cpp@@ -5,58 +5,21 @@*/#include <LibWeb/WebAudio/Rendering/AnalyserRenderNode.h>-#include <LibWeb/WebAudio/Rendering/RenderGraph.h>+#include <LibWeb/WebAudio/RustFFI.h>namespace Web::WebAudio::Rendering {AnalyserRenderNode::AnalyserRenderNode(NodeID node_id, size_t quantum_size, NonnullRefPtr<Audio::SpscAudioFrameRing> time_domain_ring)- : RenderNode(node_id, 1, 1, quantum_size)- , m_time_domain_ring(move(time_domain_ring))+ : RenderNode(RustFFI::web_audio_node_create_analyser(node_id.value(), quantum_size,+ { time_domain_ring.ptr(), [](void* ring) { static_cast<Audio::SpscAudioFrameRing*>(ring)->ref(); }, [](void* ring) { static_cast<Audio::SpscAudioFrameRing*>(ring)->unref(); } },+ {+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->channel_count(); },+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->frames_available(); },+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->frames_free(); },+ [](void* ring, Span<float> samples) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->try_pop(samples); },+ [](void* ring, ReadonlySpan<float> samples) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->try_push(samples); },+ })){- VERIFY(m_time_domain_ring->channel_count() == 1);-- // NB: The control thread queues SetChannelConfig before AddNode and messages addressed to- // unknown nodes are dropped, so the constructor must establish the node's channel- // configuration itself.- // https://webaudio.github.io/web-audio-api/#AnalyserNode- set_channel_count(2);- set_channel_count_mode(Bindings::ChannelCountMode::Max);- set_channel_interpretation(Bindings::ChannelInterpretation::Speakers);-- m_mono_scratch.resize(quantum_size);- m_discard_scratch.resize(quantum_size);-}--void AnalyserRenderNode::process(RenderGraph& graph, RenderContext const& context)-{- auto const& input = pull_input(graph, context, 0);-- // The AnalyserNode passes its input through unprocessed.- output(0).copy_from(input);-- // https://webaudio.github.io/web-audio-api/#current-time-domain-data- // The input signal must be down-mixed to mono as if channelCount is 1, channelCountMode- // is "max" and channelInterpretation is "speakers".- // AD-HOC: The down-mix is an unweighted channel average, which matches the speakers rules- // for mono and stereo input; inputs with more channels would need the weighted- // speakers down-mix.- auto channel_count = input.channel_count();- for (size_t frame = 0; frame < context.quantum_size; ++frame) {- float sum = 0;- for (size_t channel_index = 0; channel_index < channel_count; ++channel_index)- sum += input.channel(channel_index)[frame];- m_mono_scratch[frame] = channel_count > 0 ? sum / static_cast<float>(channel_count) : 0.f;- }-- // The ring must always end up holding the most recent samples, so a full ring (the page- // is not currently polling any of the analyser getters) drops its oldest quantum first.- // NB: Popping from the producing side bends the SPSC discipline. It can only race with- // the control thread while the ring is simultaneously full and being drained by a- // getter, in which case the worst outcome is one repeated or skipped quantum in the- // analysis window; the ring's masked indices keep the race memory-safe.- if (m_time_domain_ring->frames_free() < context.quantum_size)- m_time_domain_ring->try_pop(m_discard_scratch);- m_time_domain_ring->try_push(m_mono_scratch);}}diff --git a/Libraries/LibWeb/WebAudio/Rendering/AnalyserRenderNode.h b/Libraries/LibWeb/WebAudio/Rendering/AnalyserRenderNode.hindex 5bfcf9e7d2a..79fb8ae290b 100644--- a/Libraries/LibWeb/WebAudio/Rendering/AnalyserRenderNode.h+++ b/Libraries/LibWeb/WebAudio/Rendering/AnalyserRenderNode.h@@ -17,13 +17,6 @@ namespace Web::WebAudio::Rendering {class AnalyserRenderNode final : public RenderNode {public:AnalyserRenderNode(NodeID, size_t quantum_size, NonnullRefPtr<Audio::SpscAudioFrameRing> time_domain_ring);-- virtual void process(RenderGraph&, RenderContext const&) override;--private:- NonnullRefPtr<Audio::SpscAudioFrameRing> m_time_domain_ring;- Vector<float> m_mono_scratch;- Vector<float> m_discard_scratch;};}diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.cpp b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.cppindex bec5a973d64..b1cf79336ca 100644--- a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.cpp@@ -1,190 +1,172 @@/** Copyright (c) 2026, Ali Mohammad Pur <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/BuiltinWrappers.h>-#include <AK/Math.h>#include <LibCore/EventLoop.h>#include <LibWeb/WebAudio/Rendering/AudioWorkletPipe.h>+#include <LibWeb/WebAudio/RustFFI.h>namespace Web::WebAudio::Rendering {-// The renderer produces a device buffer's worth of quanta in one burst, so lookahead must cover a full burst plus-// scheduling margin. At the 100 ms, 48 kHz defaults this is 38 quanta, a prime level of 48, and capacity 64.-AudioWorkletPipe::Config::RingSizing AudioWorkletPipe::Config::ring_sizing_for_device_latency(u32 device_latency_ms, float sample_rate, size_t quantum_size)-{- VERIFY(sample_rate > 0);- VERIFY(quantum_size > 0);- auto burst_quanta = static_cast<size_t>(AK::ceil(device_latency_ms / 1000.0 * sample_rate / quantum_size));- auto prime_level = ceil_div(burst_quanta * 5, static_cast<size_t>(4));- size_t ring_capacity = 1;- while (ring_capacity < prime_level + max(burst_quanta / 4, static_cast<size_t>(1)))- ring_capacity *= 2;- return { .ring_capacity = ring_capacity, .prime_level = prime_level };-}+struct AudioWorkletPipeCallbacks : AtomicRefCounted<AudioWorkletPipeCallbacks> {+ explicit AudioWorkletPipeCallbacks(Core::EventLoop& loop)+ : event_loop(loop)+ {+ }+ Core::EventLoop& event_loop;+ Function<void()> pump_callback;+};-NonnullRefPtr<AudioWorkletPipe> AudioWorkletPipe::create(Config config, Core::EventLoop& main_thread_event_loop)+NonnullRefPtr<AudioWorkletPipe> AudioWorkletPipe::create(Config config, Core::EventLoop& event_loop){- VERIFY(config.quantum_size > 0);- VERIFY(config.input_channel_capacity.size() == config.input_count);- VERIFY(config.output_channel_capacity.size() == config.output_count);- VERIFY(config.param_is_a_rate.size() == config.param_count);- VERIFY(config.ring_capacity > 0 && popcount(config.ring_capacity) == 1);- VERIFY(config.prime_level <= config.ring_capacity);- return adopt_ref(*new AudioWorkletPipe(move(config), main_thread_event_loop));+ return adopt_ref(*new AudioWorkletPipe(move(config), event_loop));}-AudioWorkletPipe::AudioWorkletPipe(Config config, Core::EventLoop& main_thread_event_loop)+AudioWorkletPipe::AudioWorkletPipe(Config config, Core::EventLoop& event_loop): m_config(move(config))- , m_ring_index_mask(m_config.ring_capacity - 1)- , m_main_thread_event_loop(main_thread_event_loop)+ , m_callbacks(adopt_ref(*new AudioWorkletPipeCallbacks(event_loop))){- auto channel_bytes = m_config.quantum_size * sizeof(float);-- size_t offset = slot_channel_counts_offset + m_config.input_count * sizeof(u32);- m_input_samples_offset.ensure_capacity(m_config.input_count);- for (u32 input = 0; input < m_config.input_count; ++input) {- m_input_samples_offset.unchecked_append(offset);- offset += m_config.input_channel_capacity[input] * channel_bytes;- }- m_param_block_offset.ensure_capacity(m_config.param_count);- m_param_block_length.ensure_capacity(m_config.param_count);- for (u32 param = 0; param < m_config.param_count; ++param) {- m_param_block_offset.unchecked_append(offset);- size_t block_length = m_config.param_is_a_rate[param] ? m_config.quantum_size : 1;- m_param_block_length.unchecked_append(block_length);- offset += block_length * sizeof(float);- }- m_input_slot_stride = round_up_to_power_of_two(offset, slot_alignment);-- offset = slot_channel_counts_offset + m_config.output_count * sizeof(u32);- m_output_samples_offset.ensure_capacity(m_config.output_count);- for (u32 output = 0; output < m_config.output_count; ++output) {- m_output_samples_offset.unchecked_append(offset);- offset += m_config.output_channel_capacity[output] * channel_bytes;- }- m_output_slot_stride = round_up_to_power_of_two(offset, slot_alignment);-- m_output_region_offset = m_config.ring_capacity * m_input_slot_stride;- m_arena = MUST(FixedArray<u8>::create(m_output_region_offset + m_config.ring_capacity * m_output_slot_stride));+ RustFFI::PipeCallbacks callbacks {+ { m_callbacks.ptr(), [](void* service) { static_cast<AudioWorkletPipeCallbacks*>(service)->ref(); }, [](void* service) { static_cast<AudioWorkletPipeCallbacks*>(service)->unref(); } },+ [](void* service, void* task, void (*invoke)(void*)) {+ static_cast<AudioWorkletPipeCallbacks*>(service)->event_loop.deferred_invoke([task, invoke] { invoke(task); });+ },+ [](void* service) {+ auto& callbacks = *static_cast<AudioWorkletPipeCallbacks*>(service);+ if (callbacks.pump_callback)+ callbacks.pump_callback();+ },+ [](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);}-bool AudioWorkletPipe::try_push_input(Function<void(InputSlotWriter&)> const& fill)+AudioWorkletPipe::~AudioWorkletPipe() { RustFFI::web_audio_worklet_pipe_destroy(m_pipe); }+AudioWorkletPipe::Config::RingSizing AudioWorkletPipe::Config::ring_sizing_for_device_latency(u32 latency, float sample_rate, size_t quantum_size){- auto tail = m_input_ring.tail.load(AK::MemoryOrder::memory_order_relaxed);- if (tail - m_input_ring.head.load(AK::MemoryOrder::memory_order_acquire) == m_config.ring_capacity) {- m_dropped_input_count.fetch_add(1, AK::MemoryOrder::memory_order_relaxed);- return false;- }- auto* slot = input_slot(tail);- *reinterpret_cast<u32*>(slot + slot_flags_offset) = 0;- InputSlotWriter writer { *this, slot };- fill(writer);- m_input_ring.tail.store(tail + 1, AK::MemoryOrder::memory_order_release);- return true;+ RingSizing sizing;+ RustFFI::web_audio_worklet_pipe_ring_sizing(latency, sample_rate, quantum_size, &sizing.ring_capacity, &sizing.prime_level);+ return sizing;}-bool AudioWorkletPipe::try_pop_input(Function<void(InputSlotReader const&)> const& read)+bool AudioWorkletPipe::try_push_input(Function<void(InputSlotWriter&)> const& callback){- auto head = m_input_ring.head.load(AK::MemoryOrder::memory_order_relaxed);- if (head == m_input_ring.tail.load(AK::MemoryOrder::memory_order_acquire))- return false;- InputSlotReader reader { *this, input_slot(head) };- read(reader);- m_input_ring.head.store(head + 1, AK::MemoryOrder::memory_order_release);- return true;+ struct Context {+ AudioWorkletPipe& pipe;+ Function<void(InputSlotWriter&)> const& callback;+ } context { *this, callback };+ return RustFFI::web_audio_worklet_pipe_transfer(m_pipe, false, true, &context, [](void* pointer, u8* slot) {+ auto& context = *static_cast<Context*>(pointer);+ InputSlotWriter view { context.pipe, slot };+ context.callback(view);+ });}-bool AudioWorkletPipe::try_push_output(Function<void(OutputSlotWriter&)> const& fill)+bool AudioWorkletPipe::try_pop_input(Function<void(InputSlotReader const&)> const& callback){- auto tail = m_output_ring.tail.load(AK::MemoryOrder::memory_order_relaxed);- if (tail - m_output_ring.head.load(AK::MemoryOrder::memory_order_acquire) == m_config.ring_capacity)- return false;- auto* slot = output_slot(tail);- *reinterpret_cast<u32*>(slot + slot_flags_offset) = 0;- OutputSlotWriter writer { *this, slot };- fill(writer);- m_output_ring.tail.store(tail + 1, AK::MemoryOrder::memory_order_release);- return true;+ struct Context {+ AudioWorkletPipe& pipe;+ Function<void(InputSlotReader const&)> const& callback;+ } context { *this, callback };+ return RustFFI::web_audio_worklet_pipe_transfer(m_pipe, false, false, &context, [](void* pointer, u8* slot) {+ auto& context = *static_cast<Context*>(pointer);+ InputSlotReader view { context.pipe, slot };+ context.callback(view);+ });}-bool AudioWorkletPipe::try_pop_output(Function<void(OutputSlotReader const&)> const& read)+bool AudioWorkletPipe::try_push_output(Function<void(OutputSlotWriter&)> const& callback){- auto head = m_output_ring.head.load(AK::MemoryOrder::memory_order_relaxed);- if (head == m_output_ring.tail.load(AK::MemoryOrder::memory_order_acquire)) {- m_underrun_count.fetch_add(1, AK::MemoryOrder::memory_order_relaxed);- return false;- }- OutputSlotReader reader { *this, output_slot(head) };- read(reader);- m_output_ring.head.store(head + 1, AK::MemoryOrder::memory_order_release);- return true;+ struct Context {+ AudioWorkletPipe& pipe;+ Function<void(OutputSlotWriter&)> const& callback;+ } context { *this, callback };+ return RustFFI::web_audio_worklet_pipe_transfer(m_pipe, true, true, &context, [](void* pointer, u8* slot) {+ auto& context = *static_cast<Context*>(pointer);+ OutputSlotWriter view { context.pipe, slot };+ context.callback(view);+ });}-size_t AudioWorkletPipe::output_occupancy() const+bool AudioWorkletPipe::try_pop_output(Function<void(OutputSlotReader const&)> const& callback){- return m_output_ring.tail.load(AK::MemoryOrder::memory_order_acquire) - m_output_ring.head.load(AK::MemoryOrder::memory_order_relaxed);+ struct Context {+ AudioWorkletPipe& pipe;+ Function<void(OutputSlotReader const&)> const& callback;+ } context { *this, callback };+ return RustFFI::web_audio_worklet_pipe_transfer(m_pipe, true, false, &context, [](void* pointer, u8* slot) {+ auto& context = *static_cast<Context*>(pointer);+ OutputSlotReader view { context.pipe, slot };+ context.callback(view);+ });}-void AudioWorkletPipe::discard_outputs_down_to(size_t target_occupancy)+size_t AudioWorkletPipe::output_occupancy() const { return RustFFI::web_audio_worklet_pipe_output_occupancy(m_pipe); }+void AudioWorkletPipe::discard_outputs_down_to(size_t target) { RustFFI::web_audio_worklet_pipe_discard(m_pipe, target); }+void AudioWorkletPipe::prime_outputs_with_silence(size_t count) { RustFFI::web_audio_worklet_pipe_prime(m_pipe, count); }+void AudioWorkletPipe::request_wakeup() { RustFFI::web_audio_worklet_pipe_request_wakeup(m_pipe); }+void AudioWorkletPipe::clear_wakeup_flag() { RustFFI::web_audio_worklet_pipe_clear_wakeup(m_pipe); }+void AudioWorkletPipe::set_pump_callback(Function<void()> callback) { m_callbacks->pump_callback = move(callback); }+void AudioWorkletPipe::clear_pump_callback() { m_callbacks->pump_callback = nullptr; }+AudioWorkletPipe::State AudioWorkletPipe::state() const { return static_cast<State>(RustFFI::web_audio_worklet_pipe_state(m_pipe)); }+void AudioWorkletPipe::set_state(State state) { RustFFI::web_audio_worklet_pipe_set_state(m_pipe, static_cast<RustFFI::WorkletPipeState>(state)); }+u64 AudioWorkletPipe::underrun_count() const { return RustFFI::web_audio_worklet_pipe_counter(m_pipe, false); }+u64 AudioWorkletPipe::dropped_input_count() const { return RustFFI::web_audio_worklet_pipe_counter(m_pipe, true); }++u64& AudioWorkletPipe::InputSlotWriter::start_frame() { return *RustFFI::web_audio_worklet_slot_frame(m_slot); }+void AudioWorkletPipe::InputSlotWriter::set_had_gap(bool value) { RustFFI::web_audio_worklet_slot_set_flag(m_slot, value); }+u32& AudioWorkletPipe::InputSlotWriter::actual_channel_count(size_t index) { return *RustFFI::web_audio_worklet_slot_count(m_pipe.m_pipe, m_slot, false, index); }+Span<float> AudioWorkletPipe::InputSlotWriter::input_channel(size_t index, size_t channel){- // A consumer-side pop-without-read: advancing the head releases the discarded slots back to the producer. New- // pushes can only move the tail further along, so the snapshot below never overshoots.- auto head = m_output_ring.head.load(AK::MemoryOrder::memory_order_relaxed);- auto tail = m_output_ring.tail.load(AK::MemoryOrder::memory_order_acquire);- if (tail - head <= target_occupancy)- return;- m_output_ring.head.store(tail - target_occupancy, AK::MemoryOrder::memory_order_release);+ Span<float> samples;+ RustFFI::web_audio_worklet_slot_channel(m_pipe.m_pipe, m_slot, false, index, channel, &samples);+ return samples;}--void AudioWorkletPipe::prime_outputs_with_silence(size_t count)+Span<float> AudioWorkletPipe::InputSlotWriter::param_block(size_t param){- for (size_t i = 0; i < count; ++i) {- bool pushed = try_push_output([&](OutputSlotWriter& slot) {- slot.start_frame() = 0;- slot.set_processor_active(true);- for (u32 output = 0; output < m_config.output_count; ++output) {- auto channel_count = m_config.output_channel_count_matches_input ? 1u : m_config.output_channel_capacity[output];- slot.actual_channel_count(output) = channel_count;- for (u32 channel = 0; channel < channel_count; ++channel)- slot.output_channel(output, channel).fill(0);- }- });- VERIFY(pushed);- }+ Span<float> samples;+ RustFFI::web_audio_worklet_slot_param(m_pipe.m_pipe, m_slot, param, &samples);+ return samples;}-void AudioWorkletPipe::request_wakeup()+u64 AudioWorkletPipe::InputSlotReader::start_frame() const { return *RustFFI::web_audio_worklet_slot_frame(const_cast<u8*>(m_slot)); }+bool AudioWorkletPipe::InputSlotReader::had_gap() const { return RustFFI::web_audio_worklet_slot_flag(m_slot); }+u32 AudioWorkletPipe::InputSlotReader::actual_channel_count(size_t index) const { return *RustFFI::web_audio_worklet_slot_count(m_pipe.m_pipe, const_cast<u8*>(m_slot), false, index); }+ReadonlySpan<float> AudioWorkletPipe::InputSlotReader::input_channel(size_t index, size_t channel) const{- // Coalesce a device burst into one main-thread pump instead of posting once per quantum.- if (m_pump_scheduled.exchange(true, AK::MemoryOrder::memory_order_acq_rel))- return;- m_main_thread_event_loop.deferred_invoke([self = NonnullRefPtr(*this)] {- if (self->state() == State::ShutDown)- return;- if (self->m_pump_callback)- self->m_pump_callback();- });+ Span<float> samples;+ RustFFI::web_audio_worklet_slot_channel(m_pipe.m_pipe, const_cast<u8*>(m_slot), false, index, channel, &samples);+ return samples;}--void AudioWorkletPipe::clear_wakeup_flag()+ReadonlySpan<float> AudioWorkletPipe::InputSlotReader::param_block(size_t param) const{- // A read-modify-write rather than a plain store: it synchronizes with the audio thread's exchange in- // request_wakeup(), so whenever that exchange elides a wakeup (returns true), everything the audio thread- // pushed beforehand is visible to this pump run's drain.- m_pump_scheduled.exchange(false, AK::MemoryOrder::memory_order_acq_rel);+ Span<float> samples;+ RustFFI::web_audio_worklet_slot_param(m_pipe.m_pipe, const_cast<u8*>(m_slot), param, &samples);+ return samples;}-void AudioWorkletPipe::set_pump_callback(Function<void()> pump_callback)+u64& AudioWorkletPipe::OutputSlotWriter::start_frame() { return *RustFFI::web_audio_worklet_slot_frame(m_slot); }+void AudioWorkletPipe::OutputSlotWriter::set_processor_active(bool value) { RustFFI::web_audio_worklet_slot_set_flag(m_slot, value); }+u32& AudioWorkletPipe::OutputSlotWriter::actual_channel_count(size_t index) { return *RustFFI::web_audio_worklet_slot_count(m_pipe.m_pipe, m_slot, true, index); }+Span<float> AudioWorkletPipe::OutputSlotWriter::output_channel(size_t index, size_t channel){- m_pump_callback = move(pump_callback);+ Span<float> samples;+ RustFFI::web_audio_worklet_slot_channel(m_pipe.m_pipe, m_slot, true, index, channel, &samples);+ return samples;}-void AudioWorkletPipe::clear_pump_callback()+u64 AudioWorkletPipe::OutputSlotReader::start_frame() const { return *RustFFI::web_audio_worklet_slot_frame(const_cast<u8*>(m_slot)); }+bool AudioWorkletPipe::OutputSlotReader::processor_active() const { return RustFFI::web_audio_worklet_slot_flag(m_slot); }+u32 AudioWorkletPipe::OutputSlotReader::actual_channel_count(size_t index) const { return *RustFFI::web_audio_worklet_slot_count(m_pipe.m_pipe, const_cast<u8*>(m_slot), true, index); }+ReadonlySpan<float> AudioWorkletPipe::OutputSlotReader::output_channel(size_t index, size_t channel) const{- m_pump_callback = nullptr;+ Span<float> samples;+ RustFFI::web_audio_worklet_slot_channel(m_pipe.m_pipe, const_cast<u8*>(m_slot), true, index, channel, &samples);+ return samples;}}diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.h b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.hindex 43b13c2cb3f..321590a2157 100644--- a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.h+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletPipe.h@@ -1,5 +1,6 @@/** Copyright (c) 2026, Ali Mohammad Pur <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/@@ -39,6 +40,8 @@ namespace Web::WebAudio::Rendering {// Slots are accessed in place through the writer/reader views below, which are only valid inside the callback they// are passed to. A slot's unwritten regions keep stale data from the previous trip around the ring, so a writer// must set the channel counts it wants a reader to trust; the flags are cleared on every push.+struct AudioWorkletPipeCallbacks;+class WEB_API AudioWorkletPipe final : public AtomicRefCounted<AudioWorkletPipe> {public:struct Config {@@ -147,6 +150,9 @@ public:static NonnullRefPtr<AudioWorkletPipe> create(Config, Core::EventLoop& main_thread_event_loop);+ ~AudioWorkletPipe();+ void const* rust_pipe() const { return m_pipe; }+Config const& config() const { return m_config; }// Audio-thread side (input producer, output consumer):@@ -190,170 +196,21 @@ public:// Either thread:- State state() const { return static_cast<State>(m_state.load(AK::MemoryOrder::memory_order_acquire)); }- void set_state(State state) { m_state.store(to_underlying(state), AK::MemoryOrder::memory_order_release); }+ State state() const;+ void set_state(State);// A single atomic store, so this is safe to call from a GC finalizer on either thread.void request_shutdown() { set_state(State::ShutDown); }- u64 underrun_count() const { return m_underrun_count.load(AK::MemoryOrder::memory_order_relaxed); }- u64 dropped_input_count() const { return m_dropped_input_count.load(AK::MemoryOrder::memory_order_relaxed); }+ u64 underrun_count() const;+ u64 dropped_input_count() const;private:AudioWorkletPipe(Config, Core::EventLoop& main_thread_event_loop);- static constexpr size_t slot_flags_offset = sizeof(u64);- static constexpr size_t slot_channel_counts_offset = sizeof(u64) + sizeof(u32);- static constexpr size_t slot_alignment = 64;- static constexpr u32 input_slot_flag_had_gap = 1u << 0;- static constexpr u32 output_slot_flag_processor_active = 1u << 0;-- u8* input_slot(size_t counter) { return m_arena.data() + (counter & m_ring_index_mask) * m_input_slot_stride; }- u8* output_slot(size_t counter) { return m_arena.data() + m_output_region_offset + (counter & m_ring_index_mask) * m_output_slot_stride; }-- struct Ring {- AK_CACHE_ALIGNED Atomic<size_t> tail { 0 }; // Producer-owned: the next slot to write.- AK_CACHE_ALIGNED Atomic<size_t> head { 0 }; // Consumer-owned: the next slot to read.- };-Config m_config;- size_t m_ring_index_mask { 0 };-- size_t m_input_slot_stride { 0 };- size_t m_output_slot_stride { 0 };- size_t m_output_region_offset { 0 };- Vector<size_t> m_input_samples_offset;- Vector<size_t> m_output_samples_offset;- Vector<size_t> m_param_block_offset;- Vector<size_t> m_param_block_length;- FixedArray<u8> m_arena;-- Ring m_input_ring;- Ring m_output_ring;-- Core::EventLoop& m_main_thread_event_loop;- Function<void()> m_pump_callback;- Atomic<bool> m_pump_scheduled { false };-- Atomic<u8> m_state { to_underlying(State::Running) };- Atomic<u64> m_underrun_count { 0 };- Atomic<u64> m_dropped_input_count { 0 };+ NonnullRefPtr<AudioWorkletPipeCallbacks> m_callbacks;+ void const* m_pipe { nullptr };};-inline u64& AudioWorkletPipe::InputSlotWriter::start_frame()-{- return *reinterpret_cast<u64*>(m_slot);-}--inline void AudioWorkletPipe::InputSlotWriter::set_had_gap(bool had_gap)-{- auto& flags = *reinterpret_cast<u32*>(m_slot + slot_flags_offset);- if (had_gap)- flags |= input_slot_flag_had_gap;- else- flags &= ~input_slot_flag_had_gap;-}--inline u32& AudioWorkletPipe::InputSlotWriter::actual_channel_count(size_t input)-{- VERIFY(input < m_pipe.m_config.input_count);- return *reinterpret_cast<u32*>(m_slot + slot_channel_counts_offset + input * sizeof(u32));-}--inline Span<float> AudioWorkletPipe::InputSlotWriter::input_channel(size_t input, size_t channel)-{- VERIFY(input < m_pipe.m_config.input_count);- VERIFY(channel < m_pipe.m_config.input_channel_capacity[input]);- auto* samples = reinterpret_cast<float*>(m_slot + m_pipe.m_input_samples_offset[input]) + channel * m_pipe.m_config.quantum_size;- return { samples, m_pipe.m_config.quantum_size };-}--inline Span<float> AudioWorkletPipe::InputSlotWriter::param_block(size_t param)-{- VERIFY(param < m_pipe.m_config.param_count);- return { reinterpret_cast<float*>(m_slot + m_pipe.m_param_block_offset[param]), m_pipe.m_param_block_length[param] };-}--inline u64 AudioWorkletPipe::InputSlotReader::start_frame() const-{- return *reinterpret_cast<u64 const*>(m_slot);-}--inline bool AudioWorkletPipe::InputSlotReader::had_gap() const-{- return (*reinterpret_cast<u32 const*>(m_slot + slot_flags_offset) & input_slot_flag_had_gap) != 0;-}--inline u32 AudioWorkletPipe::InputSlotReader::actual_channel_count(size_t input) const-{- VERIFY(input < m_pipe.m_config.input_count);- return *reinterpret_cast<u32 const*>(m_slot + slot_channel_counts_offset + input * sizeof(u32));-}--inline ReadonlySpan<float> AudioWorkletPipe::InputSlotReader::input_channel(size_t input, size_t channel) const-{- VERIFY(input < m_pipe.m_config.input_count);- VERIFY(channel < m_pipe.m_config.input_channel_capacity[input]);- auto const* samples = reinterpret_cast<float const*>(m_slot + m_pipe.m_input_samples_offset[input]) + channel * m_pipe.m_config.quantum_size;- return { samples, m_pipe.m_config.quantum_size };-}--inline ReadonlySpan<float> AudioWorkletPipe::InputSlotReader::param_block(size_t param) const-{- VERIFY(param < m_pipe.m_config.param_count);- return { reinterpret_cast<float const*>(m_slot + m_pipe.m_param_block_offset[param]), m_pipe.m_param_block_length[param] };-}--inline u64& AudioWorkletPipe::OutputSlotWriter::start_frame()-{- return *reinterpret_cast<u64*>(m_slot);-}--inline void AudioWorkletPipe::OutputSlotWriter::set_processor_active(bool processor_active)-{- auto& flags = *reinterpret_cast<u32*>(m_slot + slot_flags_offset);- if (processor_active)- flags |= output_slot_flag_processor_active;- else- flags &= ~output_slot_flag_processor_active;-}--inline u32& AudioWorkletPipe::OutputSlotWriter::actual_channel_count(size_t output)-{- VERIFY(output < m_pipe.m_config.output_count);- return *reinterpret_cast<u32*>(m_slot + slot_channel_counts_offset + output * sizeof(u32));-}--inline Span<float> AudioWorkletPipe::OutputSlotWriter::output_channel(size_t output, size_t channel)-{- VERIFY(output < m_pipe.m_config.output_count);- VERIFY(channel < m_pipe.m_config.output_channel_capacity[output]);- auto* samples = reinterpret_cast<float*>(m_slot + m_pipe.m_output_samples_offset[output]) + channel * m_pipe.m_config.quantum_size;- return { samples, m_pipe.m_config.quantum_size };-}--inline u64 AudioWorkletPipe::OutputSlotReader::start_frame() const-{- return *reinterpret_cast<u64 const*>(m_slot);-}--inline bool AudioWorkletPipe::OutputSlotReader::processor_active() const-{- return (*reinterpret_cast<u32 const*>(m_slot + slot_flags_offset) & output_slot_flag_processor_active) != 0;-}--inline u32 AudioWorkletPipe::OutputSlotReader::actual_channel_count(size_t output) const-{- VERIFY(output < m_pipe.m_config.output_count);- return *reinterpret_cast<u32 const*>(m_slot + slot_channel_counts_offset + output * sizeof(u32));-}--inline ReadonlySpan<float> AudioWorkletPipe::OutputSlotReader::output_channel(size_t output, size_t channel) const-{- VERIFY(output < m_pipe.m_config.output_count);- VERIFY(channel < m_pipe.m_config.output_channel_capacity[output]);- auto const* samples = reinterpret_cast<float const*>(m_slot + m_pipe.m_output_samples_offset[output]) + channel * m_pipe.m_config.quantum_size;- return { samples, m_pipe.m_config.quantum_size };-}-}diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.cppindex 69aa6951906..2035b8f678c 100644--- a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.cpp@@ -5,102 +5,25 @@*/#include <LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.h>-#include <LibWeb/WebAudio/Rendering/RenderGraph.h>+#include <LibWeb/WebAudio/RustFFI.h>namespace Web::WebAudio::Rendering {+static void* create_render_node(NodeID node_id, size_t input_count, size_t output_count, size_t quantum_size, Vector<u32> const& output_channel_capacities, size_t channel_count, Bindings::ChannelCountMode channel_count_mode, Bindings::ChannelInterpretation channel_interpretation, AudioWorkletPipe& pipe, Vector<NonnullRefPtr<RenderAudioParam>> const& params)+{+ Vector<void const*> native_params;+ for (auto const& param : params)+ native_params.append(param->rust_param());+ return RustFFI::web_audio_node_create_audio_worklet(node_id.value(), input_count, output_count, quantum_size, output_channel_capacities.span(), channel_count, static_cast<RustFFI::ChannelCountMode>(channel_count_mode), static_cast<RustFFI::ChannelInterpretation>(channel_interpretation), pipe.rust_pipe(), native_params.span());+}+AudioWorkletRenderNode::AudioWorkletRenderNode(NodeID node_id, size_t input_count, size_t output_count, size_t quantum_size,Vector<u32> output_channel_capacities,size_t channel_count, Bindings::ChannelCountMode channel_count_mode, Bindings::ChannelInterpretation channel_interpretation,NonnullRefPtr<AudioWorkletPipe> pipe,Vector<NonnullRefPtr<RenderAudioParam>> params)- : RenderNode(node_id, input_count, output_count, quantum_size, /* output_channel_count */ 1)- , m_pipe(move(pipe))- , m_params(move(params))- , m_output_channel_capacities(move(output_channel_capacities))-{- // Channel configuration must be set here: the SetChannelConfig messages queued during node- // construction arrive before our AddNode and are dropped by the graph.- set_channel_count(channel_count);- set_channel_count_mode(channel_count_mode);- set_channel_interpretation(channel_interpretation);- m_param_scratch.resize(quantum_size);-}--AudioWorkletRenderNode::~AudioWorkletRenderNode() = default;--void AudioWorkletRenderNode::for_each_param(Function<void(RenderAudioParam&)> const& callback)+ : RenderNode(create_render_node(node_id, input_count, output_count, quantum_size, output_channel_capacities, channel_count, channel_count_mode, channel_interpretation, pipe, params)){- for (auto& param : m_params)- callback(*param);-}--void AudioWorkletRenderNode::process(RenderGraph& graph, RenderContext const& context)-{- // A failed (processor threw) or shut-down (node finalized / context closed) worklet renders- // silence forever; the pump side owns the state transitions.- if (m_pipe->state() != AudioWorkletPipe::State::Running) {- for (size_t output = 0; output < output_count(); ++output)- this->output(output).zero();- return;- }-- (void)m_pipe->try_push_input([&](AudioWorkletPipe::InputSlotWriter& slot) {- slot.start_frame() = context.quantum_start_frame;- for (size_t input = 0; input < input_count(); ++input) {- // Unlike the render graph's silent mono bus, an unconnected worklet input- // is represented by an empty channel array in process().- if (!has_input_connections(input)) {- slot.actual_channel_count(input) = 0;- continue;- }- auto const& input_bus = pull_input(graph, context, input);- auto capacity_channels = m_pipe->config().input_channel_capacity[input];- auto channels_to_copy = min(input_bus.channel_count(), static_cast<size_t>(capacity_channels));- slot.actual_channel_count(input) = channels_to_copy;- for (size_t channel = 0; channel < channels_to_copy; ++channel) {- auto destination = slot.input_channel(input, channel);- auto source = input_bus.channel(channel);- VERIFY(destination.size() == source.size());- __builtin_memcpy(destination.data(), source.data(), source.size() * sizeof(float));- }- }- for (size_t param_index = 0; param_index < m_params.size(); ++param_index) {- auto block = slot.param_block(param_index);- // a-rate params fill the whole block; k-rate blocks are a single value. compute() handles- // both through the shared timeline + any audio-rate param connections.- m_param_scratch.resize(block.size());- m_params[param_index]->compute(graph, context, m_param_scratch.span().slice(0, block.size()));- __builtin_memcpy(block.data(), m_param_scratch.data(), block.size() * sizeof(float));- }- });- m_pipe->request_wakeup();-- bool popped = m_pipe->try_pop_output([&](AudioWorkletPipe::OutputSlotReader const& slot) {- for (size_t output = 0; output < output_count(); ++output) {- auto output_bus = this->output(output);- auto channel_count = min(static_cast<size_t>(slot.actual_channel_count(output)), static_cast<size_t>(m_output_channel_capacities[output]));- output_bus.set_channel_count(max(channel_count, static_cast<size_t>(1)));- output_bus.zero();- for (size_t channel = 0; channel < channel_count; ++channel) {- auto source = slot.output_channel(output, channel);- auto destination = output_bus.channel(channel);- auto frames = min(source.size(), destination.size());- __builtin_memcpy(destination.data(), source.data(), frames * sizeof(float));- }- }- });- if (!popped) {- for (size_t output = 0; output < output_count(); ++output)- this->output(output).zero();- return;- }-- // Latency clamp: after a main-thread stall, the pump refills the output ring past the configured- // lookahead (the audio side emitted silence meanwhile). Discard the excess so the stall does not- // permanently ratchet up this node's latency.- if (m_pipe->output_occupancy() > m_pipe->config().prime_level)- m_pipe->discard_outputs_down_to(m_pipe->config().prime_level);}}diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.h b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.hindex 310675fa49d..b04cfc72638 100644--- a/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.h+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioWorkletRenderNode.h@@ -22,17 +22,6 @@ public:size_t channel_count, Bindings::ChannelCountMode, Bindings::ChannelInterpretation,NonnullRefPtr<AudioWorkletPipe>,Vector<NonnullRefPtr<RenderAudioParam>> params);-- virtual ~AudioWorkletRenderNode() override;-- virtual void process(RenderGraph&, RenderContext const&) override;- virtual void for_each_param(Function<void(RenderAudioParam&)> const&) override;--private:- NonnullRefPtr<AudioWorkletPipe> m_pipe;- Vector<NonnullRefPtr<RenderAudioParam>> m_params;- Vector<float> m_param_scratch;- Vector<u32> m_output_channel_capacities;};}diff --git a/Libraries/LibWeb/WebAudio/Rendering/MediaStreamDestinationRenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/MediaStreamDestinationRenderNode.cppindex 322fb52d774..778cffb25b1 100644--- a/Libraries/LibWeb/WebAudio/Rendering/MediaStreamDestinationRenderNode.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/MediaStreamDestinationRenderNode.cpp@@ -6,59 +6,50 @@#include <LibCore/EventLoop.h>#include <LibWeb/WebAudio/Rendering/MediaStreamDestinationRenderNode.h>-#include <LibWeb/WebAudio/Rendering/RenderGraph.h>+#include <LibWeb/WebAudio/RustFFI.h>namespace Web::WebAudio::Rendering {-MediaStreamDestinationRenderNode::MediaStreamDestinationRenderNode(NodeID node_id, size_t quantum_size, size_t channel_count, NonnullRefPtr<MediaStreamDestinationSharedState> shared_state, Core::EventLoop& control_thread_event_loop)- : RenderNode(node_id, 1, 1, quantum_size, channel_count)- , m_shared_state(move(shared_state))- , m_control_thread_event_loop(control_thread_event_loop)- , m_mix_bus(channel_count, quantum_size)-{- // NB: The control thread queues SetChannelConfig before AddNode and messages addressed to- // unknown nodes are dropped, so the constructor must establish the node's channel- // configuration itself.- // https://webaudio.github.io/web-audio-api/#MediaStreamAudioDestinationNode- set_channel_count(channel_count);- set_channel_count_mode(Bindings::ChannelCountMode::Explicit);- set_channel_interpretation(Bindings::ChannelInterpretation::Speakers);+struct DestinationCallbackService : AtomicRefCounted<DestinationCallbackService> {+ DestinationCallbackService(NonnullRefPtr<MediaStreamDestinationSharedState> state, Core::EventLoop& loop)+ : shared_state(move(state))+ , event_loop(loop)+ {+ }+ NonnullRefPtr<MediaStreamDestinationSharedState> shared_state;+ Core::EventLoop& event_loop;+};- m_interleaved_scratch.resize(quantum_size * channel_count);+static void* create_render_node(NodeID node_id, size_t quantum_size, size_t channel_count, NonnullRefPtr<MediaStreamDestinationSharedState> shared_state, Core::EventLoop& event_loop)+{+ auto service = adopt_ref(*new DestinationCallbackService(shared_state, event_loop));+ RustFFI::PipeCallbacks callbacks {+ { service.ptr(), [](void* service) { static_cast<DestinationCallbackService*>(service)->ref(); }, [](void* service) { static_cast<DestinationCallbackService*>(service)->unref(); } },+ [](void* service, void* task, void (*invoke)(void*)) {+ static_cast<DestinationCallbackService*>(service)->event_loop.deferred_invoke([task, invoke] { invoke(task); });+ },+ [](void* service) {+ auto& shared_state = *static_cast<DestinationCallbackService*>(service)->shared_state;+ if (shared_state.drain)+ shared_state.drain();+ },+ [](void*, size_t, u64) { return false; },+ };+ return RustFFI::web_audio_node_create_media_stream_destination(node_id.value(), quantum_size, channel_count,+ { shared_state->ring.ptr(), [](void* ring) { static_cast<Audio::SpscAudioFrameRing*>(ring)->ref(); }, [](void* ring) { static_cast<Audio::SpscAudioFrameRing*>(ring)->unref(); } },+ {+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->channel_count(); },+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->frames_available(); },+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->frames_free(); },+ [](void* ring, Span<float> samples) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->try_pop(samples); },+ [](void* ring, ReadonlySpan<float> samples) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->try_push(samples); },+ },+ callbacks);}-void MediaStreamDestinationRenderNode::process(RenderGraph& graph, RenderContext const& context)+MediaStreamDestinationRenderNode::MediaStreamDestinationRenderNode(NodeID node_id, size_t quantum_size, size_t channel_count, NonnullRefPtr<MediaStreamDestinationSharedState> shared_state, Core::EventLoop& control_thread_event_loop)+ : RenderNode(create_render_node(node_id, quantum_size, channel_count, move(shared_state), control_thread_event_loop)){- auto const& input = pull_input(graph, context, 0);-- // AD-HOC: The spec gives this node zero outputs, but RenderGraph only pulls nodes that- // have at least one, so the render node exposes its input as a passthrough- // output. This keeps the node processing every quantum and also makes it audible- // when a page connects it onward.- output(0).copy_from(input);-- // Mix the input to the track's channel count and interleave it into the shared ring. If- // the control thread has stalled and the ring is full, the newest frames are dropped; the- // consumer resynchronizes when it drains.- m_mix_bus.zero();- m_mix_bus.sum_from(input, channel_interpretation());- auto channel_count = m_mix_bus.channel_count();- for (size_t frame = 0; frame < context.quantum_size; ++frame) {- for (size_t channel_index = 0; channel_index < channel_count; ++channel_index)- m_interleaved_scratch[frame * channel_count + channel_index] = m_mix_bus.channel(channel_index)[frame];- }- m_shared_state->ring->try_push(m_interleaved_scratch);-- // Coalesced render→control notification, following the renderer's ended-sources pattern:- // at most one queued drain per rendered burst, so the control thread wakes up ~10 times- // per second rather than once per quantum.- if (!m_shared_state->drain_pending.exchange(true, AK::MemoryOrder::memory_order_acq_rel)) {- m_control_thread_event_loop.deferred_invoke([shared_state = m_shared_state] {- shared_state->drain_pending.store(false, AK::MemoryOrder::memory_order_release);- if (shared_state->drain)- shared_state->drain();- });- }}}diff --git a/Libraries/LibWeb/WebAudio/Rendering/MediaStreamDestinationRenderNode.h b/Libraries/LibWeb/WebAudio/Rendering/MediaStreamDestinationRenderNode.hindex 04ab509abb3..ea1dba0e453 100644--- a/Libraries/LibWeb/WebAudio/Rendering/MediaStreamDestinationRenderNode.h+++ b/Libraries/LibWeb/WebAudio/Rendering/MediaStreamDestinationRenderNode.h@@ -17,8 +17,6 @@namespace Web::WebAudio::Rendering {-// The render thread only touches the ring and pending flag; the control thread owns the drain-// callback so its captured GC roots never cross threads.struct MediaStreamDestinationSharedState final : public AtomicRefCounted<MediaStreamDestinationSharedState> {explicit MediaStreamDestinationSharedState(NonnullRefPtr<Audio::SpscAudioFrameRing> ring): ring(move(ring))@@ -27,14 +25,7 @@ struct MediaStreamDestinationSharedState final : public AtomicRefCounted<MediaStNonnullRefPtr<Audio::SpscAudioFrameRing> ring;- // Set by the rendering thread when it schedules a drain on the control thread and cleared- // by the control thread when the drain runs, coalescing the notifications down to one- // wakeup per rendered burst.- Atomic<bool> drain_pending { false };-- // Control thread only: drains the ring and forwards the frames to the node's track. Set- // when the node is created and cleared in its finalizer, which also makes any drain still- // queued by the rendering thread a no-op.+ // Only the control thread invokes or clears this callback.Function<void()> drain;};@@ -42,14 +33,6 @@ struct MediaStreamDestinationSharedState final : public AtomicRefCounted<MediaStclass MediaStreamDestinationRenderNode final : public RenderNode {public:MediaStreamDestinationRenderNode(NodeID, size_t quantum_size, size_t channel_count, NonnullRefPtr<MediaStreamDestinationSharedState>, Core::EventLoop& control_thread_event_loop);-- virtual void process(RenderGraph&, RenderContext const&) override;--private:- NonnullRefPtr<MediaStreamDestinationSharedState> m_shared_state;- Core::EventLoop& m_control_thread_event_loop;- AudioBus m_mix_bus;- Vector<float> m_interleaved_scratch;};}diff --git a/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.cppindex 9335af6dcfb..817ad316575 100644--- a/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.cpp@@ -5,62 +5,19 @@*/#include <LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.h>-#include <LibWeb/WebAudio/Rendering/RenderGraph.h>+#include <LibWeb/WebAudio/RustFFI.h>namespace Web::WebAudio::Rendering {MediaStreamSourceRenderNode::MediaStreamSourceRenderNode(NodeID node_id, size_t quantum_size)- : RenderNode(node_id, 0, 1, quantum_size, 2)+ : RenderNode(RustFFI::web_audio_node_create_media_stream_source(node_id.value(), quantum_size, {+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->channel_count(); },+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->frames_available(); },+ [](void* ring) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->frames_free(); },+ [](void* ring, Span<float> samples) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->try_pop(samples); },+ [](void* ring, ReadonlySpan<float> samples) { return static_cast<Audio::SpscAudioFrameRing*>(ring)->try_push(samples); },+ })){- // NB: The control thread queues SetChannelConfig before AddNode and messages addressed to- // unknown nodes are dropped, so the constructor must establish the node's channel- // configuration itself.- // https://webaudio.github.io/web-audio-api/#MediaStreamAudioSourceNode- set_channel_count(2);- set_channel_count_mode(Bindings::ChannelCountMode::Max);- set_channel_interpretation(Bindings::ChannelInterpretation::Speakers);-}--void MediaStreamSourceRenderNode::handle_message(NodeMessage const& message)-{- message.visit(- [&](SetMediaStreamSourceRing const& set_ring) {- m_ring = set_ring.ring;- // NB: The ring's own channel count wins over the message field so the interleaved- // stride below can never disagree with the ring's layout.- m_channel_count = m_ring ? m_ring->channel_count() : max(set_ring.channel_count, 1u);- },- [](auto const&) { });-}--void MediaStreamSourceRenderNode::process(RenderGraph&, RenderContext const& context)-{- auto source_output = output(0);-- // The number of channels of the output corresponds to the number of channels of the track.- source_output.set_channel_count(m_channel_count);- source_output.zero();- if (!m_ring)- return;-- // Drain the ring sequentially, up to one render quantum. When the producer has not- // delivered enough frames yet (startup, scheduling jitter), the tail of the quantum stays- // silent; skipping ahead to "the most recent frames" instead would drift against the- // producer's cadence and repeat or drop content.- auto frames_to_pop = min(context.quantum_size, m_ring->frames_available());- if (frames_to_pop == 0)- return;-- m_interleaved_scratch.resize(frames_to_pop * m_channel_count);- auto frames_popped = m_ring->try_pop(m_interleaved_scratch);-- for (size_t channel_index = 0; channel_index < m_channel_count; ++channel_index) {- auto output_samples = source_output.channel(channel_index);- for (size_t frame = 0; frame < frames_popped; ++frame)- output_samples[frame] = m_interleaved_scratch[frame * m_channel_count + channel_index];- }-- // The producer converts track samples to the context's sample rate before filling the ring.}}diff --git a/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.h b/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.hindex 6f4c69d889a..6c9541fb64a 100644--- a/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.h+++ b/Libraries/LibWeb/WebAudio/Rendering/MediaStreamSourceRenderNode.h@@ -17,14 +17,6 @@ namespace Web::WebAudio::Rendering {class MediaStreamSourceRenderNode final : public RenderNode {public:MediaStreamSourceRenderNode(NodeID, size_t quantum_size);-- virtual void process(RenderGraph&, RenderContext const&) override;- virtual void handle_message(NodeMessage const&) override;--private:- RefPtr<Audio::SpscAudioFrameRing> m_ring;- u32 m_channel_count { 1 };- Vector<float> m_interleaved_scratch;};}diff --git a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp b/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cppindex a9918c5f8d2..14b36ef5d52 100644--- a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.cpp@@ -1,161 +1,77 @@/** 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/Rendering/RenderNodes.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(NonnullRefPtr<ControlMessageQueue> 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(move(control_message_queue), destination_node_id, number_of_channels, length, sample_rate, quantum_size));}OfflineAudioRenderer::OfflineAudioRenderer(NonnullRefPtr<ControlMessageQueue> control_message_queue, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size)- : m_control_message_queue(move(control_message_queue))- , m_destination_node_id(destination_node_id)- , m_number_of_channels(number_of_channels)- , m_length(length)- , m_sample_rate(sample_rate)- , m_quantum_size(quantum_size)- , m_main_thread_event_loop(Core::EventLoop::current())+ : 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->rust_queue(), destination_node_id.value(), number_of_channels, length, sample_rate, quantum_size, callbacks);m_rendered_channels.resize(number_of_channels);- for (auto& channel : m_rendered_channels)- channel.resize(length);-}--void OfflineAudioRenderer::set_on_complete(Function<void()> on_complete)-{- m_on_complete = move(on_complete);-}--void OfflineAudioRenderer::set_on_suspended(Function<void(double)> on_suspended)-{- m_on_suspended = move(on_suspended);-}--void OfflineAudioRenderer::set_on_sources_ended(Function<void(Vector<NodeID> const&)> on_sources_ended)-{- m_on_sources_ended = move(on_sources_ended);+ 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_on_complete = nullptr;- m_on_suspended = nullptr;- m_on_sources_ended = nullptr;-}--void OfflineAudioRenderer::start_rendering()-{- VERIFY(!m_thread);- m_graph.set_destination(m_destination_node_id);- m_thread = MUST(Threading::Thread::try_create("OfflineAudioRenderer"sv, [self = NonnullRefPtr(*this)] {- return self->render_thread_main();- }));- m_thread->start();- m_thread->detach();-}--// Ends rendering without completing it, unblocking the rendering thread if it is waiting in a suspension.-void OfflineAudioRenderer::stop()-{- MutexLocker locker(m_suspend_mutex);- m_shutting_down = true;- m_resume_signal.broadcast();-}--// Registers a suspension at the given render quantum boundary. Returns false if the rendering thread already looked-// for suspensions at that boundary.-bool OfflineAudioRenderer::request_suspend(u64 frame)-{- MutexLocker locker(m_suspend_mutex);- if (frame < m_next_suspend_check_frame)- return false;- m_suspend_frames.set(frame);- return true;-}--void OfflineAudioRenderer::resume()-{- MutexLocker locker(m_suspend_mutex);- m_suspended = false;- m_resume_signal.broadcast();-}--void OfflineAudioRenderer::post_to_control_thread(Function<void(OfflineAudioRenderer&)> callback)-{- m_main_thread_event_loop.deferred_invoke([self = NonnullRefPtr(*this), callback = move(callback)] {- callback(*self);- });-}--intptr_t OfflineAudioRenderer::render_thread_main()-{- u64 current_frame = 0;- while (current_frame < m_length) {- // Suspend rendering if a suspension was scheduled at this render quantum boundary.- {- MutexLocker locker(m_suspend_mutex);- if (m_shutting_down)- return 0;- m_next_suspend_check_frame = current_frame + m_quantum_size;- if (m_suspend_frames.remove(current_frame)) {- m_suspended = true;- auto suspend_time = current_frame / static_cast<double>(m_sample_rate);- post_to_control_thread([suspend_time](OfflineAudioRenderer& renderer) {- if (renderer.m_on_suspended)- renderer.m_on_suspended(suspend_time);- });- m_resume_signal.wait_while([&] { return m_suspended && !m_shutting_down; });- if (m_shutting_down)- return 0;- }- }-- m_graph.apply_control_messages(m_control_message_queue->drain());-- RenderContext context {- .sample_rate = m_sample_rate,- .quantum_size = m_quantum_size,- .quantum_start_frame = current_frame,- };- m_graph.render_quantum(context);-- // Copy the destination's captured output into the rendered buffer.- if (auto maybe_destination_output = m_graph.destination_output(); maybe_destination_output.has_value()) {- auto const& destination_output = *maybe_destination_output;- auto frames_to_copy = min(m_quantum_size, m_length - current_frame);- for (size_t channel_index = 0; channel_index < m_number_of_channels; ++channel_index) {- if (channel_index >= destination_output.channel_count())- break;- auto samples = destination_output.channel(channel_index);- for (size_t frame = 0; frame < frames_to_copy; ++frame)- m_rendered_channels[channel_index][current_frame + frame] = samples[frame];- }- }-- current_frame += m_quantum_size;- m_frames_rendered.store(current_frame);-- if (auto ended_nodes = m_graph.take_ended_nodes(); !ended_nodes.is_empty()) {- post_to_control_thread([ended_nodes = move(ended_nodes)](OfflineAudioRenderer& renderer) {- if (renderer.m_on_sources_ended)- renderer.m_on_sources_ended(ended_nodes);- });- }- }-- post_to_control_thread([](OfflineAudioRenderer& renderer) {- if (renderer.m_on_complete)- renderer.m_on_complete();- });- return 0;+ 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); }+bool OfflineAudioRenderer::is_rendering_started() const { return RustFFI::web_audio_offline_renderer_started(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.hindex 1838700e83f..a46e8d89c98 100644--- a/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h+++ b/Libraries/LibWeb/WebAudio/Rendering/OfflineAudioRenderer.h@@ -1,5 +1,6 @@/** Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/@@ -33,10 +34,14 @@ namespace Web::WebAudio::Rendering {// 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(NonnullRefPtr<ControlMessageQueue>, 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()>);@@ -54,46 +59,18 @@ public:bool request_suspend(u64 frame);void resume();- bool is_rendering_started() const { return m_thread != nullptr; }- u64 frames_rendered() const { return m_frames_rendered.load(); }+ bool is_rendering_started() const;+ u64 frames_rendered() const;// Only safe to access on the control thread after the completion callback was invoked.- Vector<Vector<float>> const& rendered_channels() const { return m_rendered_channels; }+ Vector<ReadonlySpan<float>> const& rendered_channels() const { return m_rendered_channels; }private:OfflineAudioRenderer(NonnullRefPtr<ControlMessageQueue>, NodeID destination_node_id, size_t number_of_channels, size_t length, float sample_rate, size_t quantum_size);- intptr_t render_thread_main();- void post_to_control_thread(Function<void(OfflineAudioRenderer&)>);-- NonnullRefPtr<ControlMessageQueue> m_control_message_queue;- NodeID m_destination_node_id;- size_t m_number_of_channels { 0 };- size_t m_length { 0 };- float m_sample_rate { 0 };- size_t m_quantum_size { 0 };-- Core::EventLoop& m_main_thread_event_loop;- RefPtr<Threading::Thread> m_thread;- RenderGraph m_graph;- Vector<Vector<float>> m_rendered_channels;- Atomic<u64> m_frames_rendered { 0 };-- Function<void()> m_on_complete;- Function<void(double)> m_on_suspended;- Function<void(Vector<NodeID> const&)> m_on_sources_ended;-- Mutex m_suspend_mutex;- ConditionVariable m_resume_signal { m_suspend_mutex };- HashTable<u64> m_suspend_frames;-- // The next render quantum boundary at which the rendering thread will look for a scheduled suspension. It is- // published under the same lock that guards the suspension set, so a suspension can never be registered for a- // boundary the rendering thread has already checked.- u64 m_next_suspend_check_frame { 0 };-- bool m_suspended { false };- bool m_shutting_down { false };+ 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.cppindex eff50ef54ab..cb170163622 100644--- a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.cpp@@ -1,5 +1,6 @@/** Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/@@ -7,36 +8,56 @@#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(NonnullRefPtr<ControlMessageQueue> 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(move(control_message_queue), destination_node_id, sample_rate, quantum_size, move(audio_output_factory)));}RealtimeAudioRenderer::RealtimeAudioRenderer(NonnullRefPtr<ControlMessageQueue> control_message_queue, NodeID destination_node_id, float sample_rate, size_t quantum_size, NonnullRefPtr<Media::AudioOutputFactory> audio_output_factory)- : m_control_message_queue(move(control_message_queue))- , m_destination_node_id(destination_node_id)- , m_sample_rate(sample_rate)- , m_quantum_size(quantum_size)- , m_main_thread_event_loop(Core::EventLoop::current())+ : 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->rust_queue(), destination_node_id.value(), sample_rate, quantum_size, callbacks);}-RealtimeAudioRenderer::~RealtimeAudioRenderer() = default;+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_on_sources_ended = move(on_sources_ended);+ m_callbacks->on_sources_ended = move(on_sources_ended);}void RealtimeAudioRenderer::clear_callbacks(){- m_on_sources_ended = nullptr;+ m_callbacks->on_sources_ended = nullptr;}void RealtimeAudioRenderer::start_rendering()@@ -54,145 +75,64 @@ void RealtimeAudioRenderer::start_rendering()void RealtimeAudioRenderer::prepare_to_start_rendering(){VERIFY(!m_playback_stream);- m_graph.set_destination(m_destination_node_id);+ RustFFI::web_audio_realtime_renderer_prepare(m_renderer);}void RealtimeAudioRenderer::set_playback_stream(NonnullRefPtr<Audio::PlaybackStream> stream){- if (m_shutting_down.load()) {+ 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();- m_device_channel_count = specification.channel_count();- m_device_sample_rate = specification.sample_rate();- m_device_bus = make<AudioBus>(specification.channel_count(), m_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.- m_playhead_step = m_sample_rate / static_cast<double>(specification.sample_rate());+ 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 (self->m_shutting_down.load())+ if (RustFFI::web_audio_realtime_renderer_is_shutting_down(self->m_renderer))return;self->m_playback_stream = nullptr;self->start_rendering();};- if (!m_suspended.load())+ if (!RustFFI::web_audio_realtime_renderer_is_suspended(m_renderer))stream->resume()->when_rejected([](auto&&) { });}void RealtimeAudioRenderer::resume(){- m_suspended.store(false);+ RustFFI::web_audio_realtime_renderer_set_suspended(m_renderer, false);if (m_playback_stream)m_playback_stream->resume()->when_rejected([](auto&&) { });}void RealtimeAudioRenderer::suspend(){- m_suspended.store(true);+ 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(){- m_shutting_down.store(true);+ 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;}}-// The amount of audio the output device has played so far, in seconds.double RealtimeAudioRenderer::output_time_played() const{- auto maybe_anchor = m_output_anchor.read();- if (!maybe_anchor.has_value() || m_device_sample_rate == 0)- return 0;- auto const& anchor = maybe_anchor.value();- auto seconds_since_buffer_started = max<i64>(0, MonotonicTime::now().nanoseconds() - anchor.plays_at_nanoseconds) / 1e9;- auto buffer_start_seconds = anchor.first_frame_index / static_cast<double>(m_device_sample_rate);- auto buffer_end_seconds = anchor.end_frame_index / static_cast<double>(m_device_sample_rate);- return min(buffer_start_seconds + seconds_since_buffer_started, buffer_end_seconds);+ 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){- if (m_shutting_down.load() || m_device_channel_count == 0)- return {};-- auto channel_count = m_device_channel_count;- auto frames_requested = buffer.size() / channel_count;- m_output_anchor.store({ .first_frame_index = m_frames_output, .end_frame_index = m_frames_output + frames_requested, .plays_at_nanoseconds = buffer_starts_playing_at.nanoseconds() });- m_frames_output += frames_requested;- for (size_t frame = 0; frame < frames_requested; ++frame) {- auto first_frame = static_cast<size_t>(m_playhead);- auto fraction = static_cast<float>(m_playhead - first_frame);-- // Interpolation between adjacent rendered frames requires one frame of lookahead.- while (m_pending_samples.size() / channel_count < first_frame + 2)- render_quantum_into_pending_samples();-- for (size_t channel = 0; channel < channel_count; ++channel) {- auto sample = m_pending_samples[first_frame * channel_count + channel];- if (fraction != 0.f) {- auto next_sample = m_pending_samples[(first_frame + 1) * channel_count + channel];- sample += fraction * (next_sample - sample);- }- buffer[frame * channel_count + channel] = sample;- }- m_playhead += m_playhead_step;- }-- // Trim rendered frames preceding the playhead. If resampling advances the playhead beyond the rendered frames,- // carry the remaining offset into the next callback.- auto rendered_frames = m_pending_samples.size() / channel_count;- auto consumed_frames = min(static_cast<size_t>(m_playhead), rendered_frames);- if (consumed_frames > 0) {- m_pending_samples.remove(0, consumed_frames * channel_count);- m_playhead -= consumed_frames;- }- return buffer;+ auto count = RustFFI::web_audio_realtime_renderer_fill(m_renderer, buffer, buffer_starts_playing_at.nanoseconds());+ return buffer.trim(count);}-void RealtimeAudioRenderer::render_quantum_into_pending_samples()-{- m_graph.apply_control_messages(m_control_message_queue->drain());-- RenderContext context {- .sample_rate = m_sample_rate,- .quantum_size = m_quantum_size,- .quantum_start_frame = m_frames_rendered.load(),- };- m_graph.render_quantum(context);-- // Mix the destination's output to the stream's channel layout and append it as interleaved samples.- if (m_device_bus) {- auto& device_bus = *m_device_bus;- device_bus.zero();- if (auto destination_output = m_graph.destination_output(); destination_output.has_value())- device_bus.sum_from(*destination_output, Bindings::ChannelInterpretation::Speakers);-- auto sample_offset = m_pending_samples.size();- m_pending_samples.resize(sample_offset + m_quantum_size * m_device_channel_count);- for (size_t frame = 0; frame < m_quantum_size; ++frame) {- for (size_t channel = 0; channel < m_device_channel_count; ++channel)- m_pending_samples[sample_offset + frame * m_device_channel_count + channel] = device_bus.channel(channel)[frame];- }- }-- m_frames_rendered.fetch_add(m_quantum_size);-- if (auto ended_nodes = m_graph.take_ended_nodes(); !ended_nodes.is_empty()) {- m_main_thread_event_loop.deferred_invoke([self = NonnullRefPtr(*this), ended_nodes = move(ended_nodes)] {- if (self->m_on_sources_ended)- self->m_on_sources_ended(ended_nodes);- });- }-}+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.hindex 9d457097355..2eccad0bd38 100644--- a/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h+++ b/Libraries/LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h@@ -1,5 +1,6 @@/** Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/@@ -29,6 +30,8 @@ namespace Web::WebAudio::Rendering {// 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@@ -48,7 +51,7 @@ public:void suspend();void stop();- u64 frames_rendered() const { return m_frames_rendered.load(); }+ u64 frames_rendered() const;// The amount of audio the output device has played so far, in seconds.double output_time_played() const;@@ -59,41 +62,11 @@ private:void prepare_to_start_rendering();void set_playback_stream(NonnullRefPtr<Audio::PlaybackStream>);ReadonlySpan<float> fill_output_buffer(Span<float>, MonotonicTime buffer_starts_playing_at);- void render_quantum_into_pending_samples();-- // The output buffer most recently handed to the stream, and when its first frame plays.- struct OutputAnchor {- u64 first_frame_index { 0 };- u64 end_frame_index { 0 };- i64 plays_at_nanoseconds { 0 };- };-- NonnullRefPtr<ControlMessageQueue> m_control_message_queue;- NodeID m_destination_node_id;- float m_sample_rate { 0 };- size_t m_quantum_size { 0 };- Core::EventLoop& m_main_thread_event_loop;+ NonnullRefPtr<RealtimeAudioRendererCallbacks> m_callbacks;NonnullRefPtr<Media::AudioOutputFactory> m_audio_output_factory;RefPtr<Audio::PlaybackStream> m_playback_stream;-- Function<void(Vector<NodeID> const&)> m_on_sources_ended;-- Atomic<u64> m_frames_rendered { 0 };- Atomic<bool> m_suspended { false };- Atomic<bool> m_shutting_down { false };- SeqLock<OutputAnchor> m_output_anchor;-- // State below is only used on the audio thread, except that the device configuration is recorded on the control- // thread after stream creation, before the first data request callback can run.- RenderGraph m_graph;- OwnPtr<AudioBus> m_device_bus;- size_t m_device_channel_count { 0 };- u32 m_device_sample_rate { 0 };- u64 m_frames_output { 0 };- double m_playhead_step { 1 };- double m_playhead { 0 };- Vector<float> m_pending_samples;+ void const* m_renderer { nullptr };};}diff --git a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cppindex 19ceadfb21a..20ff30d8c9c 100644--- a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cpp@@ -51,20 +51,6 @@ void RenderAudioParam::compute(RenderGraph& graph, RenderContext const& context,return bus.has_value() ? bus->rust_bus() : nullptr; }, &rust_context, output);}-RenderNode::RenderNode(NodeID node_id, size_t input_count, size_t output_count, size_t quantum_size, size_t output_channel_count)- : m_external(true)-{- m_node = RustFFI::web_audio_node_create_external(node_id.value(), input_count, output_count, quantum_size, output_channel_count, this, {- .process = [](void* node, void const* graph, RustFFI::RenderContext const* context) {- RenderGraph borrowed_graph(const_cast<void*>(graph), false);- RenderContext render_context { context->sample_rate, context->quantum_size, context->quantum_start_frame };- static_cast<RenderNode*>(node)->process(borrowed_graph, render_context); },- .set_ring = [](void* node, void* ring, u32 channel_count) { static_cast<RenderNode*>(node)->handle_message(NodeMessage { SetMediaStreamSourceRing { {}, static_cast<Audio::SpscAudioFrameRing*>(ring), channel_count } }); },- .for_each_param = [](void* node, void* context, void (*callback)(void*, void const*)) { static_cast<RenderNode*>(node)->for_each_param([&](RenderAudioParam& param) { callback(context, param.rust_param()); }); },- .ended = [](void* node) { return static_cast<RenderNode*>(node)->take_ended_notification(); },- .destroy = [](void* node) { if (static_cast<RenderNode*>(node)->m_transferred) delete static_cast<RenderNode*>(node); },- });-}RenderNode::RenderNode(void* node): m_node(node){@@ -77,7 +63,6 @@ RenderNode::~RenderNode()void* RenderNode::release_rust_node(){m_owned = false;- m_transferred = true;return m_node;}NodeID RenderNode::node_id() const { return RustFFI::web_audio_node_id(m_node); }diff --git a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.h b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.hindex ffb33be74fe..36b28532f6b 100644--- a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.h+++ b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.h@@ -53,7 +53,6 @@ class WEB_API RenderNode {public:AK_ALLOC_WITH_KMALLOC;- RenderNode(NodeID, size_t input_count, size_t output_count, size_t quantum_size, size_t output_channel_count = 1);virtual ~RenderNode();NodeID node_id() const;size_t input_count() const;@@ -77,12 +76,7 @@ public:NonnullRefPtr<RenderAudioParam> destination;size_t output_index;};- virtual void process(RenderGraph&, RenderContext const&) { VERIFY_NOT_REACHED(); }- virtual void handle_message(NodeMessage const&) { }- virtual void for_each_param(Function<void(RenderAudioParam&)> const&) { }- virtual bool take_ended_notification() { return false; }void* release_rust_node();- bool is_external() const { return m_external; }protected:explicit RenderNode(void*);@@ -91,8 +85,6 @@ protected:private:void* m_node { nullptr };bool m_owned { true };- bool m_external { false };- bool m_transferred { false };};}diff --git a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.cpp b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.cppindex 5fd0525cb94..a2a7797e55d 100644--- a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.cpp@@ -1,96 +1,72 @@/** 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 {-// 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.-NonnullRefPtr<ScriptProcessorPipe> ScriptProcessorPipe::create(Config config, Core::EventLoop& control_thread_event_loop)+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){- VERIFY(config.buffer_size > 0);- VERIFY(config.block_count >= 2);- return adopt_ref(*new ScriptProcessorPipe(config, control_thread_event_loop));+ return adopt_ref(*new ScriptProcessorPipe(move(config), event_loop));}-ScriptProcessorPipe::ScriptProcessorPipe(Config config, Core::EventLoop& control_thread_event_loop)- : m_config(config)- , m_input_samples(MUST(FixedArray<float>::create(config.block_count * config.input_channel_count * config.buffer_size)))- , m_output_samples(MUST(FixedArray<float>::create(config.block_count * config.output_channel_count * config.buffer_size)))- , m_blocks(MUST(FixedArray<Block>::create(config.block_count)))- , m_control_thread_event_loop(control_thread_event_loop)+ScriptProcessorPipe::ScriptProcessorPipe(Config config, Core::EventLoop& event_loop)+ : m_config(move(config))+ , 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 { m_config.buffer_size, m_config.input_channel_count, m_config.output_channel_count, m_config.block_count, m_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); }Span<float> ScriptProcessorPipe::input_channel(size_t block, size_t channel){- VERIFY(block < m_config.block_count);- VERIFY(channel < m_config.input_channel_count);- return m_input_samples.span().slice((block * m_config.input_channel_count + channel) * m_config.buffer_size, m_config.buffer_size);+ Span<float> samples;+ RustFFI::web_audio_script_pipe_channel(m_pipe, false, block, channel, &samples);+ return samples;}-Span<float> ScriptProcessorPipe::output_channel(size_t block, size_t channel){- VERIFY(block < m_config.block_count);- VERIFY(channel < m_config.output_channel_count);- return m_output_samples.span().slice((block * m_config.output_channel_count + channel) * m_config.buffer_size, m_config.buffer_size);-}--bool ScriptProcessorPipe::is_block_owned_by_rendering_thread(size_t block) const-{- return !m_blocks[block].is_owned_by_control_thread.load(AK::MemoryOrder::memory_order_acquire);-}--void ScriptProcessorPipe::hand_block_to_control_thread(size_t block, u64 start_frame)-{- m_blocks[block].is_owned_by_control_thread.store(true, AK::MemoryOrder::memory_order_release);- m_control_thread_event_loop.deferred_invoke([self = NonnullRefPtr(*this), block, start_frame] {- if (self->m_process_callback && !self->is_shut_down())- self->m_process_callback(block, start_frame);- else- self->hand_block_back_to_rendering_thread(block, false);- });-- if (!m_config.waits_for_processing)- return;- MutexLocker locker(m_mutex);- m_block_returned.wait_while([&] {- return !is_block_owned_by_rendering_thread(block) && !is_shut_down();- });-}--void ScriptProcessorPipe::set_process_callback(Function<void(size_t, u64)> process_callback)-{- m_process_callback = move(process_callback);-}--void ScriptProcessorPipe::clear_process_callback()-{- m_process_callback = nullptr;-}--void ScriptProcessorPipe::hand_block_back_to_rendering_thread(size_t block, bool has_output)-{- m_blocks[block].has_output = has_output;- m_blocks[block].is_owned_by_control_thread.store(false, AK::MemoryOrder::memory_order_release);-- // The lock orders this notification after a waiting rendering thread has checked the block's owner.- MutexLocker locker(m_mutex);- m_block_returned.broadcast();-}--void ScriptProcessorPipe::shut_down()-{- m_is_shut_down.store(true, AK::MemoryOrder::memory_order_release);- MutexLocker locker(m_mutex);- m_block_returned.broadcast();+ Span<float> samples;+ RustFFI::web_audio_script_pipe_channel(m_pipe, true, block, channel, &samples);+ return samples;}+bool ScriptProcessorPipe::has_output(size_t block) const { return RustFFI::web_audio_script_pipe_has_output(m_pipe, block); }+bool ScriptProcessorPipe::is_block_owned_by_rendering_thread(size_t block) const { return RustFFI::web_audio_script_pipe_is_rendering_owner(m_pipe, block); }+void ScriptProcessorPipe::hand_block_to_control_thread(size_t block, u64 frame) { RustFFI::web_audio_script_pipe_to_control(m_pipe, block, frame); }+void ScriptProcessorPipe::hand_block_back_to_rendering_thread(size_t block, bool has_output) { RustFFI::web_audio_script_pipe_to_rendering(m_pipe, block, has_output); }+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; }+void ScriptProcessorPipe::shut_down() { RustFFI::web_audio_script_pipe_shutdown(m_pipe); }+bool ScriptProcessorPipe::is_shut_down() const { return RustFFI::web_audio_script_pipe_is_shutdown(m_pipe); }}diff --git a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.hindex 3f816365187..e4c758f58b7 100644--- a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h+++ b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h@@ -1,5 +1,6 @@/** Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/@@ -20,6 +21,8 @@namespace Web::WebAudio::Rendering {+struct ScriptProcessorPipeCallbacks;+class WEB_API ScriptProcessorPipe final : public AtomicRefCounted<ScriptProcessorPipe> {public:struct Config {@@ -32,11 +35,14 @@ public:static NonnullRefPtr<ScriptProcessorPipe> create(Config, Core::EventLoop& control_thread_event_loop);+ ~ScriptProcessorPipe();+ void const* rust_pipe() const { return m_pipe; }+Config const& config() const { return m_config; }Span<float> input_channel(size_t block, size_t channel);Span<float> output_channel(size_t block, size_t channel);- bool has_output(size_t block) const { return m_blocks[block].has_output; }+ bool has_output(size_t block) const;bool is_block_owned_by_rendering_thread(size_t block) const;void hand_block_to_control_thread(size_t block, u64 start_frame);@@ -46,27 +52,14 @@ public:void hand_block_back_to_rendering_thread(size_t block, bool has_output);void shut_down();- bool is_shut_down() const { return m_is_shut_down.load(AK::MemoryOrder::memory_order_acquire); }+ bool is_shut_down() const;private:ScriptProcessorPipe(Config, Core::EventLoop& control_thread_event_loop);- struct Block {- Atomic<bool> is_owned_by_control_thread { false };- bool has_output { false };- };-Config m_config;- FixedArray<float> m_input_samples;- FixedArray<float> m_output_samples;- FixedArray<Block> m_blocks;-- Core::EventLoop& m_control_thread_event_loop;- Function<void(size_t, u64)> m_process_callback;-- Mutex m_mutex;- ConditionVariable m_block_returned { m_mutex };- Atomic<bool> m_is_shut_down { false };+ NonnullRefPtr<ScriptProcessorPipeCallbacks> m_callbacks;+ void const* m_pipe { nullptr };};}diff --git a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.cppindex 48b187e2746..db2642d9ca8 100644--- a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.cpp+++ b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.cpp@@ -1,69 +1,18 @@/** Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <LibWeb/WebAudio/Rendering/RenderGraph.h>#include <LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.h>+#include <LibWeb/WebAudio/RustFFI.h>namespace Web::WebAudio::Rendering {ScriptProcessorRenderNode::ScriptProcessorRenderNode(NodeID node_id, size_t quantum_size, NonnullRefPtr<ScriptProcessorPipe> pipe)- : RenderNode(node_id, 1, 1, quantum_size, max(pipe->config().output_channel_count, 1uz))- , m_pipe(move(pipe))+ : RenderNode(RustFFI::web_audio_node_create_script_processor(node_id.value(), quantum_size, pipe->rust_pipe())){- VERIFY(m_pipe->config().buffer_size % quantum_size == 0);-}--ScriptProcessorRenderNode::~ScriptProcessorRenderNode() = default;--void ScriptProcessorRenderNode::process(RenderGraph& graph, RenderContext const& context)-{- auto output_bus = output(0);- output_bus.set_channel_count(max(m_pipe->config().output_channel_count, 1uz));- output_bus.zero();- if (m_pipe->is_shut_down())- return;-- // https://webaudio.github.io/web-audio-api/#ScriptProcessorNode- // audioprocess events are only dispatched if the ScriptProcessorNode has at least one input or one output- // connected.- if (!has_input_connections(0) && outgoing_node_connection_count() == 0 && outgoing_param_connection_count() == 0)- return;-- auto const& config = m_pipe->config();- if (m_frame_in_block == 0) {- m_block_start_frame = context.quantum_start_frame;- m_block_is_owned = m_pipe->is_block_owned_by_rendering_thread(m_block);- }-- if (m_block_is_owned) {- if (config.input_channel_count > 0) {- auto const& input_bus = pull_input(graph, context, 0);- for (size_t channel = 0; channel < config.input_channel_count; ++channel) {- auto destination = m_pipe->input_channel(m_block, channel).slice(m_frame_in_block, context.quantum_size);- if (channel < input_bus.channel_count())- input_bus.channel(channel).copy_to(destination);- else- destination.fill(0);- }- }-- if (m_pipe->has_output(m_block)) {- for (size_t channel = 0; channel < config.output_channel_count; ++channel)- m_pipe->output_channel(m_block, channel).slice(m_frame_in_block, context.quantum_size).copy_to(output_bus.channel(channel));- }- }-- m_frame_in_block += context.quantum_size;- if (m_frame_in_block < config.buffer_size)- return;-- if (m_block_is_owned)- m_pipe->hand_block_to_control_thread(m_block, m_block_start_frame);- m_block = (m_block + 1) % config.block_count;- m_frame_in_block = 0;}}diff --git a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.h b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.hindex db677e29b4f..b34e65bcab0 100644--- a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.h+++ b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.h@@ -1,5 +1,6 @@/** Copyright (c) 2026, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/@@ -15,16 +16,6 @@ namespace Web::WebAudio::Rendering {class ScriptProcessorRenderNode final : public RenderNode {public:ScriptProcessorRenderNode(NodeID, size_t quantum_size, NonnullRefPtr<ScriptProcessorPipe>);- virtual ~ScriptProcessorRenderNode() override;-- virtual void process(RenderGraph&, RenderContext const&) override;--private:- NonnullRefPtr<ScriptProcessorPipe> m_pipe;- size_t m_block { 0 };- size_t m_frame_in_block { 0 };- u64 m_block_start_frame { 0 };- bool m_block_is_owned { false };};}