Skip to content

Truly independent web browser

LibWeb: Reserve WebAudio mixing storage before rendering

Shannon Booth1d07e318d8bc
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rs
index 2c3d42a35ae..03de94a6e5c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rs
@@ -14,7 +14,7 @@ use libweb_rust::web_audio::audio_param_timeline::{AudioParamTimeline, InsertRes
use libweb_rust::web_audio::rendering::render_node::RenderAudioParam;
use super::audio_node::AnyAudioNode;
-use super::base_audio_context::AnyBaseAudioContext;
+use super::base_audio_context::{AnyBaseAudioContext, BaseAudioContext};
use crate::bindings::interface::{Ref, Wrappable, allocate};
use crate::bindings::{CallContext, Exception, WebIdlResult};
@@ -87,6 +87,7 @@ impl AudioParam {
min_value,
max_value,
automation_rate,
+ BaseAudioContext::RENDER_QUANTUM_SIZE as usize,
));
Self {
context,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs
index 86455f83cdf..e3a59899787 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs
@@ -190,7 +190,7 @@ impl BaseAudioContext {
// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer-numberofchannels
// > An implementation MUST support at least 32 channels.
// Other browsers appear to only allow 32 channels - so let's limit ourselves to that too.
- pub(crate) const MAX_NUMBER_OF_CHANNELS: u32 = 32;
+ pub(crate) const MAX_NUMBER_OF_CHANNELS: u32 = libweb_rust::web_audio::MAX_NUMBER_OF_CHANNELS as u32;
// https://webaudio.github.io/web-audio-api/#sample-rates
// Implementations MUST support sample rates between 3000 Hz and 768000 Hz, inclusive. A NotSupportedError MUST
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/allocation_count.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/allocation_count.rs
index d185d4dd58c..c8a9574841e 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/allocation_count.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/allocation_count.rs
@@ -32,7 +32,7 @@ thread_local! {
/// How many times a thread allocated or reallocated.
#[derive(Clone, Copy, Debug)]
-pub(super) struct Allocations {
+pub(crate) struct Allocations {
pub everywhere: u64,
/// Those inside a `StyleSection`: invalidating, restyling and installing.
pub in_style: u64,
@@ -111,7 +111,7 @@ unsafe impl GlobalAlloc for CountingAllocator {
/// Runs `body`, answering what it answers and how many times the calling thread allocated or
/// reallocated meanwhile. What other threads allocate is not counted.
-pub(super) fn count_allocations<T>(body: impl FnOnce() -> T) -> (T, Allocations) {
+pub(crate) fn count_allocations<T>(body: impl FnOnce() -> T) -> (T, Allocations) {
static PRINTS_BACKTRACES_CACHE: OnceLock<bool> = OnceLock::new();
let prints_backtraces =
*PRINTS_BACKTRACES_CACHE.get_or_init(|| std::env::var_os("LIBWEB_TEST_ALLOCATION_BACKTRACES").is_some());
diff --git a/Libraries/LibWeb/Rust/src/web_audio/mod.rs b/Libraries/LibWeb/Rust/src/web_audio/mod.rs
index e34d032f037..8630afaa2a0 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/mod.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/mod.rs
@@ -10,3 +10,5 @@ pub mod control_message;
pub mod control_message_queue;
pub mod control_thread;
pub mod rendering;
+
+pub const MAX_NUMBER_OF_CHANNELS: usize = 32;
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.rs
index a07e7d89ef5..7bd65c45c6c 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/analyser_render_node.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/analyser_render_node.rs
@@ -9,6 +9,7 @@ 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::MAX_NUMBER_OF_CHANNELS;
use crate::web_audio::control_message::FfiSharedCppObject;
// https://webaudio.github.io/web-audio-api/#AnalyserNode
@@ -61,7 +62,8 @@ pub unsafe fn create_analyser_render_node(
callbacks,
};
assert_eq!(time_domain_ring.channel_count(), 1);
- let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ let mut data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ data.reserve_output_channels(0, MAX_NUMBER_OF_CHANNELS);
// 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
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs
index b0bc6d48b4e..f91b933f4ae 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/audio_bus.rs
@@ -13,24 +13,24 @@ const CENTER: usize = 2;
const SURROUND_LEFT: usize = 4;
const SURROUND_RIGHT: usize = 5;
-// A block of audio samples for a single render quantum, holding one buffer of frames per channel.
+// A block of planar audio samples for a single render quantum.
pub struct AudioBus {
- channels: Vec<Vec<f32>>,
+ samples: Vec<f32>,
+ channel_count: usize,
frame_count: usize,
}
impl AudioBus {
pub fn new(channel_count: usize, frame_count: usize) -> Self {
- let mut bus = Self {
- channels: Vec::new(),
+ Self {
+ samples: vec![0.; channel_count * frame_count],
+ channel_count,
frame_count,
- };
- bus.set_channel_count(channel_count);
- bus
+ }
}
pub fn channel_count(&self) -> usize {
- self.channels.len()
+ self.channel_count
}
pub fn frame_count(&self) -> usize {
@@ -38,50 +38,47 @@ impl AudioBus {
}
pub fn channel(&self, index: usize) -> &[f32] {
- &self.channels[index]
+ assert!(index < self.channel_count);
+ let start = index * self.frame_count;
+ &self.samples[start..start + self.frame_count]
}
pub fn channel_mut(&mut self, index: usize) -> &mut [f32] {
- &mut self.channels[index]
+ assert!(index < self.channel_count);
+ let start = index * self.frame_count;
+ &mut self.samples[start..start + self.frame_count]
}
pub(crate) unsafe fn channel_pointer(bus: *mut Self, index: usize) -> (*mut f32, usize) {
- let channels = unsafe { &raw mut (*bus).channels };
- assert!(index < unsafe { (*channels).len() });
- let channel = unsafe { (*channels).as_mut_ptr().add(index) };
- unsafe { ((*channel).as_mut_ptr(), (*channel).len()) }
+ assert!(index < unsafe { (*bus).channel_count });
+ let frame_count = unsafe { (*bus).frame_count };
+ let samples = unsafe { &raw mut (*bus).samples };
+ unsafe { ((*samples).as_mut_ptr().add(index * frame_count), frame_count) }
}
pub fn zero(&mut self) {
- for channel in &mut self.channels {
- channel.fill(0.);
- }
+ self.samples.fill(0.);
}
pub fn is_silent(&self) -> bool {
- !self
- .channels
- .iter()
- .any(|channel| channel.iter().any(|&sample| sample != 0.))
+ self.samples.iter().all(|&sample| sample == 0.)
+ }
+
+ pub(crate) fn reserve_channels(&mut self, channel_capacity: usize) {
+ let extra_samples = (channel_capacity * self.frame_count).saturating_sub(self.samples.len());
+ self.samples.reserve_exact(extra_samples);
}
// Preserve active channels' samples and zero newly added channels.
pub fn set_channel_count(&mut self, channel_count: usize) {
- if self.channels.len() == channel_count {
- return;
- }
- self.channels.resize_with(channel_count, Vec::new);
- for channel in &mut self.channels {
- channel.resize(self.frame_count, 0.);
- }
+ self.samples.resize(channel_count * self.frame_count, 0.);
+ self.channel_count = channel_count;
}
pub fn copy_from(&mut self, source: &Self) {
assert_eq!(source.frame_count(), self.frame_count());
self.set_channel_count(source.channel_count());
- for channel_index in 0..self.channels.len() {
- self.channels[channel_index].clone_from(&source.channels[channel_index]);
- }
+ self.samples.copy_from_slice(&source.samples);
}
// https://webaudio.github.io/web-audio-api/#channel-up-mixing-and-down-mixing
@@ -100,10 +97,10 @@ impl AudioBus {
let destination_channels = self.channel_count();
let mut sum_channel = |destination_index: usize, source_index: usize, gain: f32| {
- let destination_span = &mut self.channels[destination_index];
+ let destination_span = self.channel_mut(destination_index);
let source_span = source.channel(source_index);
- for frame in 0..self.frame_count {
- destination_span[frame] += source_span[frame] * gain;
+ for (destination_sample, source_sample) in destination_span.iter_mut().zip(source_span) {
+ *destination_sample += *source_sample * gain;
}
};
@@ -217,10 +214,10 @@ impl AudioBus {
// channels as possible, then dropping remaining channels.
let channels_to_sum = source.channel_count().min(self.channel_count());
for channel_index in 0..channels_to_sum {
- let destination_span = &mut self.channels[channel_index];
+ let destination_span = self.channel_mut(channel_index);
let source_span = source.channel(channel_index);
- for frame in 0..self.frame_count {
- destination_span[frame] += source_span[frame];
+ for (destination_sample, source_sample) in destination_span.iter_mut().zip(source_span) {
+ *destination_sample += *source_sample;
}
}
}
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.rs
index 38fbcc26e14..61b6e33148f 100644
--- 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.rs
@@ -117,7 +117,10 @@ pub fn create_audio_worklet_render_node(
pipe: Arc<AudioWorkletPipe>,
params: Vec<Arc<RenderAudioParam>>,
) -> Box<NodeHandle> {
- let data = RenderNodeData::new(node_id, input_count, output_count, quantum_size, 1);
+ let mut data = RenderNodeData::new(node_id, input_count, output_count, quantum_size, 1);
+ for (output, &channel_capacity) in output_channel_capacities.iter().enumerate() {
+ data.reserve_output_channels(output, channel_capacity as usize);
+ }
// Channel configuration must be set here: the SetChannelConfig messages queued during node
// construction arrive before our AddNode and are dropped by the graph.
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.rs
index da84edf4e0f..2d7158b54cc 100644
--- 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.rs
@@ -10,6 +10,7 @@ use super::node_message::NodeMessage;
use super::render_graph::RenderGraph;
use super::render_node::*;
use super::render_nodes::{BusRef, NodeProcessor, node_handle};
+use crate::web_audio::MAX_NUMBER_OF_CHANNELS;
// https://webaudio.github.io/web-audio-api/#MediaStreamAudioSourceNode
struct MediaStreamSourceRenderNode {
@@ -79,7 +80,8 @@ pub unsafe fn create_media_stream_source_render_node(
quantum_size: usize,
callbacks: AudioFrameRingCallbacks,
) -> Box<NodeHandle> {
- let data = RenderNodeData::new(node_id, 0, 1, quantum_size, 2);
+ let mut data = RenderNodeData::new(node_id, 0, 1, quantum_size, 2);
+ data.reserve_output_channels(0, MAX_NUMBER_OF_CHANNELS);
// 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
@@ -94,7 +96,7 @@ pub unsafe fn create_media_stream_source_render_node(
ring: None,
ring_callbacks: callbacks,
channel_count: 1,
- interleaved_scratch: Vec::new(),
+ interleaved_scratch: Vec::with_capacity(quantum_size * MAX_NUMBER_OF_CHANNELS),
},
)
}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_graph.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_graph.rs
index d39e51db502..04905f91b2e 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_graph.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_graph.rs
@@ -306,22 +306,25 @@ impl NodeMap {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::css::style::pipeline::allocation_count::count_allocations;
use crate::web_audio::audio_param_timeline::AudioParamTimeline;
use crate::web_audio::control_message::*;
use crate::web_audio::control_message_queue::ControlMessageQueue;
use crate::web_audio::rendering::node_message::{NodeMessage, StartSource, StopSource};
use crate::web_audio::rendering::render_node::{
- AutomationRate, ChannelCountMode, ChannelInterpretation, OutgoingNodeConnection, RenderAudioParam,
+ AutomationRate, ChannelCountMode, ChannelInterpretation, OutgoingNodeConnection, OutgoingParamConnection,
+ RenderAudioParam,
};
use crate::web_audio::rendering::render_nodes::{
- create_constant_source_render_node, create_destination_render_node,
+ create_channel_merger_render_node, create_constant_source_render_node, create_destination_render_node,
+ create_gain_render_node,
};
use std::sync::Arc;
#[test]
fn control_queue_rendering_and_ended_node_retirement() {
let timeline = Arc::new(AudioParamTimeline::new(0.75));
- let param = Arc::new(RenderAudioParam::new(timeline, -1., 1., AutomationRate::ARate));
+ let param = Arc::new(RenderAudioParam::new(timeline, -1., 1., AutomationRate::ARate, 4));
let queue = ControlMessageQueue::default();
queue.enqueue(ControlMessage::SetChannelConfig(SetChannelConfig {
node_id: 1,
@@ -376,4 +379,79 @@ mod tests {
assert!(unsafe { &*graph.destination().unwrap().data().output(0) }.is_silent());
assert!(graph.take_ended_nodes().is_empty());
}
+
+ #[test]
+ fn connected_params_and_bus_layout_changes_do_not_allocate_during_processing() {
+ let context = RenderContext {
+ sample_rate: 48000.,
+ quantum_size: 4,
+ quantum_start_frame: 0,
+ };
+ let source_param = Arc::new(RenderAudioParam::new(
+ Arc::new(AudioParamTimeline::new(0.5)),
+ -1.,
+ 1.,
+ AutomationRate::ARate,
+ context.quantum_size,
+ ));
+ let gain_param = Arc::new(RenderAudioParam::new(
+ Arc::new(AudioParamTimeline::new(1.)),
+ f32::MIN,
+ f32::MAX,
+ AutomationRate::ARate,
+ context.quantum_size,
+ ));
+ let mut graph = RenderGraph::default();
+ graph.set_destination(3);
+ graph.apply_control_messages(vec![
+ ControlMessage::AddNode(AddNode {
+ node: create_constant_source_render_node(1, context.quantum_size, source_param),
+ }),
+ ControlMessage::AddNode(AddNode {
+ node: create_channel_merger_render_node(2, context.quantum_size, 6),
+ }),
+ ControlMessage::AddNode(AddNode {
+ node: create_gain_render_node(3, context.quantum_size, Arc::clone(&gain_param)),
+ }),
+ ControlMessage::NodeMessage(NodeMessage::StartSource(StartSource { node_id: 1, when: 0. })),
+ ]);
+ for channel_count in [1, 6, 1, 6] {
+ let input = if channel_count == 1 { 3 } else { 2 };
+ graph.apply_control_messages(vec![
+ ControlMessage::ReplaceConnections(ReplaceConnections {
+ source: 1,
+ node_connections: vec![OutgoingNodeConnection {
+ destination: input,
+ output_index: 0,
+ input_index: 0,
+ }],
+ param_connections: vec![OutgoingParamConnection {
+ destination: Arc::clone(&gain_param),
+ output_index: 0,
+ }],
+ }),
+ ControlMessage::ReplaceConnections(ReplaceConnections {
+ source: 2,
+ node_connections: if channel_count == 1 {
+ Vec::new()
+ } else {
+ vec![OutgoingNodeConnection {
+ destination: 3,
+ output_index: 0,
+ input_index: 0,
+ }]
+ },
+ param_connections: Vec::new(),
+ }),
+ ]);
+ // Apply topology changes before counting DSP allocations.
+ unsafe { graph.rebuild_incoming_connections() };
+ graph.incoming_connections_dirty.set(false);
+ let (_, allocations) = count_allocations(|| graph.render_quantum(&context));
+ assert_eq!(allocations.everywhere, 0);
+ let output = unsafe { &*graph.destination().unwrap().data().output(0) };
+ assert_eq!(output.channel_count(), channel_count);
+ assert_eq!(output.channel(0), &[0.75; 4]);
+ }
+ }
}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs
index 9e96a670421..433d0013406 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs
@@ -10,7 +10,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
use super::audio_bus::AudioBus;
-use crate::web_audio::audio_param_timeline::AudioParamTimeline;
+use crate::web_audio::{MAX_NUMBER_OF_CHANNELS, audio_param_timeline::AudioParamTimeline};
// State for a single render quantum that is passed to every node being processed.
#[derive(Clone, Copy)]
@@ -49,7 +49,7 @@ struct Input {
struct RenderAudioParamState {
inputs: Vec<Input>,
- input_scratch: Option<Box<AudioBus>>,
+ input_scratch: AudioBus,
}
// The rendering thread's view of an AudioParam. The automation timeline is shared with the AudioParam on the control
@@ -73,6 +73,7 @@ impl RenderAudioParam {
min_value: f32,
max_value: f32,
automation_rate: AutomationRate,
+ quantum_size: usize,
) -> Self {
Self {
timeline,
@@ -81,7 +82,7 @@ impl RenderAudioParam {
automation_rate: AtomicU8::new(automation_rate as u8),
state: UnsafeCell::new(RenderAudioParamState {
inputs: Vec::new(),
- input_scratch: None,
+ input_scratch: AudioBus::new(1, quantum_size),
}),
}
}
@@ -132,13 +133,6 @@ impl RenderAudioParam {
// The AudioParam will take the rendered audio data from any AudioNode output connected to it and convert it to
// mono by down-mixing if it is not already mono.
let input_scratch = unsafe { &mut (*state).input_scratch };
- if input_scratch
- .as_ref()
- .is_none_or(|scratch| scratch.frame_count() != context.quantum_size)
- {
- *input_scratch = Some(Box::new(AudioBus::new(1, context.quantum_size)));
- }
- let input_scratch = input_scratch.as_mut().unwrap();
input_scratch.zero();
input_scratch.sum_from(bus, true);
@@ -222,7 +216,6 @@ pub struct RenderNodeData {
pub channel_interpretation: std::cell::Cell<ChannelInterpretation>,
pub input_connections: UnsafeCell<Vec<Vec<Connection>>>,
input_buses: UnsafeCell<Vec<AudioBus>>,
- pulled_source_buses: UnsafeCell<smallvec::SmallVec<[*const AudioBus; 4]>>,
outputs: UnsafeCell<Vec<AudioBus>>,
pub outgoing_node_connections: UnsafeCell<Vec<OutgoingNodeConnection>>,
pub outgoing_param_connections: UnsafeCell<Vec<OutgoingParamConnection>>,
@@ -245,7 +238,9 @@ impl RenderNodeData {
let input_connections = (0..input_count).map(|_| Vec::new()).collect();
let mut input_buses = Vec::with_capacity(input_count);
for _input_index in 0..input_count {
- input_buses.push(AudioBus::new(1, quantum_size));
+ let mut bus = AudioBus::new(1, quantum_size);
+ bus.reserve_channels(MAX_NUMBER_OF_CHANNELS);
+ input_buses.push(bus);
}
let mut outputs = Vec::with_capacity(output_count);
for _output_index in 0..output_count {
@@ -258,7 +253,6 @@ impl RenderNodeData {
channel_interpretation: std::cell::Cell::new(ChannelInterpretation::Speakers),
input_connections: UnsafeCell::new(input_connections),
input_buses: UnsafeCell::new(input_buses),
- pulled_source_buses: UnsafeCell::new(smallvec::SmallVec::new()),
outputs: UnsafeCell::new(outputs),
outgoing_node_connections: UnsafeCell::new(Vec::new()),
outgoing_param_connections: UnsafeCell::new(Vec::new()),
@@ -267,6 +261,10 @@ impl RenderNodeData {
}
}
+ pub(crate) fn reserve_output_channels(&mut self, output: usize, channel_capacity: usize) {
+ self.outputs.get_mut()[output].reserve_channels(channel_capacity);
+ }
+
pub fn input_count(&self) -> usize {
unsafe { &*self.input_connections.get() }.len()
}
@@ -303,16 +301,16 @@ impl RenderNodeData {
) -> *const AudioBus {
let connections = &unsafe { &*self.input_connections.get() }[input_index];
let input_bus = unsafe { (*self.input_buses.get()).as_mut_ptr().add(input_index) };
- let source_buses = unsafe { &mut *self.pulled_source_buses.get() };
- source_buses.clear();
+ let mut maximum_source_channels = 0;
for connection in connections {
let bus = graph.pull_output(connection.source, connection.output_index, context);
- // A ScriptProcessorNode can supply an AudioBuffer with no channels.
- if unsafe { bus.as_ref() }.is_some_and(|bus| bus.channel_count() != 0) {
- source_buses.push(bus);
+ if let Some(bus) = unsafe { bus.as_ref() } {
+ maximum_source_channels = maximum_source_channels.max(bus.channel_count());
}
}
- if source_buses.is_empty() {
+
+ // AD-HOC: Treat a zero-channel ScriptProcessorNode buffer as a disconnected input.
+ if maximum_source_channels == 0 {
unsafe {
(&mut *input_bus).set_channel_count(1);
(&mut *input_bus).zero();
@@ -320,35 +318,26 @@ impl RenderNodeData {
return input_bus;
}
- let mut computed_number_of_channels = 0;
- match self.channel_count_mode.get() {
- ChannelCountMode::Max | ChannelCountMode::ClampedMax => {
- // "max": computedNumberOfChannels is the maximum of the number of channels of all connections to an input.
- // In this mode channelCount is ignored.
- // "clamped-max": computedNumberOfChannels is determined as for "max" and then clamped to a maximum value of
- // the given channelCount.
- for &bus in source_buses.iter() {
- computed_number_of_channels = computed_number_of_channels.max(unsafe { &*bus }.channel_count());
- }
- if self.channel_count_mode.get() == ChannelCountMode::ClampedMax {
- computed_number_of_channels = computed_number_of_channels.min(self.channel_count.get());
- }
- }
- ChannelCountMode::Explicit => {
- // "explicit": computedNumberOfChannels is the exact value as specified by the channelCount.
- computed_number_of_channels = self.channel_count.get();
- }
- }
- unsafe {
- (&mut *input_bus).set_channel_count(computed_number_of_channels);
- (&mut *input_bus).zero();
- }
- for &bus in source_buses.iter() {
- unsafe {
- (&mut *input_bus).sum_from(
- &*bus,
- self.channel_interpretation.get() == ChannelInterpretation::Speakers,
- );
+ let computed_number_of_channels = match self.channel_count_mode.get() {
+ // "max": computedNumberOfChannels is the maximum of the number of channels of all connections to an input.
+ // In this mode channelCount is ignored.
+ ChannelCountMode::Max => maximum_source_channels,
+ // "clamped-max": computedNumberOfChannels is determined as for "max" and then clamped to a maximum value of
+ // the given channelCount.
+ ChannelCountMode::ClampedMax => maximum_source_channels.min(self.channel_count.get()),
+ // "explicit": computedNumberOfChannels is the exact value as specified by the channelCount.
+ ChannelCountMode::Explicit => self.channel_count.get(),
+ };
+ let input_bus_mut = unsafe { &mut *input_bus };
+ input_bus_mut.set_channel_count(computed_number_of_channels);
+ input_bus_mut.zero();
+
+ // The first pass already processed every dependency, including any re-entrant pulls.
+ let speakers = self.channel_interpretation.get() == ChannelInterpretation::Speakers;
+ for connection in connections {
+ let bus = graph.pull_output(connection.source, connection.output_index, context);
+ if let Some(bus) = unsafe { bus.as_ref() } {
+ input_bus_mut.sum_from(bus, speakers);
}
}
input_bus
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs
index 80cc85a0cf0..ea1eeceb52e 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_nodes.rs
@@ -25,6 +25,7 @@ use super::fft::{FFT, FFTDirection};
use super::node_message::*;
use super::render_graph::RenderGraph;
use super::render_node::*;
+use crate::web_audio::MAX_NUMBER_OF_CHANNELS;
// Additive synthesis of the built-in oscillator waveforms is capped to keep the per-sample cost bounded for very low
// fundamental frequencies.
@@ -1827,14 +1828,16 @@ impl NodeProcessor for PassthroughRenderNode {
}
pub fn create_destination_render_node(node_id: u64, quantum_size: usize, channel_count: usize) -> Box<NodeHandle> {
- let data = RenderNodeData::new(node_id, 1, 1, quantum_size, channel_count);
+ let mut data = RenderNodeData::new(node_id, 1, 1, quantum_size, channel_count);
+ data.reserve_output_channels(0, MAX_NUMBER_OF_CHANNELS);
data.channel_count.set(channel_count);
data.channel_count_mode.set(ChannelCountMode::Explicit);
node_handle(data, DestinationRenderNode)
}
pub fn create_gain_render_node(node_id: u64, quantum_size: usize, gain: Arc<RenderAudioParam>) -> Box<NodeHandle> {
- let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ let mut data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ data.reserve_output_channels(0, MAX_NUMBER_OF_CHANNELS);
node_handle(
data,
GainRenderNode {
@@ -1889,7 +1892,8 @@ pub fn create_audio_buffer_source_render_node(
playback_rate: Arc<RenderAudioParam>,
detune: Arc<RenderAudioParam>,
) -> Box<NodeHandle> {
- let data = RenderNodeData::new(node_id, 0, 1, quantum_size, 1);
+ let mut data = RenderNodeData::new(node_id, 0, 1, quantum_size, 1);
+ data.reserve_output_channels(0, MAX_NUMBER_OF_CHANNELS);
node_handle(
data,
AudioBufferSourceRenderNode {
@@ -1917,7 +1921,8 @@ pub fn create_delay_render_node(
delay_time: Arc<RenderAudioParam>,
max_delay_time: f64,
) -> Box<NodeHandle> {
- let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ let mut data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ data.reserve_output_channels(0, MAX_NUMBER_OF_CHANNELS);
node_handle(
data,
DelayRenderNode {
@@ -1977,7 +1982,8 @@ pub fn create_biquad_filter_render_node(
q: Arc<RenderAudioParam>,
gain: Arc<RenderAudioParam>,
) -> Box<NodeHandle> {
- let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ let mut data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ data.reserve_output_channels(0, MAX_NUMBER_OF_CHANNELS);
node_handle(
data,
BiquadFilterRenderNode {
@@ -1990,7 +1996,7 @@ pub fn create_biquad_filter_render_node(
q_values: vec![0.; quantum_size],
gain_values: vec![0.; quantum_size],
r#type: BiquadFilterType::Lowpass,
- filter_states: Vec::new(),
+ filter_states: Vec::with_capacity(MAX_NUMBER_OF_CHANNELS),
},
)
}
@@ -2001,7 +2007,8 @@ pub fn create_iir_filter_render_node(
feedforward: &[f64],
feedback: &[f64],
) -> Box<NodeHandle> {
- let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ let mut data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ data.reserve_output_channels(0, MAX_NUMBER_OF_CHANNELS);
assert!(feedforward.len() < 32);
assert!(feedback.len() < 32);
node_handle(
@@ -2009,20 +2016,21 @@ pub fn create_iir_filter_render_node(
IIRFilterRenderNode {
feedforward: feedforward.to_vec(),
feedback: feedback.to_vec(),
- filter_states: Vec::new(),
+ filter_states: Vec::with_capacity(MAX_NUMBER_OF_CHANNELS),
position: 0,
},
)
}
pub fn create_wave_shaper_render_node(node_id: u64, quantum_size: usize) -> Box<NodeHandle> {
- let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ let mut data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ data.reserve_output_channels(0, MAX_NUMBER_OF_CHANNELS);
node_handle(
data,
WaveShaperRenderNode {
curve: None,
oversample: OverSampleType::None,
- channel_states: Vec::new(),
+ channel_states: Vec::with_capacity(MAX_NUMBER_OF_CHANNELS),
two_times_samples: vec![0.; quantum_size * 2],
four_times_samples: vec![0.; quantum_size * 4],
},
@@ -2030,7 +2038,8 @@ pub fn create_wave_shaper_render_node(node_id: u64, quantum_size: usize) -> Box<
}
pub fn create_convolver_render_node(node_id: u64, quantum_size: usize) -> Box<NodeHandle> {
- let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ let mut data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ data.reserve_output_channels(0, 2);
data.channel_count_mode.set(ChannelCountMode::ClampedMax);
node_handle(
data,
@@ -2085,6 +2094,7 @@ pub fn create_panner_render_node(
}
pub fn create_passthrough_render_node(node_id: u64, quantum_size: usize) -> Box<NodeHandle> {
- let data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ let mut data = RenderNodeData::new(node_id, 1, 1, quantum_size, 1);
+ data.reserve_output_channels(0, MAX_NUMBER_OF_CHANNELS);
node_handle(data, PassthroughRenderNode)
}