Skip to content

Commit f18e91e

Browse files
authored
feat(audio-context): render the Android audio graph as a real node graph (#285)
* fix(audio-context): Android scheduling clock, targeted disconnect, close, channel mixing and worklet wakeups - Realtime blocks run on a frame clock instead of the device timestamp, which jittered between callbacks, so a source's position and gain automation drifted apart (tens of frames). - nativeAttachPanner/Biquad/PlaybackRate export their 2-arg overloads under the long JNI name; the short name also bound the 4-arg overloads and dropped output/input. - AudioNode.disconnect calls the Java overloads (disconnectOutput/disconnectTo didn't exist, so every targeted disconnect was a full one). A new CMD_DETACH_FROM clears only the voice slots holding the target. - Closing a realtime AudioContext stops and frees its voices and nodes; the shared engine only suspends once no realtime context is open. Buffer sources whose buffer is set after creation are now created in their context's engine and tracked by it (offline ones were created on the realtime engine and never rendered). - An empty gain attach clears voiceDelay_. - Buffer sources and worklet outputs up/down-mix with the Web Audio speaker rules (mono, stereo, quad, 5.1), so a stereo buffer in a mono context plays (L+R)/2. - Worklet inputs render at each input's own channelCount from each source's own channels. - The worklet Worker is woken by an eventfd on its looper per requested quantum instead of a 2 ms poll (Atomics.notify can't come from the render thread). 400 offline quanta with an input worklet: ~1000 ms -> ~130 ms. - BiquadFilterNode.type has a getter/setter on Android. * feat(audio-context): render the Android audio graph as a real node graph Android flattened every connection onto the source voices: one gain, filter and panner slot per voice output, with DelayNode and worklet inputs in side maps. A node feeding a delay or a worklet played only there, a source couldn't fan out to two gains, chained gains replaced each other, wiring depended on the order of connect calls, a DelayNode couldn't sit in a feedback loop, and source.disconnect(firstGain) left a gain chain playing. The engine now keeps the graph itself (audio_graph.cpp). connect/disconnect go straight to native as edges; each 128-frame quantum renders the nodes in topological order, each input summing its connections at its computed channel count with the Web Audio up/down-mix rules. Tarjan's SCCs find cycles: a cycle through a DelayNode reads the delay line before its input is written (delay at least one quantum), a cycle without one is muted. node.connect(AudioParam) adds the source's mono mix to gain-style and panner params every frame. Realtime callbacks play from a quantum FIFO; offline renders a quantum per call. Nodes the app frees while something still plays into them stay until it stops.
1 parent 16ff853 commit f18e91e

31 files changed

Lines changed: 2372 additions & 4668 deletions

‎packages/audio-context/README.md‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -147,9 +147,14 @@ Context lifecycle and routing:
147147
- `state`, `onstatechange`
148148
- `sinkId`, `setSinkId(deviceId)`
149149

150-
On Android an `OfflineAudioContext` renders on its own engine, the same mixer as the realtime
151-
one, with nothing reaching the device. A source connected to it reads an `AudioBuffer` in place.
152-
A `DelayNode` there can't be part of a feedback loop: its output doesn't reach its own input.
150+
On Android the engine renders the node graph itself, a 128-frame quantum at a time in
151+
topological order: a node's inputs sum every connection, an output can feed any number of nodes,
152+
and each input mixes up or down by its `channelCount`, `channelCountMode` and
153+
`channelInterpretation` (the speaker rules for mono, stereo, quad and 5.1). A cycle plays only
154+
through a `DelayNode`, whose delay is then at least one quantum, as in the spec; a cycle without
155+
one is silent. An `OfflineAudioContext` renders on its own engine with nothing reaching the
156+
device, and a source connected to it reads an `AudioBuffer` in place. A `ConvolverNode` passes its
157+
input through.
153158

154159
On iOS a `GainNode` and a `DelayNode` evaluate `gain` and `delayTime` every frame, so automation
155160
lands on its frame, in an `OfflineAudioContext` and a realtime one, and `gain` can go above 1 or
@@ -159,8 +164,13 @@ between two frames interpolates linearly.
159164
On iOS `node.connect(param)` works for those two params, `GainNode.gain` and `DelayNode.delayTime`:
160165
the node's output, mixed down to mono, adds to the param's value every frame. Other params
161166
(oscillator `frequency`, `BiquadFilterNode`, panner and `ConstantSourceNode.offset` params, and
162-
the rest) aren't evaluated per frame and ignore audio connected to them. Android doesn't
163-
support `node.connect(param)`.
167+
the rest) aren't evaluated per frame and ignore audio connected to them.
168+
169+
On Android `node.connect(param)` adds the node's output, mixed down to mono, to the param every
170+
frame for `GainNode.gain`, `DelayNode.delayTime`, `ConstantSourceNode.offset`, oscillator
171+
`frequency`, `AudioBufferSourceNode.playbackRate`, the `DynamicsCompressorNode` params, panner
172+
params and `AudioWorkletNode` params (for a worklet with inputs). `BiquadFilterNode` and listener
173+
params ignore audio connected to them.
164174

165175
## Android memory
166176

@@ -218,8 +228,7 @@ on the app's JS thread.
218228
(`Atomics.notify` can't come from the render thread, so the wake is native.)
219229
- On Android each input is mixed from every source's own channels straight to its
220230
`channelCount`, with the speaker rules for mono, stereo, quad and 5.1 (other counts mix
221-
discretely), in any context. A node connected into a worklet input plays only into it, as with
222-
`DelayNode`.
231+
discretely), in any context.
223232

224233
## Linux
225234

