diff --git a/packages/audio-context/README.md b/packages/audio-context/README.md index f668e5774..113359221 100644 --- a/packages/audio-context/README.md +++ b/packages/audio-context/README.md @@ -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 diff --git a/packages/audio-context/index.android.ts b/packages/audio-context/index.android.ts index 8f3f8d796..784664650 100644 --- a/packages/audio-context/index.android.ts +++ b/packages/audio-context/index.android.ts @@ -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 { @@ -611,6 +614,12 @@ export class OfflineAudioContext extends BaseAudioContext { private _rendering: Promise | 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(); @@ -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')); } @@ -835,17 +848,19 @@ let nextWorkletNode = 1; // Connected nodes keep playing without a JS reference, as in browsers. const connectedWorkletNodes = new Set(); // 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; } @@ -873,28 +888,48 @@ export class AudioWorklet { } } +const ANDROID_WORKLET_MAX_CHANNELS = 8; + export class AudioWorkletNode extends AudioNode { readonly port: AudioWorkletPort; readonly parameters: AudioParamMap; - [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) { @@ -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() { @@ -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 }); } } diff --git a/packages/audio-context/platforms/android/audiocontext-release.aar b/packages/audio-context/platforms/android/audiocontext-release.aar index 10cbce004..33eb61759 100644 Binary files a/packages/audio-context/platforms/android/audiocontext-release.aar and b/packages/audio-context/platforms/android/audiocontext-release.aar differ diff --git a/packages/audio-context/src-native/android/audiocontext/src/androidTest/java/org/nativescript/audiocontext/WorkletSourceInstrumentedTest.java b/packages/audio-context/src-native/android/audiocontext/src/androidTest/java/org/nativescript/audiocontext/WorkletSourceInstrumentedTest.java index e44dd592c..50b3ffcf7 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/androidTest/java/org/nativescript/audiocontext/WorkletSourceInstrumentedTest.java +++ b/packages/audio-context/src-native/android/audiocontext/src/androidTest/java/org/nativescript/audiocontext/WorkletSourceInstrumentedTest.java @@ -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()); diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.h b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.h index dd0efc8cf..ec51e1151 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.h +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_context.h @@ -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 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 &inputChannels, + const std::vector &outputChannels, int slotWords, int header, + int inputCounts, int inputData, int outputCounts, + const std::vector &outputData, int paramLengths, int paramData, + std::vector 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 @@ -158,6 +164,9 @@ class NativeEngine { int64_t offlineBaseNs_ = 0; std::mutex offlineRenderMutex_; std::vector 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 nowNs_{0}; @@ -207,27 +216,48 @@ class NativeEngine { std::atomic ended{false}; }; - struct WorkletRing { + static constexpr int kWorkletMaxPorts = 16; + static constexpr int kWorkletMaxChannels = 8; + + struct WorkletNode { + std::string id; float *words = nullptr; std::atomic *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 paramIds; // Render thread only. - std::vector out; + bool connected[kWorkletMaxPorts] = {}; + // The context's channels of each input, a quantum each: inputs x mixChannels x 128. + int mixChannels = 1; + std::vector inMix; + bool inActive[kWorkletMaxPorts] = {}; + // The quantum playing: outputs x kWorkletMaxChannels x 128. + std::vector 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"; @@ -255,7 +285,8 @@ class NativeEngine { int bufferSampleRate = 0; std::shared_ptr externalRing; - std::shared_ptr worklet; + std::shared_ptr worklet; + int workletOutput = 0; std::vector externalPrev; std::vector externalCurr; double externalSubPos = 0.0; @@ -271,14 +302,27 @@ class NativeEngine { double delayFrames = 0.0; // `channels` runs of `size` frames. std::vector data; + // One render call's input, `channels` runs of `inputStride` frames. std::vector input; + int inputStride = 0; }; std::unordered_map delays_; // Voice id -> the DelayNode it plays through. std::unordered_map 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> worklets_; + // Voice id -> the worklet and input it plays into. + std::unordered_map> 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 audioBuffers_; std::unordered_map audioVoices_; @@ -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 { @@ -400,7 +445,7 @@ class NativeEngine { std::shared_ptr> pcm; std::shared_ptr> pcmFloat; std::shared_ptr externalRing; - std::shared_ptr worklet; + std::shared_ptr worklet; std::shared_ptr> hrirLeft; std::shared_ptr> hrirRight; bool clearHrir = false; diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_jni.cpp b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_jni.cpp index 5d1c3aa7f..6ef67ea4c 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_jni.cpp +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_jni.cpp @@ -298,8 +298,9 @@ Java_org_nativescript_audiocontext_AudioContext_nativeCancelAndHoldPannerEvents( } } +// The long name: a short one would also bind the (voice, gain, output, input) overload. extern "C" JNIEXPORT void JNICALL -Java_org_nativescript_audiocontext_AudioContext_nativeAttachGain(JNIEnv *env, jobject thiz, +Java_org_nativescript_audiocontext_AudioContext_nativeAttachGain__Ljava_lang_String_2Ljava_lang_String_2(JNIEnv *env, jobject thiz, jstring jvoiceId, jstring jgainId) { NativeEngine::Scope scope__(engineFor(env, jvoiceId)); @@ -2055,18 +2056,24 @@ Java_org_nativescript_audiocontext_AudioContext_nativeEndExternalPcmSource(JNIEn env->ReleaseStringUTFChars(jid, idChars); } +static std::vector intArray(JNIEnv *env, jintArray array) { + std::vector values(array ? static_cast(env->GetArrayLength(array)) : 0); + if (!values.empty()) env->GetIntArrayRegion(array, 0, static_cast(values.size()), reinterpret_cast(values.data())); + return values; +} + +// layout: slotWords, header, inputCounts, inputData, outputCounts, paramLengths, paramData. extern "C" JNIEXPORT jstring JNICALL -Java_org_nativescript_audiocontext_AudioContext_nativeCreateWorkletSource(JNIEnv *env, jobject thiz, jstring jcontextId, - jobject ring, jint channels, - jint slotWords, jint header, - jint outputCounts, jint outputData, - jint paramLengths, jint paramData, - jobjectArray paramIds) { +Java_org_nativescript_audiocontext_AudioContext_nativeCreateWorklet(JNIEnv *env, jobject thiz, jstring jcontextId, + jobject ring, jintArray jinputChannels, + jintArray joutputChannels, jintArray jlayout, + jintArray joutputData, jobjectArray paramIds) { NativeEngine::Scope scope__(engineFor(env, jcontextId)); if (!ring) return nullptr; auto *words = static_cast(env->GetDirectBufferAddress(ring)); jlong capacity = env->GetDirectBufferCapacity(ring); - if (!words || capacity < (static_cast(header) + 8) * 4) return nullptr; + std::vector layout = intArray(env, jlayout); + if (!words || layout.size() < 7 || capacity < (static_cast(layout[1]) + 8) * 4) return nullptr; std::vector ids; jsize count = paramIds ? env->GetArrayLength(paramIds) : 0; for (jsize i = 0; i < count; i++) { @@ -2076,8 +2083,20 @@ Java_org_nativescript_audiocontext_AudioContext_nativeCreateWorkletSource(JNIEnv if (chars) env->ReleaseStringUTFChars(id, chars); if (id) env->DeleteLocalRef(id); } - std::string id = NativeEngine::getInstance().createWorkletSource( - words, channels, slotWords, header, outputCounts, outputData, paramLengths, paramData, - std::move(ids)); + std::string id = NativeEngine::getInstance().createWorklet( + words, intArray(env, jinputChannels), intArray(env, joutputChannels), layout[0], layout[1], + layout[2], layout[3], layout[4], intArray(env, joutputData), layout[5], layout[6], std::move(ids)); return id.empty() ? nullptr : env->NewStringUTF(id.c_str()); } + +extern "C" JNIEXPORT void JNICALL +Java_org_nativescript_audiocontext_AudioContext_nativeSetWorkletOutputConnected(JNIEnv *env, jobject thiz, + jstring jid, jint output, + jboolean connected) { + NativeEngine::Scope scope__(engineFor(env, jid)); + if (!jid) return; + const char *id = env->GetStringUTFChars(jid, nullptr); + if (!id) return; + NativeEngine::getInstance().setWorkletOutputConnected(id, (int) output, connected == JNI_TRUE); + env->ReleaseStringUTFChars(jid, id); +} diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_offline.cpp b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_offline.cpp index d1eeb0c7b..01a578ece 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_offline.cpp +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_offline.cpp @@ -15,8 +15,10 @@ void NativeEngine::renderOfflineFrames(int64_t startFrame, int frames, const std const int channels = std::max(1, streamChannels_); const double frameNs = 1e9 / static_cast(streamSampleRate_ > 0 ? streamSampleRate_ : 48000); offlineScratch_.resize(static_cast(kQuantum * channels)); + offlineLimitFrame_ = startFrame + frames; for (int done = 0; done < frames; done += kQuantum) { const int64_t frame = startFrame + done; + offlineFrame_ = frame; nowNs_.store(offlineBaseNs_ + std::llround(static_cast(frame) * frameNs), std::memory_order_relaxed); onAudioReady(nullptr, offlineScratch_.data(), kQuantum); const int n = std::min(kQuantum, frames - done); diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_render.cpp b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_render.cpp index 044bc195d..40ed5372f 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_render.cpp +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_render.cpp @@ -513,10 +513,17 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n break; } case NativeEngine::CMD_ATTACH_GAIN: { + if (!c.gainId.empty() && worklets_.count(c.gainId)) { + voiceWorklet_[c.id] = {c.gainId, c.inputIndex}; + voiceDelay_.erase(c.id); + break; + } if (!c.gainId.empty() && delays_.count(c.gainId)) { voiceDelay_[c.id] = c.gainId; + voiceWorklet_.erase(c.id); break; } + if (c.gainId.empty()) voiceWorklet_.erase(c.id); auto vit = audioVoices_.find(c.id); std::string prevGainId; bool voiceExists = vit != audioVoices_.end(); @@ -1341,6 +1348,11 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n break; } case NativeEngine::CMD_STOP_TRACK: { + if (worklets_.count(c.id)) { + removeWorklet(c.id); + break; + } + voiceWorklet_.erase(c.id); auto vit = audioVoices_.find(c.id); bool existed = vit != audioVoices_.end(); size_t gainOutputsForVoice = 0; @@ -1370,9 +1382,6 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n vit->second.filterId.c_str(), gainOutputsForVoice, pannerOutputsForVoice, filterOutputsForVoice); } - if (existed && vit->second.worklet) { - vit->second.worklet->header[3].store(1, std::memory_order_release); - } audioVoices_.erase(c.id); break; } @@ -1450,27 +1459,35 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n break; } case NativeEngine::CMD_CREATE_WORKLET: { - if (!c.externalRing || !c.worklet) break; - Voice v; - v.voiceType = Voice::ExternalPCM; - v.id = c.id; - v.playing = true; - v.bufferChannels = c.channels; - v.bufferSampleRate = streamSampleRate_ > 0 ? streamSampleRate_ : 48000; - v.increment = 1.0; - v.externalRing = c.externalRing; - v.worklet = c.worklet; - v.externalPrev.assign((size_t) v.bufferChannels, 0.0f); - v.externalCurr.assign((size_t) v.bufferChannels, 0.0f); - auto vg = voiceGainByOutput_.find(v.id); - if (vg != voiceGainByOutput_.end() && !vg->second.empty()) { - auto mapIt = vg->second.find(0); - if (mapIt == vg->second.end()) mapIt = vg->second.begin(); - v.gainId = mapIt->second; - auto git = gains_.find(v.gainId); - if (git != gains_.end()) v.gain = git->second; + if (!c.worklet) break; + auto worklet = c.worklet; + worklets_[worklet->id] = worklet; + for (int o = 0; o < worklet->outputs; o++) { + Voice v; + v.voiceType = Voice::WorkletOutput; + v.id = o == 0 ? worklet->id : worklet->id + "#" + std::to_string(o); + v.playing = true; + v.bufferChannels = worklet->outChannels[o]; + v.bufferSampleRate = streamSampleRate_ > 0 ? streamSampleRate_ : 48000; + v.worklet = worklet; + v.workletOutput = o; + auto vg = voiceGainByOutput_.find(v.id); + if (vg != voiceGainByOutput_.end() && !vg->second.empty()) { + auto mapIt = vg->second.find(0); + if (mapIt == vg->second.end()) mapIt = vg->second.begin(); + v.gainId = mapIt->second; + auto git = gains_.find(v.gainId); + if (git != gains_.end()) v.gain = git->second; + } + audioVoices_[v.id] = std::move(v); + } + break; + } + case NativeEngine::CMD_WORKLET_OUTPUT: { + auto wit = worklets_.find(c.id); + if (wit != worklets_.end() && c.outputIndex >= 0 && c.outputIndex < wit->second->outputs) { + wit->second->connected[c.outputIndex] = c.loop; } - audioVoices_[c.id] = std::move(v); break; } case NativeEngine::CMD_CREATE_EXTERNAL_PCM: { @@ -1701,18 +1718,13 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n std::array pannerNodeByOutput{}; const std::string *playbackRatePrimaryId = nullptr; NativeEngine::DelayLine *delay = nullptr; + // The worklet input this voice plays into instead of the output. + NativeEngine::WorkletNode *into = nullptr; + int intoInput = 0; + // Routed into a worklet that is gone. + bool dropped = false; }; - { - const int64_t workletStartNs = nowNs_.load(std::memory_order_relaxed) + 4; - const double workletFrameNs = 1000000000.0 / (streamSampleRate_ > 0 ? streamSampleRate_ : 48000); - for (auto &kv: audioVoices_) { - if (kv.second.worklet && kv.second.playing) { - produceWorkletQuanta(kv.second, numFrames, workletStartNs, workletFrameNs); - } - } - } - std::vector localVoices; localVoices.reserve(audioVoices_.size()); for (auto &kv: audioVoices_) { @@ -1798,6 +1810,17 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n auto lineIt = delays_.find(delayIt->second); if (lineIt != delays_.end()) view.delay = &lineIt->second; } + auto intoIt = voiceWorklet_.find(voice.id); + if (intoIt != voiceWorklet_.end()) { + auto nodeIt = worklets_.find(intoIt->second.first); + if (nodeIt != worklets_.end() && intoIt->second.second >= 0 && + intoIt->second.second < nodeIt->second->inputs) { + view.into = nodeIt->second.get(); + view.intoInput = intoIt->second.second; + } else { + view.dropped = true; + } + } localVoices.push_back(std::move(view)); } @@ -2372,12 +2395,38 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n if (collectAnalyser) analyserMono.assign((size_t) numFrames, 0.0f); const double delayRate = streamSampleRate_ > 0 ? static_cast(streamSampleRate_) : 48000.0; - // A voice routed through a DelayNode feeds its line instead of the output. - auto emitVoice = [](const ActiveVoiceView &view, int channel, float sample, float &mixed) { - if (view.delay && channel < view.delay->channels) view.delay->input[static_cast(channel)] += sample; - else mixed += sample; + for (auto &kv: delays_) { + NativeEngine::DelayLine &d = kv.second; + const size_t need = static_cast(d.channels) * static_cast(numFrames); + if (d.input.size() < need) d.input.assign(need, 0.0f); + d.inputStride = numFrames; + } + // Offline renders one quantum per call, so a worklet's position is the frame. + auto workletAt = [&](const NativeEngine::WorkletNode &w, int frame) { + return static_cast(offline_ ? frame : w.position); + }; + // A voice routed into a worklet input or through a DelayNode feeds it instead of the output. + auto emitVoice = [&](const ActiveVoiceView &view, int channel, int frame, float sample, float &mixed) { + if (view.dropped) return; + if (view.into) { + NativeEngine::WorkletNode &w = *view.into; + if (channel < w.mixChannels) { + w.inMix[static_cast((view.intoInput * w.mixChannels + channel) * 128) + workletAt(w, frame)] += sample; + w.inActive[view.intoInput] = true; + } + } else if (view.delay && channel < view.delay->channels) { + view.delay->input[static_cast(channel * view.delay->inputStride + frame)] += sample; + } else { + mixed += sample; + } }; + std::vector worklets; + worklets.reserve(worklets_.size()); + for (auto &kv: worklets_) worklets.push_back(kv.second.get()); + + // Mixes `pass`'s voices into `out`; realtime worklets step a frame at a time. + auto renderPass = [&](const std::vector &pass) { for (int frame = 0; frame < numFrames; ++frame) { pannerCutoffByBiquad.clear(); pannerFrameCache.clear(); @@ -2385,7 +2434,8 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n hrtfOutputCache.clear(); for (int ch = 0; ch < channels; ++ch) { float mixed = 0.0f; - for (const auto &voiceView: localVoices) { + for (const ActiveVoiceView *voiceViewPtr: pass) { + const ActiveVoiceView &voiceView = *voiceViewPtr; Voice &v = *voiceView.voice; const BufferData *voiceBuffer = voiceView.bufferData; const auto *gainRoute = voiceView.gainRoute; @@ -2393,6 +2443,13 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n const auto *pannerRoute = voiceView.pannerRoute; const std::string *playbackRatePrimaryId = voiceView.playbackRatePrimaryId; if (!v.playing) continue; + if (v.voiceType == Voice::WorkletOutput) { + if (!v.worklet || v.worklet->ended) { + v.playing = false; + continue; + } + if (!v.worklet->connected[v.workletOutput]) continue; + } if (v.startAtNs > 0 || v.stopAtNs > 0) { auto frameNs = audioStartNs + static_cast(frame * sampleDurationNs); if (v.stopAtNs > 0 && frameNs >= v.stopAtNs) { @@ -2515,25 +2572,25 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n float voiceOut = static_cast(s * monoGain); voiceOut = applyDynamicsCompressorForGain(effGainId, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } else { double g = static_cast(scheduled) * distanceAtt; if (ch == 0) { float voiceOut = static_cast(s * g * leftGain); voiceOut = applyDynamicsCompressorForGain(effGainId, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } else if (ch == 1) { float voiceOut = static_cast(s * g * rightGain); voiceOut = applyDynamicsCompressorForGain(effGainId, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } else { double avg = 0.5 * (leftGain + rightGain); float voiceOut = static_cast(s * g * avg); voiceOut = applyDynamicsCompressorForGain(effGainId, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } } if (ch == channels - 1) { @@ -2541,7 +2598,8 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n if (v.phase >= 1.0) v.phase -= 1.0; } } else if (v.voiceType == Voice::BufferSource || - v.voiceType == Voice::ExternalPCM) { + v.voiceType == Voice::ExternalPCM || + v.voiceType == Voice::WorkletOutput) { int bufChannels = 1; int bufFrames = 0; int chIdx = ch; @@ -2550,6 +2608,8 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n int idx0_dbg = 0; int idx1_dbg = 0; const BufferData *bd_dbg = nullptr; + // A worklet output's quantum at this frame, channel c at c * 128. + const float *workletFrame = nullptr; if (v.voiceType == Voice::BufferSource) { if (!voiceBuffer) continue; @@ -2621,6 +2681,24 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n } sample = fs0 * (1.0f - static_cast(frac)) + fs1 * static_cast(frac); + } else if (v.voiceType == Voice::WorkletOutput) { + const NativeEngine::WorkletNode &w = *v.worklet; + bufChannels = w.outChannels[v.workletOutput]; + bufFrames = INT32_MAX; + if (bufChannels == 1) chIdx = 0; + else if (bufChannels >= channels) chIdx = ch; + else chIdx = ch % bufChannels; + workletFrame = w.outQ.data() + + static_cast(v.workletOutput * NativeEngine::kWorkletMaxChannels * 128) + + workletAt(w, frame); + if (channels == 1 && bufChannels > 1) { + // Down-mixes by averaging, as Web Audio's "speakers" do. + float sum = 0.0f; + for (int c = 0; c < bufChannels; c++) sum += workletFrame[c * 128]; + sample = sum / static_cast(bufChannels); + } else { + sample = workletFrame[chIdx * 128]; + } } else /* ExternalPCM */ { auto &ring = v.externalRing; if (!ring) continue; @@ -2767,6 +2845,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n fs1 * static_cast(frac); } + if (workletFrame) return workletFrame[inputChannelIndex * 128]; auto &ring = v.externalRing; if (!ring || !v.externalPrimed || bufChannels <= 0) return 0.0f; size_t safeChannel = static_cast(inputChannelIndex); @@ -2936,7 +3015,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n float voiceOut = static_cast(sample * monoGain); voiceOut = applyDynamicsCompressorForGain(effGainId3, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } else { double g = static_cast(scheduled) * distanceAtt; if (stereoInput && !treatStereoAsMono) { @@ -2950,7 +3029,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n float voiceOut = static_cast(outputL * g); voiceOut = applyDynamicsCompressorForGain(effGainId3, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } else if (ch == 1) { double outputR = inputRight; if (hasResolvedPanner) { @@ -2961,20 +3040,20 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n float voiceOut = static_cast(outputR * g); voiceOut = applyDynamicsCompressorForGain(effGainId3, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } else { double avg = 0.5 * (leftGain + rightGain); float voiceOut = static_cast(sample * g * avg); voiceOut = applyDynamicsCompressorForGain(effGainId3, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } } else if (useHrtfConvolution) { if (ch <= 1) { float voiceOut = static_cast(sample * g); voiceOut = applyDynamicsCompressorForGain(effGainId3, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } else { auto hrtfIt = hrtfOutputCache.find(v.id); float hrtfAvg = sample; @@ -2985,24 +3064,24 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n float voiceOut = static_cast(hrtfAvg * g); voiceOut = applyDynamicsCompressorForGain(effGainId3, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } } else if (ch == 0) { float voiceOut = static_cast(sample * g * leftGain); voiceOut = applyDynamicsCompressorForGain(effGainId3, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } else if (ch == 1) { float voiceOut = static_cast(sample * g * rightGain); voiceOut = applyDynamicsCompressorForGain(effGainId3, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } else { double avg = 0.5 * (leftGain + rightGain); float voiceOut = static_cast(sample * g * avg); voiceOut = applyDynamicsCompressorForGain(effGainId3, ch, frame, voiceOut); - emitVoice(voiceView, ch, voiceOut, mixed); + emitVoice(voiceView, ch, frame, voiceOut, mixed); } } @@ -3022,7 +3101,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n if (v.loop) v.position = std::fmod(v.position, bufFrames); else v.playing = false; } - } else /* ExternalPCM */ { + } else if (v.voiceType == Voice::ExternalPCM) { auto &ring = v.externalRing; if (ring && v.externalPrimed && bufChannels > 0) { v.externalSubPos += v.increment; @@ -3055,6 +3134,72 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n } + out[frame * channels + ch] += mixed; + } + if (!offline_) { + for (NativeEngine::WorkletNode *w: worklets) { + if (++w->position >= 128) { + workletEndQuantum(*w, audioStartNs + static_cast((frame + 1) * sampleDurationNs)); + } + } + } + } + }; + + std::vector allViews; + allViews.reserve(localVoices.size()); + for (auto &view: localVoices) allViews.push_back(&view); + if (!offline_) { + renderPass(allViews); + } else { + // Offline output is sample-exact: a worklet with inputs runs once every voice feeding it has. + std::vector pending; + for (NativeEngine::WorkletNode *w: worklets) { + if (w->inputs == 0) workletRenderOffline(*w); + else pending.push_back(w); + } + auto isPending = [&](const NativeEngine::WorkletNode *w) { + return std::find(pending.begin(), pending.end(), w) != pending.end(); + }; + auto ownerOf = [](const ActiveVoiceView *view) -> NativeEngine::WorkletNode * { + const Voice &v = *view->voice; + return v.voiceType == Voice::WorkletOutput ? v.worklet.get() : nullptr; + }; + std::vector pass; + for (ActiveVoiceView *view: allViews) { + if (!isPending(ownerOf(view))) pass.push_back(view); + } + renderPass(pass); + while (!pending.empty()) { + std::vector ready; + for (NativeEngine::WorkletNode *w: pending) { + bool waiting = false; + for (ActiveVoiceView *view: allViews) { + NativeEngine::WorkletNode *owner = ownerOf(view); + if (view->into == w && owner != w && isPending(owner)) { + waiting = true; + break; + } + } + if (!waiting) ready.push_back(w); + } + // A cycle: run what's left with the inputs it has. + if (ready.empty()) ready = pending; + for (NativeEngine::WorkletNode *w: ready) { + workletRenderOffline(*w); + pending.erase(std::find(pending.begin(), pending.end(), w)); + } + pass.clear(); + for (ActiveVoiceView *view: allViews) { + if (std::find(ready.begin(), ready.end(), ownerOf(view)) != ready.end()) pass.push_back(view); + } + renderPass(pass); + } + } + + for (int frame = 0; frame < numFrames; ++frame) { + for (int ch = 0; ch < channels; ++ch) { + float mixed = out[frame * channels + ch]; for (auto &kv: delays_) { NativeEngine::DelayLine &d = kv.second; const int lineChannels = std::min(d.channels, channels); @@ -3064,8 +3209,9 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n d.delayFrames = std::max(0.0, std::min(seconds * delayRate, static_cast(d.size - 2))); } float *line = d.data.data() + static_cast(ch) * d.size; - line[d.writePos] = d.input[static_cast(ch)]; - d.input[static_cast(ch)] = 0.0f; + float &input = d.input[static_cast(ch * d.inputStride + frame)]; + line[d.writePos] = input; + input = 0.0f; double readPos = d.writePos - d.delayFrames; if (readPos < 0.0) readPos += d.size; const int i0 = static_cast(readPos); @@ -3137,11 +3283,13 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n } for (const auto &voiceId: stoppedVoices) { - auto vit = audioVoices_.find(voiceId); - if (vit != audioVoices_.end() && vit->second.worklet) { - vit->second.worklet->header[3].store(1, std::memory_order_release); - } audioVoices_.erase(voiceId); + voiceWorklet_.erase(voiceId); + } + for (NativeEngine::WorkletNode *w: worklets) { + if (!w->ended) continue; + std::string id = w->id; + removeWorklet(id); } queueEnded(stoppedVoices); diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_worklet.cpp b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_worklet.cpp index b56e5d467..a5293ea11 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_worklet.cpp +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_worklet.cpp @@ -1,148 +1,277 @@ -// AudioWorkletNode sources: the C++ side of crates/audio-context-napi/src/worklet.rs's ring. +// AudioWorkletNode: the C++ side of crates/audio-context-napi/src/worklet.rs's ring. #include "audio_context.h" #include "audio_internal.h" #include +#include +#include #include +#include namespace { constexpr int kQuantum = 128; constexpr uint32_t kSlots = 64; constexpr uint32_t kMaxBacklog = 48; constexpr uint32_t kShrinkWindow = 128; -constexpr int kMaxChannels = 8; +// Offline: a Worker answering nothing for this long renders silence. +constexpr auto kOfflineStall = std::chrono::seconds(5); // Header words after the slots (audio-worklet-ring.ts). enum { REQUESTED = 0, DONE = 1, READ = 2, CLOSED = 3, NATIVE_MARK = 5 }; enum { ALIVE = 2 }; + +std::string outputVoiceId(const std::string &id, int output) { + return output == 0 ? id : id + "#" + std::to_string(output); +} } -std::string NativeEngine::createWorkletSource(float *ring, int channels, int slotWords, int header, - int outputCounts, int outputData, int paramLengths, - int paramData, std::vector paramIds) { - if (!ring) return ""; - auto worklet = std::make_shared(); - worklet->words = ring; - worklet->header = reinterpret_cast *>(reinterpret_cast(ring) + header); - worklet->channels = std::max(1, std::min(channels, kMaxChannels)); - worklet->slotWords = slotWords; - worklet->outputCounts = outputCounts; - worklet->outputData = outputData; - worklet->paramLengths = paramLengths; - worklet->paramData = paramData; - worklet->paramIds = std::move(paramIds); - worklet->out.assign(static_cast(worklet->channels * kQuantum), 0.0f); +std::string NativeEngine::createWorklet(float *ring, const std::vector &inputChannels, + const std::vector &outputChannels, int slotWords, + int header, int inputCounts, int inputData, + int outputCounts, const std::vector &outputData, + int paramLengths, int paramData, + std::vector paramIds) { + const int inputs = static_cast(inputChannels.size()); + const int outputs = static_cast(outputChannels.size()); + if (!ring || inputs > kWorkletMaxPorts || outputs > kWorkletMaxPorts || inputs + outputs == 0 || + outputData.size() != outputChannels.size()) { + return ""; + } + auto w = std::make_shared(); + w->id = genId(); + w->words = ring; + w->header = reinterpret_cast *>(reinterpret_cast(ring) + header); + w->slotWords = slotWords; + w->inputCounts = inputCounts; + w->inputData = inputData; + w->outputCounts = outputCounts; + w->paramLengths = paramLengths; + w->paramData = paramData; + w->inputs = inputs; + w->outputs = outputs; + for (int i = 0; i < inputs; i++) w->inChannels[i] = std::max(1, std::min(inputChannels[i], kWorkletMaxChannels)); + for (int o = 0; o < outputs; o++) { + w->outChannels[o] = std::max(1, std::min(outputChannels[o], kWorkletMaxChannels)); + w->outputData[o] = outputData[o]; + } + w->paramIds = std::move(paramIds); +#ifdef HAS_OBOE + w->mixChannels = std::max(1, std::min(streamChannels_, kWorkletMaxChannels)); +#endif + w->inMix.assign(static_cast(std::max(inputs, 1) * w->mixChannels * kQuantum), 0.0f); + w->outQ.assign(static_cast(std::max(outputs, 1) * kWorkletMaxChannels * kQuantum), 0.0f); // Lets JS check the runtime handed over the SharedArrayBuffer itself, not a copy. - worklet->header[NATIVE_MARK].store(0x574B4C54u, std::memory_order_release); - - auto external = std::make_shared(); - external->capacity = 1u << 13; - external->mask = external->capacity - 1; - external->channels = worklet->channels; - external->data.assign(static_cast(external->capacity) * worklet->channels, 0.0f); + w->header[NATIVE_MARK].store(0x574B4C54u, std::memory_order_release); - std::string id = genId(); + std::string id = w->id; Command cmd; cmd.type = CMD_CREATE_WORKLET; cmd.id = id; - cmd.channels = worklet->channels; - cmd.externalRing = external; - cmd.worklet = worklet; + cmd.worklet = std::move(w); enqueueCommand(std::move(cmd)); return id; } +void NativeEngine::setWorkletOutputConnected(const std::string &id, int output, bool connected) { + Command cmd; + cmd.type = CMD_WORKLET_OUTPUT; + cmd.id = id; + cmd.outputIndex = output; + cmd.loop = connected; + enqueueCommand(std::move(cmd)); +} + +void NativeEngine::removeWorklet(const std::string &id) { + auto it = worklets_.find(id); + if (it == worklets_.end()) return; + WorkletNode &w = *it->second; + w.header[CLOSED].store(1, std::memory_order_release); + // Voices routed into it stay routed, and silent. + for (int o = 0; o < w.outputs; o++) audioVoices_.erase(outputVoiceId(id, o)); + worklets_.erase(it); +} + static float paramValueAt(const std::vector *events, int64_t ns, double fallback) { return events ? getScheduledGainValueAt(*events, ns, fallback) : static_cast(fallback); } -void NativeEngine::produceWorkletQuanta(Voice &voice, int frames, int64_t startNs, double frameNs) { - if (!voice.worklet || !voice.externalRing) return; - WorkletRing &w = *voice.worklet; - ExternalRing &ring = *voice.externalRing; - if (ring.ended.load(std::memory_order_acquire)) return; - uint32_t write = ring.writeIdx.load(std::memory_order_relaxed); - uint32_t buffered = write - ring.readIdx.load(std::memory_order_acquire); - if (buffered >= static_cast(frames)) return; - - std::lock_guard lock(scheduledEventsMutex_); - while (buffered < static_cast(frames) && ring.capacity - buffered >= kQuantum) { - auto quantumNs = startNs + static_cast(buffered * frameNs); - if (!w.finished) { - uint32_t requested = w.header[REQUESTED].load(std::memory_order_relaxed); - uint32_t read = w.header[READ].load(std::memory_order_acquire); - if (requested - read < kSlots) { - float *slot = w.words + (requested % kSlots) * static_cast(w.slotWords); - auto *words = reinterpret_cast(slot); - double frame = static_cast(w.nextFrame); - std::memcpy(slot, &frame, sizeof frame); - words[ALIVE] = 1; - words[w.outputCounts] = static_cast(w.channels); - for (size_t p = 0; p < w.paramIds.size(); p++) { - const std::string &id = w.paramIds[p]; - auto git = gains_.find(id); - double fallback = git != gains_.end() ? git->second : 0.0; - auto eit = scheduledGainEvents_.find(id); - const std::vector *events = - eit != scheduledGainEvents_.end() && !eit->second.empty() ? &eit->second : nullptr; - float *values = slot + w.paramData + p * kQuantum; - uint32_t length = 1; - values[0] = paramValueAt(events, quantumNs, fallback); - if (events && (*events)[0].rate == RATE_A) { - for (int i = 1; i < kQuantum; i++) { - values[i] = paramValueAt(events, quantumNs + static_cast(i * frameNs), fallback); - if (values[i] != values[0]) length = kQuantum; - } - } - words[w.paramLengths + p] = length; +bool NativeEngine::workletPush(WorkletNode &w, uint64_t frame, int64_t paramNs, bool withInputs) { + uint32_t requested = w.header[REQUESTED].load(std::memory_order_relaxed); + uint32_t read = w.header[READ].load(std::memory_order_acquire); + if (requested - read >= kSlots) return false; + float *slot = w.words + (requested % kSlots) * static_cast(w.slotWords); + auto *words = reinterpret_cast(slot); + double frameValue = static_cast(frame); + std::memcpy(slot, &frameValue, sizeof frameValue); + words[ALIVE] = 1; + + // Web Audio "speakers" mixing from the context's channels to the input's channelCount. + const int have = w.mixChannels; + for (int i = 0; i < w.inputs; i++) { + const int want = w.inChannels[i]; + const uint32_t count = withInputs && w.inActive[i] ? static_cast(want) : 0u; + words[w.inputCounts + i] = count; + const float *mix = w.inMix.data() + static_cast(i * have * kQuantum); + for (int c = 0; c < static_cast(count); c++) { + float *dst = slot + w.inputData + (i * kWorkletMaxChannels + c) * kQuantum; + if (want == 1 && have > 1) { + const float scale = 1.0f / static_cast(have); + for (int k = 0; k < kQuantum; k++) { + float sum = 0.0f; + for (int h = 0; h < have; h++) sum += mix[h * kQuantum + k]; + dst[k] = sum * scale; } - w.header[REQUESTED].store(requested + 1, std::memory_order_release); + } else if (c < have) { + std::memcpy(dst, mix + c * kQuantum, kQuantum * sizeof(float)); + } else if (have == 1) { + std::memcpy(dst, mix, kQuantum * sizeof(float)); + } else { + std::memset(dst, 0, kQuantum * sizeof(float)); } } + } + for (int o = 0; o < w.outputs; o++) words[w.outputCounts + o] = static_cast(w.outChannels[o]); - uint32_t read = w.header[READ].load(std::memory_order_relaxed); - uint32_t done = w.header[DONE].load(std::memory_order_acquire); - uint32_t backlog = done - read; - if (backlog > kMaxBacklog) { - read = done - kMaxBacklog; - } else { - uint32_t low = std::min(w.lowWater, backlog); - if (++w.window >= kShrinkWindow) { - if (low >= 2) read += std::max((low - 1) / 2, 1u); - w.window = 0; - w.lowWater = UINT32_MAX; - } else { - w.lowWater = low; + if (!w.paramIds.empty()) { +#ifdef HAS_OBOE + const double frameNs = 1e9 / static_cast(streamSampleRate_ > 0 ? streamSampleRate_ : 48000); +#else + const double frameNs = 1e9 / 48000.0; +#endif + std::lock_guard lock(scheduledEventsMutex_); + for (size_t p = 0; p < w.paramIds.size(); p++) { + const std::string &id = w.paramIds[p]; + auto git = gains_.find(id); + double fallback = git != gains_.end() ? git->second : 0.0; + auto eit = scheduledGainEvents_.find(id); + const std::vector *events = + eit != scheduledGainEvents_.end() && !eit->second.empty() ? &eit->second : nullptr; + float *values = slot + w.paramData + p * kQuantum; + uint32_t length = 1; + values[0] = paramValueAt(events, paramNs, fallback); + if (events && (*events)[0].rate == RATE_A) { + for (int k = 1; k < kQuantum; k++) { + values[k] = paramValueAt(events, paramNs + static_cast(k * frameNs), fallback); + if (values[k] != values[0]) length = kQuantum; + } } + words[w.paramLengths + p] = length; } - if (done != read) { - float *slot = w.words + (read % kSlots) * static_cast(w.slotWords); - auto *words = reinterpret_cast(slot); - uint32_t count = std::min(words[w.outputCounts], static_cast(w.channels)); - for (int c = 0; c < w.channels; c++) { - float *dst = w.out.data() + c * kQuantum; - if (static_cast(c) < count) std::memcpy(dst, slot + w.outputData + c * kQuantum, kQuantum * sizeof(float)); - else std::memset(dst, 0, kQuantum * sizeof(float)); - } - if (words[ALIVE] == 0) w.finished = true; - read++; + } + w.header[REQUESTED].store(requested + 1, std::memory_order_release); + return true; +} + +void NativeEngine::workletReadSlot(WorkletNode &w, uint32_t read) { + float *slot = w.words + (read % kSlots) * static_cast(w.slotWords); + auto *words = reinterpret_cast(slot); + for (int o = 0; o < w.outputs; o++) { + uint32_t count = std::min(words[w.outputCounts + o], static_cast(w.outChannels[o])); + for (int c = 0; c < w.outChannels[o]; c++) { + float *dst = w.outQ.data() + (o * kWorkletMaxChannels + c) * kQuantum; + if (static_cast(c) < count) std::memcpy(dst, slot + w.outputData[o] + c * kQuantum, kQuantum * sizeof(float)); + else std::memset(dst, 0, kQuantum * sizeof(float)); + } + } + if (words[ALIVE] == 0) w.finished = true; +} + +void NativeEngine::workletSilence(WorkletNode &w) { + std::fill(w.outQ.begin(), w.outQ.end(), 0.0f); +} + +template +static void clearInputs(Worklet &w) { + std::fill(w.inMix.begin(), w.inMix.end(), 0.0f); + std::fill(std::begin(w.inActive), std::end(w.inActive), false); +} + +void NativeEngine::workletEndQuantum(WorkletNode &w, int64_t paramNs) { + // process() returned false: a source ends once its last quantum has played. + if (w.inputs == 0 && w.drained) w.ended = true; + if (!w.finished && w.header[CLOSED].load(std::memory_order_acquire) == 0) { + workletPush(w, w.nextFrame, paramNs, true); + } + w.nextFrame += kQuantum; + + // The newest responses, shrinking a backlog a stall left behind. + uint32_t read = w.header[READ].load(std::memory_order_relaxed); + uint32_t done = w.header[DONE].load(std::memory_order_acquire); + uint32_t backlog = done - read; + if (backlog > kMaxBacklog) { + read = done - kMaxBacklog; + } else { + uint32_t low = std::min(w.lowWater, backlog); + if (++w.window >= kShrinkWindow) { + if (low >= 2) read += std::max((low - 1) / 2, 1u); + w.window = 0; + w.lowWater = UINT32_MAX; } else { - std::fill(w.out.begin(), w.out.end(), 0.0f); + w.lowWater = low; } - w.header[READ].store(read, std::memory_order_release); + } + if (done != read) { + workletReadSlot(w, read); + read++; + } else { + workletSilence(w); + } + w.header[READ].store(read, std::memory_order_release); + w.drained = w.finished && done == read; + clearInputs(w); + w.position = 0; +} - for (int i = 0; i < kQuantum; i++) { - uint32_t pos = (write + i) & ring.mask; - for (int c = 0; c < w.channels; c++) { - ring.data[static_cast(pos) * w.channels + c] = w.out[static_cast(c * kQuantum + i)]; +void NativeEngine::workletRenderOffline(WorkletNode &w) { + const auto frame = static_cast(offlineFrame_); +#ifdef HAS_OBOE + const double frameNs = 1e9 / static_cast(streamSampleRate_ > 0 ? streamSampleRate_ : 48000); +#else + const double frameNs = 1e9 / 48000.0; +#endif + auto paramNs = [&](uint64_t f) { + return offlineBaseNs_ + std::llround(static_cast(f) * frameNs) + 4; + }; + if (w.inputs == 0 && w.drained) w.ended = true; + auto closed = [&] { return w.header[CLOSED].load(std::memory_order_acquire) != 0; }; + if (!w.finished && !closed()) { + if (w.inputs > 0) { + // This quantum's inputs exist only now. + workletPush(w, frame, paramNs(frame), true); + } else { + // A source's requests run ahead to the end of this render call; params can't change before it. + if (!w.requesting || w.requestFrame < frame) { + w.requesting = true; + w.requestFrame = frame; + } + const auto limit = static_cast(std::max(offlineLimitFrame_, offlineFrame_ + kQuantum)); + while (w.requestFrame < limit && workletPush(w, w.requestFrame, paramNs(w.requestFrame), false)) { + w.requestFrame += kQuantum; } } - write += kQuantum; - buffered += kQuantum; - w.nextFrame += kQuantum; + const auto deadline = std::chrono::steady_clock::now() + kOfflineStall; + while (w.header[DONE].load(std::memory_order_acquire) == w.header[READ].load(std::memory_order_relaxed) && + w.header[REQUESTED].load(std::memory_order_relaxed) != w.header[READ].load(std::memory_order_relaxed) && + !closed()) { + if (std::chrono::steady_clock::now() > deadline) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "AudioWorkletNode: the Worker stopped answering; rendering silence"); + w.finished = true; + w.header[CLOSED].store(1, std::memory_order_release); + break; + } + usleep(100); + } } - ring.writeIdx.store(write, std::memory_order_release); - // process() returned false: play out what's queued, then end like a finished stream. - if (w.finished && w.header[DONE].load(std::memory_order_acquire) == w.header[READ].load(std::memory_order_relaxed)) { - ring.ended.store(true, std::memory_order_release); + // The oldest response, never skipped. + uint32_t read = w.header[READ].load(std::memory_order_relaxed); + uint32_t done = w.header[DONE].load(std::memory_order_acquire); + if (done != read) { + workletReadSlot(w, read); + read++; + w.header[READ].store(read, std::memory_order_release); + } else { + workletSilence(w); } + w.drained = w.finished && done == read; + w.nextFrame = frame + kQuantum; + clearInputs(w); } diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContext.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContext.java index eb665de92..33cabe18d 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContext.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContext.java @@ -2872,20 +2872,26 @@ public void endExternalPcmSource(String trackId) { private native String nativeCreateExternalPcmSource(String contextId, int sampleRate, int channels); - private native String nativeCreateWorkletSource(String contextId, java.nio.ByteBuffer ring, int channels, int slotWords, int header, int outputCounts, int outputData, int paramLengths, int paramData, String[] paramIds); + private native String nativeCreateWorklet(String contextId, java.nio.ByteBuffer ring, int[] inputChannels, int[] outputChannels, int[] layout, int[] outputData, String[] paramIds); + + private native void nativeSetWorkletOutputConnected(String id, int output, boolean connected); @Nullable - String createWorkletSource(String contextId, java.nio.ByteBuffer ring, int channels, int[] layout, String[] paramIds) { - if (!nativeAvailable || ring == null || !ring.isDirect() || layout == null || layout.length < 6) return null; + String createWorkletNative(String contextId, java.nio.ByteBuffer ring, int[] inputChannels, int[] outputChannels, int[] layout, int[] outputData, String[] paramIds) { + if (!nativeAvailable || ring == null || !ring.isDirect() || layout == null || layout.length < 7) return null; // Param automation times are the context's. for (String paramId : paramIds) registerGainForContext(contextId, paramId); - return nativeCreateWorkletSource(contextId, ring, channels, layout[0], layout[1], layout[2], layout[3], layout[4], layout[5], paramIds); + return nativeCreateWorklet(contextId, ring, inputChannels, outputChannels, layout, outputData, paramIds); + } + + void setWorkletOutputConnected(String id, int output, boolean connected) { + if (nativeAvailable) nativeSetWorkletOutputConnected(id, output, connected); } - /** An AudioWorkletNode's source over `ring` (a SharedArrayBuffer); layout: slotWords, header, outputCounts, outputData, paramLengths, paramData. */ + /** An AudioWorkletNode over `ring` (a SharedArrayBuffer); layout: slotWords, header, inputCounts, inputData, outputCounts, paramLengths, paramData. */ @Nullable - public WorkletSourceNode createWorkletSource(AudioContextInstance context, java.nio.ByteBuffer ring, int channels, int[] layout, double[] paramDefaults) { - return WorkletSourceNode.create(context, ring, channels, layout, paramDefaults); + public WorkletNode createWorklet(AudioContextInstance context, java.nio.ByteBuffer ring, int[] inputChannels, int[] outputChannels, int[] layout, int[] outputData, double[] paramDefaults) { + return WorkletNode.create(context, ring, inputChannels, outputChannels, layout, outputData, paramDefaults); } private native void nativeConfigureExternalPcmSource(String trackId, int sampleRate, int channels); diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WorkletNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WorkletNode.java new file mode 100644 index 000000000..98a32f102 --- /dev/null +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WorkletNode.java @@ -0,0 +1,168 @@ +package org.nativescript.audiocontext; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import java.nio.ByteBuffer; +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +/** An AudioWorkletNode: quanta come from a JS processor in a Worker; output o plays as voice {@link #getOutputId}. */ +public class WorkletNode implements NativeObject, AudioNode { + private final String id; + private final int outputs; + private final AudioParam[] params; + // The ring's memory belongs to the JS SharedArrayBuffer; JS keeps it alive past stop(). + private final ByteBuffer ring; + // Each output's destinations; an unconnected output is silent. + private final Set[] destinations; + + @SuppressWarnings("unchecked") + private WorkletNode(String id, int outputs, ByteBuffer ring, AudioParam[] params) { + this.id = id; + this.outputs = outputs; + this.ring = ring; + this.params = params; + this.destinations = new Set[outputs]; + for (int o = 0; o < outputs; o++) destinations[o] = new HashSet<>(); + } + + /** layout: slotWords, header, inputCounts, inputData, outputCounts, paramLengths, paramData (audio-worklet-ring.ts). */ + @Nullable + static WorkletNode create(@NonNull AudioContextInstance context, @NonNull ByteBuffer ring, @NonNull int[] inputChannels, @NonNull int[] outputChannels, @NonNull int[] layout, @NonNull int[] outputData, @Nullable double[] defaults) { + int count = defaults == null ? 0 : defaults.length; + String contextId = context.getId(); + // Param ids carry an offline context's engine prefix, which routes their calls. + int prefixEnd = contextId != null ? contextId.indexOf('_') : -1; + String prefix = (contextId != null && contextId.startsWith("o") && prefixEnd > 0 ? contextId.substring(0, prefixEnd + 1) : "") + "worklet-param-" + UUID.randomUUID() + "-"; + String[] ids = new String[count]; + for (int i = 0; i < count; i++) ids[i] = prefix + i; + String id = AudioContext.getInstance().createWorkletNative(contextId, ring, inputChannels, outputChannels, layout, outputData, ids); + if (id == null) return null; + AudioParam[] params = new AudioParam[count]; + for (int i = 0; i < count; i++) { + params[i] = new AudioParam(ids[i]); + params[i].setValue(defaults[i]); + } + return new WorkletNode(id, outputChannels.length, ring, params); + } + + @Override + public String getId() { + return id; + } + + /** The voice output {@code output} plays as. */ + public String getOutputId(int output) { + return output == 0 ? id : id + "#" + output; + } + + public int getParamCount() { + return params.length; + } + + public AudioParam getParam(int index) { + return params[index]; + } + + public void stop() { + AudioContext.getInstance().stopTrack(id); + } + + @Override + public void release() { + stop(); + } + + @Override + public void connect(AudioNode node) { + connect(node, 0, 0); + } + + @Override + public void connect(AudioNode node, int output) { + connect(node, output, 0); + } + + @Override + public void connect(AudioNode node, int output, int input) { + if (!(node instanceof NativeObject) || output < 0 || output >= outputs) return; + String destId = ((NativeObject) node).getId(); + if (destId == null) return; + AudioContext context = AudioContext.getInstance(); + synchronized (destinations) { + if (destinations[output].isEmpty()) context.setWorkletOutputConnected(id, output, true); + destinations[output].add(destId); + } + if (context.isDestinationNode(destId)) return; + String voice = getOutputId(output); + if (node instanceof AudioPannerNode) { + context.attachPannerToVoice(voice, destId, 0, input); + } else if (node instanceof AudioBiquadNode) { + context.attachBiquadToVoice(voice, destId, 0, input); + } else { + context.attachGainToVoice(voice, destId, 0, input); + } + context.registerNodeSource(destId, voice); + } + + private void disconnectOutput(int output, @Nullable AudioNode node) { + if (output < 0 || output >= outputs) return; + AudioContext context = AudioContext.getInstance(); + String destId = node instanceof NativeObject ? ((NativeObject) node).getId() : null; + synchronized (destinations) { + if (destId != null) { + if (!destinations[output].remove(destId)) return; + } else { + destinations[output].clear(); + } + if (destinations[output].isEmpty()) context.setWorkletOutputConnected(id, output, false); + } + String voice = getOutputId(output); + if (destId == null) { + context.attachPannerToVoice(voice, "", 0, 0); + context.attachBiquadToVoice(voice, "", 0, 0); + context.attachGainToVoice(voice, "", 0, 0); + return; + } + if (node instanceof AudioPannerNode) { + context.attachPannerToVoice(voice, "", 0, 0); + } else if (node instanceof AudioBiquadNode) { + context.attachBiquadToVoice(voice, "", 0, 0); + } else if (!context.isDestinationNode(destId)) { + context.attachGainToVoice(voice, "", 0, 0); + } + context.unregisterNodeSource(destId, voice); + } + + @Override + public void disconnect() { + for (int o = 0; o < outputs; o++) disconnectOutput(o, null); + } + + @Override + public void disconnect(int output) { + disconnectOutput(output, null); + } + + @Override + public void disconnect(AudioNode node) { + if (node == null) { + disconnect(); + return; + } + for (int o = 0; o < outputs; o++) disconnectOutput(o, node); + } + + @Override + public void disconnect(AudioNode node, int output) { + if (node == null) disconnectOutput(output, null); + else disconnectOutput(output, node); + } + + @Override + public void disconnect(AudioNode node, int output, int input) { + disconnect(node, output); + } +} diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WorkletSourceNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WorkletSourceNode.java deleted file mode 100644 index 39eea50d0..000000000 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WorkletSourceNode.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.nativescript.audiocontext; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import java.nio.ByteBuffer; -import java.util.UUID; - -/** An AudioWorkletNode: a source whose quanta come from a JS processor in a Worker. */ -public class WorkletSourceNode extends AudioScheduledSourceNode { - private final AudioParam[] params; - // The ring's memory belongs to the JS SharedArrayBuffer; JS keeps it alive past stop(). - private final ByteBuffer ring; - - private WorkletSourceNode(String id, ByteBuffer ring, AudioParam[] params) { - super(id); - this.ring = ring; - this.params = params; - } - - @Nullable - static WorkletSourceNode create(@NonNull AudioContextInstance context, @NonNull ByteBuffer ring, int channels, @NonNull int[] layout, @Nullable double[] defaults) { - int count = defaults == null ? 0 : defaults.length; - String[] ids = new String[count]; - AudioParam[] params = new AudioParam[count]; - String prefix = "worklet-param-" + UUID.randomUUID() + "-"; - for (int i = 0; i < count; i++) ids[i] = prefix + i; - String id = AudioContext.getInstance().createWorkletSource(context.getId(), ring, channels, layout, ids); - if (id == null) return null; - for (int i = 0; i < count; i++) { - params[i] = new AudioParam(ids[i]); - params[i].setValue(defaults[i]); - } - WorkletSourceNode node = new WorkletSourceNode(id, ring, params); - node.contextId = context.getId(); - return node; - } - - public int getParamCount() { - return params.length; - } - - public AudioParam getParam(int index) { - return params[index]; - } -} diff --git a/packages/audio-context/typings/android.d.ts b/packages/audio-context/typings/android.d.ts index 139f418ff..e914b8a38 100644 --- a/packages/audio-context/typings/android.d.ts +++ b/packages/audio-context/typings/android.d.ts @@ -154,7 +154,7 @@ declare module org { public pushPcmFrames(p: string, this_: java.nio.FloatBuffer): void; public createOscillator(context: org.nativescript.audiocontext.AudioContextInstance, type: string, frequency: number): org.nativescript.audiocontext.AudioOscillatorNode; public createExternalPcmSource(context: org.nativescript.audiocontext.AudioContextInstance, sampleRate: number, channels: number): org.nativescript.audiocontext.ExternalPcmSourceNode; - public createWorkletSource(context: org.nativescript.audiocontext.AudioContextInstance, ring: java.nio.ByteBuffer, channels: number, layout: number[], paramDefaults: number[]): org.nativescript.audiocontext.WorkletSourceNode; + public createWorklet(context: org.nativescript.audiocontext.AudioContextInstance, ring: java.nio.ByteBuffer, inputChannels: number[], outputChannels: number[], layout: number[], outputData: number[], paramDefaults: number[]): org.nativescript.audiocontext.WorkletNode; public createOscillator(context: org.nativescript.audiocontext.AudioContextInstance): org.nativescript.audiocontext.AudioOscillatorNode; public decodeAudioDataFromByteArrayAsync(data: androidNative.Array, context: org.nativescript.audiocontext.AudioContextInstance, cb: org.nativescript.audiocontext.DecodeCallback): void; public createConvolver(context: org.nativescript.audiocontext.AudioContextInstance): org.nativescript.audiocontext.ConvolverNode; @@ -733,10 +733,22 @@ declare module org { declare module org { export module nativescript { export module audiocontext { - export class WorkletSourceNode extends org.nativescript.audiocontext.AudioScheduledSourceNode { - public static class: java.lang.Class; + export class WorkletNode extends java.lang.Object implements org.nativescript.audiocontext.AudioNode { + public static class: java.lang.Class; + public getId(): string; + public getOutputId(output: number): string; public getParamCount(): number; public getParam(index: number): org.nativescript.audiocontext.AudioParam; + public stop(): void; + public release(): void; + public connect(node: org.nativescript.audiocontext.AudioNode): void; + public connect(node: org.nativescript.audiocontext.AudioNode, output: number): void; + public connect(node: org.nativescript.audiocontext.AudioNode, output: number, input: number): void; + public disconnect(): void; + public disconnect(output: number): void; + public disconnect(node: org.nativescript.audiocontext.AudioNode): void; + public disconnect(node: org.nativescript.audiocontext.AudioNode, output: number): void; + public disconnect(node: org.nativescript.audiocontext.AudioNode, output: number, input: number): void; } export class ExternalPcmSourceNode extends org.nativescript.audiocontext.AudioScheduledSourceNode { public static class: java.lang.Class; diff --git a/tools/demo/canvas/spec/audio-offline-suspend.ts b/tools/demo/canvas/spec/audio-offline-suspend.ts index 576ccb57c..8a800fa4f 100644 --- a/tools/demo/canvas/spec/audio-offline-suspend.ts +++ b/tools/demo/canvas/spec/audio-offline-suspend.ts @@ -1,6 +1,5 @@ import { AudioWorkletNode, OfflineAudioContext } from '@nativescript/audio-context'; -import { isAndroid } from '@nativescript/core'; -import { suite, test, skip, equal, closeTo, rejects } from './harness'; +import { suite, test, equal, closeTo, rejects } from './harness'; // OfflineAudioContext.suspend(when) / resume(), against what Chrome does. @@ -72,8 +71,7 @@ export function registerAudioOfflineSuspendSpec() { equal(samples[Q * 10 + 5], 1.5, 'the source scheduled before rendering joins on its frame'); }); - if (isAndroid) skip('a worklet sees a param set while held from the suspend frame', 'no OfflineAudioContext worklets on Android'); - else test('a worklet sees a param set while held from the suspend frame', async () => { + test('a worklet sees a param set while held from the suspend frame', async () => { if (typeof (globalThis as any).Worker !== 'function') return; const context = new OfflineAudioContext(1, Q * 16, RATE); await context.audioWorklet.addModule(LEVEL); diff --git a/tools/demo/canvas/spec/audio-worklet.ts b/tools/demo/canvas/spec/audio-worklet.ts index 0c16d60ec..c146d1b4a 100644 --- a/tools/demo/canvas/spec/audio-worklet.ts +++ b/tools/demo/canvas/spec/audio-worklet.ts @@ -1,5 +1,4 @@ import { AudioContext, AudioWorkletNode, OfflineAudioContext } from '@nativescript/audio-context'; -import { isAndroid } from '@nativescript/core'; import { suite, test, skip, equal, closeTo, ok } from './harness'; // AudioWorkletNode inputs, outputs and fan-in, against what Chrome does. @@ -64,10 +63,6 @@ const MONO = { channelCount: 1, channelCountMode: 'explicit' } as any; export function registerAudioWorkletSpec() { suite('audio.worklet', () => { - if (isAndroid) { - skip('inputs and outputs', 'Android worklets are sources only'); - return; - } if (typeof (globalThis as any).Worker !== 'function') { skip('inputs and outputs', 'no Worker in this runtime'); return;