mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02: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
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user