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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions packages/audio-context/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
20 changes: 16 additions & 4 deletions packages/audio-context/audio-worklet-ring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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();
};

Expand Down
52 changes: 21 additions & 31 deletions packages/audio-context/index.android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,8 @@ class NativeEngine {
int64_t offlineLimitFrame_ = 0;
// The render clock: CLOCK_MONOTONIC ns for realtime, virtual for offline.
std::atomic<int64_t> nowNs_{0};
// Realtime: the next block's first frame on the render thread's frame clock.
int64_t renderClockNs_ = 0;

void ensureStream();

Expand Down Expand Up @@ -237,7 +239,7 @@ class NativeEngine {
std::vector<std::string> 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<float> inMix;
bool inActive[kWorkletMaxPorts] = {};
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -509,4 +509,36 @@ inline float getScheduledGainValueAt(const std::vector<NativeEngine::ParamEvent>
return static_cast<float>(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<typename Read>
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
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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<int>(joutput);
cmd.inputIndex = static_cast<int>(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) {
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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));
Expand Down
Loading
Loading