Skip to content

Commit a8e4e21

Browse files
authored
feat(audio-context): AudioWorklet on Android (#275)
audioContext.audioWorklet, addModule and AudioWorkletNode on Android, with the scope script, host and SharedArrayBuffer ring the iOS build uses. - The node's ring is a SharedArrayBuffer. The runtime hands it to Java as a direct ByteBuffer over the same memory; the native side marks a header word and the constructor checks it from JS, so a runtime that copied would fail loudly instead of playing silence. - WorkletSourceNode (Java) / createWorkletSource (JNI) add a voice to the Oboe engine. It is an ExternalPCM voice whose ExternalRing a render-thread pre-pass fills with quanta: push a request (param values from the gain-event automation the other params use, a-rate or k-rate), pull the oldest response with the Rust ring's backlog handling. So gain, filter and panner routing work unchanged. - Params are context-registered gain ids, so setValueAtTime and ramps use the context's clock. - process() returning false plays out the queue, then ends the voice. Stopping or ending the voice marks the ring closed for the Worker. - The Worker runs at the 'audio' thread priority and polls the rings every 2 ms, as on iOS. Connected nodes are kept until disconnect() or context close; a collected node stops its voice and keeps the ring alive for 2 s, past the render thread's last read. Limits: no inputs and one output of up to 8 channels; no OfflineAudioContext worklet. Tested with WorkletSourceInstrumentedTest (a Java stand-in for the Worker serves the ring; analyser levels follow the param) and a probe app on an API 36 arm64 emulator.
1 parent 1afe2b4 commit a8e4e21

12 files changed

Lines changed: 571 additions & 6 deletions

File tree

‎packages/audio-context/README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,10 @@ on the app's JS thread.
176176
- An input or a channel-following output carries at most 8 channels; unconnected inputs are one
177177
silent channel rather than empty.
178178
- `audioWorklet` is `undefined` where the runtime has no `Worker` (the QuickJS, Hermes and JSC
179-
builds) and on iOS and Android.
179+
builds).
180+
- On Android an `AudioWorkletNode` is a source: no inputs, one output of up to 8 channels, and no
181+
`OfflineAudioContext` worklet. Its ring is a `SharedArrayBuffer` the Worker polls every 2 ms, so
182+
output plays up to a device buffer plus 2 ms late.
180183

181184
## Linux
182185

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

Lines changed: 163 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Utils } from '@nativescript/core';
1+
import { File, Utils, knownFolders } from '@nativescript/core';
22
import {
33
AnalyserOptions,
44
AudioBufferCopyOptions,
@@ -41,6 +41,10 @@ import {
4141
resolveNativePlayer,
4242
throwInvalidMediaElement,
4343
} from './common';
44+
import { AUDIO_WORKLET_SCOPE } from './audio-worklet-scope';
45+
import { SHARED_RING_BRIDGE, createWorkletRing, workletRingLayout } from './audio-worklet-ring';
46+
import { AudioParamMap, AudioWorkletNodeOptions, AudioWorkletPort, WorkletHost, closeWithContext, domError, isWorkerSupported, loadWorkletModule, resolveWorkletNodeOptions } from './audio-worklet-host';
47+
export { AudioWorkletNodeOptions };
4448

4549
type NativeBaseAudioContext = BaseAudioContext & { native: org.nativescript.audiocontext.AudioContextInstance };
4650

@@ -741,6 +745,153 @@ export class OfflineAudioContext extends BaseAudioContext {
741745
}
742746
}
743747

