diff --git a/src/server/webrtc-audio.ts b/src/server/webrtc-audio.ts index 663e901..87bcb32 100644 --- a/src/server/webrtc-audio.ts +++ b/src/server/webrtc-audio.ts @@ -127,6 +127,7 @@ export class WebRtcAudioSession { private lastIngressRtpAt: number | null = null; private lastEgressRtpAt: number | null = null; private lastQueueEnqueuedAt: number | null = null; + private microphoneMuted: boolean; private accompanimentActive: boolean; private readonly stats: WebRtcAudioStats = { webrtcIngressRtpFrames: 0, @@ -153,6 +154,7 @@ export class WebRtcAudioSession { this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId }); this.onVoiceFrame = options.onVoiceFrame; this.onVoiceActivity = options.onVoiceActivity; + this.microphoneMuted = options.microphoneMuted === true; this.accompanimentActive = options.accompanimentActive === true; this.outgoingTrack = new MediaStreamTrack({ kind: "audio" }); @@ -179,6 +181,13 @@ export class WebRtcAudioSession { this.stats.webrtcIngressRtpFrames++; if (!this.opusPayloadTypes.has(rtp.header.payloadType)) return; const payload = Buffer.from(rtp.payload); + // A muted microphone must stop the browser user's TeamSpeak voice + // packets at the gateway. Browser-side track.enabled/gain changes + // still produce RTP comfort-silence on some browsers, and forwarding + // those packets makes TeamSpeak keep the user in the speaking state. + // When accompaniment is active, keep forwarding the mixed track: the + // browser has already removed only the microphone component. + if (this.microphoneMuted && !this.accompanimentActive) return; // Forward every valid negotiated Opus payload unchanged. Do not // decode it for RMS analysis or pass it through a speech/silence gate: // quiet frames are still part of the codec timeline and dropping them @@ -406,10 +415,7 @@ export class WebRtcAudioSession { } setMicrophoneMuted(muted: boolean): void { - // The browser sends a mixed microphone/accompaniment track. The mute gain - // is applied before RTP encoding, so a server-side mute flag must not drop - // the whole packet and silence a still-playing accompaniment. - void muted; + this.microphoneMuted = muted; } setAccompanimentActive(active: boolean): void { diff --git a/web/package-lock.json b/web/package-lock.json index 3cfec6c..c28a2c0 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -6,6 +6,7 @@ "": { "name": "webspeak-webclient-frontend", "dependencies": { + "@sapphi-red/web-noise-suppressor": "^0.4.0", "pinia": "^3.0.2", "vue": "^3.5.13", "vue-router": "^4.5.1" @@ -861,6 +862,16 @@ "win32" ] }, + "node_modules/@sapphi-red/web-noise-suppressor": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@sapphi-red/web-noise-suppressor/-/web-noise-suppressor-0.4.0.tgz", + "integrity": "sha512-vkBEL/VDkbeP3qqSRQFRtPLGa19a38JUzO6J0r5D/MQSumrlERy671DAMaETgY6etXjDCoJcD7JBIaXnuGVtVw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/sapphi-red" + } + }, "node_modules/@types/estree": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", @@ -1343,6 +1354,7 @@ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -1503,6 +1515,7 @@ "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", "devOptional": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -1517,6 +1530,7 @@ "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", @@ -1598,6 +1612,7 @@ "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.34.tgz", "integrity": "sha512-WdLBG9gm02OgJIG9axd5Hpx0TFLdzVgfG2evFFu8Rur5O/IoGc5cMjnjh3tPL6GnRGsYvUhBSKVPYVcxRKpMCA==", "license": "MIT", + "peer": true, "dependencies": { "@vue/compiler-dom": "3.5.34", "@vue/compiler-sfc": "3.5.34", diff --git a/web/package.json b/web/package.json index 646b425..40512ad 100644 --- a/web/package.json +++ b/web/package.json @@ -8,6 +8,7 @@ "preview": "vite preview" }, "dependencies": { + "@sapphi-red/web-noise-suppressor": "^0.4.0", "pinia": "^3.0.2", "vue": "^3.5.13", "vue-router": "^4.5.1" diff --git a/web/src/composables/useVoiceWebSocket.ts b/web/src/composables/useVoiceWebSocket.ts index e1f0b86..9cf78a3 100644 --- a/web/src/composables/useVoiceWebSocket.ts +++ b/web/src/composables/useVoiceWebSocket.ts @@ -1,4 +1,8 @@ import { reactive, ref } from "vue"; +import { RnnoiseWorkletNode, loadRnnoise } from "@sapphi-red/web-noise-suppressor"; +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 { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js"; const micCaptureWorkletUrl = "/mic-capture-worklet.js"; @@ -45,6 +49,7 @@ export interface MicrophoneProcessingSettings { echoCancellation: boolean | null; noiseSuppression: boolean | null; autoGainControl: boolean | null; + rnnoise: boolean | null; } type SinkAudioContext = AudioContext & { @@ -156,9 +161,13 @@ export function useVoiceWebSocket() { let workletNode: AudioWorkletNode | null = null; let workletContext: AudioContext | null = null; let workletModulePromise: Promise | null = null; + let rnnoiseNode: RnnoiseWorkletNode | null = null; + let rnnoiseWorkletModulePromise: Promise | null = null; + let rnnoiseWasmPromise: Promise | null = null; let micSource: MediaStreamAudioSourceNode | null = null; let micGain: GainNode | null = null; let silentGain: GainNode | null = null; + let processedMicDestination: MediaStreamAudioDestinationNode | null = null; const accompanimentActive = ref(false); const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia)); const accompanimentErrorCode = ref<"" | "unsupported" | "needsWebRtc" | "noAudio" | "permission">(""); @@ -181,6 +190,7 @@ export function useVoiceWebSocket() { echoCancellation: null, noiseSuppression: null, autoGainControl: null, + rnnoise: null, }); const audioContextState = ref("unknown"); const micLevel = ref(0); @@ -416,6 +426,36 @@ export function useVoiceWebSocket() { await refreshAudioDevices(); } + async function createRnnoiseNode(ctx: AudioContext): Promise { + if (typeof AudioWorkletNode === "undefined" || !ctx.audioWorklet) { + microphoneProcessing.rnnoise = false; + return null; + } + try { + if (!rnnoiseWasmPromise) { + rnnoiseWasmPromise = loadRnnoise({ url: rnnoiseWasmUrl, simdUrl: rnnoiseSimdWasmUrl }).catch((error) => { + rnnoiseWasmPromise = null; + throw error; + }); + } + if (!rnnoiseWorkletModulePromise) { + rnnoiseWorkletModulePromise = ctx.audioWorklet.addModule(rnnoiseWorkletUrl).catch((error) => { + rnnoiseWorkletModulePromise = null; + throw error; + }); + } + const [wasmBinary] = await Promise.all([rnnoiseWasmPromise, rnnoiseWorkletModulePromise]); + const node = new RnnoiseWorkletNode(ctx, { maxChannels: 1, wasmBinary }); + microphoneProcessing.rnnoise = true; + return node; + } catch { + // Native browser NS remains active as a fallback. RNNoise is an optional + // enhancement and must never prevent a microphone from starting. + microphoneProcessing.rnnoise = false; + return null; + } + } + async function startMicrophone(): Promise { const ctx = getAudioCtx(); if (ctx.state === "suspended") await ctx.resume(); @@ -438,6 +478,13 @@ export function useVoiceWebSocket() { micStream = nextStream; micSource = ctx.createMediaStreamSource(micStream); + rnnoiseNode = await createRnnoiseNode(ctx); + const processedSource: AudioNode = rnnoiseNode ?? micSource; + if (rnnoiseNode) micSource.connect(rnnoiseNode); + processedMicDestination = ctx.createMediaStreamDestination(); + processedMicDestination.channelCount = 1; + processedMicDestination.channelCountMode = "explicit"; + processedSource.connect(processedMicDestination); micGain = ctx.createGain(); micGain.gain.value = inputVolume.value; silentGain = ctx.createGain(); @@ -520,7 +567,7 @@ export function useVoiceWebSocket() { scriptNode.onaudioprocess = (event) => handleCaptureChunk(event.inputBuffer.getChannelData(0)); } - micSource.connect(micGain); + processedSource.connect(micGain); const captureNode = workletNode ?? scriptNode!; micGain.connect(captureNode); captureNode.connect(silentGain); @@ -580,7 +627,11 @@ export function useVoiceWebSocket() { const destination = ctx.createMediaStreamDestination(); destination.channelCount = 1; destination.channelCountMode = "explicit"; - const microphoneSource = ctx.createMediaStreamSource(micStream); + // Use the browser-native processed track plus the browser-side RNNoise + // graph. Display/application audio is added separately below and never + // passes through this microphone denoiser. + const microphoneStream = processedMicDestination?.stream ?? micStream; + const microphoneSource = ctx.createMediaStreamSource(microphoneStream); const microphoneGain = ctx.createGain(); microphoneGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value; microphoneSource.connect(microphoneGain); @@ -896,17 +947,27 @@ export function useVoiceWebSocket() { workletNode?.port.close(); workletNode?.disconnect(); micGain?.disconnect(); - micSource?.disconnect(); silentGain?.disconnect(); scriptNode = null; workletNode = null; micGain = null; - micSource = null; silentGain = null; } + function stopMicrophoneProcessingGraph(): void { + rnnoiseNode?.destroy(); + rnnoiseNode?.disconnect(); + rnnoiseNode = null; + micSource?.disconnect(); + processedMicDestination?.disconnect(); + processedMicDestination?.stream.getTracks().forEach((track) => track.stop()); + micSource = null; + processedMicDestination = null; + } + function stopMicrophone(closeContext = true): void { stopCaptureGraph(); + stopMicrophoneProcessingGraph(); releaseAccompanimentStream(); stopWebRtcMix(); micStream?.getTracks().forEach((track) => track.stop()); @@ -916,6 +977,7 @@ export function useVoiceWebSocket() { audioCtx = null; workletContext = null; workletModulePromise = null; + rnnoiseWorkletModulePromise = null; } } diff --git a/web/src/views/WebClient.vue b/web/src/views/WebClient.vue index 9a10b61..11d11ad 100644 --- a/web/src/views/WebClient.vue +++ b/web/src/views/WebClient.vue @@ -292,7 +292,7 @@