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

+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();