mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-01 02:52:49 +08:00
fix(audio): move capture framing to audio worklet
This commit is contained in:
1 parent
3e7674c94f
commit
8ab2fbe8ea
4 files changed
+87
-14
No files matched your search
@@ -21,6 +21,7 @@ All notable changes to WebSpeak are documented here. Versions follow SemVer.
|
||||
- Replaced the visually off-center settings glyph and normalized icon alignment for settings-related controls across the client.
|
||||
- Fixed narrow-screen exit and microphone controls so their text-collapse rules apply correctly.
|
||||
- Bounded browser and gateway voice buffering, reset stale browser playback queues, and exposed low-overhead in-memory audio counters for diagnosing jitter without per-frame log writes.
|
||||
- Moved microphone frame assembly to an `AudioWorklet` with a compatibility fallback to `ScriptProcessorNode`; both paths emit fixed 960-sample frames.
|
||||
|
||||
## [0.1.1] — 2026-09-02
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ Browser (playback) ← WebSocket ← Node.js server (Opus relay) ← TeamSpea
|
||||
```
|
||||
|
||||
- Each browser user = one independent TS3 virtual client via `@echosixhiya/teamspeak-client`
|
||||
- Frontend captures PCM via `ScriptProcessorNode`, sends as Int16 binary over WebSocket
|
||||
- Frontend captures PCM in an `AudioWorklet` when available (with a `ScriptProcessorNode` fallback), assembles fixed 960-sample frames, and sends Int16 binary over WebSocket
|
||||
- Server encodes PCM → Opus using `@discordjs/opus` (CJS, loaded via `createRequire`)
|
||||
- Server sends Opus to TS via `client.sendVoice(data, codec=4)`
|
||||
- Incoming TS voice → Opus frames → binary WebSocket → browser `AudioDecoder` → playback
|
||||
@@ -36,9 +36,9 @@ src/
|
||||
## Key Technical Details
|
||||
|
||||
### Audio Pipeline
|
||||
1. Browser mic → `getUserMedia` (48kHz mono) → `ScriptProcessorNode` (1024 samples)
|
||||
1. Browser mic → `getUserMedia` (48kHz mono) → `AudioWorklet` frame assembler (960 samples); older browsers use `ScriptProcessorNode` (1024-sample chunks) before the same assembler
|
||||
2. Float32 → Int16 conversion → PTT/VOX gate → WebSocket binary send
|
||||
3. Server accumulates PCM → every 1920 bytes (960 samples, 20ms) → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
|
||||
3. Server encodes each 1920-byte (960-sample, 20ms) PCM frame → `OpusEncoder.encode()` → `tsClient.sendVoice(opus, 4)`
|
||||
4. Incoming: TS → `voiceData` event → 3-byte header `[codec][clientId BE]` → WS binary → browser `AudioDecoder` → playback
|
||||
5. Browser uplink is capped at 10 PCM frames (about 200ms); gateway egress applies a bounded WebSocket byte guard; browser playback resets stale decoder/source queues above 120ms.
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
const FRAME_SAMPLES = 960;
|
||||
|
||||
class WebSpeakMicCaptureProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.frame = new Float32Array(FRAME_SAMPLES);
|
||||
this.offset = 0;
|
||||
}
|
||||
|
||||
process(inputs, outputs) {
|
||||
const input = inputs[0]?.[0];
|
||||
const output = outputs[0]?.[0];
|
||||
if (output) output.fill(0);
|
||||
if (!input) return true;
|
||||
|
||||
let inputOffset = 0;
|
||||
while (inputOffset < input.length) {
|
||||
const count = Math.min(input.length - inputOffset, FRAME_SAMPLES - this.offset);
|
||||
this.frame.set(input.subarray(inputOffset, inputOffset + count), this.offset);
|
||||
this.offset += count;
|
||||
inputOffset += count;
|
||||
if (this.offset !== FRAME_SAMPLES) continue;
|
||||
|
||||
let sum = 0;
|
||||
for (let index = 0; index < this.frame.length; index++) sum += this.frame[index] * this.frame[index];
|
||||
const frame = this.frame;
|
||||
this.frame = new Float32Array(FRAME_SAMPLES);
|
||||
this.offset = 0;
|
||||
this.port.postMessage({ samples: frame, rms: Math.sqrt(sum / FRAME_SAMPLES) }, [frame.buffer]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor("webspeak-mic-capture", WebSpeakMicCaptureProcessor);
|
||||
@@ -1,6 +1,8 @@
|
||||
import { reactive, ref } from "vue";
|
||||
import { loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
|
||||
|
||||
const micCaptureWorkletUrl = "/mic-capture-worklet.js";
|
||||
|
||||
export interface VoiceState {
|
||||
connected: boolean;
|
||||
connecting: boolean;
|
||||
@@ -90,6 +92,9 @@ export function useVoiceWebSocket() {
|
||||
let audioCtx: SinkAudioContext | null = null;
|
||||
let micStream: MediaStream | null = null;
|
||||
let scriptNode: ScriptProcessorNode | null = null;
|
||||
let workletNode: AudioWorkletNode | null = null;
|
||||
let workletContext: AudioContext | null = null;
|
||||
let workletModulePromise: Promise<void> | null = null;
|
||||
let micSource: MediaStreamAudioSourceNode | null = null;
|
||||
let micGain: GainNode | null = null;
|
||||
let silentGain: GainNode | null = null;
|
||||
@@ -113,7 +118,7 @@ export function useVoiceWebSocket() {
|
||||
let voxAttack = 0;
|
||||
let voxRelease = 0;
|
||||
const VOX_HOLD = 15;
|
||||
const VOX_ATTACK_FRAMES = 2;
|
||||
const VOX_ATTACK_FRAMES = 1;
|
||||
let convBuf = new Int16Array(1024);
|
||||
let accumBuf = new Int16Array(2048);
|
||||
let accumLen = 0;
|
||||
@@ -320,15 +325,12 @@ export function useVoiceWebSocket() {
|
||||
micSource = ctx.createMediaStreamSource(micStream);
|
||||
micGain = ctx.createGain();
|
||||
micGain.gain.value = inputVolume.value;
|
||||
scriptNode = ctx.createScriptProcessor(1024, 1, 1);
|
||||
silentGain = ctx.createGain();
|
||||
silentGain.gain.value = 0;
|
||||
|
||||
scriptNode.onaudioprocess = (event) => {
|
||||
const input = event.inputBuffer.getChannelData(0);
|
||||
let sum = 0;
|
||||
for (let i = 0; i < input.length; i++) sum += input[i] * input[i];
|
||||
micLevel.value = Math.min(1, Math.sqrt(sum / Math.max(1, input.length)) * 6);
|
||||
const handleCaptureChunk = (input: Float32Array, rms?: number): void => {
|
||||
if (!input.length) return;
|
||||
micLevel.value = Math.min(1, (rms ?? Math.sqrt(input.reduce((sum, sample) => sum + sample * sample, 0) / input.length)) * 6);
|
||||
const socket = ws.value;
|
||||
const shouldSend = !microphoneMuted.value
|
||||
&& !microphoneTestActive.value
|
||||
@@ -354,11 +356,10 @@ export function useVoiceWebSocket() {
|
||||
publishAudioDiagnostics();
|
||||
return;
|
||||
}
|
||||
markSpeaking(state.tsClientId);
|
||||
|
||||
if (convBuf.length < input.length) convBuf = new Int16Array(input.length);
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const sample = Math.max(-1, Math.min(1, input[i]));
|
||||
const sample = Math.max(-1, Math.min(1, input[i]!));
|
||||
convBuf[i] = sample < 0 ? sample * 0x8000 : sample * 0x7fff;
|
||||
}
|
||||
|
||||
@@ -374,13 +375,44 @@ export function useVoiceWebSocket() {
|
||||
audioCounters.uplinkFrames++;
|
||||
publishAudioDiagnostics();
|
||||
}
|
||||
if (offset > 0) markSpeaking(state.tsClientId);
|
||||
accumLen -= offset;
|
||||
if (offset > 0) accumBuf.set(accumBuf.subarray(offset, offset + accumLen), 0);
|
||||
};
|
||||
|
||||
if (typeof AudioWorkletNode !== "undefined" && ctx.audioWorklet) {
|
||||
try {
|
||||
if (workletContext !== ctx || !workletModulePromise) {
|
||||
workletContext = ctx;
|
||||
workletModulePromise = ctx.audioWorklet.addModule(micCaptureWorkletUrl);
|
||||
}
|
||||
await workletModulePromise;
|
||||
workletNode = new AudioWorkletNode(ctx, "webspeak-mic-capture", {
|
||||
numberOfInputs: 1,
|
||||
numberOfOutputs: 1,
|
||||
outputChannelCount: [1],
|
||||
});
|
||||
workletNode.port.onmessage = (event: MessageEvent<{ samples?: Float32Array; rms?: number }>) => {
|
||||
const samples = event.data?.samples;
|
||||
if (samples instanceof Float32Array) handleCaptureChunk(samples, event.data.rms);
|
||||
};
|
||||
} catch {
|
||||
workletNode?.disconnect();
|
||||
workletNode = null;
|
||||
workletContext = null;
|
||||
workletModulePromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!workletNode) {
|
||||
scriptNode = ctx.createScriptProcessor(1024, 1, 1);
|
||||
scriptNode.onaudioprocess = (event) => handleCaptureChunk(event.inputBuffer.getChannelData(0));
|
||||
}
|
||||
|
||||
micSource.connect(micGain);
|
||||
micGain.connect(scriptNode);
|
||||
scriptNode.connect(silentGain);
|
||||
const captureNode = workletNode ?? scriptNode!;
|
||||
micGain.connect(captureNode);
|
||||
captureNode.connect(silentGain);
|
||||
silentGain.connect(ctx.destination);
|
||||
await refreshAudioDevices();
|
||||
}
|
||||
@@ -419,10 +451,13 @@ export function useVoiceWebSocket() {
|
||||
voxRelease = 0;
|
||||
micLevel.value = 0;
|
||||
scriptNode?.disconnect();
|
||||
workletNode?.port.close();
|
||||
workletNode?.disconnect();
|
||||
micGain?.disconnect();
|
||||
micSource?.disconnect();
|
||||
silentGain?.disconnect();
|
||||
scriptNode = null;
|
||||
workletNode = null;
|
||||
micGain = null;
|
||||
micSource = null;
|
||||
silentGain = null;
|
||||
@@ -431,6 +466,8 @@ export function useVoiceWebSocket() {
|
||||
if (closeContext) {
|
||||
audioCtx?.close();
|
||||
audioCtx = null;
|
||||
workletContext = null;
|
||||
workletModulePromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user