mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-01 02:52:49 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
556084233d | ||
|
|
c38239ec35 | ||
|
|
21041346e3 | ||
|
|
7320aa3bb5 | ||
|
|
d9b8ea625a | ||
|
|
2323e22fef | ||
|
|
b5f8f01301 | ||
|
|
e964ff460e | ||
|
|
21d8d9c3bc | ||
|
|
169cf88306 | ||
|
|
059435f4cb | ||
|
|
4d4d4cdeb1 | ||
|
|
d42e7a033c | ||
|
|
0986c65551 | ||
|
|
694f864d36 | ||
|
|
512854ab9f | ||
|
|
b298496911 | ||
|
|
b6367e2645 | ||
|
|
b0fa4bf5d0 | ||
|
|
cb3dbe4ca4 |
No files matched your search
@@ -34,7 +34,11 @@ jobs:
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$releaseVersion = $env:RELEASE_REF -replace '^v', ''
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm run prepare:sdk
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
@@ -130,7 +134,9 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
release_version="${RELEASE_REF#v}"
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
current_version="$(node -p "require('./package.json').version")"
|
||||
if [ "$current_version" != "$release_version" ]; then
|
||||
|
||||
@@ -22,7 +22,9 @@ jobs:
|
||||
web/package-lock.json
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
npm ci --no-audit --no-fund
|
||||
npm ci --ignore-scripts --no-audit --no-fund
|
||||
npm run prepare:sdk
|
||||
npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
npm --prefix web ci --no-audit --no-fund
|
||||
- name: Test and build
|
||||
run: |
|
||||
|
||||
@@ -1,5 +1,31 @@
|
||||
# Changelog
|
||||
|
||||
## [0.1.6] — 2026-09-04
|
||||
|
||||
### 中文
|
||||
|
||||
- 新增保持身份并发连接提醒,避免同一浏览器复用身份造成连接卡住。
|
||||
- 新增桌面端伴奏共享功能。
|
||||
- 新增网站 favicon,并更新仓库 README 主视觉。
|
||||
|
||||
### English
|
||||
|
||||
- Added a warning for concurrent remembered-identity connections in the same browser.
|
||||
- Added desktop accompaniment sharing.
|
||||
- Added a site favicon and refreshed the repository README branding.
|
||||
|
||||
## [0.1.5] — 2026-09-04
|
||||
|
||||
### 中文
|
||||
|
||||
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
|
||||
- 修复浏览器身份保存与退出后的保持逻辑。
|
||||
|
||||
### English
|
||||
|
||||
- Fixed and refined the theme toggle so the first click switches themes, with sun/moon icons.
|
||||
- Fixed browser identity persistence across exit and return.
|
||||
|
||||
All notable changes to WebSpeak are documented here. Versions follow SemVer.
|
||||
|
||||
## [0.1.4] — 2026-09-03
|
||||
|
||||
+5
-2
@@ -2,12 +2,15 @@ FROM node:22-bookworm-slim AS build
|
||||
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends git python3 make g++ \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates git python3 make g++ \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
COPY web/package.json web/package-lock.json ./web/
|
||||
RUN npm ci
|
||||
RUN npm ci --ignore-scripts --no-audit --no-fund
|
||||
COPY scripts/prepare-sdk.mjs ./scripts/prepare-sdk.mjs
|
||||
RUN npm run prepare:sdk
|
||||
RUN npm rebuild @discordjs/opus --foreground-scripts --no-audit --no-fund
|
||||
RUN npm --prefix web ci
|
||||
|
||||
COPY . .
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
# WebSpeak
|
||||
|
||||
<p>
|
||||
<img src="./仓库图标.png" alt="WebSpeak" width="220">
|
||||
</p>
|
||||
|
||||
**让 TeamSpeak 真正进入浏览器。**
|
||||
|
||||
自托管的 TeamSpeak 3 / TeamSpeak 6 网页客户端。打开网页即可加入语音、查看频道、发送消息,无需安装桌面客户端。
|
||||
@@ -9,7 +13,7 @@
|
||||
**在线体验:[webspeak.example.invalid](https://webspeak.example.invalid)**
|
||||
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.4)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6)
|
||||
[](LICENSE)
|
||||
[](https://www.teamspeak.com/)
|
||||
|
||||
@@ -129,6 +133,17 @@ sudo ufw allow 40000:40099/udp
|
||||
|
||||
完整记录见 [`CHANGELOG.md`](CHANGELOG.md)。
|
||||
|
||||
#### 2026-09-04 · v0.1.6
|
||||
|
||||
- 新增保持身份并发连接提醒。
|
||||
- 新增桌面端伴奏共享功能。
|
||||
- 新增网站 favicon,并更新仓库 README 主视觉。
|
||||
|
||||
#### 2026-09-04 · v0.1.5
|
||||
|
||||
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
|
||||
- 修复浏览器身份保存与退出后的保持逻辑。
|
||||
|
||||
#### 2026-09-03 · v0.1.4
|
||||
|
||||
- 修复 WebRTC 语音收发与发言状态同步。
|
||||
@@ -287,6 +302,17 @@ The admin console can:
|
||||
|
||||
See [`CHANGELOG.md`](CHANGELOG.md) for the complete release history.
|
||||
|
||||
#### 2026-09-04 · v0.1.6
|
||||
|
||||
- Added a warning for concurrent remembered-identity connections.
|
||||
- Added desktop accompaniment sharing.
|
||||
- Added a site favicon and refreshed the repository README branding.
|
||||
|
||||
#### 2026-09-04 · v0.1.5
|
||||
|
||||
- Fixed and refined the theme toggle so the first click switches themes, with sun/moon icons.
|
||||
- Fixed browser identity persistence across exit and return.
|
||||
|
||||
#### 2026-09-03 · v0.1.4
|
||||
|
||||
- Fixed WebRTC voice transport and speaking-state synchronization.
|
||||
|
||||
Generated
+4
-4
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.6",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#4e9edf7",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
@@ -63,7 +63,7 @@
|
||||
},
|
||||
"node_modules/@echosixhiya/teamspeak-client": {
|
||||
"version": "0.2.4",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6cd83c0fd4f6e00fc9c1ff4ec79dcbfd55",
|
||||
"resolved": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#4e9edf7198418d8a0a0eff97e05aa2b3369c2fe0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1"
|
||||
|
||||
+4
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.4",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
@@ -14,11 +14,12 @@
|
||||
"test": "tsx --test \"test/**/*.test.ts\"",
|
||||
"start": "node dist/index.js",
|
||||
"web:dev": "cd web && npx vite --host",
|
||||
"web:build": "cd web && npx vite build"
|
||||
"web:build": "cd web && npx vite build",
|
||||
"prepare:sdk": "node scripts/prepare-sdk.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#f38dee6",
|
||||
"@echosixhiya/teamspeak-client": "git+https://github.com/EchoSixHIYA/teamspeak-js.git#4e9edf7",
|
||||
"express": "^5.2.1",
|
||||
"pino": "^10.3.1",
|
||||
"werift": "0.24.4",
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { cpSync, existsSync, mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import process from "node:process";
|
||||
|
||||
const root = process.cwd();
|
||||
const sdkPackage = "@echosixhiya/teamspeak-client";
|
||||
const packageJson = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
||||
const dependency = packageJson.dependencies?.[sdkPackage];
|
||||
const match = typeof dependency === "string" ? /^git\+(.+?)#(.+)$/.exec(dependency) : null;
|
||||
|
||||
if (!match) {
|
||||
throw new Error(`${sdkPackage} must be pinned to a Git repository commit`);
|
||||
}
|
||||
|
||||
const [, repository, commit] = match;
|
||||
const temporaryRoot = mkdtempSync(join(tmpdir(), "webspeak-sdk-build-"));
|
||||
const destination = join(root, "node_modules", "@echosixhiya", "teamspeak-client", "dist");
|
||||
|
||||
try {
|
||||
execFileSync("git", ["clone", "--no-checkout", repository, temporaryRoot], { stdio: "inherit" });
|
||||
execFileSync("git", ["checkout", "--detach", commit], { cwd: temporaryRoot, stdio: "inherit" });
|
||||
const npmOptions = { cwd: temporaryRoot, stdio: "inherit" };
|
||||
const runNpm = (args) => {
|
||||
if (process.platform === "win32") {
|
||||
execFileSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `npm.cmd ${args.join(" ")}`], npmOptions);
|
||||
} else {
|
||||
execFileSync("npm", args, npmOptions);
|
||||
}
|
||||
};
|
||||
runNpm(["install", "--ignore-scripts", "--no-audit", "--no-fund"]);
|
||||
runNpm(["run", "build"]);
|
||||
|
||||
const source = join(temporaryRoot, "dist");
|
||||
if (!existsSync(join(source, "index.mjs"))) {
|
||||
throw new Error(`SDK build did not produce ${join(source, "index.mjs")}`);
|
||||
}
|
||||
|
||||
mkdirSync(dirname(destination), { recursive: true });
|
||||
mkdirSync(destination, { recursive: true });
|
||||
for (const entry of readdirSync(source)) {
|
||||
cpSync(join(source, entry), join(destination, entry), { recursive: true, force: true });
|
||||
}
|
||||
console.log(`Prepared ${sdkPackage} from ${commit}`);
|
||||
} finally {
|
||||
rmSync(temporaryRoot, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Prevents one persisted TeamSpeak identity from being used by two live
|
||||
* browser sessions at the same target at the same time.
|
||||
*/
|
||||
export class IdentityLeaseStore {
|
||||
private readonly owners = new Map<string, string>();
|
||||
|
||||
acquire(key: string, owner: string): boolean {
|
||||
const currentOwner = this.owners.get(key);
|
||||
if (currentOwner && currentOwner !== owner) return false;
|
||||
this.owners.set(key, owner);
|
||||
return true;
|
||||
}
|
||||
|
||||
release(key: string, owner: string): void {
|
||||
if (this.owners.get(key) === owner) this.owners.delete(key);
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,13 @@ import { DirectorySynchronizer } from "./directory-sync.js";
|
||||
import { TSClient, type TSDirectorySnapshot, type TSVoiceData } from "./ts-client.js";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import { normalizeTeamSpeakError } from "../errors.js";
|
||||
import { formatTeamSpeakTarget, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js";
|
||||
import { IdentityLeaseStore } from "./identity-lease.js";
|
||||
import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js";
|
||||
import { parseClientCommand, type ClientCommand } from "./voice-protocol.js";
|
||||
import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.js";
|
||||
import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcSessionDescription } from "./webrtc-audio.js";
|
||||
import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcAudioStats, type WebRtcSessionDescription } from "./webrtc-audio.js";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { OpusEncoder } = require("@discordjs/opus") as {
|
||||
@@ -72,6 +73,24 @@ export interface AudioFlowStats {
|
||||
egressSentMaxGapMs: number;
|
||||
egressPeakBufferedBytes: number;
|
||||
egressFramesByClient: Record<string, number>;
|
||||
webrtcIngressRtpFrames: number;
|
||||
webrtcIngressRtpFirstAt: number | null;
|
||||
webrtcIngressRtpLastAt: number | null;
|
||||
webrtcIngressRtpMaxGapMs: number;
|
||||
webrtcEgressRtpFrames: number;
|
||||
webrtcEgressRtpFirstAt: number | null;
|
||||
webrtcEgressRtpLastAt: number | null;
|
||||
webrtcEgressRtpMaxGapMs: number;
|
||||
webrtcQueuePeakFrames: number;
|
||||
webrtcQueueDroppedFrames: number;
|
||||
webrtcQueueUnderrunTicks: number;
|
||||
webrtcPacerLateTicks: number;
|
||||
webrtcQueueCurrentFrames: number;
|
||||
webrtcIngressQuietFrames: number;
|
||||
webrtcIngressDecodeErrors: number;
|
||||
webrtcDownlinkDecodedFrames: number;
|
||||
webrtcDownlinkDecodeErrors: number;
|
||||
webrtcDownlinkShortFrames: number;
|
||||
}
|
||||
|
||||
interface ChannelMember {
|
||||
@@ -100,6 +119,7 @@ interface WebClientEntry {
|
||||
nickname: string;
|
||||
rememberIdentity: boolean;
|
||||
target: TeamSpeakTarget;
|
||||
identityLeaseKey?: string;
|
||||
webrtcPublicHost?: string;
|
||||
channelTree: unknown[];
|
||||
members: Map<number, ChannelMember>;
|
||||
@@ -116,6 +136,7 @@ interface WebClientEntry {
|
||||
export class VoiceBridge {
|
||||
private readonly sessionManager = new SessionManager();
|
||||
private readonly entries = new Map<string, WebClientEntry>();
|
||||
private readonly identityLeases = new IdentityLeaseStore();
|
||||
private wss: WebSocketServer | null = null;
|
||||
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private logger: LoggerType;
|
||||
@@ -160,11 +181,22 @@ export class VoiceBridge {
|
||||
return;
|
||||
}
|
||||
|
||||
const identityLeaseKey = identity
|
||||
? `${teamSpeakTargetKey(target)}:${identity.toString()}`
|
||||
: "";
|
||||
if (identityLeaseKey && !this.identityLeases.acquire(identityLeaseKey, entryId)) {
|
||||
this.logger.warn({ entryId, nickname, target: formatTeamSpeakTarget(target) }, "TeamSpeak identity already in use");
|
||||
void this.sessionManager.teardown(entryId, "teamSpeak-connect-failed");
|
||||
ws.close(4005, "IDENTITY_IN_USE");
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.info({ entryId, nickname, channel: channelName, target: formatTeamSpeakTarget(target) }, "WebClient connecting");
|
||||
let tsClient: TSClient;
|
||||
try {
|
||||
tsClient = new TSClient({ target, nickname, serverPassword, defaultChannel: channelName, identity }, this.logger);
|
||||
} catch (error: unknown) {
|
||||
if (identityLeaseKey) this.identityLeases.release(identityLeaseKey, entryId);
|
||||
this.logger.error({ err: error, entryId }, "Could not create TeamSpeak client");
|
||||
void this.sessionManager.teardown(entryId, "teamSpeak-connect-failed");
|
||||
ws.close(4003, "TeamSpeak client unavailable");
|
||||
@@ -178,6 +210,7 @@ export class VoiceBridge {
|
||||
nickname,
|
||||
rememberIdentity: connection.rememberIdentity === true,
|
||||
target,
|
||||
...(identityLeaseKey ? { identityLeaseKey } : {}),
|
||||
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
|
||||
channelTree: [],
|
||||
members: new Map(),
|
||||
@@ -416,6 +449,7 @@ export class VoiceBridge {
|
||||
tsClient.on("clientLeave", (info) => {
|
||||
const wasKnown = entry!.members.has(info.id);
|
||||
const leavingMember = entry!.members.get(info.id);
|
||||
entry!.webrtc?.setMemberVolume(info.id, 1);
|
||||
directory.applyClientLeave(info.id);
|
||||
refreshDirectory();
|
||||
if (tsReady && initialStateSent && wasKnown) {
|
||||
@@ -567,7 +601,11 @@ export class VoiceBridge {
|
||||
if (isWebRtcStopMessage(rawMessage)) {
|
||||
const webRtc = entry!.webrtc;
|
||||
entry!.webrtc = null;
|
||||
if (webRtc) void webRtc.close();
|
||||
if (webRtc) {
|
||||
void webRtc.close()
|
||||
.then(() => Object.assign(entry!.audio, webRtc.getStats()))
|
||||
.catch(() => undefined);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const command = parseClientCommand(rawMessage);
|
||||
@@ -658,7 +696,7 @@ export class VoiceBridge {
|
||||
tsClientId,
|
||||
channelId,
|
||||
memberCount: entry.members.size,
|
||||
audio: { ...entry.audio },
|
||||
audio: snapshotAudioStats(entry),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -684,6 +722,7 @@ export class VoiceBridge {
|
||||
entry.webrtc = null;
|
||||
if (webRtc) {
|
||||
try { await webRtc.close(); } catch { /* peer teardown is idempotent */ }
|
||||
Object.assign(entry.audio, webRtc.getStats());
|
||||
}
|
||||
entry.whisperTargetIds.clear();
|
||||
entry.whisperActive = false;
|
||||
@@ -696,6 +735,7 @@ export class VoiceBridge {
|
||||
if (reason === "heartbeat-timeout" || reason === "gateway-shutdown") entry.ws.terminate();
|
||||
else entry.ws.close(reason === "protocol-error" ? 1008 : 1000, reason);
|
||||
}
|
||||
if (entry.identityLeaseKey) this.identityLeases.release(entry.identityLeaseKey, entry.id);
|
||||
this.logger.info({ entryId: entry.id, reason, audio: { ...entry.audio } }, "Client session torn down");
|
||||
}
|
||||
|
||||
@@ -732,7 +772,9 @@ export class VoiceBridge {
|
||||
sendJson: (message: Record<string, unknown>) => void,
|
||||
): Promise<void> {
|
||||
if (entry.webrtc) {
|
||||
try { await entry.webrtc.close(); } catch { /* replace a retried offer */ }
|
||||
const previousWebRtc = entry.webrtc;
|
||||
try { await previousWebRtc.close(); } catch { /* replace a retried offer */ }
|
||||
Object.assign(entry.audio, previousWebRtc.getStats());
|
||||
entry.webrtc = null;
|
||||
}
|
||||
const config = this.getWebRtcOptions();
|
||||
@@ -743,16 +785,23 @@ export class VoiceBridge {
|
||||
udpPortRange: config.udpPortRange,
|
||||
logger: this.logger,
|
||||
microphoneMuted: offer.muted === true,
|
||||
onVoiceFrame: (data) => {
|
||||
accompanimentActive: offer.accompanimentActive === true,
|
||||
onVoiceFrame: (data, codec) => {
|
||||
const now = Date.now();
|
||||
if (entry.audio.ingressLastAt !== null) entry.audio.ingressMaxGapMs = Math.max(entry.audio.ingressMaxGapMs, now - entry.audio.ingressLastAt);
|
||||
entry.audio.ingressFirstAt ??= now;
|
||||
entry.audio.ingressLastAt = now;
|
||||
entry.audio.ingressFrames++;
|
||||
try {
|
||||
if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], 4);
|
||||
else entry.tsClient.sendVoice(data, 4);
|
||||
if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], codec);
|
||||
else entry.tsClient.sendVoice(data, codec);
|
||||
const sentAt = Date.now();
|
||||
if (entry.audio.tsSendLastAt !== null) entry.audio.tsSendMaxGapMs = Math.max(entry.audio.tsSendMaxGapMs, sentAt - entry.audio.tsSendLastAt);
|
||||
entry.audio.tsSendFirstAt ??= sentAt;
|
||||
entry.audio.tsSendLastAt = sentAt;
|
||||
entry.audio.tsSendFrames++;
|
||||
} catch {
|
||||
entry.audio.tsSendErrors++;
|
||||
// A packet arriving while the TeamSpeak session is being replaced
|
||||
// is discarded; the WebRTC peer remains independently closable.
|
||||
}
|
||||
@@ -872,6 +921,11 @@ async function handleCommand(
|
||||
sendJson({ type: "whisperTargets", targetIds: [...entry.whisperTargetIds], active: entry.whisperActive });
|
||||
} else if (command.type === "setMicrophoneMuted") {
|
||||
entry.webrtc?.setMicrophoneMuted(command.payload.muted as boolean);
|
||||
} else if (command.type === "setAccompanimentActive") {
|
||||
entry.webrtc?.setAccompanimentActive(command.payload.active as boolean);
|
||||
} else if (command.type === "setMemberVolume") {
|
||||
const clientId = command.payload.clientId as number;
|
||||
entry.webrtc?.setMemberVolume(clientId, command.payload.volume as number);
|
||||
}
|
||||
if (command.requestId) sendJson({ type: "commandCompleted", requestId: command.requestId });
|
||||
} catch (error: unknown) {
|
||||
@@ -902,7 +956,13 @@ function parseWebRtcOffer(raw: string): WebRtcSessionDescription | null {
|
||||
const description = value.payload.sdp;
|
||||
if (description.type !== "offer" || typeof description.sdp !== "string" || description.sdp.length > 256 * 1024) return null;
|
||||
if (value.payload.muted !== undefined && typeof value.payload.muted !== "boolean") return null;
|
||||
return { type: "offer", sdp: description.sdp, muted: value.payload.muted === true };
|
||||
if (value.payload.accompanimentActive !== undefined && typeof value.payload.accompanimentActive !== "boolean") return null;
|
||||
return {
|
||||
type: "offer",
|
||||
sdp: description.sdp,
|
||||
muted: value.payload.muted === true,
|
||||
accompanimentActive: value.payload.accompanimentActive === true,
|
||||
};
|
||||
}
|
||||
|
||||
function isWebRtcStopMessage(raw: string): boolean {
|
||||
@@ -949,9 +1009,34 @@ function createAudioFlowStats(): AudioFlowStats {
|
||||
egressSentMaxGapMs: 0,
|
||||
egressPeakBufferedBytes: 0,
|
||||
egressFramesByClient: {},
|
||||
webrtcIngressRtpFrames: 0,
|
||||
webrtcIngressRtpFirstAt: null,
|
||||
webrtcIngressRtpLastAt: null,
|
||||
webrtcIngressRtpMaxGapMs: 0,
|
||||
webrtcEgressRtpFrames: 0,
|
||||
webrtcEgressRtpFirstAt: null,
|
||||
webrtcEgressRtpLastAt: null,
|
||||
webrtcEgressRtpMaxGapMs: 0,
|
||||
webrtcQueuePeakFrames: 0,
|
||||
webrtcQueueDroppedFrames: 0,
|
||||
webrtcQueueUnderrunTicks: 0,
|
||||
webrtcPacerLateTicks: 0,
|
||||
webrtcQueueCurrentFrames: 0,
|
||||
webrtcIngressQuietFrames: 0,
|
||||
webrtcIngressDecodeErrors: 0,
|
||||
webrtcDownlinkDecodedFrames: 0,
|
||||
webrtcDownlinkDecodeErrors: 0,
|
||||
webrtcDownlinkShortFrames: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function snapshotAudioStats(entry: WebClientEntry): AudioFlowStats {
|
||||
const stats = { ...entry.audio };
|
||||
const webRtcStats: WebRtcAudioStats | undefined = entry.webrtc?.getStats();
|
||||
if (webRtcStats) Object.assign(stats, webRtcStats);
|
||||
return stats;
|
||||
}
|
||||
|
||||
function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] {
|
||||
return snapshot.channels.map((channel) => ({
|
||||
id: String(channel.id),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export interface ClientCommand {
|
||||
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted";
|
||||
type: "switchChannel" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume";
|
||||
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", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted"]);
|
||||
const supportedTypes = new Set(["switchChannel", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume"]);
|
||||
if (!supportedTypes.has(value.type)) {
|
||||
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
|
||||
}
|
||||
@@ -59,6 +59,12 @@ export function parseClientCommand(raw: string): ClientCommandResult {
|
||||
if (value.type === "setMicrophoneMuted" && typeof value.payload.muted !== "boolean") {
|
||||
return { error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" } };
|
||||
}
|
||||
if (value.type === "setAccompanimentActive" && typeof value.payload.active !== "boolean") {
|
||||
return { error: { code: "INVALID_ACCOMPANIMENT_STATE", message: "伴奏状态无效" } };
|
||||
}
|
||||
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: "成员音量无效" } };
|
||||
}
|
||||
return {
|
||||
type: value.type as ClientCommand["type"],
|
||||
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
|
||||
|
||||
+278
-61
@@ -26,10 +26,17 @@ const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * 2;
|
||||
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
|
||||
const AUDIO_CLOCK_INTERVAL_MS = 20;
|
||||
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
|
||||
const MAX_MIXER_QUEUE_FRAMES = 4;
|
||||
const MAX_MIXER_PACER_LAG_MS = AUDIO_CLOCK_INTERVAL_MS * 2;
|
||||
const MAX_MIXER_FRAME_AGE_MS = MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
|
||||
const MIXER_UNDERRUN_WINDOW_MS = 200;
|
||||
// TeamSpeak and browsers can emit valid Opus comfort-noise/silence packets
|
||||
// while a client is muted. Do not turn those packets into a false "speaking"
|
||||
// indicator or forward them to TeamSpeak as if they were voice.
|
||||
const MIN_SPEAKER_RMS = 160;
|
||||
// Keep this below the speaking threshold so quiet but valid accompaniment is
|
||||
// forwarded while comfort-noise packets remain filtered.
|
||||
const MIN_FORWARD_RMS = 24;
|
||||
|
||||
// WebRTC is served by the WebSpeak process itself. The default range is also
|
||||
// published by the bundled Docker Compose file; advanced administrators can
|
||||
@@ -43,6 +50,7 @@ export interface WebRtcSessionDescription {
|
||||
type: "offer" | "answer";
|
||||
sdp: string;
|
||||
muted?: boolean;
|
||||
accompanimentActive?: boolean;
|
||||
}
|
||||
|
||||
export interface WebRtcAudioSessionOptions {
|
||||
@@ -51,45 +59,105 @@ export interface WebRtcAudioSessionOptions {
|
||||
udpPortRange?: [number, number];
|
||||
logger: LoggerType;
|
||||
microphoneMuted?: boolean;
|
||||
onVoiceFrame: (data: Buffer) => void;
|
||||
accompanimentActive?: boolean;
|
||||
onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
|
||||
onVoiceActivity: (clientIds: number[]) => void;
|
||||
}
|
||||
|
||||
export interface WebRtcAudioStats {
|
||||
webrtcIngressRtpFrames: number;
|
||||
webrtcIngressRtpFirstAt: number | null;
|
||||
webrtcIngressRtpLastAt: number | null;
|
||||
webrtcIngressRtpMaxGapMs: number;
|
||||
webrtcEgressRtpFrames: number;
|
||||
webrtcEgressRtpFirstAt: number | null;
|
||||
webrtcEgressRtpLastAt: number | null;
|
||||
webrtcEgressRtpMaxGapMs: number;
|
||||
webrtcQueuePeakFrames: number;
|
||||
webrtcQueueDroppedFrames: number;
|
||||
webrtcQueueUnderrunTicks: number;
|
||||
webrtcPacerLateTicks: number;
|
||||
webrtcQueueCurrentFrames: number;
|
||||
webrtcIngressQuietFrames: number;
|
||||
webrtcIngressDecodeErrors: number;
|
||||
webrtcDownlinkDecodedFrames: number;
|
||||
webrtcDownlinkDecodeErrors: number;
|
||||
webrtcDownlinkShortFrames: number;
|
||||
}
|
||||
|
||||
interface PendingAudioFrame {
|
||||
pcm: Buffer;
|
||||
receivedAt: number;
|
||||
/** Preserve a native 20 ms Opus frame when no mix is required. */
|
||||
opus?: Buffer;
|
||||
}
|
||||
|
||||
interface SelectedAudioFrame extends PendingAudioFrame {
|
||||
clientId: number;
|
||||
volume: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* One low-latency WebRTC audio session for one browser connection.
|
||||
*
|
||||
* TeamSpeak provides one Opus payload per speaker. WebRTC has one negotiated
|
||||
* audio track in this first transport, so this class mixes only the newest
|
||||
* 20 ms frame from each active speaker and packetizes the result as RTP. The
|
||||
* map is deliberately bounded to one frame per speaker; an old frame is
|
||||
* replaced instead of becoming a playback queue.
|
||||
* audio track in this first transport, so this class mixes one 20 ms frame
|
||||
* from each active speaker and packetizes the result as RTP. Each speaker has
|
||||
* a very small bounded queue so bursts from the TeamSpeak adapter can be
|
||||
* smoothed without turning into an ever-growing playback delay.
|
||||
*/
|
||||
export class WebRtcAudioSession {
|
||||
readonly peer: RTCPeerConnection;
|
||||
private readonly logger: LoggerType;
|
||||
private readonly onVoiceFrame: (data: Buffer) => void;
|
||||
private readonly onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
|
||||
private readonly onVoiceActivity: (clientIds: number[]) => void;
|
||||
private readonly outgoingTrack: MediaStreamTrack;
|
||||
private ingressDecoder: { decode(data: Buffer): Buffer } | null = null;
|
||||
private readonly decoderByClient = new Map<number, { decode(data: Buffer): Buffer }>();
|
||||
private readonly pendingFrames = new Map<number, Buffer>();
|
||||
private readonly partialPcmByClient = new Map<number, Buffer>();
|
||||
private readonly pendingFrames = new Map<number, PendingAudioFrame[]>();
|
||||
private readonly memberVolumes = new Map<number, number>();
|
||||
private readonly activeSpeakerIds = new Set<number>();
|
||||
private readonly opusPayloadTypes = new Set<number>();
|
||||
private readonly audioTimer: ReturnType<typeof setInterval>;
|
||||
private audioTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private readonly activityTimer: ReturnType<typeof setInterval>;
|
||||
private encoder: { encode(data: Buffer): Buffer } | null;
|
||||
private microphoneMuted: boolean;
|
||||
private sequenceNumber = randomInt(0, 65_536);
|
||||
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
|
||||
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
|
||||
private outgoingPayloadType = DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE;
|
||||
private closed = false;
|
||||
private nextAudioDeadline = 0;
|
||||
private lastIngressRtpAt: number | null = null;
|
||||
private lastEgressRtpAt: number | null = null;
|
||||
private lastQueueEnqueuedAt: number | null = null;
|
||||
private accompanimentActive: boolean;
|
||||
private readonly stats: WebRtcAudioStats = {
|
||||
webrtcIngressRtpFrames: 0,
|
||||
webrtcIngressRtpFirstAt: null,
|
||||
webrtcIngressRtpLastAt: null,
|
||||
webrtcIngressRtpMaxGapMs: 0,
|
||||
webrtcEgressRtpFrames: 0,
|
||||
webrtcEgressRtpFirstAt: null,
|
||||
webrtcEgressRtpLastAt: null,
|
||||
webrtcEgressRtpMaxGapMs: 0,
|
||||
webrtcQueuePeakFrames: 0,
|
||||
webrtcQueueDroppedFrames: 0,
|
||||
webrtcQueueUnderrunTicks: 0,
|
||||
webrtcPacerLateTicks: 0,
|
||||
webrtcQueueCurrentFrames: 0,
|
||||
webrtcIngressQuietFrames: 0,
|
||||
webrtcIngressDecodeErrors: 0,
|
||||
webrtcDownlinkDecodedFrames: 0,
|
||||
webrtcDownlinkDecodeErrors: 0,
|
||||
webrtcDownlinkShortFrames: 0,
|
||||
};
|
||||
|
||||
constructor(options: WebRtcAudioSessionOptions) {
|
||||
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
|
||||
this.onVoiceFrame = options.onVoiceFrame;
|
||||
this.onVoiceActivity = options.onVoiceActivity;
|
||||
this.microphoneMuted = options.microphoneMuted === true;
|
||||
this.accompanimentActive = options.accompanimentActive === true;
|
||||
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
|
||||
|
||||
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
|
||||
@@ -106,14 +174,27 @@ export class WebRtcAudioSession {
|
||||
const audio = this.peer.addTransceiver("audio", { direction: "sendrecv" });
|
||||
audio.onTrack.subscribe((track) => {
|
||||
track.onReceiveRtp.subscribe((rtp) => {
|
||||
if (this.closed || this.microphoneMuted || !this.opusPayloadTypes.has(rtp.header.payloadType)) return;
|
||||
if (this.closed) return;
|
||||
const receivedAt = performance.now();
|
||||
if (this.lastIngressRtpAt !== null) this.stats.webrtcIngressRtpMaxGapMs = Math.max(this.stats.webrtcIngressRtpMaxGapMs, Math.round(receivedAt - this.lastIngressRtpAt));
|
||||
this.lastIngressRtpAt = receivedAt;
|
||||
this.stats.webrtcIngressRtpFirstAt ??= Date.now();
|
||||
this.stats.webrtcIngressRtpLastAt = Date.now();
|
||||
this.stats.webrtcIngressRtpFrames++;
|
||||
if (!this.opusPayloadTypes.has(rtp.header.payloadType)) return;
|
||||
const payload = Buffer.from(rtp.payload);
|
||||
// A disabled browser MediaStreamTrack normally still produces RTP
|
||||
// comfort-noise packets. TeamSpeak treats any received voice packet
|
||||
// as activity, so enforce mute/VAD at this gateway boundary instead
|
||||
// of relying on the browser's local speaking indicator.
|
||||
if (!this.hasVoiceEnergy(payload)) return;
|
||||
this.onVoiceFrame(payload);
|
||||
// The track is a browser-side mix of microphone and accompaniment.
|
||||
// Decode it once to reject malformed RTP. A normal microphone still
|
||||
// uses the low-level comfort-noise gate, while accompaniment must not
|
||||
// be treated as speech: quiet music frames are valid audio and are
|
||||
// forwarded with TeamSpeak's music codec marker.
|
||||
const rms = this.getIngressRms(payload);
|
||||
if (rms === null) return;
|
||||
if (!this.accompanimentActive && rms < MIN_FORWARD_RMS) {
|
||||
this.stats.webrtcIngressQuietFrames++;
|
||||
return;
|
||||
}
|
||||
this.onVoiceFrame(payload, this.accompanimentActive ? 5 : 4);
|
||||
});
|
||||
void audio.sender.replaceTrack(this.outgoingTrack).catch((error: unknown) => {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not attach WebRTC output track");
|
||||
@@ -139,8 +220,8 @@ export class WebRtcAudioSession {
|
||||
throw new Error("WebRTC Opus codec is unavailable");
|
||||
}
|
||||
|
||||
this.audioTimer = setInterval(() => this.flushAudio(), AUDIO_CLOCK_INTERVAL_MS);
|
||||
this.audioTimer.unref?.();
|
||||
this.nextAudioDeadline = performance.now();
|
||||
this.scheduleAudioTick();
|
||||
this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS);
|
||||
this.activityTimer.unref?.();
|
||||
this.peer.onconnectionstatechange = () => {
|
||||
@@ -148,6 +229,10 @@ export class WebRtcAudioSession {
|
||||
};
|
||||
}
|
||||
|
||||
getStats(): WebRtcAudioStats {
|
||||
return { ...this.stats, webrtcQueueCurrentFrames: this.getQueueFrameCount() };
|
||||
}
|
||||
|
||||
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
|
||||
if (this.closed) throw new Error("WebRTC session is closed");
|
||||
this.setOpusPayloadTypes(offer.sdp);
|
||||
@@ -163,7 +248,7 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
|
||||
pushTeamSpeakVoice(data: TSVoiceData): void {
|
||||
if (this.closed || data.codec !== 4) return;
|
||||
if (this.closed || (data.codec !== 4 && data.codec !== 5)) return;
|
||||
let decoder = this.decoderByClient.get(data.clientId);
|
||||
if (!decoder) {
|
||||
try {
|
||||
@@ -178,19 +263,53 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
try {
|
||||
const pcm = decoder.decode(data.data);
|
||||
// Only advertise speaking after a valid TeamSpeak Opus frame has been
|
||||
// decoded. Otherwise the UI can show activity while the mixer has no
|
||||
// audio to send, which is especially confusing on the WebRTC path.
|
||||
if (pcm.length < AUDIO_FRAME_BYTES) return;
|
||||
let sum = 0;
|
||||
for (let index = 0; index + 1 < AUDIO_FRAME_BYTES; index += 2) {
|
||||
const sample = pcm.readInt16LE(index);
|
||||
sum += sample * sample;
|
||||
this.stats.webrtcDownlinkDecodedFrames++;
|
||||
if (pcm.length < 2) {
|
||||
this.stats.webrtcDownlinkShortFrames++;
|
||||
return;
|
||||
}
|
||||
// TeamSpeak may deliver 10/20/40/60 ms Opus frames. Keep a partial
|
||||
// decoded frame per speaker and split every decoded buffer into the
|
||||
// fixed 20 ms cadence used by the WebRTC mixer instead of discarding
|
||||
// anything after the first 20 ms.
|
||||
const pendingPcm = this.partialPcmByClient.get(data.clientId);
|
||||
const combined = pendingPcm ? Buffer.concat([pendingPcm, pcm]) : pcm;
|
||||
const rms = this.calculateRms(pcm);
|
||||
// A muted TeamSpeak client can still produce comfort-noise packets.
|
||||
// Do not let those packets turn a single accompaniment stream into a
|
||||
// synthetic multi-source mix. Music packets use codec 5 and must be
|
||||
// retained even when their instantaneous RMS is low.
|
||||
if (data.codec !== 5 && rms < MIN_SPEAKER_RMS) return;
|
||||
if (rms >= MIN_SPEAKER_RMS) this.activeSpeakerIds.add(data.clientId);
|
||||
const canForwardOpus = !pendingPcm && pcm.length === AUDIO_FRAME_BYTES;
|
||||
let offset = 0;
|
||||
let enqueued = false;
|
||||
let queue = this.pendingFrames.get(data.clientId);
|
||||
while (offset + AUDIO_FRAME_BYTES <= combined.length) {
|
||||
if (!queue) {
|
||||
queue = [];
|
||||
this.pendingFrames.set(data.clientId, queue);
|
||||
}
|
||||
if (queue.length >= MAX_MIXER_QUEUE_FRAMES) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
queue.push({
|
||||
pcm: Buffer.from(combined.subarray(offset, offset + AUDIO_FRAME_BYTES)),
|
||||
receivedAt: performance.now(),
|
||||
...(canForwardOpus && offset === 0 ? { opus: Buffer.from(data.data) } : {}),
|
||||
});
|
||||
enqueued = true;
|
||||
offset += AUDIO_FRAME_BYTES;
|
||||
}
|
||||
if (offset < combined.length) this.partialPcmByClient.set(data.clientId, Buffer.from(combined.subarray(offset)));
|
||||
else this.partialPcmByClient.delete(data.clientId);
|
||||
if (enqueued) {
|
||||
this.lastQueueEnqueuedAt = performance.now();
|
||||
this.stats.webrtcQueuePeakFrames = Math.max(this.stats.webrtcQueuePeakFrames, this.getQueueFrameCount());
|
||||
}
|
||||
if (Math.sqrt(sum / AUDIO_FRAME_SAMPLES) < MIN_SPEAKER_RMS) return;
|
||||
this.pendingFrames.set(data.clientId, pcm.subarray(0, AUDIO_FRAME_BYTES));
|
||||
this.activeSpeakerIds.add(data.clientId);
|
||||
} catch {
|
||||
this.stats.webrtcDownlinkDecodeErrors++;
|
||||
// A malformed or codec-transition packet is discarded without touching
|
||||
// the peer connection. The next valid Opus frame can recover the stream.
|
||||
}
|
||||
@@ -199,9 +318,12 @@ export class WebRtcAudioSession {
|
||||
async close(): Promise<void> {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
clearInterval(this.audioTimer);
|
||||
if (this.audioTimer) clearTimeout(this.audioTimer);
|
||||
this.audioTimer = null;
|
||||
clearInterval(this.activityTimer);
|
||||
this.pendingFrames.clear();
|
||||
this.memberVolumes.clear();
|
||||
this.partialPcmByClient.clear();
|
||||
this.activeSpeakerIds.clear();
|
||||
this.ingressDecoder = null;
|
||||
this.decoderByClient.clear();
|
||||
@@ -210,41 +332,91 @@ export class WebRtcAudioSession {
|
||||
await this.peer.close();
|
||||
}
|
||||
|
||||
private scheduleAudioTick(): void {
|
||||
if (this.closed) return;
|
||||
const delay = Math.max(0, this.nextAudioDeadline - performance.now());
|
||||
this.audioTimer = setTimeout(() => this.flushAudio(), delay);
|
||||
this.audioTimer.unref?.();
|
||||
}
|
||||
|
||||
private flushAudio(): void {
|
||||
if (this.closed || !this.encoder || !this.pendingFrames.size) return;
|
||||
if (this.closed) return;
|
||||
const now = performance.now();
|
||||
if (now > this.nextAudioDeadline + MAX_MIXER_PACER_LAG_MS) {
|
||||
this.stats.webrtcPacerLateTicks++;
|
||||
this.nextAudioDeadline = now;
|
||||
this.trimQueuesAfterLateTick();
|
||||
}
|
||||
this.nextAudioDeadline += AUDIO_CLOCK_INTERVAL_MS;
|
||||
this.audioTimer = null;
|
||||
this.mixAndSendAudio();
|
||||
this.scheduleAudioTick();
|
||||
}
|
||||
|
||||
private mixAndSendAudio(): void {
|
||||
if (!this.encoder) {
|
||||
return;
|
||||
}
|
||||
if (!this.pendingFrames.size) {
|
||||
if (this.lastQueueEnqueuedAt !== null && performance.now() - this.lastQueueEnqueuedAt <= MIXER_UNDERRUN_WINDOW_MS) {
|
||||
this.stats.webrtcQueueUnderrunTicks++;
|
||||
}
|
||||
}
|
||||
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
|
||||
let sourceCount = 0;
|
||||
for (const pcm of this.pendingFrames.values()) {
|
||||
sourceCount++;
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) mixed[index] += pcm.readInt16LE(index * 2);
|
||||
const selectedFrames: SelectedAudioFrame[] = [];
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
const frame = queue.shift();
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
if (!frame) continue;
|
||||
const volume = this.memberVolumes.get(clientId) ?? 1;
|
||||
selectedFrames.push({ ...frame, clientId, volume });
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
mixed[index] += Math.round(frame.pcm.readInt16LE(index * 2) * volume);
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedFrames.length === 1 && selectedFrames[0]?.opus && selectedFrames[0].volume === 1) {
|
||||
this.sendRtpAudio(selectedFrames[0].opus);
|
||||
return;
|
||||
}
|
||||
this.pendingFrames.clear();
|
||||
if (!sourceCount) return;
|
||||
|
||||
const pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
|
||||
const scale = 1 / Math.sqrt(sourceCount);
|
||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
||||
const sample = Math.max(-32_768, Math.min(32_767, Math.round(mixed[index]! * scale)));
|
||||
// Keep a fixed gain for the mixed path. Per-sample soft limiting changes
|
||||
// the waveform's apparent loudness as the source level changes, which
|
||||
// is especially noticeable on music. Only clip actual overflow caused
|
||||
// by simultaneous speakers; never normalize by the active speaker count.
|
||||
const sample = Math.max(-32_768, Math.min(32_767, mixed[index]!));
|
||||
pcm.writeInt16LE(sample, index * 2);
|
||||
}
|
||||
try {
|
||||
const encoded = this.encoder.encode(pcm);
|
||||
const packet = new RtpPacket(new RtpHeader({
|
||||
payloadType: this.outgoingPayloadType,
|
||||
sequenceNumber: this.sequenceNumber,
|
||||
timestamp: this.timestamp,
|
||||
ssrc: this.ssrc,
|
||||
marker: true,
|
||||
}), encoded);
|
||||
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
|
||||
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
|
||||
this.outgoingTrack.writeRtp(packet);
|
||||
this.sendRtpAudio(encoded);
|
||||
} catch {
|
||||
// A peer closing concurrently may reject a packet; teardown owns the
|
||||
// session lifecycle and no per-frame error needs to reach the logs.
|
||||
}
|
||||
}
|
||||
|
||||
private sendRtpAudio(encoded: Buffer): void {
|
||||
const packet = new RtpPacket(new RtpHeader({
|
||||
payloadType: this.outgoingPayloadType,
|
||||
sequenceNumber: this.sequenceNumber,
|
||||
timestamp: this.timestamp,
|
||||
ssrc: this.ssrc,
|
||||
marker: true,
|
||||
}), encoded);
|
||||
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
|
||||
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
|
||||
this.outgoingTrack.writeRtp(packet);
|
||||
const sentAt = performance.now();
|
||||
if (this.lastEgressRtpAt !== null) this.stats.webrtcEgressRtpMaxGapMs = Math.max(this.stats.webrtcEgressRtpMaxGapMs, Math.round(sentAt - this.lastEgressRtpAt));
|
||||
this.lastEgressRtpAt = sentAt;
|
||||
this.stats.webrtcEgressRtpFirstAt ??= Date.now();
|
||||
this.stats.webrtcEgressRtpLastAt = Date.now();
|
||||
this.stats.webrtcEgressRtpFrames++;
|
||||
}
|
||||
|
||||
private flushSpeakerActivity(): void {
|
||||
if (this.closed || !this.activeSpeakerIds.size) return;
|
||||
const ids = [...this.activeSpeakerIds];
|
||||
@@ -253,28 +425,73 @@ export class WebRtcAudioSession {
|
||||
}
|
||||
|
||||
setMicrophoneMuted(muted: boolean): void {
|
||||
this.microphoneMuted = muted;
|
||||
// The browser sends a mixed microphone/accompaniment track. The mute gain
|
||||
// is applied before RTP encoding, so a server-side mute flag must not drop
|
||||
// the whole packet and silence a still-playing accompaniment.
|
||||
void muted;
|
||||
}
|
||||
|
||||
private hasVoiceEnergy(data: Buffer): boolean {
|
||||
setAccompanimentActive(active: boolean): void {
|
||||
this.accompanimentActive = active;
|
||||
}
|
||||
|
||||
setMemberVolume(clientId: number, volume: number): void {
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535 || !Number.isFinite(volume)) return;
|
||||
const normalized = Math.max(0, Math.min(4, volume));
|
||||
if (normalized === 1) this.memberVolumes.delete(clientId);
|
||||
else this.memberVolumes.set(clientId, normalized);
|
||||
}
|
||||
|
||||
private getIngressRms(data: Buffer): number | null {
|
||||
const decoder = this.ingressDecoder;
|
||||
if (!decoder) return false;
|
||||
if (!decoder) return null;
|
||||
try {
|
||||
const pcm = decoder.decode(data);
|
||||
if (pcm.length < AUDIO_FRAME_BYTES) return false;
|
||||
let sum = 0;
|
||||
for (let index = 0; index + 1 < AUDIO_FRAME_BYTES; index += 2) {
|
||||
const sample = pcm.readInt16LE(index);
|
||||
sum += sample * sample;
|
||||
if (pcm.length < 2) {
|
||||
this.stats.webrtcIngressDecodeErrors++;
|
||||
return null;
|
||||
}
|
||||
return Math.sqrt(sum / AUDIO_FRAME_SAMPLES) >= MIN_SPEAKER_RMS;
|
||||
return this.calculateRms(pcm);
|
||||
} catch {
|
||||
// Malformed/transition packets are discarded without interrupting the
|
||||
// rest of the peer. The next valid Opus packet can recover the decoder.
|
||||
return false;
|
||||
this.stats.webrtcIngressDecodeErrors++;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private calculateRms(pcm: Buffer): number {
|
||||
let sum = 0;
|
||||
let samples = 0;
|
||||
for (let index = 0; index + 1 < pcm.length; index += 2) {
|
||||
const sample = pcm.readInt16LE(index);
|
||||
sum += sample * sample;
|
||||
samples++;
|
||||
}
|
||||
return samples ? Math.sqrt(sum / samples) : 0;
|
||||
}
|
||||
|
||||
private trimQueuesAfterLateTick(): void {
|
||||
const now = performance.now();
|
||||
for (const [clientId, queue] of this.pendingFrames) {
|
||||
while (queue.length > 1) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
if (queue[0] && now - queue[0].receivedAt > MAX_MIXER_FRAME_AGE_MS) {
|
||||
queue.shift();
|
||||
this.stats.webrtcQueueDroppedFrames++;
|
||||
}
|
||||
if (queue.length === 0) this.pendingFrames.delete(clientId);
|
||||
}
|
||||
}
|
||||
|
||||
private getQueueFrameCount(): number {
|
||||
let count = 0;
|
||||
for (const queue of this.pendingFrames.values()) count += queue.length;
|
||||
return count;
|
||||
}
|
||||
|
||||
private setOpusPayloadTypes(sdp: string): void {
|
||||
this.opusPayloadTypes.clear();
|
||||
for (const match of sdp.matchAll(/^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?/gim)) {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { IdentityLeaseStore } from "../src/server/identity-lease.js";
|
||||
|
||||
test("an identity lease rejects a second live owner and ignores a release from another owner", () => {
|
||||
const store = new IdentityLeaseStore();
|
||||
assert.equal(store.acquire("target:identity", "first"), true);
|
||||
assert.equal(store.acquire("target:identity", "second"), false);
|
||||
store.release("target:identity", "second");
|
||||
assert.equal(store.acquire("target:identity", "second"), false);
|
||||
store.release("target:identity", "first");
|
||||
assert.equal(store.acquire("target:identity", "second"), true);
|
||||
});
|
||||
@@ -83,3 +83,26 @@ test("voice protocol accepts and validates the microphone mute state", () => {
|
||||
error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol accepts and validates the accompaniment state", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAccompanimentActive", payload: { active: true } })), {
|
||||
type: "setAccompanimentActive",
|
||||
payload: { active: true },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setAccompanimentActive", payload: { active: "yes" } })), {
|
||||
error: { code: "INVALID_ACCOMPANIMENT_STATE", message: "伴奏状态无效" },
|
||||
});
|
||||
});
|
||||
|
||||
test("voice protocol accepts and validates per-member volume", () => {
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: 1.5 } })), {
|
||||
type: "setMemberVolume",
|
||||
payload: { clientId: 7, volume: 1.5 },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: 4.1 } })), {
|
||||
error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" },
|
||||
});
|
||||
assert.deepEqual(parseClientCommand(JSON.stringify({ type: "setMemberVolume", payload: { clientId: 7, volume: Number.NaN } })), {
|
||||
error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" },
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#006a64" />
|
||||
<meta name="description" content="WebSpeak — TeamSpeak browser voice workspace" />
|
||||
<link rel="icon" type="image/jpeg" href="/网站图标.jpg" />
|
||||
<title>WebSpeak · TeamSpeak Web Client</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
@@ -31,7 +31,12 @@
|
||||
</template>
|
||||
<path v-else-if="name === 'mic'" d="M12 14a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v5a3 3 0 0 0 3 3Zm-7-3a7 7 0 0 0 14 0m-7 7v3m-3 0h6" />
|
||||
<path v-else-if="name === 'mic-off'" d="m4 4 16 16M10 6v5a2 2 0 0 0 3.2 1.6M14 6V5a2 2 0 0 0-3.7-1M5 11a7 7 0 0 0 10.6 6m3.4-6a7 7 0 0 0-.5-2.5M12 18v3m-3 0h6" />
|
||||
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 0 1-1z" />
|
||||
<template v-else-if="name === 'music'">
|
||||
<path d="M9 18V5l10-2v13" />
|
||||
<circle cx="6" cy="18" r="3" />
|
||||
<circle cx="16" cy="16" r="3" />
|
||||
</template>
|
||||
<path v-else-if="name === 'headset'" d="M4 14v-2a8 8 0 0 1 16 0v2M4 14h3v5H5a1 1 0 0 1-1-1zm16 0h-3v5h2a1 1 0 0 1-1-1z" />
|
||||
<path v-else-if="name === 'volume'" d="M4 10v4h3l4 3V7l-4 3zm10.5-2.5a6 6 0 0 1 0 9m2-11a9 9 0 0 1 0 13" />
|
||||
<path v-else-if="name === 'volume-off'" d="m4 4 16 16M4 10v4h3l4 3V7l-4 3z" />
|
||||
<template v-else-if="name === 'search'">
|
||||
@@ -68,6 +73,11 @@
|
||||
<path v-else-if="name === 'door'" d="M10 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5m5 14 5-5-5-5m5 5H9" />
|
||||
<path v-else-if="name === 'waveform'" d="M3 12h2l2-6 3 12 3-9 2 6h6" />
|
||||
<path v-else-if="name === 'shield'" d="M12 21s8-3.5 8-10V5l-8-3-8 3v6c0 6.5 8 10 8 10Z" />
|
||||
<template v-else-if="name === 'sun'">
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2v2m0 16v2M4.93 4.93l1.42 1.42m11.3 11.3 1.42 1.42M2 12h2m16 0h2M4.93 19.07l1.42-1.42m11.3-11.3 1.42-1.42" />
|
||||
</template>
|
||||
<path v-else-if="name === 'moon'" d="M20.4 15.2A8.5 8.5 0 0 1 8.8 3.6 8.5 8.5 0 1 0 20.4 15.2Z" />
|
||||
<path v-else-if="name === 'monitor'" d="M4 4h16v12H4zM8 20h8M12 16v4" />
|
||||
<path v-else-if="name === 'github'" fill="currentColor" stroke="none" d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.7-3.88-1.54-3.88-1.54-.53-1.33-1.28-1.68-1.28-1.68-1.04-.71.08-.7.08-.7 1.15.08 1.75 1.18 1.75 1.18 1.02 1.75 2.68 1.24 3.33.95.1-.74.4-1.24.73-1.52-2.55-.29-5.23-1.28-5.23-5.68 0-1.25.45-2.27 1.18-3.07-.12-.29-.51-1.45.11-3.03 0 0 .96-.31 3.15 1.17.91-.25 1.88-.38 2.85-.38.97 0 1.94.13 2.85.38 2.19-1.48 3.15-1.17 3.15-1.17.62 1.58.23 2.74.11 3.03.73.8 1.18 1.82 1.18 3.07 0 4.41-2.69 5.38-5.25 5.67.41.35.78 1.04.78 2.1 0 1.52-.01 2.75-.01 3.12 0 .3.21.67.8.56C20.71 21.39 24 17.08 24 12 24 5.65 18.35.5 12 .5Z" />
|
||||
<path v-else-if="name === 'check'" d="m5 12 4 4L19 6" />
|
||||
|
||||
@@ -109,6 +109,15 @@ export function useVoiceWebSocket() {
|
||||
let micSource: MediaStreamAudioSourceNode | null = null;
|
||||
let micGain: GainNode | null = null;
|
||||
let silentGain: GainNode | null = null;
|
||||
const accompanimentActive = ref(false);
|
||||
const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia));
|
||||
const accompanimentErrorCode = ref<"" | "unsupported" | "needsWebRtc" | "noAudio" | "permission">("");
|
||||
let accompanimentStream: MediaStream | null = null;
|
||||
let webrtcMixDestination: MediaStreamAudioDestinationNode | null = null;
|
||||
let webrtcMixMicSource: MediaStreamAudioSourceNode | null = null;
|
||||
let webrtcMixMicGain: GainNode | null = null;
|
||||
let webrtcMixAccompanimentSource: MediaStreamAudioSourceNode | null = null;
|
||||
let webrtcMixAccompanimentGain: GainNode | null = null;
|
||||
let webrtcMicMonitorSource: MediaStreamAudioSourceNode | null = null;
|
||||
let webrtcMicMonitorAnalyser: AnalyserNode | null = null;
|
||||
let webrtcMicMonitorGain: GainNode | null = null;
|
||||
@@ -162,40 +171,6 @@ export function useVoiceWebSocket() {
|
||||
// for jitter; stale audio is discarded instead of being played late.
|
||||
const MAX_REMOTE_PLAY_AHEAD_SECONDS = 0.08;
|
||||
const MAX_REMOTE_DECODE_QUEUE_FRAMES = 3;
|
||||
const audioDebugEnabled = typeof location !== "undefined"
|
||||
&& new URLSearchParams(location.search).get("audioDebug") === "1";
|
||||
const audioDiagnostics = reactive({
|
||||
uplinkFrames: 0,
|
||||
uplinkDroppedFrames: 0,
|
||||
downlinkFrames: 0,
|
||||
decoderOutputFrames: 0,
|
||||
playbackStarts: 0,
|
||||
playbackResets: 0,
|
||||
peakBufferedBytes: 0,
|
||||
peakPlayAheadMs: 0,
|
||||
peakDecodeQueueFrames: 0,
|
||||
downlinkFirstAt: null as number | null,
|
||||
lastDownlinkAt: null as number | null,
|
||||
downlinkMaxGapMs: 0,
|
||||
lastDecodeOutputAt: null as number | null,
|
||||
lastPlaybackStartAt: null as number | null,
|
||||
lastPlayAheadMs: 0,
|
||||
});
|
||||
const audioCounters = { ...audioDiagnostics };
|
||||
let nextAudioDiagnosticsPublishAt = 0;
|
||||
|
||||
function publishAudioDiagnostics(force = false): void {
|
||||
const now = Date.now();
|
||||
if (!force && now < nextAudioDiagnosticsPublishAt) return;
|
||||
nextAudioDiagnosticsPublishAt = now + 1_000;
|
||||
Object.assign(audioDiagnostics, audioCounters);
|
||||
if (audioDebugEnabled) {
|
||||
console.info("[WebSpeak audio checkpoint]", JSON.stringify({
|
||||
at: new Date(now).toISOString(),
|
||||
...audioDiagnostics,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
async function saveAudioPreferences(): Promise<void> {
|
||||
await saveLocalPreferences({
|
||||
@@ -418,11 +393,8 @@ export function useVoiceWebSocket() {
|
||||
return;
|
||||
}
|
||||
const bufferedBytes = socket.bufferedAmount;
|
||||
audioCounters.peakBufferedBytes = Math.max(audioCounters.peakBufferedBytes, bufferedBytes);
|
||||
if (bufferedBytes > MAX_AUDIO_BUFFERED_BYTES) {
|
||||
accumLen = 0;
|
||||
audioCounters.uplinkDroppedFrames++;
|
||||
publishAudioDiagnostics();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -441,8 +413,6 @@ export function useVoiceWebSocket() {
|
||||
while (offset + AUDIO_FRAME_SAMPLES <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= MAX_AUDIO_BUFFERED_BYTES) {
|
||||
socket.send(accumBuf.slice(offset, offset + AUDIO_FRAME_SAMPLES).buffer);
|
||||
offset += AUDIO_FRAME_SAMPLES;
|
||||
audioCounters.uplinkFrames++;
|
||||
publishAudioDiagnostics();
|
||||
}
|
||||
if (offset > 0) markSpeaking(state.tsClientId);
|
||||
accumLen -= offset;
|
||||
@@ -514,19 +484,143 @@ export function useVoiceWebSocket() {
|
||||
return false;
|
||||
}
|
||||
|
||||
function stopWebRtcMix(): void {
|
||||
webrtcMixAccompanimentSource?.disconnect();
|
||||
webrtcMixAccompanimentGain?.disconnect();
|
||||
webrtcMixMicSource?.disconnect();
|
||||
webrtcMixMicGain?.disconnect();
|
||||
webrtcMixDestination?.disconnect();
|
||||
webrtcMixAccompanimentSource = null;
|
||||
webrtcMixAccompanimentGain = null;
|
||||
webrtcMixMicSource = null;
|
||||
webrtcMixMicGain = null;
|
||||
webrtcMixDestination = null;
|
||||
}
|
||||
|
||||
function releaseAccompanimentStream(): void {
|
||||
accompanimentStream?.getTracks().forEach((track) => track.stop());
|
||||
accompanimentStream = null;
|
||||
accompanimentActive.value = false;
|
||||
}
|
||||
|
||||
function createWebRtcMixStream(): MediaStream {
|
||||
if (!micStream) throw new Error("没有可用的麦克风音轨");
|
||||
const ctx = getAudioCtx();
|
||||
stopWebRtcMix();
|
||||
const destination = ctx.createMediaStreamDestination();
|
||||
destination.channelCount = 1;
|
||||
destination.channelCountMode = "explicit";
|
||||
const microphoneSource = ctx.createMediaStreamSource(micStream);
|
||||
const microphoneGain = ctx.createGain();
|
||||
microphoneGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value;
|
||||
microphoneSource.connect(microphoneGain);
|
||||
microphoneGain.connect(destination);
|
||||
|
||||
webrtcMixDestination = destination;
|
||||
webrtcMixMicSource = microphoneSource;
|
||||
webrtcMixMicGain = microphoneGain;
|
||||
|
||||
const accompanimentTrack = accompanimentStream?.getAudioTracks()[0];
|
||||
if (accompanimentTrack) {
|
||||
const accompanimentSource = ctx.createMediaStreamSource(accompanimentStream!);
|
||||
const accompanimentGain = ctx.createGain();
|
||||
accompanimentGain.gain.value = 0.78;
|
||||
accompanimentSource.connect(accompanimentGain);
|
||||
accompanimentGain.connect(destination);
|
||||
webrtcMixAccompanimentSource = accompanimentSource;
|
||||
webrtcMixAccompanimentGain = accompanimentGain;
|
||||
}
|
||||
return destination.stream;
|
||||
}
|
||||
|
||||
async function replaceWebRtcAudioTrack(): Promise<void> {
|
||||
if (!webrtcPeer || !micStream) return;
|
||||
const sender = webrtcPeer.getSenders().find((candidate) => candidate.track?.kind === "audio");
|
||||
if (!sender) throw new Error("WebRTC 音频轨道尚未就绪");
|
||||
const mixedStream = createWebRtcMixStream();
|
||||
const mixedTrack = mixedStream.getAudioTracks()[0];
|
||||
if (!mixedTrack) throw new Error("混合音频轨道创建失败");
|
||||
await sender.replaceTrack(mixedTrack);
|
||||
}
|
||||
|
||||
async function startAccompaniment(): Promise<void> {
|
||||
accompanimentErrorCode.value = "";
|
||||
if (!accompanimentSupported.value) {
|
||||
accompanimentErrorCode.value = "unsupported";
|
||||
throw new Error("伴奏共享不可用");
|
||||
}
|
||||
if (!webrtcActive.value || !webrtcPeer || !micStream) {
|
||||
accompanimentErrorCode.value = "needsWebRtc";
|
||||
throw new Error("伴奏功能需要启用 WebRTC");
|
||||
}
|
||||
|
||||
const audioConstraints = {} as MediaTrackConstraints & { restrictOwnAudio?: boolean };
|
||||
const supportedConstraints = navigator.mediaDevices.getSupportedConstraints?.() as Record<string, boolean> | undefined;
|
||||
if (supportedConstraints?.restrictOwnAudio) audioConstraints.restrictOwnAudio = true;
|
||||
const options = {
|
||||
video: { displaySurface: "browser" },
|
||||
audio: audioConstraints,
|
||||
selfBrowserSurface: "exclude",
|
||||
systemAudio: "include",
|
||||
windowAudio: "window",
|
||||
} as unknown as DisplayMediaStreamOptions;
|
||||
|
||||
let nextStream: MediaStream;
|
||||
try {
|
||||
nextStream = await navigator.mediaDevices.getDisplayMedia(options);
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === "AbortError") return;
|
||||
accompanimentErrorCode.value = "permission";
|
||||
throw error;
|
||||
}
|
||||
const audioTrack = nextStream.getAudioTracks()[0];
|
||||
nextStream.getVideoTracks().forEach((track) => track.stop());
|
||||
if (!audioTrack) {
|
||||
nextStream.getTracks().forEach((track) => track.stop());
|
||||
accompanimentErrorCode.value = "noAudio";
|
||||
throw new Error("所选来源没有可共享音频");
|
||||
}
|
||||
|
||||
accompanimentStream?.getTracks().forEach((track) => track.stop());
|
||||
accompanimentStream = nextStream;
|
||||
accompanimentActive.value = true;
|
||||
sendCmd("setAccompanimentActive", { active: true });
|
||||
audioTrack.addEventListener("ended", () => { void stopAccompaniment(); }, { once: true });
|
||||
try {
|
||||
await replaceWebRtcAudioTrack();
|
||||
} catch (error) {
|
||||
releaseAccompanimentStream();
|
||||
sendCmd("setAccompanimentActive", { active: false });
|
||||
stopWebRtcMix();
|
||||
accompanimentErrorCode.value = "permission";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function stopAccompaniment(): Promise<void> {
|
||||
accompanimentErrorCode.value = "";
|
||||
releaseAccompanimentStream();
|
||||
if (webrtcActive.value) sendCmd("setAccompanimentActive", { active: false });
|
||||
if (webrtcActive.value && webrtcPeer && micStream) await replaceWebRtcAudioTrack();
|
||||
else stopWebRtcMix();
|
||||
}
|
||||
|
||||
async function startWebRtcTransport(sequence: number, socket: WebSocket): Promise<void> {
|
||||
if (typeof RTCPeerConnection === "undefined") throw new Error("当前浏览器不支持 WebRTC");
|
||||
await ensureMicrophone();
|
||||
if (sequence !== connectionSequence || socket.readyState !== WebSocket.OPEN || !micStream) return;
|
||||
const track = micStream.getAudioTracks()[0];
|
||||
if (!track) throw new Error("没有可用的麦克风音轨");
|
||||
const microphoneTrack = micStream.getAudioTracks()[0];
|
||||
if (!microphoneTrack) throw new Error("没有可用的麦克风音轨");
|
||||
|
||||
stopCaptureGraph();
|
||||
const peer = new RTCPeerConnection({ iceServers: [] });
|
||||
webrtcPeer = peer;
|
||||
webrtcFallbackStarted = false;
|
||||
track.enabled = !microphoneMuted.value;
|
||||
peer.addTrack(track, micStream);
|
||||
microphoneTrack.enabled = !microphoneMuted.value;
|
||||
const mixedStream = createWebRtcMixStream();
|
||||
const mixedTrack = mixedStream.getAudioTracks()[0];
|
||||
if (!mixedTrack) throw new Error("混合音频轨道创建失败");
|
||||
peer.addTrack(mixedTrack, mixedStream);
|
||||
peer.ontrack = (event) => {
|
||||
const stream = event.streams[0] ?? new MediaStream([event.track]);
|
||||
// Use the browser's native WebRTC media output. Routing the remote
|
||||
@@ -556,7 +650,7 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
void syncWebRtcPlayback();
|
||||
};
|
||||
startWebRtcMicMonitor(getAudioCtx(), micStream, track);
|
||||
startWebRtcMicMonitor(getAudioCtx(), micStream, microphoneTrack);
|
||||
peer.onconnectionstatechange = () => {
|
||||
if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket);
|
||||
};
|
||||
@@ -569,7 +663,11 @@ export function useVoiceWebSocket() {
|
||||
if (sequence !== connectionSequence || webrtcPeer !== peer || socket.readyState !== WebSocket.OPEN) return;
|
||||
const description = peer.localDescription;
|
||||
if (!description) throw new Error("WebRTC offer was not created");
|
||||
socket.send(JSON.stringify({ type: "webrtcOffer", payload: { sdp: { type: description.type, sdp: description.sdp }, muted: microphoneMuted.value } }));
|
||||
socket.send(JSON.stringify({ type: "webrtcOffer", payload: {
|
||||
sdp: { type: description.type, sdp: description.sdp },
|
||||
muted: microphoneMuted.value,
|
||||
accompanimentActive: accompanimentActive.value,
|
||||
} }));
|
||||
window.setTimeout(() => {
|
||||
if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket);
|
||||
}, 8_000);
|
||||
@@ -609,6 +707,7 @@ export function useVoiceWebSocket() {
|
||||
try {
|
||||
await webrtcPeer.setRemoteDescription(description);
|
||||
webrtcActive.value = true;
|
||||
syncWebRtcMemberVolumes();
|
||||
} catch {
|
||||
if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value);
|
||||
}
|
||||
@@ -632,6 +731,8 @@ export function useVoiceWebSocket() {
|
||||
webrtcPeer = null;
|
||||
webrtcActive.value = false;
|
||||
webrtcNegotiationPromise = null;
|
||||
releaseAccompanimentStream();
|
||||
stopWebRtcMix();
|
||||
stopWebRtcMicMonitor();
|
||||
stopWebRtcPlayback();
|
||||
if (peer) void peer.close();
|
||||
@@ -716,6 +817,8 @@ export function useVoiceWebSocket() {
|
||||
|
||||
function stopMicrophone(closeContext = true): void {
|
||||
stopCaptureGraph();
|
||||
releaseAccompanimentStream();
|
||||
stopWebRtcMix();
|
||||
micStream?.getTracks().forEach((track) => track.stop());
|
||||
micStream = null;
|
||||
if (closeContext) {
|
||||
@@ -843,7 +946,6 @@ export function useVoiceWebSocket() {
|
||||
const now = ctx.currentTime;
|
||||
const scheduledUntil = remotePlayTimes.get(clientId) ?? now;
|
||||
const decodeQueueSize = decoder?.decodeQueueSize ?? 0;
|
||||
audioCounters.peakDecodeQueueFrames = Math.max(audioCounters.peakDecodeQueueFrames, decodeQueueSize);
|
||||
if (
|
||||
decoder &&
|
||||
(scheduledUntil > now + MAX_REMOTE_PLAY_AHEAD_SECONDS || decodeQueueSize >= MAX_REMOTE_DECODE_QUEUE_FRAMES)
|
||||
@@ -866,8 +968,6 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
try {
|
||||
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
|
||||
audioCounters.decoderOutputFrames++;
|
||||
audioCounters.lastDecodeOutputAt = Date.now();
|
||||
const buffer = ctx.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
|
||||
for (let ch = 0; ch < numberOfChannels; ch++) {
|
||||
const data = new Float32Array(numberOfFrames);
|
||||
@@ -899,17 +999,7 @@ export function useVoiceWebSocket() {
|
||||
return;
|
||||
}
|
||||
source.start(playTime);
|
||||
audioCounters.playbackStarts++;
|
||||
audioCounters.lastPlaybackStartAt = Date.now();
|
||||
remotePlayTimes.set(clientId, playTime + numberOfFrames / sampleRate);
|
||||
audioCounters.lastPlayAheadMs = Math.max(
|
||||
0,
|
||||
Math.round((playTime + numberOfFrames / sampleRate - ctx.currentTime) * 1_000),
|
||||
);
|
||||
audioCounters.peakPlayAheadMs = Math.max(
|
||||
audioCounters.peakPlayAheadMs,
|
||||
audioCounters.lastPlayAheadMs,
|
||||
);
|
||||
} catch {
|
||||
// A decoder can finish while the audio context is being torn down.
|
||||
}
|
||||
@@ -932,8 +1022,6 @@ export function useVoiceWebSocket() {
|
||||
const timestamp = remoteDecodeTimestamps.get(clientId) ?? 0;
|
||||
decoder.decode(new EncodedAudioChunk({ type: "key", timestamp, duration: 20_000, data: opusData }));
|
||||
remoteDecodeTimestamps.set(clientId, timestamp + 20_000);
|
||||
audioCounters.downlinkFrames++;
|
||||
publishAudioDiagnostics();
|
||||
} catch {
|
||||
// Ignore malformed frames; the next valid frame can still be decoded.
|
||||
}
|
||||
@@ -960,8 +1048,6 @@ export function useVoiceWebSocket() {
|
||||
|
||||
function resetRemotePlayback(clientId: number): void {
|
||||
clearRemotePlayback(clientId);
|
||||
audioCounters.playbackResets++;
|
||||
publishAudioDiagnostics();
|
||||
}
|
||||
|
||||
function connect(target: string, channel: string, nickname: string, serverPassword = "", identity = "", rememberIdentity = false, inviteToken = ""): void {
|
||||
@@ -1025,15 +1111,18 @@ export function useVoiceWebSocket() {
|
||||
state.connected = false;
|
||||
state.connecting = false;
|
||||
state.reconnecting = false;
|
||||
if (event.code !== 1000 && !state.error && !state.reconnectFailed) state.error = closeReason(event.code);
|
||||
// Prefer the close code over the generic WebSocket error event. The
|
||||
// gateway uses a dedicated code when a remembered identity is already
|
||||
// active in another browser page.
|
||||
if (event.code !== 1000 && !state.reconnectFailed) state.error = closeReason(event.code);
|
||||
stopWebRtcTransport();
|
||||
stopMicrophone();
|
||||
whisperTargetIds.clear();
|
||||
whisperActive.value = false;
|
||||
};
|
||||
socket.onerror = () => {
|
||||
if (sequence !== connectionSequence) return;
|
||||
state.error = "连接服务器失败,请检查邀请链接或服务器状态";
|
||||
// The following close event contains the actionable close code. Do not
|
||||
// overwrite it with a generic browser WebSocket error first.
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1049,11 +1138,13 @@ export function useVoiceWebSocket() {
|
||||
if (code === 4002) return "TeamSpeak 服务器地址无效";
|
||||
if (code === 4003) return "TeamSpeak 服务器连接失败";
|
||||
if (code === 4004) return "服务器当前已满,请稍后重试";
|
||||
if (code === 4005) return "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试";
|
||||
return "连接已断开";
|
||||
}
|
||||
|
||||
function disconnect(preserveConnection = false): void {
|
||||
connectionSequence++;
|
||||
const keepRememberedIdentity = lastConnection?.rememberIdentity === true;
|
||||
if (!preserveConnection) lastConnection = null;
|
||||
stopMicrophone();
|
||||
const socket = ws.value;
|
||||
@@ -1067,7 +1158,7 @@ export function useVoiceWebSocket() {
|
||||
state.reconnectFailed = false;
|
||||
state.tsClientId = 0;
|
||||
state.errorCode = "";
|
||||
identityMaterial.value = "";
|
||||
if (!keepRememberedIdentity) identityMaterial.value = "";
|
||||
members.length = 0;
|
||||
channels.length = 0;
|
||||
chatMessages.length = 0;
|
||||
@@ -1247,12 +1338,6 @@ export function useVoiceWebSocket() {
|
||||
if (data.length < 4) return;
|
||||
const clientId = (data[1] << 8) | data[2];
|
||||
if (clientId === state.tsClientId) return;
|
||||
const receivedAt = Date.now();
|
||||
if (audioCounters.lastDownlinkAt !== null) {
|
||||
audioCounters.downlinkMaxGapMs = Math.max(audioCounters.downlinkMaxGapMs, receivedAt - audioCounters.lastDownlinkAt);
|
||||
}
|
||||
audioCounters.downlinkFirstAt ??= receivedAt;
|
||||
audioCounters.lastDownlinkAt = receivedAt;
|
||||
markSpeaking(clientId);
|
||||
playAudioFrame(clientId, data.slice(3));
|
||||
}
|
||||
@@ -1340,6 +1425,7 @@ export function useVoiceWebSocket() {
|
||||
voxRelease = 0;
|
||||
accumLen = 0;
|
||||
if (webrtcActive.value) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; });
|
||||
if (webrtcMixMicGain) webrtcMixMicGain.gain.value = muted ? 0 : inputVolume.value;
|
||||
if (webrtcActive.value) sendCmd("setMicrophoneMuted", { muted });
|
||||
if (muted && state.tsClientId) clearSpeaking(state.tsClientId);
|
||||
void saveAudioPreferences();
|
||||
@@ -1364,6 +1450,7 @@ export function useVoiceWebSocket() {
|
||||
INVALID_POKE_MESSAGE: "戳一戳消息无效",
|
||||
INVALID_AWAY_STATUS: "离开状态无效",
|
||||
INVALID_AUDIO_FRAME: "音频帧格式无效",
|
||||
INVALID_MEMBER_VOLUME: "成员音量无效",
|
||||
INVALID_WHISPER_TARGETS: "私语目标无效",
|
||||
INVALID_WHISPER_STATE: "私语状态无效",
|
||||
NO_WHISPER_TARGETS: "请先选择私语目标",
|
||||
@@ -1388,11 +1475,22 @@ export function useVoiceWebSocket() {
|
||||
}
|
||||
const gain = remoteGains.get(clientId);
|
||||
if (gain) gain.gain.value = normalized * outputVolume.value;
|
||||
if (webrtcPeer || webrtcActive.value) sendCmd("setMemberVolume", { clientId, volume: normalized });
|
||||
}
|
||||
|
||||
function syncWebRtcMemberVolumes(): void {
|
||||
if (!webrtcActive.value || ws.value?.readyState !== WebSocket.OPEN) return;
|
||||
for (const [rawClientId, volume] of Object.entries(volumes)) {
|
||||
const clientId = Number(rawClientId);
|
||||
if (!Number.isInteger(clientId) || clientId <= 0) continue;
|
||||
sendCmd("setMemberVolume", { clientId, volume });
|
||||
}
|
||||
}
|
||||
|
||||
function setInputVolume(volume: number): void {
|
||||
inputVolume.value = Math.max(0, Math.min(1, volume));
|
||||
if (micGain) micGain.gain.value = inputVolume.value;
|
||||
if (webrtcMixMicGain) webrtcMixMicGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value;
|
||||
void saveAudioPreferences();
|
||||
}
|
||||
|
||||
@@ -1433,7 +1531,6 @@ export function useVoiceWebSocket() {
|
||||
outputDeviceSupported,
|
||||
audioPermission,
|
||||
audioContextState,
|
||||
audioDiagnostics,
|
||||
identityMaterial,
|
||||
micLevel,
|
||||
microphoneTestActive,
|
||||
@@ -1442,6 +1539,9 @@ export function useVoiceWebSocket() {
|
||||
whisperTargetIds,
|
||||
whisperActive,
|
||||
volumes,
|
||||
accompanimentActive,
|
||||
accompanimentSupported,
|
||||
accompanimentErrorCode,
|
||||
setVolume,
|
||||
setInputVolume,
|
||||
setOutputVolume,
|
||||
@@ -1466,6 +1566,8 @@ export function useVoiceWebSocket() {
|
||||
setWhisperTargets,
|
||||
setWhisperActive,
|
||||
setMicrophoneMuted,
|
||||
startAccompaniment,
|
||||
stopAccompaniment,
|
||||
checkSupport,
|
||||
clearError,
|
||||
};
|
||||
|
||||
@@ -118,6 +118,18 @@ export async function saveStoredIdentity(privateMaterial: string, label = "此
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeStoredIdentity(): Promise<void> {
|
||||
try {
|
||||
await request("identities", "readwrite", (store, resolve, reject) => {
|
||||
const remove = store.delete(CURRENT_IDENTITY_KEY);
|
||||
remove.onsuccess = () => resolve(undefined);
|
||||
remove.onerror = () => reject(remove.error);
|
||||
});
|
||||
} catch {
|
||||
// Identity removal is best effort when browser storage is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadLocalPreferences(): Promise<LocalPreferences> {
|
||||
const defaults: LocalPreferences = { schemaVersion: 1, volumesByUid: {} };
|
||||
try {
|
||||
|
||||
@@ -17,8 +17,16 @@ export function saveTheme(theme: ThemeMode): void {
|
||||
applyTheme(theme);
|
||||
}
|
||||
|
||||
export function isDarkTheme(theme: ThemeMode): boolean {
|
||||
if (theme === "dark") return true;
|
||||
if (theme === "light") return false;
|
||||
return typeof window !== "undefined" && typeof window.matchMedia === "function"
|
||||
? window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
: false;
|
||||
}
|
||||
|
||||
export function nextTheme(theme: ThemeMode): ThemeMode {
|
||||
return theme === "system" ? "light" : theme === "light" ? "dark" : "system";
|
||||
return isDarkTheme(theme) ? "light" : "dark";
|
||||
}
|
||||
|
||||
applyTheme(getStoredTheme());
|
||||
@@ -28,7 +28,7 @@
|
||||
</aside>
|
||||
|
||||
<main class="admin-main">
|
||||
<header class="admin-topbar"><div><small>{{ tr('adminConsole') }}</small><h1>{{ currentPageTitle }}</h1></div><div><span class="running-dot"></span>{{ tr('gatewayRunning') }}<button type="button" :title="themeLabel" @click="cycleTheme">{{ themeLabel }}</button><button type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button></div></header>
|
||||
<header class="admin-topbar"><div><small>{{ tr('adminConsole') }}</small><h1>{{ currentPageTitle }}</h1></div><div><span class="running-dot"></span>{{ tr('gatewayRunning') }}<button type="button" class="theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon :name="themeIcon" :size="17" /><span>{{ themeLabel }}</span></button><button type="button" @click="toggleLanguage">{{ tr('languageSwitch') }}</button></div></header>
|
||||
|
||||
<div v-if="errorMessage" class="alert error page-alert">{{ errorMessage }}</div>
|
||||
<section v-if="route.path === '/admin/server'" class="page-content server-page">
|
||||
@@ -68,7 +68,7 @@ import { computed, onMounted, reactive, ref, watch } from "vue";
|
||||
import { RouterLink, useRoute, useRouter } from "vue-router";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import { combineTeamSpeakTarget, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
import { applyTheme, getStoredTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
import { applyTheme, getStoredTheme, isDarkTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
|
||||
type Language = "zh" | "en";
|
||||
type Screen = "login" | "change-password" | "admin";
|
||||
@@ -79,7 +79,8 @@ const route = useRoute();
|
||||
const router = useRouter();
|
||||
const language = ref<Language>((localStorage.getItem("webspeak:language") as Language) || "zh");
|
||||
const themeMode = ref<ThemeMode>(getStoredTheme());
|
||||
const themeLabel = computed(() => themeMode.value === "dark" ? tr("themeDark") : themeMode.value === "light" ? tr("themeLight") : tr("themeSystem"));
|
||||
const themeIcon = computed(() => isDarkTheme(themeMode.value) ? "sun" : "moon");
|
||||
const themeLabel = computed(() => isDarkTheme(themeMode.value) ? tr("switchToLightTheme") : tr("switchToDarkTheme"));
|
||||
applyTheme(themeMode.value);
|
||||
const loading = ref(true);
|
||||
const screen = ref<Screen>("login");
|
||||
@@ -122,6 +123,8 @@ const copy = {
|
||||
themeSystem: "跟随系统",
|
||||
themeLight: "浅色主题",
|
||||
themeDark: "深色主题",
|
||||
switchToLightTheme: "切换到浅色主题",
|
||||
switchToDarkTheme: "切换到深色主题",
|
||||
welcomeAdmin: "欢迎回来",
|
||||
loginLead: "输入管理员账号和密码以管理此 WebSpeak 实例。",
|
||||
adminPassword: "管理员密码",
|
||||
@@ -277,6 +280,8 @@ const copy = {
|
||||
themeSystem: "System theme",
|
||||
themeLight: "Light theme",
|
||||
themeDark: "Dark theme",
|
||||
switchToLightTheme: "Switch to light theme",
|
||||
switchToDarkTheme: "Switch to dark theme",
|
||||
welcomeAdmin: "Welcome back",
|
||||
loginLead: "Enter the admin account and password to manage this WebSpeak instance.",
|
||||
adminPassword: "Admin password",
|
||||
@@ -467,6 +472,7 @@ async function parseResponse(response: Response) { const value = await response.
|
||||
|
||||
<style scoped>
|
||||
.intro-copy h1{font-size:clamp(38px,4.2vw,56px)!important;line-height:1.05!important;letter-spacing:-.055em!important}
|
||||
.admin-topbar .theme-toggle{display:inline-flex;align-items:center;gap:6px}
|
||||
:global(*){box-sizing:border-box}:global(body){margin:0;font-family:Inter,"Segoe UI","PingFang SC",sans-serif;color:#20302c;background:#f4f8f6}.admin-root{min-height:100dvh}.auth-layout{display:grid;min-height:100dvh;grid-template-columns:minmax(360px,.82fr) minmax(520px,1.18fr)}.auth-intro{display:flex;flex-direction:column;padding:48px clamp(38px,6vw,92px);color:#e8fffa;background:radial-gradient(circle at 20% 0,rgba(90,211,191,.28),transparent 32rem),#063f3b}.admin-brand{display:flex;align-items:center;gap:12px}.admin-brand>span{display:grid;place-items:center;width:42px;height:42px;color:#fff;background:#07877d;border-radius:12px;box-shadow:0 8px 22px rgba(0,0,0,.15)}.admin-brand strong,.admin-brand small{display:block}.admin-brand strong{font-size:20px;letter-spacing:-.04em}.admin-brand small{margin-top:3px;color:#9bc9c2;font-size:11px}.intro-copy{margin:auto 0 48px}.intro-copy i{color:#75e3d2;font-size:12px;font-style:normal;font-weight:800;letter-spacing:.12em}.intro-copy h1{max-width:540px;margin:16px 0;font-size:clamp(40px,5vw,66px);line-height:1.03;letter-spacing:-.065em}.intro-copy p{max-width:530px;color:#a9d0ca;font-size:16px;line-height:1.75}.step-list{display:grid;gap:10px}.step-list button{display:flex;align-items:center;gap:13px;width:100%;padding:13px;color:#89bbb4;text-align:left;background:transparent;border:1px solid transparent;border-radius:12px}.step-list button.active{color:#fff;background:rgba(255,255,255,.08);border-color:rgba(255,255,255,.1)}.step-list button.done{color:#8ee4d7}.step-list button>span{display:grid;place-items:center;width:28px;height:28px;flex:none;border:1px solid currentColor;border-radius:50%;font-size:12px;font-weight:800}.step-list strong,.step-list small{display:block}.step-list strong{font-size:13px}.step-list small{margin-top:3px;font-size:10px;opacity:.75}.auth-panel{position:relative;display:grid;place-items:center;padding:80px 40px;background:radial-gradient(circle at 80% 10%,rgba(99,205,188,.15),transparent 25rem),#f5f9f7}.panel-tools{position:absolute;top:28px;right:34px}.panel-tools button,.language-link,.admin-topbar button{color:#08766e;background:#e4f3ef;border:1px solid #cae7e0;border-radius:8px;padding:8px 12px;font-size:11px;font-weight:700;cursor:pointer}.setup-card,.login-card{width:min(560px,100%);padding:36px;background:#fff;border:1px solid #dfeae6;border-radius:20px;box-shadow:0 20px 55px rgba(27,69,61,.09)}.setup-card header small{color:#07877d;font-size:11px;font-weight:800;letter-spacing:.08em}.setup-card header h2,.login-card h1{margin:10px 0 7px;font-size:29px;letter-spacing:-.045em}.setup-card header p,.login-card header p{margin:0;color:#71817c;font-size:13px;line-height:1.6}.form-stack,.login-card form{display:grid;gap:17px;margin-top:27px}label>span,fieldset legend{display:block;margin-bottom:7px;color:#40514c;font-size:12px;font-weight:700}label em{color:#91a09c;font-size:10px;font-style:normal;font-weight:500}label small{display:block;margin-top:6px;color:#899792;font-size:10px;line-height:1.5}input,textarea{width:100%;padding:11px 12px;color:#22332f;background:#fbfdfc;border:1px solid #dbe7e3;border-radius:9px;font:inherit;font-size:13px;outline:none}input{height:43px}input:focus,textarea:focus{border-color:#54bdb2;box-shadow:0 0 0 3px rgba(84,189,178,.13)}textarea{resize:vertical}.strength{height:4px;overflow:hidden;background:#e7eeeb;border-radius:4px}.strength i{display:block;height:100%;background:linear-gradient(90deg,#e7a452,#50c5a2);transition:.2s}fieldset{display:grid;gap:9px;margin:0;padding:0;border:0}.choice{display:flex;align-items:flex-start;gap:10px;padding:13px;border:1px solid #dfe9e6;border-radius:10px;cursor:pointer}.choice:has(input:checked){border-color:#62bfb5;background:#eff8f6}.choice input{width:16px;height:16px;flex:none;margin:2px 0}.choice strong,.choice small{display:block}.choice strong{font-size:12px}.choice small{margin-top:4px;color:#7b8985;font-size:10px;line-height:1.45}.setup-card footer{display:flex;align-items:center;justify-content:space-between;margin-top:28px;padding-top:20px;border-top:1px solid #edf1ef}.primary-button,.secondary-button,.text-button{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:42px;padding:0 18px;border:0;border-radius:9px;font-size:12px;font-weight:800;cursor:pointer}.primary-button{color:#fff;background:#087d74}.primary-button:hover{background:#056b63}.primary-button:disabled,.secondary-button:disabled{opacity:.55;cursor:not-allowed}.secondary-button{color:#08776e;background:#eaf6f3;border:1px solid #cfe9e3}.text-button{color:#687a74;background:transparent}.wide{width:100%}.spinner{display:inline-block;width:22px;height:22px;border:2px solid #cde6df;border-top-color:#087d74;border-radius:50%;animation:spin .7s linear infinite}.spinner.small{width:15px;height:15px;border-color:rgba(255,255,255,.35);border-top-color:currentColor}@keyframes spin{to{transform:rotate(360deg)}}.alert{padding:12px 14px;border-radius:9px;font-size:12px;linLine truncated
|
||||
@media(max-width:850px){.auth-layout{display:block}.auth-intro{min-height:auto;padding:28px 24px}.intro-copy{margin:55px 0 35px}.step-list{display:none}.auth-panel{padding:35px 18px 60px}.panel-tools{top:18px;right:18px}.admin-shell{display:block}.admin-sidebar{position:static;width:100%;height:auto;flex-direction:row;align-items:center;padding:12px 16px}.admin-sidebar .admin-brand{padding:0}.admin-sidebar .admin-brand small{display:none}.admin-sidebar nav{display:flex;margin-left:auto}.admin-sidebar nav a{font-size:0}.admin-sidebar nav a .ui-icon{width:20px;height:20px}.sidebar-bottom{display:flex;margin:0 0 0 8px;padding:0;border:0}.sidebar-bottom a{display:none}.sidebar-bottom button{font-size:0}.settings-grid,.overview-columns{grid-template-columns:1fr}.readonly-card dl{grid-template-columns:1fr 1fr}.admin-topbar{padding:0 18px}.page-content{width:min(100% - 28px,700px);padding-top:24px}.metric-grid{grid-template-columns:1fr}.hero-status{align-items:flex-start;gap:20px}.hero-status p{max-width:75%}}
|
||||
@media(max-width:520px){.setup-card,.login-card{padding:25px 20px;border-radius:15px}.setup-card header h2{font-size:24px}.admin-topbar>div:last-child{font-size:0}.page-heading{gap:15px}.page-heading .primary-button{padding-inline:12px}.settings-card,.readonly-card,.overview-card{padding:18px}.readonly-card dl,.overview-card dl{grid-template-columns:1fr}.password-row{grid-template-columns:1fr}.password-actions{padding:0}.hero-status{padding:23px}.status-badge{display:none}}
|
||||
|
||||
+94
-16
@@ -10,7 +10,7 @@
|
||||
<small>{{ t('browserWorkspace') }}</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-tools"><div class="header-note"><span class="tiny-dot"></span> {{ t('secureGateway') }}</div><a class="github-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak" target="_blank" rel="noreferrer" :title="t('githubRepository')" :aria-label="t('githubRepository')"><Icon name="github" :size="18" /><span>{{ t('githubRepository') }}</span></a><a class="bilibili-button" href="https://space.bilibili.com/25414873" target="_blank" rel="noreferrer" :title="t('bilibiliProfile')" :aria-label="t('bilibiliProfile')"><span class="bilibili-glyph">B</span><span class="bilibili-label">{{ t('bilibiliProfile') }}</span></a><span class="version-badge" :title="`${t('currentVersion')}: v${appVersion}`" :aria-label="`${t('currentVersion')}: v${appVersion}`">v{{ appVersion }}</span><a class="changelog-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/CHANGELOG.md" target="_blank" rel="noreferrer" :title="t('viewChangelog')" :aria-label="t('viewChangelog')"><Icon name="clock" :size="16" /><span>{{ t('viewChangelog') }}</span></a><a class="guide-button" href="/admin" :title="t('adminConsole')" :aria-label="t('adminConsole')"><Icon name="settings" :size="15" /><span>{{ t('adminConsole') }}</span></a><button type="button" class="header-action theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon name="monitor" :size="17" /></button><button class="language-switch" :aria-label="t('langSwitch')" @click="toggleLanguage">{{ t('langSwitch') }}</button></div>
|
||||
<div class="header-tools"><div class="header-note"><span class="tiny-dot"></span> {{ t('secureGateway') }}</div><a class="github-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak" target="_blank" rel="noreferrer" :title="t('githubRepository')" :aria-label="t('githubRepository')"><Icon name="github" :size="18" /><span>{{ t('githubRepository') }}</span></a><a class="bilibili-button" href="https://space.bilibili.com/25414873" target="_blank" rel="noreferrer" :title="t('bilibiliProfile')" :aria-label="t('bilibiliProfile')"><span class="bilibili-glyph">B</span><span class="bilibili-label">{{ t('bilibiliProfile') }}</span></a><span class="version-badge" :title="`${t('currentVersion')}: v${appVersion}`" :aria-label="`${t('currentVersion')}: v${appVersion}`">v{{ appVersion }}</span><a class="changelog-button" href="https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/blob/master/CHANGELOG.md" target="_blank" rel="noreferrer" :title="t('viewChangelog')" :aria-label="t('viewChangelog')"><Icon name="clock" :size="16" /><span>{{ t('viewChangelog') }}</span></a><a class="guide-button" href="/admin" :title="t('adminConsole')" :aria-label="t('adminConsole')"><Icon name="settings" :size="15" /><span>{{ t('adminConsole') }}</span></a><button type="button" class="header-action theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon :name="themeIcon" :size="17" /></button><button class="language-switch" :aria-label="t('langSwitch')" @click="toggleLanguage">{{ t('langSwitch') }}</button></div>
|
||||
</header>
|
||||
|
||||
<main class="join-content">
|
||||
@@ -64,9 +64,9 @@
|
||||
<input id="channel" v-model="channel" :placeholder="t('emptyDefault')" @keyup.enter="doConnect" />
|
||||
</div>
|
||||
|
||||
<details class="identity-options"><summary>{{ t('identityOptions') }}</summary><label class="remember-identity"><input v-model="rememberIdentity" type="checkbox" /><span><strong>{{ t('rememberIdentity') }}</strong><small>{{ t('rememberIdentityHint') }}</small></span></label></details>
|
||||
<details class="identity-options"><summary>{{ t('identityOptions') }}</summary><label class="remember-identity"><input v-model="rememberIdentity" type="checkbox" /><span><strong>{{ t('rememberIdentity') }}</strong><small>{{ t('rememberIdentityHint') }}</small></span></label></details><p v-if="rememberIdentity" class="identity-warning">{{ t('rememberIdentityConcurrentWarning') }}</p>
|
||||
|
||||
<button class="primary-button connect-button" :disabled="!canJoin || serverConfigLoading || voiceState.connecting" type="submit">
|
||||
<button class="primary-button connect-button" :disabled="!canJoin || serverConfigLoading || !identityReady || voiceState.connecting" type="submit">
|
||||
<span v-if="voiceState.connecting" class="button-spinner"></span>
|
||||
<span>{{ voiceState.connecting ? t('connecting') : t('enterVoice') }}</span>
|
||||
<Icon v-if="!voiceState.connecting" name="chevron-right" :size="17" />
|
||||
@@ -95,9 +95,9 @@
|
||||
</select>
|
||||
</label>
|
||||
<button class="header-action" :title="t('copyInvite')" @click="doShare"><Icon name="share" :size="18" /></button>
|
||||
<button class="header-action microphone-header-toggle" :class="{ muted: microphoneMuted }" :title="microphoneMuted ? t('unmuteMic') : t('muteMic')" :aria-label="microphoneMuted ? t('microphoneMuted') : t('microphoneActive')" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /></button>
|
||||
<button class="header-action" :title="t('audioSettings')" :aria-label="t('audioSettings')" @click="settingsOpen = true"><Icon name="settings" :size="18" /></button>
|
||||
<button type="button" class="header-action theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon name="monitor" :size="17" /></button>
|
||||
<button v-if="isMobileViewport" class="header-action microphone-header-toggle" :class="{ muted: microphoneMuted }" :title="microphoneMuted ? t('unmuteMic') : t('muteMic')" :aria-label="microphoneMuted ? t('microphoneMuted') : t('microphoneActive')" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /></button>
|
||||
<button v-if="isMobileViewport" class="header-action" :title="t('audioSettings')" :aria-label="t('audioSettings')" @click="settingsOpen = true"><Icon name="settings" :size="18" /></button>
|
||||
<button type="button" class="header-action theme-toggle" :title="themeLabel" :aria-label="themeLabel" @click="cycleTheme"><Icon :name="themeIcon" :size="17" /></button>
|
||||
<button class="language-switch workspace-language" :aria-label="t('langSwitch')" @click="toggleLanguage">{{ t('langSwitch') }}</button>
|
||||
<button class="disconnect-button" @click="doDisconnect"><Icon name="door" :size="17" /><span>{{ t('exit') }}</span></button>
|
||||
</div>
|
||||
@@ -198,7 +198,14 @@
|
||||
</section>
|
||||
</div>
|
||||
<div v-if="!filteredMemberChannels.length" class="member-empty">{{ t('noMatchingMembers') }}</div>
|
||||
<div class="member-panel-tip"><Icon name="volume" :size="16" /><span>{{ t('volumeTip') }}</span></div>
|
||||
<div v-if="!isMobileViewport" class="desktop-audio-dock" role="toolbar" :aria-label="t('desktopAudioControls')">
|
||||
<div class="desktop-audio-dock-copy"><strong>{{ t('desktopAudioControls') }}</strong><span>{{ accompanimentActive ? t('accompanimentActive') : t('volumeTip') }}</span></div>
|
||||
<div class="desktop-audio-dock-actions">
|
||||
<button type="button" class="dock-audio-button microphone-header-toggle" :class="{ muted: microphoneMuted }" :title="microphoneMuted ? t('unmuteMic') : t('muteMic')" :aria-label="microphoneMuted ? t('microphoneMuted') : t('microphoneActive')" :aria-pressed="!microphoneMuted" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /></button>
|
||||
<button type="button" class="dock-audio-button" :title="t('audioSettings')" :aria-label="t('audioSettings')" @click="settingsOpen = true"><Icon name="settings" :size="18" /></button>
|
||||
<button type="button" class="dock-audio-button accompaniment-toggle" :class="{ active: accompanimentActive }" :title="accompanimentActive ? t('stopAccompaniment') : t('startAccompaniment')" :aria-label="accompanimentActive ? t('stopAccompaniment') : t('startAccompaniment')" :aria-pressed="accompanimentActive" @click="toggleAccompaniment"><Icon name="music" :size="18" /></button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section v-if="mobileSection === 'more'" class="mobile-more-panel">
|
||||
@@ -206,7 +213,7 @@
|
||||
<h2>{{ t('mobileMore') }}</h2>
|
||||
<button type="button" :class="{ muted: microphoneMuted }" @click="toggleMicrophone"><Icon :name="microphoneMuted ? 'mic-off' : 'mic'" :size="18" /> {{ microphoneMuted ? t('unmuteMic') : t('muteMic') }}</button>
|
||||
<button type="button" @click="settingsOpen = true"><Icon name="settings" :size="18" /> {{ t('audioSettings') }}</button>
|
||||
<button type="button" @click="cycleTheme"><Icon name="monitor" :size="18" /> {{ themeLabel }}</button>
|
||||
<button type="button" @click="cycleTheme"><Icon :name="themeIcon" :size="18" /> {{ themeLabel }}</button>
|
||||
<button type="button" @click="toggleLanguage"><Icon name="globe" :size="18" /> {{ t('langSwitch') }}</button>
|
||||
<button type="button" class="danger" @click="doDisconnect"><Icon name="door" :size="18" /> {{ t('exit') }}</button>
|
||||
</section>
|
||||
@@ -247,8 +254,8 @@
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import { useVoiceWebSocket, type ChannelInfo, type ChannelMember } from "../composables/useVoiceWebSocket.js";
|
||||
import { clearLocalData as clearStoredLocalData, isLocalPersistenceAvailable, listFavorites, listRecentServers, loadLocalPreferences, loadStoredIdentity, recordRecentServer, removeFavorite, saveFavorite, saveLocalPreferences, saveStoredIdentity, type FavoriteServer, type RecentServer } from "../services/local-persistence.js";
|
||||
import { applyTheme, getStoredTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
import { clearLocalData as clearStoredLocalData, isLocalPersistenceAvailable, listFavorites, listRecentServers, loadLocalPreferences, loadStoredIdentity, recordRecentServer, removeFavorite, removeStoredIdentity, saveFavorite, saveLocalPreferences, saveStoredIdentity, type FavoriteServer, type RecentServer } from "../services/local-persistence.js";
|
||||
import { applyTheme, getStoredTheme, isDarkTheme, nextTheme, saveTheme, type ThemeMode } from "../services/theme.js";
|
||||
import { combineTeamSpeakTarget, DEFAULT_TEAM_SPEAK_PORT, isValidTeamSpeakPort, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
|
||||
interface TreeChannel extends ChannelInfo {
|
||||
@@ -307,6 +314,10 @@ const {
|
||||
setWhisperTargets,
|
||||
setWhisperActive,
|
||||
setMicrophoneMuted,
|
||||
accompanimentActive,
|
||||
accompanimentErrorCode,
|
||||
startAccompaniment,
|
||||
stopAccompaniment,
|
||||
checkSupport,
|
||||
clearError,
|
||||
} = useVoiceWebSocket();
|
||||
@@ -338,6 +349,7 @@ const audioSettingsError = ref("");
|
||||
const toast = ref("");
|
||||
const chatListEl = ref<HTMLElement | null>(null);
|
||||
const localPersistenceAvailable = isLocalPersistenceAvailable();
|
||||
const identityReady = ref(!localPersistenceAvailable);
|
||||
const chatTab = ref<"channel" | "server" | "private" | "events">("channel");
|
||||
const privateClientId = ref(0);
|
||||
const away = ref(false);
|
||||
@@ -351,13 +363,16 @@ let toastTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
type Language = "zh" | "en";
|
||||
const language = ref<Language>(getInitialLanguage());
|
||||
const themeMode = ref<ThemeMode>(getStoredTheme());
|
||||
const themeLabel = computed(() => themeMode.value === "dark" ? t("themeDark") : themeMode.value === "light" ? t("themeLight") : t("themeSystem"));
|
||||
const themeIcon = computed(() => isDarkTheme(themeMode.value) ? "sun" : "moon");
|
||||
const themeLabel = computed(() => isDarkTheme(themeMode.value) ? t("switchToLightTheme") : t("switchToDarkTheme"));
|
||||
applyTheme(themeMode.value);
|
||||
const translations: Record<Language, Record<string, string>> = {
|
||||
zh: {
|
||||
themeSystem: "跟随系统",
|
||||
themeLight: "浅色主题",
|
||||
themeDark: "深色主题",
|
||||
switchToLightTheme: "切换到浅色主题",
|
||||
switchToDarkTheme: "切换到深色主题",
|
||||
browserWorkspace: "浏览器语音工作台",
|
||||
secureGateway: "安全语音网关",
|
||||
adminConsole: "管理控制台",
|
||||
@@ -393,6 +408,7 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
emptyDefault: "留空进入默认频道",
|
||||
rememberIdentity: "记住此设备的 TeamSpeak 身份",
|
||||
rememberIdentityHint: "仅保存在本设备,用于下次连接时保持身份。",
|
||||
rememberIdentityConcurrentWarning: "同一浏览器只能同时使用一条保持身份的连接;要开启第二条,请取消勾选或使用另一个浏览器。",
|
||||
identityOptions: "设备身份选项",
|
||||
localPersistenceUnavailable: "当前浏览器无法使用持久化存储,本次将使用临时身份。",
|
||||
favoriteServers: "常用服务器",
|
||||
@@ -421,6 +437,16 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
serverOptions: "更多服务器选项",
|
||||
online: "在线",
|
||||
audioSettings: "音频设置",
|
||||
desktopAudioControls: "音频控制",
|
||||
startAccompaniment: "共享伴奏",
|
||||
stopAccompaniment: "停止伴奏",
|
||||
accompanimentStarted: "伴奏共享已开始",
|
||||
accompanimentStopped: "伴奏共享已停止",
|
||||
accompanimentActive: "伴奏共享中",
|
||||
accompanimentNeedsWebRtc: "伴奏功能需要启用 WebRTC",
|
||||
accompanimentNoAudio: "所选来源没有可共享音频,请重新选择并勾选共享音频",
|
||||
accompanimentPermissionDenied: "无法获取伴奏音频,请允许屏幕共享并勾选共享音频",
|
||||
accompanimentUnsupported: "当前浏览器不支持伴奏共享",
|
||||
serverPassword: "服务器密码",
|
||||
optionalPassword: "没有密码可留空",
|
||||
switchChannel: "切换频道",
|
||||
@@ -576,6 +602,8 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
themeSystem: "System theme",
|
||||
themeLight: "Light theme",
|
||||
themeDark: "Dark theme",
|
||||
switchToLightTheme: "Switch to light theme",
|
||||
switchToDarkTheme: "Switch to dark theme",
|
||||
browserWorkspace: "Browser voice workspace",
|
||||
secureGateway: "Secure voice gateway",
|
||||
adminConsole: "Admin console",
|
||||
@@ -611,6 +639,7 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
emptyDefault: "Leave empty to use the default channel",
|
||||
rememberIdentity: "Remember this TeamSpeak identity on this device",
|
||||
rememberIdentityHint: "Stored only on this device and reused on the next connection.",
|
||||
rememberIdentityConcurrentWarning: "Only one connection can use this identity in the same browser. Clear this option for a second connection or use another browser.",
|
||||
identityOptions: "Device identity options",
|
||||
localPersistenceUnavailable: "Persistent browser storage is unavailable; this session will use an ephemeral identity.",
|
||||
favoriteServers: "Favorites",
|
||||
@@ -639,6 +668,16 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
serverOptions: "More server options",
|
||||
online: "Online",
|
||||
audioSettings: "Audio settings",
|
||||
desktopAudioControls: "Audio controls",
|
||||
startAccompaniment: "Share accompaniment",
|
||||
stopAccompaniment: "Stop accompaniment",
|
||||
accompanimentStarted: "Accompaniment sharing started",
|
||||
accompanimentStopped: "Accompaniment sharing stopped",
|
||||
accompanimentActive: "Accompaniment sharing",
|
||||
accompanimentNeedsWebRtc: "Accompaniment requires WebRTC",
|
||||
accompanimentNoAudio: "The selected source has no shareable audio. Select it again and enable audio sharing",
|
||||
accompanimentPermissionDenied: "Could not access accompaniment audio. Allow screen sharing and enable audio sharing",
|
||||
accompanimentUnsupported: "This browser does not support accompaniment sharing",
|
||||
serverPassword: "Server password",
|
||||
optionalPassword: "Leave blank if not required",
|
||||
switchChannel: "Switch channel",
|
||||
@@ -824,6 +863,7 @@ function localizedMessage(message: string) {
|
||||
"连接服务器失败,请检查邀请链接或服务器状态": "Could not connect. Check the invite link or server status",
|
||||
"TeamSpeak 连接已断开": "The TeamSpeak connection was closed",
|
||||
"连接已断开": "The connection was closed",
|
||||
"此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试": "This TeamSpeak identity is already used by another browser page. Close that connection or clear ‘Remember identity’ and try again",
|
||||
"TeamSpeak 服务器地址无效": "The TeamSpeak server address is invalid",
|
||||
"TeamSpeak 服务器连接失败": "Could not connect to the TeamSpeak server",
|
||||
"服务器当前已满,请稍后重试": "The server is full. Try again shortly",
|
||||
@@ -984,7 +1024,10 @@ watch(settingsOpen, (open) => {
|
||||
});
|
||||
watch(rememberIdentity, (remember) => {
|
||||
localStorage.setItem("webspeak:remember-identity", remember ? "1" : "0");
|
||||
if (!remember) identityMaterial.value = "";
|
||||
if (!remember) {
|
||||
identityMaterial.value = "";
|
||||
void removeStoredIdentity();
|
||||
}
|
||||
});
|
||||
watch([rememberIdentity, identityMaterial], ([remember, material]) => {
|
||||
if (remember && material) void saveStoredIdentity(material);
|
||||
@@ -1029,10 +1072,12 @@ onMounted(() => {
|
||||
}
|
||||
});
|
||||
void loadStoredIdentity().then((stored) => {
|
||||
if (stored) {
|
||||
if (stored && localStorage.getItem("webspeak:remember-identity") === "1") {
|
||||
identityMaterial.value = stored.privateMaterial;
|
||||
rememberIdentity.value = true;
|
||||
}
|
||||
}).finally(() => {
|
||||
identityReady.value = true;
|
||||
});
|
||||
void listFavorites().then((items) => { favoriteServers.value = items; });
|
||||
void listRecentServers().then((items) => { recentServers.value = items; });
|
||||
@@ -1042,6 +1087,7 @@ onMounted(() => {
|
||||
viewportChangeHandler = () => {
|
||||
isMobileViewport.value = viewportMediaQuery?.matches ?? false;
|
||||
if (!isMobileViewport.value) memberMenu.value = null;
|
||||
else if (accompanimentActive.value) void stopAccompaniment();
|
||||
};
|
||||
viewportChangeHandler();
|
||||
viewportMediaQuery.addEventListener?.("change", viewportChangeHandler);
|
||||
@@ -1350,6 +1396,27 @@ function toggleMicrophone(): void {
|
||||
showToast(microphoneMuted.value ? t("microphoneMuted") : t("microphoneActive"));
|
||||
}
|
||||
|
||||
async function toggleAccompaniment(): Promise<void> {
|
||||
try {
|
||||
if (accompanimentActive.value) {
|
||||
await stopAccompaniment();
|
||||
showToast(t("accompanimentStopped"));
|
||||
return;
|
||||
}
|
||||
await startAccompaniment();
|
||||
if (accompanimentActive.value) showToast(t("accompanimentStarted"));
|
||||
} catch {
|
||||
const messageKey = accompanimentErrorCode.value === "needsWebRtc"
|
||||
? "accompanimentNeedsWebRtc"
|
||||
: accompanimentErrorCode.value === "noAudio"
|
||||
? "accompanimentNoAudio"
|
||||
: accompanimentErrorCode.value === "unsupported"
|
||||
? "accompanimentUnsupported"
|
||||
: "accompanimentPermissionDenied";
|
||||
showToast(t(messageKey));
|
||||
}
|
||||
}
|
||||
|
||||
function onWhisperPttDown(event: PointerEvent): void {
|
||||
if (!whisperTargetIds.size) return;
|
||||
const target = event.currentTarget as HTMLElement | null;
|
||||
@@ -1529,6 +1596,7 @@ function stopWhisperTalk(): void {
|
||||
.remember-identity strong, .remember-identity small { display: block; }
|
||||
.remember-identity strong { font-size: 11px; font-weight: 700; }
|
||||
.remember-identity small { margin-top: 3px; color: #8b9994; font-size: 10px; line-height: 1.4; }
|
||||
.identity-warning { margin: 8px 0 0; color: #9a6a32; font-size: 10px; line-height: 1.45; }
|
||||
.local-servers { display: grid; gap: 8px; margin: 1px 0 5px; }
|
||||
.local-server-group { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; }
|
||||
.local-server-group > span { width: 100%; color: #87958f; font-size: 10px; font-weight: 700; }
|
||||
@@ -1625,8 +1693,9 @@ function stopWhisperTalk(): void {
|
||||
.app-shell { grid-template-rows: minmax(0, 1fr) 220px; }
|
||||
}
|
||||
|
||||
/* Keep connected controls in the header; the old bottom dock consumed the
|
||||
chat viewport and made the settings action appear detached from its icon. */
|
||||
/* Desktop audio controls live in the member rail so the workspace header
|
||||
stays focused on navigation. Mobile keeps its existing controls below the
|
||||
voice cards and in the More panel. */
|
||||
.header-tools { align-items: center; }
|
||||
.header-action, .round-icon { line-height: 0; }
|
||||
.guide-button { display: inline-flex; align-items: center; gap: 6px; min-height: 30px; padding: 0 10px; color: #006a64; background: #edf7f4; border: 1px solid #d7ebe6; border-radius: 8px; font-size: 12px; font-weight: 700; text-decoration: none; cursor: pointer; }
|
||||
@@ -1634,6 +1703,15 @@ function stopWhisperTalk(): void {
|
||||
.workspace-actions { align-items: center; flex-wrap: nowrap; }
|
||||
.workspace-actions .header-action { flex: 0 0 34px; padding: 0; line-height: 0; }
|
||||
.workspace-actions .header-action .ui-icon { margin: 0; }
|
||||
.desktop-audio-dock { display: flex; align-items: center; gap: 9px; flex: 0 0 auto; min-width: 0; margin-top: 12px; padding: 9px; color: var(--text-muted); background: color-mix(in srgb, var(--accent) 8%, var(--surface-1)); border: 1px solid var(--border); border-radius: 12px; box-shadow: 0 8px 20px color-mix(in srgb, var(--text-primary) 10%, transparent); }
|
||||
.desktop-audio-dock-copy { display: flex; min-width: 0; flex: 1; flex-direction: column; gap: 3px; }
|
||||
.desktop-audio-dock-copy strong { overflow: hidden; color: var(--text-primary); font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.desktop-audio-dock-copy span { overflow: hidden; font-size: 10px; line-height: 1.35; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.desktop-audio-dock-actions { display: flex; align-items: center; gap: 4px; flex: 0 0 auto; }
|
||||
.dock-audio-button { display: grid; place-items: center; width: 34px; height: 34px; padding: 0; color: var(--text-muted); background: transparent; border: 1px solid transparent; border-radius: 9px; cursor: pointer; transition: color .16s, background .16s, border-color .16s, transform .16s; }
|
||||
.dock-audio-button:hover, .dock-audio-button:focus-visible { color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, var(--surface-1)); border-color: color-mix(in srgb, var(--accent) 32%, var(--border)); transform: translateY(-1px); }
|
||||
.dock-audio-button.microphone-header-toggle.muted { color: var(--danger); background: color-mix(in srgb, var(--danger) 12%, var(--surface-1)); }
|
||||
.dock-audio-button.accompaniment-toggle.active { color: var(--accent); background: color-mix(in srgb, var(--accent) 18%, var(--surface-1)); border-color: color-mix(in srgb, var(--accent) 40%, var(--border)); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 12%, transparent); }
|
||||
.settings-mode-switch { width: fit-content; margin: 0 0 7px; }
|
||||
.settings-hint { margin: -1px 0 19px; color: #8b9994; font-size: 11px; }
|
||||
|
||||
@@ -1858,7 +1936,7 @@ function stopWhisperTalk(): void {
|
||||
.member-presence { width: 10px; height: 10px; }
|
||||
.member-copy strong { font-size: 14px; }
|
||||
.member-copy span { margin-top: 3px; font-size: 12px; }
|
||||
.member-flags, .member-volume, .member-panel-tip { display: none; }
|
||||
.desktop-audio-dock, .member-flags, .member-volume, .member-panel-tip { display: none; }
|
||||
.member-action-button { display: grid; place-items: center; width: 38px; height: 38px; flex: 0 0 38px; color: var(--text-muted); background: transparent; border-radius: 10px; cursor: pointer; }
|
||||
.member-action-button:hover, .member-action-button:active { color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, var(--surface-1)); }
|
||||
|
||||
|
||||
Reference in new issue
Block a user