mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
feat: report live voice status and harden target handling
This commit is contained in:
1 parent
e0d5916a86
commit
0a4fff6f6f
19 files changed
+1003
-101
No files matched your search
+2
-1
@@ -35,11 +35,12 @@ COPY --from=build --chown=node:node /app/package.json /app/package-lock.json ./
|
||||
COPY --from=build --chown=node:node /app/node_modules ./node_modules
|
||||
COPY --from=build --chown=node:node /app/dist ./dist
|
||||
COPY --from=build --chown=node:node /app/web/dist ./web/dist
|
||||
COPY --from=build --chown=node:node /app/scripts/docker-healthcheck.mjs ./scripts/docker-healthcheck.mjs
|
||||
|
||||
USER node
|
||||
VOLUME ["/data"]
|
||||
EXPOSE 3040/tcp 39087/udp 40000-40099/udp
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD ["sh", "-c", "if [ \"$WEBSPEAK_MODE\" = \"relay\" ]; then node -e \"process.exit(0)\"; else node -e \"fetch('http://127.0.0.1:3040/health').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))\"; fi"]
|
||||
CMD ["node", "scripts/docker-healthcheck.mjs"]
|
||||
|
||||
CMD ["node", "dist/index.js"]
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
"scripts": {
|
||||
"dev": "tsx src/index.ts",
|
||||
"build": "tsc",
|
||||
"test": "node --import tsx --test src/admin/skin-registry.test.ts src/server/visitor-count.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts",
|
||||
"test": "node --import tsx --test src/admin/skin-registry.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts scripts/docker-healthcheck.test.mjs web/src/services/skin-catalog.test.ts web/src/services/skin-pack.test.ts",
|
||||
"start": "node dist/index.js",
|
||||
"web:dev": "cd web && npx vite --host",
|
||||
"web:build": "cd web && npx vite build",
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import http from "node:http";
|
||||
import https from "node:https";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const scriptDirectory = path.dirname(fileURLToPath(import.meta.url));
|
||||
const appRoot = path.resolve(scriptDirectory, "..");
|
||||
const defaultCertDirectory = path.join(appRoot, "certs");
|
||||
|
||||
export function healthcheckUsesHttps(certDirectory = defaultCertDirectory) {
|
||||
return existsSync(path.join(certDirectory, "cert.pem"));
|
||||
}
|
||||
|
||||
export function runDockerHealthcheck({ mode = process.env.WEBSPEAK_MODE, certDirectory = defaultCertDirectory } = {}) {
|
||||
if (mode?.trim().toLowerCase() === "relay") {
|
||||
process.exitCode = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const secure = healthcheckUsesHttps(certDirectory);
|
||||
const client = secure ? https : http;
|
||||
const request = client.get({
|
||||
hostname: "127.0.0.1",
|
||||
port: 3040,
|
||||
path: "/health",
|
||||
...(secure ? { rejectUnauthorized: false } : {}),
|
||||
}, (response) => {
|
||||
response.resume();
|
||||
process.exitCode = response.statusCode >= 200 && response.statusCode < 300 ? 0 : 1;
|
||||
});
|
||||
request.setTimeout(4_000, () => request.destroy(new Error("Healthcheck timed out")));
|
||||
request.on("error", () => { process.exitCode = 1; });
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
runDockerHealthcheck();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { healthcheckUsesHttps } from "./docker-healthcheck.mjs";
|
||||
|
||||
test("Docker healthcheck selects HTTP or HTTPS from the same certificate marker as the server", (context) => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-healthcheck-"));
|
||||
context.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
|
||||
assert.equal(healthcheckUsesHttps(directory), false);
|
||||
mkdirSync(directory, { recursive: true });
|
||||
writeFileSync(path.join(directory, "cert.pem"), "test certificate marker");
|
||||
assert.equal(healthcheckUsesHttps(directory), true);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isSafeOpenTargetForPrefill } from "./open-target-policy.js";
|
||||
|
||||
test("open-mode target prefill follows the same allow/deny result as the join policy", async () => {
|
||||
assert.equal(await isSafeOpenTargetForPrefill({ host: "198.51.100.24", port: 9987 }, {
|
||||
resolveTarget: async (target) => target,
|
||||
}), true);
|
||||
assert.equal(await isSafeOpenTargetForPrefill({ host: "teamspeak", port: 9987 }, {
|
||||
resolveTarget: async () => { throw new Error("private or unresolved target"); },
|
||||
}), false);
|
||||
});
|
||||
|
||||
test("open-mode target prefill fails closed when DNS validation stalls", async () => {
|
||||
const result = await isSafeOpenTargetForPrefill({ host: "internal.example", port: 9987 }, {
|
||||
timeoutMs: 10,
|
||||
resolveTarget: async () => new Promise(() => undefined),
|
||||
});
|
||||
assert.equal(result, false);
|
||||
});
|
||||
@@ -27,6 +27,26 @@ export async function resolveSafeOpenTarget(target: TeamSpeakTarget): Promise<Te
|
||||
return { host: addresses[0]!.address, port: target.port };
|
||||
}
|
||||
|
||||
/** A bounded, non-authoritative check used only to avoid pre-filling a target that open mode will reject. */
|
||||
export async function isSafeOpenTargetForPrefill(
|
||||
target: TeamSpeakTarget,
|
||||
options: { timeoutMs?: number; resolveTarget?: (target: TeamSpeakTarget) => Promise<TeamSpeakTarget> } = {},
|
||||
): Promise<boolean> {
|
||||
const timeoutMs = options.timeoutMs ?? 1_000;
|
||||
const resolveTarget = options.resolveTarget ?? resolveSafeOpenTarget;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await Promise.race([
|
||||
Promise.resolve().then(() => resolveTarget(target)).then(() => true, () => false),
|
||||
new Promise<boolean>((resolve) => {
|
||||
timer = setTimeout(() => resolve(false), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
export function isRestrictedAddress(address: string): boolean {
|
||||
const version = isIP(address);
|
||||
if (version === 4) return isRestrictedIpv4(address);
|
||||
|
||||
+16
-3
@@ -9,7 +9,7 @@ import { parseTeamSpeakTarget, teamSpeakTargetKey } from "../domain/teamspeak-ta
|
||||
import { createAdminRouter } from "../admin/admin-router.js";
|
||||
import type { AdminService } from "../admin/admin-service.js";
|
||||
import { AdminSessionStore } from "../admin/admin-session.js";
|
||||
import { resolveSafeOpenTarget } from "../security/open-target-policy.js";
|
||||
import { isSafeOpenTargetForPrefill, resolveSafeOpenTarget } from "../security/open-target-policy.js";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { JoinRateLimiter } from "./join-rate-limit.js";
|
||||
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
@@ -65,7 +65,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
app.get("/health", healthHandler);
|
||||
app.get("/api/health", healthHandler);
|
||||
|
||||
app.get("/api/public-config", (request, response) => {
|
||||
app.get("/api/public-config", async (request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
const acceleration = resolveAccelerationOptions(options.voiceBridgeOptions.acceleration);
|
||||
let visitorNumber = readVisitorNumberCookie(request.header("cookie"));
|
||||
@@ -90,8 +90,21 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
} else if (visitorNumber !== null) {
|
||||
visitorTotal = visitorNumber;
|
||||
}
|
||||
const publicConfig = options.adminService.getPublicConfig();
|
||||
let target = typeof publicConfig.target === "string" ? publicConfig.target : "";
|
||||
let targetPrefillBlocked = false;
|
||||
if (publicConfig.accessMode === "open" && target.trim()) {
|
||||
try {
|
||||
targetPrefillBlocked = !await isSafeOpenTargetForPrefill(parseTeamSpeakTarget(target));
|
||||
} catch {
|
||||
targetPrefillBlocked = true;
|
||||
}
|
||||
if (targetPrefillBlocked) target = "";
|
||||
}
|
||||
response.json({
|
||||
...options.adminService.getPublicConfig(),
|
||||
...publicConfig,
|
||||
target,
|
||||
targetPrefillBlocked,
|
||||
...(visitorNumber === null ? {} : { visitorNumber }),
|
||||
...(visitorTotal === null ? {} : { visitorTotal }),
|
||||
accelerationAvailable: acceleration.length > 0,
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type ClientOptions,
|
||||
type Identity,
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
import { WebSpeakTeamSpeakResolver } from "./teamspeak-resolver.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { normalizeTeamSpeakError } from "../errors.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
@@ -85,6 +86,7 @@ export class TeamSpeakAdapter {
|
||||
) {
|
||||
this.identity = options.identity ?? generateIdentity(8);
|
||||
const clientOptions: ClientOptions = {
|
||||
resolver: new WebSpeakTeamSpeakResolver(),
|
||||
serverPassword: options.serverPassword,
|
||||
defaultChannel: options.defaultChannel,
|
||||
defaultChannelPassword: options.channelPassword,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { AddrResolver, ResolvedAddr } from "@echosixhiya/teamspeak-client";
|
||||
import { WebSpeakTeamSpeakResolver } from "./teamspeak-resolver.js";
|
||||
|
||||
function fixedResolver(result: ResolvedAddr[], onResolve?: (signal?: AbortSignal) => void): AddrResolver {
|
||||
return {
|
||||
resolve: async (_address, signal) => {
|
||||
onResolve?.(signal);
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("private short hostnames use local DNS directly without cloud nickname discovery", async () => {
|
||||
let baseCalls = 0;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async (hostname) => {
|
||||
assert.equal(hostname, "teamspeak");
|
||||
return [{ address: "172.18.0.6", family: 4 }];
|
||||
},
|
||||
baseResolver: {
|
||||
resolve: async () => {
|
||||
baseCalls++;
|
||||
return [];
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = await resolver.resolve("teamspeak:9988");
|
||||
assert.equal(result[0]?.addr, "172.18.0.6:9988");
|
||||
assert.equal(result[0]?.source, "Direct");
|
||||
assert.equal(baseCalls, 0);
|
||||
});
|
||||
|
||||
test("undotted nickname discovery is bounded and falls back to the direct host", async () => {
|
||||
let baseSignal: AbortSignal | undefined;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => [],
|
||||
baseResolver: {
|
||||
resolve: async (_address, signal) => {
|
||||
baseSignal = signal;
|
||||
return new Promise<ResolvedAddr[]>(() => undefined);
|
||||
},
|
||||
},
|
||||
localAliasLookupTimeoutMs: 20,
|
||||
nicknameLookupTimeoutMs: 25,
|
||||
});
|
||||
|
||||
const result = await resolver.resolve("teamspeak:9987");
|
||||
assert.equal(result[0]?.addr, "teamspeak:9987");
|
||||
assert.equal(result[0]?.source, "Direct");
|
||||
assert.equal(baseSignal?.aborted, true);
|
||||
});
|
||||
|
||||
test("dotted hostnames preserve the SDK resolver path", async () => {
|
||||
const expected: ResolvedAddr[] = [{ addr: "voice.example.com:9987", source: "Direct", expiry: new Date(0) }];
|
||||
let lookupCalls = 0;
|
||||
let baseCalls = 0;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => {
|
||||
lookupCalls++;
|
||||
return [];
|
||||
},
|
||||
baseResolver: fixedResolver(expected, () => { baseCalls++; }),
|
||||
});
|
||||
|
||||
assert.deepEqual(await resolver.resolve("voice.example.com:9987"), expected);
|
||||
assert.equal(lookupCalls, 0);
|
||||
assert.equal(baseCalls, 1);
|
||||
});
|
||||
|
||||
test("DNS resolution failures continue through bounded nickname discovery", async () => {
|
||||
const expected: ResolvedAddr[] = [{ addr: "public.example.com:9987", source: "Nickname", expiry: new Date(0) }];
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => { throw new Error("ENOTFOUND"); },
|
||||
baseResolver: fixedResolver(expected),
|
||||
nicknameLookupTimeoutMs: 100,
|
||||
});
|
||||
|
||||
assert.deepEqual(await resolver.resolve("public-alias"), expected);
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import { Resolver as TeamSpeakResolver } from "@echosixhiya/teamspeak-client/discovery";
|
||||
import type { AddrResolver, ResolvedAddr } from "@echosixhiya/teamspeak-client";
|
||||
import { formatTeamSpeakTarget, parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
const LOCAL_ALIAS_LOOKUP_TIMEOUT_MS = 1_000;
|
||||
const NICKNAME_LOOKUP_TIMEOUT_MS = 3_000;
|
||||
|
||||
type LocalAddress = { address: string; family: number };
|
||||
type LocalLookup = (hostname: string) => Promise<LocalAddress[]>;
|
||||
|
||||
interface WebSpeakTeamSpeakResolverOptions {
|
||||
baseResolver?: AddrResolver;
|
||||
localLookup?: LocalLookup;
|
||||
localAliasLookupTimeoutMs?: number;
|
||||
nicknameLookupTimeoutMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep TeamSpeak nickname discovery for normal names, while allowing an
|
||||
* internal short hostname (for example a Docker Compose service name) to use
|
||||
* the local resolver directly. Bound cloud nickname discovery so a network
|
||||
* black hole cannot prevent the SDK's direct-host fallback indefinitely.
|
||||
*/
|
||||
export class WebSpeakTeamSpeakResolver implements AddrResolver {
|
||||
private readonly baseResolver: AddrResolver;
|
||||
private readonly localLookup: LocalLookup;
|
||||
private readonly localAliasLookupTimeoutMs: number;
|
||||
private readonly nicknameLookupTimeoutMs: number;
|
||||
|
||||
constructor(options: WebSpeakTeamSpeakResolverOptions = {}) {
|
||||
this.baseResolver = options.baseResolver ?? new TeamSpeakResolver();
|
||||
this.localLookup = options.localLookup ?? ((hostname) => lookup(hostname, { all: true, verbatim: true }));
|
||||
this.localAliasLookupTimeoutMs = options.localAliasLookupTimeoutMs ?? LOCAL_ALIAS_LOOKUP_TIMEOUT_MS;
|
||||
this.nicknameLookupTimeoutMs = options.nicknameLookupTimeoutMs ?? NICKNAME_LOOKUP_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
async resolve(address: string, signal?: AbortSignal): Promise<ResolvedAddr[]> {
|
||||
if (signal?.aborted) throw signal.reason ?? new Error("TeamSpeak address resolution was aborted");
|
||||
|
||||
let target;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(address);
|
||||
} catch {
|
||||
return this.resolveBase(address, signal);
|
||||
}
|
||||
|
||||
const { host, port } = target;
|
||||
if (isIP(host) || host === "localhost" || host.includes(".")) {
|
||||
return this.resolveBase(address, signal);
|
||||
}
|
||||
|
||||
const localAddresses = await raceWithTimeout(
|
||||
Promise.resolve().then(() => this.localLookup(host)),
|
||||
this.localAliasLookupTimeoutMs,
|
||||
signal,
|
||||
)
|
||||
.catch((error: unknown) => {
|
||||
if (signal?.aborted) throw signal.reason ?? error;
|
||||
return null;
|
||||
});
|
||||
const localAddress = localAddresses?.find(({ address: candidate }) => isPrivateNetworkAddress(candidate));
|
||||
if (localAddress) {
|
||||
return [directAddress(localAddress.address, port)];
|
||||
}
|
||||
|
||||
const baseResults = await this.resolveBaseWithTimeout(address, signal);
|
||||
return baseResults?.length ? baseResults : [directAddress(host, port)];
|
||||
}
|
||||
|
||||
private resolveBase(address: string, signal?: AbortSignal): Promise<ResolvedAddr[]> {
|
||||
return this.baseResolver.resolve(address, signal);
|
||||
}
|
||||
|
||||
private async resolveBaseWithTimeout(address: string, signal?: AbortSignal): Promise<ResolvedAddr[] | null> {
|
||||
const timeoutController = new AbortController();
|
||||
const combinedSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
|
||||
try {
|
||||
return await raceWithTimeout(
|
||||
Promise.resolve().then(() => this.baseResolver.resolve(address, combinedSignal)),
|
||||
this.nicknameLookupTimeoutMs,
|
||||
signal,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
if (signal?.aborted) throw signal.reason ?? error;
|
||||
return null;
|
||||
} finally {
|
||||
timeoutController.abort(new Error("TeamSpeak nickname lookup timed out"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function directAddress(host: string, port: number): ResolvedAddr {
|
||||
return {
|
||||
addr: formatTeamSpeakTarget({ host, port }),
|
||||
source: "Direct",
|
||||
expiry: new Date(0),
|
||||
};
|
||||
}
|
||||
|
||||
function isPrivateNetworkAddress(address: string): boolean {
|
||||
const version = isIP(address);
|
||||
if (version === 4) {
|
||||
const [a, b] = address.split(".").map(Number) as [number, number, number, number];
|
||||
return a === 10
|
||||
|| a === 127
|
||||
|| (a === 169 && b === 254)
|
||||
|| (a === 172 && b >= 16 && b <= 31)
|
||||
|| (a === 192 && b === 168);
|
||||
}
|
||||
if (version !== 6) return false;
|
||||
|
||||
const normalized = address.toLowerCase();
|
||||
if (normalized.startsWith("::ffff:")) return isPrivateNetworkAddress(normalized.slice("::ffff:".length));
|
||||
if (normalized === "::" || normalized === "::1") return true;
|
||||
const firstGroup = Number.parseInt(normalized.split(":", 1)[0] || "0", 16);
|
||||
return (firstGroup & 0xfe00) === 0xfc00 || (firstGroup & 0xffc0) === 0xfe80;
|
||||
}
|
||||
|
||||
function raceWithTimeout<T>(work: Promise<T>, timeoutMs: number, signal?: AbortSignal): Promise<T | null> {
|
||||
if (signal?.aborted) return Promise.reject(signal.reason ?? new Error("TeamSpeak address resolution was aborted"));
|
||||
|
||||
return new Promise<T | null>((resolve, reject) => {
|
||||
let settled = false;
|
||||
const finish = (callback: (value: T | null) => void, value: T | null): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
callback(value);
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
reject(signal?.reason ?? new Error("TeamSpeak address resolution was aborted"));
|
||||
};
|
||||
const timer = setTimeout(() => finish(resolve, null), timeoutMs);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
work.then(
|
||||
(value) => finish(resolve, value),
|
||||
(error: unknown) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -154,6 +154,7 @@ interface WebClientEntry {
|
||||
audio: AudioFlowStats;
|
||||
webrtc: WebRtcAudioSession | null;
|
||||
lastLatencyProbeAt: number;
|
||||
lastAudioStatsProbeAt: number;
|
||||
connectionFailureCode?: string;
|
||||
screenPeerId: string;
|
||||
}
|
||||
@@ -296,6 +297,7 @@ export class VoiceBridge {
|
||||
audio: createAudioFlowStats(),
|
||||
webrtc: null,
|
||||
lastLatencyProbeAt: 0,
|
||||
lastAudioStatsProbeAt: 0,
|
||||
screenPeerId: entryId,
|
||||
};
|
||||
this.entries.set(entryId, entry!);
|
||||
@@ -1730,6 +1732,8 @@ async function handleCommand(
|
||||
sendJson: (message: Record<string, unknown>) => void,
|
||||
): Promise<void> {
|
||||
if (command.type === "latencyProbe") {
|
||||
// Keep the control-path probe for already-open older browser clients. The
|
||||
// current voice status panel exclusively requests actual audio counters.
|
||||
const sequence = command.payload.sequence as string;
|
||||
const now = Date.now();
|
||||
if (now - entry.lastLatencyProbeAt < 150) return;
|
||||
@@ -1747,6 +1751,19 @@ async function handleCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
if (command.type === "audioStatsProbe") {
|
||||
const sequence = command.payload.sequence as string;
|
||||
const now = Date.now();
|
||||
if (now - entry.lastAudioStatsProbeAt < 750) return;
|
||||
entry.lastAudioStatsProbeAt = now;
|
||||
sendJson({
|
||||
type: "audioStats",
|
||||
sequence,
|
||||
stats: snapshotAudioStatus(entry),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (command.type === "switchChannel") {
|
||||
const rawId = command.payload.channelId as string;
|
||||
const channelPassword = typeof command.payload.password === "string" ? command.payload.password : "";
|
||||
@@ -2042,6 +2059,33 @@ function snapshotAudioStats(entry: WebClientEntry): AudioFlowStats {
|
||||
return stats;
|
||||
}
|
||||
|
||||
function snapshotAudioStatus(entry: WebClientEntry): Record<string, number | string | null> {
|
||||
const stats = snapshotAudioStats(entry);
|
||||
return {
|
||||
transport: entry.webrtc ? "webrtc" : "websocket",
|
||||
ingressFrames: stats.ingressFrames,
|
||||
ingressDroppedFrames: stats.ingressDroppedFrames,
|
||||
ingressMaxGapMs: stats.ingressMaxGapMs,
|
||||
tsSendFrames: stats.tsSendFrames,
|
||||
tsSendErrors: stats.tsSendErrors,
|
||||
tsSendMaxGapMs: stats.tsSendMaxGapMs,
|
||||
tsReceiveFrames: stats.tsReceiveFrames,
|
||||
tsReceiveMaxGapMs: stats.tsReceiveMaxGapMs,
|
||||
egressFrames: stats.egressFrames,
|
||||
egressDroppedFrames: stats.egressDroppedFrames,
|
||||
egressMaxGapMs: stats.egressMaxGapMs,
|
||||
webrtcIngressRtpFrames: stats.webrtcIngressRtpFrames,
|
||||
webrtcIngressRtpMaxGapMs: stats.webrtcIngressRtpMaxGapMs,
|
||||
webrtcEgressRtpFrames: stats.webrtcEgressRtpFrames,
|
||||
webrtcEgressRtpMaxGapMs: stats.webrtcEgressRtpMaxGapMs,
|
||||
webrtcQueueDroppedFrames: stats.webrtcQueueDroppedFrames,
|
||||
webrtcQueueUnderrunTicks: stats.webrtcQueueUnderrunTicks,
|
||||
webrtcPacerLateTicks: stats.webrtcPacerLateTicks,
|
||||
webrtcIngressDecodeErrors: stats.webrtcIngressDecodeErrors,
|
||||
webrtcDownlinkDecodeErrors: stats.webrtcDownlinkDecodeErrors,
|
||||
};
|
||||
}
|
||||
|
||||
function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new Map<string, string | null>()): unknown[] {
|
||||
return snapshot.channels.map((channel) => ({
|
||||
id: String(channel.id),
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { parseClientCommand } from "./voice-protocol.js";
|
||||
|
||||
test("accepts a bounded audio stats snapshot request", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({
|
||||
type: "audioStatsProbe",
|
||||
payload: { sequence: "audio-sample-1" },
|
||||
})), {
|
||||
type: "audioStatsProbe",
|
||||
payload: { sequence: "audio-sample-1" },
|
||||
});
|
||||
});
|
||||
|
||||
test("continues accepting the legacy control-path probe for cached clients", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({
|
||||
type: "latencyProbe",
|
||||
payload: { sequence: "latency-old-client" },
|
||||
})), {
|
||||
type: "latencyProbe",
|
||||
payload: { sequence: "latency-old-client" },
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects audio stats requests without a short sequence id", () => {
|
||||
const result = parseClientCommand(JSON.stringify({
|
||||
type: "audioStatsProbe",
|
||||
payload: { sequence: "x".repeat(65) },
|
||||
}));
|
||||
assert.deepEqual(result, {
|
||||
error: { code: "INVALID_AUDIO_STATS_PROBE", message: "音频状态采样标识无效" },
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
export interface ClientCommand {
|
||||
type: "switchChannel" | "moveClient" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume" | "latencyProbe";
|
||||
type: "switchChannel" | "moveClient" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume" | "latencyProbe" | "audioStatsProbe";
|
||||
requestId?: string;
|
||||
payload: Record<string, unknown>;
|
||||
}
|
||||
@@ -19,7 +19,7 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
|
||||
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
|
||||
}
|
||||
const supportedTypes = new Set(["switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe"]);
|
||||
const supportedTypes = new Set(["switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe", "audioStatsProbe"]);
|
||||
if (!supportedTypes.has(value.type)) {
|
||||
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
|
||||
}
|
||||
@@ -74,6 +74,9 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.type === "setMemberVolume" && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535 || typeof value.payload.volume !== "number" || !Number.isFinite(value.payload.volume) || value.payload.volume < 0 || value.payload.volume > 4)) {
|
||||
return { error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" } };
|
||||
}
|
||||
if (value.type === "audioStatsProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) {
|
||||
return { error: { code: "INVALID_AUDIO_STATS_PROBE", message: "音频状态采样标识无效" } };
|
||||
}
|
||||
if (value.type === "latencyProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) {
|
||||
return { error: { code: "INVALID_LATENCY_PROBE", message: "延迟探测标识无效" } };
|
||||
}
|
||||
|
||||
@@ -201,11 +201,55 @@ export interface ServerEvent {
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface LatencyProbeResult {
|
||||
browserRttMs: number;
|
||||
teamSpeakLatencyMs: number | null;
|
||||
teamSpeakReachable: boolean;
|
||||
teamSpeakErrorCode?: string;
|
||||
export interface VoiceAudioBridgeStats {
|
||||
transport: "webrtc" | "websocket";
|
||||
ingressFrames: number;
|
||||
ingressDroppedFrames: number;
|
||||
ingressMaxGapMs: number;
|
||||
tsSendFrames: number;
|
||||
tsSendErrors: number;
|
||||
tsSendMaxGapMs: number;
|
||||
tsReceiveFrames: number;
|
||||
tsReceiveMaxGapMs: number;
|
||||
egressFrames: number;
|
||||
egressDroppedFrames: number;
|
||||
egressMaxGapMs: number;
|
||||
webrtcIngressRtpFrames: number;
|
||||
webrtcIngressRtpMaxGapMs: number;
|
||||
webrtcEgressRtpFrames: number;
|
||||
webrtcEgressRtpMaxGapMs: number;
|
||||
webrtcQueueDroppedFrames: number;
|
||||
webrtcQueueUnderrunTicks: number;
|
||||
webrtcPacerLateTicks: number;
|
||||
webrtcIngressDecodeErrors: number;
|
||||
webrtcDownlinkDecodeErrors: number;
|
||||
}
|
||||
|
||||
export interface BrowserVoiceAudioStats {
|
||||
outboundBytes: number | null;
|
||||
outboundPackets: number | null;
|
||||
outboundPacketsLost: number | null;
|
||||
outboundLossPercent: number | null;
|
||||
outboundRttMs: number | null;
|
||||
inboundBytes: number | null;
|
||||
inboundPackets: number | null;
|
||||
inboundPacketsLost: number | null;
|
||||
inboundLossPercent: number | null;
|
||||
inboundJitterMs: number | null;
|
||||
concealedSamples: number | null;
|
||||
}
|
||||
|
||||
export interface VoiceAudioStatusSample {
|
||||
sampledAt: number;
|
||||
transport: "webrtc" | "websocket" | "negotiating" | "disconnected";
|
||||
connectionState: string | null;
|
||||
microphoneMuted: boolean;
|
||||
microphoneReady: boolean;
|
||||
microphonePermission: AudioPermission;
|
||||
playbackState: "playing" | "paused" | "unavailable" | null;
|
||||
bridge: VoiceAudioBridgeStats;
|
||||
browser: BrowserVoiceAudioStats | null;
|
||||
fallbackPlayback: { framesReceived: number; framesDropped: number; decodeErrors: number };
|
||||
}
|
||||
|
||||
const MAX_VISIBLE_ERROR_CODE_LENGTH = 64;
|
||||
@@ -228,6 +272,38 @@ function safeClientErrorCode(value: unknown): string {
|
||||
return normalized.slice(0, MAX_VISIBLE_ERROR_CODE_LENGTH);
|
||||
}
|
||||
|
||||
function parseVoiceAudioBridgeStats(value: unknown): VoiceAudioBridgeStats | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
const readCount = (key: string): number => {
|
||||
const candidate = record[key];
|
||||
return typeof candidate === "number" && Number.isFinite(candidate) && candidate >= 0 ? candidate : 0;
|
||||
};
|
||||
return {
|
||||
transport: record.transport === "webrtc" ? "webrtc" : "websocket",
|
||||
ingressFrames: readCount("ingressFrames"),
|
||||
ingressDroppedFrames: readCount("ingressDroppedFrames"),
|
||||
ingressMaxGapMs: readCount("ingressMaxGapMs"),
|
||||
tsSendFrames: readCount("tsSendFrames"),
|
||||
tsSendErrors: readCount("tsSendErrors"),
|
||||
tsSendMaxGapMs: readCount("tsSendMaxGapMs"),
|
||||
tsReceiveFrames: readCount("tsReceiveFrames"),
|
||||
tsReceiveMaxGapMs: readCount("tsReceiveMaxGapMs"),
|
||||
egressFrames: readCount("egressFrames"),
|
||||
egressDroppedFrames: readCount("egressDroppedFrames"),
|
||||
egressMaxGapMs: readCount("egressMaxGapMs"),
|
||||
webrtcIngressRtpFrames: readCount("webrtcIngressRtpFrames"),
|
||||
webrtcIngressRtpMaxGapMs: readCount("webrtcIngressRtpMaxGapMs"),
|
||||
webrtcEgressRtpFrames: readCount("webrtcEgressRtpFrames"),
|
||||
webrtcEgressRtpMaxGapMs: readCount("webrtcEgressRtpMaxGapMs"),
|
||||
webrtcQueueDroppedFrames: readCount("webrtcQueueDroppedFrames"),
|
||||
webrtcQueueUnderrunTicks: readCount("webrtcQueueUnderrunTicks"),
|
||||
webrtcPacerLateTicks: readCount("webrtcPacerLateTicks"),
|
||||
webrtcIngressDecodeErrors: readCount("webrtcIngressDecodeErrors"),
|
||||
webrtcDownlinkDecodeErrors: readCount("webrtcDownlinkDecodeErrors"),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizedClientErrorCode(value: unknown, fallback = "CONNECTION_FAILED"): string {
|
||||
const safe = safeClientErrorCode(value);
|
||||
return CLIENT_ERROR_CODE_ALIASES[safe] ?? (safe || fallback);
|
||||
@@ -343,11 +419,14 @@ export function useVoiceWebSocket() {
|
||||
const pokeNotifications = reactive<{ id: string; invokerId: number; invokerUid: string; invokerName: string; message: string; timestamp: number }[]>([]);
|
||||
let connectionSequence = 0;
|
||||
let lastConnection: { target: string; channel: string; nickname: string; serverPassword: string; identity?: string; rememberIdentity: boolean; accelerated: boolean; accelerationRelayId: string } | null = null;
|
||||
let latencyProbeSequence = 0;
|
||||
const pendingLatencyProbes = new Map<string, { startedAt: number; resolve: (result: LatencyProbeResult | null) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||
let audioStatusProbeSequence = 0;
|
||||
const pendingAudioStatusProbes = new Map<string, { resolve: (stats: VoiceAudioBridgeStats | null) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||
let commandSequence = 0;
|
||||
const pendingCommands = new Map<string, { resolve: () => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||
let webrtcPeer: RTCPeerConnection | null = null;
|
||||
let fallbackAudioFramesReceived = 0;
|
||||
let fallbackAudioFramesDropped = 0;
|
||||
let fallbackAudioDecodeErrors = 0;
|
||||
let webrtcOutputElement: SinkAudioElement | null = null;
|
||||
let webrtcPlaybackStream: MediaStream | null = null;
|
||||
let webrtcPlaybackRetryCleanup: (() => void) | null = null;
|
||||
@@ -1405,7 +1484,10 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
|
||||
function playAudioFrame(clientId: number, opusData: Uint8Array): void {
|
||||
if (opusData.length < 3) return;
|
||||
if (opusData.length < 3) {
|
||||
fallbackAudioFramesDropped++;
|
||||
return;
|
||||
}
|
||||
let decoder = remoteDecoders.get(clientId);
|
||||
const ctx = getAudioCtx();
|
||||
const now = ctx.currentTime;
|
||||
@@ -1472,6 +1554,7 @@ export function useVoiceWebSocket() {
|
||||
},
|
||||
error: () => {
|
||||
if (remoteDecoderGenerations.get(clientId) === generation) {
|
||||
fallbackAudioDecodeErrors++;
|
||||
remoteDecoderGenerations.delete(clientId);
|
||||
remoteDecoders.delete(clientId);
|
||||
}
|
||||
@@ -1488,6 +1571,7 @@ export function useVoiceWebSocket() {
|
||||
decoder.decode(new EncodedAudioChunk({ type: "key", timestamp, duration: 20_000, data: opusData }));
|
||||
remoteDecodeTimestamps.set(clientId, timestamp + 20_000);
|
||||
} catch {
|
||||
fallbackAudioDecodeErrors++;
|
||||
// Ignore malformed frames; the next valid frame can still be decoded.
|
||||
}
|
||||
}
|
||||
@@ -1584,7 +1668,7 @@ export function useVoiceWebSocket() {
|
||||
};
|
||||
socket.onclose = (event) => {
|
||||
if (sequence !== connectionSequence) return;
|
||||
clearLatencyProbes();
|
||||
clearAudioStatusProbes();
|
||||
rejectPendingCommands(new Error("语音连接已关闭"));
|
||||
state.connected = false;
|
||||
state.connecting = false;
|
||||
@@ -1673,7 +1757,7 @@ export function useVoiceWebSocket() {
|
||||
|
||||
function disconnect(preserveConnection = false): void {
|
||||
connectionSequence++;
|
||||
clearLatencyProbes();
|
||||
clearAudioStatusProbes();
|
||||
rejectPendingCommands(new Error("语音连接已关闭"));
|
||||
const keepRememberedIdentity = lastConnection?.rememberIdentity === true;
|
||||
if (!preserveConnection) lastConnection = null;
|
||||
@@ -1709,10 +1793,10 @@ export function useVoiceWebSocket() {
|
||||
for (const key of Object.keys(volumes)) delete volumes[Number(key)];
|
||||
}
|
||||
|
||||
function clearLatencyProbes(): void {
|
||||
for (const [sequence, pending] of pendingLatencyProbes) {
|
||||
function clearAudioStatusProbes(): void {
|
||||
for (const [sequence, pending] of pendingAudioStatusProbes) {
|
||||
clearTimeout(pending.timer);
|
||||
pendingLatencyProbes.delete(sequence);
|
||||
pendingAudioStatusProbes.delete(sequence);
|
||||
pending.resolve(null);
|
||||
}
|
||||
}
|
||||
@@ -2523,18 +2607,13 @@ export function useVoiceWebSocket() {
|
||||
state.error = "";
|
||||
state.errorCode = "";
|
||||
break;
|
||||
case "latencyPong": {
|
||||
case "audioStats": {
|
||||
const sequence = typeof msg.sequence === "string" ? msg.sequence : "";
|
||||
const pending = pendingLatencyProbes.get(sequence);
|
||||
const pending = pendingAudioStatusProbes.get(sequence);
|
||||
if (!pending) break;
|
||||
pendingLatencyProbes.delete(sequence);
|
||||
pendingAudioStatusProbes.delete(sequence);
|
||||
clearTimeout(pending.timer);
|
||||
pending.resolve({
|
||||
browserRttMs: Math.max(0, Math.round(performance.now() - pending.startedAt)),
|
||||
teamSpeakLatencyMs: typeof msg.teamSpeakLatencyMs === "number" ? msg.teamSpeakLatencyMs : null,
|
||||
teamSpeakReachable: msg.teamSpeakReachable === true,
|
||||
...(typeof msg.teamSpeakErrorCode === "string" ? { teamSpeakErrorCode: msg.teamSpeakErrorCode } : {}),
|
||||
});
|
||||
pending.resolve(parseVoiceAudioBridgeStats(msg.stats));
|
||||
break;
|
||||
}
|
||||
case "disconnected":
|
||||
@@ -2645,9 +2724,13 @@ export function useVoiceWebSocket() {
|
||||
// in-flight fallback WebSocket packets so a transport switch cannot
|
||||
// produce duplicate or delayed playback.
|
||||
if (webrtcActive.value) return;
|
||||
if (data.length < 4) return;
|
||||
if (data.length < 4) {
|
||||
fallbackAudioFramesDropped++;
|
||||
return;
|
||||
}
|
||||
const clientId = (data[1] << 8) | data[2];
|
||||
if (clientId === state.tsClientId) return;
|
||||
fallbackAudioFramesReceived++;
|
||||
markSpeaking(clientId);
|
||||
playAudioFrame(clientId, data.slice(3));
|
||||
}
|
||||
@@ -2680,17 +2763,114 @@ export function useVoiceWebSocket() {
|
||||
return sendCommandAndWait("moveClient", { clientId, channelId, ...(password ? { password } : {}) });
|
||||
}
|
||||
|
||||
function measureLatency(timeoutMs = 2_200): Promise<LatencyProbeResult | null> {
|
||||
async function collectBrowserVoiceAudioStats(): Promise<BrowserVoiceAudioStats | null> {
|
||||
const peer = webrtcPeer;
|
||||
if (!peer) return null;
|
||||
try {
|
||||
const report = await peer.getStats();
|
||||
let outbound: Record<string, unknown> | undefined;
|
||||
let remoteInbound: Record<string, unknown> | undefined;
|
||||
let inbound: Record<string, unknown> | undefined;
|
||||
let candidatePair: Record<string, unknown> | undefined;
|
||||
report.forEach((raw) => {
|
||||
const stats = raw as unknown as Record<string, unknown>;
|
||||
const type = typeof stats.type === "string" ? stats.type : "";
|
||||
const kind = typeof stats.kind === "string" ? stats.kind : typeof stats.mediaType === "string" ? stats.mediaType : "";
|
||||
if (kind === "audio") {
|
||||
if (type === "outbound-rtp") outbound = stats;
|
||||
else if (type === "remote-inbound-rtp") remoteInbound = stats;
|
||||
else if (type === "inbound-rtp") inbound = stats;
|
||||
}
|
||||
if (type === "candidate-pair" && (stats.selected === true || stats.nominated === true) && stats.state === "succeeded") candidatePair = stats;
|
||||
});
|
||||
const readNumber = (stats: Record<string, unknown> | undefined, key: string): number | null => {
|
||||
const value = stats?.[key];
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
||||
};
|
||||
const outboundLost = readNumber(remoteInbound, "packetsLost");
|
||||
const outboundPackets = readNumber(outbound, "packetsSent");
|
||||
const fractionLost = readNumber(remoteInbound, "fractionLost");
|
||||
const outboundLossPercent = fractionLost !== null
|
||||
? Math.min(100, Math.max(0, fractionLost * 100))
|
||||
: outboundLost !== null && outboundPackets !== null && outboundPackets + Math.max(0, outboundLost) > 0
|
||||
? (Math.max(0, outboundLost) / (outboundPackets + Math.max(0, outboundLost))) * 100
|
||||
: null;
|
||||
const inboundPackets = readNumber(inbound, "packetsReceived");
|
||||
const inboundPacketsLost = readNumber(inbound, "packetsLost");
|
||||
const inboundLossTotal = inboundPackets !== null && inboundPacketsLost !== null
|
||||
? inboundPackets + Math.max(0, inboundPacketsLost)
|
||||
: null;
|
||||
const outboundRttSeconds = readNumber(remoteInbound, "roundTripTime") ?? readNumber(candidatePair, "currentRoundTripTime");
|
||||
const inboundJitterSeconds = readNumber(inbound, "jitter");
|
||||
return {
|
||||
outboundBytes: readNumber(outbound, "bytesSent"),
|
||||
outboundPackets,
|
||||
outboundPacketsLost: outboundLost,
|
||||
outboundLossPercent,
|
||||
outboundRttMs: outboundRttSeconds === null ? null : outboundRttSeconds * 1_000,
|
||||
inboundBytes: readNumber(inbound, "bytesReceived"),
|
||||
inboundPackets,
|
||||
inboundPacketsLost,
|
||||
inboundLossPercent: inboundLossTotal && inboundLossTotal > 0 && inboundPacketsLost !== null
|
||||
? (Math.max(0, inboundPacketsLost) / inboundLossTotal) * 100
|
||||
: null,
|
||||
inboundJitterMs: inboundJitterSeconds === null ? null : inboundJitterSeconds * 1_000,
|
||||
concealedSamples: readNumber(inbound, "concealedSamples"),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function measureVoiceAudioStatus(timeoutMs = 1_800): Promise<VoiceAudioStatusSample | null> {
|
||||
const socket = ws.value;
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) return Promise.resolve(null);
|
||||
const sequence = `latency-${Date.now().toString(36)}-${(latencyProbeSequence++).toString(36)}`;
|
||||
return new Promise((resolve) => {
|
||||
const sequence = `audio-${Date.now().toString(36)}-${(audioStatusProbeSequence++).toString(36)}`;
|
||||
const browserStatsPromise = collectBrowserVoiceAudioStats();
|
||||
return new Promise<VoiceAudioStatusSample | null>((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
pendingLatencyProbes.delete(sequence);
|
||||
pendingAudioStatusProbes.delete(sequence);
|
||||
resolve(null);
|
||||
}, timeoutMs);
|
||||
pendingLatencyProbes.set(sequence, { startedAt: performance.now(), resolve, timer });
|
||||
sendCmd("latencyProbe", { sequence });
|
||||
pendingAudioStatusProbes.set(sequence, {
|
||||
resolve: (bridge) => {
|
||||
if (!bridge) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
void browserStatsPromise.then((browser) => {
|
||||
const peer = webrtcPeer;
|
||||
const transport = !state.connected
|
||||
? "disconnected"
|
||||
: webrtcActive.value
|
||||
? "webrtc"
|
||||
: peer && !webrtcFallbackStarted
|
||||
? "negotiating"
|
||||
: "websocket";
|
||||
const playbackState = peer
|
||||
? webrtcOutputElement ? webrtcOutputElement.paused ? "paused" : "playing" : "unavailable"
|
||||
: audioCtx ? audioCtx.state === "running" ? "playing" : "paused" : null;
|
||||
resolve({
|
||||
sampledAt: performance.now(),
|
||||
transport,
|
||||
connectionState: peer?.connectionState ?? null,
|
||||
microphoneMuted: microphoneMuted.value,
|
||||
microphoneReady: Boolean(micStream?.getAudioTracks().some((track) => track.readyState === "live")),
|
||||
microphonePermission: audioPermission.value,
|
||||
playbackState,
|
||||
bridge,
|
||||
browser,
|
||||
fallbackPlayback: {
|
||||
framesReceived: fallbackAudioFramesReceived,
|
||||
framesDropped: fallbackAudioFramesDropped,
|
||||
decodeErrors: fallbackAudioDecodeErrors,
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
timer,
|
||||
});
|
||||
sendCmd("audioStatsProbe", { sequence });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2964,6 +3144,6 @@ export function useVoiceWebSocket() {
|
||||
leaveScreenShare,
|
||||
checkSupport,
|
||||
clearError,
|
||||
measureLatency,
|
||||
measureVoiceAudioStatus,
|
||||
};
|
||||
}
|
||||
@@ -1,45 +1,153 @@
|
||||
import { computed, onUnmounted, ref, watch, type Ref } from "vue";
|
||||
import type { LatencyProbeResult } from "./useVoiceWebSocket.js";
|
||||
import type { VoiceAudioStatusSample } from "./useVoiceWebSocket.js";
|
||||
|
||||
const SAMPLE_INTERVAL_MS = 3_000;
|
||||
const SAMPLE_WINDOW_SIZE = 20;
|
||||
const SAMPLE_INTERVAL_MS = 2_000;
|
||||
|
||||
export type VoiceAudioHealth = "disconnected" | "sampling" | "connecting" | "warning" | "active" | "quiet";
|
||||
|
||||
function counterDelta(current: number, previous: number | undefined): number | null {
|
||||
if (previous === undefined || current < previous) return null;
|
||||
return current - previous;
|
||||
}
|
||||
|
||||
function ratePerSecond(current: number, previous: number | undefined, elapsedMs: number): number | null {
|
||||
const delta = counterDelta(current, previous);
|
||||
if (delta === null || elapsedMs < 250) return null;
|
||||
return Math.round((delta * 1_000) / elapsedMs);
|
||||
}
|
||||
|
||||
function bitrateKbps(current: number | null, previous: number | null | undefined, elapsedMs: number): number | null {
|
||||
if (current === null || previous == null || current < previous || elapsedMs < 250) return null;
|
||||
return Math.round(((current - previous) * 8) / elapsedMs);
|
||||
}
|
||||
|
||||
function intervalLossPercent(
|
||||
currentReceived: number | null | undefined,
|
||||
previousReceived: number | null | undefined,
|
||||
currentLost: number | null | undefined,
|
||||
previousLost: number | null | undefined,
|
||||
fallback: number | null,
|
||||
): number | null {
|
||||
if (currentReceived == null || previousReceived == null || currentLost == null || previousLost == null) return fallback;
|
||||
const receivedDelta = counterDelta(currentReceived, previousReceived);
|
||||
const lostDelta = counterDelta(Math.max(0, currentLost), Math.max(0, previousLost));
|
||||
if (receivedDelta === null || lostDelta === null) return fallback;
|
||||
const total = receivedDelta + lostDelta;
|
||||
return total > 0 ? (lostDelta / total) * 100 : fallback;
|
||||
}
|
||||
|
||||
export function useWebClientPerformance(
|
||||
connected: Readonly<Ref<boolean>>,
|
||||
measureLatency: () => Promise<LatencyProbeResult | null>,
|
||||
measureAudioStatus: () => Promise<VoiceAudioStatusSample | null>,
|
||||
) {
|
||||
const panelOpen = ref(false);
|
||||
const running = ref(false);
|
||||
const samples = ref<LatencyProbeResult[]>([]);
|
||||
const probeResults = ref<Array<LatencyProbeResult | null>>([]);
|
||||
const attempts = ref(0);
|
||||
const latestSample = ref<VoiceAudioStatusSample | null>(null);
|
||||
const previousSample = ref<VoiceAudioStatusSample | null>(null);
|
||||
let timer: number | null = null;
|
||||
let generation = 0;
|
||||
|
||||
const median = (values: number[]) => {
|
||||
const sorted = [...values].sort((left, right) => left - right);
|
||||
return sorted.length ? sorted[Math.floor(sorted.length / 2)] : null;
|
||||
};
|
||||
|
||||
const stats = computed(() => {
|
||||
const gatewaySamples = samples.value.map((sample) => sample.browserRttMs);
|
||||
const teamSpeakSamples = samples.value
|
||||
.filter((sample) => sample.teamSpeakReachable && sample.teamSpeakLatencyMs != null)
|
||||
.map((sample) => sample.teamSpeakLatencyMs as number);
|
||||
const current = latestSample.value;
|
||||
const previous = previousSample.value;
|
||||
const elapsedMs = current && previous ? current.sampledAt - previous.sampledAt : 0;
|
||||
const bridge = current?.bridge;
|
||||
const previousBridge = previous?.bridge;
|
||||
const browser = current?.browser;
|
||||
const previousBrowser = previous?.browser;
|
||||
const uplinkFramesPerSecond = bridge
|
||||
? ratePerSecond(bridge.tsSendFrames, previousBridge?.tsSendFrames, elapsedMs)
|
||||
: null;
|
||||
const downlinkCounter = current
|
||||
? current.transport === "websocket"
|
||||
? current.fallbackPlayback.framesReceived
|
||||
: current.transport === "webrtc" && browser?.inboundPackets !== null && browser?.inboundPackets !== undefined
|
||||
? browser.inboundPackets
|
||||
: bridge?.egressFrames ?? null
|
||||
: null;
|
||||
const previousDownlinkCounter = previous
|
||||
? previous.transport === "websocket"
|
||||
? previous.fallbackPlayback.framesReceived
|
||||
: previous.transport === "webrtc" && previousBrowser?.inboundPackets !== null && previousBrowser?.inboundPackets !== undefined
|
||||
? previousBrowser.inboundPackets
|
||||
: previousBridge?.egressFrames ?? null
|
||||
: null;
|
||||
const downlinkFramesPerSecond = downlinkCounter === null
|
||||
? null
|
||||
: ratePerSecond(downlinkCounter, previousDownlinkCounter ?? undefined, elapsedMs);
|
||||
const uplinkLossPercent = browser
|
||||
? intervalLossPercent(browser.outboundPackets, previousBrowser?.outboundPackets, browser.outboundPacketsLost, previousBrowser?.outboundPacketsLost, browser.outboundLossPercent)
|
||||
: null;
|
||||
const downlinkLossPercent = browser
|
||||
? intervalLossPercent(browser.inboundPackets, previousBrowser?.inboundPackets, browser.inboundPacketsLost, previousBrowser?.inboundPacketsLost, browser.inboundLossPercent)
|
||||
: null;
|
||||
const recentErrors = bridge && previousBridge
|
||||
? (counterDelta(bridge.tsSendErrors, previousBridge.tsSendErrors) ?? 0)
|
||||
+ (counterDelta(bridge.ingressDroppedFrames, previousBridge.ingressDroppedFrames) ?? 0)
|
||||
+ (counterDelta(bridge.egressDroppedFrames, previousBridge.egressDroppedFrames) ?? 0)
|
||||
+ (counterDelta(bridge.webrtcIngressDecodeErrors, previousBridge.webrtcIngressDecodeErrors) ?? 0)
|
||||
+ (counterDelta(bridge.webrtcDownlinkDecodeErrors, previousBridge.webrtcDownlinkDecodeErrors) ?? 0)
|
||||
+ (counterDelta(bridge.webrtcQueueDroppedFrames, previousBridge.webrtcQueueDroppedFrames) ?? 0)
|
||||
+ (counterDelta(current?.fallbackPlayback.decodeErrors ?? 0, previous?.fallbackPlayback.decodeErrors ?? 0) ?? 0)
|
||||
: 0;
|
||||
const uplinkBitrateKbps = browser ? bitrateKbps(browser.outboundBytes, previousBrowser?.outboundBytes, elapsedMs) : null;
|
||||
const downlinkBitrateKbps = browser ? bitrateKbps(browser.inboundBytes, previousBrowser?.inboundBytes, elapsedMs) : null;
|
||||
const mediaIsActive = (uplinkFramesPerSecond ?? 0) > 0
|
||||
|| (downlinkFramesPerSecond ?? 0) > 0
|
||||
|| (uplinkBitrateKbps ?? 0) > 0
|
||||
|| (downlinkBitrateKbps ?? 0) > 0;
|
||||
const playbackBlocked = (downlinkFramesPerSecond ?? 0) > 0
|
||||
&& (current?.playbackState === "paused" || current?.playbackState === "unavailable");
|
||||
let health: VoiceAudioHealth = "sampling";
|
||||
if (!connected.value) health = "disconnected";
|
||||
else if (current) {
|
||||
if (current.connectionState === "failed" || recentErrors > 0 || playbackBlocked || (!current.microphoneMuted && (current.microphonePermission === "denied" || (current.microphonePermission === "granted" && !current.microphoneReady)))) health = "warning";
|
||||
else if (current.transport === "negotiating" || (current.transport === "webrtc" && current.connectionState && current.connectionState !== "connected")) health = "connecting";
|
||||
else health = mediaIsActive ? "active" : "quiet";
|
||||
}
|
||||
|
||||
return {
|
||||
gatewayLatencyMs: median(gatewaySamples),
|
||||
gatewayLossPercent: attempts.value > 0 ? Math.round(((attempts.value - samples.value.length) / attempts.value) * 100) : null,
|
||||
teamSpeakLatencyMs: median(teamSpeakSamples),
|
||||
teamSpeakLossPercent: attempts.value > 0 ? Math.round(((attempts.value - teamSpeakSamples.length) / attempts.value) * 100) : null,
|
||||
ready: attempts.value > 0,
|
||||
ready: current !== null,
|
||||
health,
|
||||
transport: current?.transport ?? "disconnected",
|
||||
connectionState: current?.connectionState ?? null,
|
||||
microphoneMuted: current?.microphoneMuted ?? false,
|
||||
microphoneReady: current?.microphoneReady ?? false,
|
||||
microphonePermission: current?.microphonePermission ?? "unknown",
|
||||
playbackState: current?.playbackState ?? null,
|
||||
uplinkFramesPerSecond,
|
||||
downlinkFramesPerSecond,
|
||||
uplinkBitrateKbps,
|
||||
downlinkBitrateKbps,
|
||||
uplinkLossPercent,
|
||||
uplinkRttMs: browser?.outboundRttMs ?? null,
|
||||
downlinkLossPercent,
|
||||
downlinkJitterMs: browser?.inboundJitterMs ?? null,
|
||||
concealedSamples: browser?.concealedSamples ?? null,
|
||||
sendErrors: bridge && previousBridge ? counterDelta(bridge.tsSendErrors, previousBridge.tsSendErrors) : null,
|
||||
droppedFrames: bridge && previousBridge
|
||||
? (counterDelta(bridge.ingressDroppedFrames, previousBridge.ingressDroppedFrames) ?? 0)
|
||||
+ (counterDelta(bridge.egressDroppedFrames, previousBridge.egressDroppedFrames) ?? 0)
|
||||
+ (counterDelta(bridge.webrtcQueueDroppedFrames, previousBridge.webrtcQueueDroppedFrames) ?? 0)
|
||||
+ (counterDelta(current?.fallbackPlayback.framesDropped ?? 0, previous?.fallbackPlayback.framesDropped ?? 0) ?? 0)
|
||||
: null,
|
||||
queueUnderruns: bridge && previousBridge ? counterDelta(bridge.webrtcQueueUnderrunTicks, previousBridge.webrtcQueueUnderrunTicks) : null,
|
||||
ingressMaxGapMs: bridge?.ingressMaxGapMs ?? null,
|
||||
egressMaxGapMs: bridge?.egressMaxGapMs ?? null,
|
||||
};
|
||||
});
|
||||
|
||||
function resetSamples(): void {
|
||||
probeResults.value = [];
|
||||
samples.value = [];
|
||||
attempts.value = 0;
|
||||
async function runProbe(expectedGeneration = generation): Promise<void> {
|
||||
if (running.value || !connected.value) return;
|
||||
running.value = true;
|
||||
try {
|
||||
const sample = await measureAudioStatus();
|
||||
if (expectedGeneration !== generation || !connected.value || !sample) return;
|
||||
previousSample.value = latestSample.value;
|
||||
latestSample.value = sample;
|
||||
} finally {
|
||||
if (expectedGeneration === generation) running.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function stop(): void {
|
||||
@@ -49,31 +157,15 @@ export function useWebClientPerformance(
|
||||
}
|
||||
generation += 1;
|
||||
running.value = false;
|
||||
}
|
||||
|
||||
async function runProbe(expectedGeneration = generation): Promise<void> {
|
||||
if (running.value || !connected.value || !panelOpen.value) return;
|
||||
running.value = true;
|
||||
try {
|
||||
const sample = await measureLatency();
|
||||
if (expectedGeneration !== generation || !panelOpen.value) return;
|
||||
probeResults.value.push(sample);
|
||||
if (probeResults.value.length > SAMPLE_WINDOW_SIZE) probeResults.value.shift();
|
||||
attempts.value = probeResults.value.length;
|
||||
samples.value = probeResults.value.filter((result): result is LatencyProbeResult => result !== null);
|
||||
} finally {
|
||||
if (expectedGeneration === generation) running.value = false;
|
||||
}
|
||||
latestSample.value = null;
|
||||
previousSample.value = null;
|
||||
}
|
||||
|
||||
function start(): void {
|
||||
if (timer !== null || !connected.value) return;
|
||||
resetSamples();
|
||||
const activeGeneration = ++generation;
|
||||
void runProbe(activeGeneration);
|
||||
timer = window.setInterval(() => {
|
||||
void runProbe(activeGeneration);
|
||||
}, SAMPLE_INTERVAL_MS);
|
||||
timer = window.setInterval(() => { void runProbe(activeGeneration); }, SAMPLE_INTERVAL_MS);
|
||||
}
|
||||
|
||||
function refresh(): void {
|
||||
@@ -84,18 +176,12 @@ export function useWebClientPerformance(
|
||||
panelOpen.value = !panelOpen.value;
|
||||
}
|
||||
|
||||
watch([connected, panelOpen], ([isConnected, isOpen]) => {
|
||||
if (isConnected && isOpen) start();
|
||||
watch(connected, (isConnected) => {
|
||||
if (isConnected) start();
|
||||
else stop();
|
||||
}, { immediate: true });
|
||||
|
||||
onUnmounted(stop);
|
||||
|
||||
return {
|
||||
panelOpen,
|
||||
running,
|
||||
stats,
|
||||
togglePanel,
|
||||
refresh,
|
||||
};
|
||||
return { panelOpen, running, stats, togglePanel, refresh };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { computed, reactive, ref, type Ref } from "vue";
|
||||
import { splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import { DEFAULT_TEAM_SPEAK_PORT, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import type { Language } from "../i18n/web-client.js";
|
||||
|
||||
interface RelayOption {
|
||||
@@ -31,6 +31,7 @@ export function useWebClientPublicConfig({
|
||||
const visitorNumber = ref<number | null>(null);
|
||||
const visitorTotal = ref<number | null>(null);
|
||||
const accelerationRelays = ref<RelayOption[]>([]);
|
||||
const openTargetPrefillBlocked = ref(false);
|
||||
const serverConfigLoading = ref(true);
|
||||
const welcomeTexts = reactive<Record<Language, string>>({ zh: "", en: "", de: "", ru: "", ja: "" });
|
||||
const accelerationAvailable = computed(() => accelerationRelays.value.length > 0);
|
||||
@@ -50,6 +51,7 @@ export function useWebClientPublicConfig({
|
||||
welcomeTexts?: unknown;
|
||||
accessMode?: unknown;
|
||||
target?: unknown;
|
||||
targetPrefillBlocked?: unknown;
|
||||
visitorNumber?: unknown;
|
||||
visitorTotal?: unknown;
|
||||
accelerationRelays?: unknown;
|
||||
@@ -80,7 +82,11 @@ export function useWebClientPublicConfig({
|
||||
: [];
|
||||
if (!accelerationAvailable.value || !accelerationRelays.value.some((relay) => relay.id === accelerationRelayId.value)) accelerationRelayId.value = "";
|
||||
const hasInviteTarget = query.has("server") || query.has("target") || query.has("tsHost") || query.has("tsPort");
|
||||
if (!hasInviteTarget && typeof config.target === "string" && config.target.trim()) {
|
||||
openTargetPrefillBlocked.value = !hasInviteTarget && accessMode.value === "open" && config.targetPrefillBlocked === true;
|
||||
if (openTargetPrefillBlocked.value) {
|
||||
serverHost.value = "";
|
||||
serverPort.value = DEFAULT_TEAM_SPEAK_PORT;
|
||||
} else if (!hasInviteTarget && typeof config.target === "string" && config.target.trim()) {
|
||||
const target = splitTeamSpeakTarget(config.target);
|
||||
serverHost.value = target.address;
|
||||
serverPort.value = target.port;
|
||||
@@ -100,6 +106,7 @@ export function useWebClientPublicConfig({
|
||||
visitorNumber,
|
||||
visitorTotal,
|
||||
accelerationRelays,
|
||||
openTargetPrefillBlocked,
|
||||
accelerationAvailable,
|
||||
serverConfigLoading,
|
||||
localizedWelcomeText,
|
||||
|
||||
@@ -42,6 +42,7 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
serverPort: "语音端口",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "这是网关服务器连接的 TeamSpeak 地址和端口,不是浏览器直接连接地址。",
|
||||
openTargetDefaultNotPrefilled: "默认目标是内网或不可公开访问的地址,因此开放模式未自动填入。请输入公网 TeamSpeak 地址,或请管理员切换为“仅限此 TeamSpeak 服务器”。",
|
||||
relayAcceleration: "连接中继",
|
||||
directConnection: "直连 TeamSpeak",
|
||||
relayAccelerationHint: "选择一个已配置的中继节点,适合直连不稳定或被拒绝的服务器。",
|
||||
@@ -313,6 +314,40 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
languageMenu: "语言",
|
||||
networkPerformance: "网络性能",
|
||||
networkPerformanceHint: "浏览器到网关,再到 TeamSpeak 的实时探测",
|
||||
voiceStatus: "语音状态",
|
||||
voiceStatusHint: "显示实际音频帧;WebRTC 时读取浏览器媒体统计,兼容模式看帧流;不会注入测试音",
|
||||
voiceHealthDisconnected: "语音未连接",
|
||||
voiceHealthSampling: "等待媒体数据",
|
||||
voiceHealthConnecting: "音频通道建立中",
|
||||
voiceHealthWarning: "检测到麦克风、播放输出或音频转发异常",
|
||||
voiceHealthActive: "实际音频流活跃",
|
||||
voiceHealthQuiet: "已连接,当前无活跃语音",
|
||||
voiceTransportWebRTC: "WebRTC 音频",
|
||||
voiceTransportWebSocket: "兼容传输 · WebSocket",
|
||||
voiceTransportNegotiating: "WebRTC 协商中",
|
||||
voiceTransportDisconnected: "未连接",
|
||||
voiceUplink: "本机 → TeamSpeak",
|
||||
voiceDownlink: "TeamSpeak → 本机播放",
|
||||
audioFramesPerSecondUnit: "帧/秒",
|
||||
audioBitrate: "媒体码率",
|
||||
voicePacketLoss: "RTP 丢包",
|
||||
voiceRtt: "RTT",
|
||||
voiceJitter: "抖动",
|
||||
voiceFallbackMetricHint: "兼容传输不提供 RTP 丢包和抖动统计",
|
||||
voiceMicMuted: "已静音",
|
||||
voiceMicOpen: "采集可用",
|
||||
voiceMicUnavailable: "麦克风不可用",
|
||||
voiceMicWaiting: "等待麦克风权限",
|
||||
voicePlayback: "播放",
|
||||
voicePlaybackReady: "输出通道可用",
|
||||
voicePlaybackPaused: "浏览器音频上下文暂停",
|
||||
voicePlaybackUnavailable: "尚未建立播放通道",
|
||||
voiceSendErrors: "发送错误",
|
||||
voiceDroppedFrames: "近期丢弃帧",
|
||||
voiceQueueUnderruns: "近期播放欠载",
|
||||
voiceStatusSampling: "正在采集当前音频指标…",
|
||||
voiceStatusLiveHint: "每 2 秒采样实际音频帧和浏览器媒体统计",
|
||||
voiceStatusWaiting: "连接后开始读取实际媒体状态",
|
||||
browser: "浏览器",
|
||||
webSpeakGateway: "WebSpeak",
|
||||
teamSpeakServer: "TeamSpeak",
|
||||
@@ -374,6 +409,7 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
serverPort: "Voice port",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "This is the TeamSpeak address and port reached by the gateway, not a direct browser connection.",
|
||||
openTargetDefaultNotPrefilled: "The default target is private or not publicly reachable, so it was not filled in for open mode. Enter a public TeamSpeak address or ask the administrator to restrict access to the configured server.",
|
||||
relayAcceleration: "Connection relay",
|
||||
directConnection: "Direct TeamSpeak connection",
|
||||
relayAccelerationHint: "Choose a configured relay when the direct path is unstable or blocked.",
|
||||
@@ -645,6 +681,40 @@ export const webClientTranslations: Record<string, Record<string, string>> = {
|
||||
languageMenu: "Language",
|
||||
networkPerformance: "Network performance",
|
||||
networkPerformanceHint: "Live probes from the browser to WebSpeak and TeamSpeak",
|
||||
voiceStatus: "Voice status",
|
||||
voiceStatusHint: "Actual audio frames; browser media stats on WebRTC, frame flow on fallback. No test audio is injected",
|
||||
voiceHealthDisconnected: "Voice session disconnected",
|
||||
voiceHealthSampling: "Waiting for media statistics",
|
||||
voiceHealthConnecting: "Audio transport connecting",
|
||||
voiceHealthWarning: "Microphone, playback, or audio forwarding issue detected",
|
||||
voiceHealthActive: "Audio media is flowing",
|
||||
voiceHealthQuiet: "Connected; no active speech frames",
|
||||
voiceTransportWebRTC: "WebRTC audio",
|
||||
voiceTransportWebSocket: "Compatibility transport · WebSocket",
|
||||
voiceTransportNegotiating: "Negotiating WebRTC",
|
||||
voiceTransportDisconnected: "Disconnected",
|
||||
voiceUplink: "Microphone → TeamSpeak",
|
||||
voiceDownlink: "TeamSpeak → Playback",
|
||||
audioFramesPerSecondUnit: "frames/s",
|
||||
audioBitrate: "Media bitrate",
|
||||
voicePacketLoss: "RTP loss",
|
||||
voiceRtt: "RTT",
|
||||
voiceJitter: "Jitter",
|
||||
voiceFallbackMetricHint: "RTP loss and jitter are unavailable on compatibility transport",
|
||||
voiceMicMuted: "Muted",
|
||||
voiceMicOpen: "Capture ready",
|
||||
voiceMicUnavailable: "Microphone unavailable",
|
||||
voiceMicWaiting: "Waiting for microphone permission",
|
||||
voicePlayback: "Playback",
|
||||
voicePlaybackReady: "Output path ready",
|
||||
voicePlaybackPaused: "Browser audio context suspended",
|
||||
voicePlaybackUnavailable: "Playback path not established",
|
||||
voiceSendErrors: "Send errors",
|
||||
voiceDroppedFrames: "Recently dropped frames",
|
||||
voiceQueueUnderruns: "Recent playback underruns",
|
||||
voiceStatusSampling: "Sampling current audio metrics…",
|
||||
voiceStatusLiveHint: "Actual audio frames and browser media stats sampled every 2 seconds",
|
||||
voiceStatusWaiting: "Actual media statistics appear after connecting",
|
||||
browser: "Browser",
|
||||
webSpeakGateway: "WebSpeak",
|
||||
teamSpeakServer: "TeamSpeak",
|
||||
@@ -709,6 +779,7 @@ webClientTranslations.de = {
|
||||
serverPort: "Sprachport",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "Dies ist die TeamSpeak-Adresse und der Port, die vom Gateway erreicht werden – keine direkte Browseradresse.",
|
||||
openTargetDefaultNotPrefilled: "Das Standardziel ist privat oder nicht öffentlich erreichbar und wird im offenen Modus nicht vorausgefüllt. Gib eine öffentliche TeamSpeak-Adresse ein oder bitte den Administrator, den Zugriff auf den konfigurierten Server zu beschränken.",
|
||||
relayAcceleration: "Verbindungs-Relay",
|
||||
directConnection: "Direkte TeamSpeak-Verbindung",
|
||||
relayAccelerationHint: "Wähle einen konfigurierten Relay, wenn die direkte Verbindung instabil ist oder abgelehnt wird.",
|
||||
@@ -971,6 +1042,40 @@ webClientTranslations.de = {
|
||||
languageMenu: "Sprache",
|
||||
networkPerformance: "Netzwerkleistung",
|
||||
networkPerformanceHint: "Live-Messung vom Browser über WebSpeak zu TeamSpeak",
|
||||
voiceStatus: "Sprachstatus",
|
||||
voiceStatusHint: "Reale Audioframes; Browser-Medienwerte bei WebRTC, Framefluss im Kompatibilitätsmodus. Kein Testton",
|
||||
voiceHealthDisconnected: "Sprachsitzung getrennt",
|
||||
voiceHealthSampling: "Warte auf Mediendaten",
|
||||
voiceHealthConnecting: "Audioverbindung wird aufgebaut",
|
||||
voiceHealthWarning: "Mikrofon-, Wiedergabe- oder Audio-Weiterleitungsproblem erkannt",
|
||||
voiceHealthActive: "Audiomedien werden übertragen",
|
||||
voiceHealthQuiet: "Verbunden; momentan keine aktiven Sprachframes",
|
||||
voiceTransportWebRTC: "WebRTC-Audio",
|
||||
voiceTransportWebSocket: "Kompatibilitätsmodus · WebSocket",
|
||||
voiceTransportNegotiating: "WebRTC wird ausgehandelt",
|
||||
voiceTransportDisconnected: "Getrennt",
|
||||
voiceUplink: "Mikrofon → TeamSpeak",
|
||||
voiceDownlink: "TeamSpeak → Wiedergabe",
|
||||
audioFramesPerSecondUnit: "Frames/s",
|
||||
audioBitrate: "Medienbitrate",
|
||||
voicePacketLoss: "RTP-Verlust",
|
||||
voiceRtt: "RTT",
|
||||
voiceJitter: "Jitter",
|
||||
voiceFallbackMetricHint: "Im Kompatibilitätsmodus sind RTP-Verlust und Jitter nicht verfügbar",
|
||||
voiceMicMuted: "Stumm",
|
||||
voiceMicOpen: "Aufnahme bereit",
|
||||
voiceMicUnavailable: "Mikrofon nicht verfügbar",
|
||||
voiceMicWaiting: "Warte auf Mikrofonberechtigung",
|
||||
voicePlayback: "Wiedergabe",
|
||||
voicePlaybackReady: "Ausgabepfad bereit",
|
||||
voicePlaybackPaused: "Audio-Kontext des Browsers angehalten",
|
||||
voicePlaybackUnavailable: "Wiedergabepfad nicht eingerichtet",
|
||||
voiceSendErrors: "Sendefehler",
|
||||
voiceDroppedFrames: "Kürzlich verworfene Frames",
|
||||
voiceQueueUnderruns: "Kürzliche Wiedergabe-Unterläufe",
|
||||
voiceStatusSampling: "Aktuelle Audiowerte werden erfasst…",
|
||||
voiceStatusLiveHint: "Tatsächliche Audioframes und Browser-Medienwerte alle 2 Sekunden",
|
||||
voiceStatusWaiting: "Messwerte werden nach dem Verbinden angezeigt",
|
||||
browser: "Browser",
|
||||
webSpeakGateway: "WebSpeak",
|
||||
teamSpeakServer: "TeamSpeak",
|
||||
@@ -1071,6 +1176,7 @@ webClientTranslations.ru = {
|
||||
serverPort: "Голосовой порт",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "Это адрес и порт TeamSpeak, к которым обращается шлюз, а не прямое подключение браузера.",
|
||||
openTargetDefaultNotPrefilled: "Целевой адрес по умолчанию является внутренним или недоступен извне, поэтому в открытом режиме он не подставлен. Введите публичный адрес TeamSpeak или попросите администратора ограничить доступ настроенным сервером.",
|
||||
relayAcceleration: "Подключение через ретранслятор",
|
||||
directConnection: "Прямое подключение к TeamSpeak",
|
||||
relayAccelerationHint: "Выберите настроенный ретранслятор, если прямой маршрут нестабилен или заблокирован.",
|
||||
@@ -1095,6 +1201,40 @@ webClientTranslations.ru = {
|
||||
languageMenu: "Язык",
|
||||
networkPerformance: "Сетевая производительность",
|
||||
networkPerformanceHint: "Непрерывные измерения от браузера через WebSpeak к TeamSpeak",
|
||||
voiceStatus: "Состояние голоса",
|
||||
voiceStatusHint: "Реальные аудиокадры; статистика браузера при WebRTC, поток кадров в совместимом режиме. Без тестового звука",
|
||||
voiceHealthDisconnected: "Голосовая сессия отключена",
|
||||
voiceHealthSampling: "Ожидание медиаданных",
|
||||
voiceHealthConnecting: "Подключение аудиоканала",
|
||||
voiceHealthWarning: "Проблема с микрофоном, воспроизведением или передачей аудио",
|
||||
voiceHealthActive: "Аудиоданные передаются",
|
||||
voiceHealthQuiet: "Подключено; активных голосовых кадров сейчас нет",
|
||||
voiceTransportWebRTC: "Аудио WebRTC",
|
||||
voiceTransportWebSocket: "Совместимый режим · WebSocket",
|
||||
voiceTransportNegotiating: "Согласование WebRTC",
|
||||
voiceTransportDisconnected: "Отключено",
|
||||
voiceUplink: "Микрофон → TeamSpeak",
|
||||
voiceDownlink: "TeamSpeak → воспроизведение",
|
||||
audioFramesPerSecondUnit: "кадр/с",
|
||||
audioBitrate: "Битрейт медиа",
|
||||
voicePacketLoss: "Потери RTP",
|
||||
voiceRtt: "RTT",
|
||||
voiceJitter: "Джиттер",
|
||||
voiceFallbackMetricHint: "В совместимом режиме потери RTP и джиттер недоступны",
|
||||
voiceMicMuted: "Выключен",
|
||||
voiceMicOpen: "Захват готов",
|
||||
voiceMicUnavailable: "Микрофон недоступен",
|
||||
voiceMicWaiting: "Ожидание разрешения на микрофон",
|
||||
voicePlayback: "Воспроизведение",
|
||||
voicePlaybackReady: "Выходной канал готов",
|
||||
voicePlaybackPaused: "Аудиоконтекст браузера приостановлен",
|
||||
voicePlaybackUnavailable: "Канал воспроизведения не создан",
|
||||
voiceSendErrors: "Ошибки отправки",
|
||||
voiceDroppedFrames: "Недавно отброшенные кадры",
|
||||
voiceQueueUnderruns: "Недавние сбои очереди воспроизведения",
|
||||
voiceStatusSampling: "Сбор текущих аудиопоказателей…",
|
||||
voiceStatusLiveHint: "Реальные аудиокадры и статистика браузера обновляются каждые 2 секунды",
|
||||
voiceStatusWaiting: "Реальные медиаданные появятся после подключения",
|
||||
packetLoss: "Потери пакетов",
|
||||
measuring: "Измерение…",
|
||||
measureComplete: "Мониторинг продолжается (обновление каждые 3 секунды)",
|
||||
@@ -1190,6 +1330,7 @@ webClientTranslations.ja = {
|
||||
serverPort: "音声ポート",
|
||||
serverPortPlaceholder: "9987",
|
||||
serverAddressHint: "ゲートウェイが接続する TeamSpeak のアドレスとポートです。ブラウザからの直接接続先ではありません。",
|
||||
openTargetDefaultNotPrefilled: "既定の接続先は内部アドレスまたは外部から到達できないため、オープンモードでは自動入力されません。公開 TeamSpeak アドレスを入力するか、管理者に設定済みサーバー限定へ切り替えてもらってください。",
|
||||
relayAcceleration: "中継接続",
|
||||
directConnection: "TeamSpeak へ直接接続",
|
||||
relayAccelerationHint: "直接接続が不安定またはブロックされている場合は、設定済みの中継を選択してください。",
|
||||
@@ -1214,6 +1355,40 @@ webClientTranslations.ja = {
|
||||
languageMenu: "言語",
|
||||
networkPerformance: "ネットワーク性能",
|
||||
networkPerformanceHint: "ブラウザから WebSpeak を経由して TeamSpeak まで継続測定",
|
||||
voiceStatus: "音声状態",
|
||||
voiceStatusHint: "実音声フレームを表示。WebRTC ではブラウザー統計、互換モードではフレーム数を計測。テスト音は送信しません",
|
||||
voiceHealthDisconnected: "音声セッション未接続",
|
||||
voiceHealthSampling: "メディア情報を取得中",
|
||||
voiceHealthConnecting: "音声経路を接続中",
|
||||
voiceHealthWarning: "マイク、再生、または音声転送に異常を検出",
|
||||
voiceHealthActive: "音声メディアを送受信中",
|
||||
voiceHealthQuiet: "接続済み・現在は発話なし",
|
||||
voiceTransportWebRTC: "WebRTC 音声",
|
||||
voiceTransportWebSocket: "互換モード · WebSocket",
|
||||
voiceTransportNegotiating: "WebRTC をネゴシエート中",
|
||||
voiceTransportDisconnected: "未接続",
|
||||
voiceUplink: "マイク → TeamSpeak",
|
||||
voiceDownlink: "TeamSpeak → 再生",
|
||||
audioFramesPerSecondUnit: "フレーム/秒",
|
||||
audioBitrate: "メディアビットレート",
|
||||
voicePacketLoss: "RTP 損失",
|
||||
voiceRtt: "RTT",
|
||||
voiceJitter: "ジッター",
|
||||
voiceFallbackMetricHint: "互換モードでは RTP 損失とジッターを取得できません",
|
||||
voiceMicMuted: "ミュート中",
|
||||
voiceMicOpen: "入力準備完了",
|
||||
voiceMicUnavailable: "マイクを利用できません",
|
||||
voiceMicWaiting: "マイクの許可を待機中",
|
||||
voicePlayback: "再生",
|
||||
voicePlaybackReady: "出力経路は利用可能",
|
||||
voicePlaybackPaused: "ブラウザーの音声処理が停止中",
|
||||
voicePlaybackUnavailable: "再生経路は未確立",
|
||||
voiceSendErrors: "送信エラー",
|
||||
voiceDroppedFrames: "直近の破棄フレーム",
|
||||
voiceQueueUnderruns: "直近の再生アンダーラン",
|
||||
voiceStatusSampling: "現在の音声指標を取得中…",
|
||||
voiceStatusLiveHint: "実音声フレームとブラウザーのメディア統計を2秒ごとに計測",
|
||||
voiceStatusWaiting: "接続後に実際のメディア状態を表示します",
|
||||
packetLoss: "パケット損失",
|
||||
measuring: "測定中…",
|
||||
measureComplete: "継続監視中(3秒ごとに更新)",
|
||||
|
||||
@@ -733,7 +733,7 @@
|
||||
.performance-trigger { display: inline-flex; align-items: center; gap: 6px; min-height: 33px; padding: 0 9px; color: var(--accent); background: color-mix(in srgb, var(--accent) 8%, var(--surface-1)); border: 1px solid var(--border); border-radius: 8px; font-size: 11px; cursor: pointer; transition: .16s; }
|
||||
.performance-trigger:hover, .performance-trigger[aria-expanded="true"] { background: color-mix(in srgb, var(--accent) 15%, var(--surface-1)); border-color: color-mix(in srgb, var(--accent) 35%, var(--border)); }
|
||||
.performance-trigger small { color: var(--text-muted); font-size: 10px; }
|
||||
.performance-panel { position: absolute; top: calc(100% + 10px); right: 0; width: 330px; padding: 15px; color: var(--text-primary); background: var(--surface-1); border: 1px solid var(--border); border-radius: 13px; box-shadow: 0 16px 36px color-mix(in srgb, var(--text-primary) 18%, transparent); }
|
||||
.performance-panel { position: absolute; top: calc(100% + 10px); right: 0; width: 380px; padding: 15px; color: var(--text-primary); background: var(--surface-1); border: 1px solid var(--border); border-radius: 13px; box-shadow: 0 16px 36px color-mix(in srgb, var(--text-primary) 18%, transparent); }
|
||||
.performance-panel header { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.performance-panel header strong, .performance-panel header small { display: block; }
|
||||
.performance-panel header strong { font-size: 13px; }
|
||||
@@ -750,6 +750,19 @@
|
||||
.performance-metrics strong { margin-top: 6px; color: var(--accent); font-size: 18px; }
|
||||
.performance-metrics span { margin-top: 4px; color: var(--text-muted); font-size: 9px; }
|
||||
.performance-status { margin: 11px 0 0; color: var(--text-muted); font-size: 10px; }
|
||||
.voice-status-summary { display: flex; align-items: center; gap: 9px; margin: 14px 0 10px; padding: 9px 10px; background: var(--surface-2); border: 1px solid var(--border); border-radius: 9px; }
|
||||
.voice-status-summary > i { width: 9px; height: 9px; flex: 0 0 9px; background: var(--text-muted); border-radius: 50%; box-shadow: 0 0 0 3px color-mix(in srgb, var(--text-muted) 12%, transparent); }
|
||||
.voice-status-summary[data-health="active"] > i { background: #22a777; box-shadow: 0 0 0 3px color-mix(in srgb, #22a777 16%, transparent); }
|
||||
.voice-status-summary[data-health="warning"] > i { background: #dc8b24; box-shadow: 0 0 0 3px color-mix(in srgb, #dc8b24 16%, transparent); }
|
||||
.voice-status-summary[data-health="connecting"], .voice-status-summary[data-health="sampling"] { opacity: .82; }
|
||||
.voice-status-summary > div { display: flex; min-width: 0; flex-direction: column; gap: 3px; }
|
||||
.voice-status-summary strong { overflow: hidden; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.voice-status-summary small { overflow: hidden; color: var(--text-muted); font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.voice-audio-metrics article { min-height: 104px; }
|
||||
.voice-audio-metrics strong { font-size: 16px; }
|
||||
.voice-audio-metrics span { white-space: normal; line-height: 1.45; }
|
||||
.voice-audio-details { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 10px; margin-top: 9px; color: var(--text-muted); font-size: 9px; line-height: 1.4; }
|
||||
.voice-audio-details > span { min-width: 0; overflow-wrap: anywhere; }
|
||||
.webrtc-stats { margin-top: 13px; padding-top: 12px; border-top: 1px solid var(--border); }
|
||||
.webrtc-stats > header { display: block; margin-bottom: 8px; }
|
||||
.webrtc-stats > header strong, .webrtc-stats > header small { display: block; }
|
||||
|
||||
@@ -49,6 +49,7 @@
|
||||
<label class="field-label" data-ws-part="home.field-label" for="server-address"><span>{{ t('serverAddress') }}</span><div class="field-wrap" data-ws-part="home.field"><Icon name="server" :size="17" /><input id="server-address" v-model="serverHost" autocomplete="url" :placeholder="t('serverAddressPlaceholder')" /></div></label>
|
||||
<label class="field-label" data-ws-part="home.field-label" for="server-port"><span>{{ t('serverPort') }}</span><div class="field-wrap" data-ws-part="home.field"><Icon name="hash" :size="17" /><input id="server-port" v-model="serverPort" inputmode="numeric" type="text" maxlength="5" :placeholder="t('serverPortPlaceholder')" /></div></label>
|
||||
</div>
|
||||
<div v-if="openTargetPrefillBlocked" class="notice warning-notice" data-ws-part="home.notice" data-ws-state="target-prefill-blocked"><span class="notice-symbol">i</span><span>{{ t('openTargetDefaultNotPrefilled') }}</span></div>
|
||||
<div v-if="accelerationAvailable" class="acceleration-choice" data-ws-part="home.relay-choice"><div class="acceleration-copy" data-ws-part="home.relay-choice.copy"><strong>{{ t('relayAcceleration') }}</strong><small>{{ t('relayAccelerationHint') }}</small></div><select v-model="accelerationRelayId" :aria-label="t('relayAcceleration')"><option value="">{{ t('directConnection') }}</option><option v-for="relay in accelerationRelays" :key="relay.id" :value="relay.id">{{ relay.name }}</option></select></div>
|
||||
<div v-if="accessMode === 'open' && (favoriteServers.length || recentServers.length)" class="local-servers" data-ws-part="home.server-history">
|
||||
<div v-if="favoriteServers.length" class="local-server-group" data-ws-part="home.server-history.group" data-ws-state="favorite"><span>{{ t('favoriteServers') }}</span><button v-for="favorite in favoriteServers" :key="favorite.id" type="button" @click="selectLocalServer(favorite.address, favorite.nickname)">{{ favorite.label }}</button></div>
|
||||
@@ -109,12 +110,16 @@
|
||||
<div class="breadcrumbs" data-ws-part="voice.breadcrumbs"><span class="mobile-brand">TeamSpeak <em>Web</em></span><span class="crumb-muted">{{ t('serverBreadcrumb') }}</span><Icon name="chevron-right" :size="14" /><strong>{{ currentChannelName }}</strong></div>
|
||||
<div class="workspace-actions" data-ws-part="voice.header-actions">
|
||||
<div class="network-performance" data-ws-part="voice.performance">
|
||||
<button type="button" class="performance-trigger" :title="t('networkPerformance')" :aria-label="t('networkPerformance')" :aria-expanded="performancePanelOpen" @click.stop="togglePerformancePanel"><Icon name="activity" :size="16" /><span class="performance-trigger-label">{{ t('networkPerformance') }}</span><small v-if="performanceStats.ready && performanceStats.gatewayLatencyMs != null">{{ performanceStats.gatewayLatencyMs }} ms</small><Icon name="chevron-down" :size="13" /></button>
|
||||
<section v-if="performancePanelOpen" class="performance-panel" data-ws-part="voice.performance.panel" role="dialog" :aria-label="t('networkPerformance')" @click.stop>
|
||||
<header><div><strong>{{ t('networkPerformance') }}</strong><small>{{ t('networkPerformanceHint') }}</small></div><button type="button" class="performance-refresh" :title="t('measureNow')" :disabled="performanceRunning" @click="refreshPerformanceProbe"><Icon name="refresh" :size="15" /></button></header>
|
||||
<div class="performance-route" data-ws-part="voice.performance.route"><span>{{ t('browser') }}</span><i></i><span>{{ t('webSpeakGateway') }}</span><i></i><span>{{ t('teamSpeakServer') }}</span></div>
|
||||
<div class="performance-metrics" data-ws-part="voice.performance.metrics"><article><small>{{ t('browserToGateway') }}</small><strong>{{ performanceStats.gatewayLatencyMs == null ? '—' : `${performanceStats.gatewayLatencyMs} ms` }}</strong><span>{{ t('packetLoss') }} {{ performanceStats.gatewayLossPercent == null ? '—' : `${performanceStats.gatewayLossPercent}%` }}</span></article><article><small>{{ t('gatewayToTeamSpeak') }}</small><strong>{{ performanceStats.teamSpeakLatencyMs == null ? '—' : `${performanceStats.teamSpeakLatencyMs} ms` }}</strong><span>{{ t('packetLoss') }} {{ performanceStats.teamSpeakLossPercent == null ? '—' : `${performanceStats.teamSpeakLossPercent}%` }}</span></article></div>
|
||||
<p class="performance-status" data-ws-part="voice.performance.status">{{ performanceRunning ? t('measuring') : performanceStats.ready ? t('measureComplete') : t('measureUnavailable') }}</p>
|
||||
<button type="button" class="performance-trigger" :title="t('voiceStatus')" :aria-label="t('voiceStatus')" :aria-expanded="performancePanelOpen" @click.stop="togglePerformancePanel"><Icon name="activity" :size="16" /><span class="performance-trigger-label">{{ t('voiceStatus') }}</span><small v-if="performanceStats.ready">{{ voiceTransportLabel }}</small><Icon name="chevron-down" :size="13" /></button>
|
||||
<section v-if="performancePanelOpen" class="performance-panel" data-ws-part="voice.performance.panel" role="dialog" :aria-label="t('voiceStatus')" @click.stop>
|
||||
<header><div><strong>{{ t('voiceStatus') }}</strong><small>{{ t('voiceStatusHint') }}</small></div><button type="button" class="performance-refresh" :title="t('measureNow')" :disabled="performanceRunning" @click="refreshPerformanceProbe"><Icon name="refresh" :size="15" /></button></header>
|
||||
<div class="voice-status-summary" :data-health="performanceStats.health" data-ws-part="voice.performance.route"><i></i><div><strong>{{ voiceHealthLabel }}</strong><small>{{ voiceTransportLabel }}<template v-if="performanceStats.connectionState"> · {{ performanceStats.connectionState }}</template></small></div></div>
|
||||
<div class="performance-metrics voice-audio-metrics" data-ws-part="voice.performance.metrics">
|
||||
<article><small>{{ t('voiceUplink') }}</small><strong>{{ performanceStats.uplinkFramesPerSecond == null ? '—' : `${performanceStats.uplinkFramesPerSecond} ${t('audioFramesPerSecondUnit')}` }}</strong><span>{{ t('audioBitrate') }} {{ performanceStats.uplinkBitrateKbps == null ? '—' : `${performanceStats.uplinkBitrateKbps} kbps` }}</span><span v-if="performanceStats.transport === 'webrtc'">{{ t('voicePacketLoss') }} {{ performanceStats.uplinkLossPercent == null ? '—' : `${performanceStats.uplinkLossPercent.toFixed(2)}%` }} · {{ t('voiceRtt') }} {{ performanceStats.uplinkRttMs == null ? '—' : `${Math.round(performanceStats.uplinkRttMs)} ms` }}</span><span v-else>{{ t('voiceFallbackMetricHint') }}</span></article>
|
||||
<article><small>{{ t('voiceDownlink') }}</small><strong>{{ performanceStats.downlinkFramesPerSecond == null ? '—' : `${performanceStats.downlinkFramesPerSecond} ${t('audioFramesPerSecondUnit')}` }}</strong><span>{{ t('audioBitrate') }} {{ performanceStats.downlinkBitrateKbps == null ? '—' : `${performanceStats.downlinkBitrateKbps} kbps` }}</span><span v-if="performanceStats.transport === 'webrtc'">{{ t('voicePacketLoss') }} {{ performanceStats.downlinkLossPercent == null ? '—' : `${performanceStats.downlinkLossPercent.toFixed(2)}%` }} · {{ t('voiceJitter') }} {{ performanceStats.downlinkJitterMs == null ? '—' : `${Math.round(performanceStats.downlinkJitterMs)} ms` }}</span><span v-else>{{ t('voiceFallbackMetricHint') }}</span></article>
|
||||
</div>
|
||||
<div class="voice-audio-details"><span>{{ t('microphone') }} · {{ voiceMicrophoneLabel }}</span><span>{{ t('voicePlayback') }} · {{ voicePlaybackLabel }}</span><span>{{ t('voiceSendErrors') }} {{ performanceStats.sendErrors == null ? '—' : performanceStats.sendErrors }} · {{ t('voiceDroppedFrames') }} {{ performanceStats.droppedFrames == null ? '—' : performanceStats.droppedFrames }}</span><span v-if="performanceStats.transport === 'webrtc'">{{ t('voiceQueueUnderruns') }} {{ performanceStats.queueUnderruns == null ? '—' : performanceStats.queueUnderruns }}</span></div>
|
||||
<p class="performance-status" data-ws-part="voice.performance.status">{{ performanceRunning ? t('voiceStatusSampling') : performanceStats.ready ? t('voiceStatusLiveHint') : t('voiceStatusWaiting') }}</p>
|
||||
<section v-if="screenShareWebRtcStats.peers.length" class="webrtc-stats" data-ws-part="voice.performance.webrtc-stats" aria-live="polite">
|
||||
<header><div><strong>{{ t('webrtcStats') }}</strong><small>{{ t('webrtcStatsHint') }}</small></div></header>
|
||||
<div v-if="screenShareWebRtcStats.capture" class="webrtc-stats-capture"><span>{{ t('screenShareCapture') }}</span><strong>{{ screenShareWebRtcStats.capture.width ?? '—' }} × {{ screenShareWebRtcStats.capture.height ?? '—' }}</strong><small>{{ screenShareWebRtcStats.capture.frameRate == null ? '—' : `${screenShareWebRtcStats.capture.frameRate.toFixed(1)} FPS` }}</small></div>
|
||||
@@ -472,7 +477,7 @@ const {
|
||||
leaveScreenShare,
|
||||
checkSupport,
|
||||
clearError,
|
||||
measureLatency,
|
||||
measureVoiceAudioStatus,
|
||||
} = useVoiceWebSocket();
|
||||
const {
|
||||
panelOpen: performancePanelOpen,
|
||||
@@ -480,7 +485,17 @@ const {
|
||||
stats: performanceStats,
|
||||
togglePanel: togglePerformancePanel,
|
||||
refresh: refreshPerformanceProbe,
|
||||
} = useWebClientPerformance(computed(() => voiceState.connected), measureLatency);
|
||||
} = useWebClientPerformance(computed(() => voiceState.connected), measureVoiceAudioStatus);
|
||||
const voiceHealthLabel = computed(() => t(({ disconnected: "voiceHealthDisconnected", sampling: "voiceHealthSampling", connecting: "voiceHealthConnecting", warning: "voiceHealthWarning", active: "voiceHealthActive", quiet: "voiceHealthQuiet" } as const)[performanceStats.value.health]));
|
||||
const voiceTransportLabel = computed(() => t(({ webrtc: "voiceTransportWebRTC", websocket: "voiceTransportWebSocket", negotiating: "voiceTransportNegotiating", disconnected: "voiceTransportDisconnected" } as const)[performanceStats.value.transport]));
|
||||
const voicePlaybackLabel = computed(() => t(({ playing: "voicePlaybackReady", paused: "voicePlaybackPaused", unavailable: "voicePlaybackUnavailable" } as const)[performanceStats.value.playbackState ?? "unavailable"]));
|
||||
const voiceMicrophoneLabel = computed(() => performanceStats.value.microphoneMuted
|
||||
? t("voiceMicMuted")
|
||||
: performanceStats.value.microphoneReady
|
||||
? t("voiceMicOpen")
|
||||
: performanceStats.value.microphonePermission === "denied" || performanceStats.value.microphonePermission === "granted"
|
||||
? t("voiceMicUnavailable")
|
||||
: t("voiceMicWaiting"));
|
||||
|
||||
const query = new URLSearchParams(location.search);
|
||||
const initialChannel = query.get("channel") ?? "";
|
||||
@@ -537,6 +552,7 @@ const {
|
||||
visitorNumber,
|
||||
visitorTotal,
|
||||
accelerationRelays,
|
||||
openTargetPrefillBlocked,
|
||||
accelerationAvailable,
|
||||
serverConfigLoading,
|
||||
localizedWelcomeText,
|
||||
|
||||
Reference in new issue
Block a user