mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 20:12:52 +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
|
# 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
|
## [0.1.5] — 2026-09-04
|
||||||
|
|
||||||
### 中文
|
### 中文
|
||||||
|
|||||||
@@ -2,6 +2,10 @@
|
|||||||
|
|
||||||
# WebSpeak
|
# WebSpeak
|
||||||
|
|
||||||
|
<p>
|
||||||
|
<img src="./仓库图标.png" alt="WebSpeak" width="220">
|
||||||
|
</p>
|
||||||
|
|
||||||
**让 TeamSpeak 真正进入浏览器。**
|
**让 TeamSpeak 真正进入浏览器。**
|
||||||
|
|
||||||
自托管的 TeamSpeak 3 / TeamSpeak 6 网页客户端。打开网页即可加入语音、查看频道、发送消息,无需安装桌面客户端。
|
自托管的 TeamSpeak 3 / TeamSpeak 6 网页客户端。打开网页即可加入语音、查看频道、发送消息,无需安装桌面客户端。
|
||||||
@@ -9,7 +13,7 @@
|
|||||||
**在线体验:[webspeak.example.invalid](https://webspeak.example.invalid)**
|
**在线体验:[webspeak.example.invalid](https://webspeak.example.invalid)**
|
||||||
|
|
||||||
[](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak)
|
[](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)
|
[](LICENSE)
|
||||||
[](https://www.teamspeak.com/)
|
[](https://www.teamspeak.com/)
|
||||||
|
|
||||||
@@ -129,6 +133,12 @@ sudo ufw allow 40000:40099/udp
|
|||||||
|
|
||||||
完整记录见 [`CHANGELOG.md`](CHANGELOG.md)。
|
完整记录见 [`CHANGELOG.md`](CHANGELOG.md)。
|
||||||
|
|
||||||
|
#### 2026-09-04 · v0.1.6
|
||||||
|
|
||||||
|
- 新增保持身份并发连接提醒。
|
||||||
|
- 新增桌面端伴奏共享功能。
|
||||||
|
- 新增网站 favicon,并更新仓库 README 主视觉。
|
||||||
|
|
||||||
#### 2026-09-04 · v0.1.5
|
#### 2026-09-04 · v0.1.5
|
||||||
|
|
||||||
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
|
- 修复并优化主题切换按钮,首次点击即可切换,并使用太阳/月亮图标。
|
||||||
@@ -292,6 +302,12 @@ The admin console can:
|
|||||||
|
|
||||||
See [`CHANGELOG.md`](CHANGELOG.md) for the complete release history.
|
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
|
#### 2026-09-04 · v0.1.5
|
||||||
|
|
||||||
- Fixed and refined the theme toggle so the first click switches themes, with sun/moon icons.
|
- 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",
|
"name": "webspeak-webclient",
|
||||||
"version": "0.1.5",
|
"version": "0.1.6",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "webspeak-webclient",
|
"name": "webspeak-webclient",
|
||||||
"version": "0.1.5",
|
"version": "0.1.6",
|
||||||
"license": "AGPL-3.0-only",
|
"license": "AGPL-3.0-only",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@discordjs/opus": "^0.10.0",
|
"@discordjs/opus": "^0.10.0",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "webspeak-webclient",
|
"name": "webspeak-webclient",
|
||||||
"version": "0.1.5",
|
"version": "0.1.6",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "AGPL-3.0-only",
|
"license": "AGPL-3.0-only",
|
||||||
"type": "module",
|
"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 { TSClient, type TSDirectorySnapshot, type TSVoiceData } from "./ts-client.js";
|
||||||
import type { Logger as LoggerType } from "../logger.js";
|
import type { Logger as LoggerType } from "../logger.js";
|
||||||
import { normalizeTeamSpeakError } from "../errors.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 { JoinTicketStore, type JoinTicketPayload } from "./join-ticket.js";
|
||||||
|
import { IdentityLeaseStore } from "./identity-lease.js";
|
||||||
import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js";
|
import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js";
|
||||||
import { parseClientCommand, type ClientCommand } from "./voice-protocol.js";
|
import { parseClientCommand, type ClientCommand } from "./voice-protocol.js";
|
||||||
import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.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 require = createRequire(import.meta.url);
|
||||||
const { OpusEncoder } = require("@discordjs/opus") as {
|
const { OpusEncoder } = require("@discordjs/opus") as {
|
||||||
@@ -72,6 +73,24 @@ export interface AudioFlowStats {
|
|||||||
egressSentMaxGapMs: number;
|
egressSentMaxGapMs: number;
|
||||||
egressPeakBufferedBytes: number;
|
egressPeakBufferedBytes: number;
|
||||||
egressFramesByClient: Record<string, 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 {
|
interface ChannelMember {
|
||||||
@@ -100,6 +119,7 @@ interface WebClientEntry {
|
|||||||
nickname: string;
|
nickname: string;
|
||||||
rememberIdentity: boolean;
|
rememberIdentity: boolean;
|
||||||
target: TeamSpeakTarget;
|
target: TeamSpeakTarget;
|
||||||
|
identityLeaseKey?: string;
|
||||||
webrtcPublicHost?: string;
|
webrtcPublicHost?: string;
|
||||||
channelTree: unknown[];
|
channelTree: unknown[];
|
||||||
members: Map<number, ChannelMember>;
|
members: Map<number, ChannelMember>;
|
||||||
@@ -116,6 +136,7 @@ interface WebClientEntry {
|
|||||||
export class VoiceBridge {
|
export class VoiceBridge {
|
||||||
private readonly sessionManager = new SessionManager();
|
private readonly sessionManager = new SessionManager();
|
||||||
private readonly entries = new Map<string, WebClientEntry>();
|
private readonly entries = new Map<string, WebClientEntry>();
|
||||||
|
private readonly identityLeases = new IdentityLeaseStore();
|
||||||
private wss: WebSocketServer | null = null;
|
private wss: WebSocketServer | null = null;
|
||||||
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
private logger: LoggerType;
|
private logger: LoggerType;
|
||||||
@@ -160,11 +181,22 @@ export class VoiceBridge {
|
|||||||
return;
|
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");
|
this.logger.info({ entryId, nickname, channel: channelName, target: formatTeamSpeakTarget(target) }, "WebClient connecting");
|
||||||
let tsClient: TSClient;
|
let tsClient: TSClient;
|
||||||
try {
|
try {
|
||||||
tsClient = new TSClient({ target, nickname, serverPassword, defaultChannel: channelName, identity }, this.logger);
|
tsClient = new TSClient({ target, nickname, serverPassword, defaultChannel: channelName, identity }, this.logger);
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
|
if (identityLeaseKey) this.identityLeases.release(identityLeaseKey, entryId);
|
||||||
this.logger.error({ err: error, entryId }, "Could not create TeamSpeak client");
|
this.logger.error({ err: error, entryId }, "Could not create TeamSpeak client");
|
||||||
void this.sessionManager.teardown(entryId, "teamSpeak-connect-failed");
|
void this.sessionManager.teardown(entryId, "teamSpeak-connect-failed");
|
||||||
ws.close(4003, "TeamSpeak client unavailable");
|
ws.close(4003, "TeamSpeak client unavailable");
|
||||||
@@ -178,6 +210,7 @@ export class VoiceBridge {
|
|||||||
nickname,
|
nickname,
|
||||||
rememberIdentity: connection.rememberIdentity === true,
|
rememberIdentity: connection.rememberIdentity === true,
|
||||||
target,
|
target,
|
||||||
|
...(identityLeaseKey ? { identityLeaseKey } : {}),
|
||||||
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
|
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
|
||||||
channelTree: [],
|
channelTree: [],
|
||||||
members: new Map(),
|
members: new Map(),
|
||||||
@@ -416,6 +449,7 @@ export class VoiceBridge {
|
|||||||
tsClient.on("clientLeave", (info) => {
|
tsClient.on("clientLeave", (info) => {
|
||||||
const wasKnown = entry!.members.has(info.id);
|
const wasKnown = entry!.members.has(info.id);
|
||||||
const leavingMember = entry!.members.get(info.id);
|
const leavingMember = entry!.members.get(info.id);
|
||||||
|
entry!.webrtc?.setMemberVolume(info.id, 1);
|
||||||
directory.applyClientLeave(info.id);
|
directory.applyClientLeave(info.id);
|
||||||
refreshDirectory();
|
refreshDirectory();
|
||||||
if (tsReady && initialStateSent && wasKnown) {
|
if (tsReady && initialStateSent && wasKnown) {
|
||||||
@@ -567,7 +601,11 @@ export class VoiceBridge {
|
|||||||
if (isWebRtcStopMessage(rawMessage)) {
|
if (isWebRtcStopMessage(rawMessage)) {
|
||||||
const webRtc = entry!.webrtc;
|
const webRtc = entry!.webrtc;
|
||||||
entry!.webrtc = null;
|
entry!.webrtc = null;
|
||||||
if (webRtc) void webRtc.close();
|
if (webRtc) {
|
||||||
|
void webRtc.close()
|
||||||
|
.then(() => Object.assign(entry!.audio, webRtc.getStats()))
|
||||||
|
.catch(() => undefined);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const command = parseClientCommand(rawMessage);
|
const command = parseClientCommand(rawMessage);
|
||||||
@@ -658,7 +696,7 @@ export class VoiceBridge {
|
|||||||
tsClientId,
|
tsClientId,
|
||||||
channelId,
|
channelId,
|
||||||
memberCount: entry.members.size,
|
memberCount: entry.members.size,
|
||||||
audio: { ...entry.audio },
|
audio: snapshotAudioStats(entry),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -684,6 +722,7 @@ export class VoiceBridge {
|
|||||||
entry.webrtc = null;
|
entry.webrtc = null;
|
||||||
if (webRtc) {
|
if (webRtc) {
|
||||||
try { await webRtc.close(); } catch { /* peer teardown is idempotent */ }
|
try { await webRtc.close(); } catch { /* peer teardown is idempotent */ }
|
||||||
|
Object.assign(entry.audio, webRtc.getStats());
|
||||||
}
|
}
|
||||||
entry.whisperTargetIds.clear();
|
entry.whisperTargetIds.clear();
|
||||||
entry.whisperActive = false;
|
entry.whisperActive = false;
|
||||||
@@ -696,6 +735,7 @@ export class VoiceBridge {
|
|||||||
if (reason === "heartbeat-timeout" || reason === "gateway-shutdown") entry.ws.terminate();
|
if (reason === "heartbeat-timeout" || reason === "gateway-shutdown") entry.ws.terminate();
|
||||||
else entry.ws.close(reason === "protocol-error" ? 1008 : 1000, reason);
|
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");
|
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,
|
sendJson: (message: Record<string, unknown>) => void,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (entry.webrtc) {
|
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;
|
entry.webrtc = null;
|
||||||
}
|
}
|
||||||
const config = this.getWebRtcOptions();
|
const config = this.getWebRtcOptions();
|
||||||
@@ -743,16 +785,23 @@ export class VoiceBridge {
|
|||||||
udpPortRange: config.udpPortRange,
|
udpPortRange: config.udpPortRange,
|
||||||
logger: this.logger,
|
logger: this.logger,
|
||||||
microphoneMuted: offer.muted === true,
|
microphoneMuted: offer.muted === true,
|
||||||
onVoiceFrame: (data) => {
|
accompanimentActive: offer.accompanimentActive === true,
|
||||||
|
onVoiceFrame: (data, codec) => {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (entry.audio.ingressLastAt !== null) entry.audio.ingressMaxGapMs = Math.max(entry.audio.ingressMaxGapMs, now - entry.audio.ingressLastAt);
|
if (entry.audio.ingressLastAt !== null) entry.audio.ingressMaxGapMs = Math.max(entry.audio.ingressMaxGapMs, now - entry.audio.ingressLastAt);
|
||||||
entry.audio.ingressFirstAt ??= now;
|
entry.audio.ingressFirstAt ??= now;
|
||||||
entry.audio.ingressLastAt = now;
|
entry.audio.ingressLastAt = now;
|
||||||
entry.audio.ingressFrames++;
|
entry.audio.ingressFrames++;
|
||||||
try {
|
try {
|
||||||
if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], 4);
|
if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], codec);
|
||||||
else entry.tsClient.sendVoice(data, 4);
|
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 {
|
} catch {
|
||||||
|
entry.audio.tsSendErrors++;
|
||||||
// A packet arriving while the TeamSpeak session is being replaced
|
// A packet arriving while the TeamSpeak session is being replaced
|
||||||
// is discarded; the WebRTC peer remains independently closable.
|
// is discarded; the WebRTC peer remains independently closable.
|
||||||
}
|
}
|
||||||
@@ -872,6 +921,11 @@ async function handleCommand(
|
|||||||
sendJson({ type: "whisperTargets", targetIds: [...entry.whisperTargetIds], active: entry.whisperActive });
|
sendJson({ type: "whisperTargets", targetIds: [...entry.whisperTargetIds], active: entry.whisperActive });
|
||||||
} else if (command.type === "setMicrophoneMuted") {
|
} else if (command.type === "setMicrophoneMuted") {
|
||||||
entry.webrtc?.setMicrophoneMuted(command.payload.muted as boolean);
|
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 });
|
if (command.requestId) sendJson({ type: "commandCompleted", requestId: command.requestId });
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
@@ -902,7 +956,13 @@ function parseWebRtcOffer(raw: string): WebRtcSessionDescription | null {
|
|||||||
const description = value.payload.sdp;
|
const description = value.payload.sdp;
|
||||||
if (description.type !== "offer" || typeof description.sdp !== "string" || description.sdp.length > 256 * 1024) return null;
|
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;
|
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 {
|
function isWebRtcStopMessage(raw: string): boolean {
|
||||||
@@ -949,9 +1009,34 @@ function createAudioFlowStats(): AudioFlowStats {
|
|||||||
egressSentMaxGapMs: 0,
|
egressSentMaxGapMs: 0,
|
||||||
egressPeakBufferedBytes: 0,
|
egressPeakBufferedBytes: 0,
|
||||||
egressFramesByClient: {},
|
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[] {
|
function mapChannelTree(snapshot: TSDirectorySnapshot): unknown[] {
|
||||||
return snapshot.channels.map((channel) => ({
|
return snapshot.channels.map((channel) => ({
|
||||||
id: String(channel.id),
|
id: String(channel.id),
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
export interface ClientCommand {
|
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;
|
requestId?: string;
|
||||||
payload: Record<string, unknown>;
|
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)) {
|
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
|
||||||
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
|
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)) {
|
if (!supportedTypes.has(value.type)) {
|
||||||
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
|
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") {
|
if (value.type === "setMicrophoneMuted" && typeof value.payload.muted !== "boolean") {
|
||||||
return { error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" } };
|
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 {
|
return {
|
||||||
type: value.type as ClientCommand["type"],
|
type: value.type as ClientCommand["type"],
|
||||||
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
|
...(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 DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
|
||||||
const AUDIO_CLOCK_INTERVAL_MS = 20;
|
const AUDIO_CLOCK_INTERVAL_MS = 20;
|
||||||
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
|
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
|
// 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"
|
// 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.
|
// indicator or forward them to TeamSpeak as if they were voice.
|
||||||
const MIN_SPEAKER_RMS = 160;
|
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
|
// WebRTC is served by the WebSpeak process itself. The default range is also
|
||||||
// published by the bundled Docker Compose file; advanced administrators can
|
// published by the bundled Docker Compose file; advanced administrators can
|
||||||
@@ -43,6 +50,7 @@ export interface WebRtcSessionDescription {
|
|||||||
type: "offer" | "answer";
|
type: "offer" | "answer";
|
||||||
sdp: string;
|
sdp: string;
|
||||||
muted?: boolean;
|
muted?: boolean;
|
||||||
|
accompanimentActive?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WebRtcAudioSessionOptions {
|
export interface WebRtcAudioSessionOptions {
|
||||||
@@ -51,45 +59,105 @@ export interface WebRtcAudioSessionOptions {
|
|||||||
udpPortRange?: [number, number];
|
udpPortRange?: [number, number];
|
||||||
logger: LoggerType;
|
logger: LoggerType;
|
||||||
microphoneMuted?: boolean;
|
microphoneMuted?: boolean;
|
||||||
onVoiceFrame: (data: Buffer) => void;
|
accompanimentActive?: boolean;
|
||||||
|
onVoiceFrame: (data: Buffer, codec: 4 | 5) => void;
|
||||||
onVoiceActivity: (clientIds: number[]) => 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.
|
* One low-latency WebRTC audio session for one browser connection.
|
||||||
*
|
*
|
||||||
* TeamSpeak provides one Opus payload per speaker. WebRTC has one negotiated
|
* TeamSpeak provides one Opus payload per speaker. WebRTC has one negotiated
|
||||||
* audio track in this first transport, so this class mixes only the newest
|
* audio track in this first transport, so this class mixes one 20 ms frame
|
||||||
* 20 ms frame from each active speaker and packetizes the result as RTP. The
|
* from each active speaker and packetizes the result as RTP. Each speaker has
|
||||||
* map is deliberately bounded to one frame per speaker; an old frame is
|
* a very small bounded queue so bursts from the TeamSpeak adapter can be
|
||||||
* replaced instead of becoming a playback queue.
|
* smoothed without turning into an ever-growing playback delay.
|
||||||
*/
|
*/
|
||||||
export class WebRtcAudioSession {
|
export class WebRtcAudioSession {
|
||||||
readonly peer: RTCPeerConnection;
|
readonly peer: RTCPeerConnection;
|
||||||
private readonly logger: LoggerType;
|
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 onVoiceActivity: (clientIds: number[]) => void;
|
||||||
private readonly outgoingTrack: MediaStreamTrack;
|
private readonly outgoingTrack: MediaStreamTrack;
|
||||||
private ingressDecoder: { decode(data: Buffer): Buffer } | null = null;
|
private ingressDecoder: { decode(data: Buffer): Buffer } | null = null;
|
||||||
private readonly decoderByClient = new Map<number, { decode(data: Buffer): Buffer }>();
|
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 activeSpeakerIds = new Set<number>();
|
||||||
private readonly opusPayloadTypes = 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 readonly activityTimer: ReturnType<typeof setInterval>;
|
||||||
private encoder: { encode(data: Buffer): Buffer } | null;
|
private encoder: { encode(data: Buffer): Buffer } | null;
|
||||||
private microphoneMuted: boolean;
|
|
||||||
private sequenceNumber = randomInt(0, 65_536);
|
private sequenceNumber = randomInt(0, 65_536);
|
||||||
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
|
private timestamp = randomInt(0, 0x1_0000_0000) >>> 0;
|
||||||
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
|
private readonly ssrc = randomInt(1, 0x1_0000_0000) >>> 0;
|
||||||
private outgoingPayloadType = DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE;
|
private outgoingPayloadType = DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE;
|
||||||
private closed = false;
|
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) {
|
constructor(options: WebRtcAudioSessionOptions) {
|
||||||
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
|
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
|
||||||
this.onVoiceFrame = options.onVoiceFrame;
|
this.onVoiceFrame = options.onVoiceFrame;
|
||||||
this.onVoiceActivity = options.onVoiceActivity;
|
this.onVoiceActivity = options.onVoiceActivity;
|
||||||
this.microphoneMuted = options.microphoneMuted === true;
|
this.accompanimentActive = options.accompanimentActive === true;
|
||||||
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
|
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
|
||||||
|
|
||||||
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
|
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
|
||||||
@@ -106,14 +174,27 @@ export class WebRtcAudioSession {
|
|||||||
const audio = this.peer.addTransceiver("audio", { direction: "sendrecv" });
|
const audio = this.peer.addTransceiver("audio", { direction: "sendrecv" });
|
||||||
audio.onTrack.subscribe((track) => {
|
audio.onTrack.subscribe((track) => {
|
||||||
track.onReceiveRtp.subscribe((rtp) => {
|
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);
|
const payload = Buffer.from(rtp.payload);
|
||||||
// A disabled browser MediaStreamTrack normally still produces RTP
|
// The track is a browser-side mix of microphone and accompaniment.
|
||||||
// comfort-noise packets. TeamSpeak treats any received voice packet
|
// Decode it once to reject malformed RTP. A normal microphone still
|
||||||
// as activity, so enforce mute/VAD at this gateway boundary instead
|
// uses the low-level comfort-noise gate, while accompaniment must not
|
||||||
// of relying on the browser's local speaking indicator.
|
// be treated as speech: quiet music frames are valid audio and are
|
||||||
if (!this.hasVoiceEnergy(payload)) return;
|
// forwarded with TeamSpeak's music codec marker.
|
||||||
this.onVoiceFrame(payload);
|
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) => {
|
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");
|
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");
|
throw new Error("WebRTC Opus codec is unavailable");
|
||||||
}
|
}
|
||||||
|
|
||||||
this.audioTimer = setInterval(() => this.flushAudio(), AUDIO_CLOCK_INTERVAL_MS);
|
this.nextAudioDeadline = performance.now();
|
||||||
this.audioTimer.unref?.();
|
this.scheduleAudioTick();
|
||||||
this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS);
|
this.activityTimer = setInterval(() => this.flushSpeakerActivity(), SPEAKER_ACTIVITY_INTERVAL_MS);
|
||||||
this.activityTimer.unref?.();
|
this.activityTimer.unref?.();
|
||||||
this.peer.onconnectionstatechange = () => {
|
this.peer.onconnectionstatechange = () => {
|
||||||
@@ -148,6 +229,10 @@ export class WebRtcAudioSession {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getStats(): WebRtcAudioStats {
|
||||||
|
return { ...this.stats, webrtcQueueCurrentFrames: this.getQueueFrameCount() };
|
||||||
|
}
|
||||||
|
|
||||||
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
|
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
|
||||||
if (this.closed) throw new Error("WebRTC session is closed");
|
if (this.closed) throw new Error("WebRTC session is closed");
|
||||||
this.setOpusPayloadTypes(offer.sdp);
|
this.setOpusPayloadTypes(offer.sdp);
|
||||||
@@ -163,7 +248,7 @@ export class WebRtcAudioSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pushTeamSpeakVoice(data: TSVoiceData): void {
|
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);
|
let decoder = this.decoderByClient.get(data.clientId);
|
||||||
if (!decoder) {
|
if (!decoder) {
|
||||||
try {
|
try {
|
||||||
@@ -178,19 +263,53 @@ export class WebRtcAudioSession {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const pcm = decoder.decode(data.data);
|
const pcm = decoder.decode(data.data);
|
||||||
// Only advertise speaking after a valid TeamSpeak Opus frame has been
|
this.stats.webrtcDownlinkDecodedFrames++;
|
||||||
// decoded. Otherwise the UI can show activity while the mixer has no
|
if (pcm.length < 2) {
|
||||||
// audio to send, which is especially confusing on the WebRTC path.
|
this.stats.webrtcDownlinkShortFrames++;
|
||||||
if (pcm.length < AUDIO_FRAME_BYTES) return;
|
return;
|
||||||
let sum = 0;
|
}
|
||||||
for (let index = 0; index + 1 < AUDIO_FRAME_BYTES; index += 2) {
|
// TeamSpeak may deliver 10/20/40/60 ms Opus frames. Keep a partial
|
||||||
const sample = pcm.readInt16LE(index);
|
// decoded frame per speaker and split every decoded buffer into the
|
||||||
sum += sample * sample;
|
// 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 {
|
} catch {
|
||||||
|
this.stats.webrtcDownlinkDecodeErrors++;
|
||||||
// A malformed or codec-transition packet is discarded without touching
|
// A malformed or codec-transition packet is discarded without touching
|
||||||
// the peer connection. The next valid Opus frame can recover the stream.
|
// the peer connection. The next valid Opus frame can recover the stream.
|
||||||
}
|
}
|
||||||
@@ -199,9 +318,12 @@ export class WebRtcAudioSession {
|
|||||||
async close(): Promise<void> {
|
async close(): Promise<void> {
|
||||||
if (this.closed) return;
|
if (this.closed) return;
|
||||||
this.closed = true;
|
this.closed = true;
|
||||||
clearInterval(this.audioTimer);
|
if (this.audioTimer) clearTimeout(this.audioTimer);
|
||||||
|
this.audioTimer = null;
|
||||||
clearInterval(this.activityTimer);
|
clearInterval(this.activityTimer);
|
||||||
this.pendingFrames.clear();
|
this.pendingFrames.clear();
|
||||||
|
this.memberVolumes.clear();
|
||||||
|
this.partialPcmByClient.clear();
|
||||||
this.activeSpeakerIds.clear();
|
this.activeSpeakerIds.clear();
|
||||||
this.ingressDecoder = null;
|
this.ingressDecoder = null;
|
||||||
this.decoderByClient.clear();
|
this.decoderByClient.clear();
|
||||||
@@ -210,41 +332,91 @@ export class WebRtcAudioSession {
|
|||||||
await this.peer.close();
|
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 {
|
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);
|
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES);
|
||||||
let sourceCount = 0;
|
const selectedFrames: SelectedAudioFrame[] = [];
|
||||||
for (const pcm of this.pendingFrames.values()) {
|
for (const [clientId, queue] of this.pendingFrames) {
|
||||||
sourceCount++;
|
const frame = queue.shift();
|
||||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) mixed[index] += pcm.readInt16LE(index * 2);
|
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 pcm = Buffer.allocUnsafe(AUDIO_FRAME_BYTES);
|
||||||
const scale = 1 / Math.sqrt(sourceCount);
|
|
||||||
for (let index = 0; index < AUDIO_FRAME_SAMPLES; index++) {
|
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);
|
pcm.writeInt16LE(sample, index * 2);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const encoded = this.encoder.encode(pcm);
|
const encoded = this.encoder.encode(pcm);
|
||||||
const packet = new RtpPacket(new RtpHeader({
|
this.sendRtpAudio(encoded);
|
||||||
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);
|
|
||||||
} catch {
|
} catch {
|
||||||
// A peer closing concurrently may reject a packet; teardown owns the
|
// A peer closing concurrently may reject a packet; teardown owns the
|
||||||
// session lifecycle and no per-frame error needs to reach the logs.
|
// 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 {
|
private flushSpeakerActivity(): void {
|
||||||
if (this.closed || !this.activeSpeakerIds.size) return;
|
if (this.closed || !this.activeSpeakerIds.size) return;
|
||||||
const ids = [...this.activeSpeakerIds];
|
const ids = [...this.activeSpeakerIds];
|
||||||
@@ -253,28 +425,73 @@ export class WebRtcAudioSession {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setMicrophoneMuted(muted: boolean): void {
|
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;
|
const decoder = this.ingressDecoder;
|
||||||
if (!decoder) return false;
|
if (!decoder) return null;
|
||||||
try {
|
try {
|
||||||
const pcm = decoder.decode(data);
|
const pcm = decoder.decode(data);
|
||||||
if (pcm.length < AUDIO_FRAME_BYTES) return false;
|
if (pcm.length < 2) {
|
||||||
let sum = 0;
|
this.stats.webrtcIngressDecodeErrors++;
|
||||||
for (let index = 0; index + 1 < AUDIO_FRAME_BYTES; index += 2) {
|
return null;
|
||||||
const sample = pcm.readInt16LE(index);
|
|
||||||
sum += sample * sample;
|
|
||||||
}
|
}
|
||||||
return Math.sqrt(sum / AUDIO_FRAME_SAMPLES) >= MIN_SPEAKER_RMS;
|
return this.calculateRms(pcm);
|
||||||
} catch {
|
} catch {
|
||||||
// Malformed/transition packets are discarded without interrupting the
|
// Malformed/transition packets are discarded without interrupting the
|
||||||
// rest of the peer. The next valid Opus packet can recover the decoder.
|
// 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 {
|
private setOpusPayloadTypes(sdp: string): void {
|
||||||
this.opusPayloadTypes.clear();
|
this.opusPayloadTypes.clear();
|
||||||
for (const match of sdp.matchAll(/^a=rtpmap:(\d+)\s+opus\/48000(?:\/\d+)?/gim)) {
|
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: "麦克风状态无效" },
|
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="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<meta name="theme-color" content="#006a64" />
|
<meta name="theme-color" content="#006a64" />
|
||||||
<meta name="description" content="WebSpeak — TeamSpeak browser voice workspace" />
|
<meta name="description" content="WebSpeak — TeamSpeak browser voice workspace" />
|
||||||
|
<link rel="icon" type="image/jpeg" href="/网站图标.jpg" />
|
||||||
<title>WebSpeak · TeamSpeak Web Client</title>
|
<title>WebSpeak · TeamSpeak Web Client</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
@@ -31,7 +31,12 @@
|
|||||||
</template>
|
</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'" 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 === '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'" 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" />
|
<path v-else-if="name === 'volume-off'" d="m4 4 16 16M4 10v4h3l4 3V7l-4 3z" />
|
||||||
<template v-else-if="name === 'search'">
|
<template v-else-if="name === 'search'">
|
||||||
|
|||||||
@@ -109,6 +109,15 @@ export function useVoiceWebSocket() {
|
|||||||
let micSource: MediaStreamAudioSourceNode | null = null;
|
let micSource: MediaStreamAudioSourceNode | null = null;
|
||||||
let micGain: GainNode | null = null;
|
let micGain: GainNode | null = null;
|
||||||
let silentGain: 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 webrtcMicMonitorSource: MediaStreamAudioSourceNode | null = null;
|
||||||
let webrtcMicMonitorAnalyser: AnalyserNode | null = null;
|
let webrtcMicMonitorAnalyser: AnalyserNode | null = null;
|
||||||
let webrtcMicMonitorGain: GainNode | 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.
|
// for jitter; stale audio is discarded instead of being played late.
|
||||||
const MAX_REMOTE_PLAY_AHEAD_SECONDS = 0.08;
|
const MAX_REMOTE_PLAY_AHEAD_SECONDS = 0.08;
|
||||||
const MAX_REMOTE_DECODE_QUEUE_FRAMES = 3;
|
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> {
|
async function saveAudioPreferences(): Promise<void> {
|
||||||
await saveLocalPreferences({
|
await saveLocalPreferences({
|
||||||
@@ -418,11 +393,8 @@ export function useVoiceWebSocket() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const bufferedBytes = socket.bufferedAmount;
|
const bufferedBytes = socket.bufferedAmount;
|
||||||
audioCounters.peakBufferedBytes = Math.max(audioCounters.peakBufferedBytes, bufferedBytes);
|
|
||||||
if (bufferedBytes > MAX_AUDIO_BUFFERED_BYTES) {
|
if (bufferedBytes > MAX_AUDIO_BUFFERED_BYTES) {
|
||||||
accumLen = 0;
|
accumLen = 0;
|
||||||
audioCounters.uplinkDroppedFrames++;
|
|
||||||
publishAudioDiagnostics();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -441,8 +413,6 @@ export function useVoiceWebSocket() {
|
|||||||
while (offset + AUDIO_FRAME_SAMPLES <= accumLen && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= MAX_AUDIO_BUFFERED_BYTES) {
|
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);
|
socket.send(accumBuf.slice(offset, offset + AUDIO_FRAME_SAMPLES).buffer);
|
||||||
offset += AUDIO_FRAME_SAMPLES;
|
offset += AUDIO_FRAME_SAMPLES;
|
||||||
audioCounters.uplinkFrames++;
|
|
||||||
publishAudioDiagnostics();
|
|
||||||
}
|
}
|
||||||
if (offset > 0) markSpeaking(state.tsClientId);
|
if (offset > 0) markSpeaking(state.tsClientId);
|
||||||
accumLen -= offset;
|
accumLen -= offset;
|
||||||
@@ -514,19 +484,143 @@ export function useVoiceWebSocket() {
|
|||||||
return false;
|
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> {
|
async function startWebRtcTransport(sequence: number, socket: WebSocket): Promise<void> {
|
||||||
if (typeof RTCPeerConnection === "undefined") throw new Error("当前浏览器不支持 WebRTC");
|
if (typeof RTCPeerConnection === "undefined") throw new Error("当前浏览器不支持 WebRTC");
|
||||||
await ensureMicrophone();
|
await ensureMicrophone();
|
||||||
if (sequence !== connectionSequence || socket.readyState !== WebSocket.OPEN || !micStream) return;
|
if (sequence !== connectionSequence || socket.readyState !== WebSocket.OPEN || !micStream) return;
|
||||||
const track = micStream.getAudioTracks()[0];
|
const microphoneTrack = micStream.getAudioTracks()[0];
|
||||||
if (!track) throw new Error("没有可用的麦克风音轨");
|
if (!microphoneTrack) throw new Error("没有可用的麦克风音轨");
|
||||||
|
|
||||||
stopCaptureGraph();
|
stopCaptureGraph();
|
||||||
const peer = new RTCPeerConnection({ iceServers: [] });
|
const peer = new RTCPeerConnection({ iceServers: [] });
|
||||||
webrtcPeer = peer;
|
webrtcPeer = peer;
|
||||||
webrtcFallbackStarted = false;
|
webrtcFallbackStarted = false;
|
||||||
track.enabled = !microphoneMuted.value;
|
microphoneTrack.enabled = !microphoneMuted.value;
|
||||||
peer.addTrack(track, micStream);
|
const mixedStream = createWebRtcMixStream();
|
||||||
|
const mixedTrack = mixedStream.getAudioTracks()[0];
|
||||||
|
if (!mixedTrack) throw new Error("混合音频轨道创建失败");
|
||||||
|
peer.addTrack(mixedTrack, mixedStream);
|
||||||
peer.ontrack = (event) => {
|
peer.ontrack = (event) => {
|
||||||
const stream = event.streams[0] ?? new MediaStream([event.track]);
|
const stream = event.streams[0] ?? new MediaStream([event.track]);
|
||||||
// Use the browser's native WebRTC media output. Routing the remote
|
// Use the browser's native WebRTC media output. Routing the remote
|
||||||
@@ -556,7 +650,7 @@ export function useVoiceWebSocket() {
|
|||||||
}
|
}
|
||||||
void syncWebRtcPlayback();
|
void syncWebRtcPlayback();
|
||||||
};
|
};
|
||||||
startWebRtcMicMonitor(getAudioCtx(), micStream, track);
|
startWebRtcMicMonitor(getAudioCtx(), micStream, microphoneTrack);
|
||||||
peer.onconnectionstatechange = () => {
|
peer.onconnectionstatechange = () => {
|
||||||
if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket);
|
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;
|
if (sequence !== connectionSequence || webrtcPeer !== peer || socket.readyState !== WebSocket.OPEN) return;
|
||||||
const description = peer.localDescription;
|
const description = peer.localDescription;
|
||||||
if (!description) throw new Error("WebRTC offer was not created");
|
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(() => {
|
window.setTimeout(() => {
|
||||||
if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket);
|
if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket);
|
||||||
}, 8_000);
|
}, 8_000);
|
||||||
@@ -609,6 +707,7 @@ export function useVoiceWebSocket() {
|
|||||||
try {
|
try {
|
||||||
await webrtcPeer.setRemoteDescription(description);
|
await webrtcPeer.setRemoteDescription(description);
|
||||||
webrtcActive.value = true;
|
webrtcActive.value = true;
|
||||||
|
syncWebRtcMemberVolumes();
|
||||||
} catch {
|
} catch {
|
||||||
if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value);
|
if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value);
|
||||||
}
|
}
|
||||||
@@ -632,6 +731,8 @@ export function useVoiceWebSocket() {
|
|||||||
webrtcPeer = null;
|
webrtcPeer = null;
|
||||||
webrtcActive.value = false;
|
webrtcActive.value = false;
|
||||||
webrtcNegotiationPromise = null;
|
webrtcNegotiationPromise = null;
|
||||||
|
releaseAccompanimentStream();
|
||||||
|
stopWebRtcMix();
|
||||||
stopWebRtcMicMonitor();
|
stopWebRtcMicMonitor();
|
||||||
stopWebRtcPlayback();
|
stopWebRtcPlayback();
|
||||||
if (peer) void peer.close();
|
if (peer) void peer.close();
|
||||||
@@ -716,6 +817,8 @@ export function useVoiceWebSocket() {
|
|||||||
|
|
||||||
function stopMicrophone(closeContext = true): void {
|
function stopMicrophone(closeContext = true): void {
|
||||||
stopCaptureGraph();
|
stopCaptureGraph();
|
||||||
|
releaseAccompanimentStream();
|
||||||
|
stopWebRtcMix();
|
||||||
micStream?.getTracks().forEach((track) => track.stop());
|
micStream?.getTracks().forEach((track) => track.stop());
|
||||||
micStream = null;
|
micStream = null;
|
||||||
if (closeContext) {
|
if (closeContext) {
|
||||||
@@ -843,7 +946,6 @@ export function useVoiceWebSocket() {
|
|||||||
const now = ctx.currentTime;
|
const now = ctx.currentTime;
|
||||||
const scheduledUntil = remotePlayTimes.get(clientId) ?? now;
|
const scheduledUntil = remotePlayTimes.get(clientId) ?? now;
|
||||||
const decodeQueueSize = decoder?.decodeQueueSize ?? 0;
|
const decodeQueueSize = decoder?.decodeQueueSize ?? 0;
|
||||||
audioCounters.peakDecodeQueueFrames = Math.max(audioCounters.peakDecodeQueueFrames, decodeQueueSize);
|
|
||||||
if (
|
if (
|
||||||
decoder &&
|
decoder &&
|
||||||
(scheduledUntil > now + MAX_REMOTE_PLAY_AHEAD_SECONDS || decodeQueueSize >= MAX_REMOTE_DECODE_QUEUE_FRAMES)
|
(scheduledUntil > now + MAX_REMOTE_PLAY_AHEAD_SECONDS || decodeQueueSize >= MAX_REMOTE_DECODE_QUEUE_FRAMES)
|
||||||
@@ -866,8 +968,6 @@ export function useVoiceWebSocket() {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
|
const { sampleRate, numberOfChannels, numberOfFrames } = chunk;
|
||||||
audioCounters.decoderOutputFrames++;
|
|
||||||
audioCounters.lastDecodeOutputAt = Date.now();
|
|
||||||
const buffer = ctx.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
|
const buffer = ctx.createBuffer(numberOfChannels, numberOfFrames, sampleRate);
|
||||||
for (let ch = 0; ch < numberOfChannels; ch++) {
|
for (let ch = 0; ch < numberOfChannels; ch++) {
|
||||||
const data = new Float32Array(numberOfFrames);
|
const data = new Float32Array(numberOfFrames);
|
||||||
@@ -899,17 +999,7 @@ export function useVoiceWebSocket() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
source.start(playTime);
|
source.start(playTime);
|
||||||
audioCounters.playbackStarts++;
|
|
||||||
audioCounters.lastPlaybackStartAt = Date.now();
|
|
||||||
remotePlayTimes.set(clientId, playTime + numberOfFrames / sampleRate);
|
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 {
|
} catch {
|
||||||
// A decoder can finish while the audio context is being torn down.
|
// 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;
|
const timestamp = remoteDecodeTimestamps.get(clientId) ?? 0;
|
||||||
decoder.decode(new EncodedAudioChunk({ type: "key", timestamp, duration: 20_000, data: opusData }));
|
decoder.decode(new EncodedAudioChunk({ type: "key", timestamp, duration: 20_000, data: opusData }));
|
||||||
remoteDecodeTimestamps.set(clientId, timestamp + 20_000);
|
remoteDecodeTimestamps.set(clientId, timestamp + 20_000);
|
||||||
audioCounters.downlinkFrames++;
|
|
||||||
publishAudioDiagnostics();
|
|
||||||
} catch {
|
} catch {
|
||||||
// Ignore malformed frames; the next valid frame can still be decoded.
|
// Ignore malformed frames; the next valid frame can still be decoded.
|
||||||
}
|
}
|
||||||
@@ -960,8 +1048,6 @@ export function useVoiceWebSocket() {
|
|||||||
|
|
||||||
function resetRemotePlayback(clientId: number): void {
|
function resetRemotePlayback(clientId: number): void {
|
||||||
clearRemotePlayback(clientId);
|
clearRemotePlayback(clientId);
|
||||||
audioCounters.playbackResets++;
|
|
||||||
publishAudioDiagnostics();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function connect(target: string, channel: string, nickname: string, serverPassword = "", identity = "", rememberIdentity = false, inviteToken = ""): void {
|
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.connected = false;
|
||||||
state.connecting = false;
|
state.connecting = false;
|
||||||
state.reconnecting = 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();
|
stopWebRtcTransport();
|
||||||
stopMicrophone();
|
stopMicrophone();
|
||||||
whisperTargetIds.clear();
|
whisperTargetIds.clear();
|
||||||
whisperActive.value = false;
|
whisperActive.value = false;
|
||||||
};
|
};
|
||||||
socket.onerror = () => {
|
socket.onerror = () => {
|
||||||
if (sequence !== connectionSequence) return;
|
// The following close event contains the actionable close code. Do not
|
||||||
state.error = "连接服务器失败,请检查邀请链接或服务器状态";
|
// overwrite it with a generic browser WebSocket error first.
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1049,6 +1138,7 @@ export function useVoiceWebSocket() {
|
|||||||
if (code === 4002) return "TeamSpeak 服务器地址无效";
|
if (code === 4002) return "TeamSpeak 服务器地址无效";
|
||||||
if (code === 4003) return "TeamSpeak 服务器连接失败";
|
if (code === 4003) return "TeamSpeak 服务器连接失败";
|
||||||
if (code === 4004) return "服务器当前已满,请稍后重试";
|
if (code === 4004) return "服务器当前已满,请稍后重试";
|
||||||
|
if (code === 4005) return "此 TeamSpeak 身份已在另一个浏览器页面使用,请关闭另一条连接或取消“保持身份”后重试";
|
||||||
return "连接已断开";
|
return "连接已断开";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1248,12 +1338,6 @@ export function useVoiceWebSocket() {
|
|||||||
if (data.length < 4) return;
|
if (data.length < 4) return;
|
||||||
const clientId = (data[1] << 8) | data[2];
|
const clientId = (data[1] << 8) | data[2];
|
||||||
if (clientId === state.tsClientId) return;
|
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);
|
markSpeaking(clientId);
|
||||||
playAudioFrame(clientId, data.slice(3));
|
playAudioFrame(clientId, data.slice(3));
|
||||||
}
|
}
|
||||||
@@ -1341,6 +1425,7 @@ export function useVoiceWebSocket() {
|
|||||||
voxRelease = 0;
|
voxRelease = 0;
|
||||||
accumLen = 0;
|
accumLen = 0;
|
||||||
if (webrtcActive.value) micStream?.getAudioTracks().forEach((track) => { track.enabled = !muted; });
|
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 (webrtcActive.value) sendCmd("setMicrophoneMuted", { muted });
|
||||||
if (muted && state.tsClientId) clearSpeaking(state.tsClientId);
|
if (muted && state.tsClientId) clearSpeaking(state.tsClientId);
|
||||||
void saveAudioPreferences();
|
void saveAudioPreferences();
|
||||||
@@ -1365,6 +1450,7 @@ export function useVoiceWebSocket() {
|
|||||||
INVALID_POKE_MESSAGE: "戳一戳消息无效",
|
INVALID_POKE_MESSAGE: "戳一戳消息无效",
|
||||||
INVALID_AWAY_STATUS: "离开状态无效",
|
INVALID_AWAY_STATUS: "离开状态无效",
|
||||||
INVALID_AUDIO_FRAME: "音频帧格式无效",
|
INVALID_AUDIO_FRAME: "音频帧格式无效",
|
||||||
|
INVALID_MEMBER_VOLUME: "成员音量无效",
|
||||||
INVALID_WHISPER_TARGETS: "私语目标无效",
|
INVALID_WHISPER_TARGETS: "私语目标无效",
|
||||||
INVALID_WHISPER_STATE: "私语状态无效",
|
INVALID_WHISPER_STATE: "私语状态无效",
|
||||||
NO_WHISPER_TARGETS: "请先选择私语目标",
|
NO_WHISPER_TARGETS: "请先选择私语目标",
|
||||||
@@ -1389,11 +1475,22 @@ export function useVoiceWebSocket() {
|
|||||||
}
|
}
|
||||||
const gain = remoteGains.get(clientId);
|
const gain = remoteGains.get(clientId);
|
||||||
if (gain) gain.gain.value = normalized * outputVolume.value;
|
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 {
|
function setInputVolume(volume: number): void {
|
||||||
inputVolume.value = Math.max(0, Math.min(1, volume));
|
inputVolume.value = Math.max(0, Math.min(1, volume));
|
||||||
if (micGain) micGain.gain.value = inputVolume.value;
|
if (micGain) micGain.gain.value = inputVolume.value;
|
||||||
|
if (webrtcMixMicGain) webrtcMixMicGain.gain.value = microphoneMuted.value ? 0 : inputVolume.value;
|
||||||
void saveAudioPreferences();
|
void saveAudioPreferences();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1434,7 +1531,6 @@ export function useVoiceWebSocket() {
|
|||||||
outputDeviceSupported,
|
outputDeviceSupported,
|
||||||
audioPermission,
|
audioPermission,
|
||||||
audioContextState,
|
audioContextState,
|
||||||
audioDiagnostics,
|
|
||||||
identityMaterial,
|
identityMaterial,
|
||||||
micLevel,
|
micLevel,
|
||||||
microphoneTestActive,
|
microphoneTestActive,
|
||||||
@@ -1443,6 +1539,9 @@ export function useVoiceWebSocket() {
|
|||||||
whisperTargetIds,
|
whisperTargetIds,
|
||||||
whisperActive,
|
whisperActive,
|
||||||
volumes,
|
volumes,
|
||||||
|
accompanimentActive,
|
||||||
|
accompanimentSupported,
|
||||||
|
accompanimentErrorCode,
|
||||||
setVolume,
|
setVolume,
|
||||||
setInputVolume,
|
setInputVolume,
|
||||||
setOutputVolume,
|
setOutputVolume,
|
||||||
@@ -1467,6 +1566,8 @@ export function useVoiceWebSocket() {
|
|||||||
setWhisperTargets,
|
setWhisperTargets,
|
||||||
setWhisperActive,
|
setWhisperActive,
|
||||||
setMicrophoneMuted,
|
setMicrophoneMuted,
|
||||||
|
startAccompaniment,
|
||||||
|
stopAccompaniment,
|
||||||
checkSupport,
|
checkSupport,
|
||||||
clearError,
|
clearError,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -64,7 +64,7 @@
|
|||||||
<input id="channel" v-model="channel" :placeholder="t('emptyDefault')" @keyup.enter="doConnect" />
|
<input id="channel" v-model="channel" :placeholder="t('emptyDefault')" @keyup.enter="doConnect" />
|
||||||
</div>
|
</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">
|
<button class="primary-button connect-button" :disabled="!canJoin || serverConfigLoading || !identityReady || voiceState.connecting" type="submit">
|
||||||
<span v-if="voiceState.connecting" class="button-spinner"></span>
|
<span v-if="voiceState.connecting" class="button-spinner"></span>
|
||||||
@@ -95,8 +95,8 @@
|
|||||||
</select>
|
</select>
|
||||||
</label>
|
</label>
|
||||||
<button class="header-action" :title="t('copyInvite')" @click="doShare"><Icon name="share" :size="18" /></button>
|
<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 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 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" :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 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="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>
|
<button class="disconnect-button" @click="doDisconnect"><Icon name="door" :size="17" /><span>{{ t('exit') }}</span></button>
|
||||||
@@ -198,7 +198,14 @@
|
|||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="!filteredMemberChannels.length" class="member-empty">{{ t('noMatchingMembers') }}</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>
|
</aside>
|
||||||
|
|
||||||
<section v-if="mobileSection === 'more'" class="mobile-more-panel">
|
<section v-if="mobileSection === 'more'" class="mobile-more-panel">
|
||||||
@@ -307,6 +314,10 @@ const {
|
|||||||
setWhisperTargets,
|
setWhisperTargets,
|
||||||
setWhisperActive,
|
setWhisperActive,
|
||||||
setMicrophoneMuted,
|
setMicrophoneMuted,
|
||||||
|
accompanimentActive,
|
||||||
|
accompanimentErrorCode,
|
||||||
|
startAccompaniment,
|
||||||
|
stopAccompaniment,
|
||||||
checkSupport,
|
checkSupport,
|
||||||
clearError,
|
clearError,
|
||||||
} = useVoiceWebSocket();
|
} = useVoiceWebSocket();
|
||||||
@@ -397,6 +408,7 @@ const translations: Record<Language, Record<string, string>> = {
|
|||||||
emptyDefault: "留空进入默认频道",
|
emptyDefault: "留空进入默认频道",
|
||||||
rememberIdentity: "记住此设备的 TeamSpeak 身份",
|
rememberIdentity: "记住此设备的 TeamSpeak 身份",
|
||||||
rememberIdentityHint: "仅保存在本设备,用于下次连接时保持身份。",
|
rememberIdentityHint: "仅保存在本设备,用于下次连接时保持身份。",
|
||||||
|
rememberIdentityConcurrentWarning: "同一浏览器只能同时使用一条保持身份的连接;要开启第二条,请取消勾选或使用另一个浏览器。",
|
||||||
identityOptions: "设备身份选项",
|
identityOptions: "设备身份选项",
|
||||||
localPersistenceUnavailable: "当前浏览器无法使用持久化存储,本次将使用临时身份。",
|
localPersistenceUnavailable: "当前浏览器无法使用持久化存储,本次将使用临时身份。",
|
||||||
favoriteServers: "常用服务器",
|
favoriteServers: "常用服务器",
|
||||||
@@ -425,6 +437,16 @@ const translations: Record<Language, Record<string, string>> = {
|
|||||||
serverOptions: "更多服务器选项",
|
serverOptions: "更多服务器选项",
|
||||||
online: "在线",
|
online: "在线",
|
||||||
audioSettings: "音频设置",
|
audioSettings: "音频设置",
|
||||||
|
desktopAudioControls: "音频控制",
|
||||||
|
startAccompaniment: "共享伴奏",
|
||||||
|
stopAccompaniment: "停止伴奏",
|
||||||
|
accompanimentStarted: "伴奏共享已开始",
|
||||||
|
accompanimentStopped: "伴奏共享已停止",
|
||||||
|
accompanimentActive: "伴奏共享中",
|
||||||
|
accompanimentNeedsWebRtc: "伴奏功能需要启用 WebRTC",
|
||||||
|
accompanimentNoAudio: "所选来源没有可共享音频,请重新选择并勾选共享音频",
|
||||||
|
accompanimentPermissionDenied: "无法获取伴奏音频,请允许屏幕共享并勾选共享音频",
|
||||||
|
accompanimentUnsupported: "当前浏览器不支持伴奏共享",
|
||||||
serverPassword: "服务器密码",
|
serverPassword: "服务器密码",
|
||||||
optionalPassword: "没有密码可留空",
|
optionalPassword: "没有密码可留空",
|
||||||
switchChannel: "切换频道",
|
switchChannel: "切换频道",
|
||||||
@@ -617,6 +639,7 @@ const translations: Record<Language, Record<string, string>> = {
|
|||||||
emptyDefault: "Leave empty to use the default channel",
|
emptyDefault: "Leave empty to use the default channel",
|
||||||
rememberIdentity: "Remember this TeamSpeak identity on this device",
|
rememberIdentity: "Remember this TeamSpeak identity on this device",
|
||||||
rememberIdentityHint: "Stored only on this device and reused on the next connection.",
|
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",
|
identityOptions: "Device identity options",
|
||||||
localPersistenceUnavailable: "Persistent browser storage is unavailable; this session will use an ephemeral identity.",
|
localPersistenceUnavailable: "Persistent browser storage is unavailable; this session will use an ephemeral identity.",
|
||||||
favoriteServers: "Favorites",
|
favoriteServers: "Favorites",
|
||||||
@@ -645,6 +668,16 @@ const translations: Record<Language, Record<string, string>> = {
|
|||||||
serverOptions: "More server options",
|
serverOptions: "More server options",
|
||||||
online: "Online",
|
online: "Online",
|
||||||
audioSettings: "Audio settings",
|
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",
|
serverPassword: "Server password",
|
||||||
optionalPassword: "Leave blank if not required",
|
optionalPassword: "Leave blank if not required",
|
||||||
switchChannel: "Switch channel",
|
switchChannel: "Switch channel",
|
||||||
@@ -830,6 +863,7 @@ function localizedMessage(message: string) {
|
|||||||
"连接服务器失败,请检查邀请链接或服务器状态": "Could not connect. Check the invite link or server status",
|
"连接服务器失败,请检查邀请链接或服务器状态": "Could not connect. Check the invite link or server status",
|
||||||
"TeamSpeak 连接已断开": "The TeamSpeak connection was closed",
|
"TeamSpeak 连接已断开": "The TeamSpeak connection was closed",
|
||||||
"连接已断开": "The 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 服务器地址无效": "The TeamSpeak server address is invalid",
|
||||||
"TeamSpeak 服务器连接失败": "Could not connect to the TeamSpeak server",
|
"TeamSpeak 服务器连接失败": "Could not connect to the TeamSpeak server",
|
||||||
"服务器当前已满,请稍后重试": "The server is full. Try again shortly",
|
"服务器当前已满,请稍后重试": "The server is full. Try again shortly",
|
||||||
@@ -1053,6 +1087,7 @@ onMounted(() => {
|
|||||||
viewportChangeHandler = () => {
|
viewportChangeHandler = () => {
|
||||||
isMobileViewport.value = viewportMediaQuery?.matches ?? false;
|
isMobileViewport.value = viewportMediaQuery?.matches ?? false;
|
||||||
if (!isMobileViewport.value) memberMenu.value = null;
|
if (!isMobileViewport.value) memberMenu.value = null;
|
||||||
|
else if (accompanimentActive.value) void stopAccompaniment();
|
||||||
};
|
};
|
||||||
viewportChangeHandler();
|
viewportChangeHandler();
|
||||||
viewportMediaQuery.addEventListener?.("change", viewportChangeHandler);
|
viewportMediaQuery.addEventListener?.("change", viewportChangeHandler);
|
||||||
@@ -1361,6 +1396,27 @@ function toggleMicrophone(): void {
|
|||||||
showToast(microphoneMuted.value ? t("microphoneMuted") : t("microphoneActive"));
|
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 {
|
function onWhisperPttDown(event: PointerEvent): void {
|
||||||
if (!whisperTargetIds.size) return;
|
if (!whisperTargetIds.size) return;
|
||||||
const target = event.currentTarget as HTMLElement | null;
|
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, .remember-identity small { display: block; }
|
||||||
.remember-identity strong { font-size: 11px; font-weight: 700; }
|
.remember-identity strong { font-size: 11px; font-weight: 700; }
|
||||||
.remember-identity small { margin-top: 3px; color: #8b9994; font-size: 10px; line-height: 1.4; }
|
.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-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 { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; }
|
||||||
.local-server-group > span { width: 100%; color: #87958f; font-size: 10px; font-weight: 700; }
|
.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; }
|
.app-shell { grid-template-rows: minmax(0, 1fr) 220px; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Keep connected controls in the header; the old bottom dock consumed the
|
/* Desktop audio controls live in the member rail so the workspace header
|
||||||
chat viewport and made the settings action appear detached from its icon. */
|
stays focused on navigation. Mobile keeps its existing controls below the
|
||||||
|
voice cards and in the More panel. */
|
||||||
.header-tools { align-items: center; }
|
.header-tools { align-items: center; }
|
||||||
.header-action, .round-icon { line-height: 0; }
|
.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; }
|
.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 { align-items: center; flex-wrap: nowrap; }
|
||||||
.workspace-actions .header-action { flex: 0 0 34px; padding: 0; line-height: 0; }
|
.workspace-actions .header-action { flex: 0 0 34px; padding: 0; line-height: 0; }
|
||||||
.workspace-actions .header-action .ui-icon { margin: 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-mode-switch { width: fit-content; margin: 0 0 7px; }
|
||||||
.settings-hint { margin: -1px 0 19px; color: #8b9994; font-size: 11px; }
|
.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-presence { width: 10px; height: 10px; }
|
||||||
.member-copy strong { font-size: 14px; }
|
.member-copy strong { font-size: 14px; }
|
||||||
.member-copy span { margin-top: 3px; font-size: 12px; }
|
.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 { 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)); }
|
.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