From 9f1a63c9d32b20b0c35bce6ceb47ee7dca34cbbd Mon Sep 17 00:00:00 2001 From: Moepchi Date: Thu, 10 Sep 2026 17:00:20 +0000 Subject: [PATCH 01/17] Pass TS6 stream signaling through connector and gateway tsclientlib dropped every command missing from the message declarations, which silently swallowed TS6's whole Stream/Call signaling exchange: none of the stream commands are declared, so notifystreamsignaling never reached a consumer. That is why the protocol could only be captured with a standalone raw-tsproto tool. handle_command now splits the parse failure - ParseError::UnknownCommand hands the raw line up as StreamItem::UnknownCommand instead of warning and returning, everything else keeps the old behaviour. The connector unescapes the TS wire format and forwards the stream commands as a streamEvent, filtered to notifystream*/notifyrespondjoinstream* so unrelated undeclared commands stay dropped. The JSON payload stays opaque the whole way - SDP and ICE belong to the browser's RTCPeerConnection, not to the connector. Outbound, streamjoin/streamleave/streamsignal join the existing raw OutCommand handlers; parameter names and order are as recovered from TeamSpeak.dll and confirmed against a live TS6 client. The gateway serializes the payload itself so no literal newline can reach the line-based stdin protocol. Nothing renders video yet - the browser side is still missing. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- connector/src/main.rs | 111 +++++++++++++++++++++++++++++++++- gateway/src/index.ts | 21 +++++++ gateway/src/ts3/connection.ts | 24 ++++++++ 3 files changed, 155 insertions(+), 1 deletion(-) diff --git a/connector/src/main.rs b/connector/src/main.rs index b2954b5..5925612 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -1,5 +1,6 @@ use std::borrow::Cow; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::str; use std::time::Duration; use anyhow::Result; @@ -29,6 +30,7 @@ use tsclientlib::{ LicenseType, MaxClients, MessageHandle, MessageTarget, Permission, Reason, ServerGroupId, ServerType, StreamItem, TextMessageTargetMode, TsError, }; +use tsproto_packets::commands::{CommandItem, CommandParser}; use tsproto_packets::packets::{AudioData, CodecType, Direction, Flags, OutAudio, OutCommand, PacketType}; /// 20ms frames at 48kHz, which is what TeamSpeak's Opus voice codec expects. @@ -344,6 +346,16 @@ enum Event { /// anywhere), for populating an "add permission" picker. #[serde(rename = "permissionCatalog")] PermissionCatalog { entries: Vec }, + /// A TS6 Stream/Call command the server sent us, forwarded verbatim. + /// + /// `tsclientlib` has no declarations for these, so they arrive as + /// `StreamItem::UnknownCommand` and are only unescaped here - the payload + /// of `notifystreamsignaling` is an opaque JSON blob (SDP offer/answer, + /// ICE candidates) that belongs to the browser's `RTCPeerConnection`, not + /// to the connector. `name` is the raw command name, e.g. + /// `notifystreamsignaling`. + #[serde(rename = "streamEvent")] + StreamEvent { name: String, args: BTreeMap }, } #[derive(Serialize)] @@ -641,6 +653,57 @@ fn snapshot(con: &data::Connection) -> Event { } } +/// Splits a raw TS command line into its unescaped key/value pairs. +/// +/// Only the first part of a `|`-separated multi-part command is read; none of +/// the stream commands use multiple parts. A flag without `=` becomes an empty +/// string, which is how TeamSpeak treats it too. +fn parse_ts_args(content: &str) -> BTreeMap { + let (_, parser) = CommandParser::new(content.as_bytes()); + let mut args = BTreeMap::new(); + for item in parser { + match item { + CommandItem::Argument(arg) => { + let (Ok(name), Ok(value)) = (str::from_utf8(arg.name()), arg.value().get_str()) + else { + continue; + }; + args.insert(name.to_string(), value.into_owned()); + } + // Stop at the first part boundary. + CommandItem::NextCommand => break, + } + } + args +} + +/// Sends `joinstreamrequest` for a `" [msg]"` argument line. +/// +/// Parameter names and order are as recovered from TS6's `TeamSpeak.dll`; `msg` +/// is written even when empty so the shape matches the native client. +fn send_join_stream_request(con: &mut tsclientlib::Connection, rest: &str, is_remove: bool) { + let mut parts = rest.splitn(3, ' '); + let (Some(id), Some(Ok(clid))) = (parts.next(), parts.next().map(|c| c.parse::())) else { + emit(&Event::Error { message: "Usage: streamjoin [msg]".into() }); + return; + }; + if id.is_empty() { + emit(&Event::Error { message: "Usage: streamjoin [msg]".into() }); + return; + } + let msg = parts.next().unwrap_or(""); + + let mut packet = + OutCommand::new(Direction::C2S, Flags::empty(), PacketType::Command, "joinstreamrequest"); + packet.write_arg("id", &id); + packet.write_arg("clid", &clid); + packet.write_arg("msg", &msg); + packet.write_arg("is_remove", &u8::from(is_remove)); + if let Err(e) = packet.send(con) { + emit(&Event::Error { message: format!("joinstreamrequest failed: {e}") }); + } +} + fn send_server_get_variables(con: &mut tsclientlib::Connection) { let packet = OutCommand::new( Direction::C2S, @@ -1401,6 +1464,42 @@ async fn run(args: Args) -> Result<()> { } Err(e) => emit(&Event::Error { message: e.to_string() }), } + } else if let Some(rest) = l.strip_prefix("streamjoin ") { + // "streamjoin [msg]" - ask the client + // publishing a TS6 stream to let us in. Its reply is a + // notifyrespondjoinstreamrequest carrying the SDP offer. + send_join_stream_request(&mut con, rest, false); + } else if let Some(rest) = l.strip_prefix("streamleave ") { + // Same command with is_remove=1, which is how TS6 leaves + // a stream it has joined. + send_join_stream_request(&mut con, rest, true); + } else if let Some(rest) = l.strip_prefix("streamsignal ") { + // "streamsignal " - the json is + // the rest of the line, opaque to us. Escaping is done by + // write_arg. + let mut parts = rest.splitn(3, ' '); + match (parts.next(), parts.next().and_then(|c| c.parse::().ok()), parts.next()) { + (Some(id), Some(clid), Some(json)) if !id.is_empty() && !json.is_empty() => { + let mut packet = OutCommand::new( + Direction::C2S, + Flags::empty(), + PacketType::Command, + "streamsignaling", + ); + packet.write_arg("id", &id); + packet.write_arg("clid", &clid); + packet.write_arg("json", &json); + // Fire and forget: ICE candidates arrive in bursts + // and a return_code round trip per candidate would + // only add latency to the handshake. + if let Err(e) = packet.send(&mut con) { + emit(&Event::Error { message: format!("streamsignaling failed: {e}") }); + } + } + _ => emit(&Event::Error { + message: "Usage: streamsignal ".into(), + }), + } } else if l == "banlist" { // No typed builder exists for banlist, so this is built as a raw // command; the reply arrives via StreamItem::MessageEvent (see below). @@ -2370,6 +2469,16 @@ async fn run(args: Args) -> Result<()> { } } } + Some(Ok(StreamItem::UnknownCommand { name, content })) => { + // TS6 Stream/Call signaling. Everything else undeclared is + // dropped on purpose - forwarding every unknown command + // would turn this into a firehose, and nothing downstream + // wants it. + if name.starts_with("notifystream") || name.starts_with("notifyrespondjoinstream") + { + emit(&Event::StreamEvent { args: parse_ts_args(&content), name }); + } + } Some(Ok(StreamItem::MessageEvent(msg))) => { // Defense in depth: TeaSpeak/GTS may surface notifyclientpoke as an // unhandled MessageEvent if bookkeeping did not mark it handled. diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 670afa5..59f566a 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -415,6 +415,27 @@ wss.on("connection", (socket: WebSocket) => { await connection?.sendAudio(msg.pcm); break; } + case "joinStream": { + const clientId = Number(msg.clientId); + if (Number.isFinite(clientId)) { + await connection?.joinStream(String(msg.streamId ?? ""), clientId, msg.message ?? ""); + } + break; + } + case "leaveStream": { + const clientId = Number(msg.clientId); + if (Number.isFinite(clientId)) { + await connection?.leaveStream(String(msg.streamId ?? ""), clientId); + } + break; + } + case "streamSignal": { + const clientId = Number(msg.clientId); + if (Number.isFinite(clientId) && msg.payload !== undefined) { + await connection?.sendStreamSignal(String(msg.streamId ?? ""), clientId, msg.payload); + } + break; + } case "setAway": { await connection?.setAway(msg.away, msg.message ?? ""); break; diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index 9796450..509da55 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -774,6 +774,30 @@ export class Ts3Connection { this.child?.stdin.write(`audio ${pcmBase64}\n`); } + /** Ask the client publishing a TS6 stream to let us watch. The answer comes + * back as a `streamEvent` of type `notifyrespondjoinstreamrequest`, which + * carries the SDP offer. */ + async joinStream(streamId: string, clientId: number, message = ""): Promise { + const id = streamId.replace(/[\s]+/g, ""); + const sanitized = message.replace(/[\r\n]+/g, " ").trim(); + if (id) this.child?.stdin.write(`streamjoin ${id} ${clientId} ${sanitized}\n`); + } + + async leaveStream(streamId: string, clientId: number): Promise { + const id = streamId.replace(/[\s]+/g, ""); + if (id) this.child?.stdin.write(`streamleave ${id} ${clientId}\n`); + } + + /** Relays one signaling payload (SDP answer, ICE candidate) to a stream peer. + * `payload` is passed straight through - the connector only escapes it for + * the TS wire, nobody in this path interprets it. Serializing here rather + * than accepting a string keeps literal newlines out of the line-based + * stdin protocol. */ + async sendStreamSignal(streamId: string, clientId: number, payload: unknown): Promise { + const id = streamId.replace(/[\s]+/g, ""); + if (id) this.child?.stdin.write(`streamsignal ${id} ${clientId} ${JSON.stringify(payload)}\n`); + } + async setAway(away: boolean, message: string): Promise { if (away) { const sanitized = message.replace(/[\r\n]+/g, " ").trim(); From 11a413d2b65b760b8cc0cf95ce1f04fae93dbc6a Mon Sep 17 00:00:00 2001 From: Moepchi Date: Thu, 10 Sep 2026 17:11:44 +0000 Subject: [PATCH 02/17] Add requeststreaminfo so late joiners can find a running stream Verified end to end against a live TS6 client: the passthrough delivers notifyrespondjoinstreamrequest with the full SDP offer plus 18 iceCandidate notifies, all correctly unescaped. Getting there turned up a gap. A client entering a channel where a stream is already running receives no stream command at all - 35 s in the channel produced zero undeclared commands. Discovery runs over the ordinary client_is_streaming property instead, and the stream id has to be pulled per client with requeststreaminfo. Without that, only a viewer who happened to be present when the stream started could ever join. The unknown-command names now go to stderr, which is what made the difference between "the server sent nothing" and "we filtered it out" visible at all. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- connector/src/main.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/connector/src/main.rs b/connector/src/main.rs index 5925612..a30a4e5 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -1464,6 +1464,27 @@ async fn run(args: Args) -> Result<()> { } Err(e) => emit(&Event::Error { message: e.to_string() }), } + } else if let Some(rest) = l.strip_prefix("streaminfo ") { + // A late joiner only learns *that* someone streams, from + // the client_is_streaming property; the stream id has to + // be pulled per client with this. + match rest.trim().parse::() { + Ok(clid) => { + let mut packet = OutCommand::new( + Direction::C2S, + Flags::empty(), + PacketType::Command, + "requeststreaminfo", + ); + packet.write_arg("clid", &clid); + if let Err(e) = packet.send(&mut con) { + emit(&Event::Error { message: format!("requeststreaminfo failed: {e}") }); + } + } + Err(_) => emit(&Event::Error { + message: format!("Invalid client id: {rest}"), + }), + } } else if let Some(rest) = l.strip_prefix("streamjoin ") { // "streamjoin [msg]" - ask the client // publishing a TS6 stream to let us in. Its reply is a @@ -2470,6 +2491,10 @@ async fn run(args: Args) -> Result<()> { } } Some(Ok(StreamItem::UnknownCommand { name, content })) => { + // Undeclared commands are invisible everywhere else, so name + // them on stderr - that is the only way to tell "the server + // sent nothing" apart from "we filtered it out". + eprintln!("[unknown-command] {name}"); // TS6 Stream/Call signaling. Everything else undeclared is // dropped on purpose - forwarding every unknown command // would turn this into a firehose, and nothing downstream From 61075014456265716e90c24ac21a26cd70080ef4 Mon Sep 17 00:00:00 2001 From: Moepchi Date: Thu, 10 Sep 2026 17:29:19 +0000 Subject: [PATCH 03/17] Browser: watch a TS6 stream Adds web/src/stream.ts, the receive-only RTCPeerConnection that takes TS6's SDP offer out of notifyrespondjoinstreamrequest, trickles ICE both ways over notifystreamsignaling and hands the remote MediaStream back. App.tsx only wires it up: a client with client_is_streaming gets a requeststreaminfo (that property is the *only* way a late joiner learns a stream is running), a badge in the tree, a context-menu entry and a floating video panel. Also adds the missing requestStreamInfo path in the gateway - the connector already had `streaminfo ` on stdin, nothing could reach it. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- connector/src/main.rs | 6 + gateway/src/index.ts | 5 + gateway/src/ts3/connection.ts | 17 +- web/src/App.css | 59 +++++++ web/src/App.tsx | 136 ++++++++++++++++ web/src/i18n.tsx | 24 +++ web/src/stream.ts | 292 ++++++++++++++++++++++++++++++++++ 7 files changed, 537 insertions(+), 2 deletions(-) create mode 100644 web/src/stream.ts diff --git a/connector/src/main.rs b/connector/src/main.rs index a30a4e5..f62a57b 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -108,6 +108,11 @@ struct ClientInfo { /// ServerQuery client (`ClientType::Query`). Always included in the /// snapshot; the UI hides these unless the user enables them per favorite. is_query: bool, + /// Whether this client is broadcasting a TS6 Stream/Call right now. This is + /// the only way a client that joins late learns a stream exists - the server + /// sends no stream command in that case, so the id has to be fetched with + /// `requeststreaminfo`. Always `false` on servers that don't report it. + is_streaming: bool, } /// Payload for the "serveredit " stdin command - every field is optional so @@ -621,6 +626,7 @@ fn snapshot(con: &data::Connection) -> Event { server_groups: c.server_groups.iter().map(|g| g.0).collect(), has_talk_power, is_query: matches!(c.client_type, ClientType::Query { .. }), + is_streaming: c.is_streaming.unwrap_or(false), } }) .collect::>(); diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 59f566a..0354e05 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -415,6 +415,11 @@ wss.on("connection", (socket: WebSocket) => { await connection?.sendAudio(msg.pcm); break; } + case "requestStreamInfo": { + const clientId = Number(msg.clientId); + if (Number.isFinite(clientId)) await connection?.requestStreamInfo(clientId); + break; + } case "joinStream": { const clientId = Number(msg.clientId); if (Number.isFinite(clientId)) { diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index 509da55..d9cfdef 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -39,6 +39,8 @@ export interface ClientInfo { hasTalkPower: boolean; /** ServerQuery client; UI may hide these unless enabled per favorite. */ isQuery: boolean; + /** Broadcasting a TS6 Stream/Call. The stream id is fetched separately. */ + isStreaming: boolean; } export interface GroupEntry { @@ -184,7 +186,9 @@ export type Ts3ConnectionEvent = | { type: "fileDownloadData"; cid: number; path: string; data: string } | { type: "fileUploadDone"; cid: number; path: string } | { type: "permList"; scope: PermScope; id1: number; id2: number | null; entries: PermissionOverviewEntry[] } - | { type: "permissionCatalog"; entries: PermissionCatalogEntry[] }; + | { type: "permissionCatalog"; entries: PermissionCatalogEntry[] } + /** TS6 Stream/Call signaling, forwarded verbatim; `args` is already unescaped. */ + | { type: "streamEvent"; name: string; args: Record }; export type ServerType = "teamspeak" | "teaspeak" | "auto"; @@ -255,6 +259,7 @@ export class Ts3Connection { server_groups: number[]; has_talk_power: boolean; is_query?: boolean; + is_streaming?: boolean; } interface RawChannelInfo { @@ -384,7 +389,8 @@ export class Ts3Connection { | { type: "fileDownloadData"; cid: number; path: string; data: string } | { type: "fileUploadDone"; cid: number; path: string } | { type: "permList"; scope: PermScope; id1: number; id2: number | null; entries: PermissionOverviewEntry[] } - | { type: "permissionCatalog"; entries: PermissionCatalogEntry[] }; + | { type: "permissionCatalog"; entries: PermissionCatalogEntry[] } + | { type: "streamEvent"; name: string; args: Record }; if (event.type === "connected") { this.emit({ @@ -428,6 +434,7 @@ export class Ts3Connection { serverGroups: c.server_groups, hasTalkPower: c.has_talk_power, isQuery: Boolean(c.is_query), + isStreaming: Boolean(c.is_streaming), })), ownClientId: event.own_client_id ?? 0, serverMaxClients: event.server_max_clients ?? 0, @@ -774,6 +781,12 @@ export class Ts3Connection { this.child?.stdin.write(`audio ${pcmBase64}\n`); } + /** Pulls a streaming client's stream details; answered with a + * `notifystreaminfo` streamEvent carrying the stream id. */ + async requestStreamInfo(clientId: number): Promise { + this.child?.stdin.write(`streaminfo ${clientId}\n`); + } + /** Ask the client publishing a TS6 stream to let us watch. The answer comes * back as a `streamEvent` of type `notifyrespondjoinstreamrequest`, which * carries the SDP offer. */ diff --git a/web/src/App.css b/web/src/App.css index f48e6b6..3cf8e4c 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -1409,6 +1409,65 @@ background: var(--border-soft); } +/* Floating viewer for a TS6 Stream/Call broadcast. */ +.ts-stream-panel { + position: fixed; + right: 1rem; + bottom: 1rem; + z-index: 29; + display: flex; + flex-direction: column; + width: min(480px, calc(100vw - 2rem)); + background: var(--bg-toolbar-1); + border: 1px solid var(--border); + border-radius: 6px; + box-shadow: 0 6px 24px rgba(0, 0, 0, 0.4); + overflow: hidden; +} + +.ts-stream-panel-header { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.35rem 0.5rem; + border-bottom: 1px solid var(--border-soft); +} + +.ts-stream-panel-title { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-weight: 600; +} + +.ts-stream-panel-state { + opacity: 0.7; + font-size: 0.85em; +} + +.ts-stream-panel-close { + padding: 0 0.35rem; + background: none; + border: none; + color: inherit; + cursor: pointer; +} + +.ts-stream-panel video { + width: 100%; + /* Letterbox rather than crop - TS6 screen shares are not always 16:9. */ + aspect-ratio: 16 / 9; + background: #000; + object-fit: contain; +} + +.ts-stream-panel-error { + padding: 0.35rem 0.5rem; + color: var(--danger, #e05a5a); + font-size: 0.85em; +} + .ts-context-menu { position: fixed; z-index: 30; diff --git a/web/src/App.tsx b/web/src/App.tsx index f6e87ce..96393c8 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -26,6 +26,7 @@ import { pickAudioOutputDevice, } from "./voice"; import { LanguageProvider, useLanguage, useT, type LangPref } from "./i18n"; +import { StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream"; import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode"; import { SOUND_EVENTS, @@ -506,6 +507,8 @@ interface ClientInfo { channelGroup: number; serverGroups: number[]; hasTalkPower: boolean; + /** TS6 Stream/Call broadcast running; absent on servers that don't report it. */ + isStreaming?: boolean; /** ServerQuery client; filtered from the tree unless a favorite enables them. */ isQuery?: boolean; } @@ -705,6 +708,7 @@ function ClientStatusIcons({ client }: { client: ClientInfo }) { 🔒 )} {client.outputMuted && 🔕} + {client.isStreaming && 📺} ); } @@ -5355,6 +5359,16 @@ function AppInner() { const [connectError, setConnectError] = useState(null); const [channels, setChannels] = useState([]); const [clients, setClients] = useState([]); + /** Stream metadata per publishing client id, keyed by clid. */ + const [streamInfos, setStreamInfos] = useState>({}); + const [watchedStream, setWatchedStream] = useState(null); + const [streamMedia, setStreamMedia] = useState(null); + const [streamState, setStreamState] = useState("new"); + const [streamError, setStreamError] = useState(null); + const streamViewerRef = useRef(null); + const streamVideoRef = useRef(null); + /** Clients we already pulled a `notifystreaminfo` for, so we ask only once. */ + const requestedStreamInfoRef = useRef>(new Set()); /** Stable self id from the connector (`own_client_id`); nickname match is fallback only. */ const [ownClientId, setOwnClientId] = useState(null); const [serverName, setServerName] = useState(""); @@ -6228,6 +6242,26 @@ function AppInner() { case "talkers": setTalkers(new Set(data.clients)); break; + case "streamEvent": { + const streamEvent = data as StreamEvent; + if (streamEvent.name === "notifystreaminfo" || streamEvent.name === "notifystreamstarted") { + const info = parseStreamInfo(streamEvent.args); + if (info) setStreamInfos((prev) => ({ ...prev, [info.clientId]: info })); + } + if (streamEvent.name === "notifystreamstopped") { + const clid = Number(streamEvent.args.clid); + if (Number.isFinite(clid)) { + setStreamInfos((prev) => { + if (!(clid in prev)) return prev; + const next = { ...prev }; + delete next[clid]; + return next; + }); + } + } + streamViewerRef.current?.handleEvent(streamEvent); + break; + } case "poke": { const id = ++pokeIdRef.current; setPokes((prev) => [...prev, { id, from: data.from, message: data.message }]); @@ -6281,6 +6315,12 @@ function AppInner() { appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" }); logClient("info", "Connection", `Disconnected: ${data.reason}`); if (wasConnected) void playSound("disconnect"); + streamViewerRef.current?.close(); + streamViewerRef.current = null; + setWatchedStream(null); + setStreamMedia(null); + setStreamInfos({}); + requestedStreamInfoRef.current.clear(); removeSession(sessionId, { skipSocketClose: true }); break; } @@ -7512,6 +7552,68 @@ function AppInner() { reader.readAsText(file); }; + // --- TS6 Stream/Call ----------------------------------------------------- + // + // A client that was already streaming when we joined announces nothing: TS6 + // only sets the `client_is_streaming` property, and the stream id has to be + // pulled with `requeststreaminfo` (ts6-re findings 6b). So whenever a + // streaming client shows up in the tree, ask once. + useEffect(() => { + const streaming = new Set(clients.filter((c) => c.isStreaming).map((c) => c.id)); + for (const id of streaming) { + if (requestedStreamInfoRef.current.has(id)) continue; + requestedStreamInfoRef.current.add(id); + socketRef.current?.send(JSON.stringify({ type: "requestStreamInfo", clientId: id })); + } + // Forget clients that stopped, so a later stream is looked up again. + for (const id of requestedStreamInfoRef.current) { + if (!streaming.has(id)) requestedStreamInfoRef.current.delete(id); + } + setStreamInfos((prev) => { + const stale = Object.keys(prev).filter((id) => !streaming.has(Number(id))); + if (stale.length === 0) return prev; + const next = { ...prev }; + for (const id of stale) delete next[Number(id)]; + return next; + }); + }, [clients]); + + useEffect(() => { + const video = streamVideoRef.current; + if (video && video.srcObject !== streamMedia) video.srcObject = streamMedia; + }, [streamMedia, watchedStream]); + + const handleStopWatchingStream = () => { + // close() sends leaveStream and fires onClosed, which clears the rest. + streamViewerRef.current?.close(); + streamViewerRef.current = null; + setWatchedStream(null); + setStreamMedia(null); + setStreamState("new"); + }; + + const handleWatchStream = (clientId: number) => { + const info = streamInfos[clientId]; + if (!info) return; + handleStopWatchingStream(); + setStreamError(null); + const viewer = new StreamViewer(info.id, info.clientId, { + send: (message) => socketRef.current?.send(JSON.stringify(message)), + onTrack: setStreamMedia, + onStateChange: setStreamState, + onError: setStreamError, + onClosed: () => { + // Also reached when the publisher stops, not just via the close button. + streamViewerRef.current = null; + setWatchedStream(null); + setStreamMedia(null); + }, + }); + streamViewerRef.current = viewer; + setWatchedStream(info); + viewer.join(); + }; + const handleShowClientConnectionInfo = (clientId: number, clientName: string) => { setClientConnectionInfoTarget({ id: clientId, name: clientName }); setClientConnectionInfo(null); @@ -9148,6 +9250,28 @@ function AppInner() { ))} + {watchedStream && ( +
+
+ + 📺 {watchedStream.name || t("stream.untitled")} + + + {streamState === "connected" ? t("stream.live") : t(`stream.state.${streamState}`)} + + +
+ {/* muted so autoplay is never blocked; the user unmutes via the controls */} +
+ )} {clientContextMenu && (
👉 {t("clientContext.poke")} + {!clientContextMenu.isSelf && streamInfos[clientContextMenu.clientId] && ( + + )} {!clientContextMenu.isSelf && ( +
+ {/* muted: this is our own capture playing back locally */} +