‎packages/audio-context/index.android.ts‎

Lines changed: 64 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -130,21 +130,75 @@ export class AudioParam extends AudioParamBase {
130130
}
131131
}
132132

133+
const COUNT_MODES = ['max', 'clamped-max', 'explicit'];
134+
const INTERPRETATIONS = ['speakers', 'discrete'];
135+
133136
export class AudioNode extends AudioNodeBase {
137+
private _channelCount?: number;
138+
private _channelCountMode?: string;
139+
private _channelInterpretation?: string;
140+
134141
constructor(context: NativeBaseAudioContext) {
135142
super(context);
136143
}
137144

145+
private get _graphNative(): org.nativescript.audiocontext.AudioNode {
146+
return (this as never as { native: org.nativescript.audiocontext.AudioNode }).native;
147+
}
148+
149+
// The Web Audio defaults for this node's kind.
150+
private _channelDefaults(): [number, string, string] {
151+
if (this instanceof ChannelSplitterNode) return [this.numberOfOutputs, 'explicit', 'discrete'];
152+
if (this instanceof ChannelMergerNode) return [1, 'explicit', 'speakers'];
153+
if (this instanceof AudioDestinationNode) return [this.context instanceof OfflineAudioContext ? (this.context as any)._channels : 2, 'explicit', 'speakers'];
154+
if (this instanceof PannerNode || this instanceof StereoPannerNode || this instanceof ConvolverNode || this instanceof DynamicsCompressorNode) return [2, 'clamped-max', 'speakers'];
155+
return [2, 'max', 'speakers'];
156+
}
157+
158+
get channelCount(): number {
159+
return this._channelCount ?? this._channelDefaults()[0];
160+
}
161+
162+
set channelCount(value: number) {
163+
const count = Math.floor(Number(value));
164+
if (!(count >= 1 && count <= 32)) throw domError('NotSupportedError', `AudioNode.channelCount: ${value} is out of range`);
165+
this._channelCount = count;
166+
this._graphNative?.setChannelConfig(count, -1, -1);
167+
}
168+
169+
get channelCountMode(): string {
170+
return this._channelCountMode ?? this._channelDefaults()[1];
171+
}
172+
173+
set channelCountMode(value: string) {
174+
const mode = COUNT_MODES.indexOf(value);
175+
if (mode < 0) return;
176+
this._channelCountMode = value;
177+
this._graphNative?.setChannelConfig(-1, mode, -1);
178+
}
179+
180+
get channelInterpretation(): string {
181+
return this._channelInterpretation ?? this._channelDefaults()[2];
182+
}
183+
184+
set channelInterpretation(value: string) {
185+
const interpretation = INTERPRETATIONS.indexOf(value);
186+
if (interpretation < 0) return;
187+
this._channelInterpretation = value;
188+
this._graphNative?.setChannelConfig(-1, -1, interpretation);
189+
}
190+
138191
connect(node: any, output?: number, input?: number) {
139192
if (node instanceof AudioWorkletNode && ((input ?? 0) < 0 || (input ?? 0) >= node.numberOfInputs)) {
140193
throw domError('IndexSizeError', `AudioNode.connect: input ${input ?? 0} is out of range`);
141194
}
142-
const that = this as never as AudioNode & { native: org.nativescript.audiocontext.AudioNode };
195+
const native = this._graphNative;
143196
const target = node?.native || node;
144197
try {
145-
if (typeof output === 'number' && typeof input === 'number') that.native.connect(target, output, input);
146-
else if (typeof output === 'number') that.native.connect(target, output);
147-
else that.native.connect(target);
198+
if (node instanceof AudioParamBase) native.connect(target as org.nativescript.audiocontext.AudioParam, output ?? 0);
199+
else if (typeof output === 'number' && typeof input === 'number') native.connect(target, output, input);
200+
else if (typeof output === 'number') native.connect(target, output);
201+
else native.connect(target);
148202
} catch (e) {
149203
console.warn('AudioNode.connect failed:', e);
150204
}
@@ -153,7 +207,7 @@ export class AudioNode extends AudioNodeBase {
153207
}
154208

155209
disconnect(destinationOrOutput?: any, output?: number, input?: number) {
156-
const native = (this as never as { native: org.nativescript.audiocontext.AudioNode }).native;
210+
const native = this._graphNative;
157211
if (destinationOrOutput === undefined || destinationOrOutput === null) {
158212
native.disconnect();
159213
return;
@@ -162,9 +216,12 @@ export class AudioNode extends AudioNodeBase {
162216
native.disconnect(destinationOrOutput);
163217
return;
164218
}
165-
// AudioParam inputs are never wired natively.
166-
if (destinationOrOutput instanceof AudioParamBase) return;
167219
const target = destinationOrOutput.native ?? destinationOrOutput;
220+
if (destinationOrOutput instanceof AudioParamBase) {
221+
if (typeof output === 'number') native.disconnect(target as org.nativescript.audiocontext.AudioParam, output);
222+
else native.disconnect(target as org.nativescript.audiocontext.AudioParam);
223+
return;
224+
}
168225
if (typeof output !== 'number') native.disconnect(target);
169226
else if (typeof input !== 'number') native.disconnect(target, output);
170227
else native.disconnect(target, output, input);
Binary file not shown.

‎packages/audio-context/src-native/android/audiocontext/src/main/cpp/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ endif()
2424
add_library(native-audio SHARED
2525
audio_context.cpp
2626
audio_render.cpp
27+
audio_graph.cpp
2728
audio_offline.cpp
2829
audio_jni.cpp
2930
audio_worklet.cpp

0 commit comments

Comments
 (0)