Skip to content

feat(audio-context): AudioWorkletNode inputs, multiple outputs and offline worklets on Android - #282

Merged
triniwiz merged 7 commits into
masterfrom
feat/android-worklet-io
Nov 24, 2026
Merged

triniwiz merged 7 commits into
masterfrom
feat/android-worklet-io

Conversation

@triniwiz

@triniwiz triniwiz commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

What changes

On Android, AudioWorkletNode was a source only: no inputs, one output, and OfflineAudioContext had no audioWorklet. It now does what iOS does:

  • numberOfInputs ≥ 0 and multiple outputs, each output playing from its own bus (node.connect(dest, output)), up to 16 inputs and 16 outputs of up to 8 channels each.
  • Each input has exactly channelCount channels (as if channelCountMode were 'explicit'), mixed with Web Audio "speakers" rules: mono copies to every channel, a down-mix to mono averages, and there is no equal-power pan. An input with nothing playing into it reports 0 channels.
  • OfflineAudioContext.audioWorklet works. Worklet sources and worklets with inputs render sample-exact, and a param set while a render is suspended applies from the suspend frame.
  • An unconnected output is silent. disconnect(), disconnect(output) and disconnect(node[, output[, input]]) act on the node's outputs.
  • connect() into a worklet throws IndexSizeError for an input that is out of range, and so does AudioWorkletNode.connect() for an output that is out of range.

Design

The Android engine has no node graph. Sources are voices, and Java flattens connections by attaching gain, filter and panner ids to the upstream voices. This PR fits worklets into that model:

  • Node. Each AudioWorkletNode is a native WorkletNode (worklets_) over the JS SharedArrayBuffer ring from audio-worklet-ring.ts. It replaces the old ExternalRing path. Output o plays as its own voice (id for output 0, id#o for the others) of a new WorkletOutput type. That voice reads the node's current quantum directly, so each output keeps its own gain, filter, panner and delay routing.

  • Inputs. Inputs use the DelayNode pattern from feat(audio-context): Android OfflineAudioContext on the realtime mixer, with suspend/resume and DelayNode #280. Attaching a voice to a worklet id (the CMD_ATTACH_GAIN intercept) routes that voice into the input (voiceWorklet_). emitVoice then adds the voice's per-channel samples to the input's quantum buffer instead of the mix. When the quantum is pushed, that buffer is mixed from the context's channel count to the input's channelCount.

  • Realtime. Each worklet steps one frame at a time. At a quantum boundary it pushes the quantum it just filled and plays the newest response, using the existing backlog control. Output therefore trails input by one quantum, as on iOS.

  • Offline. onAudioReady renders in passes:

    1. Every voice that doesn't depend on a worklet with inputs renders first.
    2. Each worklet with inputs whose feeding voices have all rendered pushes its quantum and blocks until the Worker answers. If the Worker is silent for 5 s, that worklet renders silence from then on.
    3. The outputs of those worklets render in the next pass.

    Chains (worklet → worklet) resolve in order, and a cycle runs with whatever input it has. Worklet sources request their quanta ahead, up to the end of the current renderOfflineFrames call, which never crosses a suspend. Delays now buffer one render call of input and run after all passes, because their output only reaches the destination.

  • Memory. Audio data stays in native memory: the shared ring, plus per-node quantum buffers allocated when the node is created. Java allocates nothing per quantum.

Fixes along the way

  • Input and output indices were dropped. nativeAttachGain(voice, gain) was exported under its JNI short name, which also binds the (voice, gain, output, input) overload. Every gain attach therefore lost its output and input index. It now uses the long name. nativeAttachPanner, nativeAttachBiquad and nativeAttachPlaybackRate have the same problem; see Known limits.
  • Offline param calls went to the wrong engine. Worklet param ids now carry an offline context's engine prefix, so calls on those params reach that engine.
  • A removed worklet leaked its inputs. A voice routed into a worklet that has been removed (its context closed, or the node collected) stays silent instead of falling through to the destination.
  • Class rename. The Java class WorkletSourceNode is now WorkletNode, and AudioContext.createWorkletSource is now createWorklet. The typings are updated to match.

Known limits

  • Inputs are captured at the context's channel count. In a mono OfflineAudioContext, a stereo source reaches a worklet as its mono mix. Mixing to more than two channels copies mono and zero-fills the rest; it doesn't use the full speaker layouts.
  • No fan-out from a node feeding a worklet. A node connected into a worklet input plays only into it, not also elsewhere. This is the same as DelayNode, because the engine routes each voice to one place.
  • Order-dependent wiring. Wiring a GainNode into a worklet before the gain has any sources attaches the gain to the worklet's output instead. This is the engine's existing behaviour for every node.
  • Offline speed. The Worker polls the ring every 2 ms, so an offline render waits up to 2 ms per 128-frame quantum for a worklet with inputs. Worklet sources request ahead and are not limited this way.
  • Realtime latency. Realtime output plays up to one device buffer plus 2 ms late, as before.

Tests

Android emulator (Pixel_9_Pro, API 37), demo app canvas-spec with suite audio:

  • Before: 25 pass, 2 skipped (the Android skip in audio-worklet.ts and the offline-suspend worklet test).
  • After: 34 pass, 0 fail, 0 skip in three consecutive runs: audio.worklet 8, audio.offline.suspend 6, audio.offline.render 7, audio.scheduling 8, audio.decode 5. Both Android skips are removed.

I also ran temporary probes, not committed, which all gave the expected values:

  • worklet → worklet chain offline: 4× the input
  • worklet → GainNode: gain applied
  • worklet → DelayNode: delayed by a quantum
  • stereo context with a stereo input: both channels
  • 2-channel output in a mono context: averaged
  • disconnect(0) with output 1 still connected: output 1 still plays
  • connecting into a 0-input worklet: IndexSizeError
  • realtime: output 1 of a 2-output node is audible
  • realtime: GainNode → worklet input applies the gain

tsc --noEmit on the package is clean. iOS sources are untouched.

OfflineAudioContext.suspend(when) and resume() on iOS, Windows and
Linux, as in browsers. A suspend holds rendering at `when` rounded up to
a 128-frame quantum; changes made before resume() apply from that frame.
Suspends can be scheduled before startRendering() or while held.

Windows and Linux:
- web-audio-api only takes suspends scheduled before rendering starts. A
  hidden worklet processor holds the render thread at each requested
  quantum until resume(), and posts an event so the offline loop applies
  the control messages queued meanwhile.
- The offline context's state is kept in JS (startRendering, suspends,
  resume, completion) rather than taken from engine events.
