stream: publish a stream TS6 can watch

The other direction, live-verified against TS6 6.0.0-beta12.1: a real
client rendered our video. Connector gains setupstream, stopstream and
respondjoinstreamrequest; the browser gains publish.ts and a toolbar
button.

The publisher offers. TS6 puts the first SDP in respondjoinstreamrequest,
so the side that owns the stream is the side that makes the offer - the
mirror of how it answered us when we were watching. Its reply confirmed
the key rule found in 7a8a1ea from the other side: TS6 sends us
args.answer, exactly as it expects args.answer from us. The key is always
named after the cmd.

The notify filter had to be fixed first. It matched
starts_with("notifyrespondjoinstream"), which drops the inbound
notifyjoinstreamrequest - so every viewer asking to watch *us* was
silently discarded, and the whole publishing direction was mute. Match
ends_with("joinstreamrequest") instead.

P2P mode is a mesh with no SFU in the path, so each viewer gets its own
peer connection and its own encode. Watching and broadcasting can run at
once, so the two panels stack in a shared container rather than both
anchoring to the same corner.

Note for later: we send bitrate=1500000 and the server reports 58208
back. It does not take our value - a real TS6 client showed 50880. Looks
server-side, and it does not stop the connection.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
MoepchiandClaude Opus 5 committed 2026-09-11 05:26:33 +00:00
1 parent b57d32bc18
commit 15e215d892
7 files changed
+654 -5

No files matched your search

