From 15e215d89297b17c9864ab2c43b250d266b97c22 Mon Sep 17 00:00:00 2001 From: Moepchi Date: Thu, 10 Sep 2026 19:41:17 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- connector/src/main.rs | 125 ++++++++++++- gateway/src/index.ts | 29 ++++ gateway/src/ts3/connection.ts | 61 +++++++ web/src/App.css | 23 ++- web/src/App.tsx | 91 ++++++++++ web/src/i18n.tsx | 12 ++ web/src/publish.ts | 318 ++++++++++++++++++++++++++++++++++ 7 files changed, 654 insertions(+), 5 deletions(-) create mode 100644 web/src/publish.ts diff --git a/connector/src/main.rs b/connector/src/main.rs index 477730e..be69def 100644 --- a/connector/src/main.rs +++ b/connector/src/main.rs @@ -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::(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::(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 [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 [reason]".into(), + }), + } } 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 @@ -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 }); } diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 0354e05..18512af 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -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; diff --git a/gateway/src/ts3/connection.ts b/gateway/src/ts3/connection.ts index d9cfdef..23673b2 100644 --- a/gateway/src/ts3/connection.ts +++ b/gateway/src/ts3/connection.ts @@ -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 { + 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 { + 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 { + 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 { if (away) { const sanitized = message.replace(/[\r\n]+/g, " ").trim(); diff --git a/web/src/App.css b/web/src/App.css index 3cf8e4c..9300849 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -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; diff --git a/web/src/App.tsx b/web/src/App.tsx index daedc98..c20abcc 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 { 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("new"); const [streamError, setStreamError] = useState(null); const streamViewerRef = useRef(null); + const [publishState, setPublishState] = useState("idle"); + const [publishViewers, setPublishViewers] = useState([]); + const [publishError, setPublishError] = useState(null); + const publisherRef = useRef(null); + const publishPreviewRef = useRef(null); const streamVideoRef = useRef(null); /** Clients we already pulled a `notifystreaminfo` for, so we ask only once. */ const requestedStreamInfoRef = useRef>(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))} /> + + + {/* muted: this is our own capture playing back locally */} +