fix: keep accompaniment audible while microphone is muted

This commit is contained in:
illusia committed 2026-10-03 09:18:49 +08:00
1 parent 051cb402e5
commit 777c779d79
8 files changed
+166 -16

No files matched your search

+54
View File
@@ -16,6 +16,9 @@ const rows = [{ client_unique_identifier: "member", client_flag_avatar: "marker"
const transfer = { size: 6n };
class SdkStub extends EventEmitter {
inputCommands: string[] = [];
inputUpdate = async (_command: string): Promise<void> => {};
async execCommand(command: string) { this.inputCommands.push(command); await this.inputUpdate(command); }
initialized = 0;
downloaded = 0;
metadata = async () => rows;
@@ -36,6 +39,57 @@ function fixture() {
return { client, sdk, state };
}
test("accompaniment remains audible with the microphone muted and stopping restores mute", async () => {
const f = fixture();
await f.client.setInputMuted(true);
await f.client.setAccompanimentActive(true);
await f.client.setInputMuted(true);
await f.client.setAccompanimentActive(false);
await f.client.setInputMuted(false);
assert.deepEqual(f.sdk.inputCommands, [1, 0, 0, 1, 0].map(value => `clientupdate client_input_muted=${value}`));
});
test("overlapping microphone and accompaniment changes use the last accepted input state", async () => {
const f = fixture();
const pending = deferred<void>();
f.sdk.inputUpdate = async () => pending.promise;
const mute = f.client.setInputMuted(true);
const music = f.client.setAccompanimentActive(true);
await nextTurn();
assert.equal(f.sdk.inputCommands.length, 1);
pending.resolve();
await Promise.all([mute, music]);
assert.deepEqual(f.sdk.inputCommands, ["clientupdate client_input_muted=1", "clientupdate client_input_muted=0"]);
});
test("a rejected accompaniment update cannot change later mute decisions or poison the queue", async () => {
const f = fixture();
await f.client.setInputMuted(true);
f.sdk.inputUpdate = async () => { throw new Error("denied"); };
await assert.rejects(f.client.setAccompanimentActive(true), /denied/);
f.sdk.inputUpdate = async () => {};
await f.client.setInputMuted(true);
assert.equal(f.sdk.inputCommands.at(-1), "clientupdate client_input_muted=1");
});
test("queued and in-flight input changes cannot cross a disconnected session", async () => {
const f = fixture();
const pending = deferred<void>();
f.sdk.inputUpdate = async () => pending.promise;
const first = assert.rejects(f.client.setAccompanimentActive(true), /session changed/);
const queued = assert.rejects(f.client.setInputMuted(true), /not ready/);
await nextTurn();
await f.client.disconnect();
f.state.client = f.sdk;
f.state.connected = true;
pending.resolve();
await Promise.all([first, queued]);
assert.equal(f.sdk.inputCommands.length, 1);
f.sdk.inputUpdate = async () => {};
await f.client.setInputMuted(true);
assert.equal(f.sdk.inputCommands.at(-1), "clientupdate client_input_muted=1");
});
test("an old avatar metadata response cannot start a transfer on a replacement SDK client", async () => {
const f = fixture();
const pending = deferred<typeof rows>();
+26 -2
View File
@@ -87,6 +87,8 @@ export class TSClient extends EventEmitter {
private clientId = 0;
private connected = false;
private connectionGeneration = 0;
private inputState = { muted: false, accompaniment: false };
private inputStateQueue: Promise<void> = Promise.resolve();
private preferredChannelId = 0n;
private accelerationClient: AccelerationRelayClient | null = null;
// Reason id of the most recent self leave, kept so the SDK `kicked` event can
@@ -102,6 +104,8 @@ export class TSClient extends EventEmitter {
async connect(): Promise<void> {
this.connectionGeneration++;
this.inputState = { muted: false, accompaniment: false };
this.inputStateQueue = Promise.resolve();
this.selfLeaveReasonId = null;
if (!this.adapter || !this.client) {
let transportTarget = this.options.target;
@@ -357,8 +361,28 @@ export class TSClient extends EventEmitter {
}
async setInputMuted(muted: boolean): Promise<void> {
if (!this.client || !this.connected) throw new Error("TeamSpeak session is not ready");
await this.client.execCommand(`clientupdate client_input_muted=${muted ? 1 : 0}`);
await this.updateInputState({ muted });
}
async setAccompanimentActive(accompaniment: boolean): Promise<void> {
await this.updateInputState({ accompaniment });
}
private updateInputState(change: Partial<typeof this.inputState>): Promise<void> {
const client = this.client;
const generation = this.connectionGeneration;
const isCurrent = () => client !== null && this.client === client && this.connected && this.connectionGeneration === generation;
const update = this.inputStateQueue.then(async () => {
if (!isCurrent()) throw new Error("TeamSpeak session is not ready");
const next = { ...this.inputState, ...change };
// TeamSpeak discards all audio from an input-muted client, including
// music. The browser removes the microphone from its accompaniment mix.
await client!.execCommand(`clientupdate client_input_muted=${next.muted && !next.accompaniment ? 1 : 0}`);
if (!isCurrent()) throw new Error("TeamSpeak session changed while updating input state");
this.inputState = next;
});
this.inputStateQueue = update.catch(() => undefined);
return update;
}
async switchChannel(channelId: bigint, password?: string): Promise<void> {
@@ -26,6 +26,7 @@ class TeamSpeakStub extends EventEmitter {
getChannelId() { return 1n; }
isConnected() { return !this.disconnected; }
async sendProtocolCommand() {}
async setAccompanimentActive() {}
sendVoice(data: Buffer) { this.sent.push(data); this.emit("sent", data); }
sendWhisper(data: Buffer) { this.sent.push(data); }
getClientAvatar(id: number, uid: string) { return this.avatarRequest(id, uid); }
+32 -3
View File
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { setImmediate as nextTurn } from "node:timers/promises";
import pino from "pino";
import { VoiceBridge } from "./voice-bridge.js";
import { JoinTicketStore } from "./join-ticket.js";
@@ -35,7 +36,7 @@ function fixture() {
const entry = {
id: "session", session: { state: "connected" }, ws: { readyState: 1 as 0 | 1 | 2 | 3, bufferedAmount: 0, send() {} },
webrtc: null as PeerStub | null, webrtcGeneration: 0,
tsClient: { setInputMuted: async (_muted: boolean) => {}, sendVoice: () => { forwarded++; }, sendWhisper: () => { forwarded++; } },
tsClient: { isConnected: () => true, setInputMuted: async (_muted: boolean) => {}, setAccompanimentActive: async (_active: boolean) => {}, sendVoice: () => { forwarded++; }, sendWhisper: () => { forwarded++; } },
whisperActive: false, whisperTargetIds: new Set<number>(), audio: createAudioFlowStats(),
audioTransport: null as SessionAudioTransport | null,
};
@@ -116,8 +117,7 @@ test("a superseded answer failure cannot send an error for the current offer", a
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 nextTurn();
await f.offer("new");
const current = f.entry.webrtc;
answer.reject(new Error("old peer closed"));
@@ -163,6 +163,35 @@ test("a current peer construction failure reports a recoverable negotiation erro
assert.deepEqual(f.messages, [{ type: "webrtcError", code: "WEBRTC_NEGOTIATION_FAILED" }]);
});
test("initial accompaniment updates TeamSpeak before creating a muted mixer and resets on stop", async () => {
const f = fixture();
const inputs: Array<[string, boolean]> = [];
f.entry.tsClient.setInputMuted = async muted => { inputs.push(["muted", muted]); };
f.entry.tsClient.setAccompanimentActive = async active => { inputs.push(["music", active]); };
await f.bridge.handleWebRtcOffer(f.entry, { type: "offer", sdp: "audio", muted: true, accompanimentActive: true }, message => f.messages.push(message));
assert.deepEqual(inputs, [["music", false], ["muted", true], ["music", true]]);
assert.equal(f.peers[0]?.options.microphoneMuted, true);
assert.equal(f.peers[0]?.options.accompanimentActive, true);
await f.bridge.stopWebRtc(f.entry);
assert.deepEqual(inputs.at(-1), ["music", false]);
});
test("stopping during accompaniment synchronization restores input even without a peer", async () => {
const f = fixture();
const waiting = deferred();
const inputs: boolean[] = [];
f.entry.tsClient.setAccompanimentActive = async active => { inputs.push(active); if (active) await waiting.promise; };
const offer = f.bridge.handleWebRtcOffer(f.entry, { type: "offer", sdp: "audio", muted: true, accompanimentActive: true }, message => f.messages.push(message));
await nextTurn();
assert.deepEqual(inputs, [false, true]);
await f.bridge.stopWebRtc(f.entry);
waiting.resolve();
await offer;
assert.deepEqual(inputs, [false, true, false]);
assert.equal(f.peers.length, 0);
assert.deepEqual(f.messages, []);
});
test("old close statistics cannot overwrite a new peer's live snapshot", async () => {
const f = fixture();
await f.offer("old");
+10 -1
View File
@@ -659,8 +659,14 @@ export class VoiceBridge {
const generation = ++entry.webrtcGeneration;
const peer = entry.webrtc;
entry.webrtc = null;
if (!peer) return;
// Enqueue the reset even while an offer is still preparing its first peer.
// A later offer's input changes are then ordered after this restoration.
const restoreInput = this.entries.get(entry.id) === entry && entry.tsClient.isConnected()
? entry.tsClient.setAccompanimentActive(false).catch(() => undefined)
: Promise.resolve();
if (!peer) { await restoreInput; return; }
try { await peer.close(); } catch { /* peer teardown is idempotent */ }
await restoreInput;
if (entry.webrtcGeneration === generation) {
try { Object.assign(entry.audio, peer.getStats()); } catch { /* diagnostics must not abort cleanup */ }
}
@@ -686,6 +692,7 @@ export class VoiceBridge {
// the browser track locally, but TeamSpeak clients only see the state
// after the gateway updates its own TS client as well.
await entry.tsClient.setInputMuted(muted);
if (isCurrent()) await entry.tsClient.setAccompanimentActive(offer.accompanimentActive === true);
} catch (error: unknown) {
if (isCurrent()) this.logger.warn({ entryId: entry.id, muted, err: error instanceof Error ? error.message : String(error) }, "Could not synchronize initial microphone mute state");
}
@@ -719,6 +726,8 @@ export class VoiceBridge {
if (entry.webrtc === peer) entry.webrtc = null;
try { await peer?.close(); } catch { /* best effort */ }
if (isCurrent()) {
try { await entry.tsClient.setAccompanimentActive(false); } catch { /* best effort */ }
if (!isCurrent()) return;
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" });
}
+18
View File
@@ -19,6 +19,7 @@ function fixture() {
poke: async (...args) => { calls.push(["poke", ...args]); },
setAway: async (...args) => { calls.push(["away", ...args]); },
setInputMuted: async (...args) => { calls.push(["mute", ...args]); },
setAccompanimentActive: async (...args) => { calls.push(["accompaniment", ...args]); },
},
channelTree: [{ id: "18446744073709551615", parentID: "0", name: "Large ID" }],
members,
@@ -134,6 +135,23 @@ test("chat routing uses the current channel, server scope, and private target in
assert.deepEqual(f.messages.at(-1), { type: "commandCompleted", requestId: "empty" });
});
test("accompaniment changes reach the mixer only after TeamSpeak accepts them", async () => {
const f = fixture();
let active = false;
f.context.webrtc = {
getStats: createAudioFlowStats, setMicrophoneMuted() {}, setMemberVolume() {},
setAccompanimentActive: value => { active = value; },
};
f.context.tsClient.setAccompanimentActive = async () => { throw Object.assign(new Error("denied"), { id: 2568 }); };
await f.run({ type: "setAccompanimentActive", payload: { active: true }, requestId: "music-denied" });
assert.equal(active, false);
assert.equal(f.messages.at(-1)?.type, "error");
f.context.tsClient.setAccompanimentActive = async () => {};
await f.run({ type: "setAccompanimentActive", payload: { active: true }, requestId: "music-ok" });
assert.equal(active, true);
assert.deepEqual(f.messages.at(-1), { type: "commandCompleted", requestId: "music-ok" });
});
test("audio probing is bounded per session and accepts the next request at the interval boundary", async () => {
const f = fixture();
f.context.audio.ingressFrames = 8;
+6 -2
View File
@@ -9,7 +9,7 @@ import { teamSpeakServerErrorCode } from "../errors.js";
/** Only the session capabilities used by control commands cross this boundary. */
export interface VoiceCommandContext extends AudioStatsSource {
tsClient: Pick<TSClient, "execCommandWithResponse" | "switchChannel" | "getClientId" | "getChannelId" | "moveClient" | "sendTextMessage" | "poke" | "setAway" | "setInputMuted">;
tsClient: Pick<TSClient, "execCommandWithResponse" | "switchChannel" | "getClientId" | "getChannelId" | "moveClient" | "sendTextMessage" | "poke" | "setAway" | "setInputMuted" | "setAccompanimentActive">;
channelTree: ChannelInfo[];
members: ReadonlyMap<number, { uid?: string }>;
whisperTargetIds: Set<number>;
@@ -154,7 +154,11 @@ export async function handleCommand(
await entry.tsClient.setInputMuted(muted);
entry.webrtc?.setMicrophoneMuted(muted);
} else if (command.type === "setAccompanimentActive") {
entry.webrtc?.setAccompanimentActive(command.payload.active);
const peer = entry.webrtc;
if (peer) {
await entry.tsClient.setAccompanimentActive(command.payload.active);
if (entry.webrtc === peer) peer.setAccompanimentActive(command.payload.active);
}
} else if (command.type === "setMemberVolume") {
const clientId = command.payload.clientId;
entry.webrtc?.setMemberVolume(clientId, command.payload.volume);