Files
WebSpeak-client-for-TeamSpeak/web/src/voice/microphone-capture.ts
T
LabKit 47abe356f5 feat(voice): add GTCRN denoise engine with raw/denoised mic test
Resolve noise suppression through one plan with four modes (off, browser, rnnoise, gtcrn, default gtcrn): model engines disable the browser suppressor, preload their WASM and worklet before getUserMedia, and fall back to browser denoising (no-worklet, sample-rate, load-failed) without a second permission prompt. Add an 80 Hz high-pass ahead of the model, persist the mode beside the legacy level mirror, and let the microphone test record raw and processed takes side by side.
2026-12-03 14:19:17 +08:00

250 lines
10 KiB
TypeScript

import { GtcrnWorkletNode, RnnoiseWorkletNode, loadGtcrn, loadRnnoise } from "@sapphi-red/web-noise-suppressor";
import gtcrnWasmUrl from "@sapphi-red/web-noise-suppressor/gtcrn.wasm?url";
import gtcrnWorkletUrl from "@sapphi-red/web-noise-suppressor/gtcrnWorklet.js?url";
import rnnoiseSimdWasmUrl from "@sapphi-red/web-noise-suppressor/rnnoise_simd.wasm?url";
import rnnoiseWasmUrl from "@sapphi-red/web-noise-suppressor/rnnoise.wasm?url";
import rnnoiseWorkletUrl from "@sapphi-red/web-noise-suppressor/rnnoiseWorklet.js?url";
import { isNeuralDenoiseEngine, type DenoiseEngine, type DenoiseFallback, type DenoisePlan } from "./noise-suppression.js";
export interface MicrophoneProcessingSettings {
echoCancellation: boolean | null;
noiseSuppression: boolean | null;
autoGainControl: boolean | null;
/** Engine that actually ran, after capability/load fallbacks. */
engine: DenoiseEngine;
/** Engine the user asked for before fallbacks. */
requestedEngine: DenoiseEngine;
fallback: DenoiseFallback;
/** The browser ignored `noiseSuppression:false`; model and browser NS may stack. */
warning: "browser-ns-active" | null;
}
export interface MicrophoneCapture {
processedStream: MediaStream;
processing: MicrophoneProcessingSettings;
activate(): void;
setVolume(value: number): void;
stopCapture(): void;
dispose(): void;
}
interface CaptureOptions {
context: AudioContext;
stream: MediaStream;
plan: DenoisePlan;
volume: number;
signal: AbortSignal;
assertCurrent(): void;
onSamples(input: Float32Array, rms?: number): void;
}
// A single high-pass before the neural model removes rumble the model would
// otherwise have to separate from speech. Chrome's APM uses the same corner.
const DENOISE_HIGHPASS_HZ = 80;
// Each prepared graph owns its stream and nodes. It cannot publish PCM before
// activation, and aborting preparation never touches the currently live graph.
export function createMicrophoneCaptureFactory() {
const modules = new WeakMap<AudioContext, Map<string, Promise<void>>>();
let rnnoiseWasmPromise: Promise<ArrayBuffer> | null = null;
let gtcrnWasmPromise: Promise<ArrayBuffer> | null = null;
function loadModule(ctx: AudioContext, url: string): Promise<void> {
let cache = modules.get(ctx);
if (!cache) { cache = new Map(); modules.set(ctx, cache); }
let pending = cache.get(url);
if (!pending) {
const ownCache = cache;
pending = ctx.audioWorklet.addModule(url).catch(error => {
if (ownCache.get(url) === pending) ownCache.delete(url);
throw error;
});
cache.set(url, pending);
}
return pending;
}
function loadWasm(engine: "rnnoise" | "gtcrn"): Promise<ArrayBuffer> {
if (engine === "gtcrn") {
if (!gtcrnWasmPromise) {
gtcrnWasmPromise = loadGtcrn({ url: gtcrnWasmUrl }).catch(error => {
gtcrnWasmPromise = null;
throw error;
});
}
return gtcrnWasmPromise;
}
if (!rnnoiseWasmPromise) {
rnnoiseWasmPromise = loadRnnoise({ url: rnnoiseWasmUrl, simdUrl: rnnoiseSimdWasmUrl }).catch(error => {
rnnoiseWasmPromise = null;
throw error;
});
}
return rnnoiseWasmPromise;
}
function engineWorkletUrl(engine: "rnnoise" | "gtcrn"): string {
return engine === "gtcrn" ? gtcrnWorkletUrl : rnnoiseWorkletUrl;
}
/**
* Load WASM and the AudioWorklet module before getUserMedia. This lets the
* capture path request `noiseSuppression:false` only when the model is really
* available, without re-acquiring the microphone for a fallback.
*/
async function preload(ctx: AudioContext, engine: DenoiseEngine): Promise<void> {
if (!isNeuralDenoiseEngine(engine)) return;
await Promise.all([loadWasm(engine), loadModule(ctx, engineWorkletUrl(engine))]);
}
async function prepare(options: CaptureOptions): Promise<MicrophoneCapture> {
const { context: ctx, stream, assertCurrent } = options;
let source: MediaStreamAudioSourceNode | null = null;
let highpass: BiquadFilterNode | null = null;
let denoiser: RnnoiseWorkletNode | GtcrnWorkletNode | null = null;
let destination: MediaStreamAudioDestinationNode | null = null;
let gain: GainNode | null = null;
let silent: GainNode | null = null;
let worklet: AudioWorkletNode | null = null;
let script: ScriptProcessorNode | null = null;
let active = false;
let captureConnected = false;
let disposed = false;
const requestedEngine = options.plan.engine;
let activeEngine: DenoiseEngine = requestedEngine === "browser" ? "browser" : requestedEngine === "off" ? "off" : "off";
let fallback: DenoiseFallback = options.plan.fallback;
const clean = (operation: () => void) => { try { operation(); } catch { /* release the other resources too */ } };
function stopCapture() {
active = false;
if (!captureConnected) return;
if (worklet) clean(() => worklet!.disconnect());
if (script) clean(() => script!.disconnect());
if (gain) clean(() => gain!.disconnect());
if (silent) clean(() => silent!.disconnect());
captureConnected = false;
}
function dispose() {
if (disposed) return;
disposed = true;
stopCapture();
if (worklet) clean(() => worklet!.port.close());
if (denoiser) { clean(() => denoiser!.destroy()); clean(() => denoiser!.disconnect()); }
if (highpass) clean(() => highpass!.disconnect());
if (source) clean(() => source!.disconnect());
if (destination) {
clean(() => destination!.disconnect());
for (const track of destination.stream.getTracks()) clean(() => track.stop());
}
for (const track of stream.getTracks()) clean(() => track.stop());
}
const onSamples = (samples: Float32Array, rms?: number) => {
if (active && !disposed) options.onSamples(samples, rms);
};
options.signal.addEventListener("abort", dispose, { once: true });
try {
assertCurrent();
const track = stream.getAudioTracks().find(candidate => candidate.readyState === "live");
if (!track) throw new DOMException("No live microphone track", "NotFoundError");
const settings = track.getSettings();
source = ctx.createMediaStreamSource(stream);
const supportsWorklet = typeof AudioWorkletNode !== "undefined" && Boolean(ctx.audioWorklet);
if (isNeuralDenoiseEngine(requestedEngine) && supportsWorklet) {
try {
const [wasmBinary] = await Promise.all([
loadWasm(requestedEngine),
loadModule(ctx, engineWorkletUrl(requestedEngine)),
]);
assertCurrent();
denoiser = requestedEngine === "gtcrn"
? new GtcrnWorkletNode(ctx, { maxChannels: 1, wasmBinary })
: new RnnoiseWorkletNode(ctx, { maxChannels: 1, wasmBinary });
activeEngine = requestedEngine;
} catch {
assertCurrent(); // A model failure must not consume cancellation as a fallback.
denoiser = null;
activeEngine = "off";
fallback = "load-failed";
}
}
let processedSource: AudioNode = source;
if (denoiser) {
highpass = ctx.createBiquadFilter();
highpass.type = "highpass";
highpass.frequency.value = DENOISE_HIGHPASS_HZ;
highpass.Q.value = Math.SQRT1_2;
source.connect(highpass);
highpass.connect(denoiser);
processedSource = denoiser;
}
destination = ctx.createMediaStreamDestination();
destination.channelCount = 1;
destination.channelCountMode = "explicit";
processedSource.connect(destination);
gain = ctx.createGain();
gain.gain.value = options.volume;
silent = ctx.createGain();
silent.gain.value = 0;
if (supportsWorklet) {
try {
await loadModule(ctx, "/mic-capture-worklet.js");
assertCurrent();
worklet = new AudioWorkletNode(ctx, "webspeak-mic-capture", {
numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1],
});
worklet.port.onmessage = (event: MessageEvent<{ samples?: Float32Array; rms?: number }>) => {
if (event.data?.samples instanceof Float32Array) onSamples(event.data.samples, event.data.rms);
};
} catch {
assertCurrent();
if (worklet) { clean(() => worklet!.port.close()); clean(() => worklet!.disconnect()); }
worklet = null;
}
}
if (!worklet) {
script = ctx.createScriptProcessor(1024, 1, 1);
script.onaudioprocess = event => onSamples(event.inputBuffer.getChannelData(0));
}
processedSource.connect(gain);
const capture = worklet ?? script!;
gain.connect(capture);
capture.connect(silent);
silent.connect(ctx.destination);
captureConnected = true;
assertCurrent();
if (track.readyState !== "live") throw new DOMException("Microphone track ended", "NotReadableError");
return {
processedStream: destination.stream,
processing: {
echoCancellation: typeof settings.echoCancellation === "boolean" ? settings.echoCancellation : null,
noiseSuppression: typeof settings.noiseSuppression === "boolean" ? settings.noiseSuppression : null,
autoGainControl: typeof settings.autoGainControl === "boolean" ? settings.autoGainControl : null,
engine: activeEngine,
requestedEngine: options.plan.mode,
fallback,
warning: isNeuralDenoiseEngine(activeEngine) && settings.noiseSuppression === true ? "browser-ns-active" : null,
},
activate() {
if (disposed || !(worklet || script)) return;
if (!captureConnected) {
processedSource.connect(gain!);
gain!.connect(capture);
capture.connect(silent!);
silent!.connect(ctx.destination);
captureConnected = true;
}
active = true;
},
setVolume(value) { if (gain) gain.gain.value = value; },
stopCapture,
dispose,
};
} catch (error) {
dispose();
throw error;
} finally {
options.signal.removeEventListener("abort", dispose);
}
}
return { prepare, preload };
}