feat: per-speaker volume and a gateway feature handshake

The gateway now greets every browser with {type:"hello", features:[...]} so
the hosted client, which updates on every push, can hide what an older
gateway cannot do instead of hanging on it. A gateway without "hello" is
treated as the v0.14 feature set, which replaces the hand-flipped
STREAM_UI_ENABLED switch.

First feature behind it: "clientVolume". The client context menu gets a
0-200% slider, stored per client UID in localStorage. The connector applies
it to tsclientlib's per-speaker AudioQueue.volume while mixing, and keeps the
value across talk pauses, when that queue is torn down and recreated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
MoepchiandClaude Opus 5.5 committed 2026-10-03 00:34:12 +00:00
1 parent c0778c8adb
commit 7b3cb5ef09
10 files changed
+150 -31

No files matched your search

+3 -9
View File
@@ -27,15 +27,9 @@ This roadmap is intentionally outcome-focused. It does not promise fixed dates.
does not document, so the wire format was derived from observed behavior and
may break with any TS6 update. Connection setup, picture quality, and viewer
admission are not yet dependable. The "Server" connection mode (TS6's SFU) is
not implemented; only direct P2P works. The UI is gated by a build-time flag,
because the hosted client updates on every push while the gateway image is
deployed by hand, and a browser that offers streaming to a gateway too old to
answer waits forever instead of reporting an error — on since 2026-09-11 for
client.webspeak3.de now that its gateway answers setupStream/joinStream/
sendStreamSignal (v0.11.0-beta.1+). The durable fix is a capability handshake
so the client can detect what its gateway supports rather than assuming;
until then the flag is flipped by hand whenever the frontend gains a stream
feature the deployed gateway doesn't have yet.
not implemented; only direct P2P works. Streaming needs a gateway from v0.11.0-beta.1
on; since v0.15 the gateway announces its features when the browser connects,
so newer features stay hidden behind an older gateway instead of hanging.
- Safari and Mobile Safari audio/microphone behavior
- Uncommon TeamSpeak permission combinations and large permission sets
- Very large servers and long-running browser sessions
+32
View File
@@ -976,6 +976,10 @@ async fn run(args: Args) -> Result<()> {
)?;
let mut audio_handler = AudioHandler::<ClientId>::new();
let mut talking: HashSet<u16> = HashSet::new();
// Per-speaker playback volume set by the browser (`clientvolume`). Kept
// outside the AudioHandler because its queues only live while someone
// talks; a new queue picks its volume up from here.
let mut client_volumes: HashMap<u16, f32> = HashMap::new();
let mut audio_ticker = tokio::time::interval(tokio::time::Duration::from_millis(20));
// Commands sent via `send()` fail silently if the server rejects them (e.g.
// missing permission) - no reply is sent back without a return code. Using
@@ -1311,6 +1315,28 @@ async fn run(args: Args) -> Result<()> {
if let Err(e) = part.send(&mut con) {
emit(&Event::Error { message: e.to_string() });
}
} else if let Some(rest) = l.strip_prefix("clientvolume ") {
// `clientvolume <clid> <factor>`, 1 = unchanged, 0 = silent.
let mut parts = rest.split_whitespace();
match (
parts.next().and_then(|v| v.parse::<u16>().ok()),
parts.next().and_then(|v| v.parse::<f32>().ok()).filter(|v| v.is_finite()),
) {
(Some(clid), Some(volume)) => {
let volume = volume.clamp(0.0, 2.0);
if volume == 1.0 {
client_volumes.remove(&clid);
} else {
client_volumes.insert(clid, volume);
}
if let Some(queue) = audio_handler.get_mut_queues().get_mut(&ClientId(clid)) {
queue.volume = volume;
}
}
_ => emit(&Event::Error {
message: format!("Malformed clientvolume command: {rest}"),
}),
}
} else if let Some(rest) = l.strip_prefix("nickname ") {
let part = con.get_state()?.client_update().set_name(rest.trim());
if let Err(e) = part.send(&mut con) {
@@ -2536,6 +2562,12 @@ async fn run(args: Args) -> Result<()> {
};
if let Some(from) = from {
if let Ok(Some(new_talker)) = audio_handler.handle_packet(from, packet) {
if let (Some(&volume), Some(queue)) = (
client_volumes.get(&new_talker.0),
audio_handler.get_mut_queues().get_mut(&new_talker),
) {
queue.volume = volume;
}
if talking.insert(new_talker.0) {
emit(&Event::Talkers { clients: talking.iter().copied().collect() });
}
+13
View File
@@ -115,6 +115,9 @@ const SERVE_STATIC = process.env.WEB_STATIC !== "0";
// issue #12): set on the container, these end up in the served index.html as
// <meta> tags the client reads at startup, so changing them needs no rebuild.
// Meta tags rather than an inline script, which CONTENT_SECURITY_POLICY forbids.
// Sent to every browser in the "hello" message on socket open; see there.
const GATEWAY_FEATURES = ["clientVolume"];
const RUNTIME_CONFIG_META = Object.entries({
"webspeak3-default-server": process.env.DEFAULT_SERVER,
"webspeak3-default-channel": process.env.DEFAULT_CHANNEL,
@@ -628,6 +631,12 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
const ip = clientIp(req);
connectionsPerIp.set(ip, (connectionsPerIp.get(ip) ?? 0) + 1);
// The hosted UI updates on every push, the gateway only when its image is
// pulled, so the browser must not assume a feature exists just because it
// knows about it. A gateway without "hello" (before v0.15) supports the
// v0.14 feature set, streaming included; anything newer gets a name here.
socket.send(JSON.stringify({ type: "hello", features: GATEWAY_FEATURES }));
heartbeats.set(socket, { isAlive: true });
socket.on("pong", () => {
const state = heartbeats.get(socket);
@@ -809,6 +818,10 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
await connection?.setOutputMuted(msg.muted);
break;
}
case "setClientVolume": {
connection?.setClientVolume(Number(msg.clientId), Number(msg.volume));
break;
}
case "setNickname": {
await connection?.setNickname(msg.nickname);
break;
+5
View File
@@ -930,6 +930,11 @@ export class Ts3Connection {
this.writeLine(`muteoutput ${muted ? "1" : "0"}`);
}
/** Playback volume for one speaker, mixed in the connector (1 = unchanged). */
setClientVolume(clientId: number, volume: number): void {
if (Number.isInteger(clientId) && Number.isFinite(volume)) this.writeLine(`clientvolume ${clientId} ${volume}`);
}
async setNickname(nickname: string): Promise<void> {
const sanitized = nickname.replace(/[\r\n]+/g, " ").trim();
if (sanitized) this.writeLine(`nickname ${sanitized}`);
+11
View File
@@ -1417,6 +1417,17 @@
flex: 1;
}
.ts-menu-volume input {
flex: 1;
min-width: 6rem;
}
.ts-menu-volume-value {
min-width: 2.6rem;
text-align: right;
color: var(--text-muted);
}
.ts-menu-item-shortcut {
color: var(--text-muted);
}
+78 -22
View File
@@ -536,6 +536,18 @@ interface Contact {
}
const CONTACTS_KEY = "webspeak3:contacts";
// Per-speaker playback volume by client UID (1 = unchanged), mixed in the
// connector. Keyed by UID so it follows a person across servers and reconnects.
const CLIENT_VOLUMES_KEY = "webspeak3:client-volumes";
function loadClientVolumes(): Record<string, number> {
try {
const raw = localStorage.getItem(CLIENT_VOLUMES_KEY);
return raw ? (JSON.parse(raw) as Record<string, number>) : {};
} catch {
return {};
}
}
function loadContacts(): Contact[] {
try {
@@ -1798,25 +1810,6 @@ const RESOLUTION_CHOICES = [360, 480, 720, 1080, 1440, 0];
const FPS_CHOICES = [5, 30, 60];
const AUDIO_BITRATE_CHOICES = [64, 96, 128, 192, 256, 320];
// Kill switch for the streaming UI.
//
// The frontend and the gateway ship on different schedules: client.webspeak3.de
// is rebuilt by Cloudflare Pages on every push to main, while the gateway and
// connector are a Docker image that has to be pulled onto the host by hand. So
// right after a release the browser can already know about setupStream while
// the gateway it talks to does not - and an unsupported setupStream is not an
// error, it is silence: the publish panel waits at "starting" forever, after
// the browser has already asked the user to share a screen.
//
// Flip this to false again whenever the frontend gains a stream feature the
// deployed gateway does not have yet, and back once it has caught up. The
// durable fix is a capability handshake so the client can tell on its own;
// see ROADMAP.md.
//
// On since 2026-09-11: the gateway on client.webspeak3.de was rebuilt on the
// v0.11.0-beta.1 image and answers setupStream/joinStream/sendStreamSignal.
const STREAM_UI_ENABLED = true;
// Streaming talks to TS6 over a protocol nobody published, so it is marked
// alpha everywhere the user can reach it: the settings dialog, both stream
// panels, and the toolbar button's tooltip.
@@ -6378,6 +6371,9 @@ function AppInner() {
// Gateway-broadcast "notice" (currently: SIGTERM restart warning). Global,
// not per-session - it should show no matter which tab is active.
const [restartNotice, setRestartNotice] = useState<string | null>(null);
// What the gateway announced in its "hello" (gateway/src/index.ts). Empty for
// a gateway older than the handshake, so a feature newer than it stays hidden.
const [gatewayFeatures, setGatewayFeatures] = useState<ReadonlySet<string>>(new Set());
// Terms of use, own-hosted instance only (see IS_OWN_HOSTED_INSTANCE): shown
// mandatorily on first visit, reopenable any time from the menu afterwards.
const [tosOpen, setTosOpen] = useState(false);
@@ -6395,6 +6391,7 @@ function AppInner() {
const [connectError, setConnectError] = useState<string | null>(null);
const [channels, setChannels] = useState<ChannelInfo[]>([]);
const [clients, setClients] = useState<ClientInfo[]>([]);
const [clientVolumes, setClientVolumes] = useState<Record<string, number>>(loadClientVolumes);
/** Stream metadata per publishing client id, keyed by clid. */
const [streamInfos, setStreamInfos] = useState<Record<number, StreamInfo>>({});
const [watchedStream, setWatchedStream] = useState<StreamInfo | null>(null);
@@ -6702,6 +6699,27 @@ function AppInner() {
localStorage.setItem(CONTACTS_KEY, JSON.stringify(contacts));
}, [contacts]);
useEffect(() => {
localStorage.setItem(CLIENT_VOLUMES_KEY, JSON.stringify(clientVolumes));
}, [clientVolumes]);
// Push each visible client's volume to its connector. Remembered per socket,
// so a reconnect (fresh connector) resends everything, and a client id reused
// by someone else gets reset to that person's volume.
const sentClientVolumesRef = useRef(new WeakMap<object, Map<number, number>>());
useEffect(() => {
const socket = socketRef.current;
if (!socket || !connected || !gatewayFeatures.has("clientVolume")) return;
let sent = sentClientVolumesRef.current.get(socket);
if (!sent) sentClientVolumesRef.current.set(socket, (sent = new Map()));
for (const c of clients) {
const volume = clientVolumes[c.uid] ?? 1;
if ((sent.get(c.id) ?? 1) === volume) continue;
socket.send(JSON.stringify({ type: "setClientVolume", clientId: c.id, volume }));
sent.set(c.id, volume);
}
}, [clients, clientVolumes, connected, gatewayFeatures]);
useEffect(() => {
localStorage.setItem(WHISPER_LISTS_KEY, JSON.stringify(whisperLists));
}, [whisperLists]);
@@ -7219,6 +7237,10 @@ function AppInner() {
setRestartNotice(data.messageKey ? t(data.messageKey) : String(data.message || ""));
return;
}
if (data.type === "hello") {
setGatewayFeatures(new Set(Array.isArray(data.features) ? data.features : []));
return;
}
// Inactive tab: update parked snapshot only (no audio playback).
if (sessionId !== activeSessionIdRef.current) {
@@ -10112,7 +10134,6 @@ function AppInner() {
onChange={(e) => setVadThreshold(Number(e.target.value))}
/>
</label>
{STREAM_UI_ENABLED && (
<button
className={`ts-icon-button${publishState === "live" ? " ts-mic-on" : ""}`}
onClick={handleStreamButton}
@@ -10128,7 +10149,6 @@ function AppInner() {
>
{publishState === "live" ? "🛑" : "🖥️"}
</button>
)}
<span className="ts-toolbar-sep" />
<button
className={`ts-icon-button${outputMuted ? " ts-muted-on" : ""}`}
@@ -10798,7 +10818,43 @@ function AppInner() {
<span className="ts-menu-item-icon">👉</span>
<span className="ts-menu-item-label">{t("clientContext.poke")}</span>
</button>
{STREAM_UI_ENABLED && !clientContextMenu.isSelf && streamInfos[clientContextMenu.clientId] && (
{!clientContextMenu.isSelf &&
gatewayFeatures.has("clientVolume") &&
(() => {
const uid = clients.find((c) => c.id === clientContextMenu.clientId)?.uid;
if (!uid) return null;
const percent = Math.round((clientVolumes[uid] ?? 1) * 100);
return (
<label className="ts-menu-item ts-menu-volume" title={t("clientContext.volumeHint")}>
<span className="ts-menu-item-icon">{percent === 0 ? "🔇" : "🔉"}</span>
<input
type="range"
min={0}
max={200}
step={5}
value={percent}
aria-label={t("clientContext.volume")}
onChange={(e) => {
const volume = Number(e.target.value) / 100;
setClientVolumes((prev) => {
const next = { ...prev };
if (volume === 1) delete next[uid];
else next[uid] = volume;
return next;
});
}}
onDoubleClick={() =>
setClientVolumes((prev) => {
const { [uid]: _, ...rest } = prev;
return rest;
})
}
/>
<span className="ts-menu-volume-value">{percent}%</span>
</label>
);
})()}
{!clientContextMenu.isSelf && streamInfos[clientContextMenu.clientId] && (
<button
className="ts-menu-item"
onClick={() => {
+2
View File
@@ -600,6 +600,8 @@
"clientContext.poke": "Anstupsen",
"clientContext.watchStream": "Stream ansehen",
"clientContext.moveTo": "Verschieben in…",
"clientContext.volume": "Lautstärke",
"clientContext.volumeHint": "Nur für dich. Doppelklick setzt auf 100 % zurück.",
"clientContext.copyName": "Namen kopieren",
"clientContext.connectionInfo": "Verbindungsinformationen anzeigen",
"clientContext.addWhisperTarget": "Als Whisper-Ziel hinzufügen",
+2
View File
@@ -600,6 +600,8 @@
"clientContext.poke": "Poke",
"clientContext.watchStream": "Watch stream",
"clientContext.moveTo": "Move to…",
"clientContext.volume": "Volume",
"clientContext.volumeHint": "Only for you. Double-click resets to 100%.",
"clientContext.copyName": "Copy name",
"clientContext.connectionInfo": "Show connection info",
"clientContext.addWhisperTarget": "Add as whisper target",
+2
View File
@@ -599,6 +599,8 @@
"clientContext.poke": "سقلمه",
"clientContext.watchStream": "تماشای پخش زنده",
"clientContext.moveTo": "انتقال به…",
"clientContext.volume": "بلندی صدا",
"clientContext.volumeHint": "فقط برای شما. دوبار کلیک به ۱۰۰٪ برمی‌گرداند.",
"clientContext.copyName": "کپی نام",
"clientContext.connectionInfo": "نمایش اطلاعات اتصال",
"clientContext.addWhisperTarget": "افزودن به مقصدهای نجوا",
+2
View File
@@ -454,6 +454,8 @@
"clientContext.privateChat": "私聊",
"clientContext.poke": "戳一戳",
"clientContext.moveTo": "移动到…",
"clientContext.volume": "音量",
"clientContext.volumeHint": "仅对你生效。双击恢复为 100%。",
"clientContext.copyName": "复制名称",
"clientContext.connectionInfo": "查看连接信息",
"clientContext.addWhisperTarget": "添加为悄悄话目标",