748+
let workletScriptPath: string | null = null;
749+
750+
function workletScript(): string {
751+
if (!workletScriptPath) {
752+
const file = knownFolders.temp().getFile('ns-audio-worklet-scope.js');
753+
file.writeTextSync(SHARED_RING_BRIDGE + '\n' + AUDIO_WORKLET_SCOPE);
754+
workletScriptPath = file.path;
755+
}
756+
return workletScriptPath;
757+
}
758+
759+
function readWorkletModule(source: string): Promise<string> {
760+
if (source.startsWith('data:')) {
761+
const comma = source.indexOf(',');
762+
const data = source.slice(comma + 1);
763+
return Promise.resolve(/;base64$/i.test(source.slice(0, comma)) ? atob(data) : decodeURIComponent(data));
764+
}
765+
if (!File.exists(source)) return Promise.reject(new Error(`${source}: no such file`));
766+
return File.fromPath(source).readText();
767+
}
768+
769+
function workletPath(path: string): string {
770+
if (path.startsWith('file://')) path = decodeURIComponent(path.slice('file://'.length));
771+
return path.startsWith('~/') ? knownFolders.currentApp().path + path.slice(1) : path;
772+
}
773+
774+
// Header word the native side marks: tells a shared ring from a copy.
775+
const RING_NATIVE_MARK = 5;
776+
const RING_CLOSED = 3;
777+
778+
let nextWorkletNode = 1;
779+
// Connected nodes keep playing without a JS reference, as in browsers.
780+
const connectedWorkletNodes = new Set<AudioWorkletNode>();
781+
// The native voice reads the ring until the render thread drops it, a callback after stop().
782+
const stopWorkletNode = (held: { native: org.nativescript.audiocontext.WorkletSourceNode; ring: SharedArrayBuffer }) => {
783+
held.native.stop();
784+
setTimeout(() => held.ring.byteLength, 2000);
785+
};
786+
const workletNodeRegistry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(stopWorkletNode) : null;
787+
788+
export class AudioWorklet {
789+
private [context_]: AudioContext;
790+
private _host: WorkletHost | null = null;
791+
792+
constructor(a?: any, context?: AudioContext) {
793+
if (a !== nativeCtor_ || !context) throw new TypeError('Illegal constructor.');
794+
this[context_] = context;
795+
}
796+
797+
/** @internal */
798+
_scope(create: boolean): WorkletHost | null {
799+
if (!this._host && create) {
800+
const context = this[context_];
801+
this._host = new WorkletHost(workletScript(), { scope: 0, sampleRate: context.sampleRate, addon: '' }, { android: { priority: 'audio' } });
802+
closeWithContext?.register(context, this._host);
803+
}
804+
return this._host;
805+
}
806+
807+
addModule(moduleURL: string | { href: string }, _options?: { credentials?: string }): Promise<void> {
808+
let host: WorkletHost;
809+
try {
810+
if (this[context_].state === 'closed') throw domError('InvalidStateError', 'The AudioContext is closed');
811+
host = this._scope(true);
812+
} catch (e) {
813+
return Promise.reject(e);
814+
}
815+
const url = typeof moduleURL === 'string' ? moduleURL : String(moduleURL?.href ?? moduleURL);
816+
return loadWorkletModule(url, readWorkletModule, workletPath).then(({ source, url }) => host.addModule(source, url));
817+
}
818+
}
819+
820+
export class AudioWorkletNode extends AudioNode {
821+
readonly port: AudioWorkletPort;
822+
readonly parameters: AudioParamMap<AudioParam>;
823+
[native_]: org.nativescript.audiocontext.WorkletSourceNode;
824+
private _ring: SharedArrayBuffer;
825+
private _onprocessorerror: ((event: any) => void) | null = null;
826+
827+
constructor(context: AudioContext, name: string, options: AudioWorkletNodeOptions = {}) {
828+
const worklet = context?.audioWorklet;
829+
const resolved = resolveWorkletNodeOptions(worklet?._scope(false), name, options);
830+
const { host, descriptors, numberOfInputs, numberOfOutputs, outputChannelCount, parameterData } = resolved;
831+
if (numberOfInputs > 0) throw domError('NotSupportedError', 'AudioWorkletNode: inputs are not supported on Android');
832+
if (numberOfOutputs !== 1) throw domError('NotSupportedError', 'AudioWorkletNode: Android supports one output');
833+
super(context);
834+
const channels = Math.min(outputChannelCount?.[0] ?? 1, 8);
835+
const layout = workletRingLayout(0, [channels], descriptors.length);
836+
const ring = createWorkletRing(layout);
837+
const offsets = (Array as any).create('int', 6);
838+
[layout.slotWords, layout.header, layout.outputCounts, layout.outputData[0], layout.paramLengths, layout.paramData].forEach((value, i) => (offsets[i] = value));
839+
const defaults = (Array as any).create('double', descriptors.length);
840+
descriptors.forEach((d, i) => (defaults[i] = parameterData?.[d.name] ?? d.defaultValue));
841+
const native = AudioContext.getInstance().createWorkletSource(context.native, ring as any, channels, offsets, defaults);
842+
if (!native) throw domError('NotSupportedError', 'AudioWorkletNode: the audio engine is unavailable');
843+
const header = new Uint32Array(ring, layout.header * 4, 8);
844+
if (Atomics.load(header, RING_NATIVE_MARK) !== 0x574b4c54) {
845+
native.stop();
846+
throw domError('NotSupportedError', 'AudioWorkletNode: this runtime copies SharedArrayBuffers passed to native code');
847+
}
848+
this[native_] = native;
849+
this._ring = ring;
850+
this.parameters = new AudioParamMap(new Map(descriptors.map((d, i) => [d.name, new AudioParam(nativeCtor_, native.getParam(i))])));
851+
const id = nextWorkletNode++;
852+
this.port = new AudioWorkletPort(host, id);
853+
workletNodeRegistry?.register(this, { native, ring }, this);
854+
host.create(this, id, String(name), { ...options, numberOfInputs, numberOfOutputs, outputChannelCount: [channels], parameterData }, { buffer: ring, layout });
855+
}
856+
857+
get native() {
858+
return this[native_];
859+
}
860+
861+
connect(node: any, output?: number, input?: number) {
862+
connectedWorkletNodes.add(this);
863+
return super.connect(node, output, input);
864+
}
865+
866+
disconnect(...args: any[]) {
867+
if (args.length === 0) connectedWorkletNodes.delete(this);
868+
return (super.disconnect as any)(...args);
869+
}
870+
871+
get onprocessorerror() {
872+
return this._onprocessorerror;
873+
}
874+
875+
set onprocessorerror(callback: ((event: any) => void) | null) {
876+
if (this._onprocessorerror) this.removeEventListener('processorerror', this._onprocessorerror);
877+
this._onprocessorerror = typeof callback === 'function' ? callback : null;
878+
if (this._onprocessorerror) this.addEventListener('processorerror', this._onprocessorerror);
879+
}
880+
881+
/** @internal */
882+
_processorError(message: string) {
883+
this.dispatchEvent({ type: 'processorerror', message, error: new Error(message), target: this } as any);
884+
}
885+
886+
/** @internal */
887+
_stop() {
888+
workletNodeRegistry?.unregister(this);
889+
connectedWorkletNodes.delete(this);
890+
Atomics.store(new Uint32Array(this._ring, this._ring.byteLength - 32, 8), RING_CLOSED, 1);
891+
stopWorkletNode({ native: this[native_], ring: this._ring });
892+
}
893+
}
894+
744895
let audioContextInstance: org.nativescript.audiocontext.AudioContext | null = null;
745896