- Unconnected AudioWorklet inputs are empty, as in browsers
  (web-audio-api's spec-compliant-worklet-inputs).

iOS:
- The main-thread render loop stops at a suspend frame and pauses the
  engine until resume().
- Worklets don't queue requests past the next suspend, so changes made
  while held reach the Worker too.
- A node connected after rendering started rendered 2 frames late and
  3 dB loud: an initialized mixer keeps a new input bus at its 44.1 kHz
  stereo default. The engine now stops before such a connect and
  restarts for the next quantum. Stopping keeps the sample time but
  clears effect state; the README notes it.
- Node start() no longer starts an offline engine; only rendering does.
…uled

With no suspend scheduled the suspend set is nil, and messaging nil gave a
look-ahead limit of 0, so a source worklet never queued a request and
rendered silence after a 5 s stall. Adds a spec: a worklet source renders
offline, and a param set while held applies from the suspend frame.
The worklet scope runs as a plain script in a Worker and polls its rings
with setInterval. 9.0.4-next gives such Workers no timers, so addModule
rejected; 9.1.0 has them. The README notes the requirement.
The iOS worklet node is now an effect unit when it has inputs. Each
input sums its connections in its own mixer, and each output is its own
bus. Offline, a node with inputs waits for the Worker each quantum, so
it stays sample-exact.

Ports of 1 or 2 channels use the context's channel count on the
AVAudio side, and the node up/down-mixes with Web Audio's speaker rules.
AVAudioMixerNode would otherwise pan equal-power (mono read 0.707x).

A realtime worklet now starts the engine and marks the context active
when it connects. With no start() of its own, a graph whose only source
was a worklet never played.
…r, with suspend/resume and DelayNode

Android's OfflineAudioContext resolved startRendering() with an empty
buffer: the native renderer kept its result where the Java wrapper never
looked. It was also a separate, simpler mixer (each param took only its
first event; no delay, compressor or convolver), and an offline
context's sources played through the device as well.

Each OfflineAudioContext now gets its own NativeEngine: the realtime
mixer with no stream, a virtual clock and the context's rate and
channels. Its ids carry the engine's prefix, so every JNI call reaches
the engine that owns the id; creation calls take the context id.
Java drives the render in quanta on its own thread and holds at each
suspend frame. The result is written straight into the AudioBuffer's
native memory, and sources read their AudioBuffer in place, so no audio
passes through the Java heap.

OfflineAudioContext gains state, suspend(when), resume(), sampleRate,
length, currentTime and listener, as on iOS, Windows and Linux. Offline
output is no longer clipped to [-1, 1]. Times converted from seconds
now land on their own frame.

DelayNode delayed nothing on Android: it was a gain whose value was
delayTime, starting at 1 s. Each DelayNode now has a native delay line
(fractional, sized by maxDelayTime) that the voices routed through it
feed, so its tail plays out after its sources stop; delayTime defaults
to 0. On iOS, delayTime changes never reached the AVAudioUnitDelay and
its 15 kHz low-pass smoothed the signal; both are fixed.

AudioContext.renderOffline(trackIds, ...), an undocumented Android-only
method that also returned empty buffers, is removed.
…fline worklets on Android

An Android AudioWorkletNode was a source voice fed through an ExternalRing:
no inputs, one output, and no OfflineAudioContext.audioWorklet. It now
matches iOS.

Native: a WorkletNode per node in the engine (worklets_), replacing the
worklet's ExternalRing. Output o plays as its own voice (`id`, `id#o`) of
a new WorkletOutput type that reads the node's current quantum directly,
so each output keeps its own gain/filter/panner routing and stays silent
until connected. Inputs reuse the DelayNode pattern: attaching a voice to
a worklet id routes it into that input (voiceWorklet_), and emitVoice sums
its per-channel output into the input's quantum buffer. On a push the
buffer is mixed to the input's channelCount with Web Audio "speakers"
rules (mono copies, down-mix averages); an input nothing played into
reports 0 channels.

Realtime: each worklet steps a frame at a time; at a quantum boundary it
pushes the quantum just filled and plays the newest response (the
existing backlog control), so output trails input by a quantum, as on iOS.

Offline: onAudioReady renders in passes. Voices that don't depend on a
worklet with inputs render first; then each such worklet whose feeding
voices have rendered pushes its quantum and waits for the Worker (5 s
stall -> silence), and its outputs render next. Chains resolve in order;
a cycle runs with what it has. Sources request ahead to the end of the
render call (never past a suspend), so a param set while held applies
from the suspend frame. Delays now take a per-call input buffer and run
after the passes, since their output only reaches the destination.

Fixes along the way:
- The short-name JNI export of nativeAttachGain also bound the 4-argument
  overload, dropping every output/input index. It now has its long name.
- Worklet param ids carry an offline context's engine prefix, so their
  calls reach that engine.
- AudioWorkletNode.disconnect routes to the node's outputs; the shared
  Android AudioNode.disconnect treats output 0 as "all" and calls Java
  methods that don't exist.
- A voice routed into a removed worklet stays silent instead of falling
  through to the destination.

Audio data stays in native memory (the SharedArrayBuffer ring and
per-node quantum buffers); nothing is allocated in Java per quantum.
Base automatically changed from feat/android-offline to master November 24, 2026 21:35
@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a1dffc05-8dd3-4243-b2fc-c57d240b528d

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

…t-io

# Conflicts:
#	packages/audio-context/index.android.ts
#	packages/audio-context/platforms/android/audiocontext-release.aar
#	packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.h
#	packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_jni.cpp
#	packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_offline.cpp
#	packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_render.cpp
#	packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContext.java
#	tools/demo/canvas/spec/audio-offline-suspend.ts
#	tools/demo/canvas/spec/audio-worklet.ts
@triniwiz
triniwiz merged commit 4de93e8 into master Nov 24, 2026
35 checks passed
@triniwiz
triniwiz deleted the feat/android-worklet-io branch November 24, 2026 21:58
@github-actions

Copy link
Copy Markdown

ℹ️ Note: npm publishing is disabled for pull requests.
Publishing is performed only from tag pushes via the npm Release workflow.
If you need a test publish, merge to master — pushes publish pr-tagged prereleases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant