audio-nodes
Skill864 starsChanged 7 days agoMITView on GitHub
C++ audio node engine for react-native-audio-api. Covers the AudioNode class hierarchy, the processNode() audio-thread contract (no allocs, no locks, no blocking I/O), AudioParam a-rate/k-rate processing, cross-thread communication patterns (CrossThreadEventScheduler, IAudioEventHandlerRegistry), and a step-by-step checklist for implementing a new node end-to-end. Use this skill when implementing a new Web Audio API node, modifying audio graph traversal or processing logic, or debugging audio rendering artifacts. Trigger phrases: "add a new node", "implement AudioNode", "processNode", "audio thread", "AudioParam automation".
In this repository13 other files it gives its agents.
- apps/CLAUDE.mdCLAUDE.md
- CLAUDE.mdCLAUDE.md
- .cursor/rules/expressive-code.mdcCursor rule
- build-compilation-dependenciesSkill
- expressive-codeSkill
- flowSkill
- host-objectsSkill
- post-work-checksSkill
- thread-safety-itcSkill
- turbo-modulesSkill
- utilitiesSkill
- web-audio-apiSkill
- writing-skillsSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
22 rules. About 0 are common, 3 are distinctive, and 19 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
19
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 66
Call into JavaScript — no JSI calls, no callInvoker_->invokeSync()
- Very specific: line 111
End-of-quantum demotion: after processInputs(), each node that was CONDITIONAL_PROCESSABLE flips back to NOT_PROCESSABLE in …
- Very specific: line 218
When the node finishes, AudioScheduledSourceNode::disable() fires ENDED through its EventCaller (dispatchEmptyFromAudioThread).
- Very specific: line 282
Every automatable property (frequency, gain, detune, Q, etc.) is an AudioParam.
- Very specific: line 390
Use CrossThreadEventScheduler (lock-free SPSC queue).
- Very specific: line 394
Use IAudioEventHandlerRegistry::invokeHandlerWithEventBody() which internally calls callInvoker_->invokeAsync() — this safely schedules the …
- Very specific: line 406
All graph mutations are queued via AudioGraphManager using its own SPSC channel (addPendingNodeConnection, addPendingParamConnection).
- Very specific: line 421
Read the emitted width from getOutputChannelNumber() on any thread.
- Very specific: line 429
Do not gate GraphObject::process() on isProcessable() of inputs: CONDITIONAL nodes demote themselves to NOT_PROCESSABLE at the end of their …
- Very specific: line 452
Call AudioNode(context, options) base constructor with correct numberOfInputs, numberOfOutputs
- Very specific: line 453
Create all AudioParam instances with correct default/min/max values from the Web Audio spec
- Very specific: line 455
Do NOT call context_->... in processNode() for anything that could block
- Very specific: line 458
Call context_.lock() to get a shared_ptr<BaseAudioContext> — return early if null
- Very specific: line 459
Call context->getCurrentTime() for automation timing
- Very specific: line 460
Use processARateParam() or processKRateParam() to read param values
- Distinctive: line 462
No allocations, no locks, no blocking I/O
- Very specific: line 465
Create MyNodeHostObject extending AudioNodeHostObject
- Very specific: line 466
Add factory method to BaseAudioContextHostObject (createMyNode)
- Very specific: line 467
Add factory method to BaseAudioContext C++ class
- Very specific: line 470
Add TS class in src/core/
- Distinctive: line 474
Check the Web Audio API spec for default values, parameter ranges, and behavior
- Distinctive: line 485
All node behavior (parameter names, default values, valid ranges, processing semantics) must match the spec:
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Skill: AudioNodes
Golden references: GainNode.h/.cpp (effect node), OscillatorNode.h/.cpp (scheduled source). Mirror their structure for any new node. See gainnode-example.md for an annotated header + .cpp.
If spec defaults or parameter ranges are unclear → fetch https://webaudio.github.io/web-audio-api/ before writing any constructor code.
Directory Structure
common/cpp/audioapi/core/
├── AudioNode.h / .cpp # Base class for all nodes
├── AudioParam.h / .cpp # Automatable parameter
├── BaseAudioContext.h / .cpp # Engine + node factory
├── AudioContext.h / .cpp # Real-time context
├── OfflineAudioContext.h / .cpp # Offline rendering context
├── sources/
│ ├── AudioScheduledSourceNode.h # Base for start/stop sources (INTERNAL)
│ ├── AudioBufferBaseSourceNode.h # Base for buffer playback (INTERNAL)
│ ├── OscillatorNode.h / .cpp
│ ├── AudioBufferSourceNode.h / .cpp
│ ├── AudioBufferQueueSourceNode.h / .cpp
│ ├── ConstantSourceNode.h / .cpp
│ ├── WorkletSourceNode.h / .cpp
│ └── RecorderAdapterNode.h / .cpp
├── effects/
│ ├── GainNode.h / .cpp
│ ├── BiquadFilterNode.h / .cpp
│ ├── DelayNode.h / .cpp
│ ├── IIRFilterNode.h / .cpp
│ ├── StereoPannerNode.h / .cpp
│ ├── WaveShaperNode.h / .cpp
│ ├── ConvolverNode.h / .cpp
│ ├── WorkletNode.h / .cpp
│ ├── channel_merger/ # ChannelMerger internal input/output nodes (composite)
│ ├── channel_splitter/ # ChannelSplitter internal input/output nodes (composite)
│ └── PeriodicWave.h / .cpp # Wave table (not a node)
├── analysis/
│ └── AnalyserNode.h / .cpp
├── destinations/
│ └── AudioDestinationNode.h / .cpp
├── inputs/
│ └── AudioRecorder.h / .cpp
└── utils/
└── AudioGraphManager.h / .cppThe Audio Thread Contract
processNode() runs on the audio thread — the real-time rendering thread driven by the native audio driver (Oboe on Android, CoreAudio on iOS). This thread has strict requirements:
MUST NOT in processNode():
- Allocate or free memory (
new,delete,malloc,free,std::vector::push_backthat grows, etc.) - Acquire any mutex or lock (
std::mutex,std::lock_guard, etc.) - Make any blocking syscall (file I/O, socket,
sleep,wait) - Call into JavaScript — no JSI calls, no
callInvoker_->invokeSync() - Throw exceptions (or rely on exception unwinding paths that allocate)
Preallocate everything in the constructor:
// Constructor — JS thread, allocations OK
GainNode::GainNode(const std::shared_ptr<BaseAudioContext> &context, const GainOptions &options)
: AudioNode(context, options) {
// Preallocate the AudioBuffer used during processing
audioBuffer_ = std::make_shared<AudioBuffer>(channelCount_, context->getBufferSize());
// Preallocate params — they own their internal AudioBuffer too
gainParam_ = std::make_shared<AudioParam>(
options.gain, -3.4028234663852886e+38f, 3.4028234663852886e+38f, context);
}
// processNode — audio thread, NO allocations
std::shared_ptr<AudioBuffer> GainNode::processNode(
const std::shared_ptr<AudioBuffer> &processingBuffer,
int framesToProcess) {
// Already-allocated buffer reused each render quantum
auto gainValues = gainParam_->processARateParam(framesToProcess, time);
for (size_t i = 0; i < processingBuffer->getNumberOfChannels(); i++) {
processingBuffer->getChannel(i)->multiply(*gainValues->getChannel(0), framesToProcess);
}
return processingBuffer;
}Processable State (seed-driven dependency pull)
Which nodes run each render quantum is decided by AudioGraph::settleProcessableState(), run inside Graph::process() after toposort/compaction and before the forward iter() pass. It is an audio-thread-only concern — never derived from HostGraph adjacency (that mutates on the JS thread under nodesMutex_).
GraphObject::PROCESSABLE_STATE:
ALWAYS_PROCESSABLE— seed / pull root. Set in ctors ofAudioDestinationNodeandAnalyserNode. Never reset by settle.CONDITIONAL_PROCESSABLE— on this quantum because something processable downstream pulls it. Recomputed from scratch every quantum.NOT_PROCESSABLE— idle / disconnected / default.
Settle algorithm (allocation-free):
- Dependency pull: depth-first from every
ALWAYS_/CONDITIONAL_PROCESSABLEseed, mark each dependency (audio inputs and processable-links alike)CONDITIONAL_PROCESSABLEand continue from it. Usestarget_placeas an embedded stack and the state as the visited marker, so it is a single O(V+E) pass independent of array order. - End-of-quantum demotion: after
processInputs(), each node that wasCONDITIONAL_PROCESSABLEflips back toNOT_PROCESSABLEinGraphObject::process(). That replaces a global reset at the start of settle — nodes that ran last quantum are already idle when the next pull begins.
Key invariants:
- Pull from
processableState_, neverAudioNode::isProcessable(). A tail-bearing node (Delay/Convolver/Biquad) overridesisProcessable()to staytruewhile its tail drains after a disconnect; using that for the pull would wrongly re-activate its whole upstream cone. The tail node stays scheduled via that override; itsprocessableState_isNOT_PROCESSABLE, so it correctly does not pull upstream. disable()is sticky.AudioNode::disable()setsNOT_PROCESSABLEandalwaysNotProcessable_ = true, so a finished source still wired to a live consumer is not re-activated by the every-quantum pull. Sources calldisable()from the audio thread when playback finishes.- DelayReader → DelayWriter have no audio edge (they share a ring buffer).
Graph::linkNodes(reader, writer)records a processable-link, mirrored ontoAudioGraph::Vertex::link_head. Settle follows links so pulling the reader also pulls the writer and the writer's inputs. Links are NOT part of the topological sort (that would create a cycle for feedback delays). Consequently a link target can sit at a HIGHER index than its holder (the writer is an audio sink, so it sorts last), and settle must be order-independent: a seed-driven DFS on an embedded stack, never a single right-to-left sweep. A sweep marks the writer but never revisits it to pull its inputs, so the source feeding a DelayNode stops rendering (SettleLinkTest.LinkTargetSortedAfterHolderStillPullsItsInputsguards this).
Class Hierarchy
classDiagram
direction TD
class AudioScheduledSourceNode {
<<internal base>>
start(when)
stop(when)
}
class AudioBufferBaseSourceNode {
<<internal base>>
playbackRate AudioParam
detune AudioParam
}
AudioNode <|-- AudioScheduledSourceNode
AudioNode <|-- GainNode
AudioNode <|-- BiquadFilterNode
AudioNode <|-- DelayNode
AudioNode <|-- IIRFilterNode
AudioNode <|-- StereoPannerNode
AudioNode <|-- WaveShaperNode
AudioNode <|-- ConvolverNode
AudioNode <|-- WorkletNode
AudioNode <|-- AnalyserNode
AudioNode <|-- AudioDestinationNode
AudioScheduledSourceNode <|-- AudioBufferBaseSourceNode
AudioScheduledSourceNode <|-- OscillatorNode
AudioScheduledSourceNode <|-- ConstantSourceNode
AudioScheduledSourceNode <|-- WorkletSourceNode
AudioBufferBaseSourceNode <|-- AudioBufferSourceNode
AudioBufferBaseSourceNode <|-- AudioBufferQueueSourceNodeAudioRecorder (not an AudioNode)
core/inputs/AudioRecorder is a standalone base class, not part of the AudioNode hierarchy — it
feeds the graph through a RecorderAdapterNode instead of being processed by it.
The split between it and IOSAudioRecorder / AndroidAudioRecorder is: the base owns everything
that happens to recorded frames (file writer, JS callback, adapter node — enableFileOutput,
prepareFileWriter, setOnAudioReadyCallback, connect, detachSideEffects/finalizeSideEffects), the
subclasses own only the platform input stream. Each output is one OutputSlot (file_, callback_,
adapter_: state, mutex, target); a subclass locks the slot mutexes and calls the base, and never
reads or writes a slot's state or target itself. A platform start() prepares the outputs only
through prepareOutputs(), and when anything fails after that it ends like stop(): detach under
the slot mutexes, finalize without them, so no file stays open. detachSideEffects() moves the file
writer out (a new one each session) but copies the callback and the adapter handle, which stay
registered: JS connect() creates its adapter once, so moving the handle out made every later
start() fail with "Recorder adapter node is unavailable.". The one thing the base needs from the platform is
resolveStreamFormat(), returning sample rate, channel count and max frames per buffer; iOS reads
it from NativeAudioRecorder on every call (a route change invalidates it), Android returns values
cached when the Oboe stream opened. Add shared recorder behavior to the base, not to one platform;
state only one platform touches (Android's streamMutex_, iOS's inputChannelCount_) lives in
that subclass. State a consumer already owns stays with the consumer: the adapter node's ring
layout (RecorderAdapterNode::writeFrames) and the session's file paths (returned by
AudioFileWriter::closeFile()) are not mirrored in the recorder.
Pitfall: never redeclare a base member (streamSampleRate_, file_,
lastCallbackFrameCount_) in a platform recorder. The shadowing copy compiles fine, but the base's
audio-thread fan-out reads its own member and silently drops that output.
AudioScheduledSourceNode (internal only — not exposed to JS directly)
Base class for source nodes that have a scheduled start and stop time. Not instantiated directly.
// Playback state machine
enum class PlaybackState {
UNSCHEDULED, // before start() called
SCHEDULED, // start() called, waiting for startTime_
PLAYING, // actively producing audio
PAUSED, // silent, position kept; stopTime_ still applies
STOP_SCHEDULED, // stop() called, waiting for stopTime_
FINISHED // done, node will be disabled
};Pausing is a state, not a stop. pause() / resume(when) move a node into and out of PAUSED. Only the HostObjects of sources that offer pausing call them: AudioBufferQueueSourceNodeHostObject maps its JS pause / resume straight onto them, with no forwarding methods on the node. Never fake a pause with stop(0), UNSCHEDULED, or a side flag: stop() on a started node takes the stop-before-start branch, whose AudioNode::disable() excludes the node from the pull for good, so a later resume renders silence (the 1.0.0 queue-source bug). The rules PAUSED carries:
stopTime_is an absolute context time and survives a pause.updatePlaybackInfofinishes a paused node in the quantum holding its stop time;resume(when)keeps the node paused when the stop time is not afterwhen.stop(when)while paused only recordsstopTime_(there is no start to compare against).canBeDestructed()is true while paused: only the JS handle can resume the node.AudioFileSourceNoderesumes throughstart()(its JSplay()), notresume(): the basestart()keepsstopTime_, and a stop time already passed ends the node a quantum later without audio.MediaElementAudioSourceNodeis a plain one-input pass-through: an<Audio>tag's file source reaches it through an ordinary graph edge, so lifetime and silence follow the normal graph rules (a node is removed only when its inputs go too). Do not give it a pointer to the file source or a side channel to pull from: the earlier design did (rawAudioFileSourceNode *, a binding id, acanBeDestructed()override tied to the source's pause state), and it crashed on the audio thread once the graph freed the file source first, left the media node in the graph forever after a play-to-end, and lost the route on the replacement source<Audio>spawns after every playthrough. The route lives in JS:useAudioSourceLoaderkeeps the tag's output (mediaElementSourceRef) and hands it to every file source it spawns (AudioFileSourceNode.setOutput); the TSMediaElementAudioSourceNodetakes the tag over in its constructor for good. That matches the spec ("the rendered audio will no longer be heard directly", from creation, not fromconnect()) and Chrome, which also throwsInvalidStateErrorfor a second node on the same element, even after the first is disconnected or its context closed — the spec itself does not require that error.- A paused source must still reach
updatePlaybackInfoeach quantum. An early return for "paused" ahead of it (the oldfilePaused_check inrenderPreflight) hides a stop time from the render path while the node stays connected.
hasEnded() is the one piece of this state readable off the audio thread (an atomic set before ENDED is dispatched, exposed as the hasEnded HostObject getter). JS wrappers that guard calls by state keep the transitions they request themselves, because native applies start/pause/resume a quantum after the call, and read only the ending from native.
Subclasses call updatePlaybackInfo(currentTime, framesToProcess) at the top of processNode() to transition the state machine and handle sample-accurate start/stop.
When the node finishes, AudioScheduledSourceNode::disable() fires ENDED through its EventCaller (dispatchEmptyFromAudioThread); a node that will never render (stop-before-start) defers it with EventCaller::deferEmpty instead — see thread-safety-itc.
A source only advances its state machine while it is being pulled. Once disconnected (no processable consumer) it is skipped by iter(), so a stop frame that has not rendered yet would never be observed and the node would stay PLAYING, never fire ended and never satisfy canBeDestructed() — the graph then keeps it forever (stretcher queues, params, scratch buffers). GraphObject::advanceWithoutRender(currentSampleFrame) closes that gap: Graph::advanceUnpulledNodes calls it each quantum for every node left out of the processable set, and AudioScheduledSourceNode overrides it to finish once the stop frame is strictly before the quantum (same transition as the render path's "first silent quantum" branch; Chromium does the same in AudioScheduledSourceHandler::HandleStoppableSourceNode). Keep the render path authoritative: the graph never calls this hook on a pulled node. The one caller besides the graph is AudioBufferBaseSourceNode::processNode, for a pulled source with nothing to render (empty queue): it returns before updatePlaybackInfo, so without the call a stop time would never be reached. A disconnected source that was never stopped still has no stop frame and stays alive until stop() or the JS wrapper dies.
Pitfalls:
start(double)in this base class is a separate overload fromAudioBufferSourceNode::start(when, offset, duration). Callingnode->start(when)on an ABSN skips the derived logic; the HostObject always passes three arguments, and so must tests.stop()on aFINISHEDnode is ignored. JS does not guard a repeatedstop(), and honouring it would take the stop-before-start branch again and fire a secondended.AudioBufferBaseSourceNode::processNodeisfinaland returns early onisEmpty(). Whether a started-but-empty source ends there (endedfires) isendsWhenStartedEmpty(): the base default is true (spec: a null buffer forcesstop = currentTime);AudioBufferQueueSourceNodeoverrides it to false because an empty queue is waiting for the next enqueue. The check runs per quantum on the audio thread on purpose, because the buffer setter legitimately acquires content assigned afterstart()but before the first render.
processNode() Signature
protected:
/// @note Audio Thread only
virtual std::shared_ptr<AudioBuffer> processNode(
const std::shared_ptr<AudioBuffer> &processingBuffer,
int framesToProcess) = 0;processingBuffer— already contains the mixed input from all connected input nodes. Modify in-place and return it.framesToProcess— number of samples per channel to process, typically 128 (RENDER_QUANTUM_SIZE).- Called by
AudioNode::processAudio()which handles input mixing, channel count modes, and deduplication (vialastRenderedFrame_).
Thread Annotations in Header Files
Annotate every method with the thread it is safe to call from. Use comments in the header:
class MyNode : public AudioNode {
public:
/// @note JS Thread only
void setSomething(float value);
float getSomething() const;
protected:
/// @note Audio Thread only
std::shared_ptr<AudioBuffer> processNode(
const std::shared_ptr<AudioBuffer> &processingBuffer,
int framesToProcess) override;
};In AudioParam.h the pattern is:
/// @note JS Thread only
[[nodiscard]] inline float getValue() const noexcept { ... }
void setValue(float value);
void setValueAtTime(float value, double startTime);
/// Audio-Thread only methods (idempotent per quantum — see below)
std::shared_ptr<DSPAudioBuffer> processARateParam(int framesToProcess, double time);
float processKRateParam(double time); // k-rate is quantum-wideAudioParam — Automatable Parameters
Every automatable property (frequency, gain, detune, Q, etc.) is an AudioParam.
gainParam_ = std::make_shared<AudioParam>(
defaultValue,
minValue,
maxValue,
context
);A-rate vs K-rate
A-rate (audio-rate): one value per sample — use when the parameter can change significantly within a render quantum (e.g. frequency modulation)
// Call processARateParam() for per-sample values — returns AudioBuffer, no allocation auto gainValues = gainParam_->processARateParam(framesToProcess, time); float *values = gainValues->getChannel(0)->getData(); // values[i] is the gain for frame i- K-rate (control-rate): one value per render quantum — use when the parameter changes slowly
// Call processKRateParam() for a single quantum-wide value float gain = gainParam_->processKRateParam(time); // Single value for the whole block
Param class hierarchy & idempotency
AudioParam and CompositeAudioParam<CombineFunction> both derive from the abstract
GeneralizedAudioParam base (core/GeneralizedAudioParam.h), which owns the nominal
range, the a-rate outputBuffer_, and the per-quantum memoization state, and centralizes
clamping via finalizeKRate / finalizeARate.
AudioParam— the only JS-connectable param; ownsinputBuffer_(BridgeNode modulation).CompositeAudioParam<Fn>(core/CompositeAudioParam.hpp) — represents a speccomputedValue(e.g.computedOscFrequency).Fnis a pure, captureless free function (defined in the owning node's header, next to the composite member) taking float children and returning float; its arity is deduced. It processes each child, foldsFnover them, and clamps to its own nominal range. NoinputBuffer_.
processKRateParam(time) / processARateParam(frames, time) are idempotent: a repeat
call with the same arguments returns the cached result and does not re-consume modulation.
This is why a composite and a node can both read the same child param in one quantum. It also
means processNode() should read context->getCurrentTime() once and thread that same
double into every param call so the cache keys match (the context clock is constant within a
quantum). Consequently, unit tests that re-process the same node must advance the clock (e.g.
context->processGraph(buffer.get(), frames)) between renders.
Clamping (§ 1.6.3): automation intrinsic values are computed without clamping (see
getValueAtTimeUnmodulated / ParamRenderQueue). Clip only in finalizeKRate /
finalizeARate after adding modulation — never on the intrinsic alone before modulation.
Automation timing model (scheduled times, snapped on demand): a RenderParamEvent stores
only its scheduled startTime/endTime, and calculateValueAtTime interpolates on them unmodified
(the spec defines the formulas on real times; a ramp between two times inside one frame must still
interpolate on those times — WPT audioparam-close.html). Effect boundaries live on the frame grid
instead: ParamRenderQueue::computeValueAtTime calls snapToSampleFrameTime
(std::round(t * sampleRate) / sampleRate) on the scheduled times whenever it decides which event
is in effect, matching Blink and the WPT reference's timeToSampleFrame. Nothing stores the
snapped values, so resolving neighbours (resolveEventValues, cancelAndHoldAtTime) only ever
touches the scheduled times. A queued event supersedes the current one as soon as its snapped
start is due, even mid-ramp; ramps stay active until their scheduled end, other finite events end
on their snapped end. On the evaluation side, processARateParam derives each sample's time as
(quantumStartFrame + i) / sampleRate — never accumulate time += 1/sampleRate, the ULP drift
lands boundaries one frame late.
Never snap an automation time through an integer type. snapToSampleFrameTime rounds in
double instead of reusing dsp::timeToSampleFrame, which returns a frame index as size_t.
Automation times are unvalidated user input: nothing in AudioParam or its host object rejects
negative or absurd values, and WPT schedules ramps at 1e300 (audioparam-large-endtime.html).
A double → size_t → int round trip on that is undefined behaviour, and in practice produced a
small negative time that sorted the event ahead of everything legitimately scheduled. The same
unguarded cast is still reachable from AudioScheduledSourceNode's startTime_/stopTime_
conversions.
Param queue capacity: both param event queues (ParamRenderQueue on AudioParam,
ParamControlQueue on the host object) are bounded by AUDIO_PARAM_MAX_QUEUED_EVENTS and
silently drop events past capacity (BoundedPriorityQueue::push returns false, nobody
checks). Automation scheduled far ahead must fit entirely; the WPT audioparam suites queue
100 events per file. Symptom of overflow: automation freezes at the last accepted event.
JS → Audio Thread parameter updates
CrossThreadEventScheduler<T> is a lock-free SPSC channel. When JS calls param.setValueAtTime(...), it enqueues a lambda on the scheduler. The audio thread drains the queue at the start of each processARateParam / processKRateParam call.
// JS-thread (in AudioParam):
void AudioParam::setValueAtTime(float value, double startTime) {
eventScheduler_.scheduleEvent([value, startTime](AudioParam ¶m) {
param.eventsQueue_.insertEvent(...);
});
}
// Audio-thread (inside processARateParam):
eventScheduler_.processAllEvents(*this); // drain all pending eventsImportant: HostObject setters forward to the node/param asynchronously through this scheduler. By the time processNode() runs, the queued update may or may not have been applied yet, depending on timing. Design accordingly — never assume immediate consistency.
Cross-Thread Communication Patterns
JS → Audio (parameter/graph updates)
Use CrossThreadEventScheduler (lock-free SPSC queue). See utils/CrossThreadEventScheduler.hpp.
Audio → JS (events like ended, loopEnded, positionChanged)
Use IAudioEventHandlerRegistry::invokeHandlerWithEventBody() which internally calls callInvoker_->invokeAsync() — this safely schedules the JS callback on the JS thread from the audio thread.
// Audio-thread: fire 'ended' event
audioEventHandlerRegistry_->invokeHandlerWithEventBody(
AudioEvent::ENDED, {});Callback IDs are stored as std::atomic<uint64_t> on the node. 0 means no listener registered.
JS → Audio (graph mutations: connect/disconnect)
All graph mutations are queued via AudioGraphManager using its own SPSC channel (addPendingNodeConnection, addPendingParamConnection). The audio thread calls graphManager_->preProcessGraph() before each render pass to apply pending changes.
Settable channel attributes (channelCount / channelCountMode / channelInterpretation)
These are mutable after construction. AudioNode (core) exposes virtual setChannelCount / setChannelCountMode / setChannelInterpretation. channelCount and channelCountMode are read only on the host thread during negotiation, so the JSI setter updates the core field directly then calls HostNode::renegotiate() → Graph::renegotiateNodeChannels() → HostGraph::renegotiateNodeChannels() (reuses collectNegotiations + an AGEvent buffer swap, self-drain aware when there is no audio/render consumer — offline construction/suspend and realtime suspended/stopped windows). When AudioBufferSourceNode setBuffer changes channel width, update outputChannelNumber_ together with the buffer then renegotiate() so MAX/CLAMPED_MAX downstream nodes update; the audio event still installs the prebuilt buffer (no audio-thread alloc). channelInterpretation is read on the audio thread in processInputs (getInputBuffer()->sum(*input, channelInterpretation_)), so it MUST be applied via scheduleAudioEvent, not mutated directly.
Negotiation decides whether to queue a buffer swap by comparing against HostVertex::pendingChannelCount (the width of the last swap queued, seeded in HostGraph::addNode), never against the live getNegotiatedBuffer(). On a running context every event queued in one JS task lands in the same render quantum, so the live buffer has not seen earlier swaps from the batch yet: a node going 2 → 1 → 2 would see the live 2, skip the second swap, and keep the queued 1 (issue #1332, e.g. source.connect(gain); source.buffer = stereo;). The width a node presents to its consumers is derived on demand as getOutputChannelNumber().value_or(pendingChannelCount); it is not cached per pass, so a negotiation pass only walks upstream (outputs) from the changed nodes — inputs outside that walk are already current. Inputs inside it are not: in a triangle (A → C, A → B → C) the walk can reach C before B, so collectNegotiations first collects the walked nodes in post-order (collectAffectedPostOrder) and computes them in reverse, which is topological — every node after each input the same pass renegotiates (GraphTest.RenegotiateNode_TriangleReadsSiblingAfterItNarrows). Never compute a node while walking. A source (getNumberOfInputs() == 0, ownsOutputBuffer) is never given a buffer by the graph: it swaps audioBuffer_ itself, in the same audio event as the content that defines its width, so the two can never disagree on the audio thread. A pass never reaches a source: connect() rejects it as a destination (HostGraph::addEdge asserts this — it has no guard of its own, so C++ tests calling it raw must respect it too) and renegotiateNodeChannels(source) starts the pass at the source's outputs. The same rule applies to any new host-side "is a swap needed?" check.
Output channel number vs channelCount (sources)
channelCount is the spec's input-mixing attribute and never decides how many channels a node emits. AudioNode keeps a separate atomic outputChannelNumber_ (getOutputChannelNumber()), initialised from AudioNodeOptions::outputChannelNumber and falling back to channelCount for nodes whose output follows their negotiated input layout. HostGraph negotiation reads each input's getOutputChannelNumber() and falls back to its pending negotiated width only when that is nullopt (pendingOutputChannelNumber in HostGraph.cpp), so a spec-default channelCount = 2 oscillator still negotiates a mono downstream buffer. Rules:
- A node that always emits one channel (Oscillator, ConstantSource) derives its options from
MonoSourceNodeOptions; do not lowerchannelCountor overridesetChannelCountto fake it. - A source that learns its width later (AudioBufferSource, AudioFileSource, AudioBufferQueueSource, RecorderAdapter) writes
outputChannelNumber_in the same step it swapsaudioBuffer_, neverchannelCount_. - When the host object schedules that swap (AudioBufferSourceNode
setBuffer), it must first callsetOutputChannelNumber()on the host thread andrenegotiate(), otherwise downstream MAX / CLAMPED_MAX nodes negotiate against the stale width until the audio event lands (this broke the StereoPanner WPTstereopannernode-panningtest when it lived onupdateChannelCount). Never route this throughupdateChannelCount: that changes the JS-visiblechannelCountattribute. - Read the emitted width from
getOutputChannelNumber()on any thread; the buffer pointer itself is audio-thread only.
Idle-node stale-buffer zeroing (settleProcessableState)
AudioGraph::iter() filters to isProcessable() nodes, so a node that has gone idle (e.g. a finished source) is skipped and its output buffer is NOT refreshed — it keeps the samples from an earlier quantum. Downstream consumers still read that buffer via getOutput() when collecting inputs, which would re-sum ghost echoes every quantum (this broke the audionode-channel-rules ~170-node WPT test).
Fix: after the dependency pull in AudioGraph::settleProcessableState(), zero the output buffer of every node that is still !isProcessable(). Active CONDITIONAL nodes have already been pulled, so they are left intact; tail-bearing nodes remain isProcessable() while draining and are also left intact.
Do not gate GraphObject::process() on isProcessable() of inputs: CONDITIONAL nodes demote themselves to NOT_PROCESSABLE at the end of their own process() call, before downstream consumers run in the same topological pass — an isProcessable() gate would drop every live conditional input every quantum.
AudioNode::disable() only sets alwaysNotProcessable_ (sticky: settle must not re-activate a finished source). The current quantum's output stays intact for downstream mixing; the next settle zeros the idle buffer. No deferred pendingDisable_ flag is needed once settle performs idle zeroing.
Tail-bearing nodes (Delay/Convolver/Biquad) need no special handling: while connected they stay CONDITIONAL_PROCESSABLE; after disconnect they stay isProcessable() via the tail override until the impulse decays, so settle does not zero them mid-tail.
Implementing a New Node — Checklist
- Subclass the right base
AudioNode— standard effect or analysis nodeAudioScheduledSourceNode— source with start/stop schedulingAudioBufferBaseSourceNode— source that plays back an AudioBuffer with pitch control WithpitchCorrectionthe WSOLA stretcher holds ~30 ms of audio, so the node must outlive its last sample. It does that itself (stretchTailFramesLeft_): once the processor reports the source ran dry it keeps the node playing and feeds the stretcher the zero-filled input untilWsolaTimeStretcher::latencyTailFramesare consumed. Never pad the buffer with silence to get the same effect — that forces a private copy per node and breaks buffer sharing with the JS-facingAudioBuffer.
- Header file (
core/<category>/MyNode.h)- Annotate every method with
/// @note JS Thread onlyor/// @note Audio Thread only - Declare
processNode()inprotected: - Declare
AudioParammembers for automatable properties - Preallocate all buffers you'll need in
private:state
- Annotate every method with
- Constructor (runs on JS thread)
- Call
AudioNode(context, options)base constructor with correctnumberOfInputs,numberOfOutputs - Create all
AudioParaminstances with correct default/min/max values from the Web Audio spec - Preallocate any DSP state buffers (IIR delay lines, ring buffers, etc.)
- Do NOT call
context_->...inprocessNode()for anything that could block
- Call
- processNode() (runs on audio thread)
- Call
context_.lock()to get ashared_ptr<BaseAudioContext>— return early if null - Call
context->getCurrentTime()for automation timing - Use
processARateParam()orprocessKRateParam()to read param values - Process samples in-place on
processingBuffer - No allocations, no locks, no blocking I/O
- Call
- HostObject (see the
host-objectsskill)- Create
MyNodeHostObjectextendingAudioNodeHostObject - Add factory method to
BaseAudioContextHostObject(createMyNode) - Add factory method to
BaseAudioContextC++ class
- Create
- TypeScript API (see the
turbo-modulesskill)- Add TS class in
src/core/ - Export from package index
- Add TS class in
- Spec compliance
- Check the Web Audio API spec for default values, parameter ranges, and behavior
- See
web-audio-apiskill
- Tests and docs — see the
flowskill
See full GainNode example for a complete header + .cpp reference implementation.
Web Audio API Spec Reference
All node behavior (parameter names, default values, valid ranges, processing semantics) must match the spec:
Key spec-defined constraints already encoded in the codebase:
AudioParammin/max values come from spec tablesGainNode.gaindefault = 1.0, no clampingBiquadFilterNode.frequencydefault = 350 Hz, range [Nyquist - epsilon, Nyquist]OscillatorNode.frequencydefault = 440 Hz- Render quantum = 128 frames
Maintenance: see maintenance.md.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

