Skip to content

Truly independent web browser

LibWeb: Fire audioprocess events on ScriptProcessorNode

Jelle Raaijmakersfac2cc66a88c
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index f08f3e09058..618ea3f391f 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1037,6 +1037,8 @@ set(SOURCES
WebAudio/Rendering/RenderGraph.cpp
WebAudio/Rendering/RenderNode.cpp
WebAudio/Rendering/RenderNodes.cpp
+ WebAudio/Rendering/ScriptProcessorPipe.cpp
+ WebAudio/Rendering/ScriptProcessorRenderNode.cpp
WebAudio/ScriptProcessorNode.cpp
WebAudio/StereoPannerNode.cpp
WebAudio/WaveShaperNode.cpp
diff --git a/Libraries/LibWeb/WebAudio/AudioNode.cpp b/Libraries/LibWeb/WebAudio/AudioNode.cpp
index 7f2c4c70f23..1b4e939ea8e 100644
--- a/Libraries/LibWeb/WebAudio/AudioNode.cpp
+++ b/Libraries/LibWeb/WebAudio/AudioNode.cpp
@@ -368,8 +368,8 @@ void AudioNode::visit_edges(Cell::Visitor& visitor)
// references to any nodes it is connected to, and so on".
// NB: The context roots every source node that is playing, which is what keeps a subgraph feeding the destination
// alive for as long as it can still produce sound.
- // FIXME: A node that is still within its tail-time, and a ScriptProcessorNode or MediaElementAudioSourceNode that
- // is actively processing, should be kept alive by the context in the same way.
+ // FIXME: A node that is still within its tail-time, and a MediaElementAudioSourceNode that is actively processing,
+ // should be kept alive by the context in the same way.
for (auto& conn : m_param_connections)
visitor.visit(conn.destination_param);
diff --git a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp b/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp
index 7623e2d6740..1603be83b39 100644
--- a/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp
+++ b/Libraries/LibWeb/WebAudio/BaseAudioContext.cpp
@@ -98,6 +98,16 @@ void BaseAudioContext::visit_edges(Cell::Visitor& visitor)
visitor.visit(m_document_observer);
visitor.visit(m_audio_worklet);
visitor.visit(m_playing_sources);
+
+ // INTEROP: Blink keeps a ScriptProcessorNode with audioprocess listeners alive until its context is cleared
+ // (ScriptProcessorNode::HasPendingActivity()), whether it is connected or not, so that a node script only
+ // reaches through its listener keeps producing audio.
+ if (state() != AudioContextState::Closed) {
+ for (auto& node : m_script_processor_nodes) {
+ if (node.has_event_listener(HTML::EventNames::audioprocess))
+ visitor.visit(node);
+ }
+ }
}
void BaseAudioContext::add_playing_source(GC::Ref<AudioNode> node)
@@ -105,6 +115,11 @@ void BaseAudioContext::add_playing_source(GC::Ref<AudioNode> node)
m_playing_sources.set(node->node_id(), node);
}
+void BaseAudioContext::add_script_processor_node(ScriptProcessorNode& node)
+{
+ m_script_processor_nodes.set(node);
+}
+
void BaseAudioContext::handle_ended_sources(ReadonlySpan<NodeID> ended_nodes)
{
for (auto node_id : ended_nodes) {
diff --git a/Libraries/LibWeb/WebAudio/BaseAudioContext.h b/Libraries/LibWeb/WebAudio/BaseAudioContext.h
index 00fc020e4dc..b94c48d500f 100644
--- a/Libraries/LibWeb/WebAudio/BaseAudioContext.h
+++ b/Libraries/LibWeb/WebAudio/BaseAudioContext.h
@@ -10,6 +10,7 @@
#include <AK/ByteBuffer.h>
#include <AK/Function.h>
+#include <LibGC/WeakHashSet.h>
#include <LibWeb/Bindings/BaseAudioContext.h>
#include <LibWeb/DOM/EventTarget.h>
#include <LibWeb/WebAudio/AnalyserNode.h>
@@ -128,6 +129,7 @@ public:
NonnullRefPtr<ControlMessageQueue> control_message_queue() const { return m_control_message_queue; }
void add_playing_source(GC::Ref<AudioNode>);
+ void add_script_processor_node(ScriptProcessorNode&);
void handle_ended_sources(ReadonlySpan<NodeID>);
void set_current_time(double current_time) { m_current_time = current_time; }
@@ -174,6 +176,7 @@ private:
NonnullRefPtr<ControlMessageQueue> m_control_message_queue;
HashMap<NodeID, GC::Ref<AudioNode>> m_playing_sources;
+ GC::WeakHashSet<ScriptProcessorNode> m_script_processor_nodes;
};
void resolve_audio_buffer_promise(JS::Realm&, WebIDL::Promise const&, AudioBuffer&);
diff --git a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.cpp b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.cpp
new file mode 100644
index 00000000000..5fd0525cb94
--- /dev/null
+++ b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.cpp
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibCore/EventLoop.h>
+#include <LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h>
+
+namespace Web::WebAudio::Rendering {
+
+// Moves a ScriptProcessorNode's blocks of buffer_size frames between the rendering thread and the control thread. The
+// render node cycles through block_count blocks, so a block's output plays block_count blocks after its input was
+// captured. A block the control thread has not handed back in time renders silence and drops its input, unless the
+// rendering thread waits for processing.
+NonnullRefPtr<ScriptProcessorPipe> ScriptProcessorPipe::create(Config config, Core::EventLoop& control_thread_event_loop)
+{
+ VERIFY(config.buffer_size > 0);
+ VERIFY(config.block_count >= 2);
+ return adopt_ref(*new ScriptProcessorPipe(config, control_thread_event_loop));
+}
+
+ScriptProcessorPipe::ScriptProcessorPipe(Config config, Core::EventLoop& control_thread_event_loop)
+ : m_config(config)
+ , m_input_samples(MUST(FixedArray<float>::create(config.block_count * config.input_channel_count * config.buffer_size)))
+ , m_output_samples(MUST(FixedArray<float>::create(config.block_count * config.output_channel_count * config.buffer_size)))
+ , m_blocks(MUST(FixedArray<Block>::create(config.block_count)))
+ , m_control_thread_event_loop(control_thread_event_loop)
+{
+}
+
+Span<float> ScriptProcessorPipe::input_channel(size_t block, size_t channel)
+{
+ VERIFY(block < m_config.block_count);
+ VERIFY(channel < m_config.input_channel_count);
+ return m_input_samples.span().slice((block * m_config.input_channel_count + channel) * m_config.buffer_size, m_config.buffer_size);
+}
+
+Span<float> ScriptProcessorPipe::output_channel(size_t block, size_t channel)
+{
+ VERIFY(block < m_config.block_count);
+ VERIFY(channel < m_config.output_channel_count);
+ return m_output_samples.span().slice((block * m_config.output_channel_count + channel) * m_config.buffer_size, m_config.buffer_size);
+}
+
+bool ScriptProcessorPipe::is_block_owned_by_rendering_thread(size_t block) const
+{
+ return !m_blocks[block].is_owned_by_control_thread.load(AK::MemoryOrder::memory_order_acquire);
+}
+
+void ScriptProcessorPipe::hand_block_to_control_thread(size_t block, u64 start_frame)
+{
+ m_blocks[block].is_owned_by_control_thread.store(true, AK::MemoryOrder::memory_order_release);
+ m_control_thread_event_loop.deferred_invoke([self = NonnullRefPtr(*this), block, start_frame] {
+ if (self->m_process_callback && !self->is_shut_down())
+ self->m_process_callback(block, start_frame);
+ else
+ self->hand_block_back_to_rendering_thread(block, false);
+ });
+
+ if (!m_config.waits_for_processing)
+ return;
+ MutexLocker locker(m_mutex);
+ m_block_returned.wait_while([&] {
+ return !is_block_owned_by_rendering_thread(block) && !is_shut_down();
+ });
+}
+
+void ScriptProcessorPipe::set_process_callback(Function<void(size_t, u64)> process_callback)
+{
+ m_process_callback = move(process_callback);
+}
+
+void ScriptProcessorPipe::clear_process_callback()
+{
+ m_process_callback = nullptr;
+}
+
+void ScriptProcessorPipe::hand_block_back_to_rendering_thread(size_t block, bool has_output)
+{
+ m_blocks[block].has_output = has_output;
+ m_blocks[block].is_owned_by_control_thread.store(false, AK::MemoryOrder::memory_order_release);
+
+ // The lock orders this notification after a waiting rendering thread has checked the block's owner.
+ MutexLocker locker(m_mutex);
+ m_block_returned.broadcast();
+}
+
+void ScriptProcessorPipe::shut_down()
+{
+ m_is_shut_down.store(true, AK::MemoryOrder::memory_order_release);
+ MutexLocker locker(m_mutex);
+ m_block_returned.broadcast();
+}
+
+}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h
new file mode 100644
index 00000000000..3f816365187
--- /dev/null
+++ b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Atomic.h>
+#include <AK/AtomicRefCounted.h>
+#include <AK/ConditionVariable.h>
+#include <AK/FixedArray.h>
+#include <AK/Function.h>
+#include <AK/Mutex.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/Span.h>
+#include <AK/Types.h>
+#include <LibCore/Forward.h>
+#include <LibWeb/Export.h>
+
+namespace Web::WebAudio::Rendering {
+
+class WEB_API ScriptProcessorPipe final : public AtomicRefCounted<ScriptProcessorPipe> {
+public:
+ struct Config {
+ size_t buffer_size { 0 };
+ size_t input_channel_count { 0 };
+ size_t output_channel_count { 0 };
+ size_t block_count { 0 };
+ bool waits_for_processing { false };
+ };
+
+ static NonnullRefPtr<ScriptProcessorPipe> create(Config, Core::EventLoop& control_thread_event_loop);
+
+ Config const& config() const { return m_config; }
+
+ Span<float> input_channel(size_t block, size_t channel);
+ Span<float> output_channel(size_t block, size_t channel);
+ bool has_output(size_t block) const { return m_blocks[block].has_output; }
+
+ bool is_block_owned_by_rendering_thread(size_t block) const;
+ void hand_block_to_control_thread(size_t block, u64 start_frame);
+
+ void set_process_callback(Function<void(size_t block, u64 start_frame)>);
+ void clear_process_callback();
+ void hand_block_back_to_rendering_thread(size_t block, bool has_output);
+
+ void shut_down();
+ bool is_shut_down() const { return m_is_shut_down.load(AK::MemoryOrder::memory_order_acquire); }
+
+private:
+ ScriptProcessorPipe(Config, Core::EventLoop& control_thread_event_loop);
+
+ struct Block {
+ Atomic<bool> is_owned_by_control_thread { false };
+ bool has_output { false };
+ };
+
+ Config m_config;
+ FixedArray<float> m_input_samples;
+ FixedArray<float> m_output_samples;
+ FixedArray<Block> m_blocks;
+
+ Core::EventLoop& m_control_thread_event_loop;
+ Function<void(size_t, u64)> m_process_callback;
+
+ Mutex m_mutex;
+ ConditionVariable m_block_returned { m_mutex };
+ Atomic<bool> m_is_shut_down { false };
+};
+
+}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.cpp b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.cpp
new file mode 100644
index 00000000000..c6f3d07f5e2
--- /dev/null
+++ b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWeb/WebAudio/Rendering/RenderGraph.h>
+#include <LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.h>
+
+namespace Web::WebAudio::Rendering {
+
+ScriptProcessorRenderNode::ScriptProcessorRenderNode(NodeID node_id, size_t quantum_size, NonnullRefPtr<ScriptProcessorPipe> pipe)
+ : RenderNode(node_id, 1, 1, quantum_size, max(pipe->config().output_channel_count, 1uz))
+ , m_pipe(move(pipe))
+{
+ VERIFY(m_pipe->config().buffer_size % quantum_size == 0);
+}
+
+ScriptProcessorRenderNode::~ScriptProcessorRenderNode() = default;
+
+void ScriptProcessorRenderNode::process(RenderGraph& graph, RenderContext const& context)
+{
+ auto& output_bus = output(0);
+ output_bus.set_channel_count(max(m_pipe->config().output_channel_count, 1uz));
+ output_bus.zero();
+ if (m_pipe->is_shut_down())
+ return;
+
+ // https://webaudio.github.io/web-audio-api/#ScriptProcessorNode
+ // audioprocess events are only dispatched if the ScriptProcessorNode has at least one input or one output
+ // connected.
+ if (input_connections(0).is_empty() && outgoing_node_connections().is_empty() && outgoing_param_connections().is_empty())
+ return;
+
+ auto const& config = m_pipe->config();
+ if (m_frame_in_block == 0) {
+ m_block_start_frame = context.quantum_start_frame;
+ m_block_is_owned = m_pipe->is_block_owned_by_rendering_thread(m_block);
+ }
+
+ if (m_block_is_owned) {
+ if (config.input_channel_count > 0) {
+ auto const& input_bus = pull_input(graph, context, 0);
+ for (size_t channel = 0; channel < config.input_channel_count; ++channel) {
+ auto destination = m_pipe->input_channel(m_block, channel).slice(m_frame_in_block, context.quantum_size);
+ if (channel < input_bus.channel_count())
+ input_bus.channel(channel).copy_to(destination);
+ else
+ destination.fill(0);
+ }
+ }
+
+ if (m_pipe->has_output(m_block)) {
+ for (size_t channel = 0; channel < config.output_channel_count; ++channel)
+ m_pipe->output_channel(m_block, channel).slice(m_frame_in_block, context.quantum_size).copy_to(output_bus.channel(channel));
+ }
+ }
+
+ m_frame_in_block += context.quantum_size;
+ if (m_frame_in_block < config.buffer_size)
+ return;
+
+ if (m_block_is_owned)
+ m_pipe->hand_block_to_control_thread(m_block, m_block_start_frame);
+ m_block = (m_block + 1) % config.block_count;
+ m_frame_in_block = 0;
+}
+
+}
diff --git a/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.h b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.h
new file mode 100644
index 00000000000..db677e29b4f
--- /dev/null
+++ b/Libraries/LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2026, Jelle Raaijmakers <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/NonnullRefPtr.h>
+#include <LibWeb/WebAudio/Rendering/RenderNode.h>
+#include <LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h>
+
+namespace Web::WebAudio::Rendering {
+
+class ScriptProcessorRenderNode final : public RenderNode {
+public:
+ ScriptProcessorRenderNode(NodeID, size_t quantum_size, NonnullRefPtr<ScriptProcessorPipe>);
+ virtual ~ScriptProcessorRenderNode() override;
+
+ virtual void process(RenderGraph&, RenderContext const&) override;
+
+private:
+ NonnullRefPtr<ScriptProcessorPipe> m_pipe;
+ size_t m_block { 0 };
+ size_t m_frame_in_block { 0 };
+ u64 m_block_start_frame { 0 };
+ bool m_block_is_owned { false };
+};
+
+}
diff --git a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp
index db4eb3b30f6..a39b7b13275 100644
--- a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp
+++ b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.cpp
@@ -7,8 +7,22 @@
#include "BaseAudioContext.h"
#include <AK/GenericShorthands.h>
+#include <LibCore/EventLoop.h>
#include <LibGC/Heap.h>
+#include <LibGC/Weak.h>
+#include <LibWeb/DOM/Document.h>
#include <LibWeb/HTML/EventNames.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/HTML/Window.h>
+#include <LibWeb/HighResolutionTime/TimeOrigin.h>
+#include <LibWeb/WebAudio/AudioBuffer.h>
+#include <LibWeb/WebAudio/AudioProcessingEvent.h>
+#include <LibWeb/WebAudio/OfflineAudioContext.h>
+#include <LibWeb/WebAudio/Rendering/AudioWorkletPipe.h>
+#include <LibWeb/WebAudio/Rendering/RealtimeAudioRenderer.h>
+#include <LibWeb/WebAudio/Rendering/ScriptProcessorPipe.h>
+#include <LibWeb/WebAudio/Rendering/ScriptProcessorRenderNode.h>
#include <LibWeb/WebAudio/ScriptProcessorNode.h>
namespace Web::WebAudio {
@@ -17,7 +31,7 @@ GC_DEFINE_ALLOCATOR(ScriptProcessorNode);
ScriptProcessorNode::ScriptProcessorNode(GC::Ref<BaseAudioContext> context,
u8 number_of_input_channels, u8 number_of_output_channels)
- : AudioNode(context)
+ : AudioNode(context, number_of_input_channels)
, m_number_of_input_channels(number_of_input_channels)
, m_number_of_output_channels(number_of_output_channels)
{
@@ -25,6 +39,20 @@ ScriptProcessorNode::ScriptProcessorNode(GC::Ref<BaseAudioContext> context,
ScriptProcessorNode::~ScriptProcessorNode() = default;
+// Other engines have a latency of two buffers. A realtime context needs more when the device pulls a burst of audio
+// that is longer than a buffer, since script cannot run in the middle of a burst.
+static size_t block_count_for_context(BaseAudioContext const& context, size_t buffer_size)
+{
+ if (is<OfflineAudioContext>(context))
+ return 2;
+ auto quantum_size = BaseAudioContext::render_quantum_size();
+ auto lookahead_frames = Rendering::AudioWorkletPipe::Config::ring_sizing_for_device_latency(
+ Rendering::RealtimeAudioRenderer::TARGET_LATENCY_MS, context.sample_rate(), quantum_size)
+ .prime_level
+ * quantum_size;
+ return max(ceil_div(lookahead_frames, buffer_size) + 1, 2uz);
+}
+
WebIDL::ExceptionOr<GC::Ref<ScriptProcessorNode>> ScriptProcessorNode::create(
GC::Ref<BaseAudioContext> context,
WebIDL::Long buffer_size,
@@ -41,9 +69,76 @@ WebIDL::ExceptionOr<GC::Ref<ScriptProcessorNode>> ScriptProcessorNode::create(
// any attempt to change the value.
TRY(script_processor_node->set_channel_count_mode(ChannelCountMode::Explicit));
+ Rendering::ScriptProcessorPipe::Config pipe_config {
+ .buffer_size = static_cast<size_t>(buffer_size),
+ .input_channel_count = number_of_input_channels,
+ .output_channel_count = number_of_output_channels,
+ .block_count = block_count_for_context(context, buffer_size),
+ .waits_for_processing = is<OfflineAudioContext>(*context),
+ };
+ auto pipe = Rendering::ScriptProcessorPipe::create(pipe_config, Core::EventLoop::current());
+ pipe->set_process_callback([node = GC::Weak { *script_processor_node }](size_t block, u64 start_frame) {
+ if (node)
+ node->process_block(block, start_frame);
+ });
+ script_processor_node->m_pipe = pipe;
+ context->add_script_processor_node(*script_processor_node);
+ script_processor_node->queue_render_node_creation(make<Rendering::ScriptProcessorRenderNode>(
+ script_processor_node->node_id(), BaseAudioContext::render_quantum_size(), move(pipe)));
+
return script_processor_node;
}
+void ScriptProcessorNode::finalize()
+{
+ if (m_pipe) {
+ m_pipe->clear_process_callback();
+ m_pipe->shut_down();
+ }
+ Base::finalize();
+}
+
+void ScriptProcessorNode::process_block(size_t block, u64 start_frame)
+{
+ auto& pipe = *m_pipe;
+ auto const& config = pipe.config();
+
+ if (!context()->relevant_window().associated_document().is_fully_active()) {
+ pipe.hand_block_back_to_rendering_thread(block, false);
+ return;
+ }
+
+ auto as_samples = [](Bytes bytes) {
+ return Span<float> { reinterpret_cast<float*>(bytes.data()), bytes.size() / sizeof(float) };
+ };
+
+ auto sample_rate = context()->sample_rate();
+ auto input_buffer = MUST(AudioBuffer::create(config.input_channel_count, config.buffer_size, sample_rate));
+ for (size_t channel = 0; channel < config.input_channel_count; ++channel)
+ pipe.input_channel(block, channel).copy_to(as_samples(MUST(input_buffer->channel_data(channel))));
+ auto output_buffer = MUST(AudioBuffer::create(config.output_channel_count, config.buffer_size, sample_rate));
+
+ auto playback_time = (start_frame + config.block_count * config.buffer_size) / static_cast<double>(sample_rate);
+
+ {
+ HTML::TemporaryExecutionContext execution_context { HTML::relevant_realm(relevant_global_object()), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ AudioProcessingEventInit event_init { {}, input_buffer, output_buffer, playback_time };
+ auto event = AudioProcessingEvent::create(HTML::EventNames::audioprocess, event_init, HighResolutionTime::current_high_resolution_time(relevant_global_object()));
+ dispatch_event(event);
+ }
+
+ // https://webaudio.github.io/web-audio-api/#acquire-the-content
+ // When the dispatch of an AudioProcessingEvent completes, it acquires the contents of its outputBuffer.
+ auto output = output_buffer->acquire_contents();
+ if (!output) {
+ pipe.hand_block_back_to_rendering_thread(block, false);
+ return;
+ }
+ for (size_t channel = 0; channel < config.output_channel_count; ++channel)
+ output->channels[channel].span().copy_to(pipe.output_channel(block, channel));
+ pipe.hand_block_back_to_rendering_thread(block, true);
+}
+
WebIDL::ExceptionOr<void> ScriptProcessorNode::validate_options(
WebIDL::Long buffer_size,
WebIDL::UnsignedLong number_of_input_channels,
diff --git a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.h b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.h
index de1b53d6aa8..ee78799c342 100644
--- a/Libraries/LibWeb/WebAudio/ScriptProcessorNode.h
+++ b/Libraries/LibWeb/WebAudio/ScriptProcessorNode.h
@@ -6,8 +6,15 @@
#pragma once
+#include <AK/RefPtr.h>
#include <LibWeb/WebAudio/AudioNode.h>
+namespace Web::WebAudio::Rendering {
+
+class ScriptProcessorPipe;
+
+}
+
namespace Web::WebAudio {
// https://webaudio.github.io/web-audio-api/#ScriptProcessorNode
@@ -46,8 +53,12 @@ public:
private:
ScriptProcessorNode(GC::Ref<BaseAudioContext>, u8 number_of_input_channels, u8 number_of_output_channels);
+ virtual void finalize() override;
+
void set_buffer_size_without_validation(WebIDL::Long buffer_size) { m_buffer_size = buffer_size; }
+ void process_block(size_t block, u64 start_frame);
+ RefPtr<Rendering::ScriptProcessorPipe> m_pipe;
WebIDL::Long m_buffer_size { 0 };
u8 m_number_of_input_channels { 0 };
u8 m_number_of_output_channels { 0 };
diff --git a/Tests/LibWeb/Text/expected/WebAudio/ScriptProcessorNode-connections.txt b/Tests/LibWeb/Text/expected/WebAudio/ScriptProcessorNode-connections.txt
new file mode 100644
index 00000000000..4d88640bdcd
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebAudio/ScriptProcessorNode-connections.txt
@@ -0,0 +1,4 @@
+audioprocess events for the node never connected: 0
+audioprocess events for the node output connected: 16
+audioprocess events for the node input connected: 16
+audioprocess events for the node disconnected in its first handler: 1
diff --git a/Tests/LibWeb/Text/expected/WebAudio/ScriptProcessorNode-lifetime.txt b/Tests/LibWeb/Text/expected/WebAudio/ScriptProcessorNode-lifetime.txt
new file mode 100644
index 00000000000..369288a6eab
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebAudio/ScriptProcessorNode-lifetime.txt
@@ -0,0 +1,4 @@
+generator with an audioprocess listener is kept alive: true
+node without an audioprocess listener is collected: true
+generator output reaches the destination: true
+generator is collected once its context is closed: true
diff --git a/Tests/LibWeb/Text/expected/WebAudio/ScriptProcessorNode-outputBuffer-acquire.txt b/Tests/LibWeb/Text/expected/WebAudio/ScriptProcessorNode-outputBuffer-acquire.txt
new file mode 100644
index 00000000000..617b248caba
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebAudio/ScriptProcessorNode-outputBuffer-acquire.txt
@@ -0,0 +1,12 @@
+event 1: output array retained from the previous event is detached: true
+event 2: output array retained from the previous event is detached: true
+event 2: detached its output array
+event 3: output array retained from the previous event is detached: true
+event 4: output array retained from the previous event is detached: true
+event 5: output array retained from the previous event is detached: true
+block 0 plays 0
+block 1 plays 0
+block 2 plays 1
+block 3 plays 2
+block 4 plays 0
+block 5 plays 4
diff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-analysernode-interface/test-analyser-minimum.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-analysernode-interface/test-analyser-minimum.txt
new file mode 100644
index 00000000000..be14b8bd787
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-analysernode-interface/test-analyser-minimum.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Test AnalyserNode when the input is silent
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-convolvernode-interface/realtime-conv.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-convolvernode-interface/realtime-conv.txt
new file mode 100644
index 00000000000..bc5c48f1bcc
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-convolvernode-interface/realtime-conv.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Test convolver with real-time context
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-scriptprocessornode-interface/scriptprocessor-rendersizehint.https.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-scriptprocessornode-interface/scriptprocessor-rendersizehint.https.txt
index bb840675f35..a66d19c9c81 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-scriptprocessornode-interface/scriptprocessor-rendersizehint.https.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-scriptprocessornode-interface/scriptprocessor-rendersizehint.https.txt
@@ -2,9 +2,9 @@ Harness status: OK
Found 5 tests
-5 Fail
-Fail ScriptProcessor handles block size with renderSizeHint 1 & bufferSize 256
-Fail ScriptProcessor handles block size with renderSizeHint 256 & bufferSize 256
-Fail ScriptProcessor handles block size with renderSizeHint 100 & bufferSize 256
-Fail ScriptProcessor handles block size with renderSizeHint 4096 & bufferSize 4096
-Fail ScriptProcessor handles block size with renderSizeHint 66000 & bufferSize 16384
\ No newline at end of file
+5 Pass
+Pass ScriptProcessor handles block size with renderSizeHint 1 & bufferSize 256
+Pass ScriptProcessor handles block size with renderSizeHint 256 & bufferSize 256
+Pass ScriptProcessor handles block size with renderSizeHint 100 & bufferSize 256
+Pass ScriptProcessor handles block size with renderSizeHint 4096 & bufferSize 4096
+Pass ScriptProcessor handles block size with renderSizeHint 66000 & bufferSize 16384
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-scriptprocessornode-interface/simple-input-output.txt b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-scriptprocessornode-interface/simple-input-output.txt
index 5c3cd4acb4f..b612e1271a3 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-scriptprocessornode-interface/simple-input-output.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/webaudio/the-audio-api/the-scriptprocessornode-interface/simple-input-output.txt
@@ -2,5 +2,5 @@ Harness status: OK
Found 1 tests
-1 Fail
-Fail ScriptProcessor with stopped input source
\ No newline at end of file
+1 Pass
+Pass ScriptProcessor with stopped input source
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/WebAudio/ScriptProcessorNode-connections.html b/Tests/LibWeb/Text/input/WebAudio/ScriptProcessorNode-connections.html
new file mode 100644
index 00000000000..9e2486aa777
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebAudio/ScriptProcessorNode-connections.html
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const context = new OfflineAudioContext(1, 4096, 44100);
+ const counts = {};
+ const createCountingNode = name => {
+ counts[name] = 0;
+ const node = context.createScriptProcessor(256, 1, 1);
+ node.onaudioprocess = () => ++counts[name];
+ return node;
+ };
+
+ const neverConnected = createCountingNode("never connected");
+
+ const outputConnected = createCountingNode("output connected");
+ outputConnected.connect(context.destination);
+
+ const inputConnected = createCountingNode("input connected");
+ const source = new ConstantSourceNode(context);
+ source.connect(inputConnected);
+ source.start();
+
+ const disconnectedInHandler = createCountingNode("disconnected in its first handler");
+ disconnectedInHandler.connect(context.destination);
+ disconnectedInHandler.addEventListener("audioprocess", () => disconnectedInHandler.disconnect());
+
+ await context.startRendering();
+ for (const [name, count] of Object.entries(counts))
+ println(`audioprocess events for the node ${name}: ${count}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/WebAudio/ScriptProcessorNode-lifetime.html b/Tests/LibWeb/Text/input/WebAudio/ScriptProcessorNode-lifetime.html
new file mode 100644
index 00000000000..a183b90ce32
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebAudio/ScriptProcessorNode-lifetime.html
@@ -0,0 +1,33 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const context = new OfflineAudioContext(1, 4096, 44100);
+
+ const generator = new WeakRef((() => {
+ const node = context.createScriptProcessor(256, 0, 1);
+ node.onaudioprocess = event => event.outputBuffer.getChannelData(0).fill(1);
+ node.connect(context.destination);
+ return node;
+ })());
+
+ const withoutListener = new WeakRef((() => {
+ const node = context.createScriptProcessor(256, 0, 1);
+ node.connect(context.destination);
+ return node;
+ })());
+
+ await internals.gcAsync();
+ await internals.gcAsync();
+ println(`generator with an audioprocess listener is kept alive: ${generator.deref() !== undefined}`);
+ println(`node without an audioprocess listener is collected: ${withoutListener.deref() === undefined}`);
+
+ const buffer = await context.startRendering();
+ println(`generator output reaches the destination: ${buffer.getChannelData(0)[4095] === 1}`);
+
+ await internals.gcAsync();
+ await internals.gcAsync();
+ println(`generator is collected once its context is closed: ${generator.deref() === undefined}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/WebAudio/ScriptProcessorNode-outputBuffer-acquire.html b/Tests/LibWeb/Text/input/WebAudio/ScriptProcessorNode-outputBuffer-acquire.html
new file mode 100644
index 00000000000..0910aad44ad
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebAudio/ScriptProcessorNode-outputBuffer-acquire.html
@@ -0,0 +1,30 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const context = new OfflineAudioContext(1, 1536, 44100);
+ const node = context.createScriptProcessor(256, 0, 1);
+ node.connect(context.destination);
+
+ let eventIndex = 0;
+ let retainedOutput = null;
+ node.onaudioprocess = event => {
+ if (retainedOutput)
+ println(`event ${eventIndex}: output array retained from the previous event is detached: ${retainedOutput.length === 0}`);
+
+ const output = event.outputBuffer.getChannelData(0);
+ output.fill(eventIndex + 1);
+ retainedOutput = output;
+ if (eventIndex === 2) {
+ structuredClone(output.buffer, { transfer: [output.buffer] });
+ println(`event ${eventIndex}: detached its output array`);
+ }
+ ++eventIndex;
+ };
+
+ const rendered = (await context.startRendering()).getChannelData(0);
+ for (let block = 0; block < 6; ++block)
+ println(`block ${block} plays ${rendered[block * 256]}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-analysernode-interface/test-analyser-minimum.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-analysernode-interface/test-analyser-minimum.html
new file mode 100644
index 00000000000..2db1ac62a92
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-analysernode-interface/test-analyser-minimum.html
@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>Test AnalyserNode when the input is silent</title>
+ <meta name="timeout" content="long">
+ <script src="../../../resources/testharness.js"></script>
+ <script src="../../../resources/testharnessreport.js"></script>
+ <script>
+ setup({ single_test: true });
+ var ac = new AudioContext();
+ var analyser = ac.createAnalyser();
+ var constant = ac.createConstantSource();
+ var sp = ac.createScriptProcessor(2048, 1, 1);
+
+ constant.offset.value = 0.0;
+
+ constant.connect(analyser).connect(ac.destination);
+
+ constant.connect(sp).connect(ac.destination);
+
+ var buf = new Float32Array(analyser.frequencyBinCount);
+ var iteration_count = 10;
+ sp.onaudioprocess = function() {
+ analyser.getFloatFrequencyData(buf);
+ var correct = true;
+ for (var i = 0; i < buf.length; i++) {
+ correct &= buf[i] == -Infinity;
+ }
+ assert_true(!!correct, "silent input process -Infinity in decibel bins");
+ if (!iteration_count--) {
+ sp.onaudioprocess = null;
+ constant.stop();
+ ac.close();
+ done();
+ }
+ };
+
+ constant.start();
+ </script>
+</head>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-convolvernode-interface/realtime-conv.html b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-convolvernode-interface/realtime-conv.html
new file mode 100644
index 00000000000..5475dabdb14
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/webaudio/the-audio-api/the-convolvernode-interface/realtime-conv.html
@@ -0,0 +1,144 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>
+ Test Convolver on Real-time Context
+ </title>
+ <script src="../../../resources/testharness.js"></script>
+ <script src="../../../resources/testharnessreport.js"></script>
+ <script src="../../../webaudio/resources/convolution-testing.js"></script>
+ </head>
+ <body>
+ <script>
+ // Choose a length that is large enough to cause multiple threads to be
+ // used in the convolver. For browsers that don't support this, this value
+ // doesn't matter.
+ const pulseLength = 16384;
+
+ // The computed SNR should be at least this large. This value depends on
+ // the platform and browser. Don't set this value to be too much lower
+ // than this. It probably indicates a fairly inaccurate convolver or
+ // ConstantSourceNode automations that should be fixed instead.
+ //
+ // Any major change of operating system or CPU architecture might affect
+ // this value significantly. See: https://crbug.com/1339291
+ const minRequiredSNR = 68.40;
+
+ // To test the real-time convolver, we convolve two square pulses
+ // together to produce a triangular pulse. To verify the result
+ // is correct we compare it against a ConstantSourceNode
+ // configured to generate the expected ramp.
+ promise_test(t => new Promise(resolve => {
+ // Use a power of two for the sample-rate to eliminate
+ // round-off in computing times from frames.
+ const context = new AudioContext({sampleRate: 16384});
+
+ // Square pulse for the ConvolverNode impulse response.
+ const squarePulse = new AudioBuffer(
+ {length: pulseLength, sampleRate: context.sampleRate});
+ squarePulse.getChannelData(0).fill(1);
+
+ const convolver = new ConvolverNode(
+ context, {buffer: squarePulse, disableNormalization: true});
+
+ // Square pulse for testing.
+ const srcSquare = new ConstantSourceNode(context, {offset: 0});
+ srcSquare.connect(convolver);
+
+ // Reference ramp. Automations on this ConstantSourceNode will
+ // generate the desired ramp.
+ const srcRamp = new ConstantSourceNode(context, {offset: 0});
+
+ // Use these GainNodes to compute the difference between the convolver
+ // output and the expected ramp to create the error signal.
+ const inverter = new GainNode(context, {gain: -1});
+ const sum = new GainNode(context, {gain: 1});
+ convolver.connect(sum);
+ srcRamp.connect(inverter).connect(sum);
+
+ // Square the error signal using this GainNode.
+ const squarer = new GainNode(context, {gain: 0});
+ sum.connect(squarer);
+ sum.connect(squarer.gain);
+
+ // Merge the error signal and the square source so we can integrate
+ // the error signal to find an SNR.
+ const merger = new ChannelMergerNode(context, {numberOfInputs: 2});
+ squarer.connect(merger, 0, 0);
+ srcSquare.connect(merger, 0, 1);
+
+ // For simplicity, use a ScriptProcessor to integrate the error
+ // signal. The square pulse signal is used as a gate over which the
+ // integration is done. When the pulse ends, the SNR is computed and
+ // the test ends.
+
+ // |doSum| is used to determine when to integrate and when it becomes
+ // false, it signals the end of integration.
+ let doSum = false;
+
+ // |signalSum| is the energy in the square pulse. |errorSum| is the
+ // energy in the error signal.
+ let signalSum = 0;
+ let errorSum = 0;
+
+ const spn = context.createScriptProcessor(0, 2, 1);
+ spn.onaudioprocess = event => {
+ // Sum the values on the first channel when the second channel is
+ // not zero. When the second channel goes from non-zero to 0,
+ // dump the value out and terminate the test.
+ const c0 = event.inputBuffer.getChannelData(0);
+ const c1 = event.inputBuffer.getChannelData(1);
+
+ for (let k = 0; k < c1.length; ++k) {
+ if (c1[k] === 0) {
+ if (doSum) {
+ doSum = false;
+ // Square wave is now silent and we were integrating, so we
+ // can stop now and verify the SNR.
+ const snr = 10 * Math.log10(signalSum / errorSum);
+ t.step(() =>
+ assert_greater_than_equal(snr, minRequiredSNR, 'SNR')
+ );
+ spn.onaudioprocess = null;
+ context.close().then(resolve);
+ }
+ } else {
+ // Signal is non-zero so sum up the values.
+ doSum = true;
+ errorSum += c0[k];
+ signalSum += c1[k] * c1[k];
+ }
+ }
+ };
+
+ merger.connect(spn).connect(context.destination);
+
+ // Schedule everything to start a bit in the future from now, and end
+ // |pulseLength| frames later.
+ const now = context.currentTime;
+
+ // |startFrame| is the number of frames to schedule ahead for testing.
+ const startFrame = 512;
+ const startTime = startFrame / context.sampleRate;
+ const pulseDuration = pulseLength / context.sampleRate;
+
+ // Create a square pulse in the ConstantSourceNode.
+ srcSquare.offset.setValueAtTime(1, now + startTime);
+ srcSquare.offset.setValueAtTime(0, now + startTime + pulseDuration);
+
+ // Create the reference ramp.
+ srcRamp.offset.setValueAtTime(1, now + startTime);
+ srcRamp.offset.linearRampToValueAtTime(
+ pulseLength,
+ now + startTime + pulseDuration - 1 / context.sampleRate);
+ srcRamp.offset.linearRampToValueAtTime(
+ 0,
+ now + startTime + 2 * pulseDuration - 1 / context.sampleRate);
+
+ // Start the ramps!
+ srcRamp.start();
+ srcSquare.start();
+ }), 'Test convolver with real-time context');
+ </script>
+ </body>
+</html>