Skip to content

Truly independent web browser

LibWeb: Port WebAudio parameter timelines and rendering to Rust

Shannon Boothbe64881fc4e1
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index 97224fb20eb..7d7ce14e032 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -2469,18 +2469,33 @@ fn main() -> Result<(), Box<dyn Error>> {
let mut web_audio_config = base_config.clone();
web_audio_config.namespaces = Some(vec!["Web".into(), "WebAudio".into(), "RustFFI".into()]);
- for name in ["FFT", "AudioBus", "ConvolverKernel", "ConvolverDelayLine"] {
+ for name in [
+ "FFT",
+ "AudioBus",
+ "ConvolverKernel",
+ "ConvolverDelayLine",
+ "AudioParamTimeline",
+ "RenderAudioParam",
+ ] {
web_audio_config.export.rename.insert(name.into(), "void".into());
web_audio_config.export.exclude.push(name.into());
}
- web_audio_config.export.exclude.push("MAX_CHANNEL_COUNT".into());
+ web_audio_config.export.item_types = vec![
+ cbindgen::ItemType::Enums,
+ cbindgen::ItemType::Structs,
+ cbindgen::ItemType::Typedefs,
+ cbindgen::ItemType::OpaqueItems,
+ cbindgen::ItemType::Functions,
+ ];
generate_ffi_header(
web_audio_config,
&[
+ manifest_dir.join("src/web_audio/audio_param_timeline.rs"),
manifest_dir.join("src/web_audio/rendering/fft.rs"),
manifest_dir.join("src/web_audio/rendering/biquad_coefficients.rs"),
manifest_dir.join("src/web_audio/rendering/audio_bus.rs"),
manifest_dir.join("src/web_audio/rendering/convolver_kernel.rs"),
+ manifest_dir.join("src/web_audio/rendering/render_node.rs"),
],
&out_dir,
Path::new("WebAudio/RustFFI.h"),
diff --git a/Libraries/LibWeb/Rust/src/web_audio/audio_param_timeline.rs b/Libraries/LibWeb/Rust/src/web_audio/audio_param_timeline.rs
new file mode 100644
index 00000000000..39c55f8f8b3
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/web_audio/audio_param_timeline.rs
@@ -0,0 +1,668 @@
+/*
+ * Copyright (c) 2024, Shannon Booth <[email protected]>
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::sync::{Arc, Mutex};
+
+use ak::{Span, SpanMut, math};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum InsertResult {
+ Success,
+ EventContainedInValueCurve,
+ ValueCurveOverlapsEvent,
+}
+
+#[derive(Clone, Copy)]
+struct RampStart {
+ set_target_event_id: usize,
+ time: f64,
+ value: f32,
+}
+
+enum Parameterization {
+ SetValue { value: f32 },
+ LinearRamp { value: f32, start: Option<RampStart> },
+ ExponentialRamp { value: f32, start: Option<RampStart> },
+ SetTarget { target: f32, time_constant: f32 },
+ SetValueCurve { values: Vec<f32>, duration: f64 },
+ Hold { value: f32 },
+}
+
+struct AutomationEvent {
+ time: f64,
+ parameterization: Parameterization,
+ id: usize,
+}
+
+#[derive(Clone, Copy, Default)]
+struct ParameterizationCache {
+ event_index: Option<usize>,
+ minimum_time: Option<f64>,
+ maximum_time: Option<f64>,
+ starting_value: f32,
+}
+
+impl ParameterizationCache {
+ fn contains(&self, time: f64) -> bool {
+ self.minimum_time.is_none_or(|minimum_time| time >= minimum_time)
+ && self.maximum_time.is_none_or(|maximum_time| time < maximum_time)
+ }
+}
+
+#[derive(Default)]
+struct TimelineState {
+ // https://webaudio.github.io/web-audio-api/#dfn-automation-event
+ automation_events: Vec<AutomationEvent>,
+ next_event_id: usize,
+ parameterization_cache: Option<ParameterizationCache>,
+}
+
+// Holds the automation events for a single AudioParam and evaluates the parameter's intrinsic value over time.
+// This timeline is shared between the control thread, which inserts events through the AudioParam interface, and
+// the rendering thread, which evaluates the parameter while rendering the audio graph. All public methods lock an
+// internal mutex, so both threads observe a consistent series of automation events.
+// https://webaudio.github.io/web-audio-api/#dfn-automation-event
+pub struct AudioParamTimeline {
+ default_value: f32,
+ mutex: Mutex<TimelineState>,
+}
+
+impl AudioParamTimeline {
+ pub fn new(default_value: f32) -> Self {
+ Self {
+ default_value,
+ mutex: Mutex::new(TimelineState::default()),
+ }
+ }
+
+ pub fn default_value(&self) -> f32 {
+ self.default_value
+ }
+
+ // https://webaudio.github.io/web-audio-api/#computedvalue
+ pub fn value_at_time(&self, time: f64) -> f32 {
+ let mut state = self.mutex.lock().unwrap();
+ state.value_at_time_locked(self.default_value, time, time)
+ }
+
+ // Evaluates the intrinsic value for each sample frame of a render quantum starting at start_time.
+ pub fn sample(&self, start_time: f64, sample_period: f64, output: &mut [f32]) {
+ let mut state = self.mutex.lock().unwrap();
+ for (frame, value) in output.iter_mut().enumerate() {
+ let frame_time = start_time + frame as f64 * sample_period;
+ *value = state.value_at_time_locked(self.default_value, frame_time + sample_period / 2., frame_time);
+ }
+ }
+
+ pub fn has_events(&self) -> bool {
+ let state = self.mutex.lock().unwrap();
+ !state.automation_events.is_empty()
+ }
+
+ // All event times passed into these methods must already be clamped to the context's current time by the caller.
+ pub fn set_value_at_time(&self, value: f32, start_time: f64) -> InsertResult {
+ let mut state = self.mutex.lock().unwrap();
+ state.insert_event(AutomationEvent {
+ time: start_time,
+ parameterization: Parameterization::SetValue { value },
+ id: 0,
+ })
+ }
+
+ pub fn linear_ramp_to_value_at_time(
+ &self,
+ value: f32,
+ end_time: f64,
+ current_time: f64,
+ current_value: f32,
+ ) -> InsertResult {
+ let mut state = self.mutex.lock().unwrap();
+
+ // If there is no event preceding this event, the linear ramp behaves as if setValueAtTime(value, currentTime) were
+ // called, where value is the current value of the attribute.
+ let event_index = state.first_event_index_after(end_time);
+ let ramp_start = state.ramp_start_for_insertion_index(self.default_value, event_index, current_time);
+ if event_index == 0 {
+ let result = state.insert_event(AutomationEvent {
+ time: current_time,
+ parameterization: Parameterization::SetValue { value: current_value },
+ id: 0,
+ });
+ assert_eq!(result, InsertResult::Success);
+ }
+
+ state.insert_event(AutomationEvent {
+ time: end_time,
+ parameterization: Parameterization::LinearRamp {
+ value,
+ start: ramp_start,
+ },
+ id: 0,
+ })
+ }
+
+ pub fn exponential_ramp_to_value_at_time(
+ &self,
+ value: f32,
+ end_time: f64,
+ current_time: f64,
+ current_value: f32,
+ ) -> InsertResult {
+ let mut state = self.mutex.lock().unwrap();
+
+ // If there is no event preceding this event, the exponential ramp behaves as if setValueAtTime(value, currentTime)
+ // were called, where value is the current value of the attribute.
+ let event_index = state.first_event_index_after(end_time);
+ let ramp_start = state.ramp_start_for_insertion_index(self.default_value, event_index, current_time);
+ if event_index == 0 {
+ let result = state.insert_event(AutomationEvent {
+ time: current_time,
+ parameterization: Parameterization::SetValue { value: current_value },
+ id: 0,
+ });
+ assert_eq!(result, InsertResult::Success);
+ }
+
+ state.insert_event(AutomationEvent {
+ time: end_time,
+ parameterization: Parameterization::ExponentialRamp {
+ value,
+ start: ramp_start,
+ },
+ id: 0,
+ })
+ }
+
+ pub fn set_target_at_time(&self, target: f32, start_time: f64, time_constant: f32) -> InsertResult {
+ let mut state = self.mutex.lock().unwrap();
+ state.insert_event(AutomationEvent {
+ time: start_time,
+ parameterization: Parameterization::SetTarget { target, time_constant },
+ id: 0,
+ })
+ }
+
+ pub fn set_value_curve_at_time(&self, values: Vec<f32>, start_time: f64, duration: f64) -> InsertResult {
+ let mut state = self.mutex.lock().unwrap();
+
+ // If there are any events with a time strictly greater than startTime but strictly less than startTime + duration,
+ // a NotSupportedError exception MUST be thrown.
+ for event in &state.automation_events {
+ if event.time > start_time && event.time < start_time + duration {
+ return InsertResult::ValueCurveOverlapsEvent;
+ }
+ }
+
+ state.insert_event(AutomationEvent {
+ time: start_time,
+ parameterization: Parameterization::SetValueCurve { values, duration },
+ id: 0,
+ })
+ }
+
+ pub fn cancel_scheduled_values(&self, cancel_time: f64) {
+ let mut state = self.mutex.lock().unwrap();
+
+ // Cancel all scheduled parameter changes with times greater than or equal to cancelTime.
+ let mut first_event_to_remove = state
+ .automation_events
+ .partition_point(|event| event.time < cancel_time);
+
+ // Any active automations whose event time is less than cancelTime are also cancelled. A SetTarget remains active
+ // until the next event, while a SetValueCurve is active through the end of its duration.
+ if first_event_to_remove > 0 {
+ let previous_event = &state.automation_events[first_event_to_remove - 1];
+ let is_active_automation = match &previous_event.parameterization {
+ Parameterization::SetTarget { .. } => true,
+ Parameterization::SetValueCurve { duration, .. } => cancel_time <= previous_event.time + duration,
+ _ => false,
+ };
+ if is_active_automation {
+ first_event_to_remove -= 1;
+ }
+ }
+
+ if first_event_to_remove < state.automation_events.len() {
+ state.automation_events.truncate(first_event_to_remove);
+ }
+ state.parameterization_cache = None;
+ }
+
+ pub fn cancel_and_hold_at_time(&self, cancel_time: f64) {
+ let mut state = self.mutex.lock().unwrap();
+
+ let value_to_hold = state.value_at_time_locked(self.default_value, cancel_time, cancel_time);
+ let event_index = state.first_event_index_after(cancel_time);
+
+ // If the event immediately after cancelTime is a ramp, rewrite it to end at cancelTime with the value from the
+ // original timeline. This takes precedence over holding the value of the event active at cancelTime.
+ let mut rewrote_ramp = false;
+ if event_index < state.automation_events.len() {
+ let next_event = &mut state.automation_events[event_index];
+ rewrote_ramp = match &mut next_event.parameterization {
+ Parameterization::LinearRamp { value, .. } | Parameterization::ExponentialRamp { value, .. } => {
+ next_event.time = cancel_time;
+ *value = value_to_hold;
+ true
+ }
+ _ => false,
+ };
+ }
+
+ // Otherwise, decide which value (if any) to hold from cancelTime onward, based on the event active at cancelTime.
+ let mut hold_value = None;
+ let mut drop_active_curve = false;
+ if !rewrote_ramp && event_index > 0 {
+ let active_event = &state.automation_events[event_index - 1];
+ hold_value = match &active_event.parameterization {
+ Parameterization::SetTarget { .. } => Some(value_to_hold),
+ Parameterization::SetValueCurve { duration, .. } => {
+ // Cancelling exactly at a curve's start truncates it to a zero-duration curve, which produces no
+ // output, so the value reverts to the value before the curve rather than the curve's first element.
+ if active_event.time == cancel_time {
+ drop_active_curve = true;
+ Some(if event_index >= 2 {
+ state.event_value_at_time(self.default_value, event_index - 2, cancel_time)
+ } else {
+ self.default_value
+ })
+ } else if cancel_time <= active_event.time + duration {
+ Some(value_to_hold)
+ } else {
+ None
+ }
+ }
+ _ => None,
+ };
+ }
+
+ // Curve removal and hold insertion mutate the event list, so they run after the visit rather than inside it.
+ if drop_active_curve {
+ state.automation_events.remove(event_index - 1);
+ }
+ if let Some(hold_value) = hold_value {
+ assert_eq!(
+ state.insert_event(AutomationEvent {
+ time: cancel_time,
+ parameterization: Parameterization::Hold { value: hold_value },
+ id: 0
+ }),
+ InsertResult::Success
+ );
+ }
+
+ // Remove all events with times greater than cancelTime. The rewritten ramp or inserted hold remains at cancelTime.
+ let first_event_to_remove = state.first_event_index_after(cancel_time);
+ if first_event_to_remove < state.automation_events.len() {
+ state.automation_events.truncate(first_event_to_remove);
+ }
+ state.parameterization_cache = None;
+ }
+}
+
+impl TimelineState {
+ fn value_at_time_locked(&mut self, default_value: f32, selection_time: f64, time: f64) -> f32 {
+ // paramIntrinsicValue will be calculated at each time, which is either the value set directly to the value
+ // attribute, or, if there are any automation events with times before or at this time, the value as calculated from
+ // these events.
+ // NB: The governing automation event is selected using selection_time, which render quantum sampling sets half a
+ // frame ahead of the evaluation time so events take effect at the nearest sample frame of their scheduled time
+ // rather than the next frame when floating-point rounding pushes them past the exact frame time.
+ let cache = self.parameterization_cache_for_time(default_value, selection_time);
+ let Some(event_index) = cache.event_index else {
+ return cache.starting_value;
+ };
+
+ let event = &self.automation_events[event_index];
+ match &event.parameterization {
+ Parameterization::SetValue { value } | Parameterization::Hold { value } => *value,
+ Parameterization::LinearRamp { value, .. } => {
+ // NB: When a ramp ends between two sample frames, selection can consider the ramp completed while the
+ // evaluation time still lies just before its end time. The cached minimum time is then the ramp's own
+ // end time, so interpolating would divide by zero; the ramp's end value applies instead.
+ let minimum_time = cache.minimum_time.unwrap();
+ if time >= event.time || event.time <= minimum_time {
+ return *value;
+ }
+
+ let progress = ((time - minimum_time) / (event.time - minimum_time)) as f32;
+ cache.starting_value + (value - cache.starting_value) * progress
+ }
+ Parameterization::ExponentialRamp { value, .. } => {
+ let minimum_time = cache.minimum_time.unwrap();
+ if time >= event.time || event.time <= minimum_time {
+ return *value;
+ }
+
+ if cache.starting_value == 0.
+ || (cache.starting_value < 0. && *value > 0.)
+ || (cache.starting_value > 0. && *value < 0.)
+ {
+ return cache.starting_value;
+ }
+
+ let progress = ((time - minimum_time) / (event.time - minimum_time)) as f32;
+ cache.starting_value * math::pow(value / cache.starting_value, progress)
+ }
+ Parameterization::SetTarget { target, time_constant } => {
+ if *time_constant == 0. {
+ return *target;
+ }
+ target
+ + (cache.starting_value - target)
+ * math::exp(-(time - event.time) / f64::from(*time_constant)) as f32
+ }
+ Parameterization::SetValueCurve { .. } => self.event_value_at_time(default_value, event_index, time),
+ }
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dfn-automation-event
+ fn first_event_index_after(&self, time: f64) -> usize {
+ self.automation_events.partition_point(|event| event.time <= time)
+ }
+
+ fn event_value_at_time(&self, default_value: f32, event_index: usize, time: f64) -> f32 {
+ let mut first_event_index = event_index;
+ while first_event_index > 0
+ && matches!(
+ self.automation_events[first_event_index].parameterization,
+ Parameterization::SetTarget { .. }
+ )
+ {
+ first_event_index -= 1;
+ }
+
+ let mut value = default_value;
+ for current_event_index in first_event_index..=event_index {
+ let event = &self.automation_events[current_event_index];
+ let evaluation_time = if current_event_index == event_index {
+ time
+ } else {
+ self.automation_events[current_event_index + 1].time
+ };
+ value = match &event.parameterization {
+ Parameterization::SetValue { value }
+ | Parameterization::LinearRamp { value, .. }
+ | Parameterization::ExponentialRamp { value, .. }
+ | Parameterization::Hold { value } => *value,
+ Parameterization::SetTarget { target, time_constant } => {
+ if *time_constant == 0. {
+ *target
+ } else {
+ target
+ + (value - target)
+ * math::exp(-(evaluation_time - event.time) / f64::from(*time_constant)) as f32
+ }
+ }
+ Parameterization::SetValueCurve { values, duration } => {
+ if evaluation_time >= event.time + duration {
+ *values.last().unwrap()
+ } else {
+ let curve_position = (values.len() - 1) as f64 * (evaluation_time - event.time) / duration;
+
+ // NB: Floating-point rounding can push curve_position to size() - 1 even though evaluation_time is
+ // still strictly less than the curve's end time, so value_index is clamped to keep value_index + 1 in bounds.
+ let value_index = (curve_position.floor() as usize).min(values.len() - 2);
+ let interpolation_factor = (curve_position - value_index as f64) as f32;
+ values[value_index] + (values[value_index + 1] - values[value_index]) * interpolation_factor
+ }
+ }
+ };
+ }
+ value
+ }
+
+ // A ramp after an already-started SetTarget begins at currentTime using the target's value at that time.
+ fn ramp_start_for_insertion_index(
+ &self,
+ default_value: f32,
+ event_index: usize,
+ current_time: f64,
+ ) -> Option<RampStart> {
+ if event_index == 0 {
+ return None;
+ }
+
+ let previous_event = &self.automation_events[event_index - 1];
+ if previous_event.time >= current_time
+ || !matches!(previous_event.parameterization, Parameterization::SetTarget { .. })
+ {
+ return None;
+ }
+
+ Some(RampStart {
+ set_target_event_id: previous_event.id,
+ time: current_time,
+ value: self.event_value_at_time(default_value, event_index - 1, current_time),
+ })
+ }
+
+ // https://webaudio.github.io/web-audio-api/#computedvalue
+ fn parameterization_cache_for_time(&mut self, default_value: f32, time: f64) -> ParameterizationCache {
+ if let Some(cache) = self.parameterization_cache
+ && cache.contains(time)
+ {
+ return cache;
+ }
+
+ let event_index = self.first_event_index_after(time);
+ if event_index == 0 {
+ let cache = ParameterizationCache {
+ maximum_time: self.automation_events.first().map(|event| event.time),
+ starting_value: default_value,
+ ..Default::default()
+ };
+ self.parameterization_cache = Some(cache);
+ return cache;
+ }
+
+ // A following ramp parameterization owns the interval before its event time. Other parameterizations fall through
+ // to caching the preceding event below.
+ if event_index < self.automation_events.len() {
+ let cache = match &self.automation_events[event_index].parameterization {
+ Parameterization::SetValue { .. }
+ | Parameterization::SetTarget { .. }
+ | Parameterization::SetValueCurve { .. }
+ | Parameterization::Hold { .. } => None,
+ Parameterization::LinearRamp { start, .. } | Parameterization::ExponentialRamp { start, .. } => {
+ let previous_event = &self.automation_events[event_index - 1];
+ let (minimum_time, starting_value);
+ if let Some(start) = start
+ && start.set_target_event_id == previous_event.id
+ {
+ minimum_time = start.time;
+ starting_value = start.value;
+ } else {
+ minimum_time = match &previous_event.parameterization {
+ Parameterization::SetValueCurve { duration, .. } => previous_event.time + duration,
+ _ => previous_event.time,
+ };
+ starting_value = self.event_value_at_time(default_value, event_index - 1, minimum_time);
+ }
+
+ // NB: A ramp rewritten by cancelAndHoldAtTime() can end before a preceding value curve's original end.
+ // In that case, the curve owns the interval before the ramp endpoint.
+ if time < minimum_time || minimum_time >= self.automation_events[event_index].time {
+ None
+ } else {
+ Some(ParameterizationCache {
+ event_index: Some(event_index),
+ minimum_time: Some(minimum_time),
+ maximum_time: Some(self.automation_events[event_index].time),
+ starting_value,
+ })
+ }
+ }
+ };
+ if let Some(cache) = cache {
+ self.parameterization_cache = Some(cache);
+ return cache;
+ }
+ }
+
+ let selected_event_index = event_index - 1;
+ let selected_event = &self.automation_events[selected_event_index];
+ let mut maximum_time = None;
+ if event_index < self.automation_events.len() {
+ let next_event = &self.automation_events[event_index];
+ maximum_time = Some(match &next_event.parameterization {
+ Parameterization::LinearRamp { start, .. } | Parameterization::ExponentialRamp { start, .. } => {
+ if let Some(start) = start
+ && start.set_target_event_id == selected_event.id
+ {
+ start.time
+ } else {
+ next_event.time
+ }
+ }
+ _ => next_event.time,
+ });
+ }
+ let cache = ParameterizationCache {
+ event_index: Some(selected_event_index),
+ minimum_time: Some(selected_event.time),
+ maximum_time,
+ starting_value: self.event_value_at_time(default_value, selected_event_index, selected_event.time),
+ };
+ self.parameterization_cache = Some(cache);
+ cache
+ }
+
+ // https://webaudio.github.io/web-audio-api/#dfn-automation-event
+ fn insert_event(&mut self, mut event: AutomationEvent) -> InsertResult {
+ let insertion_index = self.first_event_index_after(event.time);
+
+ // If any automation method is called at a time contained in a SetValueCurve event, a NotSupportedError exception
+ // MUST be thrown.
+ if insertion_index > 0 {
+ let previous_event = &self.automation_events[insertion_index - 1];
+ let is_contained_in_curve = match &previous_event.parameterization {
+ Parameterization::SetValueCurve { duration, .. } => event.time < previous_event.time + duration,
+ _ => false,
+ };
+
+ // NB: A hold event ends an active value curve without changing how the curve is sampled before the hold time.
+ if is_contained_in_curve && !matches!(event.parameterization, Parameterization::Hold { .. }) {
+ return InsertResult::EventContainedInValueCurve;
+ }
+ }
+
+ // If an event is added at a time where there are already events, it is placed after them but before later events.
+ event.id = self.next_event_id;
+ self.next_event_id += 1;
+ self.automation_events.insert(insertion_index, event);
+ self.parameterization_cache = None;
+ InsertResult::Success
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) extern "C" fn web_audio_param_timeline_create(default_value: f32) -> *const AudioParamTimeline {
+ Arc::into_raw(Arc::new(AudioParamTimeline::new(default_value)))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_destroy(timeline: *const AudioParamTimeline) {
+ drop(unsafe { Arc::from_raw(timeline) });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_set_value_at_time(
+ timeline: *const AudioParamTimeline,
+ value: f32,
+ start_time: f64,
+) -> InsertResult {
+ unsafe { &*timeline }.set_value_at_time(value, start_time)
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_linear_ramp_to_value_at_time(
+ timeline: *const AudioParamTimeline,
+ value: f32,
+ end_time: f64,
+ current_time: f64,
+ current_value: f32,
+) -> InsertResult {
+ unsafe { &*timeline }.linear_ramp_to_value_at_time(value, end_time, current_time, current_value)
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_exponential_ramp_to_value_at_time(
+ timeline: *const AudioParamTimeline,
+ value: f32,
+ end_time: f64,
+ current_time: f64,
+ current_value: f32,
+) -> InsertResult {
+ unsafe { &*timeline }.exponential_ramp_to_value_at_time(value, end_time, current_time, current_value)
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_set_target_at_time(
+ timeline: *const AudioParamTimeline,
+ target: f32,
+ start_time: f64,
+ time_constant: f32,
+) -> InsertResult {
+ unsafe { &*timeline }.set_target_at_time(target, start_time, time_constant)
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_set_value_curve_at_time(
+ timeline: *const AudioParamTimeline,
+ values: Span<'_, f32>,
+ start_time: f64,
+ duration: f64,
+) -> InsertResult {
+ unsafe { &*timeline }.set_value_curve_at_time(values.as_slice().to_vec(), start_time, duration)
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_cancel_scheduled_values(
+ timeline: *const AudioParamTimeline,
+ cancel_time: f64,
+) {
+ unsafe { &*timeline }.cancel_scheduled_values(cancel_time);
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_cancel_and_hold_at_time(
+ timeline: *const AudioParamTimeline,
+ cancel_time: f64,
+) {
+ unsafe { &*timeline }.cancel_and_hold_at_time(cancel_time);
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_value_at_time(
+ timeline: *const AudioParamTimeline,
+ time: f64,
+) -> f32 {
+ unsafe { &*timeline }.value_at_time(time)
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_sample(
+ timeline: *const AudioParamTimeline,
+ start_time: f64,
+ sample_period: f64,
+ output: SpanMut<'_, f32>,
+) {
+ unsafe { &*timeline }.sample(start_time, sample_period, output.into_slice());
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_has_events(timeline: *const AudioParamTimeline) -> bool {
+ unsafe { &*timeline }.has_events()
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_param_timeline_default_value(timeline: *const AudioParamTimeline) -> f32 {
+ unsafe { &*timeline }.default_value()
+}
diff --git a/Libraries/LibWeb/Rust/src/web_audio/mod.rs b/Libraries/LibWeb/Rust/src/web_audio/mod.rs
index 2a92c0c2bd4..fa6467f7e96 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/mod.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/mod.rs
@@ -5,4 +5,5 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+pub mod audio_param_timeline;
pub mod rendering;
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs
index 6a755aa6a78..3c2bf13f217 100644
--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/mod.rs
@@ -9,6 +9,7 @@ pub mod audio_bus;
pub mod biquad_coefficients;
pub mod convolver_kernel;
pub mod fft;
+pub mod render_node;
#[cfg(test)]
mod tests;
diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs
new file mode 100644
index 00000000000..80471cf26e7
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs
@@ -0,0 +1,254 @@
+/*
+ * 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::Arc;
+use std::sync::atomic::{AtomicU8, Ordering};
+
+use ak::SpanMut;
+
+use super::audio_bus::AudioBus;
+use crate::web_audio::audio_param_timeline::AudioParamTimeline;
+
+// State for a single render quantum that is passed to every node being processed.
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub struct RenderContext {
+ pub sample_rate: f64,
+ pub quantum_size: usize,
+ pub quantum_start_frame: u64,
+}
+
+impl RenderContext {
+ pub fn quantum_start_time(&self) -> f64 {
+ self.quantum_start_frame as f64 / self.sample_rate
+ }
+
+ pub fn sample_period(&self) -> f64 {
+ 1. / self.sample_rate
+ }
+
+ pub fn frame_time(&self, frame: usize) -> f64 {
+ (self.quantum_start_frame + frame as u64) as f64 / self.sample_rate
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum AutomationRate {
+ ARate,
+ KRate,
+}
+
+struct Input {
+ source: u64,
+ output_index: usize,
+}
+
+struct RenderAudioParamState {
+ inputs: Vec<Input>,
+ input_scratch: Option<Box<AudioBus>>,
+}
+
+// The rendering thread's view of an AudioParam. The automation timeline is shared with the AudioParam on the control
+// thread; input connections are only manipulated by the rendering thread.
+// https://webaudio.github.io/web-audio-api/#computedvalue
+pub struct RenderAudioParam {
+ timeline: Arc<AudioParamTimeline>,
+ min_value: f32,
+ max_value: f32,
+ automation_rate: AtomicU8,
+ state: UnsafeCell<RenderAudioParamState>,
+}
+
+// SAFETY: Only the rendering thread accesses state, and other threads use only the atomic automation rate.
+unsafe impl Send for RenderAudioParam {}
+unsafe impl Sync for RenderAudioParam {}
+
+pub type PullOutput = unsafe extern "C" fn(*mut c_void, u64, usize, *const RenderContext) -> *const AudioBus;
+
+struct RenderGraph {
+ graph: *mut c_void,
+ pull_output: PullOutput,
+}
+
+impl RenderAudioParam {
+ fn new(timeline: Arc<AudioParamTimeline>, min_value: f32, max_value: f32, automation_rate: AutomationRate) -> Self {
+ Self {
+ timeline,
+ min_value,
+ max_value,
+ automation_rate: AtomicU8::new(automation_rate as u8),
+ state: UnsafeCell::new(RenderAudioParamState {
+ inputs: Vec::new(),
+ input_scratch: None,
+ }),
+ }
+ }
+
+ fn set_automation_rate(&self, automation_rate: AutomationRate) {
+ self.automation_rate.store(automation_rate as u8, Ordering::SeqCst);
+ }
+
+ fn automation_rate(&self) -> AutomationRate {
+ if self.automation_rate.load(Ordering::SeqCst) == AutomationRate::ARate as u8 {
+ AutomationRate::ARate
+ } else {
+ AutomationRate::KRate
+ }
+ }
+
+ // https://webaudio.github.io/web-audio-api/#computation-of-value
+ unsafe fn compute(&self, graph: &RenderGraph, context: &RenderContext, output: &mut [f32]) {
+ let state = unsafe { &mut *self.state.get() };
+
+ // 1. paramIntrinsicValue will be calculated at each time, which is either the value set directly to the value
+ // attribute, or, if there are any automation events with times before or at this time, the value as calculated
+ // from these events.
+ // NB: An a-rate parameter takes the exact value of the signal at each sample frame of the render quantum, while a
+ // k-rate parameter uses the value of the very first sample frame for the entire quantum.
+ let rate = self.automation_rate();
+ if rate == AutomationRate::KRate {
+ let value = self.timeline.value_at_time(context.quantum_start_time());
+ output.fill(value);
+ } else {
+ self.timeline
+ .sample(context.quantum_start_time(), context.sample_period(), output);
+ }
+
+ // 2. Set [[current value]] to the value of paramIntrinsicValue at the beginning of this render quantum.
+ // NB: The render param keeps no [[current value]] slot of its own; the AudioParam's value getter reads the shared
+ // automation timeline directly on the control thread.
+
+ // 3. paramComputedValue is the sum of the paramIntrinsicValue value and the value of the input AudioParam
+ // buffer. If the sum is NaN, replace the sum with the defaultValue.
+ for input in &state.inputs {
+ let bus = unsafe { (graph.pull_output)(graph.graph, input.source, input.output_index, context) };
+ let Some(bus) = (unsafe { bus.as_ref() }) else {
+ continue;
+ };
+
+ // 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.
+ if state
+ .input_scratch
+ .as_ref()
+ .is_none_or(|scratch| scratch.frame_count() != context.quantum_size)
+ {
+ state.input_scratch = Some(Box::new(AudioBus::new(1, context.quantum_size)));
+ }
+ let input_scratch = state.input_scratch.as_mut().unwrap();
+ input_scratch.zero();
+ input_scratch.sum_from(bus, true);
+
+ let input_samples = input_scratch.channel(0);
+ if rate == AutomationRate::KRate {
+ for value in output.iter_mut() {
+ *value += input_samples[0];
+ }
+ } else {
+ for frame in 0..output.len() {
+ output[frame] += input_samples[frame];
+ }
+ }
+ }
+ let default_value = self.timeline.default_value();
+ for value in output.iter_mut() {
+ if value.is_nan() {
+ *value = default_value;
+ }
+ }
+
+ // 4. If this AudioParam is a compound parameter, compute its final value with other AudioParams.
+ // NB: None of the AudioParams backed by a render node are compound parameters.
+
+ // 5. Set computedValue to paramComputedValue.
+
+ // NB: The computedValue is clamped to the simple nominal range for this parameter.
+ // https://webaudio.github.io/web-audio-api/#simple-nominal-range
+ for value in output {
+ assert!(self.max_value >= self.min_value);
+ *value = if *value > self.max_value {
+ self.max_value
+ } else if *value < self.min_value {
+ self.min_value
+ } else {
+ *value
+ };
+ }
+ }
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_render_param_create(
+ timeline: *const AudioParamTimeline,
+ min_value: f32,
+ max_value: f32,
+ automation_rate: AutomationRate,
+) -> *const RenderAudioParam {
+ unsafe {
+ Arc::increment_strong_count(timeline);
+ }
+ let timeline = unsafe { Arc::from_raw(timeline) };
+ Arc::into_raw(Arc::new(RenderAudioParam::new(
+ timeline,
+ min_value,
+ max_value,
+ automation_rate,
+ )))
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_render_param_destroy(param: *const RenderAudioParam) {
+ drop(unsafe { Arc::from_raw(param) });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_render_param_set_automation_rate(
+ param: *const RenderAudioParam,
+ rate: AutomationRate,
+) {
+ unsafe { &*param }.set_automation_rate(rate);
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_render_param_automation_rate(
+ param: *const RenderAudioParam,
+) -> AutomationRate {
+ unsafe { &*param }.automation_rate()
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_render_param_clear_inputs(param: *const RenderAudioParam) {
+ unsafe { &mut *(*param).state.get() }.inputs.clear();
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_render_param_add_input(
+ param: *const RenderAudioParam,
+ source: u64,
+ output_index: usize,
+) {
+ unsafe { &mut *(*param).state.get() }
+ .inputs
+ .push(Input { source, output_index });
+}
+
+#[unsafe(no_mangle)]
+pub(crate) unsafe extern "C" fn web_audio_render_param_compute(
+ param: *const RenderAudioParam,
+ graph: *mut c_void,
+ pull_output: PullOutput,
+ context: *const RenderContext,
+ output: SpanMut<'_, f32>,
+) {
+ let graph = RenderGraph { graph, pull_output };
+ unsafe {
+ (&*param).compute(&graph, &*context, output.into_slice());
+ }
+}
diff --git a/Libraries/LibWeb/WebAudio/AudioParamTimeline.cpp b/Libraries/LibWeb/WebAudio/AudioParamTimeline.cpp
index 9b3cc918571..e545dd187a6 100644
--- a/Libraries/LibWeb/WebAudio/AudioParamTimeline.cpp
+++ b/Libraries/LibWeb/WebAudio/AudioParamTimeline.cpp
@@ -1,435 +1,82 @@
/*
* Copyright (c) 2024, Shannon Booth <[email protected]>
* Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/BinarySearch.h>
-#include <AK/Math.h>
#include <LibWeb/WebAudio/AudioParamTimeline.h>
+#include <LibWeb/WebAudio/RustFFI.h>
namespace Web::WebAudio {
AudioParamTimeline::AudioParamTimeline(float default_value)
- : m_default_value(default_value)
+ : m_timeline(RustFFI::web_audio_param_timeline_create(default_value))
{
+ static_assert(to_underlying(InsertResult::Success) == to_underlying(RustFFI::InsertResult::Success));
+ static_assert(to_underlying(InsertResult::EventContainedInValueCurve) == to_underlying(RustFFI::InsertResult::EventContainedInValueCurve));
+ static_assert(to_underlying(InsertResult::ValueCurveOverlapsEvent) == to_underlying(RustFFI::InsertResult::ValueCurveOverlapsEvent));
}
-// https://webaudio.github.io/web-audio-api/#computedvalue
-float AudioParamTimeline::value_at_time(double time) const
+AudioParamTimeline::~AudioParamTimeline()
{
- MutexLocker locker(m_mutex);
- return value_at_time_locked(time, time);
+ RustFFI::web_audio_param_timeline_destroy(m_timeline);
}
-float AudioParamTimeline::value_at_time_locked(double selection_time, double time) const
+float AudioParamTimeline::value_at_time(double time) const
{
- // paramIntrinsicValue will be calculated at each time, which is either the value set directly to the value
- // attribute, or, if there are any automation events with times before or at this time, the value as calculated from
- // these events.
- // NB: The governing automation event is selected using selection_time, which render quantum sampling sets half a
- // frame ahead of the evaluation time so events take effect at the nearest sample frame of their scheduled time
- // rather than the next frame when floating-point rounding pushes them past the exact frame time.
- auto const& cache = parameterization_cache_for_time(selection_time);
- if (!cache.event_index.has_value())
- return cache.starting_value;
-
- auto const& event = m_automation_events[*cache.event_index];
- return event.parameterization.visit(
- [](OneOf<SetValue, Hold> auto const& parameterization) {
- return parameterization.value;
- },
- [&](LinearRamp const& linear_ramp) {
- // NB: When a ramp ends between two sample frames, selection can consider the ramp completed while the
- // evaluation time still lies just before its end time. The cached minimum time is then the ramp's own
- // end time, so interpolating would divide by zero; the ramp's end value applies instead.
- VERIFY(cache.minimum_time.has_value());
- if (time >= event.time || event.time <= *cache.minimum_time)
- return linear_ramp.value;
-
- auto progress = static_cast<float>((time - *cache.minimum_time) / (event.time - *cache.minimum_time));
- return cache.starting_value + (linear_ramp.value - cache.starting_value) * progress;
- },
- [&](ExponentialRamp const& exponential_ramp) {
- VERIFY(cache.minimum_time.has_value());
- if (time >= event.time || event.time <= *cache.minimum_time)
- return exponential_ramp.value;
-
- if (cache.starting_value == 0
- || (cache.starting_value < 0 && exponential_ramp.value > 0)
- || (cache.starting_value > 0 && exponential_ramp.value < 0))
- return cache.starting_value;
-
- auto progress = static_cast<float>((time - *cache.minimum_time) / (event.time - *cache.minimum_time));
- return cache.starting_value * static_cast<float>(AK::pow(exponential_ramp.value / cache.starting_value, progress));
- },
- [&](SetTarget const& set_target) -> float {
- if (set_target.time_constant == 0)
- return set_target.target;
- return set_target.target + (cache.starting_value - set_target.target) * static_cast<float>(AK::exp(-(time - event.time) / set_target.time_constant));
- },
- [&](SetValueCurve const&) {
- return event_value_at_time(*cache.event_index, time);
- });
+ return RustFFI::web_audio_param_timeline_value_at_time(m_timeline, time);
}
-// Evaluates the intrinsic value for each sample frame of a render quantum starting at start_time.
void AudioParamTimeline::sample(double start_time, double sample_period, Span<float> output) const
{
- MutexLocker locker(m_mutex);
- for (size_t frame = 0; frame < output.size(); ++frame) {
- auto frame_time = start_time + frame * sample_period;
- output[frame] = value_at_time_locked(frame_time + sample_period / 2, frame_time);
- }
+ RustFFI::web_audio_param_timeline_sample(m_timeline, start_time, sample_period, output);
}
bool AudioParamTimeline::has_events() const
{
- MutexLocker locker(m_mutex);
- return !m_automation_events.is_empty();
+ return RustFFI::web_audio_param_timeline_has_events(m_timeline);
+}
+
+float AudioParamTimeline::default_value() const
+{
+ return RustFFI::web_audio_param_timeline_default_value(m_timeline);
}
AudioParamTimeline::InsertResult AudioParamTimeline::set_value_at_time(float value, double start_time)
{
- MutexLocker locker(m_mutex);
- return insert_event({
- .time = start_time,
- .parameterization = SetValue { value },
- });
+ return static_cast<InsertResult>(RustFFI::web_audio_param_timeline_set_value_at_time(m_timeline, value, start_time));
}
AudioParamTimeline::InsertResult AudioParamTimeline::linear_ramp_to_value_at_time(float value, double end_time, double current_time, float current_value)
{
- MutexLocker locker(m_mutex);
-
- // If there is no event preceding this event, the linear ramp behaves as if setValueAtTime(value, currentTime) were
- // called, where value is the current value of the attribute.
- auto event_index = first_event_index_after(end_time);
- auto ramp_start = ramp_start_for_insertion_index(event_index, current_time);
- if (event_index == 0) {
- auto result = insert_event({
- .time = current_time,
- .parameterization = SetValue { current_value },
- });
- VERIFY(result == InsertResult::Success);
- }
-
- return insert_event({
- .time = end_time,
- .parameterization = LinearRamp { value, ramp_start },
- });
+ return static_cast<InsertResult>(RustFFI::web_audio_param_timeline_linear_ramp_to_value_at_time(m_timeline, value, end_time, current_time, current_value));
}
AudioParamTimeline::InsertResult AudioParamTimeline::exponential_ramp_to_value_at_time(float value, double end_time, double current_time, float current_value)
{
- MutexLocker locker(m_mutex);
-
- // If there is no event preceding this event, the exponential ramp behaves as if setValueAtTime(value, currentTime)
- // were called, where value is the current value of the attribute.
- auto event_index = first_event_index_after(end_time);
- auto ramp_start = ramp_start_for_insertion_index(event_index, current_time);
- if (event_index == 0) {
- auto result = insert_event({
- .time = current_time,
- .parameterization = SetValue { current_value },
- });
- VERIFY(result == InsertResult::Success);
- }
-
- return insert_event({
- .time = end_time,
- .parameterization = ExponentialRamp { value, ramp_start },
- });
+ return static_cast<InsertResult>(RustFFI::web_audio_param_timeline_exponential_ramp_to_value_at_time(m_timeline, value, end_time, current_time, current_value));
}
AudioParamTimeline::InsertResult AudioParamTimeline::set_target_at_time(float target, double start_time, float time_constant)
{
- MutexLocker locker(m_mutex);
- return insert_event({
- .time = start_time,
- .parameterization = SetTarget { target, time_constant },
- });
+ return static_cast<InsertResult>(RustFFI::web_audio_param_timeline_set_target_at_time(m_timeline, target, start_time, time_constant));
}
AudioParamTimeline::InsertResult AudioParamTimeline::set_value_curve_at_time(Vector<float> values, double start_time, double duration)
{
- MutexLocker locker(m_mutex);
-
- // If there are any events with a time strictly greater than startTime but strictly less than startTime + duration,
- // a NotSupportedError exception MUST be thrown.
- for (auto const& event : m_automation_events) {
- if (event.time > start_time && event.time < start_time + duration)
- return InsertResult::ValueCurveOverlapsEvent;
- }
-
- return insert_event({
- .time = start_time,
- .parameterization = SetValueCurve { move(values), duration },
- });
-}
-
-// https://webaudio.github.io/web-audio-api/#dfn-automation-event
-size_t AudioParamTimeline::first_event_index_after(double time) const
-{
- return AK::lower_bound_index(m_automation_events, time, [](auto const& event, double time) {
- return event.time <= time ? -1 : 1;
- });
-}
-
-float AudioParamTimeline::event_value_at_time(size_t event_index, double time) const
-{
- auto first_event_index = event_index;
- while (first_event_index > 0 && m_automation_events[first_event_index].parameterization.has<SetTarget>())
- --first_event_index;
-
- auto value = m_default_value;
- for (auto current_event_index = first_event_index; current_event_index <= event_index; ++current_event_index) {
- auto const& event = m_automation_events[current_event_index];
- auto evaluation_time = current_event_index == event_index ? time : m_automation_events[current_event_index + 1].time;
- value = event.parameterization.visit(
- [](OneOf<SetValue, LinearRamp, ExponentialRamp, Hold> auto const& parameterization) {
- return parameterization.value;
- },
- [&](SetTarget const& set_target) -> float {
- if (set_target.time_constant == 0)
- return set_target.target;
- return set_target.target + (value - set_target.target) * static_cast<float>(AK::exp(-(evaluation_time - event.time) / set_target.time_constant));
- },
- [&](SetValueCurve const& set_value_curve) {
- if (evaluation_time >= event.time + set_value_curve.duration)
- return set_value_curve.values.last();
-
- auto curve_position = (set_value_curve.values.size() - 1) * (evaluation_time - event.time) / set_value_curve.duration;
-
- // NB: Floating-point rounding can push curve_position to size() - 1 even though evaluation_time is
- // still strictly less than the curve's end time, so value_index is clamped to keep value_index + 1 in bounds.
- auto value_index = min(static_cast<size_t>(AK::floor(curve_position)), set_value_curve.values.size() - 2);
- auto interpolation_factor = static_cast<float>(curve_position - value_index);
- return set_value_curve.values[value_index]
- + (set_value_curve.values[value_index + 1] - set_value_curve.values[value_index]) * interpolation_factor;
- });
- }
- return value;
-}
-
-// A ramp after an already-started SetTarget begins at currentTime using the target's value at that time.
-Optional<AudioParamTimeline::RampStart> AudioParamTimeline::ramp_start_for_insertion_index(size_t event_index, double current_time) const
-{
- if (event_index == 0)
- return {};
-
- auto const& previous_event = m_automation_events[event_index - 1];
- if (previous_event.time >= current_time || !previous_event.parameterization.has<SetTarget>())
- return {};
-
- return RampStart {
- .set_target_event_id = previous_event.id,
- .time = current_time,
- .value = event_value_at_time(event_index - 1, current_time),
- };
-}
-
-AudioParamTimeline::ParameterizationCache const& AudioParamTimeline::parameterization_cache_for_time(double time) const
-{
- if (m_parameterization_cache.has_value() && m_parameterization_cache->contains(time))
- return *m_parameterization_cache;
-
- auto event_index = first_event_index_after(time);
- if (event_index == 0) {
- m_parameterization_cache = {
- .maximum_time = m_automation_events.is_empty() ? Optional<double> {} : m_automation_events.first().time,
- .starting_value = m_default_value,
- };
- return *m_parameterization_cache;
- }
-
- // A following ramp parameterization owns the interval before its event time. Other parameterizations fall through
- // to caching the preceding event below.
- if (event_index < m_automation_events.size()) {
- auto cache = m_automation_events[event_index].parameterization.visit(
- [](OneOf<SetValue, SetTarget, SetValueCurve, Hold> auto const&) -> Optional<ParameterizationCache> {
- return {};
- },
- [&](OneOf<LinearRamp, ExponentialRamp> auto const& ramp) -> Optional<ParameterizationCache> {
- auto const& previous_event = m_automation_events[event_index - 1];
- double minimum_time;
- float starting_value;
- if (ramp.start.has_value() && ramp.start->set_target_event_id == previous_event.id) {
- minimum_time = ramp.start->time;
- starting_value = ramp.start->value;
- } else {
- minimum_time = previous_event.parameterization.visit(
- [&](SetValueCurve const& set_value_curve) {
- return previous_event.time + set_value_curve.duration;
- },
- [&](auto const&) {
- return previous_event.time;
- });
- starting_value = event_value_at_time(event_index - 1, minimum_time);
- }
-
- // NB: A ramp rewritten by cancelAndHoldAtTime() can end before a preceding value curve's original end.
- // In that case, the curve owns the interval before the ramp endpoint.
- if (time < minimum_time || minimum_time >= m_automation_events[event_index].time)
- return {};
- return ParameterizationCache {
- .event_index = event_index,
- .minimum_time = minimum_time,
- .maximum_time = m_automation_events[event_index].time,
- .starting_value = starting_value,
- };
- });
- if (cache.has_value()) {
- m_parameterization_cache = cache.release_value();
- return *m_parameterization_cache;
- }
- }
-
- auto selected_event_index = event_index - 1;
- auto const& selected_event = m_automation_events[selected_event_index];
- Optional<double> maximum_time;
- if (event_index < m_automation_events.size()) {
- auto const& next_event = m_automation_events[event_index];
- maximum_time = next_event.parameterization.visit(
- [&](OneOf<LinearRamp, ExponentialRamp> auto const& ramp) {
- if (ramp.start.has_value() && ramp.start->set_target_event_id == selected_event.id)
- return ramp.start->time;
- return next_event.time;
- },
- [&](auto const&) {
- return next_event.time;
- });
- }
- m_parameterization_cache = {
- .event_index = selected_event_index,
- .minimum_time = selected_event.time,
- .maximum_time = maximum_time,
- .starting_value = event_value_at_time(selected_event_index, selected_event.time),
- };
- return *m_parameterization_cache;
-}
-
-// https://webaudio.github.io/web-audio-api/#dfn-automation-event
-AudioParamTimeline::InsertResult AudioParamTimeline::insert_event(AutomationEvent event)
-{
- auto insertion_index = first_event_index_after(event.time);
-
- // If any automation method is called at a time contained in a SetValueCurve event, a NotSupportedError exception
- // MUST be thrown.
- if (insertion_index > 0) {
- auto const& previous_event = m_automation_events[insertion_index - 1];
- auto is_contained_in_curve = previous_event.parameterization.visit(
- [&](SetValueCurve const& set_value_curve) {
- return event.time < previous_event.time + set_value_curve.duration;
- },
- [](auto const&) {
- return false;
- });
-
- // NB: A hold event ends an active value curve without changing how the curve is sampled before the hold time.
- if (is_contained_in_curve && !event.parameterization.has<Hold>())
- return InsertResult::EventContainedInValueCurve;
- }
-
- // If an event is added at a time where there are already events, it is placed after them but before later events.
- event.id = m_next_event_id++;
- m_automation_events.insert(insertion_index, move(event));
- m_parameterization_cache = {};
- return InsertResult::Success;
+ return static_cast<InsertResult>(RustFFI::web_audio_param_timeline_set_value_curve_at_time(m_timeline, values.span(), start_time, duration));
}
void AudioParamTimeline::cancel_scheduled_values(double cancel_time)
{
- MutexLocker locker(m_mutex);
-
- // Cancel all scheduled parameter changes with times greater than or equal to cancelTime.
- auto first_event_to_remove = AK::lower_bound_index(m_automation_events, cancel_time, [](auto const& event, double time) {
- return event.time < time ? -1 : 1;
- });
-
- // Any active automations whose event time is less than cancelTime are also cancelled. A SetTarget remains active
- // until the next event, while a SetValueCurve is active through the end of its duration.
- if (first_event_to_remove > 0) {
- auto const& previous_event = m_automation_events[first_event_to_remove - 1];
- auto is_active_automation = previous_event.parameterization.visit(
- [](SetTarget const&) {
- return true;
- },
- [&](SetValueCurve const& set_value_curve) {
- return cancel_time <= previous_event.time + set_value_curve.duration;
- },
- [](auto const&) {
- return false;
- });
- if (is_active_automation)
- --first_event_to_remove;
- }
-
- if (first_event_to_remove < m_automation_events.size())
- m_automation_events.remove(first_event_to_remove, m_automation_events.size() - first_event_to_remove);
- m_parameterization_cache = {};
+ RustFFI::web_audio_param_timeline_cancel_scheduled_values(m_timeline, cancel_time);
}
void AudioParamTimeline::cancel_and_hold_at_time(double cancel_time)
{
- MutexLocker locker(m_mutex);
-
- auto value_to_hold = value_at_time_locked(cancel_time, cancel_time);
- auto event_index = first_event_index_after(cancel_time);
-
- // If the event immediately after cancelTime is a ramp, rewrite it to end at cancelTime with the value from the
- // original timeline. This takes precedence over holding the value of the event active at cancelTime.
- auto rewrote_ramp = false;
- if (event_index < m_automation_events.size()) {
- auto& next_event = m_automation_events[event_index];
- rewrote_ramp = next_event.parameterization.visit(
- [&](OneOf<LinearRamp, ExponentialRamp> auto& ramp) {
- next_event.time = cancel_time;
- ramp.value = value_to_hold;
- return true;
- },
- [](auto&) {
- return false;
- });
- }
-
- // Otherwise, decide which value (if any) to hold from cancelTime onward, based on the event active at cancelTime.
- Optional<float> hold_value;
- auto drop_active_curve = false;
- if (!rewrote_ramp && event_index > 0) {
- auto const& active_event = m_automation_events[event_index - 1];
- hold_value = active_event.parameterization.visit(
- [&](SetTarget const&) -> Optional<float> {
- return value_to_hold;
- },
- [&](SetValueCurve const& set_value_curve) -> Optional<float> {
- // Cancelling exactly at a curve's start truncates it to a zero-duration curve, which produces no
- // output, so the value reverts to the value before the curve rather than the curve's first element.
- if (active_event.time == cancel_time) {
- drop_active_curve = true;
- return event_index >= 2 ? event_value_at_time(event_index - 2, cancel_time) : m_default_value;
- }
- if (cancel_time <= active_event.time + set_value_curve.duration)
- return value_to_hold;
- return {};
- },
- [](auto const&) -> Optional<float> {
- return {};
- });
- }
-
- // Curve removal and hold insertion mutate the event list, so they run after the visit rather than inside it.
- if (drop_active_curve)
- m_automation_events.remove(event_index - 1);
- if (hold_value.has_value())
- VERIFY(insert_event({ .time = cancel_time, .parameterization = Hold { *hold_value } }) == InsertResult::Success);
-
- // Remove all events with times greater than cancelTime. The rewritten ramp or inserted hold remains at cancelTime.
- auto first_event_to_remove = first_event_index_after(cancel_time);
- if (first_event_to_remove < m_automation_events.size())
- m_automation_events.remove(first_event_to_remove, m_automation_events.size() - first_event_to_remove);
- m_parameterization_cache = {};
+ RustFFI::web_audio_param_timeline_cancel_and_hold_at_time(m_timeline, cancel_time);
}
}
diff --git a/Libraries/LibWeb/WebAudio/AudioParamTimeline.h b/Libraries/LibWeb/WebAudio/AudioParamTimeline.h
index d55042663b3..dee1ffd199a 100644
--- a/Libraries/LibWeb/WebAudio/AudioParamTimeline.h
+++ b/Libraries/LibWeb/WebAudio/AudioParamTimeline.h
@@ -1,6 +1,7 @@
/*
* Copyright (c) 2024, Shannon Booth <[email protected]>
* Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@@ -8,10 +9,7 @@
#pragma once
#include <AK/AtomicRefCounted.h>
-#include <AK/Mutex.h>
-#include <AK/Optional.h>
#include <AK/Span.h>
-#include <AK/Variant.h>
#include <AK/Vector.h>
#include <LibWeb/Export.h>
@@ -31,6 +29,7 @@ public:
};
explicit AudioParamTimeline(float default_value);
+ ~AudioParamTimeline();
// All event times passed into these methods must already be clamped to the context's current time by the caller.
InsertResult set_value_at_time(float value, double start_time);
@@ -41,95 +40,17 @@ public:
void cancel_scheduled_values(double cancel_time);
void cancel_and_hold_at_time(double cancel_time);
- // https://webaudio.github.io/web-audio-api/#computedvalue
float value_at_time(double time) const;
// Evaluates the intrinsic value for each sample frame of a render quantum starting at start_time.
void sample(double start_time, double sample_period, Span<float> output) const;
bool has_events() const;
- float default_value() const { return m_default_value; }
+ float default_value() const;
+ void const* rust_timeline() const { return m_timeline; }
private:
- struct SetValue {
- float value { 0 };
- };
-
- struct RampStart {
- size_t set_target_event_id { 0 };
- double time { 0 };
- float value { 0 };
- };
-
- struct LinearRamp {
- float value { 0 };
- Optional<RampStart> start;
- };
-
- struct ExponentialRamp {
- float value { 0 };
- Optional<RampStart> start;
- };
-
- struct SetTarget {
- float target { 0 };
- float time_constant { 0 };
- };
-
- struct SetValueCurve {
- Vector<float> values;
- double duration { 0 };
- };
-
- struct Hold {
- float value { 0 };
- };
-
- using Parameterization = Variant<SetValue, LinearRamp, ExponentialRamp, SetTarget, SetValueCurve, Hold>;
-
- struct AutomationEvent {
- double time { 0 };
- Parameterization parameterization;
- size_t id { 0 };
- };
-
- struct ParameterizationCache {
- Optional<size_t> event_index {};
- Optional<double> minimum_time {};
- Optional<double> maximum_time {};
- float starting_value { 0 };
-
- bool contains(double time) const
- {
- return (!minimum_time.has_value() || time >= *minimum_time)
- && (!maximum_time.has_value() || time < *maximum_time);
- }
- };
-
- float value_at_time_locked(double selection_time, double time) const;
-
- // https://webaudio.github.io/web-audio-api/#dfn-automation-event
- size_t first_event_index_after(double) const;
-
- Optional<RampStart> ramp_start_for_insertion_index(size_t event_index, double current_time) const;
-
- float event_value_at_time(size_t event_index, double time) const;
-
- // https://webaudio.github.io/web-audio-api/#computedvalue
- ParameterizationCache const& parameterization_cache_for_time(double) const;
-
- // https://webaudio.github.io/web-audio-api/#dfn-automation-event
- InsertResult insert_event(AutomationEvent);
-
- mutable Mutex m_mutex;
-
- float m_default_value {};
-
- // https://webaudio.github.io/web-audio-api/#dfn-automation-event
- Vector<AutomationEvent> m_automation_events;
- size_t m_next_event_id { 0 };
-
- mutable Optional<ParameterizationCache> m_parameterization_cache;
+ void const* m_timeline { nullptr };
};
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/AudioBus.h b/Libraries/LibWeb/WebAudio/Rendering/AudioBus.h
index 6dfae344f44..cd37957284b 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/AudioBus.h
+++ b/Libraries/LibWeb/WebAudio/Rendering/AudioBus.h
@@ -31,6 +31,8 @@ public:
Span<float> channel(size_t index);
ReadonlySpan<float> channel(size_t index) const;
+ void const* rust_bus() const { return m_bus; }
+
void zero();
bool is_silent() const;
void set_channel_count(size_t);
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.cpp b/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.cpp
index 0b2754470de..9e94b1afc9a 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/RenderGraph.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
*/
@@ -111,7 +112,7 @@ void RenderGraph::rebuild_incoming_connections()
for (size_t input_index = 0; input_index < graph_node->input_count(); ++input_index)
graph_node->input_connections(input_index).clear_with_capacity();
graph_node->for_each_param([](RenderAudioParam& param) {
- param.inputs().clear_with_capacity();
+ param.clear_inputs();
});
}
@@ -122,7 +123,7 @@ void RenderGraph::rebuild_incoming_connections()
destination_node->input_connections(connection.input_index).append({ node_id, connection.output_index });
}
for (auto const& connection : graph_node->outgoing_param_connections())
- connection.destination->inputs().append({ node_id, connection.output_index });
+ connection.destination->add_input(node_id, connection.output_index);
}
}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cpp
index bcef238edc7..96169636ae7 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cpp
+++ b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.cpp
@@ -1,81 +1,56 @@
/*
* Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Math.h>
+#include <LibWeb/WebAudio/RustFFI.h>
#include <LibWeb/WebAudio/Rendering/RenderGraph.h>
#include <LibWeb/WebAudio/Rendering/RenderNode.h>
namespace Web::WebAudio::Rendering {
RenderAudioParam::RenderAudioParam(NonnullRefPtr<AudioParamTimeline> timeline, float min_value, float max_value, Bindings::AutomationRate automation_rate)
- : m_timeline(move(timeline))
- , m_min_value(min_value)
- , m_max_value(max_value)
- , m_automation_rate(automation_rate)
+ : m_param(RustFFI::web_audio_render_param_create(timeline->rust_timeline(), min_value, max_value, static_cast<RustFFI::AutomationRate>(automation_rate)))
{
+ static_assert(to_underlying(Bindings::AutomationRate::ARate) == to_underlying(RustFFI::AutomationRate::ARate));
+ static_assert(to_underlying(Bindings::AutomationRate::KRate) == to_underlying(RustFFI::AutomationRate::KRate));
}
-// https://webaudio.github.io/web-audio-api/#computation-of-value
-void RenderAudioParam::compute(RenderGraph& graph, RenderContext const& context, Span<float> output)
+RenderAudioParam::~RenderAudioParam()
{
- // 1. paramIntrinsicValue will be calculated at each time, which is either the value set directly to the value
- // attribute, or, if there are any automation events with times before or at this time, the value as calculated
- // from these events.
- // NB: An a-rate parameter takes the exact value of the signal at each sample frame of the render quantum, while a
- // k-rate parameter uses the value of the very first sample frame for the entire quantum.
- auto rate = automation_rate();
- if (rate == Bindings::AutomationRate::KRate) {
- auto value = m_timeline->value_at_time(context.quantum_start_time());
- output.fill(value);
- } else {
- m_timeline->sample(context.quantum_start_time(), context.sample_period(), output);
- }
+ RustFFI::web_audio_render_param_destroy(m_param);
+}
- // 2. Set [[current value]] to the value of paramIntrinsicValue at the beginning of this render quantum.
- // NB: The render param keeps no [[current value]] slot of its own; the AudioParam's value getter reads the shared
- // automation timeline directly on the control thread.
-
- // 3. paramComputedValue is the sum of the paramIntrinsicValue value and the value of the input AudioParam
- // buffer. If the sum is NaN, replace the sum with the defaultValue.
- for (auto const& input : m_inputs) {
- auto const* bus = graph.pull_output(input.source, input.output_index, context);
- if (!bus)
- continue;
-
- // 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.
- if (!m_input_scratch || m_input_scratch->frame_count() != context.quantum_size)
- m_input_scratch = make<AudioBus>(1, context.quantum_size);
- m_input_scratch->zero();
- m_input_scratch->sum_from(*bus, Bindings::ChannelInterpretation::Speakers);
-
- auto input_samples = m_input_scratch->channel(0);
- if (rate == Bindings::AutomationRate::KRate) {
- for (auto& value : output)
- value += input_samples[0];
- } else {
- for (size_t frame = 0; frame < output.size(); ++frame)
- output[frame] += input_samples[frame];
- }
- }
- auto default_value = m_timeline->default_value();
- for (auto& value : output) {
- if (isnan(value))
- value = default_value;
- }
+void RenderAudioParam::set_automation_rate(Bindings::AutomationRate rate)
+{
+ RustFFI::web_audio_render_param_set_automation_rate(m_param, static_cast<RustFFI::AutomationRate>(rate));
+}
+
+Bindings::AutomationRate RenderAudioParam::automation_rate() const
+{
+ return static_cast<Bindings::AutomationRate>(RustFFI::web_audio_render_param_automation_rate(m_param));
+}
- // 4. If this AudioParam is a compound parameter, compute its final value with other AudioParams.
- // NB: None of the AudioParams backed by a render node are compound parameters.
+void RenderAudioParam::clear_inputs()
+{
+ RustFFI::web_audio_render_param_clear_inputs(m_param);
+}
- // 5. Set computedValue to paramComputedValue.
+void RenderAudioParam::add_input(NodeID source, size_t output_index)
+{
+ RustFFI::web_audio_render_param_add_input(m_param, source.value(), output_index);
+}
- // NB: The computedValue is clamped to the simple nominal range for this parameter.
- // https://webaudio.github.io/web-audio-api/#simple-nominal-range
- for (auto& value : output)
- value = clamp(value, m_min_value, m_max_value);
+void RenderAudioParam::compute(RenderGraph& graph, RenderContext const& context, Span<float> output)
+{
+ RustFFI::RenderContext rust_context { context.sample_rate, context.quantum_size, context.quantum_start_frame };
+ RustFFI::web_audio_render_param_compute(m_param, &graph, [](void* graph, u64 source, size_t output_index, RustFFI::RenderContext const* context) -> void const* {
+ RenderContext render_context { context->sample_rate, context->quantum_size, context->quantum_start_frame };
+ auto const* bus = static_cast<RenderGraph*>(graph)->pull_output(source, output_index, render_context);
+ return bus ? 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)
diff --git a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.h b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.h
index baec91da805..b7f24e6516e 100644
--- a/Libraries/LibWeb/WebAudio/Rendering/RenderNode.h
+++ b/Libraries/LibWeb/WebAudio/Rendering/RenderNode.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
*/
@@ -42,25 +43,18 @@ class WEB_API RenderAudioParam : public AtomicRefCounted<RenderAudioParam> {
public:
RenderAudioParam(NonnullRefPtr<AudioParamTimeline> timeline, float min_value, float max_value, Bindings::AutomationRate);
- void set_automation_rate(Bindings::AutomationRate automation_rate) { m_automation_rate.store(automation_rate); }
- Bindings::AutomationRate automation_rate() const { return m_automation_rate.load(); }
+ ~RenderAudioParam();
+
+ void set_automation_rate(Bindings::AutomationRate);
+ Bindings::AutomationRate automation_rate() const;
void compute(RenderGraph&, RenderContext const&, Span<float> output);
- struct Input {
- NodeID source;
- size_t output_index;
- };
- Vector<Input>& inputs() { return m_inputs; }
+ void clear_inputs();
+ void add_input(NodeID source, size_t output_index);
private:
- NonnullRefPtr<AudioParamTimeline> m_timeline;
- float m_min_value { 0 };
- float m_max_value { 0 };
- Atomic<Bindings::AutomationRate> m_automation_rate;
-
- Vector<Input> m_inputs;
- OwnPtr<AudioBus> m_input_scratch;
+ void const* m_param { nullptr };
};
// Base class for the rendering thread's counterparts of AudioNodes. Render nodes are constructed on the control thread