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 |
No files matched your search
@@ -1,5 +1,19 @@
|
||||
# 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
|
||||
|
||||
### 中文
|
||||
|
||||
@@ -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.5)
|
||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.1.6)
|
||||
[](LICENSE)
|
||||
[](https://www.teamspeak.com/)
|
||||
|
||||
@@ -129,6 +133,12 @@ sudo ufw allow 40000:40099/udp
|
||||
|
||||
完整记录见 [`CHANGELOG.md`](CHANGELOG.md)。
|
||||
|
||||
#### 2026-09-04 · v0.1.6
|
||||
|
||||
- 新增保持身份并发连接提醒。
|
||||
- 新增桌面端伴奏共享功能。
|
||||
- 新增网站 favicon,并更新仓库 README 主视觉。
|
||||
|
||||
#### 2026-09-04 · v0.1.5
|
||||
|
||||
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
|
||||
@@ -292,6 +302,12 @@ 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.
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@discordjs/opus": "^0.10.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "webspeak-webclient",
|
||||
"version": "0.1.5",
|
||||
"version": "0.1.6",
|
||||
"private": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
|
||||
@@ -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'">
|
||||
|
||||
@@ -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,6 +1138,7 @@ export function useVoiceWebSocket() {
|
||||
if (code === 4002) return "TeamSpeak 服务器地址无效";
|
||||
if (code === 4003) return "TeamSpeak 服务器连接失败";
|
||||
if (code === 4004) return "服务器当前已满,请稍后重试";
|
||||
if (code === 4005) return "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试";
|
||||
return "连接已断开";
|
||||
}
|
||||
|
||||
@@ -1248,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));
|
||||
}
|
||||
@@ -1341,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();
|
||||
@@ -1365,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: "请先选择私语目标",
|
||||
@@ -1389,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();
|
||||
}
|
||||
|
||||
@@ -1434,7 +1531,6 @@ export function useVoiceWebSocket() {
|
||||
outputDeviceSupported,
|
||||
audioPermission,
|
||||
audioContextState,
|
||||
audioDiagnostics,
|
||||
identityMaterial,
|
||||
micLevel,
|
||||
microphoneTestActive,
|
||||
@@ -1443,6 +1539,9 @@ export function useVoiceWebSocket() {
|
||||
whisperTargetIds,
|
||||
whisperActive,
|
||||
volumes,
|
||||
accompanimentActive,
|
||||
accompanimentSupported,
|
||||
accompanimentErrorCode,
|
||||
setVolume,
|
||||
setInputVolume,
|
||||
setOutputVolume,
|
||||
@@ -1467,6 +1566,8 @@ export function useVoiceWebSocket() {
|
||||
setWhisperTargets,
|
||||
setWhisperActive,
|
||||
setMicrophoneMuted,
|
||||
startAccompaniment,
|
||||
stopAccompaniment,
|
||||
checkSupport,
|
||||
clearError,
|
||||
};
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
<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 || !identityReady || voiceState.connecting" type="submit">
|
||||
<span v-if="voiceState.connecting" class="button-spinner"></span>
|
||||
@@ -95,8 +95,8 @@
|
||||
</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 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>
|
||||
@@ -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">
|
||||
@@ -307,6 +314,10 @@ const {
|
||||
setWhisperTargets,
|
||||
setWhisperActive,
|
||||
setMicrophoneMuted,
|
||||
accompanimentActive,
|
||||
accompanimentErrorCode,
|
||||
startAccompaniment,
|
||||
stopAccompaniment,
|
||||
checkSupport,
|
||||
clearError,
|
||||
} = useVoiceWebSocket();
|
||||
@@ -397,6 +408,7 @@ const translations: Record<Language, Record<string, string>> = {
|
||||
emptyDefault: "留空进入默认频道",
|
||||
rememberIdentity: "记住此设备的 TeamSpeak 身份",
|
||||
rememberIdentityHint: "仅保存在本设备,用于下次连接时保持身份。",
|
||||
rememberIdentityConcurrentWarning: "同一浏览器只能同时使用一条保持身份的连接;要开启第二条,请取消勾选或使用另一个浏览器。",
|
||||
identityOptions: "设备身份选项",
|
||||
localPersistenceUnavailable: "当前浏览器无法使用持久化存储,本次将使用临时身份。",
|
||||
favoriteServers: "常用服务器",
|
||||
@@ -425,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: "切换频道",
|
||||
@@ -617,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",
|
||||
@@ -645,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",
|
||||
@@ -830,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",
|
||||
@@ -1053,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);
|
||||
@@ -1361,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;
|
||||
@@ -1540,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; }
|
||||
@@ -1636,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; }
|
||||
@@ -1645,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; }
|
||||
|
||||
@@ -1869,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