mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-01 00:42:49 +08:00
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 <clid>` on stdin, nothing could reach it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
1 parent
11a413d2b6
commit
6107501445
7 files changed
+537
-2
No files matched your search
@@ -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::<Vec<_>>();
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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<string, string> };
|
||||
|
||||
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<string, string> };
|
||||
|
||||
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<void> {
|
||||
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. */
|
||||
|
||||
@@ -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;
|
||||
|
||||
+136
@@ -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 }) {
|
||||
<span title={t("tree.noTalkPower")}>🔒</span>
|
||||
)}
|
||||
{client.outputMuted && <span title={t("tree.soundMuted")}>🔕</span>}
|
||||
{client.isStreaming && <span title={t("tree.streaming")}>📺</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -5355,6 +5359,16 @@ function AppInner() {
|
||||
const [connectError, setConnectError] = useState<string | null>(null);
|
||||
const [channels, setChannels] = useState<ChannelInfo[]>([]);
|
||||
const [clients, setClients] = useState<ClientInfo[]>([]);
|
||||
/** Stream metadata per publishing client id, keyed by clid. */
|
||||
const [streamInfos, setStreamInfos] = useState<Record<number, StreamInfo>>({});
|
||||
const [watchedStream, setWatchedStream] = useState<StreamInfo | null>(null);
|
||||
const [streamMedia, setStreamMedia] = useState<MediaStream | null>(null);
|
||||
const [streamState, setStreamState] = useState<RTCPeerConnectionState>("new");
|
||||
const [streamError, setStreamError] = useState<string | null>(null);
|
||||
const streamViewerRef = useRef<StreamViewer | null>(null);
|
||||
const streamVideoRef = useRef<HTMLVideoElement | null>(null);
|
||||
/** Clients we already pulled a `notifystreaminfo` for, so we ask only once. */
|
||||
const requestedStreamInfoRef = useRef<Set<number>>(new Set());
|
||||
/** Stable self id from the connector (`own_client_id`); nickname match is fallback only. */
|
||||
const [ownClientId, setOwnClientId] = useState<number | null>(null);
|
||||
const [serverName, setServerName] = useState("");
|
||||
@@ -6228,6 +6242,26 @@ function AppInner() {
|
||||
case "talkers":
|
||||
setTalkers(new Set<number>(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() {
|
||||
</div>
|
||||
))}
|
||||
|
||||
{watchedStream && (
|
||||
<div className="ts-stream-panel">
|
||||
<div className="ts-stream-panel-header">
|
||||
<span className="ts-stream-panel-title">
|
||||
📺 {watchedStream.name || t("stream.untitled")}
|
||||
</span>
|
||||
<span className="ts-stream-panel-state">
|
||||
{streamState === "connected" ? t("stream.live") : t(`stream.state.${streamState}`)}
|
||||
</span>
|
||||
<button
|
||||
className="ts-stream-panel-close"
|
||||
onClick={handleStopWatchingStream}
|
||||
title={t("stream.stop")}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
{/* muted so autoplay is never blocked; the user unmutes via the controls */}
|
||||
<video ref={streamVideoRef} autoPlay playsInline muted controls />
|
||||
{streamError && <div className="ts-stream-panel-error">{streamError}</div>}
|
||||
</div>
|
||||
)}
|
||||
{clientContextMenu && (
|
||||
<div
|
||||
ref={clientContextMenuRef}
|
||||
@@ -9177,6 +9301,18 @@ function AppInner() {
|
||||
<span className="ts-menu-item-icon">👉</span>
|
||||
<span className="ts-menu-item-label">{t("clientContext.poke")}</span>
|
||||
</button>
|
||||
{!clientContextMenu.isSelf && streamInfos[clientContextMenu.clientId] && (
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
onClick={() => {
|
||||
handleWatchStream(clientContextMenu.clientId);
|
||||
setClientContextMenu(null);
|
||||
}}
|
||||
>
|
||||
<span className="ts-menu-item-icon">📺</span>
|
||||
<span className="ts-menu-item-label">{t("clientContext.watchStream")}</span>
|
||||
</button>
|
||||
)}
|
||||
{!clientContextMenu.isSelf && (
|
||||
<button
|
||||
className="ts-menu-item"
|
||||
|
||||
@@ -375,6 +375,17 @@ const translations: Record<Lang, Record<string, string>> = {
|
||||
"tree.talking": "Spricht",
|
||||
"tree.noTalkPower": "Keine Redeerlaubnis in diesem Channel",
|
||||
"tree.soundMuted": "Ton stummgeschaltet (deafened)",
|
||||
"tree.streaming": "Überträgt einen Stream",
|
||||
|
||||
"stream.untitled": "Stream",
|
||||
"stream.stop": "Stream schließen",
|
||||
"stream.live": "Live",
|
||||
"stream.state.new": "Warte auf Angebot…",
|
||||
"stream.state.connecting": "Verbinde…",
|
||||
"stream.state.connected": "Live",
|
||||
"stream.state.disconnected": "Verbindung unterbrochen",
|
||||
"stream.state.failed": "Verbindung fehlgeschlagen",
|
||||
"stream.state.closed": "Beendet",
|
||||
|
||||
"chat.server": "Server",
|
||||
"chat.channel": "Channel",
|
||||
@@ -544,6 +555,7 @@ const translations: Record<Lang, Record<string, string>> = {
|
||||
|
||||
"clientContext.privateChat": "Privater Chat",
|
||||
"clientContext.poke": "Anstupsen",
|
||||
"clientContext.watchStream": "Stream ansehen",
|
||||
"clientContext.moveTo": "Verschieben in…",
|
||||
"clientContext.copyName": "Namen kopieren",
|
||||
"clientContext.connectionInfo": "Verbindungsinformationen anzeigen",
|
||||
@@ -964,6 +976,17 @@ const translations: Record<Lang, Record<string, string>> = {
|
||||
"tree.talking": "Talking",
|
||||
"tree.noTalkPower": "No talk power in this channel",
|
||||
"tree.soundMuted": "Sound muted (deafened)",
|
||||
"tree.streaming": "Broadcasting a stream",
|
||||
|
||||
"stream.untitled": "Stream",
|
||||
"stream.stop": "Close stream",
|
||||
"stream.live": "Live",
|
||||
"stream.state.new": "Waiting for offer…",
|
||||
"stream.state.connecting": "Connecting…",
|
||||
"stream.state.connected": "Live",
|
||||
"stream.state.disconnected": "Connection interrupted",
|
||||
"stream.state.failed": "Connection failed",
|
||||
"stream.state.closed": "Ended",
|
||||
|
||||
"chat.server": "Server",
|
||||
"chat.channel": "Channel",
|
||||
@@ -1133,6 +1156,7 @@ const translations: Record<Lang, Record<string, string>> = {
|
||||
|
||||
"clientContext.privateChat": "Private chat",
|
||||
"clientContext.poke": "Poke",
|
||||
"clientContext.watchStream": "Watch stream",
|
||||
"clientContext.moveTo": "Move to…",
|
||||
"clientContext.copyName": "Copy name",
|
||||
"clientContext.connectionInfo": "Show connection info",
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
// Viewing a TeamSpeak 6 Stream/Call broadcast in the browser.
|
||||
//
|
||||
// TS6's stream signaling rides the ordinary TS3 command channel, so everything
|
||||
// here travels the same WebSocket as the rest of the session: the connector
|
||||
// unescapes the TS wire format and hands us the JSON payload untouched (see
|
||||
// ts6-re/findings/ts6-stream-protocol-static-analysis.md).
|
||||
//
|
||||
// The exchange, from our side:
|
||||
//
|
||||
// 1. discover client_is_streaming=1 on a client in view
|
||||
// 2. joinStream -> notifyrespondjoinstreamrequest (decision=1 + SDP offer)
|
||||
// 3. answer <- streamSignal {cmd:"answer"}
|
||||
// 4. trickle ICE both directions via {cmd:"iceCandidate"}
|
||||
//
|
||||
// TS6 publishes sendonly, so this is a receive-only peer connection.
|
||||
|
||||
/** A `streamEvent` as the connector emits it. */
|
||||
export interface StreamEvent {
|
||||
type: "streamEvent";
|
||||
name: string;
|
||||
args: Record<string, string>;
|
||||
}
|
||||
|
||||
/** The payload shape inside `notifystreamsignaling`'s `json` argument. */
|
||||
interface SignalingMessage {
|
||||
cmd: string;
|
||||
args: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface StreamInfo {
|
||||
id: string;
|
||||
clientId: number;
|
||||
name: string;
|
||||
/** Current viewer count as of the last notifystreaminfo. */
|
||||
viewers: number;
|
||||
hasAudio: boolean;
|
||||
bitrate: number;
|
||||
}
|
||||
|
||||
export interface StreamViewerOptions {
|
||||
/** Sends one message up the session WebSocket. */
|
||||
send: (message: Record<string, unknown>) => void;
|
||||
/** The remote media, once the first track arrives. */
|
||||
onTrack: (stream: MediaStream) => void;
|
||||
onStateChange?: (state: RTCPeerConnectionState) => void;
|
||||
onError?: (error: string) => void;
|
||||
/** The viewer shut down — by us, or because the publisher stopped. */
|
||||
onClosed?: () => void;
|
||||
/**
|
||||
* ICE servers to use. TS6 itself only ever configures `stun:` URLs and so
|
||||
* never gathers a relay candidate, but it will happily *connect* to one we
|
||||
* offer - which is how webspeak3 can work on networks where TS6 cannot.
|
||||
*/
|
||||
iceServers?: RTCIceServer[];
|
||||
}
|
||||
|
||||
const DEFAULT_ICE_SERVERS: RTCIceServer[] = [
|
||||
{ urls: "stun:turn.teamspeak.com:3478" },
|
||||
{ urls: "stun:turn2.teamspeak.com:3478" },
|
||||
{ urls: "stun:stun.l.google.com:19302" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Reads a stream's properties out of a `notifystreaminfo` / `notifystreamstarted`.
|
||||
*
|
||||
* The two notifies disagree on one name: `notifystreaminfo` says
|
||||
* `accessibility`, `notifystreamstarted` shortens it to `access`. Only
|
||||
* `notifystreaminfo` carries `viewer`.
|
||||
*/
|
||||
export function parseStreamInfo(args: Record<string, string>): StreamInfo | null {
|
||||
const id = args.id;
|
||||
const clientId = Number(args.clid);
|
||||
if (!id || !Number.isFinite(clientId)) return null;
|
||||
return {
|
||||
id,
|
||||
clientId,
|
||||
name: args.name ?? "",
|
||||
viewers: Number(args.viewer ?? 0) || 0,
|
||||
hasAudio: args.audio === "1",
|
||||
bitrate: Number(args.bitrate ?? 0) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
export class StreamViewer {
|
||||
private pc: RTCPeerConnection | null = null;
|
||||
private readonly opts: StreamViewerOptions;
|
||||
private readonly remote = new MediaStream();
|
||||
|
||||
/** Candidates that arrived before setRemoteDescription; replayed after. */
|
||||
private pendingRemoteCandidates: RTCIceCandidateInit[] = [];
|
||||
private remoteDescriptionSet = false;
|
||||
private closed = false;
|
||||
|
||||
readonly streamId: string;
|
||||
readonly peerClientId: number;
|
||||
|
||||
constructor(streamId: string, peerClientId: number, opts: StreamViewerOptions) {
|
||||
this.streamId = streamId;
|
||||
this.peerClientId = peerClientId;
|
||||
this.opts = opts;
|
||||
}
|
||||
|
||||
/** Asks the publishing client to let us watch. The offer arrives asynchronously. */
|
||||
join(message = ""): void {
|
||||
this.opts.send({
|
||||
type: "joinStream",
|
||||
streamId: this.streamId,
|
||||
clientId: this.peerClientId,
|
||||
message,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Feeds one `streamEvent` in. Events for other streams are ignored, so the
|
||||
* caller can pass everything it receives without filtering.
|
||||
*/
|
||||
handleEvent(event: StreamEvent): void {
|
||||
if (this.closed) return;
|
||||
if (event.args.id && event.args.id !== this.streamId) return;
|
||||
|
||||
switch (event.name) {
|
||||
case "notifyrespondjoinstreamrequest":
|
||||
void this.handleJoinResponse(event.args);
|
||||
break;
|
||||
case "notifystreamsignaling":
|
||||
void this.handleSignaling(event.args);
|
||||
break;
|
||||
case "notifystreamstopped":
|
||||
case "notifystreamclientleft":
|
||||
this.close();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async handleJoinResponse(args: Record<string, string>): Promise<void> {
|
||||
if (args.decision !== "1") {
|
||||
this.fail(args.msg ? `Stream join refused: ${args.msg}` : "Stream join refused");
|
||||
return;
|
||||
}
|
||||
if (!args.offer) {
|
||||
this.fail("Stream join accepted but no SDP offer was sent");
|
||||
return;
|
||||
}
|
||||
await this.acceptOffer(args.offer);
|
||||
}
|
||||
|
||||
private async acceptOffer(sdp: string): Promise<void> {
|
||||
const pc = this.ensurePeerConnection();
|
||||
try {
|
||||
await pc.setRemoteDescription({ type: "offer", sdp });
|
||||
this.remoteDescriptionSet = true;
|
||||
await this.flushRemoteCandidates();
|
||||
|
||||
const answer = await pc.createAnswer();
|
||||
await pc.setLocalDescription(answer);
|
||||
this.signal("answer", { sdp: answer.sdp });
|
||||
} catch (err) {
|
||||
this.fail(`Could not answer the stream offer: ${describe(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async handleSignaling(args: Record<string, string>): Promise<void> {
|
||||
let msg: SignalingMessage;
|
||||
try {
|
||||
msg = JSON.parse(args.json ?? "");
|
||||
} catch {
|
||||
this.fail("Received malformed stream signaling payload");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (msg.cmd) {
|
||||
case "iceCandidate": {
|
||||
const candidate = candidateFromArgs(msg.args);
|
||||
if (!candidate) return;
|
||||
if (!this.remoteDescriptionSet) {
|
||||
// TS6 starts trickling immediately, so these routinely beat the
|
||||
// offer's setRemoteDescription. Holding them is not an edge case.
|
||||
this.pendingRemoteCandidates.push(candidate);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this.ensurePeerConnection().addIceCandidate(candidate);
|
||||
} catch (err) {
|
||||
// A single unusable candidate must not tear the session down; ICE
|
||||
// only needs one working pair.
|
||||
console.warn("[stream] ignoring ICE candidate:", describe(err));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "offer":
|
||||
case "reconnectOffer":
|
||||
// Renegotiation from the publisher, e.g. after it switches source.
|
||||
if (typeof msg.args.sdp === "string") await this.acceptOffer(msg.args.sdp);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async flushRemoteCandidates(): Promise<void> {
|
||||
const pending = this.pendingRemoteCandidates;
|
||||
this.pendingRemoteCandidates = [];
|
||||
const pc = this.ensurePeerConnection();
|
||||
for (const candidate of pending) {
|
||||
try {
|
||||
await pc.addIceCandidate(candidate);
|
||||
} catch (err) {
|
||||
console.warn("[stream] ignoring buffered ICE candidate:", describe(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ensurePeerConnection(): RTCPeerConnection {
|
||||
if (this.pc) return this.pc;
|
||||
|
||||
const pc = new RTCPeerConnection({
|
||||
iceServers: this.opts.iceServers ?? DEFAULT_ICE_SERVERS,
|
||||
});
|
||||
|
||||
pc.ontrack = (ev) => {
|
||||
this.remote.addTrack(ev.track);
|
||||
this.opts.onTrack(this.remote);
|
||||
};
|
||||
|
||||
pc.onicecandidate = (ev) => {
|
||||
if (!ev.candidate) return; // end-of-candidates; TS6 sends no such marker
|
||||
this.signal("iceCandidate", {
|
||||
sdp: ev.candidate.candidate,
|
||||
mid: ev.candidate.sdpMid ?? "0",
|
||||
mLine: ev.candidate.sdpMLineIndex ?? 0,
|
||||
});
|
||||
};
|
||||
|
||||
pc.onconnectionstatechange = () => {
|
||||
this.opts.onStateChange?.(pc.connectionState);
|
||||
if (pc.connectionState === "failed") this.fail("The stream connection failed");
|
||||
};
|
||||
|
||||
this.pc = pc;
|
||||
return pc;
|
||||
}
|
||||
|
||||
private signal(cmd: string, args: Record<string, unknown>): void {
|
||||
this.opts.send({
|
||||
type: "streamSignal",
|
||||
streamId: this.streamId,
|
||||
clientId: this.peerClientId,
|
||||
payload: { cmd, args },
|
||||
});
|
||||
}
|
||||
|
||||
private fail(message: string): void {
|
||||
this.opts.onError?.(message);
|
||||
}
|
||||
|
||||
/** Leaves the stream and releases the peer connection. Safe to call twice. */
|
||||
close(): void {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
|
||||
this.opts.send({
|
||||
type: "leaveStream",
|
||||
streamId: this.streamId,
|
||||
clientId: this.peerClientId,
|
||||
});
|
||||
|
||||
for (const track of this.remote.getTracks()) track.stop();
|
||||
this.pc?.close();
|
||||
this.pc = null;
|
||||
this.opts.onClosed?.();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an `RTCIceCandidateInit` from TS6's `iceCandidate` args.
|
||||
*
|
||||
* TS6 names them `sdp`, `mid` and `mLine`, which map to `candidate`, `sdpMid`
|
||||
* and `sdpMLineIndex`.
|
||||
*/
|
||||
function candidateFromArgs(args: Record<string, unknown>): RTCIceCandidateInit | null {
|
||||
const candidate = args.sdp;
|
||||
if (typeof candidate !== "string" || !candidate) return null;
|
||||
return {
|
||||
candidate,
|
||||
sdpMid: typeof args.mid === "string" ? args.mid : undefined,
|
||||
sdpMLineIndex: typeof args.mLine === "number" ? args.mLine : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function describe(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
Reference in new issue
Block a user