Truly independent web browser
LibWeb: Retain AudioParam intrinsic values after cancellation
Shannon Booth9d979bfaffb1
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rsindex 24ee67048f2..2c3d42a35ae 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_param.rs@@ -42,7 +42,6 @@ pub(crate) struct AudioParam {render_param: Arc<RenderAudioParam>,// https://webaudio.github.io/web-audio-api/#dom-audioparam-current-value-slot- current_value: Cell<f32>, // [[current value]]default_value: f32,min_value: f32,max_value: f32,@@ -94,7 +93,6 @@ impl AudioParam {owner: Cell::new(owner),timeline,render_param,- current_value: Cell::new(default_value),default_value,min_value,max_value,@@ -130,22 +128,15 @@ impl AudioParam {pub(crate) fn value(&self, _: &mut CallContext) -> WebIdlResult<f32> {// Each AudioParam includes minValue and maxValue attributes that together form the simple nominal range// for the parameter. In effect, value of the parameter is clamped to the range [minValue, maxValue].- if self.timeline.has_events() {- return Ok(clamp(- self.timeline.value_at_time(self.current_time()),- self.min_value,- self.max_value,- ));- }- Ok(clamp(self.current_value.get(), self.min_value, self.max_value))+ Ok(clamp(self.timeline.current_value(), self.min_value, self.max_value))}// https://webaudio.github.io/web-audio-api/#dom-audioparam-valuepub(crate) fn set_value(this: &Ref<Self>, cx: &mut CallContext, value: f32) -> WebIdlResult<()> {// Setting this attribute has the effect of assigning the requested value to the [[current value]] slot, and calling// the setValueAtTime() method with the current AudioContext's currentTime and [[current value]].- this.current_value.set(value);- Self::set_value_at_time(this, cx, this.current_value.get(), this.current_time())?;+ this.timeline.set_current_value(value);+ Self::set_value_at_time(this, cx, value, this.current_time())?;Ok(())}@@ -239,7 +230,7 @@ impl AudioParam {this.map_insert_result(cx.vm(),this.timeline- .linear_ramp_to_value_at_time(value, end_time, current_time, this.current_value.get()),+ .linear_ramp_to_value_at_time(value, end_time, current_time, this.timeline.current_value()),)?;Ok(*this)}@@ -266,8 +257,12 @@ impl AudioParam {end_time = max(end_time, current_time);this.map_insert_result(cx.vm(),- this.timeline- .exponential_ramp_to_value_at_time(value, end_time, current_time, this.current_value.get()),+ this.timeline.exponential_ramp_to_value_at_time(+ value,+ end_time,+ current_time,+ this.timeline.current_value(),+ ),)?;Ok(*this)}diff --git a/Libraries/LibWeb/Rust/src/web_audio/audio_param_timeline.rs b/Libraries/LibWeb/Rust/src/web_audio/audio_param_timeline.rsindex 7fa5da24a26..687add0fe6c 100644--- a/Libraries/LibWeb/Rust/src/web_audio/audio_param_timeline.rs+++ b/Libraries/LibWeb/Rust/src/web_audio/audio_param_timeline.rs@@ -55,8 +55,9 @@ impl ParameterizationCache {}}-#[derive(Default)]struct TimelineState {+ current_value: f32,+ fallback_value: f32,// https://webaudio.github.io/web-audio-api/#dfn-automation-eventautomation_events: Vec<AutomationEvent>,next_event_id: usize,@@ -77,7 +78,13 @@ impl AudioParamTimeline {pub fn new(default_value: f32) -> Self {Self {default_value,- mutex: Mutex::new(TimelineState::default()),+ mutex: Mutex::new(TimelineState {+ current_value: default_value,+ fallback_value: default_value,+ automation_events: Vec::new(),+ next_event_id: 0,+ parameterization_cache: None,+ }),}}@@ -85,24 +92,29 @@ impl AudioParamTimeline {self.default_value}+ pub fn current_value(&self) -> f32 {+ self.mutex.lock().unwrap().current_value+ }++ pub fn set_current_value(&self, value: f32) {+ let mut state = self.mutex.lock().unwrap();+ state.current_value = value;+ state.fallback_value = value;+ state.parameterization_cache = None;+ }+// https://webaudio.github.io/web-audio-api/#computedvaluepub 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)+ self.mutex.lock().unwrap().value_at_time_locked(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);+ *value = state.value_at_time_locked(frame_time + sample_period / 2., frame_time);}- }-- pub fn has_events(&self) -> bool {- let state = self.mutex.lock().unwrap();- !state.automation_events.is_empty()+ state.current_value = output[0];}// All event times passed into these methods must already be clamped to the context's current time by the caller.@@ -127,7 +139,7 @@ impl AudioParamTimeline {// 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);+ let ramp_start = state.ramp_start_for_insertion_index(state.fallback_value, event_index, current_time);if event_index == 0 {let result = state.insert_event(AutomationEvent {time: current_time,@@ -159,7 +171,7 @@ impl AudioParamTimeline {// 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);+ let ramp_start = state.ramp_start_for_insertion_index(state.fallback_value, event_index, current_time);if event_index == 0 {let result = state.insert_event(AutomationEvent {time: current_time,@@ -230,6 +242,9 @@ impl AudioParamTimeline {if first_event_to_remove < state.automation_events.len() {state.automation_events.truncate(first_event_to_remove);+ if state.automation_events.is_empty() {+ state.fallback_value = state.current_value;+ }}state.parameterization_cache = None;}@@ -237,7 +252,7 @@ impl AudioParamTimeline {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 value_to_hold = state.value_at_time_locked(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@@ -268,9 +283,9 @@ impl AudioParamTimeline {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)+ state.event_value_at_time(state.fallback_value, event_index - 2, cancel_time)} else {- self.default_value+ state.fallback_value})} else if cancel_time <= active_event.time + duration {Some(value_to_hold)@@ -307,14 +322,12 @@ impl AudioParamTimeline {}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.+ fn value_at_time_locked(&mut self, selection_time: f64, time: f64) -> f32 {// 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 fallback_value = self.fallback_value;+ let cache = self.parameterization_cache_for_time(fallback_value, selection_time);let Some(event_index) = cache.event_index else {return cache.starting_value;};@@ -358,7 +371,7 @@ impl TimelineState {+ (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),+ Parameterization::SetValueCurve { .. } => self.event_value_at_time(fallback_value, event_index, time),}}diff --git a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rsindex bf981972d3d..2335e091e69 100644--- a/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs+++ b/Libraries/LibWeb/Rust/src/web_audio/rendering/render_node.rs@@ -104,12 +104,14 @@ impl 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.+ // from these events. If automation events are removed from a given time range, then the paramIntrinsicValue+ // value will remain unchanged and stay at its previous value until either the value attribute is directly+ // set, or automation events are added for the time range.+ // NB: A k-rate parameter uses the 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());+ self.timeline.sample(context.quantum_start_time(), 0., &mut output[..1]);+ let value = output[0];output.fill(value);} else {self.timeline@@ -117,8 +119,7 @@ impl RenderAudioParam {}// 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.+ // NB: Sampling updates the slot while holding the timeline lock.// 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.diff --git a/Tests/LibWeb/Text/expected/WebAudio/AudioParam-value-after-cancellation.txt b/Tests/LibWeb/Text/expected/WebAudio/AudioParam-value-after-cancellation.txtnew file mode 100644index 00000000000..e74cfeea433--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebAudio/AudioParam-value-after-cancellation.txt@@ -0,0 +1,3 @@+Intrinsic gain before rendering: 2+Intrinsic gain after rendering: 2+Every sample uses the retained gain: truediff --git a/Tests/LibWeb/Text/input/WebAudio/AudioParam-value-after-cancellation.html b/Tests/LibWeb/Text/input/WebAudio/AudioParam-value-after-cancellation.htmlnew file mode 100644index 00000000000..f1b2e651a81--- /dev/null+++ b/Tests/LibWeb/Text/input/WebAudio/AudioParam-value-after-cancellation.html@@ -0,0 +1,20 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const context = new OfflineAudioContext(1, 128, 48000);+ const source = new ConstantSourceNode(context);+ const gain = new GainNode(context);+ source.connect(gain).connect(context.destination);+ source.start();++ gain.gain.value = 2;+ gain.gain.setValueAtTime(3, 0);+ gain.gain.cancelScheduledValues(0);+ println(`Intrinsic gain before rendering: ${gain.gain.value}`);++ const output = await context.startRendering();+ println(`Intrinsic gain after rendering: ${gain.gain.value}`);+ println(`Every sample uses the retained gain: ${output.getChannelData(0).every(sample => sample === 2)}`);+ });+</script>