+124 -1
View File
@@ -115,6 +115,43 @@ struct ClientInfo {
is_streaming: bool,
}
/// Payload for the "streamsetup " stdin command - the `setupstream` args, which
/// TS6 always sends in full. The server answers by broadcasting
/// `notifystreamstarted` with the stream id it assigned; there is no id here
/// because the client does not get to pick one.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct StreamSetupPayload {
name: String,
/// Source kind. A real TS6 screen share sends 3.
#[serde(rename = "type")]
kind: u8,
bitrate: u32,
/// Who may join: TS6's Privacy setting (public / contacts / private).
accessibility: u8,
/// Connection mode - P2P or via the server's SFU.
mode: u8,
/// 0 means unlimited.
viewer_limit: u32,
audio: bool,
}
/// Payload for the "streamrespond " stdin command - our reply to a
/// `notifyjoinstreamrequest`. JSON rather than a plain argument line because
/// `offer` is a multi-line SDP and stdin here is line-based.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct StreamRespondPayload {
id: String,
clid: u16,
#[serde(default)]
msg: String,
/// The publisher offers, so on accept this carries our whole SDP.
#[serde(default)]
offer: String,
decision: u8,
}
/// Payload for the "serveredit " stdin command - every field is optional so
/// the frontend only needs to send what actually changed. Covers the fields
/// tsclientlib's `Server::edit()` builder exposes named setters for; a few
@@ -1491,6 +1528,87 @@ async fn run(args: Args) -> Result<()> {
message: format!("Invalid client id: {rest}"),
}),
}
} else if let Some(rest) = l.strip_prefix("streamsetup ") {
// Announce a stream we publish. The id is assigned by the
// server and comes back as notifystreamstarted.
match serde_json::from_str::<StreamSetupPayload>(rest) {
Ok(s) => {
let mut packet = OutCommand::new(
Direction::C2S,
Flags::empty(),
PacketType::Command,
"setupstream",
);
packet.write_arg("name", &s.name);
packet.write_arg("type", &s.kind);
packet.write_arg("bitrate", &s.bitrate);
packet.write_arg("accessibility", &s.accessibility);
packet.write_arg("mode", &s.mode);
packet.write_arg("viewer_limit", &s.viewer_limit);
packet.write_arg("audio", &u8::from(s.audio));
match packet.send_with_result(&mut con) {
Ok(handle) => {
pending_messages.insert(handle, "Start stream".into());
}
Err(e) => emit(&Event::Error {
message: format!("setupstream failed: {e}"),
}),
}
}
Err(e) => emit(&Event::Error {
message: format!("Invalid streamsetup payload: {e}"),
}),
}
} else if let Some(rest) = l.strip_prefix("streamrespond ") {
// Accept or refuse a viewer. decision=1 carries our SDP offer,
// which is the mirror of how TS6 answered us when we watched.
match serde_json::from_str::<StreamRespondPayload>(rest) {
Ok(s) => {
let mut packet = OutCommand::new(
Direction::C2S,
Flags::empty(),
PacketType::Command,
"respondjoinstreamrequest",
);
packet.write_arg("id", &s.id);
packet.write_arg("clid", &s.clid);
packet.write_arg("msg", &s.msg);
packet.write_arg("offer", &s.offer);
packet.write_arg("decision", &s.decision);
match packet.send_with_result(&mut con) {
Ok(handle) => {
pending_messages.insert(handle, "Stream join response".into());
}
Err(e) => emit(&Event::Error {
message: format!("respondjoinstreamrequest failed: {e}"),
}),
}
}
Err(e) => emit(&Event::Error {
message: format!("Invalid streamrespond payload: {e}"),
}),
}
} else if let Some(rest) = l.strip_prefix("streamstop ") {
// "streamstop <stream-id> [reason]"
let mut parts = rest.splitn(2, ' ');
match parts.next() {
Some(id) if !id.is_empty() => {
let mut packet = OutCommand::new(
Direction::C2S,
Flags::empty(),
PacketType::Command,
"stopstream",
);
packet.write_arg("id", &id);
packet.write_arg("reason", &parts.next().unwrap_or(""));
if let Err(e) = packet.send(&mut con) {
emit(&Event::Error { message: format!("stopstream failed: {e}") });
}
}
_ => emit(&Event::Error {
message: "Usage: streamstop <stream-id> [reason]".into(),
}),
}
} else if let Some(rest) = l.strip_prefix("streamjoin ") {
// "streamjoin <stream-id> <clid> [msg]" - ask the client
// publishing a TS6 stream to let us in. Its reply is a
@@ -2511,7 +2629,12 @@ async fn run(args: Args) -> Result<()> {
// 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")
// ends_with, not starts_with: the inbound request is
// notifyjoinstreamrequest and the reply
// notifyrespondjoinstreamrequest. Matching only the latter's
// prefix silently dropped every viewer asking to watch *us*,
// which is the whole publishing direction.
if name.starts_with("notifystream") || name.ends_with("joinstreamrequest")
{
emit(&Event::StreamEvent { args: parse_ts_args(&content), name });
}
+29
View File
@@ -441,6 +441,35 @@ wss.on("connection", (socket: WebSocket) => {
}
break;
}
case "setupStream": {
await connection?.setupStream({
name: String(msg.name ?? "Stream"),
type: Number(msg.streamType ?? 3),
bitrate: Number(msg.bitrate ?? 1_500_000),
accessibility: Number(msg.accessibility ?? 1),
mode: Number(msg.mode ?? 1),
viewerLimit: Number(msg.viewerLimit ?? 0),
audio: Boolean(msg.audio),
});
break;
}
case "respondJoinStream": {
const clientId = Number(msg.clientId);
if (Number.isFinite(clientId)) {
await connection?.respondJoinStream(
String(msg.streamId ?? ""),
clientId,
Boolean(msg.accept),
String(msg.offer ?? ""),
String(msg.message ?? ""),
);
}
break;
}
case "stopStream": {
await connection?.stopStream(String(msg.streamId ?? ""), String(msg.reason ?? ""));
break;
}
case "setAway": {
await connection?.setAway(msg.away, msg.message ?? "");
break;
+61
View File
@@ -21,6 +21,24 @@ export interface ChannelInfo {
hasPassword: boolean;
}
/**
* The `setupstream` arguments. TS6 always sends all of them, so none are
* optional here - the defaults live in the caller, not on the wire.
*/
export interface StreamSetupOptions {
name: string;
/** Source kind; a real TS6 screen share sends 3. */
type: number;
bitrate: number;
/** TS6's Privacy setting: who may join without being asked. */
accessibility: number;
/** Connection mode - peer-to-peer or via the server's SFU. */
mode: number;
/** 0 means unlimited. */
viewerLimit: number;
audio: boolean;
}
export interface ClientInfo {
id: number;
channel: number;
@@ -811,6 +829,49 @@ export class Ts3Connection {
if (id) this.child?.stdin.write(`streamsignal ${id} ${clientId} ${JSON.stringify(payload)}\n`);
}
/** Announces a stream we publish. The server assigns the id and reports it
* back as a `notifystreamstarted` streamEvent naming our own client id. */
async setupStream(options: StreamSetupOptions): Promise<void> {
const payload = {
name: options.name.replace(/[\r\n]+/g, " ").trim() || "Stream",
type: options.type,
bitrate: options.bitrate,
accessibility: options.accessibility,
mode: options.mode,
viewerLimit: options.viewerLimit,
audio: options.audio,
};
this.child?.stdin.write(`streamsetup ${JSON.stringify(payload)}\n`);
}
/** Accepts or refuses a viewer that asked to watch our stream. On accept,
* `offer` is our SDP - the publisher offers, which is the mirror of how a
* TS6 publisher answered us. JSON-encoded because an SDP is multi-line. */
async respondJoinStream(
streamId: string,
clientId: number,
accept: boolean,
offer = "",
message = "",
): Promise<void> {
const id = streamId.replace(/[\s]+/g, "");
if (!id) return;
const payload = {
id,
clid: clientId,
msg: message.replace(/[\r\n]+/g, " ").trim(),
offer,
decision: accept ? 1 : 0,
};
this.child?.stdin.write(`streamrespond ${JSON.stringify(payload)}\n`);
}
async stopStream(streamId: string, reason = ""): Promise<void> {
const id = streamId.replace(/[\s]+/g, "");
const sanitized = reason.replace(/[\r\n]+/g, " ").trim();
if (id) this.child?.stdin.write(`streamstop ${id} ${sanitized}\n`);
}
async setAway(away: boolean, message: string): Promise<void> {
if (away) {
const sanitized = message.replace(/[\r\n]+/g, " ").trim();
+19 -4
View File
@@ -1411,10 +1411,6 @@
/* 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));
@@ -1468,6 +1464,25 @@
font-size: 0.85em;
}
.ts-stream-panel-publish {
border-color: var(--accent);
}
/* Watching and broadcasting can run at the same time, so the two panels stack
instead of each anchoring itself to the same corner. */
.ts-stream-panels {
position: fixed;
right: 1rem;
bottom: 1rem;
z-index: 29;
display: flex;
flex-direction: column;
gap: 0.5rem;
align-items: flex-end;
max-height: calc(100vh - 2rem);
overflow-y: auto;
}
.ts-context-menu {
position: fixed;
z-index: 30;
+91
View File
@@ -26,6 +26,7 @@ import {
pickAudioOutputDevice,
} from "./voice";
import { LanguageProvider, useLanguage, useT, type LangPref } from "./i18n";
import { StreamPublisher, type PublishState } from "./publish";
import { StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream";
import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode";
import {
@@ -5380,6 +5381,11 @@ function AppInner() {
const [streamState, setStreamState] = useState<RTCPeerConnectionState>("new");
const [streamError, setStreamError] = useState<string | null>(null);
const streamViewerRef = useRef<StreamViewer | null>(null);
const [publishState, setPublishState] = useState<PublishState>("idle");
const [publishViewers, setPublishViewers] = useState<number[]>([]);
const [publishError, setPublishError] = useState<string | null>(null);
const publisherRef = useRef<StreamPublisher | null>(null);
const publishPreviewRef = useRef<HTMLVideoElement | 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());
@@ -6274,6 +6280,7 @@ function AppInner() {
}
}
streamViewerRef.current?.handleEvent(streamEvent);
publisherRef.current?.handleEvent(streamEvent);
break;
}
case "poke": {
@@ -6335,6 +6342,10 @@ function AppInner() {
setStreamMedia(null);
setStreamInfos({});
requestedStreamInfoRef.current.clear();
publisherRef.current?.stop();
publisherRef.current = null;
setPublishState("idle");
setPublishViewers([]);
removeSession(sessionId, { skipSocketClose: true });
break;
}
@@ -7597,6 +7608,15 @@ function AppInner() {
if (video && video.srcObject !== streamMedia) video.srcObject = streamMedia;
}, [streamMedia, watchedStream]);
useEffect(() => {
// 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.
const video = publishPreviewRef.current;
if (!video) return;
const media = publisherRef.current?.previewStream ?? null;
if (video.srcObject !== media) video.srcObject = media;
}, [publishState, publishViewers]);
const handleStopWatchingStream = () => {
// close() sends leaveStream and fires onClosed, which clears the rest.
streamViewerRef.current?.close();
@@ -7628,6 +7648,43 @@ function AppInner() {
viewer.join();
};
const handleStopPublishing = () => {
publisherRef.current?.stop();
publisherRef.current = null;
setPublishState("idle");
setPublishViewers([]);
};
const handleStartPublishing = () => {
if (ownClientId === null) return;
if (publisherRef.current) {
handleStopPublishing();
return;
}
setPublishError(null);
const publisher = new StreamPublisher({
send: (message) => socketRef.current?.send(JSON.stringify(message)),
ownClientId,
onStateChange: (state) => {
setPublishState(state);
// "stopped" is also how the browser's own stop-sharing bar reports in,
// so the ref has to be dropped here and not only in the click handler.
if (state === "stopped" || state === "idle") {
publisherRef.current = null;
setPublishViewers([]);
}
},
onViewersChange: setPublishViewers,
onError: setPublishError,
});
publisherRef.current = publisher;
void publisher.start({
name: `${ownClient?.name ?? "WebSpeak3"} - ${t("publish.screen")}`,
bitrate: 1_500_000,
audio: true,
});
};
const handleShowClientConnectionInfo = (clientId: number, clientName: string) => {
setClientConnectionInfoTarget({ id: clientId, name: clientName });
setClientConnectionInfo(null);
@@ -8726,6 +8783,14 @@ function AppInner() {
onChange={(e) => setVadThreshold(Number(e.target.value))}
/>
</label>
<button
className={`ts-icon-button${publishState === "live" ? " ts-mic-on" : ""}`}
onClick={handleStartPublishing}
disabled={!connected || ownClientId === null}
title={publishState === "live" ? t("publish.stop") : t("publish.start")}
>
{publishState === "live" ? "🛑" : "🖥️"}
</button>
<span className="ts-toolbar-sep" />
<button
className={`ts-icon-button${outputMuted ? " ts-muted-on" : ""}`}
@@ -9264,6 +9329,30 @@ function AppInner() {
</div>
))}
{(watchedStream || (publishState !== "idle" && publishState !== "stopped")) && (
<div className="ts-stream-panels">
{publishState !== "idle" && publishState !== "stopped" && (
<div className="ts-stream-panel ts-stream-panel-publish">
<div className="ts-stream-panel-header">
<span className="ts-stream-panel-title">🖥️ {t("publish.title")}</span>
<span className="ts-stream-panel-state">
{publishState === "live"
? t("publish.viewers", { count: String(publishViewers.length) })
: t("publish.starting")}
</span>
<button
className="ts-stream-panel-close"
onClick={handleStopPublishing}
title={t("publish.stop")}
>
✕
</button>
</div>
{/* muted: this is our own capture playing back locally */}
<video ref={publishPreviewRef} autoPlay playsInline muted />
{publishError && <div className="ts-stream-panel-error">{publishError}</div>}
</div>
)}
{watchedStream && (
<div className="ts-stream-panel">
<div className="ts-stream-panel-header">
@@ -9286,6 +9375,8 @@ function AppInner() {
{streamError && <div className="ts-stream-panel-error">{streamError}</div>}
</div>
)}
</div>
)}
{clientContextMenu && (
<div
ref={clientContextMenuRef}
+12
View File
@@ -376,6 +376,12 @@ const translations: Record<Lang, Record<string, string>> = {
"tree.noTalkPower": "Keine Redeerlaubnis in diesem Channel",
"tree.soundMuted": "Ton stummgeschaltet (deafened)",
"tree.streaming": "Überträgt einen Stream",
"publish.start": "Bildschirm übertragen",
"publish.stop": "Übertragung beenden",
"publish.title": "Deine Übertragung",
"publish.screen": "Bildschirm",
"publish.starting": "Wird gestartet…",
"publish.viewers": "{count} Zuschauer",
"stream.untitled": "Stream",
"stream.stop": "Stream schließen",
@@ -977,6 +983,12 @@ const translations: Record<Lang, Record<string, string>> = {
"tree.noTalkPower": "No talk power in this channel",
"tree.soundMuted": "Sound muted (deafened)",
"tree.streaming": "Broadcasting a stream",
"publish.start": "Share your screen",
"publish.stop": "Stop sharing",
"publish.title": "Your broadcast",
"publish.screen": "Screen",
"publish.starting": "Starting…",
"publish.viewers": "{count} watching",
"stream.untitled": "Stream",
"stream.stop": "Close stream",
+318
View File
@@ -0,0 +1,318 @@
// Publishing a stream that TeamSpeak 6 clients can watch.
//
// The mirror image of stream.ts. Where a viewer answers an offer, a publisher
// makes one - TS6 puts the first SDP in `respondjoinstreamrequest`, so the
// side that owns the stream is the side that offers.
//
// The exchange, from our side:
//
// 1. setupStream -> notifystreamstarted naming our own clid + the id
// 2. wait <- notifyjoinstreamrequest, one per viewer
// 3. offer respondJoinStream(accept, <our SDP>)
// 4. answer <- {cmd:"answer", args:{answer:"<sdp>"}}
// 5. trickle ICE both directions via {cmd:"iceCandidate"}
//
// TS6's P2P mode is a mesh: there is no SFU in the path, so every viewer gets
// its own peer connection and its own copy of the encoded media.
import type { StreamEvent } from "./stream";
/** Source kind in `setupstream`. A real TS6 screen share sends 3. */
export const STREAM_TYPE_SCREEN = 3;
/** `mode` in `setupstream`. 1 is what a real TS6 client sends for P2P. */
export const STREAM_MODE_P2P = 1;
/**
* `accessibility` in `setupstream` - TS6's Privacy setting. 1 is what the
* observed client sent; the three UI choices are public / contacts / private,
* and which number maps to which is still unverified.
*/
export const STREAM_ACCESS_DEFAULT = 1;
const DEFAULT_ICE_SERVERS: RTCIceServer[] = [
{ urls: "stun:turn.teamspeak.com:3478" },
{ urls: "stun:turn2.teamspeak.com:3478" },
{ urls: "stun:stun.l.google.com:19302" },
];
export interface StreamPublishOptions {
name: string;
bitrate: number;
/** Send the capture's audio track too, when the source has one. */
audio: boolean;
/** 0 means unlimited. */
viewerLimit?: number;
}
export interface StreamPublisherOptions {
send: (message: Record<string, unknown>) => void;
/** Needed to recognise our own `notifystreamstarted` among everyone's. */
ownClientId: number;
onStateChange?: (state: PublishState) => void;
onViewersChange?: (viewers: number[]) => void;
onError?: (error: string) => void;
iceServers?: RTCIceServer[];
}
export type PublishState = "idle" | "starting" | "live" | "stopped";
interface Viewer {
pc: RTCPeerConnection;
/** Candidates that arrived before the answer; replayed after. */
pending: RTCIceCandidateInit[];
answered: boolean;
}
export class StreamPublisher {
private readonly opts: StreamPublisherOptions;
private readonly viewers = new Map<number, Viewer>();
private media: MediaStream | null = null;
private state: PublishState = "idle";
/** Assigned by the server, not by us; null until notifystreamstarted. */
streamId: string | null = null;
/** The local capture, for showing the user what they are sending. */
get previewStream(): MediaStream | null {
return this.media;
}
constructor(opts: StreamPublisherOptions) {
this.opts = opts;
}
/**
* Captures a screen and announces the stream.
*
* `getDisplayMedia` is secure-context-only, so this throws on a plain-http
* origin - the same limitation the microphone already has.
*/
async start(options: StreamPublishOptions): Promise<void> {
if (this.state === "live" || this.state === "starting") return;
if (!navigator.mediaDevices?.getDisplayMedia) {
this.fail("Screen sharing requires HTTPS (or localhost) - the site is not a secure context.");
return;
}
this.setState("starting");
try {
this.media = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: options.audio,
});
} catch (err) {
this.setState("idle");
this.fail(`Could not capture the screen: ${describe(err)}`);
return;
}
// The browser's own "stop sharing" bar bypasses our UI entirely, so the
// track ending is the authoritative signal that the stream is over.
for (const track of this.media.getTracks()) {
track.onended = () => this.stop();
}
this.opts.send({
type: "setupStream",
name: options.name,
streamType: STREAM_TYPE_SCREEN,
bitrate: options.bitrate,
accessibility: STREAM_ACCESS_DEFAULT,
mode: STREAM_MODE_P2P,
viewerLimit: options.viewerLimit ?? 0,
audio: options.audio && this.media.getAudioTracks().length > 0,
});
}
/** Feeds one `streamEvent` in; events for other streams are ignored. */
handleEvent(event: StreamEvent): void {
switch (event.name) {
case "notifystreamstarted":
// Everyone in the channel sees this, so the clid decides whether it
// is the answer to our own setupstream.
if (Number(event.args.clid) === this.opts.ownClientId && event.args.id) {
this.streamId = event.args.id;
this.setState("live");
}
break;
case "notifyjoinstreamrequest":
if (event.args.id === this.streamId) void this.admit(event.args);
break;
case "notifystreamsignaling":
if (event.args.id === this.streamId) void this.handleSignaling(event.args);
break;
case "notifystreamclientleft":
if (event.args.id === this.streamId) this.dropViewer(Number(event.args.clid));
break;
case "notifystreamstopped":
if (event.args.id === this.streamId) this.teardown("stopped");
break;
}
}
/** Accepts a viewer and sends it our offer. */
private async admit(args: Record<string, string>): Promise<void> {
const clid = Number(args.clid);
if (!Number.isFinite(clid) || !this.media || !this.streamId) return;
// is_remove=1 is how TS6 says "stop watching"; the same notify carries it.
if (args.is_remove === "1") {
this.dropViewer(clid);
return;
}
if (this.viewers.has(clid)) return;
const pc = new RTCPeerConnection({ iceServers: this.opts.iceServers ?? DEFAULT_ICE_SERVERS });
const viewer: Viewer = { pc, pending: [], answered: false };
this.viewers.set(clid, viewer);
for (const track of this.media.getTracks()) pc.addTrack(track, this.media);
pc.onicecandidate = (ev) => {
if (!ev.candidate) return;
this.signal(clid, "iceCandidate", {
sdp: ev.candidate.candidate,
mid: ev.candidate.sdpMid ?? "0",
mLine: ev.candidate.sdpMLineIndex ?? 0,
});
};
pc.onconnectionstatechange = () => {
if (pc.connectionState === "failed" || pc.connectionState === "closed") this.dropViewer(clid);
};
try {
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
this.opts.send({
type: "respondJoinStream",
streamId: this.streamId,
clientId: clid,
accept: true,
offer: offer.sdp ?? "",
});
this.notifyViewers();
} catch (err) {
this.dropViewer(clid);
this.fail(`Could not offer the stream to client ${clid}: ${describe(err)}`);
}
}
private async handleSignaling(args: Record<string, string>): Promise<void> {
const clid = Number(args.clid);
const viewer = this.viewers.get(clid);
if (!viewer) return;
let msg: { cmd: string; args: unknown };
try {
msg = JSON.parse(args.json ?? "");
} catch {
return;
}
const payload = msg.args as Record<string, unknown> | string | null;
switch (msg.cmd) {
case "answer": {
// Same key rule as the sending side: the key is named after the cmd.
const sdp =
typeof payload === "string"
? payload
: typeof payload?.answer === "string"
? payload.answer
: typeof payload?.sdp === "string"
? payload.sdp
: null;
if (!sdp) return;
try {
await viewer.pc.setRemoteDescription({ type: "answer", sdp });
viewer.answered = true;
const pending = viewer.pending;
viewer.pending = [];
for (const c of pending) {
try {
await viewer.pc.addIceCandidate(c);
} catch (err) {
console.warn("[publish] ignoring buffered ICE candidate:", describe(err));
}
}
} catch (err) {
this.fail(`Could not accept the viewer's answer: ${describe(err)}`);
}
break;
}
case "iceCandidate": {
if (typeof payload !== "object" || payload === null) return;
const candidate = payload.sdp;
if (typeof candidate !== "string" || !candidate) return;
const init: RTCIceCandidateInit = {
candidate,
sdpMid: typeof payload.mid === "string" ? payload.mid : undefined,
sdpMLineIndex: typeof payload.mLine === "number" ? payload.mLine : undefined,
};
// TS6 trickles from the moment it gets the offer, so these routinely
// beat its own answer. Holding them is not an edge case.
if (!viewer.answered) {
viewer.pending.push(init);
return;
}
try {
await viewer.pc.addIceCandidate(init);
} catch (err) {
console.warn("[publish] ignoring ICE candidate:", describe(err));
}
break;
}
}
}
private dropViewer(clid: number): void {
const viewer = this.viewers.get(clid);
if (!viewer) return;
this.viewers.delete(clid);
viewer.pc.close();
this.notifyViewers();
}
/** Stops the capture and takes the stream down. Safe to call twice. */
stop(): void {
if (this.state === "idle" || this.state === "stopped") return;
if (this.streamId) this.opts.send({ type: "stopStream", streamId: this.streamId });
this.teardown("stopped");
}
private teardown(state: PublishState): void {
for (const [, viewer] of this.viewers) viewer.pc.close();
this.viewers.clear();
for (const track of this.media?.getTracks() ?? []) track.stop();
this.media = null;
this.streamId = null;
this.notifyViewers();
this.setState(state);
}
private signal(clid: number, cmd: string, args: unknown): void {
this.opts.send({
type: "streamSignal",
streamId: this.streamId,
clientId: clid,
payload: { cmd, args },
});
}
private setState(state: PublishState): void {
this.state = state;
this.opts.onStateChange?.(state);
}
private notifyViewers(): void {
this.opts.onViewersChange?.([...this.viewers.keys()]);
}
private fail(message: string): void {
this.opts.onError?.(message);
}
}
function describe(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}