mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
fix: cancel stale voice operations and isolate Android startup
This commit is contained in:
1 parent
8960189bc7
commit
e2f0a43762
15 files changed
+913
-174
No files matched your search
@@ -0,0 +1,169 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import pino from "pino";
|
||||
import { VoiceBridge } from "./voice-bridge.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { createAudioFlowStats } from "./audio-stats.js";
|
||||
import type { WebRtcAudioSession, WebRtcAudioSessionOptions, WebRtcSessionDescription } from "./webrtc-audio.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<void>((done, fail) => { resolve = done; reject = fail; });
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
class PeerStub {
|
||||
closed = false;
|
||||
closeResult = Promise.resolve();
|
||||
answerResult = Promise.resolve();
|
||||
constructor(readonly options: WebRtcAudioSessionOptions) {}
|
||||
async close() { this.closed = true; await this.closeResult; }
|
||||
getStats() { return { webrtcIngressRtpFrames: 10 }; }
|
||||
async createAnswer(offer: WebRtcSessionDescription): Promise<WebRtcSessionDescription> {
|
||||
await this.answerResult;
|
||||
return { type: "answer", sdp: offer.sdp };
|
||||
}
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
const peers: PeerStub[] = [];
|
||||
const messages: ServerMessage[] = [];
|
||||
const entry = {
|
||||
id: "session", session: { state: "connected" }, ws: { readyState: 1 },
|
||||
webrtc: null as PeerStub | null, webrtcGeneration: 0,
|
||||
tsClient: { setInputMuted: async (_muted: boolean) => {}, sendVoice: () => { forwarded++; } },
|
||||
whisperActive: false, whisperTargetIds: new Set<number>(), audio: createAudioFlowStats(),
|
||||
};
|
||||
let forwarded = 0;
|
||||
let configurePeer = (_peer: PeerStub): void => {};
|
||||
const instance = new VoiceBridge({ joinTickets: new JoinTicketStore(), webRtc: { enabled: true } }, pino({ enabled: false }), options => {
|
||||
const peer = new PeerStub(options);
|
||||
peers.push(peer);
|
||||
configurePeer(peer);
|
||||
return peer as unknown as WebRtcAudioSession;
|
||||
});
|
||||
// Exercise the bridge's orchestration itself, replacing only SDK/WebRTC I/O.
|
||||
type Entry = typeof entry;
|
||||
const bridge = instance as unknown as {
|
||||
entries: Map<string, Entry>;
|
||||
handleWebRtcOffer(entry: Entry, offer: WebRtcSessionDescription, send: (message: ServerMessage) => void): Promise<void>;
|
||||
stopWebRtc(entry: Entry): Promise<void>;
|
||||
};
|
||||
bridge.entries.set(entry.id, entry);
|
||||
const offer = (sdp: string) => bridge.handleWebRtcOffer(entry, { type: "offer", sdp }, message => messages.push(message));
|
||||
return { bridge, entry, peers, messages, offer, forwarded: () => forwarded, configure: (callback: typeof configurePeer) => { configurePeer = callback; } };
|
||||
}
|
||||
|
||||
test("an offer waiting on the SDK cannot create a peer after its session is removed", async () => {
|
||||
const f = fixture();
|
||||
const mute = deferred();
|
||||
f.entry.tsClient.setInputMuted = () => mute.promise;
|
||||
const pending = f.offer("old");
|
||||
// Allow the operation to reach the SDK boundary before teardown wins.
|
||||
await Promise.resolve();
|
||||
f.bridge.entries.delete(f.entry.id);
|
||||
f.entry.session.state = "disconnecting";
|
||||
f.entry.ws.readyState = 3;
|
||||
mute.resolve();
|
||||
await pending;
|
||||
assert.equal(f.peers.length, 0);
|
||||
});
|
||||
|
||||
test("a newer offer wins while the old offer waits for its mute update", async () => {
|
||||
const f = fixture();
|
||||
const mute = deferred();
|
||||
f.entry.tsClient.setInputMuted = () => mute.promise;
|
||||
const old = f.offer("old");
|
||||
await Promise.resolve();
|
||||
f.entry.tsClient.setInputMuted = async () => {};
|
||||
await f.offer("new");
|
||||
const current = f.entry.webrtc;
|
||||
mute.resolve();
|
||||
await old;
|
||||
assert.equal(f.entry.webrtc, current);
|
||||
assert.equal(f.peers.length, 1);
|
||||
assert.deepEqual(f.messages.filter(message => message.type === "webrtcAnswer").map(message => message.payload.sdp.sdp), ["new"]);
|
||||
});
|
||||
|
||||
test("closing an older peer cannot clear or overwrite a newer offer", async () => {
|
||||
const f = fixture();
|
||||
await f.offer("initial");
|
||||
const closing = deferred();
|
||||
f.peers[0]!.closeResult = closing.promise;
|
||||
const old = f.offer("old");
|
||||
await Promise.resolve();
|
||||
const newer = f.offer("new");
|
||||
closing.resolve();
|
||||
await Promise.all([old, newer]);
|
||||
assert.equal(f.peers.length, 2);
|
||||
assert.equal(f.entry.webrtc, f.peers[1]);
|
||||
assert.deepEqual(f.messages.filter(message => message.type === "webrtcAnswer").map(message => message.payload.sdp.sdp), ["initial", "new"]);
|
||||
});
|
||||
|
||||
test("a superseded answer failure cannot send an error for the current offer", async () => {
|
||||
const f = fixture();
|
||||
const answer = deferred();
|
||||
f.configure(peer => { if (f.peers.length === 1) peer.answerResult = answer.promise; });
|
||||
const old = f.offer("old");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await f.offer("new");
|
||||
const current = f.entry.webrtc;
|
||||
answer.reject(new Error("old peer closed"));
|
||||
await old;
|
||||
assert.equal(f.entry.webrtc, current);
|
||||
assert.equal(current?.closed, false);
|
||||
assert.equal(f.messages.some(message => message.type === "webrtcError"), false);
|
||||
});
|
||||
|
||||
test("a replaced peer cannot forward late audio or activity into the current session", async () => {
|
||||
const f = fixture();
|
||||
await f.offer("old");
|
||||
const old = f.peers[0]!;
|
||||
await f.offer("new");
|
||||
old.options.onVoiceFrame(Buffer.from([1, 2, 3]), 4);
|
||||
old.options.onVoiceActivity([7]);
|
||||
assert.equal(f.forwarded(), 0);
|
||||
assert.equal(f.entry.audio.ingressFrames, 0);
|
||||
assert.equal(f.messages.some(message => message.type === "voiceActivity"), false);
|
||||
f.peers[1]!.options.onVoiceFrame(Buffer.from([4, 5, 6]), 4);
|
||||
assert.equal(f.forwarded(), 1);
|
||||
});
|
||||
|
||||
test("stop invalidates an offer before the first peer has been created", async () => {
|
||||
const f = fixture();
|
||||
const mute = deferred();
|
||||
f.entry.tsClient.setInputMuted = () => mute.promise;
|
||||
const pending = f.offer("pending");
|
||||
await Promise.resolve();
|
||||
await f.bridge.stopWebRtc(f.entry);
|
||||
mute.resolve();
|
||||
await pending;
|
||||
assert.equal(f.entry.webrtc, null);
|
||||
assert.equal(f.peers.length, 0);
|
||||
assert.deepEqual(f.messages, []);
|
||||
});
|
||||
|
||||
test("a current peer construction failure reports a recoverable negotiation error", async () => {
|
||||
const f = fixture();
|
||||
f.configure(() => { throw new Error("codec unavailable"); });
|
||||
await f.offer("current");
|
||||
assert.equal(f.entry.webrtc, null);
|
||||
assert.deepEqual(f.messages, [{ type: "webrtcError", code: "WEBRTC_NEGOTIATION_FAILED" }]);
|
||||
});
|
||||
|
||||
test("old close statistics cannot overwrite a new peer's live snapshot", async () => {
|
||||
const f = fixture();
|
||||
await f.offer("old");
|
||||
const closing = deferred();
|
||||
f.peers[0]!.closeResult = closing.promise;
|
||||
const stopped = f.bridge.stopWebRtc(f.entry);
|
||||
await f.offer("new");
|
||||
f.entry.audio.webrtcIngressRtpFrames = 27;
|
||||
closing.resolve();
|
||||
await stopped;
|
||||
assert.equal(f.entry.audio.webrtcIngressRtpFrames, 27);
|
||||
assert.equal(f.entry.webrtc, f.peers[1]);
|
||||
});
|
||||
+69
-57
@@ -21,7 +21,7 @@ import { IdentityLeaseStore } from "./identity-lease.js";
|
||||
import { SessionManager, type ManagedSession, type SessionTeardownReason } from "./session-manager.js";
|
||||
import { parseClientCommand } from "./voice-protocol.js";
|
||||
import { isRecoverable, reconnectDelayMs, reconnectWindowOpen } from "./reconnect-policy.js";
|
||||
import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcSessionDescription } from "./webrtc-audio.js";
|
||||
import { WebRtcAudioSession, type WebRtcAudioOptions, type WebRtcAudioSessionOptions, type WebRtcSessionDescription } from "./webrtc-audio.js";
|
||||
import type { AccelerationRelayOptions, ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenShareIceServer } from "./screen-share.js";
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
@@ -93,6 +93,7 @@ interface WebClientEntry {
|
||||
reconnectTimer: ReturnType<typeof setTimeout> | null;
|
||||
audio: AudioFlowStats;
|
||||
webrtc: WebRtcAudioSession | null;
|
||||
webrtcGeneration: number;
|
||||
lastLatencyProbeAt: number;
|
||||
lastAudioStatsProbeAt: number;
|
||||
connectionFailureCode?: string;
|
||||
@@ -111,6 +112,7 @@ export class VoiceBridge {
|
||||
constructor(
|
||||
private options: VoiceBridgeOptions,
|
||||
logger: LoggerType,
|
||||
private readonly createWebRtcSession: (options: WebRtcAudioSessionOptions) => WebRtcAudioSession = options => new WebRtcAudioSession(options),
|
||||
) {
|
||||
this.logger = logger.child({ component: "voice-bridge" });
|
||||
this.screenShares = new ScreenShareCoordinator(this.entries, (entryId, message) => {
|
||||
@@ -219,6 +221,7 @@ export class VoiceBridge {
|
||||
reconnectTimer: null,
|
||||
audio: createAudioFlowStats(),
|
||||
webrtc: null,
|
||||
webrtcGeneration: 0,
|
||||
lastLatencyProbeAt: 0,
|
||||
lastAudioStatsProbeAt: 0,
|
||||
screenPeerId: entryId,
|
||||
@@ -394,6 +397,7 @@ export class VoiceBridge {
|
||||
|
||||
const resetDirectoryForReconnect = () => {
|
||||
tsReady = false;
|
||||
void this.stopWebRtc(entry!);
|
||||
initialStateSent = false;
|
||||
selfId = 0;
|
||||
selfChannelId = 0n;
|
||||
@@ -732,13 +736,7 @@ export class VoiceBridge {
|
||||
return;
|
||||
}
|
||||
if (isWebRtcStopMessage(rawMessage)) {
|
||||
const webRtc = entry!.webrtc;
|
||||
entry!.webrtc = null;
|
||||
if (webRtc) {
|
||||
void webRtc.close()
|
||||
.then(() => Object.assign(entry!.audio, webRtc.getStats()))
|
||||
.catch(() => undefined);
|
||||
}
|
||||
void this.stopWebRtc(entry!);
|
||||
return;
|
||||
}
|
||||
const screenShareMessage = parseScreenShareMessage(rawMessage);
|
||||
@@ -866,12 +864,7 @@ export class VoiceBridge {
|
||||
}
|
||||
entry.opusEncoder?.dispose();
|
||||
entry.opusEncoder = null;
|
||||
const webRtc = entry.webrtc;
|
||||
entry.webrtc = null;
|
||||
if (webRtc) {
|
||||
try { await webRtc.close(); } catch { /* peer teardown is idempotent */ }
|
||||
Object.assign(entry.audio, webRtc.getStats());
|
||||
}
|
||||
await this.stopWebRtc(entry);
|
||||
entry.whisperTargetIds.clear();
|
||||
entry.whisperActive = false;
|
||||
entry.channelTree = [];
|
||||
@@ -939,17 +932,27 @@ export class VoiceBridge {
|
||||
return selected;
|
||||
}
|
||||
|
||||
private async stopWebRtc(entry: WebClientEntry): Promise<void> {
|
||||
const generation = ++entry.webrtcGeneration;
|
||||
const peer = entry.webrtc;
|
||||
entry.webrtc = null;
|
||||
if (!peer) return;
|
||||
try { await peer.close(); } catch { /* peer teardown is idempotent */ }
|
||||
if (entry.webrtcGeneration === generation) Object.assign(entry.audio, peer.getStats());
|
||||
}
|
||||
|
||||
private async handleWebRtcOffer(
|
||||
entry: WebClientEntry,
|
||||
offer: WebRtcSessionDescription,
|
||||
sendJson: (message: ServerMessage) => void,
|
||||
): Promise<void> {
|
||||
if (entry.webrtc) {
|
||||
const previousWebRtc = entry.webrtc;
|
||||
try { await previousWebRtc.close(); } catch { /* replace a retried offer */ }
|
||||
Object.assign(entry.audio, previousWebRtc.getStats());
|
||||
entry.webrtc = null;
|
||||
}
|
||||
const closing = this.stopWebRtc(entry);
|
||||
const generation = entry.webrtcGeneration;
|
||||
const isCurrent = (): boolean => entry.webrtcGeneration === generation
|
||||
&& this.entries.get(entry.id) === entry && entry.session.state === "connected"
|
||||
&& entry.ws.readyState === WebSocket.OPEN;
|
||||
await closing;
|
||||
if (!isCurrent()) return;
|
||||
const config = this.getWebRtcOptions();
|
||||
if (!config?.enabled) return;
|
||||
const muted = offer.muted === true;
|
||||
@@ -959,50 +962,59 @@ export class VoiceBridge {
|
||||
// after the gateway updates its own TS client as well.
|
||||
await entry.tsClient.setInputMuted(muted);
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({ entryId: entry.id, muted, err: error instanceof Error ? error.message : String(error) }, "Could not synchronize initial microphone mute state");
|
||||
if (isCurrent()) this.logger.warn({ entryId: entry.id, muted, err: error instanceof Error ? error.message : String(error) }, "Could not synchronize initial microphone mute state");
|
||||
}
|
||||
const peer = new WebRtcAudioSession({
|
||||
connectionId: entry.id,
|
||||
...(entry.webrtcPublicHost ? { publicHost: entry.webrtcPublicHost } : {}),
|
||||
udpPortRange: config.udpPortRange,
|
||||
logger: this.logger,
|
||||
microphoneMuted: muted,
|
||||
accompanimentActive: offer.accompanimentActive === true,
|
||||
onVoiceFrame: (data, codec) => {
|
||||
const now = Date.now();
|
||||
if (entry.audio.ingressLastAt !== null) entry.audio.ingressMaxGapMs = Math.max(entry.audio.ingressMaxGapMs, now - entry.audio.ingressLastAt);
|
||||
entry.audio.ingressFirstAt ??= now;
|
||||
entry.audio.ingressLastAt = now;
|
||||
entry.audio.ingressFrames++;
|
||||
try {
|
||||
if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], codec);
|
||||
else entry.tsClient.sendVoice(data, codec);
|
||||
const sentAt = Date.now();
|
||||
if (entry.audio.tsSendLastAt !== null) entry.audio.tsSendMaxGapMs = Math.max(entry.audio.tsSendMaxGapMs, sentAt - entry.audio.tsSendLastAt);
|
||||
entry.audio.tsSendFirstAt ??= sentAt;
|
||||
entry.audio.tsSendLastAt = sentAt;
|
||||
entry.audio.tsSendFrames++;
|
||||
} catch {
|
||||
entry.audio.tsSendErrors++;
|
||||
// A packet arriving while the TeamSpeak session is being replaced
|
||||
// is discarded; the WebRTC peer remains independently closable.
|
||||
}
|
||||
},
|
||||
onVoiceActivity: (clientIds) => {
|
||||
if (entry.ws.readyState === WebSocket.OPEN) sendJson({ type: "voiceActivity", clientIds });
|
||||
},
|
||||
});
|
||||
entry.webrtc = peer;
|
||||
if (!isCurrent()) return;
|
||||
let peer: WebRtcAudioSession | null = null;
|
||||
const isCurrentPeer = (): boolean => isCurrent() && peer !== null && entry.webrtc === peer;
|
||||
try {
|
||||
peer = this.createWebRtcSession({
|
||||
connectionId: entry.id,
|
||||
...(entry.webrtcPublicHost ? { publicHost: entry.webrtcPublicHost } : {}),
|
||||
udpPortRange: config.udpPortRange,
|
||||
logger: this.logger,
|
||||
microphoneMuted: muted,
|
||||
accompanimentActive: offer.accompanimentActive === true,
|
||||
onVoiceFrame: (data, codec) => {
|
||||
if (!isCurrentPeer()) return;
|
||||
const now = Date.now();
|
||||
if (entry.audio.ingressLastAt !== null) entry.audio.ingressMaxGapMs = Math.max(entry.audio.ingressMaxGapMs, now - entry.audio.ingressLastAt);
|
||||
entry.audio.ingressFirstAt ??= now;
|
||||
entry.audio.ingressLastAt = now;
|
||||
entry.audio.ingressFrames++;
|
||||
try {
|
||||
if (entry.whisperActive && entry.whisperTargetIds.size) entry.tsClient.sendWhisper(data, [...entry.whisperTargetIds], codec);
|
||||
else entry.tsClient.sendVoice(data, codec);
|
||||
const sentAt = Date.now();
|
||||
if (entry.audio.tsSendLastAt !== null) entry.audio.tsSendMaxGapMs = Math.max(entry.audio.tsSendMaxGapMs, sentAt - entry.audio.tsSendLastAt);
|
||||
entry.audio.tsSendFirstAt ??= sentAt;
|
||||
entry.audio.tsSendLastAt = sentAt;
|
||||
entry.audio.tsSendFrames++;
|
||||
} catch {
|
||||
entry.audio.tsSendErrors++;
|
||||
// A packet arriving while the TeamSpeak session is being replaced
|
||||
// is discarded; the WebRTC peer remains independently closable.
|
||||
}
|
||||
},
|
||||
onVoiceActivity: (clientIds) => {
|
||||
if (isCurrentPeer()) sendJson({ type: "voiceActivity", clientIds });
|
||||
},
|
||||
});
|
||||
entry.webrtc = peer;
|
||||
const answer = await peer.createAnswer({ type: offer.type, sdp: offer.sdp });
|
||||
if (entry.webrtc !== peer || entry.ws.readyState !== WebSocket.OPEN) return;
|
||||
if (!isCurrentPeer()) {
|
||||
try { await peer.close(); } catch { /* a replaced peer may already be closed */ }
|
||||
return;
|
||||
}
|
||||
sendJson({ type: "webrtcAnswer", payload: { sdp: answer } });
|
||||
this.logger.info({ entryId: entry.id }, "WebRTC audio negotiation completed");
|
||||
} catch (error: unknown) {
|
||||
if (entry.webrtc === peer) entry.webrtc = null;
|
||||
try { await peer.close(); } catch { /* best effort */ }
|
||||
this.logger.warn({ entryId: entry.id, err: error instanceof Error ? error.message : String(error) }, "WebRTC audio negotiation failed");
|
||||
if (entry.ws.readyState === WebSocket.OPEN) sendJson({ type: "webrtcError", code: "WEBRTC_NEGOTIATION_FAILED" });
|
||||
try { await peer?.close(); } catch { /* best effort */ }
|
||||
if (isCurrent()) {
|
||||
this.logger.warn({ entryId: entry.id, err: error instanceof Error ? error.message : String(error) }, "WebRTC audio negotiation failed");
|
||||
sendJson({ type: "webrtcError", code: "WEBRTC_NEGOTIATION_FAILED" });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user