Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions packages/audio-context/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,14 @@ on the app's JS thread.
still feeds silent channels until it is garbage collected.
- `audioWorklet` is `undefined` where the runtime has no `Worker` (the QuickJS, Hermes and JSC
builds).
- On Android an `AudioWorkletNode` is a source: no inputs, one output of up to 8 channels, and no
`OfflineAudioContext` worklet. Its ring is a `SharedArrayBuffer` the Worker polls every 2 ms, so
output plays up to a device buffer plus 2 ms late.
- On Android an `AudioWorkletNode` has up to 16 inputs and 16 outputs of up to 8 channels each,
with the same input mixing as iOS, and works in an `OfflineAudioContext`. Its ring is a
`SharedArrayBuffer` the Worker polls every 2 ms, so realtime output plays up to a device buffer
plus 2 ms late, and an offline render waits up to 2 ms per 128-frame quantum for a worklet with
inputs (a source's quanta are requested ahead).
- On Android an input is mixed at the context's channel count before it is up- or down-mixed to
`channelCount`, so in a mono context a stereo source reaches the worklet as its mono mix. A node
connected into a worklet input plays only into it, as with `DelayNode`.

## Linux

Expand Down
107 changes: 88 additions & 19 deletions packages/audio-context/index.android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ export class AudioNode extends AudioNodeBase {
}

connect(node: any, output?: number, input?: number) {
if (node instanceof AudioWorkletNode && ((input ?? 0) < 0 || (input ?? 0) >= node.numberOfInputs)) {
throw domError('IndexSizeError', `AudioNode.connect: input ${input ?? 0} is out of range`);
}
const that = this as never as AudioNode & { native: org.nativescript.audiocontext.AudioNode };
const target = node?.native || node;
try {
Expand Down Expand Up @@ -611,6 +614,12 @@ export class OfflineAudioContext extends BaseAudioContext {
private _rendering: Promise<AudioBuffer> | null = null;
private _suspends = new OfflineSuspends();
private _listener: AudioListener | null = null;
private _audioWorklet: AudioWorklet | null = null;

get audioWorklet(): AudioWorklet | undefined {
if (!this._audioWorklet && isWorkerSupported()) this._audioWorklet = new AudioWorklet(nativeCtor_, this);
return this._audioWorklet ?? undefined;
}

static getInstance() {
if (!audioContextInstance) audioContextInstance = org.nativescript.audiocontext.AudioContext.getInstance();
Expand Down Expand Up @@ -689,6 +698,10 @@ export class OfflineAudioContext extends BaseAudioContext {
onComplete(buffer) {
const context = ref.deref();
if (context) {
context._audioWorklet?._scope(false)?.close();
connectedWorkletNodes.forEach((node) => {
if (node.context === context) node._stop();
});
context._setState('closed');
context._suspends.rejectAll(() => domError('InvalidStateError', 'OfflineAudioContext: rendering finished before the suspend'));
}
Expand Down Expand Up @@ -835,17 +848,19 @@ let nextWorkletNode = 1;
// Connected nodes keep playing without a JS reference, as in browsers.
const connectedWorkletNodes = new Set<AudioWorkletNode>();
// The native voice reads the ring until the render thread drops it, a callback after stop().
const stopWorkletNode = (held: { native: org.nativescript.audiocontext.WorkletSourceNode; ring: SharedArrayBuffer }) => {
const stopWorkletNode = (held: { native: org.nativescript.audiocontext.WorkletNode; ring: SharedArrayBuffer }) => {
held.native.stop();
setTimeout(() => held.ring.byteLength, 2000);
};
const workletNodeRegistry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(stopWorkletNode) : null;

type WorkletContext = AudioContext | OfflineAudioContext;

export class AudioWorklet {
private [context_]: AudioContext;
private [context_]: WorkletContext;
private _host: WorkletHost | null = null;

constructor(a?: any, context?: AudioContext) {
constructor(a?: any, context?: WorkletContext) {
if (a !== nativeCtor_ || !context) throw new TypeError('Illegal constructor.');
this[context_] = context;
}
Expand Down Expand Up @@ -873,28 +888,48 @@ export class AudioWorklet {
}
}

const ANDROID_WORKLET_MAX_CHANNELS = 8;

export class AudioWorkletNode extends AudioNode {
readonly port: AudioWorkletPort;
readonly parameters: AudioParamMap<AudioParam>;
[native_]: org.nativescript.audiocontext.WorkletSourceNode;
[native_]: org.nativescript.audiocontext.WorkletNode;
private _ring: SharedArrayBuffer;
private _numberOfInputs: number;
private _numberOfOutputs: number;
private _onprocessorerror: ((event: any) => void) | null = null;

constructor(context: AudioContext, name: string, options: AudioWorkletNodeOptions = {}) {
constructor(context: WorkletContext, name: string, options: AudioWorkletNodeOptions = {}) {
const worklet = context?.audioWorklet;
const resolved = resolveWorkletNodeOptions(worklet?._scope(false), name, options);
const { host, descriptors, numberOfInputs, numberOfOutputs, outputChannelCount, parameterData } = resolved;
if (numberOfInputs > 0) throw domError('NotSupportedError', 'AudioWorkletNode: inputs are not supported on Android');
if (numberOfOutputs !== 1) throw domError('NotSupportedError', 'AudioWorkletNode: Android supports one output');
super(context);
const channels = Math.min(outputChannelCount?.[0] ?? 1, 8);
const layout = workletRingLayout(0, [channels], descriptors.length);
const { host, descriptors, numberOfInputs, numberOfOutputs, parameterData } = resolved;
// Each input sums into channelCount channels.
const inputChannels = Array.from({ length: numberOfInputs }, () => Math.max(1, (options as any).channelCount ?? 2) | 0);
// One input and one output: the output follows the input; otherwise one channel per output.
const outputChannelCount = resolved.outputChannelCount ?? Array.from({ length: numberOfOutputs }, () => (numberOfInputs === 1 && numberOfOutputs === 1 ? inputChannels[0] : 1));
if ([...inputChannels, ...outputChannelCount].some((count) => count > ANDROID_WORKLET_MAX_CHANNELS)) {
throw domError('NotSupportedError', `AudioWorkletNode: at most ${ANDROID_WORKLET_MAX_CHANNELS} channels per input or output on Android`);
}
if (numberOfInputs > 16 || numberOfOutputs > 16) throw domError('NotSupportedError', 'AudioWorkletNode: at most 16 inputs and 16 outputs on Android');
super(context as any);
const layout = workletRingLayout(numberOfInputs, outputChannelCount, descriptors.length);
const ring = createWorkletRing(layout);
const offsets = (Array as any).create('int', 6);
[layout.slotWords, layout.header, layout.outputCounts, layout.outputData[0], layout.paramLengths, layout.paramData].forEach((value, i) => (offsets[i] = value));
const ints = (values: number[]) => {
const array = (Array as any).create('int', values.length);
values.forEach((value, i) => (array[i] = value));
return array;
};
const defaults = (Array as any).create('double', descriptors.length);
descriptors.forEach((d, i) => (defaults[i] = parameterData?.[d.name] ?? d.defaultValue));
const native = AudioContext.getInstance().createWorkletSource(context.native, ring as any, channels, offsets, defaults);
const native = AudioContext.getInstance().createWorklet(
context.native,
ring as any,
ints(inputChannels),
ints(outputChannelCount),
ints([layout.slotWords, layout.header, layout.inputCounts, layout.inputData, layout.outputCounts, layout.paramLengths, layout.paramData]),
ints(layout.outputData),
defaults,
);
if (!native) throw domError('NotSupportedError', 'AudioWorkletNode: the audio engine is unavailable');
const header = new Uint32Array(ring, layout.header * 4, 8);
if (Atomics.load(header, RING_NATIVE_MARK) !== 0x574b4c54) {
Expand All @@ -903,25 +938,53 @@ export class AudioWorkletNode extends AudioNode {
}
this[native_] = native;
this._ring = ring;
this._numberOfInputs = numberOfInputs;
this._numberOfOutputs = numberOfOutputs;
this.parameters = new AudioParamMap(new Map(descriptors.map((d, i) => [d.name, new AudioParam(nativeCtor_, native.getParam(i))])));
const id = nextWorkletNode++;
this.port = new AudioWorkletPort(host, id);
workletNodeRegistry?.register(this, { native, ring }, this);
host.create(this, id, String(name), { ...options, numberOfInputs, numberOfOutputs, outputChannelCount: [channels], parameterData }, { buffer: ring, layout });
host.create(this, id, String(name), { ...options, numberOfInputs, numberOfOutputs, outputChannelCount, parameterData }, { buffer: ring, layout });
}

get native() {
return this[native_];
}

get numberOfInputs() {
return this._numberOfInputs;
}

get numberOfOutputs() {
return this._numberOfOutputs;
}

connect(node: any, output?: number, input?: number) {
if (output !== undefined && (output < 0 || output >= this._numberOfOutputs)) throw domError('IndexSizeError', `AudioWorkletNode.connect: output ${output} is out of range`);
connectedWorkletNodes.add(this);
return super.connect(node, output, input);
}

disconnect(...args: any[]) {
if (args.length === 0) connectedWorkletNodes.delete(this);
return (super.disconnect as any)(...args);
disconnect(destinationOrOutput?: any, output?: number, input?: number) {
const native = this[native_];
const checkOutput = (index: number) => {
if (index < 0 || index >= this._numberOfOutputs) throw domError('IndexSizeError', `AudioWorkletNode.disconnect: output ${index} is out of range`);
};
if (destinationOrOutput === undefined || destinationOrOutput === null) {
connectedWorkletNodes.delete(this);
native.disconnect();
} else if (typeof destinationOrOutput === 'number') {
checkOutput(destinationOrOutput);
native.disconnect(destinationOrOutput);
} else {
const target = destinationOrOutput.native || destinationOrOutput;
if (typeof output !== 'number') native.disconnect(target);
else {
checkOutput(output);
if (typeof input === 'number') native.disconnect(target, output, input);
else native.disconnect(target, output);
}
}
}

get onprocessorerror() {
Expand All @@ -936,14 +999,20 @@ export class AudioWorkletNode extends AudioNode {

/** @internal */
_processorError(message: string) {
// An offline render stops waiting on a failed processor.
this._close();
this.dispatchEvent({ type: 'processorerror', message, error: new Error(message), target: this } as any);
}

private _close() {
Atomics.store(new Uint32Array(this._ring, this._ring.byteLength - 32, 8), RING_CLOSED, 1);
}

/** @internal */
_stop() {
workletNodeRegistry?.unregister(this);
connectedWorkletNodes.delete(this);
Atomics.store(new Uint32Array(this._ring, this._ring.byteLength - 32, 8), RING_CLOSED, 1);
this._close();
stopWorkletNode({ native: this[native_], ring: this._ring });
}
}
Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,9 @@ public void playsQuantaFromTheRingWithParamValues() throws Exception {
AudioContextInstance context = audio.createContextInstance(48000, 0.01);
AnalyserNode analyser = audio.createAnalyser(context);
ByteBuffer ring = ByteBuffer.allocateDirect((HEADER + 8) * 4).order(ByteOrder.LITTLE_ENDIAN);
WorkletSourceNode node = audio.createWorkletSource(context, ring, 1, new int[]{SLOT_WORDS, HEADER, OUTPUT_COUNTS, OUTPUT_DATA, PARAM_LENGTHS, PARAM_DATA}, new double[]{0.25});
WorkletNode node = audio.createWorklet(context, ring, new int[0], new int[]{1}, new int[]{SLOT_WORDS, HEADER, OUTPUT_COUNTS, OUTPUT_DATA, OUTPUT_COUNTS, PARAM_LENGTHS, PARAM_DATA}, new int[]{OUTPUT_DATA}, new double[]{0.25});
Assert.assertNotNull(node);
node.connect(analyser);
Assert.assertEquals("native marks the ring it reads", 0x574B4C54, ring.getInt((HEADER + 5) * 4));
Assert.assertEquals(1, node.getParamCount());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,16 @@ class NativeEngine {
void pushPcmFrames(const std::string &id, const float *interleaved, size_t sampleCount);
void endExternalPcmSource(const std::string &id);

// An AudioWorkletNode's voice over its ring (audio-worklet-ring.ts); offsets are in 4-byte words.
std::string createWorkletSource(float *ring, int channels, int slotWords, int header,
int outputCounts, int outputData, int paramLengths,
int paramData, std::vector<std::string> paramIds);
// An AudioWorkletNode over its ring (audio-worklet-ring.ts); offsets are in 4-byte words.
// Output o plays as voice `id` (o = 0) or `id#o`.
std::string createWorklet(float *ring, const std::vector<int> &inputChannels,
const std::vector<int> &outputChannels, int slotWords, int header,
int inputCounts, int inputData, int outputCounts,
const std::vector<int> &outputData, int paramLengths, int paramData,
std::vector<std::string> paramIds);

// Whether output `output` of worklet `id` is connected; unconnected outputs are silent.
void setWorkletOutputConnected(const std::string &id, int output, bool connected);

#ifdef HAS_OBOE

Expand Down Expand Up @@ -158,6 +164,9 @@ class NativeEngine {
int64_t offlineBaseNs_ = 0;
std::mutex offlineRenderMutex_;
std::vector<float> offlineScratch_;
// Offline: the quantum being rendered and the end of the current render call, in frames.
int64_t offlineFrame_ = 0;
int64_t offlineLimitFrame_ = 0;
// The render clock: CLOCK_MONOTONIC ns for realtime, virtual for offline.
std::atomic<int64_t> nowNs_{0};

Expand Down Expand Up @@ -207,27 +216,48 @@ class NativeEngine {
std::atomic<bool> ended{false};
};

struct WorkletRing {
static constexpr int kWorkletMaxPorts = 16;
static constexpr int kWorkletMaxChannels = 8;

struct WorkletNode {
std::string id;
float *words = nullptr;
std::atomic<uint32_t> *header = nullptr;
int channels = 1;
int slotWords = 0;
int inputCounts = 0;
int inputData = 0;
int outputCounts = 0;
int outputData = 0;
int paramLengths = 0;
int paramData = 0;
int inputs = 0;
int outputs = 0;
int inChannels[kWorkletMaxPorts] = {};
int outChannels[kWorkletMaxPorts] = {};
int outputData[kWorkletMaxPorts] = {};
std::vector<std::string> paramIds;
// Render thread only.
std::vector<float> out;
bool connected[kWorkletMaxPorts] = {};
// The context's channels of each input, a quantum each: inputs x mixChannels x 128.
int mixChannels = 1;
std::vector<float> inMix;
bool inActive[kWorkletMaxPorts] = {};
// The quantum playing: outputs x kWorkletMaxChannels x 128.
std::vector<float> outQ;
int position = 0;
uint64_t nextFrame = 0;
uint32_t lowWater = UINT32_MAX;
uint32_t window = 0;
bool finished = false;
bool drained = false;
bool ended = false;
// Offline sources: requests run ahead of the render to here.
bool requesting = false;
uint64_t requestFrame = 0;
};

struct Voice {
enum Type {
Oscillator, BufferSource, ExternalPCM
Oscillator, BufferSource, ExternalPCM, WorkletOutput
} voiceType;
std::string id;
std::string waveform = "sine";
Expand Down Expand Up @@ -255,7 +285,8 @@ class NativeEngine {
int bufferSampleRate = 0;

std::shared_ptr<ExternalRing> externalRing;
std::shared_ptr<WorkletRing> worklet;
std::shared_ptr<WorkletNode> worklet;
int workletOutput = 0;
std::vector<float> externalPrev;
std::vector<float> externalCurr;
double externalSubPos = 0.0;
Expand All @@ -271,14 +302,27 @@ class NativeEngine {
double delayFrames = 0.0;
// `channels` runs of `size` frames.
std::vector<float> data;
// One render call's input, `channels` runs of `inputStride` frames.
std::vector<float> input;
int inputStride = 0;
};
std::unordered_map<std::string, DelayLine> delays_;
// Voice id -> the DelayNode it plays through.
std::unordered_map<std::string, std::string> voiceDelay_;

// Fills the voice's ExternalRing with worklet quanta until it holds `frames`.
void produceWorkletQuanta(Voice &voice, int frames, int64_t startNs, double frameNs);
std::unordered_map<std::string, std::shared_ptr<WorkletNode>> worklets_;
// Voice id -> the worklet and input it plays into.
std::unordered_map<std::string, std::pair<std::string, int>> voiceWorklet_;

// Pushes a request for the quantum at `frame`, with params from `paramNs`; false if the ring is full.
bool workletPush(WorkletNode &w, uint64_t frame, int64_t paramNs, bool withInputs);
void workletReadSlot(WorkletNode &w, uint32_t read);
void workletSilence(WorkletNode &w);
// Realtime: pushes the quantum just filled and plays the newest response.
void workletEndQuantum(WorkletNode &w, int64_t paramNs);
// Offline: renders the quantum at offlineFrame_ into outQ, waiting for the Worker.
void workletRenderOffline(WorkletNode &w);
void removeWorklet(const std::string &id);

std::unordered_map<std::string, BufferData> audioBuffers_;
std::unordered_map<std::string, Voice> audioVoices_;
Expand Down Expand Up @@ -339,7 +383,8 @@ class NativeEngine {
CMD_SET_PANNER_HRIR,
CMD_SET_PANNER_PARTITION_SIZE,
CMD_CREATE_WORKLET,
CMD_CREATE_DELAY
CMD_CREATE_DELAY,
CMD_WORKLET_OUTPUT
};

struct Command {
Expand Down Expand Up @@ -400,7 +445,7 @@ class NativeEngine {
std::shared_ptr<std::vector<int16_t>> pcm;
std::shared_ptr<std::vector<float>> pcmFloat;
std::shared_ptr<ExternalRing> externalRing;
std::shared_ptr<WorkletRing> worklet;
std::shared_ptr<WorkletNode> worklet;
std::shared_ptr<std::vector<float>> hrirLeft;
std::shared_ptr<std::vector<float>> hrirRight;
bool clearHrir = false;
Expand Down
Loading
Loading