web: watch several streams at once

Viewer state was a single slot, so opening a second stream closed the
first. It is now keyed by publisher clid: each stream gets its own
StreamViewer and panel (they already stack bottom-right), "watch" on a
stream that is open is a no-op, and closing one leaves the others running.
StreamViewer already ignored events for other stream ids, so only the app
state changed.

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-11-30 21:25:59 +00:00
1 parent f2d9115782
commit 73ae268dfb
1 file changed
+55 -43
+55 -43
View File
@@ -135,6 +135,13 @@ import {
type StreamPublishOptions, type StreamPublishOptions,
} from "./publish"; } from "./publish";
import { DEFAULT_ICE_SERVERS, StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream"; import { DEFAULT_ICE_SERVERS, StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream";
interface WatchedStream {
info: StreamInfo;
media: MediaStream | null;
state: RTCPeerConnectionState;
error: string | null;
}
import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode"; import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode";
import { import {
DEFAULT_SYNC_SERVER, DEFAULT_SYNC_SERVER,
@@ -9007,11 +9014,9 @@ function AppInner() {
const [clientVolumes, setClientVolumes] = useState<Record<string, number>>(loadClientVolumes); const [clientVolumes, setClientVolumes] = useState<Record<string, number>>(loadClientVolumes);
/** Stream metadata per publishing client id, keyed by clid. */ /** Stream metadata per publishing client id, keyed by clid. */
const [streamInfos, setStreamInfos] = useState<Record<number, StreamInfo>>({}); const [streamInfos, setStreamInfos] = useState<Record<number, StreamInfo>>({});
const [watchedStream, setWatchedStream] = useState<StreamInfo | null>(null); /** Streams being watched, keyed by the publisher's clid - several at once, like Discord. */
const [streamMedia, setStreamMedia] = useState<MediaStream | null>(null); const [watchedStreams, setWatchedStreams] = useState<Record<number, WatchedStream>>({});
const [streamState, setStreamState] = useState<RTCPeerConnectionState>("new"); const streamViewersRef = useRef<Map<number, StreamViewer>>(new Map());
const [streamError, setStreamError] = useState<string | null>(null);
const streamViewerRef = useRef<StreamViewer | null>(null);
const [publishState, setPublishState] = useState<PublishState>("idle"); const [publishState, setPublishState] = useState<PublishState>("idle");
const [publishViewers, setPublishViewers] = useState<number[]>([]); const [publishViewers, setPublishViewers] = useState<number[]>([]);
const [publishPending, setPublishPending] = useState<[number, string][]>([]); const [publishPending, setPublishPending] = useState<[number, string][]>([]);
@@ -9019,7 +9024,6 @@ function AppInner() {
const publisherRef = useRef<StreamPublisher | null>(null); const publisherRef = useRef<StreamPublisher | null>(null);
const publishPreviewRef = useRef<HTMLVideoElement | null>(null); const publishPreviewRef = useRef<HTMLVideoElement | null>(null);
const [streamSettingsOpen, setStreamSettingsOpen] = useState(false); const [streamSettingsOpen, setStreamSettingsOpen] = useState(false);
const streamVideoRef = useRef<HTMLVideoElement | null>(null);
/** Clients we already pulled a `notifystreaminfo` for, so we ask only once. */ /** Clients we already pulled a `notifystreaminfo` for, so we ask only once. */
const requestedStreamInfoRef = useRef<Set<number>>(new Set()); const requestedStreamInfoRef = useRef<Set<number>>(new Set());
/** Stable self id from the connector (`own_client_id`); nickname match is fallback only. */ /** Stable self id from the connector (`own_client_id`); nickname match is fallback only. */
@@ -10394,7 +10398,7 @@ function AppInner() {
}); });
} }
} }
streamViewerRef.current?.handleEvent(streamEvent); for (const viewer of streamViewersRef.current.values()) viewer.handleEvent(streamEvent);
publisherRef.current?.handleEvent(streamEvent); publisherRef.current?.handleEvent(streamEvent);
break; break;
} }
@@ -10471,10 +10475,7 @@ function AppInner() {
appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" }); appendLog({ text: `Disconnected: ${data.reason}`, kind: "info" });
logClient("info", "Connection", `Disconnected: ${data.reason}`); logClient("info", "Connection", `Disconnected: ${data.reason}`);
if (wasConnected) void notify("CONNECTION_DISCONNECTED"); if (wasConnected) void notify("CONNECTION_DISCONNECTED");
streamViewerRef.current?.close(); handleStopWatchingStream();
streamViewerRef.current = null;
setWatchedStream(null);
setStreamMedia(null);
setStreamInfos({}); setStreamInfos({});
requestedStreamInfoRef.current.clear(); requestedStreamInfoRef.current.clear();
publisherRef.current?.stop(); publisherRef.current?.stop();
@@ -12143,11 +12144,6 @@ function AppInner() {
}); });
}, [clients]); }, [clients]);
useEffect(() => {
const video = streamVideoRef.current;
if (video && video.srcObject !== streamMedia) video.srcObject = streamMedia;
}, [streamMedia, watchedStream]);
useEffect(() => { useEffect(() => {
// The publisher owns the capture; the preview only mirrors it, so it is // The publisher owns the capture; the preview only mirrors it, so it is
// read off the peer connection's senders rather than kept in state. // read off the peer connection's senders rather than kept in state.
@@ -12157,35 +12153,43 @@ function AppInner() {
if (video.srcObject !== media) video.srcObject = media; if (video.srcObject !== media) video.srcObject = media;
}, [publishState, publishViewers]); }, [publishState, publishViewers]);
const handleStopWatchingStream = () => { /** Stops one watched stream, or all of them without a clid. */
// close() sends leaveStream and fires onClosed, which clears the rest. const handleStopWatchingStream = (clientId?: number) => {
streamViewerRef.current?.close(); const viewers = streamViewersRef.current;
streamViewerRef.current = null; const ids = clientId === undefined ? [...viewers.keys()] : [clientId];
setWatchedStream(null); for (const id of ids) {
setStreamMedia(null); // close() sends leaveStream; delete first so its onClosed is a no-op.
setStreamState("new"); const viewer = viewers.get(id);
viewers.delete(id);
viewer?.close();
}
setWatchedStreams((prev) => {
if (clientId === undefined) return {};
const next = { ...prev };
delete next[clientId];
return next;
});
}; };
const handleWatchStream = (clientId: number) => { const handleWatchStream = (clientId: number) => {
const info = streamInfos[clientId]; const info = streamInfos[clientId];
if (!info) return; if (!info || streamViewersRef.current.has(clientId)) return;
handleStopWatchingStream(); const patch = (change: Partial<WatchedStream>) =>
setStreamError(null); setWatchedStreams((prev) => (prev[clientId] ? { ...prev, [clientId]: { ...prev[clientId], ...change } } : prev));
const viewer = new StreamViewer(info.id, info.clientId, { const viewer = new StreamViewer(info.id, info.clientId, {
send: (message) => socketRef.current?.send(JSON.stringify(message)), send: (message) => socketRef.current?.send(JSON.stringify(message)),
onTrack: setStreamMedia, onTrack: (media) => patch({ media }),
iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers], iceServers: [...DEFAULT_ICE_SERVERS, ...turnServers],
onStateChange: setStreamState, onStateChange: (state) => patch({ state }),
onError: setStreamError, onError: (error) => patch({ error }),
onClosed: () => { onClosed: () => {
// Also reached when the publisher stops, not just via the close button. // Also reached when the publisher stops, not just via the close button.
streamViewerRef.current = null; if (streamViewersRef.current.get(clientId) !== viewer) return;
setWatchedStream(null); handleStopWatchingStream(clientId);
setStreamMedia(null);
}, },
}); });
streamViewerRef.current = viewer; streamViewersRef.current.set(clientId, viewer);
setWatchedStream(info); setWatchedStreams((prev) => ({ ...prev, [clientId]: { info, media: null, state: "new", error: null } }));
viewer.join(); viewer.join();
}; };
@@ -14270,7 +14274,7 @@ function AppInner() {
onCancel={() => setStreamSettingsOpen(false)} onCancel={() => setStreamSettingsOpen(false)}
/> />
)} )}
{(watchedStream || (publishState !== "idle" && publishState !== "stopped")) && ( {(Object.keys(watchedStreams).length > 0 || (publishState !== "idle" && publishState !== "stopped")) && (
<div className="ts-stream-panels"> <div className="ts-stream-panels">
{publishState !== "idle" && publishState !== "stopped" && ( {publishState !== "idle" && publishState !== "stopped" && (
<div className="ts-stream-panel ts-stream-panel-publish"> <div className="ts-stream-panel ts-stream-panel-publish">
@@ -14320,28 +14324,36 @@ function AppInner() {
{publishError && <div className="ts-stream-panel-error">{publishError}</div>} {publishError && <div className="ts-stream-panel-error">{publishError}</div>}
</div> </div>
)} )}
{watchedStream && ( {Object.entries(watchedStreams).map(([clid, watched]) => (
<div className="ts-stream-panel"> <div className="ts-stream-panel" key={clid}>
<div className="ts-stream-panel-header"> <div className="ts-stream-panel-header">
<span className="ts-stream-panel-title"> <span className="ts-stream-panel-title">
📺 {watchedStream.name || t("stream.untitled")} <AlphaBadge /> 📺 {watched.info.name || t("stream.untitled")} <AlphaBadge />
</span> </span>
<span className="ts-stream-panel-state"> <span className="ts-stream-panel-state">
{streamState === "connected" ? t("stream.live") : t(`stream.state.${streamState}`)} {watched.state === "connected" ? t("stream.live") : t(`stream.state.${watched.state}`)}
</span> </span>
<button <button
className="ts-stream-panel-close" className="ts-stream-panel-close"
onClick={handleStopWatchingStream} onClick={() => handleStopWatchingStream(Number(clid))}
title={t("stream.stop")} title={t("stream.stop")}
> >
✕ ✕
</button> </button>
</div> </div>
{/* muted so autoplay is never blocked; the user unmutes via the controls */} {/* muted so autoplay is never blocked; the user unmutes via the controls */}
<video ref={streamVideoRef} autoPlay playsInline muted controls /> <video
{streamError && <div className="ts-stream-panel-error">{streamError}</div>} ref={(video) => {
if (video && video.srcObject !== watched.media) video.srcObject = watched.media;
}}
autoPlay
playsInline
muted
controls
/>
{watched.error && <div className="ts-stream-panel-error">{watched.error}</div>}
</div> </div>
)} ))}
</div> </div>
)} )}
{clientContextMenu && ( {clientContextMenu && (