746897
export class AudioContext extends BaseAudioContext {
@@ -763,6 +914,13 @@ export class AudioContext extends BaseAudioContext {
763914
this._setState('running');
764915
}
765916

917+
private _audioWorklet: AudioWorklet | null = null;
918+
919+
get audioWorklet(): AudioWorklet | undefined {
920+
if (!this._audioWorklet && isWorkerSupported()) this._audioWorklet = new AudioWorklet(nativeCtor_, this);
921+
return this._audioWorklet ?? undefined;
922+
}
923+
766924
createMediaElementSource(mediaElement: MediaElementLike): MediaElementAudioSourceNode {
767925
return new MediaElementAudioSourceNode(this, mediaElement);
768926
}
@@ -964,6 +1122,10 @@ export class AudioContext extends BaseAudioContext {
9641122

9651123
close(): Promise<void> {
9661124
if (this._state === 'closed') return Promise.resolve();
1125+
this._audioWorklet?._scope(false)?.close();
1126+
connectedWorkletNodes.forEach((node) => {
1127+
if (node.context === this) node._stop();
1128+
});
9671129
return new Promise((resolve, reject) => {
9681130
const ref = new WeakRef(this);
9691131
AudioContext.getInstance().closeAsync(

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -222,12 +222,12 @@ export interface AudioWorkletNodeOptions {
222222
channelInterpretation?: string;
223223
}
224224

225-
/** Windows and Linux. */
225+
/** Windows, Linux and Android. */
226226
export declare class AudioWorklet {
227227
addModule(moduleURL: string | URL, options?: { credentials?: string }): Promise<void>;
228228
}
229229

230-
/** Windows and Linux. */
230+
/** Windows, Linux and Android (a source there: no inputs, one output). */
231231
export declare class AudioWorkletNode extends AudioNode {
232232
constructor(context: BaseAudioContext, name: string, options?: AudioWorkletNodeOptions);
233233
readonly port: MessagePort;
@@ -239,7 +239,7 @@ export declare class AudioContext extends BaseAudioContext {
239239
constructor(options?: AudioContextOptions);
240240

241241
readonly destination: AudioDestinationNode;
242-
/** Undefined where processors can't run (iOS, Android, runtimes without Worker). */
242+
/** Undefined where the runtime has no Worker. */
243243
readonly audioWorklet: AudioWorklet | undefined;
244244

245245
createGain(options?: { gain?: number }): GainNode;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package org.nativescript.audiocontext;
2+
3+
import androidx.test.ext.junit.runners.AndroidJUnit4;
4+
import androidx.test.filters.SdkSuppress;
5+
6+
import org.junit.Assert;
7+
import org.junit.Test;
8+
import org.junit.runner.RunWith;
9+
10+
import java.lang.invoke.VarHandle;
11+
import java.nio.ByteBuffer;
12+
import java.nio.ByteOrder;
13+
import java.nio.FloatBuffer;
14+
15+
/** A worklet voice over a ring served by a Java stand-in for the Worker. */
16+
@RunWith(AndroidJUnit4.class)
17+
@SdkSuppress(minSdkVersion = 33)
18+
public class WorkletSourceInstrumentedTest {
19+
// workletRingLayout(0, [1], 1) in audio-worklet-ring.ts.
20+
private static final int SLOTS = 64;
21+
private static final int OUTPUT_COUNTS = 4;
22+
private static final int PARAM_LENGTHS = 5;
23+
private static final int OUTPUT_DATA = 8;
24+
private static final int PARAM_DATA = OUTPUT_DATA + 128;
25+
private static final int SLOT_WORDS = PARAM_DATA + 128;
26+
private static final int HEADER = SLOT_WORDS * SLOTS;
27+
28+
private volatile boolean serving = true;
29+
30+
private void serve(ByteBuffer ring) {
31+
while (serving) {
32+
int requested = ring.getInt(HEADER * 4);
33+
int done = ring.getInt((HEADER + 1) * 4);
34+
VarHandle.acquireFence();
35+
for (int k = done; k != requested; k++) {
36+
int slot = Integer.remainderUnsigned(k, SLOTS) * SLOT_WORDS * 4;
37+
float level = ring.getFloat(slot + PARAM_DATA * 4);
38+
for (int i = 0; i < 128; i++) ring.putFloat(slot + (OUTPUT_DATA + i) * 4, level);
39+
ring.putInt(slot + 2 * 4, 1);
40+
}
41+
VarHandle.releaseFence();
42+
ring.putInt((HEADER + 1) * 4, requested);
43+
try {
44+
Thread.sleep(1);
45+
} catch (InterruptedException e) {
46+
return;
47+
}
48+
}
49+
}
50+
51+
private static float peak(AnalyserNode analyser) {
52+
FloatBuffer data = ByteBuffer.allocateDirect(analyser.getFftSize() * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
53+
analyser.getFloatTimeDomainData(data);
54+
float peak = 0;
55+
for (int i = 0; i < data.capacity(); i++) peak = Math.max(peak, Math.abs(data.get(i)));
56+
return peak;
57+
}
58+
59+
@Test
60+
public void playsQuantaFromTheRingWithParamValues() throws Exception {
61+
AudioContext audio = AudioContext.getInstance();
62+
AudioContextInstance context = audio.createContextInstance(48000, 0.01);
63+
AnalyserNode analyser = audio.createAnalyser(context);
64+
ByteBuffer ring = ByteBuffer.allocateDirect((HEADER + 8) * 4).order(ByteOrder.LITTLE_ENDIAN);
65+
WorkletSourceNode node = audio.createWorkletSource(context, ring, 1, new int[]{SLOT_WORDS, HEADER, OUTPUT_COUNTS, OUTPUT_DATA, PARAM_LENGTHS, PARAM_DATA}, new double[]{0.25});
66+
Assert.assertNotNull(node);
67+
Assert.assertEquals("native marks the ring it reads", 0x574B4C54, ring.getInt((HEADER + 5) * 4));
68+
Assert.assertEquals(1, node.getParamCount());
69+
70+
Thread worker = new Thread(() -> serve(ring));
71+
worker.start();
72+
try {
73+
Thread.sleep(600);
74+
Assert.assertEquals(0.25f, peak(analyser), 0.01f);
75+
Assert.assertTrue("requests keep coming", ring.getInt(HEADER * 4) > 100);
76+
node.getParam(0).setValue(0.5);
77+
Thread.sleep(400);
78+
Assert.assertEquals(0.5f, peak(analyser), 0.01f);
79+
node.stop();
80+
Thread.sleep(200);
81+
Assert.assertEquals("closed once the voice is gone", 1, ring.getInt((HEADER + 3) * 4));
82+
} finally {
83+
serving = false;
84+
worker.join();
85+
}
86+
}
87+
}

‎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
@@ -26,6 +26,7 @@ add_library(native-audio SHARED
2626
audio_render.cpp
2727
audio_offline.cpp
2828
audio_jni.cpp
29+
audio_worklet.cpp
2930
hrtf_convolver.cpp)
3031

3132
# Include small bundled kissfft implementation

‎packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.h‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,11 @@ class NativeEngine {
101101
void pushPcmFrames(const std::string &id, const float *interleaved, size_t sampleCount);
102102
void endExternalPcmSource(const std::string &id);
103103

104+
// An AudioWorkletNode's voice over its ring (audio-worklet-ring.ts); offsets are in 4-byte words.
105+
std::string createWorkletSource(float *ring, int channels, int slotWords, int header,
106+
int outputCounts, int outputData, int paramLengths,
107+
int paramData, std::vector<std::string> paramIds);
108+
104109
#ifdef HAS_OBOE
105110

106111
oboe::DataCallbackResult
@@ -168,6 +173,24 @@ class NativeEngine {
168173
std::atomic<bool> ended{false};
169174
};
170175

176+
struct WorkletRing {
177+
float *words = nullptr;
178+
std::atomic<uint32_t> *header = nullptr;
179+
int channels = 1;
180+
int slotWords = 0;
181+
int outputCounts = 0;
182+
int outputData = 0;
183+
int paramLengths = 0;
184+
int paramData = 0;
185+
std::vector<std::string> paramIds;
186+
// Render thread only.
187+
std::vector<float> out;
188+
uint64_t nextFrame = 0;
189+
uint32_t lowWater = UINT32_MAX;
190+
uint32_t window = 0;
191+
bool finished = false;
192+
};
193+
171194
struct Voice {
172195
enum Type {
173196
Oscillator, BufferSource, ExternalPCM
@@ -198,12 +221,16 @@ class NativeEngine {
198221
int bufferSampleRate = 0;
199222

200223
std::shared_ptr<ExternalRing> externalRing;
224+
std::shared_ptr<WorkletRing> worklet;
201225
std::vector<float> externalPrev;
202226
std::vector<float> externalCurr;
203227
double externalSubPos = 0.0;
204228
bool externalPrimed = false;
205229
};
206230

231+
// Fills the voice's ExternalRing with worklet quanta until it holds `frames`.
232+
void produceWorkletQuanta(Voice &voice, int frames, int64_t startNs, double frameNs);
233+
207234
std::unordered_map<std::string, BufferData> audioBuffers_;
208235
std::unordered_map<std::string, Voice> audioVoices_;
209236
// Buffers to free once no playing voice reads them; render thread only.
@@ -261,7 +288,8 @@ class NativeEngine {
261288
CMD_DETACH_PLAYBACK_RATE,
262289
CMD_FREE_PLAYBACK_RATE,
263290
CMD_SET_PANNER_HRIR,
264-
CMD_SET_PANNER_PARTITION_SIZE
291+
CMD_SET_PANNER_PARTITION_SIZE,
292+
CMD_CREATE_WORKLET
265293
};
266294

267295
struct Command {
@@ -321,6 +349,7 @@ class NativeEngine {
321349
std::shared_ptr<std::vector<int16_t>> pcm;
322350
std::shared_ptr<std::vector<float>> pcmFloat;
323351
std::shared_ptr<ExternalRing> externalRing;
352+
std::shared_ptr<WorkletRing> worklet;
324353
std::shared_ptr<std::vector<float>> hrirLeft;
325354
std::shared_ptr<std::vector<float>> hrirRight;
326355
bool clearHrir = false;

0 commit comments

Comments
 (0)