diff --git a/packages/audio-context/README.md b/packages/audio-context/README.md index c46546be..13f775fa 100644 --- a/packages/audio-context/README.md +++ b/packages/audio-context/README.md @@ -213,12 +213,13 @@ on the app's JS thread. builds). - 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`. + `SharedArrayBuffer`; the engine wakes the Worker's looper each time it requests a quantum, so + realtime output plays up to a device buffer late and an offline render doesn't wait on a timer. + (`Atomics.notify` can't come from the render thread, so the wake is native.) +- On Android each input is mixed from every source's own channels straight to its + `channelCount`, with the speaker rules for mono, stereo, quad and 5.1 (other counts mix + discretely), in any context. A node connected into a worklet input plays only into it, as with + `DelayNode`. ## Linux diff --git a/packages/audio-context/audio-worklet-ring.ts b/packages/audio-context/audio-worklet-ring.ts index d3682ae3..2cce4ce0 100644 --- a/packages/audio-context/audio-worklet-ring.ts +++ b/packages/audio-context/audio-worklet-ring.ts @@ -63,8 +63,8 @@ export function createWorkletRing(layout: WorkletRingLayout): SharedArrayBuffer return new SharedArrayBuffer((layout.header + WORKLET_HEADER_WORDS) * 4); } -// Worker-side bridge over the shared rings: prepended to AUDIO_WORKLET_SCOPE. The render thread -// can't wake a Worker here, so it polls. +// Worker-side bridge over the shared rings: prepended to AUDIO_WORKLET_SCOPE. On Android the engine +// wakes the Worker's looper per requested quantum; elsewhere the Worker polls. export const SHARED_RING_BRIDGE = String.raw`(function (global) { var REQUESTED = 0, DONE = 1, CLOSED = 3, RELEASED = 4; function Ring(ring) { @@ -80,15 +80,27 @@ export const SHARED_RING_BRIDGE = String.raw`(function (global) { Ring.prototype.commit = function (count) { Atomics.add(this._h, DONE, Math.min(count, this.pending())); }; Ring.prototype.release = function () { Atomics.store(this._h, RELEASED, 1); }; + function nativeWaker(drain) { + try { + var ns = global.org && global.org.nativescript; + var Waker = ns && ns.audiocontext && ns.audiocontext.WorkletWaker; + return Waker ? Waker.attach(new java.lang.Runnable({ run: drain })) : null; + } catch (e) { + return null; + } + } + function Bridge(drain) { this.rings = new Map(); - this.timer = setInterval(drain, 2); + this.waker = nativeWaker(drain); + this.timer = this.waker ? 0 : setInterval(drain, 2); } Bridge.prototype.adopt = function (id, ring) { this.rings.set(id, new Ring(ring)); }; Bridge.prototype.node = function (id) { return this.rings.get(id) || null; }; Bridge.prototype.beginDrain = function () {}; Bridge.prototype.close = function () { - clearInterval(this.timer); + if (this.waker) this.waker.detach(); + else clearInterval(this.timer); this.rings.clear(); }; diff --git a/packages/audio-context/index.android.ts b/packages/audio-context/index.android.ts index 78466465..a0fd110f 100644 --- a/packages/audio-context/index.android.ts +++ b/packages/audio-context/index.android.ts @@ -153,37 +153,21 @@ export class AudioNode extends AudioNodeBase { } disconnect(destinationOrOutput?: any, output?: number, input?: number) { - const that = this as never as AudioNode & { native: org.nativescript.audiocontext.AudioNode }; - try { - if (!destinationOrOutput) { - that.native.disconnect(); - return; - } - if (typeof destinationOrOutput === 'number') { - try { - (that.native as any).disconnectOutput(destinationOrOutput); - } catch (e) { - console.warn('AudioNode.disconnect(output): falling back to full disconnect:', e); - that.native.disconnect(); - } - return; - } - const dest = destinationOrOutput.native || destinationOrOutput; - try { - if (typeof output === 'number' && typeof input === 'number') (that.native as any).disconnectTo(dest, output, input); - else if (typeof output === 'number') (that.native as any).disconnectTo(dest, output); - else (that.native as any).disconnectTo(dest); - } catch (e) { - console.warn('AudioNode.disconnect(target): falling back to full disconnect:', e); - try { - that.native.disconnect(); - } catch (ee) { - console.warn('AudioNode.disconnect fallback also failed:', ee); - } - } - } catch (e) { - console.warn('AudioNode.disconnect failed:', e); + const native = (this as never as { native: org.nativescript.audiocontext.AudioNode }).native; + if (destinationOrOutput === undefined || destinationOrOutput === null) { + native.disconnect(); + return; } + if (typeof destinationOrOutput === 'number') { + native.disconnect(destinationOrOutput); + return; + } + // AudioParam inputs are never wired natively. + if (destinationOrOutput instanceof AudioParamBase) return; + const target = destinationOrOutput.native ?? destinationOrOutput; + if (typeof output !== 'number') native.disconnect(target); + else if (typeof input !== 'number') native.disconnect(target, output); + else native.disconnect(target, output, input); } } @@ -295,6 +279,12 @@ export class BiquadFilterNode extends AudioNode { get native() { return this[native_]; } + get type(): string { + return this.native.getType(); + } + set type(value: string) { + this.native.setType(value); + } get frequency(): AudioParam { if (!this._frequencyParam) this._frequencyParam = new AudioParam(nativeCtor_, this.native.getFrequency()); return this._frequencyParam; @@ -1237,7 +1227,7 @@ export class AudioContext extends BaseAudioContext { }); return new Promise((resolve, reject) => { const ref = new WeakRef(this); - AudioContext.getInstance().closeAsync( + this.native.closeAsync( new org.nativescript.audiocontext.AudioContext.AsyncCallback({ onComplete(ok) { if (ok) { diff --git a/packages/audio-context/platforms/android/audiocontext-release.aar b/packages/audio-context/platforms/android/audiocontext-release.aar index 33eb6175..cd706601 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/main/cpp/CMakeLists.txt b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/CMakeLists.txt index e078a4e0..09ffd257 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/CMakeLists.txt +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/CMakeLists.txt @@ -38,14 +38,14 @@ find_library(log-lib log) target_include_directories(native-audio PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) if (HAS_OBOE) - target_link_libraries(native-audio PRIVATE oboe ${log-lib}) + target_link_libraries(native-audio PRIVATE oboe ${log-lib} android) target_compile_definitions(native-audio PRIVATE HAS_OBOE=1) else() find_library(AAUDIO_LIB aaudio) if (AAUDIO_LIB) - target_link_libraries(native-audio PRIVATE ${AAUDIO_LIB} ${log-lib}) + target_link_libraries(native-audio PRIVATE ${AAUDIO_LIB} ${log-lib} android) else() - target_link_libraries(native-audio PRIVATE ${log-lib}) + target_link_libraries(native-audio PRIVATE ${log-lib} android) endif() target_compile_definitions(native-audio PRIVATE HAS_OBOE=0) endif() 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 ec51e115..cb3b45ac 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 @@ -169,6 +169,8 @@ class NativeEngine { int64_t offlineLimitFrame_ = 0; // The render clock: CLOCK_MONOTONIC ns for realtime, virtual for offline. std::atomic nowNs_{0}; + // Realtime: the next block's first frame on the render thread's frame clock. + int64_t renderClockNs_ = 0; void ensureStream(); @@ -237,7 +239,7 @@ class NativeEngine { std::vector paramIds; // Render thread only. bool connected[kWorkletMaxPorts] = {}; - // The context's channels of each input, a quantum each: inputs x mixChannels x 128. + // Each input at its channelCount, a quantum per channel: inputs x mixChannels x 128. int mixChannels = 1; std::vector inMix; bool inActive[kWorkletMaxPorts] = {}; @@ -384,7 +386,8 @@ class NativeEngine { CMD_SET_PANNER_PARTITION_SIZE, CMD_CREATE_WORKLET, CMD_CREATE_DELAY, - CMD_WORKLET_OUTPUT + CMD_WORKLET_OUTPUT, + CMD_DETACH_FROM }; struct Command { diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_internal.h b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_internal.h index 2f72ec6b..aeb46239 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_internal.h +++ b/packages/audio-context/src-native/android/audiocontext/src/main/cpp/audio_internal.h @@ -509,4 +509,36 @@ inline float getScheduledGainValueAt(const std::vector return static_cast(prev.value); } +// Web Audio "speakers" up/down-mix: output channel `out` of `outCh` from `in` channels read by `read(c)`. +// Layouts are mono, stereo, quad (L R SL SR) and 5.1 (L R C LFE SL SR); other counts mix discretely. +template +static inline float speakerMix(Read &&read, int in, int outCh, int out) { + constexpr float h = 0.7071067811865476f; + if (in == outCh) return read(out); + auto known = [](int n) { return n == 1 || n == 2 || n == 4 || n == 6; }; + if (!known(in) || !known(outCh)) return out < in ? read(out) : 0.0f; + if (in == 1) { + if (outCh == 6) return out == 2 ? read(0) : 0.0f; + return out < 2 ? read(0) : 0.0f; + } + if (outCh == 1) { + if (in == 2) return 0.5f * (read(0) + read(1)); + if (in == 4) return 0.25f * (read(0) + read(1) + read(2) + read(3)); + return h * (read(0) + read(1)) + read(2) + 0.5f * (read(4) + read(5)); + } + if (in < outCh) { + // Up-mix: L R copy; quad surrounds land on 5.1's SL SR. + if (out < 2) return read(out); + if (in == 4 && outCh == 6 && out >= 4) return read(out - 2); + return 0.0f; + } + if (outCh == 2) { + if (in == 4) return 0.5f * (read(out) + read(out + 2)); + return read(out) + h * (read(2) + read(out + 4)); + } + // 5.1 to quad. + if (out < 2) return read(out) + h * read(2); + return read(out + 2); +} + #endif // AUDIO_INTERNAL_H 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 6ef67ea4..7b6077f6 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 @@ -316,7 +316,7 @@ Java_org_nativescript_audiocontext_AudioContext_nativeAttachGain__Ljava_lang_Str } extern "C" JNIEXPORT void JNICALL -Java_org_nativescript_audiocontext_AudioContext_nativeAttachPlaybackRate(JNIEnv *env, jobject thiz, +Java_org_nativescript_audiocontext_AudioContext_nativeAttachPlaybackRate__Ljava_lang_String_2Ljava_lang_String_2(JNIEnv *env, jobject thiz, jstring jvoiceId, jstring jplaybackRateId) { NativeEngine::Scope scope__(engineFor(env, jvoiceId)); @@ -352,6 +352,26 @@ Java_org_nativescript_audiocontext_AudioContext_nativeAttachPlaybackRate__Ljava_ if (pid) env->ReleaseStringUTFChars(jplaybackRateId, pid); } +extern "C" JNIEXPORT void JNICALL +Java_org_nativescript_audiocontext_AudioContext_nativeDetachFrom(JNIEnv *env, jobject thiz, + jstring jvoiceId, + jstring jtargetId, + jint joutput, + jint jinput) { + NativeEngine::Scope scope__(engineFor(env, jvoiceId)); + const char *vid = env->GetStringUTFChars(jvoiceId, nullptr); + const char *tid = env->GetStringUTFChars(jtargetId, nullptr); + NativeEngine::Command cmd; + cmd.type = NativeEngine::CMD_DETACH_FROM; + cmd.id = vid ? vid : std::string(); + cmd.gainId = tid ? tid : std::string(); + cmd.outputIndex = static_cast(joutput); + cmd.inputIndex = static_cast(jinput); + NativeEngine::getInstance().enqueueCommand(std::move(cmd)); + if (vid) env->ReleaseStringUTFChars(jvoiceId, vid); + if (tid) env->ReleaseStringUTFChars(jtargetId, tid); +} + extern "C" JNIEXPORT void JNICALL Java_org_nativescript_audiocontext_AudioContext_nativeDetachPlaybackRate(JNIEnv *env, jobject thiz, jstring jplaybackRateId) { @@ -878,7 +898,7 @@ Java_org_nativescript_audiocontext_AudioContext_nativeSetWaveShaperOversample(JN } extern "C" JNIEXPORT void JNICALL -Java_org_nativescript_audiocontext_AudioContext_nativeAttachBiquad(JNIEnv *env, jobject thiz, +Java_org_nativescript_audiocontext_AudioContext_nativeAttachBiquad__Ljava_lang_String_2Ljava_lang_String_2(JNIEnv *env, jobject thiz, jstring jvoiceId, jstring jbiquadId) { NativeEngine::Scope scope__(engineFor(env, jvoiceId)); @@ -1189,7 +1209,7 @@ Java_org_nativescript_audiocontext_AudioContext_nativeGetListenerParamValue(JNIE } extern "C" JNIEXPORT void JNICALL -Java_org_nativescript_audiocontext_AudioContext_nativeAttachPanner(JNIEnv *env, jobject thiz, +Java_org_nativescript_audiocontext_AudioContext_nativeAttachPanner__Ljava_lang_String_2Ljava_lang_String_2(JNIEnv *env, jobject thiz, jstring jvoiceId, jstring jpannerId) { NativeEngine::Scope scope__(engineFor(env, jvoiceId)); 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 40ed5372..83e36d43 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 @@ -272,20 +272,17 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n static std::atomic sGraphTraceSeq{0}; if (!offline_) { - if (stream) { - auto tsRes = stream->getTimestamp(CLOCK_MONOTONIC); - if (tsRes) { - auto frameTs = tsRes.value(); - g_audioTimeNanos.store(frameTs.timestamp, std::memory_order_relaxed); - } else { - int64_t nowNs = monotonicNowNs(); - g_audioTimeNanos.store(nowNs, std::memory_order_relaxed); - } - } else { - int64_t nowNs = monotonicNowNs(); - g_audioTimeNanos.store(nowNs, std::memory_order_relaxed); - } - nowNs_.store(g_audioTimeNanos.load(std::memory_order_relaxed), std::memory_order_relaxed); + // A frame clock, so automation and source positions advance together; device timestamps + // jitter between callbacks. It re-anchors to the monotonic clock after a stall or restart. + constexpr int64_t kClockBehindNs = 50000000; + constexpr int64_t kClockAheadNs = 500000000; + const int64_t now = monotonicNowNs(); + int64_t clock = renderClockNs_; + if (clock == 0 || now - clock > kClockBehindNs || clock - now > kClockAheadNs) clock = now; + const double rate = streamSampleRate_ > 0 ? static_cast(streamSampleRate_) : 48000.0; + renderClockNs_ = clock + std::llround(static_cast(numFrames) * 1e9 / rate); + g_audioTimeNanos.store(clock, std::memory_order_relaxed); + nowNs_.store(clock, std::memory_order_relaxed); } @@ -523,7 +520,10 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n voiceWorklet_.erase(c.id); break; } - if (c.gainId.empty()) voiceWorklet_.erase(c.id); + if (c.gainId.empty()) { + voiceWorklet_.erase(c.id); + voiceDelay_.erase(c.id); + } auto vit = audioVoices_.find(c.id); std::string prevGainId; bool voiceExists = vit != audioVoices_.end(); @@ -581,6 +581,55 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n } break; } + case NativeEngine::CMD_DETACH_FROM: { + // Clears voice c.id's slots holding c.gainId (any target when empty, any output when < 0). + const std::string &target = c.gainId; + std::string pannerFilter; + auto pfIt = panners_.find(target); + if (pfIt != panners_.end()) pannerFilter = pfIt->second.biquadId; + auto matches = [&](const std::string &slot) { + return target.empty() || slot == target || + (!pannerFilter.empty() && slot == pannerFilter); + }; + auto eraseFrom = [&](std::unordered_map> &byOutput) { + auto it = byOutput.find(c.id); + if (it == byOutput.end()) return; + for (auto o = it->second.begin(); o != it->second.end();) { + if (matches(o->second) && (c.outputIndex < 0 || o->first == c.outputIndex)) + o = it->second.erase(o); + else ++o; + } + if (it->second.empty()) byOutput.erase(it); + }; + auto firstOf = [&](std::unordered_map> &byOutput) { + auto it = byOutput.find(c.id); + if (it == byOutput.end() || it->second.empty()) return std::string(); + auto o = it->second.find(0); + return o != it->second.end() ? o->second : it->second.begin()->second; + }; + eraseFrom(voiceGainByOutput_); + eraseFrom(voiceFilterByOutput_); + eraseFrom(voicePannerByOutput_); + bool anyOutput = c.outputIndex <= 0; + auto dIt = voiceDelay_.find(c.id); + if (anyOutput && dIt != voiceDelay_.end() && matches(dIt->second)) voiceDelay_.erase(dIt); + auto wIt = voiceWorklet_.find(c.id); + if (anyOutput && wIt != voiceWorklet_.end() && matches(wIt->second.first) && + (c.inputIndex < 0 || wIt->second.second == c.inputIndex)) + voiceWorklet_.erase(wIt); + auto vit = audioVoices_.find(c.id); + if (vit != audioVoices_.end()) { + Voice &v = vit->second; + if (!v.gainId.empty() && matches(v.gainId)) { + v.gainId = firstOf(voiceGainByOutput_); + auto git = gains_.find(v.gainId); + v.gain = git != gains_.end() ? git->second : 1.0; + } + if (!v.filterId.empty() && matches(v.filterId)) v.filterId = firstOf(voiceFilterByOutput_); + if (!v.panId.empty() && matches(v.panId)) v.panId = firstOf(voicePannerByOutput_); + } + break; + } case NativeEngine::CMD_ATTACH_PLAYBACK_RATE: { auto vit = audioVoices_.find(c.id); if (vit != audioVoices_.end()) { @@ -2427,15 +2476,22 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n // Mixes `pass`'s voices into `out`; realtime worklets step a frame at a time. auto renderPass = [&](const std::vector &pass) { + int passChannels = channels; + for (const ActiveVoiceView *view: pass) { + if (view->into) passChannels = std::max(passChannels, view->into->inChannels[view->intoInput]); + } for (int frame = 0; frame < numFrames; ++frame) { pannerCutoffByBiquad.clear(); pannerFrameCache.clear(); stereoInputCache.clear(); hrtfOutputCache.clear(); - for (int ch = 0; ch < channels; ++ch) { + for (int ch = 0; ch < passChannels; ++ch) { float mixed = 0.0f; for (const ActiveVoiceView *voiceViewPtr: pass) { const ActiveVoiceView &voiceView = *voiceViewPtr; + // A voice feeding a worklet input renders at that input's channelCount. + const int vch = voiceView.into ? voiceView.into->inChannels[voiceView.intoInput] : channels; + if (ch >= vch) continue; Voice &v = *voiceView.voice; const BufferData *voiceBuffer = voiceView.bufferData; const auto *gainRoute = voiceView.gainRoute; @@ -2515,7 +2571,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n if (filterRef.biquad) { int fsIndex = ch; if (v.filterState.size() <= static_cast(fsIndex)) - v.filterState.assign(channels, NativeEngine::BiquadState()); + v.filterState.assign(vch, NativeEngine::BiquadState()); auto in = static_cast(s); float outS = processBiquadSample(*filterRef.biquad, v.filterState[fsIndex], @@ -2523,7 +2579,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n s = outS; } else if (filterRef.iir) { int fsIndex = ch; - size_t chCount = static_cast(channels); + size_t chCount = static_cast(vch); if (v.iirState.size() < chCount) v.iirState.assign(chCount, std::vector()); if (v.iirState.size() <= static_cast(fsIndex)) @@ -2559,7 +2615,9 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n : resolveOutputMappedId(gainRoute, ch, v.gainId); double scheduled = resolveGainValueForFrame(effGainId, v.gain, frame); - if (channels <= 1) { + // Mono up-mix: quad leaves the surrounds silent, 5.1 plays only the centre. + s *= static_cast(speakerMix([](int) { return 1.0f; }, 1, vch, ch)); + if (vch <= 1) { if (!effGainId.empty()) { auto wsIt = waveShapers_.find(effGainId); if (wsIt != waveShapers_.end() && !wsIt->second.curve.empty()) { @@ -2593,7 +2651,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n emitVoice(voiceView, ch, frame, voiceOut, mixed); } } - if (ch == channels - 1) { + if (ch == vch - 1) { v.phase += v.phaseIncrement; if (v.phase >= 1.0) v.phase -= 1.0; } @@ -2633,72 +2691,69 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n double frac = pos - i0; if (bufChannels == 1) chIdx = 0; - else if (bufChannels >= channels) chIdx = ch; + else if (bufChannels >= vch) chIdx = ch; else chIdx = ch % bufChannels; - int idx0 = (i0 % bufFrames) * bufChannels + chIdx; - int idx1 = ((i0 + 1) % bufFrames) * bufChannels + chIdx; - idx0_dbg = idx0; - idx1_dbg = idx1; - float fs0 = 0.0f; - float fs1 = 0.0f; - if (bd.isPlanar && !bd.planarPtrs.empty() && bd.planarFrames > 0) { - int planarChannel = std::max(0, std::min( - static_cast(bd.planarPtrs.size()) - 1, - chIdx)); - const float *fptr = bd.planarPtrs[static_cast(planarChannel)]; - if (fptr) { - int maxIndex = bd.planarFrames - 1; - int sample0 = i0 % bufFrames; - int sample1 = (i0 + 1) % bufFrames; - int safe0 = std::max(0, std::min(maxIndex, sample0)); - int safe1 = std::max(0, std::min(maxIndex, sample1)); - fs0 = fptr[safe0]; - fs1 = fptr[safe1]; - } - } else if (bd.isDirect && bd.directPtr) { - if (bd.bytesPerSample == 4) { - const auto *fptr = reinterpret_cast(bd.directPtr); - int maxIndex = static_cast((bd.byteLength / 4) - 1); - int safe0 = std::max(0, std::min(maxIndex, idx0)); - int safe1 = std::max(0, std::min(maxIndex, idx1)); - fs0 = fptr[safe0]; - fs1 = fptr[safe1]; + auto readChannel = [&](int bc) -> float { + int idx0 = (i0 % bufFrames) * bufChannels + bc; + int idx1 = ((i0 + 1) % bufFrames) * bufChannels + bc; + float fs0 = 0.0f; + float fs1 = 0.0f; + if (bd.isPlanar && !bd.planarPtrs.empty() && bd.planarFrames > 0) { + int planarChannel = std::max(0, std::min( + static_cast(bd.planarPtrs.size()) - 1, + bc)); + const float *fptr = bd.planarPtrs[static_cast(planarChannel)]; + if (fptr) { + int maxIndex = bd.planarFrames - 1; + int sample0 = i0 % bufFrames; + int sample1 = (i0 + 1) % bufFrames; + int safe0 = std::max(0, std::min(maxIndex, sample0)); + int safe1 = std::max(0, std::min(maxIndex, sample1)); + fs0 = fptr[safe0]; + fs1 = fptr[safe1]; + } + } else if (bd.isDirect && bd.directPtr) { + if (bd.bytesPerSample == 4) { + const auto *fptr = reinterpret_cast(bd.directPtr); + int maxIndex = static_cast((bd.byteLength / 4) - 1); + int safe0 = std::max(0, std::min(maxIndex, idx0)); + int safe1 = std::max(0, std::min(maxIndex, idx1)); + fs0 = fptr[safe0]; + fs1 = fptr[safe1]; + } else { + const auto *iptr = reinterpret_cast(bd.directPtr); + int maxIndex = static_cast((bd.byteLength / 2) - 1); + int safe0 = std::max(0, std::min(maxIndex, idx0)); + int safe1 = std::max(0, std::min(maxIndex, idx1)); + fs0 = static_cast(iptr[safe0]) / 32768.0f; + fs1 = static_cast(iptr[safe1]) / 32768.0f; + } } else { - const auto *iptr = reinterpret_cast(bd.directPtr); - int maxIndex = static_cast((bd.byteLength / 2) - 1); + int maxIndex = static_cast(bd.pcm.size()) - 1; int safe0 = std::max(0, std::min(maxIndex, idx0)); int safe1 = std::max(0, std::min(maxIndex, idx1)); - fs0 = static_cast(iptr[safe0]) / 32768.0f; - fs1 = static_cast(iptr[safe1]) / 32768.0f; + fs0 = static_cast(bd.pcm[safe0]) / 32768.0f; + fs1 = static_cast(bd.pcm[safe1]) / 32768.0f; } - } else { - int maxIndex = static_cast(bd.pcm.size()) - 1; - int safe0 = std::max(0, std::min(maxIndex, idx0)); - int safe1 = std::max(0, std::min(maxIndex, idx1)); - fs0 = static_cast(bd.pcm[safe0]) / 32768.0f; - fs1 = static_cast(bd.pcm[safe1]) / 32768.0f; - } - sample = fs0 * (1.0f - static_cast(frac)) + - fs1 * static_cast(frac); + return fs0 * (1.0f - static_cast(frac)) + + fs1 * static_cast(frac); + }; + idx0_dbg = (i0 % bufFrames) * bufChannels + chIdx; + idx1_dbg = ((i0 + 1) % bufFrames) * bufChannels + chIdx; + sample = speakerMix(readChannel, bufChannels, vch, ch); } 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 if (bufChannels >= vch) 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]; - } + sample = speakerMix([&](int c) { return workletFrame[c * 128]; }, + bufChannels, vch, ch); } else /* ExternalPCM */ { auto &ring = v.externalRing; if (!ring) continue; @@ -2716,7 +2771,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n bufChannels = externalChannels; bufFrames = INT32_MAX; if (bufChannels == 1) chIdx = 0; - else if (bufChannels >= channels) chIdx = ch; + else if (bufChannels >= vch) chIdx = ch; else chIdx = ch % bufChannels; uint32_t w = ring->writeIdx.load(std::memory_order_acquire); @@ -2764,7 +2819,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n if (filterRef.biquad) { int fsIndex = outputChannelIndex; if (v.filterState.size() <= static_cast(fsIndex)) { - v.filterState.assign(channels, NativeEngine::BiquadState()); + v.filterState.assign(vch, NativeEngine::BiquadState()); } return processBiquadSample(*filterRef.biquad, v.filterState[static_cast(fsIndex)], @@ -2773,7 +2828,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n if (filterRef.iir) { int fsIndex = outputChannelIndex; - auto chCount = static_cast(channels); + auto chCount = static_cast(vch); if (v.iirState.size() < chCount) { v.iirState.assign(chCount, std::vector()); } @@ -2855,7 +2910,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n return prev * (1.0f - t) + curr * t; }; - bool stereoInput = bufChannels > 1 && channels > 1; + bool stereoInput = bufChannels > 1 && vch > 1; float inputLeft = sample; float inputRight = sample; bool hrtfModel = false; @@ -2864,8 +2919,8 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n auto cacheIt = stereoInputCache.find(v.id); if (cacheIt == stereoInputCache.end()) { std::array cached{{ - applyVoiceFilter(sampleInputChannel(0), 0), - applyVoiceFilter(sampleInputChannel(1), 1), + applyVoiceFilter(speakerMix(sampleInputChannel, bufChannels, vch, 0), 0), + applyVoiceFilter(speakerMix(sampleInputChannel, bufChannels, vch, 1), 1), }}; cacheIt = stereoInputCache.emplace(v.id, cached).first; } @@ -2909,7 +2964,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n } bool useHrtfConvolution = - hrtfModel && hrtfConvolver != nullptr && channels > 1; + hrtfModel && hrtfConvolver != nullptr && vch > 1; bool treatStereoAsMono = stereoInput && useHrtfConvolution; if (useHrtfConvolution && ch < 2) { auto hrtfIt = hrtfOutputCache.find(v.id); @@ -2936,10 +2991,10 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n double frac = v.position - i0; int idx0 = idx0_dbg; int idx1 = idx1_dbg; - int chOther = (channels > 1) ? 1 : 0; + int chOther = (vch > 1) ? 1 : 0; int chIdxOther = chOther; if (bufChannels == 1) chIdxOther = 0; - else if (bufChannels >= channels) chIdxOther = chOther; + else if (bufChannels >= vch) chIdxOther = chOther; else chIdxOther = chOther % bufChannels; int idx0Other = (i0 % bufFrames) * bufChannels + chIdxOther; int idx1Other = ((i0 + 1) % bufFrames) * bufChannels + chIdxOther; @@ -2989,7 +3044,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n (void) idx1; audioThreadLog(ANDROID_LOG_INFO, "VOICE_DEBUG id=%s buffer=%s bufCh=%d streamCh=%d ch0_chIdx=%d ch0_idx0=%d ch0_idx1=%d ch0_sample=%f ch1_chIdx=%d ch1_idx0=%d ch1_idx1=%d ch1_sample=%f leftGain=%f rightGain=%f panId=%s", - v.id.c_str(), v.bufferId.c_str(), bufChannels, channels, + v.id.c_str(), v.bufferId.c_str(), bufChannels, vch, chIdx, idx0, idx1, sample, chIdxOther, idx0Other, idx1Other, sampleOther, leftGain, rightGain, v.panId.c_str()); @@ -3002,7 +3057,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n : resolveOutputMappedId(gainRoute, ch, v.gainId); double scheduled = resolveGainValueForFrame(effGainId3, v.gain, frame); - if (channels <= 1) { + if (vch <= 1) { if (!effGainId3.empty()) { auto wsIt3 = waveShapers_.find(effGainId3); if (wsIt3 != waveShapers_.end() && !wsIt3->second.curve.empty()) { @@ -3085,7 +3140,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n } } - if (ch == channels - 1) { + if (ch == vch - 1) { if (v.voiceType == Voice::BufferSource) { double prScale = 1.0; const std::string &resolvedPRId = @@ -3134,7 +3189,7 @@ NativeEngine::onAudioReady(oboe::AudioStream *stream, void *audioData, int32_t n } - out[frame * channels + ch] += mixed; + if (ch < channels) out[frame * channels + ch] += mixed; } if (!offline_) { for (NativeEngine::WorkletNode *w: worklets) { 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 a5293ea1..364f17ba 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 @@ -7,6 +7,11 @@ #include #include #include +#include +#include +#include +#include +#include namespace { constexpr int kQuantum = 128; @@ -55,7 +60,7 @@ std::string NativeEngine::createWorklet(float *ring, const std::vector &inp } w->paramIds = std::move(paramIds); #ifdef HAS_OBOE - w->mixChannels = std::max(1, std::min(streamChannels_, kWorkletMaxChannels)); + w->mixChannels = 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); @@ -80,11 +85,94 @@ void NativeEngine::setWorkletOutputConnected(const std::string &id, int output, enqueueCommand(std::move(cmd)); } +// Worker wakers: an eventfd on each AudioWorklet Worker's looper, written when a quantum is requested. +namespace { + constexpr int kMaxWakers = 16; + std::atomic g_wakeFds[kMaxWakers]{}; // fd + 1; 0 is free + std::atomic g_wakeWriters{0}; + + struct Waker { + int fd; + int slot; + ALooper *looper; + JavaVM *vm; + jobject drain; + jmethodID run; + }; + + int onWake(int fd, int, void *data) { + auto *w = static_cast(data); + uint64_t n; + (void) read(fd, &n, sizeof n); + JNIEnv *env = nullptr; + if (w->vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK || !env) return 1; + env->CallVoidMethod(w->drain, w->run); + if (env->ExceptionCheck()) env->ExceptionClear(); + return 1; + } +} + +static void wakeWorkletWorkers() { + g_wakeWriters.fetch_add(1, std::memory_order_acquire); + const uint64_t one = 1; + for (auto &slot: g_wakeFds) { + int fd = slot.load(std::memory_order_acquire) - 1; + if (fd >= 0) (void) write(fd, &one, sizeof one); + } + g_wakeWriters.fetch_sub(1, std::memory_order_release); +} + +// Called on the Worker thread: `drain.run()` runs there whenever the engine requests a quantum. +extern "C" JNIEXPORT jlong JNICALL +Java_org_nativescript_audiocontext_WorkletWaker_nativeAttach(JNIEnv *env, jclass, jobject drain) { + ALooper *looper = ALooper_forThread(); + if (!looper || !drain) return 0; + JavaVM *vm = nullptr; + if (env->GetJavaVM(&vm) != JNI_OK) return 0; + jclass cls = env->GetObjectClass(drain); + jmethodID run = env->GetMethodID(cls, "run", "()V"); + env->DeleteLocalRef(cls); + if (!run) { + env->ExceptionClear(); + return 0; + } + int fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); + if (fd < 0) return 0; + int slot = -1; + for (int i = 0; i < kMaxWakers && slot < 0; i++) { + int expected = 0; + if (g_wakeFds[i].compare_exchange_strong(expected, fd + 1)) slot = i; + } + if (slot < 0) { + close(fd); + return 0; + } + auto *w = new Waker{fd, slot, looper, vm, env->NewGlobalRef(drain), run}; + ALooper_acquire(looper); + ALooper_addFd(looper, fd, ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, onWake, w); + return reinterpret_cast(w); +} + +extern "C" JNIEXPORT void JNICALL +Java_org_nativescript_audiocontext_WorkletWaker_nativeDetach(JNIEnv *env, jclass, jlong handle) { + auto *w = reinterpret_cast(handle); + if (!w) return; + g_wakeFds[w->slot].store(0, std::memory_order_release); + // No writer may still hold the fd once it closes. + while (g_wakeWriters.load(std::memory_order_acquire) != 0) std::this_thread::yield(); + ALooper_removeFd(w->looper, w->fd); + ALooper_release(w->looper); + close(w->fd); + env->DeleteGlobalRef(w->drain); + delete w; +} + 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); + wakeWorkletWorkers(); // Voices routed into it stay routed, and silent. for (int o = 0; o < w.outputs; o++) audioVoices_.erase(outputVoiceId(id, o)); worklets_.erase(it); @@ -104,29 +192,16 @@ bool NativeEngine::workletPush(WorkletNode &w, uint64_t frame, int64_t paramNs, 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; + // The mixer already rendered each input at its own channelCount. + const int stride = 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); + const float *mix = w.inMix.data() + static_cast(i * stride * 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; - } - } 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)); - } + std::memcpy(dst, mix + c * kQuantum, kQuantum * sizeof(float)); } } for (int o = 0; o < w.outputs; o++) words[w.outputCounts + o] = static_cast(w.outChannels[o]); @@ -158,6 +233,7 @@ bool NativeEngine::workletPush(WorkletNode &w, uint64_t frame, int64_t paramNs, } } w.header[REQUESTED].store(requested + 1, std::memory_order_release); + wakeWorkletWorkers(); return true; } diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AnalyserNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AnalyserNode.java index c661e289..ce9f2e7d 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AnalyserNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AnalyserNode.java @@ -111,30 +111,8 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", 0, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", 0, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", 0, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override @@ -151,12 +129,14 @@ public void disconnect(int output) { @Override public void disconnect(AudioNode node, int output) { - disconnect(node); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override public void disconnect(AudioNode node, int output, int input) { - disconnect(node); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, input); } @Override diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioBiquadNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioBiquadNode.java index 9a439326..1760df67 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioBiquadNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioBiquadNode.java @@ -108,6 +108,16 @@ public AudioParam getDetune() { } + public String getType() { + return currentType; + } + + public void setType(String type) { + if (type == null) return; + currentType = type; + AudioContext.getInstance().setBiquadParams(id, currentFrequency, currentQ, currentGain, currentType); + } + public void setParams(String type, double frequency, double Q, double gain) { if (type != null) { currentType = type; @@ -160,30 +170,8 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", 0, 0); - } else if (node instanceof GainNode) { - context.attachGainToVoice(sourceId, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachBiquadToVoice(sourceId, "", 0, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachBiquadToVoice(destId, "", 0, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override @@ -200,58 +188,14 @@ public void disconnect(int output) { @Override public void disconnect(AudioNode node, int output) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", output, 0); - } else if (node instanceof GainNode) { - context.attachGainToVoice(sourceId, "", output, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachBiquadToVoice(sourceId, "", output, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachBiquadToVoice(destId, "", output, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override public void disconnect(AudioNode node, int output, int input) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", output, input); - } else if (node instanceof GainNode) { - context.attachGainToVoice(sourceId, "", output, input); - } else if (!context.isDestinationNode(destId)) { - context.attachBiquadToVoice(sourceId, "", output, input); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachBiquadToVoice(destId, "", output, input); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, input); } @Override 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 33cabe18..44cb2313 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 @@ -265,6 +265,7 @@ String createContext(int sampleRate, double latencyHintSec) { } if (start == 0L) start = System.nanoTime(); contextStartNanos.put(id, start); + openRealtimeContexts.add(id); try { nativeRegisterContextStart(id, start); } catch (Throwable ignored) { @@ -281,8 +282,16 @@ public AudioContextInstance createContextInstance(int sampleRate, double latency return new AudioContextInstance(createContext(sampleRate, latencyHintSec)); } + private final Set openRealtimeContexts = createConcurrentSet(); + void releaseContext(String contextId) { + releaseContext(contextId, false); + } + + // Closing keeps buffers (they outlive contexts) and the clock (currentTime stays readable). + private void releaseContext(String contextId, boolean closing) { if (contextId == null) return; + openRealtimeContexts.remove(contextId); Set tracksSet = contextTracksMap.remove(contextId); if (tracksSet != null) { for (String tid : tracksSet) { @@ -290,7 +299,7 @@ void releaseContext(String contextId) { tracks.remove(tid); } } - Set bufs = contextBuffers.remove(contextId); + Set bufs = closing ? null : contextBuffers.remove(contextId); if (bufs != null) { for (String bid : bufs) { releaseBuffer(bid); @@ -332,6 +341,7 @@ void releaseContext(String contextId) { clearNodeSources(did); releaseGain(did); } + if (closing) return; contextSampleRates.remove(contextId); try { nativeUnregisterContextStart(contextId); @@ -1687,11 +1697,22 @@ public void suspendAsync(@Nullable AsyncCallback cb) { } public void closeAsync(@Nullable AsyncCallback cb) { + closeAsync(null, cb); + } + + // Frees `contextId`'s voices and nodes; the shared engine suspends once no realtime context is open. + public void closeAsync(@Nullable String contextId, @Nullable AsyncCallback cb) { final Looper callerLooper = captureCallerLooper(); + if (contextId != null) { + try { + releaseContext(contextId, true); + } catch (Throwable ignored) { + } + } decodeExecutor.submit(() -> { boolean ok = true; try { - if (nativeAvailable) nativeSuspend(); + if (nativeAvailable && (contextId == null || openRealtimeContexts.isEmpty())) nativeSuspend(); } catch (Throwable t) { ok = false; } @@ -2548,6 +2569,33 @@ void cancelPannerScheduledValues(String id, int paramType, double time) { return out; } + private native void nativeDetachFrom(String voiceId, String targetId, int output, int input); + + /** + * AudioNode.disconnect for node {@code nodeId}: detaches the voices feeding it from {@code node} + * (every target when null) at {@code output}/{@code input} (any when negative). + * A source node is its own voice. + */ + void disconnectNode(String nodeId, boolean isSource, @Nullable AudioNode node, int output, int input) { + if (nodeId == null) return; + String destId = node instanceof NativeObject ? ((NativeObject) node).getId() : null; + if (node != null && destId == null) return; + if (destId != null && isDestinationNode(destId)) return; + Set voices = isSource ? java.util.Collections.singleton(nodeId) : getNodeSourcesSnapshot(nodeId); + if (!isSource && voices.isEmpty()) { + // Connected before it had sources: the target was attached as a voice fed by this node. + if (destId != null) { + if (nativeAvailable) nativeDetachFrom(destId, nodeId, output, input); + unregisterNodeSource(destId, nodeId); + } + return; + } + for (String voice : voices) { + if (nativeAvailable) nativeDetachFrom(voice, destId == null ? "" : destId, output, input); + if (destId != null) unregisterNodeSource(destId, voice); + } + } + void attachPannerToVoice(String voiceId, String pannerId) { if (voiceId == null || pannerId == null) return; if (nativeAvailable) { @@ -2979,6 +3027,9 @@ String switchBufferSource(String trackId, @Nullable AudioBuffer buffer) { return null; } + // The new voice belongs to the track's context, and its engine (an offline one has its own). + String contextId = findContextForTrack(trackId); + String scope = contextId != null ? contextId : trackId; if (nativeAvailable) { try { int sampleRate = sampleRates.containsKey(buffer.id) ? sampleRates.get(buffer.id) : 48000; @@ -2989,7 +3040,7 @@ String switchBufferSource(String trackId, @Nullable AudioBuffer buffer) { int resolvedChannels = channels > 0 ? channels : channelData.length; resolvedChannels = Math.min(resolvedChannels, channelData.length); if (resolvedChannels > 0) { - String newId = nativeCreateBufferSourcePlanar(trackId, channelData, sampleRate, resolvedChannels); + String newId = nativeCreateBufferSourcePlanar(scope, channelData, sampleRate, resolvedChannels); if (newId != null && !newId.isEmpty()) { java.nio.ByteBuffer src = directBuffers.get(buffer.id); if (src != null) directBuffers.put(newId, src); @@ -2998,6 +3049,7 @@ String switchBufferSource(String trackId, @Nullable AudioBuffer buffer) { getOrCreate(newId).incrementAndGet(); sampleRates.put(newId, sampleRate); bufferChannels.put(newId, resolvedChannels); + if (contextId != null) addToContextSet(contextTracksMap, contextId, newId); return newId; } } @@ -3011,12 +3063,13 @@ String switchBufferSource(String trackId, @Nullable AudioBuffer buffer) { srcView.position(src.position()); srcView.limit(src.limit()); java.nio.ByteBuffer srcSlice = srcView.slice(); - String newId = nativeCreateBufferSourceDirect(trackId, srcSlice, sampleRate, channels, bytesPerSample); + String newId = nativeCreateBufferSourceDirect(scope, srcSlice, sampleRate, channels, bytesPerSample); if (newId == null || newId.isEmpty()) return null; directBuffers.put(newId, src); getOrCreate(newId).incrementAndGet(); sampleRates.put(newId, sampleRate); bufferChannels.put(newId, channels); + if (contextId != null) addToContextSet(contextTracksMap, contextId, newId); return newId; } catch (Throwable ignored) { return null; diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContextInstance.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContextInstance.java index fc5ad81f..ac541999 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContextInstance.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioContextInstance.java @@ -98,7 +98,7 @@ public void suspendAsync(@androidx.annotation.Nullable AudioContext.AsyncCallbac } public void closeAsync(@androidx.annotation.Nullable AudioContext.AsyncCallback cb) { - AudioContext.getInstance().closeAsync(cb); + AudioContext.getInstance().closeAsync(id, cb); } public AudioOscillatorNode createOscillatorNodeFrequency(String type, double frequency) { diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioIIRNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioIIRNode.java index 8732e35c..af89272c 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioIIRNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioIIRNode.java @@ -66,30 +66,8 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", 0, 0); - } else if (node instanceof GainNode) { - context.attachGainToVoice(sourceId, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachBiquadToVoice(sourceId, "", 0, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachBiquadToVoice(destId, "", 0, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override @@ -106,12 +84,14 @@ public void disconnect(int output) { @Override public void disconnect(AudioNode node, int output) { - disconnect(node); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override public void disconnect(AudioNode node, int output, int input) { - disconnect(node); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, input); } @Override diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioPannerNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioPannerNode.java index af5bf703..53df4b45 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioPannerNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioPannerNode.java @@ -166,29 +166,8 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - String destId = ((NativeObject) node).getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof GainNode) { - context.attachGainToVoice(sourceId, "", 0, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachPannerToVoice(sourceId, "", 0, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachPannerToVoice(destId, ""); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override @@ -205,56 +184,14 @@ public void disconnect(int output) { @Override public void disconnect(AudioNode node, int output) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - String destId = ((NativeObject) node).getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof GainNode) { - context.attachGainToVoice(sourceId, "", output, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", output, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachPannerToVoice(sourceId, "", output, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachPannerToVoice(destId, "", output, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override public void disconnect(AudioNode node, int output, int input) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - String destId = ((NativeObject) node).getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof GainNode) { - context.attachGainToVoice(sourceId, "", output, input); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", output, input); - } else if (!context.isDestinationNode(destId)) { - context.attachPannerToVoice(sourceId, "", output, input); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachPannerToVoice(destId, "", output, input); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, input); } @Override diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioScheduledSourceNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioScheduledSourceNode.java index 298e87b7..463de124 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioScheduledSourceNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/AudioScheduledSourceNode.java @@ -78,76 +78,30 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - String destId = ((NativeObject) node).getId(); - if (destId != null) { - AudioContext context = AudioContext.getInstance(); - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(id, "", 0, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(id, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(id, "", 0, 0); - } - context.unregisterNodeSource(destId, id); - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, true, node, -1, -1); } @Override public void disconnect() { - AudioContext.getInstance().attachPannerToVoice(id, "", 0, 0); - AudioContext.getInstance().attachBiquadToVoice(id, "", 0, 0); - AudioContext.getInstance().attachGainToVoice(id, "", 0, 0); + AudioContext.getInstance().disconnectNode(id, true, null, -1, -1); } @Override public void disconnect(int output) { - AudioContext.getInstance().attachPannerToVoice(id, "", output, 0); - AudioContext.getInstance().attachBiquadToVoice(id, "", output, 0); - AudioContext.getInstance().attachGainToVoice(id, "", output, 0); + disconnect(); } @Override public void disconnect(AudioNode node, int output) { - if (node instanceof NativeObject) { - String destId = ((NativeObject) node).getId(); - if (destId != null) { - AudioContext context = AudioContext.getInstance(); - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(id, "", output, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(id, "", output, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(id, "", output, 0); - } - context.unregisterNodeSource(destId, id); - return; - } - } - disconnect(output); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, true, node, -1, -1); } @Override public void disconnect(AudioNode node, int output, int input) { - if (node instanceof NativeObject) { - String destId = ((NativeObject) node).getId(); - if (destId != null) { - AudioContext context = AudioContext.getInstance(); - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(id, "", output, input); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(id, "", output, input); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(id, "", output, input); - } - context.unregisterNodeSource(destId, id); - return; - } - } - disconnect(output); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, true, node, -1, input); } @Override diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ChannelMergerNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ChannelMergerNode.java index 4d32614b..0105173b 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ChannelMergerNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ChannelMergerNode.java @@ -63,30 +63,8 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", 0, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", 0, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", 0, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override @@ -103,58 +81,14 @@ public void disconnect(int output) { @Override public void disconnect(AudioNode node, int output) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", output, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", output, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", output, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", output, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override public void disconnect(AudioNode node, int output, int input) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", output, input); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", output, input); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", output, input); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", output, input); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, input); } @Override diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ChannelSplitterNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ChannelSplitterNode.java index f6b47594..a3d23f3d 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ChannelSplitterNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ChannelSplitterNode.java @@ -70,30 +70,8 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", 0, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", 0, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", 0, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override @@ -105,65 +83,19 @@ public void disconnect() { @Override public void disconnect(int output) { - disconnect(); + AudioContext.getInstance().disconnectNode(id, false, null, output, -1); } @Override public void disconnect(AudioNode node, int output) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - int sourceOutput = clampOutput(output); - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", sourceOutput, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", sourceOutput, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", sourceOutput, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", sourceOutput, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, output, -1); } @Override public void disconnect(AudioNode node, int output, int input) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - int sourceOutput = clampOutput(output); - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", sourceOutput, input); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", sourceOutput, input); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", sourceOutput, input); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", sourceOutput, input); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, output, input); } @Override diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ConvolverNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ConvolverNode.java index 0506ccce..136f4fd2 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ConvolverNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/ConvolverNode.java @@ -91,30 +91,8 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", 0, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", 0, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", 0, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override @@ -131,12 +109,14 @@ public void disconnect(int output) { @Override public void disconnect(AudioNode node, int output) { - disconnect(node); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override public void disconnect(AudioNode node, int output, int input) { - disconnect(node); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, input); } @Override diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/DelayNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/DelayNode.java index 04c37601..cb8b89f6 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/DelayNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/DelayNode.java @@ -60,30 +60,8 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", 0, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", 0, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", 0, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override @@ -97,10 +75,16 @@ public void disconnect() { public void disconnect(int output) { disconnect(); } @Override - public void disconnect(AudioNode node, int output) { disconnect(node); } + public void disconnect(AudioNode node, int output) { + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); + } @Override - public void disconnect(AudioNode node, int output, int input) { disconnect(node); } + public void disconnect(AudioNode node, int output, int input) { + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, input); + } @Override public void release() { diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/DynamicsCompressorNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/DynamicsCompressorNode.java index ad3243b4..fa46efbb 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/DynamicsCompressorNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/DynamicsCompressorNode.java @@ -116,30 +116,8 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", 0, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", 0, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", 0, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override @@ -156,58 +134,14 @@ public void disconnect(int output) { @Override public void disconnect(AudioNode node, int output) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", output, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", output, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", output, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", output, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override public void disconnect(AudioNode node, int output, int input) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", output, input); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", output, input); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", output, input); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", output, input); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, input); } @Override diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/GainNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/GainNode.java index 8c6dac49..c2759489 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/GainNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/GainNode.java @@ -75,30 +75,8 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", 0, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", 0, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", 0, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override @@ -115,58 +93,14 @@ public void disconnect(int output) { @Override public void disconnect(AudioNode node, int output) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", output, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", output, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", output, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", output, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override public void disconnect(AudioNode node, int output, int input) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", output, input); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", output, input); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", output, input); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", output, input); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, input); } @Override diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WaveShaperNode.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WaveShaperNode.java index 3063673c..a7316563 100644 --- a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WaveShaperNode.java +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WaveShaperNode.java @@ -65,30 +65,8 @@ public void connect(AudioNode node, int output, int input) { @Override public void disconnect(AudioNode node) { - if (node instanceof NativeObject) { - AudioContext context = AudioContext.getInstance(); - NativeObject object = (NativeObject) node; - String destId = object.getId(); - if (destId != null) { - java.util.Set sources = context.getNodeSourcesSnapshot(id); - for (String sourceId : sources) { - if (node instanceof AudioPannerNode) { - context.attachPannerToVoice(sourceId, "", 0, 0); - } else if (node instanceof AudioBiquadNode) { - context.attachBiquadToVoice(sourceId, "", 0, 0); - } else if (!context.isDestinationNode(destId)) { - context.attachGainToVoice(sourceId, "", 0, 0); - } - context.unregisterNodeSource(destId, sourceId); - } - if (sources.isEmpty() && !context.isDestinationNode(destId)) { - context.attachGainToVoice(destId, "", 0, 0); - context.unregisterNodeSource(destId, id); - } - return; - } - } - disconnect(); + if (node == null) disconnect(); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override @@ -105,12 +83,14 @@ public void disconnect(int output) { @Override public void disconnect(AudioNode node, int output) { - disconnect(node); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, -1); } @Override public void disconnect(AudioNode node, int output, int input) { - disconnect(node); + if (node == null) disconnect(output); + else AudioContext.getInstance().disconnectNode(id, false, node, -1, input); } @Override 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 index 98a32f10..df245870 100644 --- 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 @@ -119,21 +119,7 @@ private void disconnectOutput(int output, @Nullable AudioNode node) { } 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); + AudioContext.getInstance().disconnectNode(getOutputId(output), true, destId == null ? null : node, -1, -1); } @Override diff --git a/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WorkletWaker.java b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WorkletWaker.java new file mode 100644 index 00000000..99c2464e --- /dev/null +++ b/packages/audio-context/src-native/android/audiocontext/src/main/java/org/nativescript/audiocontext/WorkletWaker.java @@ -0,0 +1,33 @@ +package org.nativescript.audiocontext; + +import androidx.annotation.Nullable; + +/** Runs an AudioWorklet Worker's drain on its own looper whenever the engine requests a quantum. */ +public final class WorkletWaker { + static { + System.loadLibrary("native-audio"); + } + + private long handle; + + private WorkletWaker(long handle) { + this.handle = handle; + } + + /** Call on the Worker thread; null where that thread has no looper. */ + @Nullable + public static WorkletWaker attach(Runnable drain) { + long handle = nativeAttach(drain); + return handle != 0 ? new WorkletWaker(handle) : null; + } + + public synchronized void detach() { + if (handle == 0) return; + nativeDetach(handle); + handle = 0; + } + + private static native long nativeAttach(Runnable drain); + + private static native void nativeDetach(long handle); +} diff --git a/packages/audio-context/typings/android.d.ts b/packages/audio-context/typings/android.d.ts index e914b8a3..27325028 100644 --- a/packages/audio-context/typings/android.d.ts +++ b/packages/audio-context/typings/android.d.ts @@ -39,6 +39,8 @@ declare module org { export module audiocontext { export class AudioBiquadNode implements org.nativescript.audiocontext.NativeObject, org.nativescript.audiocontext.AudioNode { public static class: java.lang.Class; + public getType(): string; + public setType(type: string): void; public connect(node: org.nativescript.audiocontext.AudioNode, output: number): void; public connect(param0: org.nativescript.audiocontext.AudioNode): void; public disconnect(param0: org.nativescript.audiocontext.AudioNode): void; diff --git a/tools/demo/canvas/spec/audio-offline-render.ts b/tools/demo/canvas/spec/audio-offline-render.ts index dbbb48aa..efa01f9a 100644 --- a/tools/demo/canvas/spec/audio-offline-render.ts +++ b/tools/demo/canvas/spec/audio-offline-render.ts @@ -1,5 +1,5 @@ -import { OfflineAudioContext } from '@nativescript/audio-context'; -import { isAndroid } from '@nativescript/core'; +import { AudioBuffer, OfflineAudioContext } from '@nativescript/audio-context'; +import { isAndroid, isIOS } from '@nativescript/core'; import { suite, test, skip, equal, closeTo, ok } from './harness'; // OfflineAudioContext rendering, against what Chrome does. @@ -13,6 +13,13 @@ function constant(context: any, offset: number, when = 0) { return source; } +function stereo(length: number, left: number, right: number) { + const buffer = new AudioBuffer({ numberOfChannels: 2, length, sampleRate: RATE }); + buffer.copyToChannel(new Float32Array(length).fill(left), 0); + buffer.copyToChannel(new Float32Array(length).fill(right), 1); + return buffer; +} + export function registerAudioOfflineRenderSpec() { suite('audio.offline.render', () => { test('renders the whole length and closes', async () => { @@ -111,6 +118,72 @@ export function registerAudioOfflineRenderSpec() { equal(samples[Q], 0.875); }); + const SPLIT_FILTER = 'a splitter output into a filter filters only that channel'; + if (isIOS) skip(SPLIT_FILTER, "iOS doesn't filter a single splitter output"); + else test(SPLIT_FILTER, async () => { + const context = new OfflineAudioContext(2, Q * 32, RATE); + const source: any = context.createBufferSource(); + source.buffer = stereo(Q * 32, 1, 1); + const splitter = context.createChannelSplitter({ numberOfOutputs: 2 }); + const merger = context.createChannelMerger({ numberOfInputs: 2 }); + // A highpass blocks DC: only the right channel goes through it. + const filter = context.createBiquadFilter(); + filter.type = 'highpass'; + filter.frequency.value = 1000; + source.connect(splitter); + splitter.connect(merger, 0, 0); + splitter.connect(filter, 1); + filter.connect(merger, 0, 1); + merger.connect(context.destination); + source.start(0); + const rendered = await context.startRendering(); + const last = Q * 32 - 1; + closeTo(rendered.getChannelData(0)[last], 1, 1e-4, 'left passes'); + closeTo(rendered.getChannelData(1)[last], 0, 1e-3, 'right is filtered'); + }); + + test('disconnect(node) cuts only that connection', async () => { + const context = new OfflineAudioContext(1, Q * 2, RATE); + const first = context.createGain(); + const half = context.createGain({ gain: 0.5 } as any); + const quarter = context.createGain({ gain: 0.25 } as any); + half.connect(context.destination); + quarter.connect(context.destination); + constant(context, 1).connect(first); + first.connect(half); + first.disconnect(half); + first.connect(quarter); + const samples = (await context.startRendering()).getChannelData(0); + equal(samples[0], 0.25, 'through the remaining connection'); + equal(samples[Q], 0.25, 'and only it'); + }); + + test('a source disconnected from a delay plays undelayed', async () => { + const context = new OfflineAudioContext(1, Q * 2, RATE); + const delay = context.createDelay(1); + delay.delayTime.value = Q / RATE; + delay.connect(context.destination); + const gain = context.createGain({ gain: 0.5 } as any); + gain.connect(context.destination); + const source = constant(context, 1); + source.connect(delay); + source.disconnect(delay); + source.connect(gain); + const samples = (await context.startRendering()).getChannelData(0); + equal(samples[0], 0.5, 'from the first frame'); + equal(samples[Q], 0.5, 'and not doubled by the delay'); + }); + + test('a stereo buffer plays its mono down-mix in a mono context', async () => { + const context = new OfflineAudioContext(1, Q * 2, RATE); + const source: any = context.createBufferSource(); + source.buffer = stereo(Q * 2, 1, 0.5); + source.connect(context.destination); + source.start(0); + const samples = (await context.startRendering()).getChannelData(0); + equal(samples[0], 0.75, 'the average of left and right'); + }); + const PARAM_INPUT = 'a node connected to a gain or delayTime param adds to it per frame'; if (isAndroid) { skip(PARAM_INPUT, 'no AudioNode.connect(AudioParam) on Android'); diff --git a/tools/demo/canvas/spec/audio-scheduling.ts b/tools/demo/canvas/spec/audio-scheduling.ts index db77bec9..6c4ece39 100644 --- a/tools/demo/canvas/spec/audio-scheduling.ts +++ b/tools/demo/canvas/spec/audio-scheduling.ts @@ -281,6 +281,20 @@ export function registerAudioSchedulingSpec() { }); } + test("close stops the context's sources", async () => { + const closed = new AudioContext(); + const source = closed.createConstantSource({ offset: 1 }); + source.connect(closed.destination); + source.start(); + await until(closed, closed.currentTime + 0.1); + await closed.close(); + const { context, analyser } = await runningContext(); + await until(context, context.currentTime + 0.2); + const rms = rmsOf(analyser); + await context.close(); + ok(quiet(rms), `silent in the next context, rms ${rms}`); + }); + test('oscillator sounds only between start(when) and stop(when)', async () => { const { context, analyser } = await runningContext(); const oscillator = context.createOscillator({ type: 'square', frequency: 440 }); diff --git a/tools/demo/canvas/spec/audio-worklet.ts b/tools/demo/canvas/spec/audio-worklet.ts index c146d1b4..34caa132 100644 --- a/tools/demo/canvas/spec/audio-worklet.ts +++ b/tools/demo/canvas/spec/audio-worklet.ts @@ -1,4 +1,5 @@ -import { AudioContext, AudioWorkletNode, OfflineAudioContext } from '@nativescript/audio-context'; +import { AudioBuffer, AudioContext, AudioWorkletNode, OfflineAudioContext } from '@nativescript/audio-context'; +import { isIOS } from '@nativescript/core'; import { suite, test, skip, equal, closeTo, ok } from './harness'; // AudioWorkletNode inputs, outputs and fan-in, against what Chrome does. @@ -43,6 +44,20 @@ class SumInputs extends AudioWorkletProcessor { } } registerProcessor('sum-inputs', SumInputs); + +// The picked input channel; -1 unless the input has the expected channel count. +class PickChannel extends AudioWorkletProcessor { + constructor(options) { + super(); + this.pick = options.processorOptions; + } + process(inputs, outputs) { + const input = inputs[0]; + outputs[0][0].fill(input.length === this.pick.count ? input[this.pick.channel][0] : -1); + return true; + } +} +registerProcessor('pick-channel', PickChannel); `; const MODULE = 'data:text/javascript,' + encodeURIComponent(PROCESSORS); @@ -61,6 +76,16 @@ function constant(context: any, offset: number, when = 0) { const MONO = { channelCount: 1, channelCountMode: 'explicit' } as any; +/** A buffer source playing `levels[c]` on channel c. */ +function levelSource(context: any, levels: number[]) { + const buffer = new AudioBuffer({ numberOfChannels: levels.length, length: Q * 2, sampleRate: RATE }); + levels.forEach((level, c) => buffer.copyToChannel(new Float32Array(Q * 2).fill(level), c)); + const source = context.createBufferSource(); + source.buffer = buffer; + source.start(0); + return source; +} + export function registerAudioWorkletSpec() { suite('audio.worklet', () => { if (typeof (globalThis as any).Worker !== 'function') { @@ -132,6 +157,39 @@ export function registerAudioWorkletSpec() { closeTo(samples[Q * 4], 1.25, 1e-6, 'weighted sum of the inputs'); }); + const SPEAKERS = 'mixes each input to its own channelCount with the speaker rules'; + if (isIOS) skip(SPEAKERS, "iOS mixes an input at the context's channel count first"); + else test(SPEAKERS, async () => { + const h = Math.SQRT1_2; + // [source channel levels, channelCount, the input's channels] + const cases: [number[], number, number[]][] = [ + [[1, 0.5], 2, [1, 0.5]], + [[0.25], 2, [0.25, 0.25]], + [[0.25], 4, [0.25, 0.25, 0, 0]], + [[0.25], 6, [0, 0, 0.25, 0, 0, 0]], + [[1, 0.5], 1, [0.75]], + [[1, 0.5], 4, [1, 0.5, 0, 0]], + [[0.1, 0.2, 0.3, 0.4], 1, [0.25]], + [[0.1, 0.2, 0.3, 0.4], 2, [0.2, 0.3]], + [[0.1, 0.2, 0.3, 0.4], 6, [0.1, 0.2, 0, 0, 0.3, 0.4]], + [[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], 1, [h * 0.3 + 0.3 + 0.5 * 1.1]], + [[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], 2, [0.1 + h * 0.8, 0.2 + h * 0.9]], + [[0.1, 0.2, 0.3, 0.4, 0.5, 0.6], 4, [0.1 + h * 0.3, 0.2 + h * 0.3, 0.5, 0.6]], + ]; + // A mono context: the input still gets every source channel. + for (const [levels, channelCount, expected] of cases) { + for (let c = 0; c < channelCount; c++) { + const context = await offline(Q * 2, 1); + const processorOptions = { channel: c, count: channelCount }; + const node = new AudioWorkletNode(context, 'pick-channel', { channelCount, channelCountMode: 'explicit', outputChannelCount: [1], processorOptions } as any); + levelSource(context, levels).connect(node); + node.connect(context.destination); + const got = (await context.startRendering()).getChannelData(0)[Q]; + closeTo(got, expected[c], 1e-5, `${levels.length} channels into ${channelCount}, channel ${c}`); + } + } + }); + test('plays each output from its own bus', async () => { for (const output of [0, 1]) { const context = await offline();