mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
fix: improve voice playback, diagnostics and workspace controls
This commit is contained in:
1 parent
72d7e6e013
commit
e82116239a
34 files changed
+502
-147
No files matched your search
+14
-4
@@ -28,7 +28,17 @@ export class PluginRegistry {
|
||||
const manifest=parsePluginManifest(v.manifest);pluginAssert(file===`${manifest.id}.json`&&typeof v.packageDigest==='string'&&/^[a-f0-9]{64}$/.test(v.packageDigest)&&typeof v.serverConfigCiphertext==='string'&&typeof v.installedAt==='number'&&Number.isFinite(v.installedAt));
|
||||
const settings=this.settings(v.settings,manifest,!!v.serverConfigCiphertext);
|
||||
const record={schemaVersion:2 as const,manifest,settings,packageDigest:v.packageDigest,serverConfigCiphertext:v.serverConfigCiphertext,installedAt:v.installedAt,revision:''};
|
||||
this.readSecret(record);record.revision=this.hash(record);pluginAssert(record.revision===v.revision);this.records.set(manifest.id,record);
|
||||
this.readSecret(record);
|
||||
if (pluginRecord(v.settings) && v.settings.toolbarPinned === undefined) {
|
||||
const legacyHash=createHash("sha256").update(JSON.stringify({manifest,settings:v.settings,packageDigest:v.packageDigest,serverConfigCiphertext:v.serverConfigCiphertext,installedAt:v.installedAt})).digest("hex");
|
||||
pluginAssert(legacyHash===v.revision);
|
||||
record.revision="";
|
||||
this.records.set(manifest.id,record);
|
||||
try { await this.commit(record); }
|
||||
catch { /* keep the migrated record usable in memory if disk replacement fails */ }
|
||||
} else {
|
||||
record.revision=this.hash(record);pluginAssert(record.revision===v.revision);this.records.set(manifest.id,record);
|
||||
}
|
||||
} catch { /* Invalid or obsolete packages are never executed. */ }
|
||||
}
|
||||
}
|
||||
@@ -41,12 +51,12 @@ export class PluginRegistry {
|
||||
return createHash('sha256').update(JSON.stringify({manifest:record.manifest,settings:record.settings,packageDigest:record.packageDigest,serverConfigCiphertext:record.serverConfigCiphertext,installedAt:record.installedAt})).digest('hex');
|
||||
}
|
||||
private settings(value: unknown, manifest: StoredPlugin['manifest'], hasServerConfig: boolean): PluginSettings {
|
||||
pluginAssert(pluginRecord(value)&&typeof value.enabled==='boolean'&&typeof value.trusted==='boolean'&&manifest.scopes.includes(value.scope as never));
|
||||
pluginAssert(pluginRecord(value)&&typeof value.enabled==='boolean'&&typeof value.trusted==='boolean'&&(value.toolbarPinned===undefined||typeof value.toolbarPinned==='boolean')&&manifest.scopes.includes(value.scope as never));
|
||||
pluginAssert(Array.isArray(value.targets)&&value.targets.length<=50&&value.targets.every(t=>typeof t==='string'&&t.length<=300));
|
||||
let targets:string[];try{targets=[...new Set(value.targets.map(t=>teamSpeakTargetKey(parseTeamSpeakTarget(t))))];}catch{throw new PluginError('PLUGIN_TARGET_INVALID');}
|
||||
pluginAssert(!value.enabled||value.trusted,'PLUGIN_TRUST_REQUIRED');
|
||||
pluginAssert(value.scope!=='server'||!value.enabled||targets.length>0,'PLUGIN_TARGET_REQUIRED');
|
||||
return {enabled:value.enabled,trusted:value.trusted,scope:value.scope as PluginSettings['scope'],targets,config:parsePluginJson(value.config),hasServerConfig};
|
||||
return {enabled:value.enabled,trusted:value.trusted,toolbarPinned:value.toolbarPinned===true,scope:value.scope as PluginSettings['scope'],targets,config:parsePluginJson(value.config),hasServerConfig};
|
||||
}
|
||||
private readSecret(record: StoredPlugin): JsonValue {
|
||||
const text=decryptSecret(record.serverConfigCiphertext,this.masterKey,`webspeak:plugin-config:v2:${record.manifest.id}`);
|
||||
@@ -66,7 +76,7 @@ export class PluginRegistry {
|
||||
await mkdir(directory,{recursive:true});const file=path.join(directory,`${digest}.wplugin`);
|
||||
try{await writeFile(file,bytes,{flag:'wx',mode:0o600});}catch(error){if(!(error&&typeof error==='object'&&'code'in error&&error.code==='EEXIST'))throw error;}
|
||||
const old=previous?.settings;
|
||||
const settings={enabled:false,trusted:false,scope:old&&pack.manifest.scopes.includes(old.scope)?old.scope:pack.manifest.scopes[0],targets:old?.targets??[],config:old?.config??{},hasServerConfig:!!previous?.serverConfigCiphertext};
|
||||
const settings={enabled:false,trusted:false,toolbarPinned:old?.toolbarPinned??false,scope:old&&pack.manifest.scopes.includes(old.scope)?old.scope:pack.manifest.scopes[0],targets:old?.targets??[],config:old?.config??{},hasServerConfig:!!previous?.serverConfigCiphertext};
|
||||
return this.commit({schemaVersion:2,manifest:pack.manifest,settings,packageDigest:digest,serverConfigCiphertext:previous?.serverConfigCiphertext??'',installedAt:previous?.installedAt??Date.now(),revision:''});
|
||||
});}
|
||||
configure(id:string,input:unknown,revision:string):Promise<InstalledPlugin>{return this.mutate(async()=>{
|
||||
|
||||
@@ -105,7 +105,7 @@ export class PluginRuntime {
|
||||
async restart(id:string):Promise<void>{this.revokePlugin(id,"PLUGIN_RESTARTED");const entry=this.entries.get(id);if(entry)entry.stale=true;await this.synchronize(id);}
|
||||
directory(voiceToken:string) {
|
||||
const participant=this.options.participant(voiceToken);pluginAssert(participant,"PLUGIN_NOT_CONNECTED");
|
||||
return this.options.registry.list().filter(policy=>{try{this.scopeKey(policy,participant);return true;}catch{return false;}}).map(policy=>({manifest:policy.manifest,scope:policy.settings.scope,runtime:this.status(policy.manifest.id)}));
|
||||
return this.options.registry.list().filter(policy=>{try{this.scopeKey(policy,participant);return true;}catch{return false;}}).map(policy=>({manifest:policy.manifest,scope:policy.settings.scope,toolbarPinned:policy.settings.toolbarPinned,runtime:this.status(policy.manifest.id)}));
|
||||
}
|
||||
private scopeKey(policy:InstalledPlugin,participant:PluginParticipant):string{
|
||||
pluginAssert(policy.settings.enabled&&policy.settings.trusted,"PLUGIN_DISABLED");
|
||||
|
||||
@@ -116,6 +116,7 @@ function fixture() {
|
||||
closed: false, closePromise: null, audioTimer: null, activityTimer: undefined,
|
||||
pendingFrames: new Map([[1, []]]), memberVolumes: new Map([[1, 1]]),
|
||||
partialPcmByClient: new Map([[1, Buffer.alloc(2)]]), activeSpeakerIds: new Set([1]),
|
||||
decoderCodecByClient: new Map([[1, 4], [2, 5]]),
|
||||
decoderByClient: new Map([
|
||||
[1, { dispose() { released.push("decoder-1"); throw new Error("Decoder failed"); } }],
|
||||
[2, { dispose() { released.push("decoder-2"); } }],
|
||||
|
||||
+40
-10
@@ -11,13 +11,15 @@ import type { TSVoiceData } from "./ts-client.js";
|
||||
import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
import type { WebRtcSessionDescription } from "../shared/webrtc.js";
|
||||
import { addOpusFmtpParameters } from "../shared/opus-sdp.js";
|
||||
export type { WebRtcSessionDescription } from "../shared/webrtc.js";
|
||||
|
||||
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
|
||||
const AUDIO_SAMPLE_RATE = 48_000;
|
||||
const AUDIO_FRAME_SAMPLES = 960;
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const AUDIO_CHANNELS = 2;
|
||||
const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS * 2;
|
||||
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
|
||||
const AUDIO_CLOCK_INTERVAL_MS = 20;
|
||||
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
|
||||
@@ -102,6 +104,7 @@ export class WebRtcAudioSession {
|
||||
private readonly onVoiceActivity: (clientIds: number[]) => void;
|
||||
private readonly outgoingTrack: MediaStreamTrack;
|
||||
private readonly decoderByClient = new Map<number, OpusEncoder>();
|
||||
private readonly decoderCodecByClient = new Map<number, 4 | 5>();
|
||||
private readonly partialPcmByClient = new Map<number, Buffer>();
|
||||
private readonly pendingFrames = new Map<number, PendingAudioFrame[]>();
|
||||
private readonly memberVolumes = new Map<number, number>();
|
||||
@@ -198,7 +201,7 @@ export class WebRtcAudioSession {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not prepare WebRTC output track");
|
||||
});
|
||||
|
||||
const createEncoder = options.createEncoder ?? (() => new OpusEncoder(AUDIO_SAMPLE_RATE, 1));
|
||||
const createEncoder = options.createEncoder ?? (() => new OpusEncoder(AUDIO_SAMPLE_RATE, AUDIO_CHANNELS));
|
||||
try {
|
||||
this.encoder = createEncoder();
|
||||
} catch (error: unknown) {
|
||||
@@ -240,22 +243,37 @@ export class WebRtcAudioSession {
|
||||
this.outgoingPayloadType = opus[0]!.payloadType;
|
||||
await transceiver.sender.replaceTrack(this.outgoingTrack);
|
||||
const answer = await this.peer.createAnswer();
|
||||
await this.peer.setLocalDescription(answer);
|
||||
await this.peer.setLocalDescription({
|
||||
...answer,
|
||||
sdp: addOpusFmtpParameters(answer.sdp ?? "", ["stereo=1", "sprop-stereo=1"]),
|
||||
});
|
||||
const description = this.peer.localDescription;
|
||||
if (!description) throw new Error("WebRTC answer was not created");
|
||||
if (description.type !== "answer" && description.type !== "offer") throw new Error("Unexpected WebRTC answer type");
|
||||
return { type: description.type, sdp: description.sdp };
|
||||
return {
|
||||
type: description.type,
|
||||
sdp: addOpusFmtpParameters(description.sdp, ["stereo=1", "sprop-stereo=1"]),
|
||||
};
|
||||
}
|
||||
|
||||
pushTeamSpeakVoice(data: TSVoiceData): void {
|
||||
if (this.closed || (data.codec !== 4 && data.codec !== 5)) return;
|
||||
let decoder = this.decoderByClient.get(data.clientId);
|
||||
if (decoder && this.decoderCodecByClient.get(data.clientId) !== data.codec) {
|
||||
try { decoder.dispose(); } catch { /* a codec transition must still reset queued PCM */ }
|
||||
this.decoderByClient.delete(data.clientId);
|
||||
this.decoderCodecByClient.delete(data.clientId);
|
||||
this.partialPcmByClient.delete(data.clientId);
|
||||
this.pendingFrames.delete(data.clientId);
|
||||
decoder = undefined;
|
||||
}
|
||||
if (!decoder) {
|
||||
try {
|
||||
// @discordjs/opus exposes decoding on OpusEncoder instances too;
|
||||
// there is no separate OpusDecoder constructor in that package.
|
||||
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, 1);
|
||||
decoder = new OpusEncoder(AUDIO_SAMPLE_RATE, data.codec === 4 ? 1 : 2);
|
||||
this.decoderByClient.set(data.clientId, decoder);
|
||||
this.decoderCodecByClient.set(data.clientId, data.codec);
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not create WebRTC mixer decoder");
|
||||
return;
|
||||
@@ -264,16 +282,26 @@ export class WebRtcAudioSession {
|
||||
try {
|
||||
const pcm = decoder.decode(data.data);
|
||||
this.stats.webrtcDownlinkDecodedFrames++;
|
||||
if (pcm.length < 2) {
|
||||
const inputChannels = data.codec === 4 ? 1 : 2;
|
||||
if (pcm.length < inputChannels * 2 || pcm.length % (inputChannels * 2) !== 0) {
|
||||
this.stats.webrtcDownlinkShortFrames++;
|
||||
return;
|
||||
}
|
||||
let stereoPcm = pcm;
|
||||
if (inputChannels === 1) {
|
||||
stereoPcm = Buffer.allocUnsafe(pcm.length * AUDIO_CHANNELS);
|
||||
for (let inputOffset = 0, outputOffset = 0; inputOffset < pcm.length; inputOffset += 2, outputOffset += 4) {
|
||||
const sample = pcm.readInt16LE(inputOffset);
|
||||
stereoPcm.writeInt16LE(sample, outputOffset);
|
||||
stereoPcm.writeInt16LE(sample, outputOffset + 2);
|
||||
}
|
||||
}
|
||||
// TeamSpeak may deliver 10/20/40/60 ms Opus frames. Keep a partial
|
||||
// decoded frame per speaker and split every decoded buffer into the
|
||||
// fixed 20 ms cadence used by the WebRTC mixer instead of discarding
|
||||
// anything after the first 20 ms.
|
||||
const pendingPcm = this.partialPcmByClient.get(data.clientId);
|
||||
const combined = pendingPcm ? Buffer.concat([pendingPcm, pcm]) : pcm;
|
||||
const combined = pendingPcm ? Buffer.concat([pendingPcm, stereoPcm]) : stereoPcm;
|
||||
const rms = this.calculateRms(pcm);
|
||||
// RMS is used only for the UI speaking indicator. Every decoded frame,
|
||||
// including quiet/comfort-noise frames, continues into the queue so the
|
||||
@@ -326,6 +354,7 @@ export class WebRtcAudioSession {
|
||||
this.closePromise = Promise.resolve().then(async () => {
|
||||
const decoders = [...this.decoderByClient.values()];
|
||||
this.decoderByClient.clear();
|
||||
this.decoderCodecByClient.clear();
|
||||
for (const decoder of decoders) {
|
||||
try { decoder.dispose(); } catch { /* continue releasing other resources */ }
|
||||
}
|
||||
@@ -368,13 +397,13 @@ export class WebRtcAudioSession {
|
||||
this.stats.webrtcQueueUnderrunTicks++;
|
||||
}
|
||||
}
|
||||
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
|
||||
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS);
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
const frame = queue.shift();
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
if (!frame) continue;
|
||||
const volume = this.memberVolumes.get(clientId) ?? 1;
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS; index++) {
|
||||
mixed[index] += Math.round(frame.pcm.readInt16LE(index * 2) * volume);
|
||||
}
|
||||
}
|
||||
@@ -383,7 +412,7 @@ export class WebRtcAudioSession {
|
||||
// source packets with our encoded silence/mixes corrupts decoder history
|
||||
// and can suppress otherwise valid speech without any packet loss.
|
||||
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS; index++) {
|
||||
// Keep a fixed gain for the mixed path. Per-sample soft limiting changes
|
||||
// the waveform's apparent loudness as the source level changes, which
|
||||
// is especially noticeable on music. Only clip actual overflow caused
|
||||
@@ -450,6 +479,7 @@ export class WebRtcAudioSession {
|
||||
const decoder = this.decoderByClient.get(clientId);
|
||||
if (!decoder) return;
|
||||
this.decoderByClient.delete(clientId);
|
||||
this.decoderCodecByClient.delete(clientId);
|
||||
try { decoder.dispose(); } catch { /* continue after codec cleanup failures */ }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/** Add Opus channel negotiation parameters to audio payloads in an SDP document. */
|
||||
export function addOpusFmtpParameters(sdp: string, parameters: readonly string[]): string {
|
||||
if (!sdp || parameters.length === 0) return sdp;
|
||||
const lines = sdp.split(/\r?\n/);
|
||||
const output: string[] = [];
|
||||
let section: string[] = [];
|
||||
const flush = () => {
|
||||
if (section[0]?.startsWith("m=audio ")) patchAudioSection(section, parameters);
|
||||
output.push(...section);
|
||||
section = [];
|
||||
};
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("m=")) {
|
||||
if (section.length) flush();
|
||||
}
|
||||
section.push(line);
|
||||
}
|
||||
if (section.length) flush();
|
||||
return output.join("\r\n");
|
||||
}
|
||||
|
||||
function patchAudioSection(section: string[], parameters: readonly string[]): void {
|
||||
const payloads = new Set(section[0]!.trim().split(/\s+/).slice(3));
|
||||
const opusPayloads = section.flatMap(line => {
|
||||
const match = /^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?\s*$/i.exec(line);
|
||||
return match && payloads.has(match[1]!) ? [match[1]!] : [];
|
||||
});
|
||||
for (const payload of opusPayloads) {
|
||||
const prefix = `a=fmtp:${payload}`;
|
||||
const index = section.findIndex(line => new RegExp(`^${prefix}(?:\\s|$)`).test(line));
|
||||
if (index < 0) {
|
||||
const rtpmap = section.findIndex(line => line.startsWith(`a=rtpmap:${payload} `));
|
||||
if (rtpmap >= 0) section.splice(rtpmap + 1, 0, `${prefix} ${parameters.join(";")}`);
|
||||
continue;
|
||||
}
|
||||
const parts = section[index]!.slice(prefix.length).trim().split(";").filter(Boolean);
|
||||
for (const parameter of parameters) {
|
||||
const name = parameter.split("=", 1)[0]!.trim().toLowerCase();
|
||||
const existing = parts.findIndex(part => part.split("=", 1)[0]!.trim().toLowerCase() === name);
|
||||
if (existing < 0) parts.push(parameter);
|
||||
else parts[existing] = parameter;
|
||||
}
|
||||
section[index] = `${prefix} ${parts.join(";")}`;
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,9 @@ export interface PluginManifest {
|
||||
}
|
||||
export interface PluginFile { encoding: "utf8" | "base64"; data: string }
|
||||
export interface PluginPackage { manifest: PluginManifest; files: Record<string, PluginFile> }
|
||||
export interface PluginSettings { enabled: boolean; trusted: boolean; scope: PluginScope; targets: string[]; config: JsonValue; hasServerConfig: boolean }
|
||||
export interface PluginSettings { enabled: boolean; trusted: boolean; toolbarPinned: boolean; scope: PluginScope; targets: string[]; config: JsonValue; hasServerConfig: boolean }
|
||||
export interface PluginSettingsInput {
|
||||
enabled: boolean; trusted: boolean; scope: PluginScope; targets: string[]; config: JsonValue;
|
||||
enabled: boolean; trusted: boolean; toolbarPinned?: boolean; scope: PluginScope; targets: string[]; config: JsonValue;
|
||||
serverConfigAction?: "keep" | "replace" | "remove"; serverConfig?: JsonValue;
|
||||
}
|
||||
export interface PluginRuntimeStatus { state: "disabled" | "client" | "stopped" | "starting" | "running" | "failed"; error?: string }
|
||||
@@ -95,8 +95,8 @@ export function parsePluginJson(v: unknown, maxBytes = 64 * 1024): JsonValue {
|
||||
export function readInstalledPlugin(v: unknown): InstalledPlugin {
|
||||
pluginAssert(pluginRecord(v) && pluginRecord(v.settings) && typeof v.revision === "string" && /^[a-f0-9]{64}$/.test(v.revision) && typeof v.installedAt === "number" && Number.isFinite(v.installedAt));
|
||||
const manifest=parsePluginManifest(v.manifest),s=v.settings;
|
||||
pluginAssert(typeof s.enabled === "boolean" && typeof s.trusted === "boolean" && typeof s.hasServerConfig === "boolean" && manifest.scopes.includes(s.scope as PluginScope) && Array.isArray(s.targets) && s.targets.length <= 50 && s.targets.every(t=>typeof t === "string" && t.length <= 300));
|
||||
const result: InstalledPlugin={manifest,revision:v.revision,installedAt:v.installedAt,settings:{enabled:s.enabled,trusted:s.trusted,scope:s.scope as PluginScope,targets:[...s.targets],config:parsePluginJson(s.config),hasServerConfig:s.hasServerConfig}};
|
||||
pluginAssert(typeof s.enabled === "boolean" && typeof s.trusted === "boolean" && (s.toolbarPinned === undefined || typeof s.toolbarPinned === "boolean") && typeof s.hasServerConfig === "boolean" && manifest.scopes.includes(s.scope as PluginScope) && Array.isArray(s.targets) && s.targets.length <= 50 && s.targets.every(t=>typeof t === "string" && t.length <= 300));
|
||||
const result: InstalledPlugin={manifest,revision:v.revision,installedAt:v.installedAt,settings:{enabled:s.enabled,trusted:s.trusted,toolbarPinned:s.toolbarPinned===true,scope:s.scope as PluginScope,targets:[...s.targets],config:parsePluginJson(s.config),hasServerConfig:s.hasServerConfig}};
|
||||
if(v.runtime!==undefined){pluginAssert(pluginRecord(v.runtime) && ["disabled","client","stopped","starting","running","failed"].includes(String(v.runtime.state)) && (v.runtime.error===undefined||typeof v.runtime.error==="string"));result.runtime={state:v.runtime.state as PluginRuntimeStatus["state"],...(v.runtime.error?{error:v.runtime.error as string}:{})};}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -278,6 +278,7 @@ const PUBLIC_PART_IDS = new Set<string>([
|
||||
"voice.favorite-servers.tooltip",
|
||||
"voice.header",
|
||||
"voice.header-actions",
|
||||
"voice.plugin-toolbar",
|
||||
"voice.member",
|
||||
"voice.member-panel",
|
||||
"voice.member-panel.channels",
|
||||
|
||||
Reference in new issue
Block a user