Add opt-in WASM AEC3 echo canceller for speaker+mic setups

Off-by-default toggle in the recording options (Aufnahmeoptionen), using
@ennuicastr/webrtcaec3.js (Google WebRTC's AEC3, compiled to WASM) as a
stronger supplement to native browser echo cancellation - addresses the
speaker+studio-mic (no headset) case from issue #2. Native echoCancellation
is turned off while this is enabled since running both fights the same
signal. Assets are synced from node_modules into public/vendor/ at
dev/build time rather than committed, since the module's glue code needs
its .wasm co-located under an exact, unhashed filename.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
MoepchiandClaude Sonnet 5 committed 2026-09-17 18:12:52 +00:00
1 parent 390a2b5749
commit 258d108f59
9 files changed
+207 -98

No files matched your search

+7 -96
View File
@@ -8,6 +8,7 @@
"name": "webspeak3-web",
"version": "0.0.0",
"dependencies": {
"@ennuicastr/webrtcaec3.js": "^0.3.0",
"fflate": "^0.8.3",
"react": "^19.2.7",
"react-dom": "^19.2.7"
@@ -1619,6 +1620,12 @@
"tslib": "^2.4.0"
}
},
"node_modules/@ennuicastr/webrtcaec3.js": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@ennuicastr/webrtcaec3.js/-/webrtcaec3.js-0.3.0.tgz",
"integrity": "sha512-ZfijX3Pzqr2zY2nTBE+APGB4X8q3up5vqQgmuolCvC2WTYYWvivf3GGVFZnTr6n/kZa9w3Y5P4ugwcrOmsqXZQ==",
"license": "BSD-3-Clause"
},
"node_modules/@isaacs/cliui": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-9.0.0.tgz",
@@ -1698,9 +1705,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1869,9 +1873,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1889,9 +1890,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1909,9 +1907,6 @@
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1929,9 +1924,6 @@
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1949,9 +1941,6 @@
"riscv64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1969,9 +1958,6 @@
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -1989,9 +1975,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2009,9 +1992,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2182,9 +2162,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2202,9 +2179,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2222,9 +2196,6 @@
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2242,9 +2213,6 @@
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2262,9 +2230,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2282,9 +2247,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2617,9 +2579,6 @@
"arm"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2634,9 +2593,6 @@
"arm"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2651,9 +2607,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2668,9 +2621,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2685,9 +2635,6 @@
"loong64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2702,9 +2649,6 @@
"loong64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2719,9 +2663,6 @@
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2736,9 +2677,6 @@
"ppc64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2753,9 +2691,6 @@
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2770,9 +2705,6 @@
"riscv64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2787,9 +2719,6 @@
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2804,9 +2733,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@@ -2821,9 +2747,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@@ -4891,9 +4814,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -4915,9 +4835,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -4939,9 +4856,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MPL-2.0",
"optional": true,
"os": [
@@ -4963,9 +4877,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MPL-2.0",
"optional": true,
"os": [
+3
View File
@@ -4,12 +4,15 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"predev": "node scripts/sync-aec3-assets.mjs",
"dev": "vite",
"prebuild": "node scripts/sync-aec3-assets.mjs",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview"
},
"dependencies": {
"@ennuicastr/webrtcaec3.js": "^0.3.0",
"fflate": "^0.8.3",
"react": "^19.2.7",
"react-dom": "^19.2.7"
+20
View File
@@ -0,0 +1,20 @@
// Copies the AEC3 WASM module's prebuilt assets into public/vendor/ so they're
// served unhashed, at the exact filenames the module's own glue code expects
// (it resolves its .wasm next to its own <script src> by a hardcoded literal
// name - see web/src/aec3.ts). Run via predev/prebuild rather than committed,
// so the binary blobs never enter git.
import { copyFileSync, mkdirSync, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const webRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const pkgDir = path.join(webRoot, "node_modules/@ennuicastr/webrtcaec3.js");
const { version } = JSON.parse(readFileSync(path.join(pkgDir, "package.json"), "utf8"));
const outDir = path.join(webRoot, "public/vendor");
mkdirSync(outDir, { recursive: true });
// The .js is renamed to a stable name (we choose its <script src>, so nothing
// depends on this filename); the .wasm keeps its exact original name (the glue
// code's own lookup is hardcoded to it).
copyFileSync(path.join(pkgDir, "dist", `webrtcaec3-${version}.js`), path.join(outDir, "webrtcaec3.js"));
copyFileSync(path.join(pkgDir, "dist", `webrtcaec3-${version}.wasm`), path.join(outDir, `webrtcaec3-${version}.wasm`));
+63 -1
View File
@@ -25,6 +25,7 @@ import {
listAudioOutputDevices,
pickAudioOutputDevice,
} from "./voice";
import { createAec3, type Aec3Instance } from "./aec3";
import { LanguageProvider, useLanguage, useT, type LangPref } from "./i18n";
import {
StreamAccess,
@@ -266,6 +267,7 @@ const PLAYBACK_VOLUME_KEY = "webspeak3:playback-volume";
const NOISE_SUPPRESSION_KEY = "webspeak3:noise-suppression";
const ECHO_CANCELLATION_KEY = "webspeak3:echo-cancellation";
const AUTO_GAIN_CONTROL_KEY = "webspeak3:auto-gain-control";
const AEC3_ENABLED_KEY = "webspeak3:aec3-enabled";
const VAD_HANGOVER_KEY = "webspeak3:vad-hangover";
const DESIGN_THEME_KEY = "webspeak3:design-theme";
// The user's actual pick - "standard" | "nova" | "greenteaspeak" | "custom:<id>".
@@ -4928,6 +4930,9 @@ interface AudioSettings {
onToggleEchoCancellation: () => void;
autoGainControlEnabled: boolean;
onToggleAutoGainControl: () => void;
aec3Enabled: boolean;
aec3Loading: boolean;
onToggleAec3: () => void;
}
function MicLevelBar({ levelRef, active }: { levelRef: React.MutableRefObject<number>; active: boolean }) {
@@ -5106,6 +5111,7 @@ function AufnahmePanel({ audio }: { audio: AudioSettings }) {
<input
type="checkbox"
checked={audio.echoCancellationEnabled}
disabled={audio.aec3Enabled}
onChange={audio.onToggleEchoCancellation}
/>
{t("recording.echoCancellation")}
@@ -5126,6 +5132,16 @@ function AufnahmePanel({ audio }: { audio: AudioSettings }) {
/>
{t("recording.autoGainControl")}
</label>
<label className="ts-options-checkbox">
<input
type="checkbox"
checked={audio.aec3Enabled}
disabled={audio.aec3Loading}
onChange={audio.onToggleAec3}
/>
{t("recording.aec3")}
{audio.aec3Loading ? "…" : ""}
</label>
</div>
</fieldset>
</div>
@@ -6160,6 +6176,11 @@ function AppInner() {
const [autoGainControlEnabled, setAutoGainControlEnabled] = useState(() =>
loadBoolPref(AUTO_GAIN_CONTROL_KEY, true)
);
// Off by default: a heavier, opt-in alternative/supplement to native AEC for
// speaker+mic (no headset) setups (github.com/Moepchi/webspeak3 issue #2).
const [aec3Enabled, setAec3Enabled] = useState(() => loadBoolPref(AEC3_ENABLED_KEY, false));
const [aec3Loading, setAec3Loading] = useState(false);
const aec3Ref = useRef<Aec3Instance | null>(null);
const [micTestOn, setMicTestOn] = useState(false);
const [connectionsMenuOpen, setConnectionsMenuOpen] = useState(false);
// Nova-theme-only: collapses the classic menu items behind a hamburger button.
@@ -6339,6 +6360,10 @@ function AppInner() {
localStorage.setItem(AUTO_GAIN_CONTROL_KEY, autoGainControlEnabled ? "1" : "0");
}, [autoGainControlEnabled]);
useEffect(() => {
localStorage.setItem(AEC3_ENABLED_KEY, aec3Enabled ? "1" : "0");
}, [aec3Enabled]);
useEffect(() => {
if (inputDeviceId) localStorage.setItem(INPUT_DEVICE_KEY, inputDeviceId);
}, [inputDeviceId]);
@@ -7801,9 +7826,12 @@ function AppInner() {
threshold: vadThreshold,
hangoverSeconds: vadHangover,
deviceId: overrides?.deviceId ?? (inputDeviceId || undefined),
echoCancellation: overrides?.echoCancellation ?? echoCancellationEnabled,
// AEC3 replaces (not stacks with) the native canceller - running both
// fights over the same signal.
echoCancellation: aec3Ref.current ? false : (overrides?.echoCancellation ?? echoCancellationEnabled),
noiseSuppression: overrides?.noiseSuppression ?? noiseSuppressionEnabled,
autoGainControl: overrides?.autoGainControl ?? autoGainControlEnabled,
aec3: aec3Ref.current ?? undefined,
});
await mic.start();
micCaptureRef.current = mic;
@@ -7868,6 +7896,37 @@ function AppInner() {
if (micCaptureRef.current) void restartMic({ autoGainControl: next });
};
const teardownAec3 = () => {
audioPlayerRef.current?.detachAecRenderTap();
aec3Ref.current?.free();
aec3Ref.current = null;
};
const handleToggleAec3 = async () => {
if (aec3Enabled) {
setAec3Enabled(false);
teardownAec3();
if (micCaptureRef.current) void restartMic({});
return;
}
setAec3Loading(true);
try {
const audioContext = ensureAudioContext();
if (audioContext.state === "suspended") await audioContext.resume();
const aec3 = await createAec3(SAMPLE_RATE, 2, 1);
aec3Ref.current = aec3;
audioPlayerRef.current?.attachAecRenderTap(aec3);
setAec3Enabled(true);
if (micCaptureRef.current) await restartMic({});
} catch (error) {
appendLog({ text: `Advanced echo cancellation failed to load: ${(error as Error).message}`, kind: "error" });
teardownAec3();
setAec3Enabled(false);
} finally {
setAec3Loading(false);
}
};
const handleToggleMicTest = () => {
const next = !micTestOn;
setMicTestOn(next);
@@ -9940,6 +9999,9 @@ function AppInner() {
onToggleEchoCancellation: handleToggleEchoCancellation,
autoGainControlEnabled,
onToggleAutoGainControl: handleToggleAutoGainControl,
aec3Enabled,
aec3Loading,
onToggleAec3: handleToggleAec3,
}}
/>
)}
+58
View File
@@ -0,0 +1,58 @@
// Lazy loader for Google WebRTC's AEC3 (compiled to WASM via
// @ennuicastr/webrtcaec3.js), an opt-in, stronger alternative to the browser's
// native echo cancellation for speaker+mic (no headset) setups where native
// AEC often isn't enough (github.com/Moepchi/webspeak3 issue #2). Loaded as a
// plain <script> tag rather than bundled: the module's own glue code resolves
// its .wasm file next to its own <script src>, by a name it decides itself -
// see scripts/sync-aec3-assets.mjs for how that file gets there.
export interface Aec3Instance {
free(): void;
analyze(data: Float32Array[]): void;
processSize(data: Float32Array[]): number;
process(out: Float32Array[], data: Float32Array[]): void;
}
interface Aec3Module {
AEC3: new (sampleRate: number, renderChannels: number, captureChannels: number) => Aec3Instance;
}
declare global {
interface Window {
WebRtcAec3?: () => Promise<Aec3Module>;
}
}
let modulePromise: Promise<Aec3Module> | null = null;
function loadScript(src: string): Promise<void> {
return new Promise((resolve, reject) => {
const el = document.createElement("script");
el.src = src;
el.onload = () => resolve();
el.onerror = () => reject(new Error(`Failed to load ${src}`));
document.head.appendChild(el);
});
}
function loadModule(): Promise<Aec3Module> {
if (!modulePromise) {
modulePromise = loadScript("/vendor/webrtcaec3.js").then(() => {
if (!window.WebRtcAec3) throw new Error("AEC3 script loaded but did not register window.WebRtcAec3");
return window.WebRtcAec3();
});
}
return modulePromise;
}
/** Creates a fresh AEC3 instance. `renderChannels` must match the channel
* count passed to `analyze()`, `captureChannels` the count passed to
* `process()`. */
export async function createAec3(
sampleRate: number,
renderChannels: number,
captureChannels: number,
): Promise<Aec3Instance> {
const mod = await loadModule();
return new mod.AEC3(sampleRate, renderChannels, captureChannels);
}
+1
View File
@@ -337,6 +337,7 @@
"recording.echoCancellation": "Echo Dämpfung",
"recording.noiseSuppression": "Hintergrundgeräusche entfernen",
"recording.autoGainControl": "Automatische Verstärkung",
"recording.aec3": "Erweiterte Echounterdrückung (Beta, mehr CPU-Last)",
"info.address": "Adresse:",
"info.version": "Version:",
"info.license": "Lizenz:",
+1
View File
@@ -337,6 +337,7 @@
"recording.echoCancellation": "Echo cancellation",
"recording.noiseSuppression": "Remove background noise",
"recording.autoGainControl": "Automatic gain control",
"recording.aec3": "Advanced echo cancellation (Beta, more CPU load)",
"info.address": "Address:",
"info.version": "Version:",
"info.license": "License:",
+51 -1
View File
@@ -4,6 +4,8 @@
// microphone -> server direction (which it Opus-encodes), stereo mixed
// for the server -> speakers direction (already decoded/mixed for us).
import type { Aec3Instance } from "./aec3";
export const SAMPLE_RATE = 48000;
export const FRAME_SAMPLES = 960; // 20ms @ 48kHz
@@ -41,6 +43,10 @@ export interface MicCaptureOptions {
* browser's own AEC runs can bring back audible echo residue in speaker+mic
* (no headset) setups - some users get a cleaner result with it off. */
autoGainControl?: boolean;
/** When set, mic audio is run through this AEC3 instance (opts:
* captureNumChannels=1) before VAD/encoding, in place of relying solely on
* the browser's native echoCancellation. */
aec3?: Aec3Instance;
}
/**
@@ -67,6 +73,8 @@ export class MicCapture {
private echoCancellation: boolean;
private noiseSuppression: boolean;
private autoGainControl: boolean;
private aec3?: Aec3Instance;
private aec3Out: Float32Array[] | null = null;
private context: AudioContext;
threshold: number;
hangoverSeconds: number;
@@ -82,6 +90,7 @@ export class MicCapture {
this.echoCancellation = options.echoCancellation ?? true;
this.noiseSuppression = options.noiseSuppression ?? true;
this.autoGainControl = options.autoGainControl ?? true;
this.aec3 = options.aec3;
}
async start(): Promise<void> {
@@ -110,7 +119,15 @@ export class MicCapture {
this.source = this.context.createMediaStreamSource(this.stream);
this.processor = this.context.createScriptProcessor(2048, 1, 1);
this.processor.onaudioprocess = (event) => {
const input = event.inputBuffer.getChannelData(0);
const raw = event.inputBuffer.getChannelData(0);
let input: Float32Array = raw;
if (this.aec3) {
const captureIn = [raw];
const outSize = this.aec3.processSize(captureIn);
if (!this.aec3Out || this.aec3Out[0].length !== outSize) this.aec3Out = [new Float32Array(outSize)];
this.aec3.process(this.aec3Out, captureIn);
input = this.aec3Out[0];
}
let sumSquares = 0;
for (let i = 0; i < input.length; i++) sumSquares += input[i] * input[i];
@@ -280,6 +297,8 @@ export class AudioPlayer {
private element: SinkableElement;
private gain: GainNode;
private context: AudioContext;
private aecTap: ScriptProcessorNode | null = null;
private aecSink: GainNode | null = null;
constructor(context: AudioContext) {
this.context = context;
@@ -352,6 +371,36 @@ export class AudioPlayer {
};
}
/** Feeds everything played back through this player into `aec3.analyze()` as
* the far-end/render reference, so a paired `MicCapture`'s aec3 `process()`
* calls can cancel it back out of the mic signal. Taps post-gain: what's
* actually reaching the speakers is what needs cancelling, not the
* pre-volume mix. */
attachAecRenderTap(aec3: Pick<Aec3Instance, "analyze">): void {
this.detachAecRenderTap();
const tap = this.context.createScriptProcessor(2048, 2, 2);
tap.onaudioprocess = (e) => {
aec3.analyze([e.inputBuffer.getChannelData(0), e.inputBuffer.getChannelData(1)]);
};
const sink = this.context.createGain();
sink.gain.value = 0;
this.gain.connect(tap);
tap.connect(sink);
sink.connect(this.context.destination);
this.aecTap = tap;
this.aecSink = sink;
}
detachAecRenderTap(): void {
if (this.aecTap) {
this.gain.disconnect(this.aecTap);
this.aecTap.disconnect();
this.aecTap = null;
}
this.aecSink?.disconnect();
this.aecSink = null;
}
/** Routes playback to a specific device (empty string = system default). */
async setOutputDevice(deviceId: string): Promise<void> {
if (typeof this.element.setSinkId === "function") {
@@ -366,6 +415,7 @@ export class AudioPlayer {
}
dispose(): void {
this.detachAecRenderTap();
this.element.pause();
this.element.srcObject = null;
this.element.remove();