Merge: TS6 screen streaming (alpha)

Adds screen streaming to and from TeamSpeak 6, marked alpha and unstable in
the UI and the docs because it speaks a protocol TeamSpeak does not publish.
Also repoints both submodules at Moepchi forks, so a fresh clone resolves
every pinned commit.

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 06:27:35 +00:00
commit 478e5c0384
13 files changed
+2232 -18

No files matched your search

+3
View File
@@ -10,3 +10,6 @@ docker-compose.override.yml
.claude/
CLAUDE.md
.serena/
# TLS material for local HTTPS - a private key never belongs in the repo.
gateway/certs/
+1 -1
View File
@@ -1,4 +1,4 @@
[submodule "tsclientlib"]
path = tsclientlib
url = https://github.com/GreenTeaSpeak/tsclientlib.git
url = https://github.com/Moepchi/tsclientlib.git
branch = webspeak3
+1
View File
@@ -81,6 +81,7 @@ not need to be installed on the same machine, modified, or operated by you.
| 🔁 **Multi-join (server tabs)** | Several connections in parallel — one tab per server, like GreenTeaSpeak 2. Audio stays on the active tab |
| 🔁 **Seamless reconnect** | Switch or add connections mid-session without tearing down unrelated tabs |
| 🍵 **GreenTeaSpeak support** | Connects to real GreenTeaSpeak servers (not just TS3/TS6/TeaSpeak), plus an optional GTS-styled UI chrome (dark panels, gold menu bar, connection-tab strip) alongside the default look |
| 🖥️ **Screen streaming to/from TS6** | <sub>**ALPHA · UNSTABLE**</sub> Share your screen to native TeamSpeak 6 clients and watch theirs. Built on TS6's undocumented Stream/Call protocol — expect it to break; see [Roadmap](ROADMAP.md) |
## 🧱 Tech Stack
+7
View File
@@ -19,6 +19,13 @@ This roadmap is intentionally outcome-focused. It does not promise fixed dates.
## Experimental or still being validated
- **Screen streaming to and from TeamSpeak 6 (alpha, unstable).** WebSpeak3 can
publish a screen share that a native TS6 client can watch, and watch a stream
a TS6 client publishes. It speaks TS6's Stream/Call protocol, which TeamSpeak
does not document, so the wire format was derived from observed behavior and
may break with any TS6 update. Connection setup, picture quality, and viewer
admission are not yet dependable. The "Server" connection mode (TS6's SFU) is
not implemented; only direct P2P works.
- Safari and Mobile Safari audio/microphone behavior
- Uncommon TeamSpeak permission combinations and large permission sets
- Very large servers and long-running browser sessions
+270 -1
View File
@@ -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.
@@ -106,6 +108,48 @@ 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 "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
@@ -344,6 +388,16 @@ enum Event {
/// anywhere), for populating an "add permission" picker.
#[serde(rename = "permissionCatalog")]
PermissionCatalog { entries: Vec<PermissionCatalogEntry> },
/// 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<String, String> },
}
#[derive(Serialize)]
@@ -609,6 +663,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<_>>();
@@ -641,6 +696,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<String, String> {
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 `"<stream-id> <clid> [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::<u16>())) else {
emit(&Event::Error { message: "Usage: streamjoin <stream-id> <clid> [msg]".into() });
return;
};
if id.is_empty() {
emit(&Event::Error { message: "Usage: streamjoin <stream-id> <clid> [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 +1507,150 @@ 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::<u16>() {
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("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
// 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 <stream-id> <clid> <json>" - 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::<u16>().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);
// Not fire-and-forget: a signaling command the server refuses
// (a stale clid, say) is otherwise indistinguishable from a peer
// that simply ignored the payload, and the whole handshake then
// stalls with nothing to look at.
match packet.send_with_result(&mut con) {
Ok(handle) => {
pending_messages.insert(handle, "Stream signaling".into());
}
Err(e) => emit(&Event::Error {
message: format!("streamsignaling failed: {e}"),
}),
}
}
_ => emit(&Event::Error {
message: "Usage: streamsignal <stream-id> <clid> <json>".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 +2620,25 @@ 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
// wants it.
// 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 });
}
}
Some(Ok(StreamItem::MessageEvent(msg))) => {
// Defense in depth: TeaSpeak/GTS may surface notifyclientpoke as an
// unhandled MessageEvent if bookkeeping did not mark it handled.
+88 -3
View File
@@ -1,4 +1,6 @@
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { createServer as createSecureServer } from "node:https";
import { readFileSync } from "node:fs";
import { readFile, appendFile, rename, stat } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -249,7 +251,26 @@ const DEV_HINT = `<!doctype html><html><body style="font:14px system-ui;padding:
to serve the UI from this port again.</p>
</body></html>`;
const server = createServer((req, res) => {
/**
* TLS material, when configured.
*
* Not a nicety: `getDisplayMedia`, `getUserMedia` and `crypto.randomUUID` are
* secure-context-only, so a LAN instance reached over plain http can neither
* share a screen nor use the microphone. Chrome also hides host ICE candidates
* behind mDNS names until a media permission is granted, which keeps a
* peer-to-peer stream from connecting at all.
*
* Set TLS_CERT and TLS_KEY to enable; a self-signed pair is enough, the
* browser only has to be told once to trust it.
*/
const TLS_CERT = process.env.TLS_CERT;
const TLS_KEY = process.env.TLS_KEY;
const tlsOptions =
TLS_CERT && TLS_KEY
? { cert: readFileSync(TLS_CERT), key: readFileSync(TLS_KEY) }
: null;
const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
void (async () => {
try {
const requestUrl = new URL(req.url ?? "/", "http://localhost");
@@ -284,7 +305,13 @@ const server = createServer((req, res) => {
res.end(DEV_HINT);
}
})();
});
};
// The frontend derives ws:// or wss:// from the page's own scheme, so the
// WebSocket follows this choice without any further configuration.
const server = tlsOptions
? createSecureServer(tlsOptions, requestHandler)
: createServer(requestHandler);
const wss = new WebSocketServer({ server, path: "/ws" });
@@ -319,7 +346,10 @@ const heartbeatTimer = setInterval(() => {
wss.on("close", () => clearInterval(heartbeatTimer));
server.listen(PORT, () => {
console.log(`WebSpeak3 gateway listening on http://localhost:${PORT} (WebSocket at /ws)`);
const scheme = tlsOptions ? "https" : "http";
console.log(
`WebSpeak3 gateway listening on ${scheme}://localhost:${PORT} (WebSocket at /ws)`
);
if (SERVE_STATIC) {
console.log(`Serving static UI from ${WEB_DIST}`);
console.log(`Dev tip: use http://localhost:5173/ for live UI; rebuild web/dist after UI changes if you open :${PORT}`);
@@ -415,6 +445,61 @@ 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)) {
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 "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;
+100 -2
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;
@@ -39,6 +57,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 +204,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 +277,7 @@ export class Ts3Connection {
server_groups: number[];
has_talk_power: boolean;
is_query?: boolean;
is_streaming?: boolean;
}
interface RawChannelInfo {
@@ -384,7 +407,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 +452,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 +799,79 @@ 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. */
async joinStream(streamId: string, clientId: number, message = ""): Promise<void> {
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<void> {
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<void> {
const id = streamId.replace(/[\s]+/g, "");
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();
+256
View File
@@ -26,6 +26,7 @@
--log-bg: #f7f8f9;
--log-text: #333;
--log-error: #b3261e;
--alpha-badge: #a15c07;
display: flex;
flex-direction: column;
@@ -68,6 +69,7 @@
--log-bg: #202124;
--log-text: #c7c9cc;
--log-error: #f2867a;
--alpha-badge: #e0a23c;
color-scheme: dark;
}
@@ -97,6 +99,7 @@
--log-bg: oklch(0.17 0.014 258);
--log-text: oklch(0.62 0.014 258);
--log-error: oklch(0.68 0.16 25);
--alpha-badge: oklch(0.75 0.14 70);
color-scheme: dark;
font-family: "Manrope", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
}
@@ -827,6 +830,7 @@
--log-bg: oklch(0.155 0.018 290);
--log-text: oklch(0.64 0.014 290);
--log-error: oklch(0.68 0.16 25);
--alpha-badge: oklch(0.75 0.14 70);
color-scheme: dark;
font-family: "Manrope", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
}
@@ -1409,6 +1413,206 @@
background: var(--border-soft);
}
/* Floating viewer for a TS6 Stream/Call broadcast. */
.ts-stream-panel {
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;
}
/* Deliberately loud: the feature speaks an undocumented TS6 protocol, so the
user should never be in doubt that it is experimental. */
.ts-alpha-badge {
display: inline-block;
padding: 0 0.35em;
border: 1px solid var(--alpha-badge);
border-radius: 3px;
color: var(--alpha-badge);
font-size: 0.7em;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
vertical-align: middle;
white-space: nowrap;
}
.ts-alpha-note {
margin: 0 0 0.75rem;
padding: 0.5rem 0.6rem;
border-left: 3px solid var(--alpha-badge);
background: var(--log-bg);
color: var(--text-muted);
font-size: 0.85em;
line-height: 1.4;
}
.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;
}
/* TS6's stream dialog, rebuilt: labelled rows with a segmented control on the
right. The segments wrap on narrow screens rather than overflowing. */
.ts-stream-settings {
width: min(680px, calc(100vw - 2rem));
}
.ts-stream-settings-section {
margin: 0.9rem 0 0.4rem;
color: var(--accent);
font-size: 1rem;
font-weight: 600;
}
.ts-stream-settings-expand {
display: flex;
width: 100%;
justify-content: space-between;
align-items: center;
padding: 0;
background: none;
border: none;
cursor: pointer;
text-align: left;
}
.ts-stream-settings-row {
display: flex;
gap: 0.75rem;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
padding: 0.35rem 0;
}
.ts-stream-settings-row > span:first-child {
opacity: 0.85;
}
.ts-segmented {
display: flex;
flex-wrap: wrap;
gap: 2px;
padding: 2px;
background: var(--bg-toolbar-2, rgba(0, 0, 0, 0.2));
border: 1px solid var(--border-soft);
border-radius: 999px;
}
.ts-segmented button {
padding: 0.25rem 0.7rem;
background: none;
border: none;
border-radius: 999px;
color: inherit;
cursor: pointer;
white-space: nowrap;
}
.ts-segmented button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.ts-segmented button.ts-segmented-on {
background: color-mix(in srgb, var(--accent) 25%, transparent);
box-shadow: inset 0 0 0 1px var(--accent);
}
.ts-stream-settings-stepper {
display: flex;
gap: 0.35rem;
align-items: center;
}
.ts-stream-settings-stepper input {
width: 5.5rem;
text-align: center;
}
.ts-stream-settings-stepper button {
width: 1.9rem;
border-radius: 999px;
}
.ts-stream-settings-unit {
opacity: 0.7;
}
.ts-stream-settings-toggle input {
width: 2.4rem;
height: 1.3rem;
}
.ts-stream-settings-go {
border-radius: 999px;
background: var(--accent);
color: #fff;
padding-inline: 1.2rem;
}
.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;
@@ -3937,3 +4141,55 @@
min-width: 160px;
}
}
/* A join request waiting for a decision. TS6 shows the viewer "waiting for
access" the whole time this is on screen, so it should not be subtle. */
.ts-stream-request {
display: flex;
align-items: center;
gap: 0.4rem;
padding: 0.45rem 0.55rem;
border-top: 1px solid var(--ts-border, #2a2f3a);
background: var(--ts-accent-soft, rgba(90, 140, 255, 0.12));
font-size: 0.82rem;
}
.ts-stream-request-who {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ts-stream-request-who em {
opacity: 0.7;
font-size: 0.75rem;
font-style: normal;
}
.ts-stream-request button {
flex: none;
padding: 0.2rem 0.5rem;
border: 1px solid var(--ts-border, #2a2f3a);
border-radius: 4px;
background: var(--ts-surface, #1b1f27);
color: inherit;
cursor: pointer;
font-size: 0.78rem;
}
.ts-stream-request button:hover {
border-color: var(--ts-accent, #5a8cff);
}
.ts-stream-request-allow {
background: var(--ts-accent, #5a8cff) !important;
color: #fff;
}
.ts-stream-request-block {
opacity: 0.65;
}
+593 -10
View File
@@ -26,6 +26,14 @@ import {
pickAudioOutputDevice,
} from "./voice";
import { LanguageProvider, useLanguage, useT, type LangPref } from "./i18n";
import {
StreamAccess,
StreamMode,
StreamPublisher,
type PublishState,
type StreamPublishOptions,
} from "./publish";
import { StreamViewer, parseStreamInfo, type StreamEvent, type StreamInfo } from "./stream";
import { DEMO_HOST, DEMO_MODE, DemoSocket } from "./demoMode";
import {
SOUND_EVENTS,
@@ -154,6 +162,20 @@ interface Identity {
blob: string | null;
}
// randomId() only exists in a secure context, so it is missing on a
// plain-http origin - which is exactly how a self-hosted instance is reached
// on a LAN before TLS is set up. It used to throw at module load and leave a
// blank page; these ids are local identifiers, not secrets, so fall back.
function randomId(): string {
if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
// One-time migration from the old single flat identity key to a list of named
// identities (so users can maintain more than one persona), and to seed a
// default entry for users who never had one either. Runs once at module load.
@@ -161,7 +183,7 @@ interface Identity {
if (localStorage.getItem(IDENTITIES_KEY) !== null) return;
const legacyBlob = localStorage.getItem(IDENTITY_KEY);
const legacyNickname = localStorage.getItem(LAST_NICKNAME_KEY) ?? "";
const id = crypto.randomUUID();
const id = randomId();
const identities: Identity[] = [
{ id, name: "Standard", nickname: legacyNickname, phoneticName: "", blob: legacyBlob },
];
@@ -178,7 +200,7 @@ function loadIdentities(): Identity[] {
// Backfill fields older saves (before per-identity nickname/phonetic
// name existed) don't have.
return parsed.map((i) => ({
id: i.id ?? crypto.randomUUID(),
id: i.id ?? randomId(),
name: i.name ?? "Standard",
nickname: i.nickname ?? "",
phoneticName: i.phoneticName ?? "",
@@ -188,7 +210,7 @@ function loadIdentities(): Identity[] {
} catch {
// fall through
}
return [{ id: crypto.randomUUID(), name: "Standard", nickname: "", phoneticName: "", blob: null }];
return [{ id: randomId(), name: "Standard", nickname: "", phoneticName: "", blob: null }];
}
const FAVORITES_KEY = "webspeak3:favorites";
@@ -506,6 +528,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 +729,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>
);
}
@@ -1567,6 +1592,292 @@ function ChannelPasswordDialog({
);
}
/**
* Presets from TS6's own stream dialog. Each one fills in the advanced
* fields; "source" keeps the capture's native resolution and "presentation"
* trades frame rate for sharp text, which is what the encoder's content hint
* is for.
*/
const STREAM_PRESETS: Record<
string,
{ height: number; fps: number; videoBitrateKbps: number; contentHint: "motion" | "detail" }
> = {
"360": { height: 360, fps: 30, videoBitrateKbps: 1000, contentHint: "motion" },
"480": { height: 480, fps: 30, videoBitrateKbps: 1500, contentHint: "motion" },
"720": { height: 720, fps: 30, videoBitrateKbps: 2500, contentHint: "motion" },
"1080": { height: 1080, fps: 30, videoBitrateKbps: 4000, contentHint: "motion" },
"1440": { height: 1440, fps: 30, videoBitrateKbps: 6000, contentHint: "motion" },
source: { height: 0, fps: 60, videoBitrateKbps: 8000, contentHint: "motion" },
presentation: { height: 0, fps: 5, videoBitrateKbps: 3000, contentHint: "detail" },
};
const RESOLUTION_CHOICES = [360, 480, 720, 1080, 1440, 0];
const FPS_CHOICES = [5, 30, 60];
const AUDIO_BITRATE_CHOICES = [64, 96, 128, 192, 256, 320];
// Streaming talks to TS6 over a protocol nobody published, so it is marked
// alpha everywhere the user can reach it: the settings dialog, both stream
// panels, and the toolbar button's tooltip.
function AlphaBadge() {
const t = useT();
return (
<span className="ts-alpha-badge" title={t("publish.alphaTitle")}>
{t("publish.alpha")}
</span>
);
}
function SegmentedChoice<T extends string | number>({
value,
options,
onChange,
disabled,
}: {
value: T;
options: { value: T; label: string; title?: string; disabled?: boolean }[];
onChange: (value: T) => void;
disabled?: boolean;
}) {
return (
<div className="ts-segmented">
{options.map((option) => (
<button
key={String(option.value)}
type="button"
className={option.value === value ? "ts-segmented-on" : ""}
disabled={disabled || option.disabled}
title={option.title}
onClick={() => onChange(option.value)}
>
{option.label}
</button>
))}
</div>
);
}
function StreamSettingsDialog({
defaultName,
onStart,
onCancel,
}: {
defaultName: string;
onStart: (options: StreamPublishOptions) => void;
onCancel: () => void;
}) {
const t = useT();
const backdrop = useBackdropDismiss(onCancel);
const [preset, setPreset] = useState<string | null>("720");
const [audio, setAudio] = useState(true);
const [accessibility, setAccessibility] = useState<number>(StreamAccess.PUBLIC);
const [advanced, setAdvanced] = useState(false);
const [height, setHeight] = useState(STREAM_PRESETS["720"]!.height);
const [fps, setFps] = useState(STREAM_PRESETS["720"]!.fps);
const [videoBitrateKbps, setVideoBitrateKbps] = useState(STREAM_PRESETS["720"]!.videoBitrateKbps);
const [audioBitrateKbps, setAudioBitrateKbps] = useState(128);
const [viewerLimit, setViewerLimit] = useState(0);
const [mode, setMode] = useState<number>(StreamMode.P2P);
const [contentHint, setContentHint] = useState<"motion" | "detail">("motion");
const applyPreset = (key: string) => {
const p = STREAM_PRESETS[key];
if (!p) return;
setPreset(key);
setHeight(p.height);
setFps(p.fps);
setVideoBitrateKbps(p.videoBitrateKbps);
setContentHint(p.contentHint);
};
// Any hand-tuned value means the result is no longer one of the presets, so
// the highlight is dropped rather than left lying about what will be sent.
const custom = <T,>(setter: (value: T) => void) => (value: T) => {
setter(value);
setPreset(null);
};
const resolutionLabel = (value: number) => (value === 0 ? t("publish.res.source") : String(value));
return (
<div className="ts-dialog-backdrop" {...backdrop}>
<div className="ts-dialog ts-stream-settings" onClick={(e) => e.stopPropagation()}>
<div className="ts-dialog-titlebar">
<span>
{t("publish.dialog.title")} <AlphaBadge />
</span>
<button onClick={onCancel} title={t("dialog.close")}>
✕
</button>
</div>
<div className="ts-dialog-body">
<p className="ts-alpha-note">{t("publish.alphaNote")}</p>
<h4 className="ts-stream-settings-section">{t("publish.dialog.basic")}</h4>
<div className="ts-stream-settings-row">
<span>{t("publish.preset")}</span>
<SegmentedChoice
value={preset ?? ""}
onChange={applyPreset}
options={[
...["360", "480", "720", "1080", "1440"].map((k) => ({ value: k, label: k })),
{ value: "source", label: t("publish.res.source") },
{ value: "presentation", label: t("publish.preset.presentation") },
]}
/>
</div>
<div className="ts-stream-settings-row">
<span>{t("publish.audio")}</span>
<label className="ts-stream-settings-toggle">
<input type="checkbox" checked={audio} onChange={(e) => setAudio(e.target.checked)} />
<span />
</label>
</div>
<div className="ts-stream-settings-row">
<span>{t("publish.privacy")}</span>
<SegmentedChoice
value={accessibility}
onChange={setAccessibility}
options={[
{ value: StreamAccess.PUBLIC, label: `🌐 ${t("publish.privacy.public")}` },
{ value: StreamAccess.CONTACTS_ONLY, label: `👥 ${t("publish.privacy.contacts")}` },
{ value: StreamAccess.PRIVATE, label: `🔒 ${t("publish.privacy.private")}` },
]}
/>
</div>
<button
type="button"
className="ts-stream-settings-section ts-stream-settings-expand"
onClick={() => setAdvanced((v) => !v)}
>
{t("publish.dialog.advanced")} <span>{advanced ? "⌄" : "›"}</span>
</button>
{advanced && (
<>
<div className="ts-stream-settings-row">
<span>{t("publish.resolution")}</span>
<SegmentedChoice
value={height}
onChange={custom(setHeight)}
options={RESOLUTION_CHOICES.map((v) => ({ value: v, label: resolutionLabel(v) }))}
/>
</div>
<div className="ts-stream-settings-row">
<span>{t("publish.fps")}</span>
<SegmentedChoice
value={fps}
onChange={custom(setFps)}
options={FPS_CHOICES.map((v) => ({ value: v, label: String(v) }))}
/>
</div>
<div className="ts-stream-settings-row">
<span>{t("publish.bitrate")}</span>
<div className="ts-stream-settings-stepper">
<button type="button" onClick={() => custom(setVideoBitrateKbps)(Math.max(200, videoBitrateKbps - 500))}>
−
</button>
<input
type="number"
min={200}
step={100}
value={videoBitrateKbps}
onChange={(e) => custom(setVideoBitrateKbps)(Math.max(200, Number(e.target.value) || 200))}
/>
<span className="ts-stream-settings-unit">Kbps</span>
<button type="button" onClick={() => custom(setVideoBitrateKbps)(videoBitrateKbps + 500)}>
+
</button>
</div>
</div>
<div className="ts-stream-settings-row">
<span>{t("publish.audioBitrate")}</span>
<SegmentedChoice
value={audioBitrateKbps}
onChange={custom(setAudioBitrateKbps)}
disabled={!audio}
options={AUDIO_BITRATE_CHOICES.map((v) => ({ value: v, label: String(v) }))}
/>
</div>
<div className="ts-stream-settings-row">
<span>{t("publish.viewerLimit")}</span>
<div className="ts-stream-settings-stepper">
<button type="button" onClick={() => setViewerLimit(Math.max(0, viewerLimit - 1))}>
−
</button>
<input
type="number"
min={0}
value={viewerLimit}
onChange={(e) => setViewerLimit(Math.max(0, Number(e.target.value) || 0))}
/>
<button type="button" onClick={() => setViewerLimit(viewerLimit + 1)}>
+
</button>
</div>
</div>
<div className="ts-stream-settings-row">
<span>{t("publish.mode")}</span>
<SegmentedChoice
value={mode}
onChange={setMode}
options={[
{ value: StreamMode.P2P, label: `👥 ${t("publish.mode.p2p")}` },
{
value: StreamMode.SFU,
label: `🖧 ${t("publish.mode.server")}`,
// The SFU path is a different transport entirely
// (requestsfuaccessinfo + mediasoup) and is not built
// yet; offering it would announce a stream nobody can
// watch.
disabled: true,
title: t("publish.mode.serverUnavailable"),
},
]}
/>
</div>
</>
)}
</div>
<div className="ts-dialog-buttons">
<div className="ts-dialog-buttons-right">
<button type="button" onClick={onCancel}>
{t("publish.dialog.cancel")}
</button>
<button
type="button"
className="ts-stream-settings-go"
onClick={() =>
onStart({
name: defaultName,
audio,
accessibility,
mode,
viewerLimit,
height,
fps,
videoBitrateKbps,
audioBitrateKbps,
contentHint,
})
}
>
{t("publish.dialog.golive")}
</button>
</div>
</div>
</div>
</div>
);
}
function UpdatePrompt() {
const t = useT();
const {
@@ -1820,7 +2131,7 @@ function FavoritesDialog({
const pendingNewRef = useRef<Favorite | null>(
prefillNew
? {
id: crypto.randomUUID(),
id: randomId(),
bookmarkName: prefillNew.host || t("favorites.newFavoriteName"),
...prefillNew,
showServerQueryClients: prefillNew.showServerQueryClients === true,
@@ -1843,7 +2154,7 @@ function FavoritesDialog({
const handleNewFavorite = () => {
const nf: Favorite = {
id: crypto.randomUUID(),
id: randomId(),
bookmarkName: t("favorites.newFavoriteName"),
nickname: "",
host: "",
@@ -5355,6 +5666,23 @@ 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 [publishState, setPublishState] = useState<PublishState>("idle");
const [publishViewers, setPublishViewers] = useState<number[]>([]);
const [publishPending, setPublishPending] = useState<[number, string][]>([]);
const [publishError, setPublishError] = useState<string | null>(null);
const publisherRef = useRef<StreamPublisher | null>(null);
const publishPreviewRef = useRef<HTMLVideoElement | null>(null);
const [streamSettingsOpen, setStreamSettingsOpen] = useState(false);
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 +6556,27 @@ 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);
publisherRef.current?.handleEvent(streamEvent);
break;
}
case "poke": {
const id = ++pokeIdRef.current;
setPokes((prev) => [...prev, { id, from: data.from, message: data.message }]);
@@ -6281,6 +6630,17 @@ 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();
publisherRef.current?.stop();
publisherRef.current = null;
setPublishState("idle");
setPublishViewers([]);
setPublishPending([]);
removeSession(sessionId, { skipSocketClose: true });
break;
}
@@ -6517,7 +6877,7 @@ function AppInner() {
ensureAudioContext();
const sessionId = crypto.randomUUID();
const sessionId = randomId();
sessionParamsRef.current.set(sessionId, params);
const socket = DEMO_MODE ? new DemoSocket() : new WebSocket(GATEWAY_URL);
@@ -7339,7 +7699,7 @@ function AppInner() {
const channelNames = channels.filter((c) => whisperChannelIds.has(c.id)).map((c) => c.name);
const clientNames = clients.filter((c) => whisperClientIds.has(c.id)).map((c) => c.name);
if (channelNames.length === 0 && clientNames.length === 0) return;
setWhisperLists((prev) => [...prev, { id: crypto.randomUUID(), name, channelNames, clientNames }]);
setWhisperLists((prev) => [...prev, { id: randomId(), name, channelNames, clientNames }]);
};
const handleActivateWhisperList = (list: WhisperList) => {
@@ -7367,7 +7727,7 @@ function AppInner() {
const handleAddIdentity = () => {
const identity: Identity = {
id: crypto.randomUUID(),
id: randomId(),
name: t("identities.newName"),
nickname: "",
phoneticName: "",
@@ -7490,7 +7850,7 @@ function AppInner() {
const ini = parseIniIdentity(text);
if (ini) {
const identity: Identity = {
id: crypto.randomUUID(),
id: randomId(),
name: ini.name || file.name.replace(/\.ini$/i, "") || t("identities.newName"),
nickname: ini.nickname,
phoneticName: ini.phonetic,
@@ -7506,12 +7866,127 @@ function AppInner() {
return;
}
const name = file.name.replace(/\.(ts3identity\.)?json$/i, "") || t("identities.newName");
const identity: Identity = { id: crypto.randomUUID(), name, nickname: "", phoneticName: "", blob: text };
const identity: Identity = { id: randomId(), name, nickname: "", phoneticName: "", blob: text };
setIdentities((prev) => [...prev, identity]);
};
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]);
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();
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 handleStopPublishing = () => {
publisherRef.current?.stop();
publisherRef.current = null;
setPublishState("idle");
setPublishViewers([]);
setPublishPending([]);
};
const handleStreamButton = () => {
if (publisherRef.current) {
handleStopPublishing();
return;
}
setStreamSettingsOpen(true);
};
const publishClientName = (clid: number) =>
clients.find((c) => c.id === clid)?.name ?? `#${clid}`;
const handleStartPublishing = (options: StreamPublishOptions) => {
if (ownClientId === null) return;
setStreamSettingsOpen(false);
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([]);
setPublishPending([]);
}
},
onViewersChange: setPublishViewers,
onPendingChange: setPublishPending,
onError: setPublishError,
});
publisherRef.current = publisher;
void publisher.start(options);
};
const handleShowClientConnectionInfo = (clientId: number, clientName: string) => {
setClientConnectionInfoTarget({ id: clientId, name: clientName });
setClientConnectionInfo(null);
@@ -8610,6 +9085,21 @@ function AppInner() {
onChange={(e) => setVadThreshold(Number(e.target.value))}
/>
</label>
<button
className={`ts-icon-button${publishState === "live" ? " ts-mic-on" : ""}`}
onClick={handleStreamButton}
// DemoSocket has no answer for setupstream, so in demo mode the
// panel would sit at "starting" forever - after the browser has
// already asked the visitor to pick a screen. Don't offer it.
disabled={!connected || ownClientId === null || DEMO_MODE}
title={
DEMO_MODE
? t("publish.demoUnavailable")
: `${publishState === "live" ? t("publish.stop") : t("publish.start")} (${t("publish.alpha")})`
}
>
{publishState === "live" ? "🛑" : "🖥️"}
</button>
<span className="ts-toolbar-sep" />
<button
className={`ts-icon-button${outputMuted ? " ts-muted-on" : ""}`}
@@ -9148,6 +9638,87 @@ function AppInner() {
</div>
))}
{streamSettingsOpen && (
<StreamSettingsDialog
defaultName={`${ownClient?.name ?? "WebSpeak3"} - ${t("publish.screen")}`}
onStart={handleStartPublishing}
onCancel={() => setStreamSettingsOpen(false)}
/>
)}
{(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")} <AlphaBadge />
</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 />
{publishPending.map(([clid, message]) => (
<div className="ts-stream-request" key={clid}>
<span className="ts-stream-request-who">
{publishClientName(clid)}
{message && <em>{message}</em>}
</span>
<button
className="ts-stream-request-allow"
onClick={() => void publisherRef.current?.approve(clid)}
>
{t("publish.request.allow")}
</button>
<button onClick={() => publisherRef.current?.deny(clid)}>
{t("publish.request.deny")}
</button>
<button
className="ts-stream-request-block"
onClick={() => publisherRef.current?.deny(clid, true)}
title={t("publish.request.blockHint")}
>
{t("publish.request.block")}
</button>
</div>
))}
{publishError && <div className="ts-stream-panel-error">{publishError}</div>}
</div>
)}
{watchedStream && (
<div className="ts-stream-panel">
<div className="ts-stream-panel-header">
<span className="ts-stream-panel-title">
📺 {watchedStream.name || t("stream.untitled")} <AlphaBadge />
</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>
)}
</div>
)}
{clientContextMenu && (
<div
ref={clientContextMenuRef}
@@ -9177,6 +9748,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"
+98
View File
@@ -375,6 +375,54 @@ 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",
"publish.alpha": "Alpha",
"publish.alphaTitle": "Alpha – instabil, kann sich jederzeit ändern oder brechen",
"publish.demoUnavailable": "Übertragen ist in der Demo nicht verfügbar – dafür braucht es einen echten TeamSpeak-6-Server.",
"publish.alphaNote":
"Streaming ist Alpha. Es spricht TeamSpeak 6s Stream/Call-Protokoll, das nicht dokumentiert ist – Verbindungsaufbau, Bildqualität und Zuschauerverwaltung können fehlschlagen oder sich ohne Vorankündigung ändern. Nicht für produktive Nutzung gedacht.",
"publish.start": "Bildschirm übertragen",
"publish.stop": "Übertragung beenden",
"publish.title": "Deine Übertragung",
"publish.screen": "Bildschirm",
"publish.starting": "Wird gestartet…",
"publish.viewers": "{count} Zuschauer",
"publish.request.allow": "Zulassen",
"publish.request.deny": "Ablehnen",
"publish.request.block": "Sperren",
"publish.request.blockHint": "Ablehnen und nicht erneut fragen",
"publish.dialog.title": "Stream-Einstellungen",
"publish.dialog.basic": "Grundeinstellungen",
"publish.dialog.advanced": "Erweiterte Einstellungen",
"publish.dialog.golive": "Live gehen",
"publish.dialog.cancel": "Zurück",
"publish.preset": "Voreinstellung",
"publish.preset.presentation": "Präsentation",
"publish.audio": "Audio aufnehmen",
"publish.privacy": "Privatsphäre",
"publish.privacy.public": "Öffentlich",
"publish.privacy.contacts": "Kontakte",
"publish.privacy.private": "Privat",
"publish.resolution": "Auflösung",
"publish.res.source": "Quelle",
"publish.fps": "FPS",
"publish.bitrate": "Bitrate",
"publish.audioBitrate": "Audio-Bitrate [Kbps]",
"publish.viewerLimit": "Zuschauerbegrenzung",
"publish.mode": "Verbindungsmodus",
"publish.mode.p2p": "P2P",
"publish.mode.server": "Server",
"publish.mode.serverUnavailable": "Der Server-Modus läuft über TS6s SFU und ist noch nicht implementiert.",
"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 +592,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 +1013,54 @@ 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",
"publish.alpha": "Alpha",
"publish.alphaTitle": "Alpha - unstable, may change or break at any time",
"publish.demoUnavailable": "Streaming is not available in the demo - it needs a real TeamSpeak 6 server.",
"publish.alphaNote":
"Streaming is alpha. It speaks TeamSpeak 6's undocumented Stream/Call protocol, so connecting, picture quality and viewer handling can fail or change without notice. Not meant for production use.",
"publish.start": "Share your screen",
"publish.stop": "Stop sharing",
"publish.title": "Your broadcast",
"publish.screen": "Screen",
"publish.starting": "Starting…",
"publish.viewers": "{count} watching",
"publish.request.allow": "Allow",
"publish.request.deny": "Deny",
"publish.request.block": "Block",
"publish.request.blockHint": "Deny and stop asking",
"publish.dialog.title": "Stream settings",
"publish.dialog.basic": "Basic settings",
"publish.dialog.advanced": "Advanced settings",
"publish.dialog.golive": "Go live",
"publish.dialog.cancel": "Back",
"publish.preset": "Preset",
"publish.preset.presentation": "Presentation",
"publish.audio": "Capture audio",
"publish.privacy": "Privacy",
"publish.privacy.public": "Public",
"publish.privacy.contacts": "Contacts",
"publish.privacy.private": "Private",
"publish.resolution": "Resolution",
"publish.res.source": "Source",
"publish.fps": "FPS",
"publish.bitrate": "Bitrate",
"publish.audioBitrate": "Audio bitrate [Kbps]",
"publish.viewerLimit": "Viewer limit",
"publish.mode": "Connection mode",
"publish.mode.p2p": "P2P",
"publish.mode.server": "Server",
"publish.mode.serverUnavailable": "Server mode goes through TS6's SFU and is not implemented yet.",
"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 +1230,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",
+499
View File
@@ -0,0 +1,499 @@
// 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";
// The three enums below are read straight out of TS6's own UI bundle
// (main.js), not inferred - see ts6-re/findings §10.
/** `type` in `setupstream`: what is being captured. */
export const StreamSource = {
NONE: 0,
CAMERA: 1,
SCREEN: 2,
WINDOW: 3,
EXISTING_SESSION: 4,
} as const;
/** `accessibility` in `setupstream`: TS6's Privacy setting. */
export const StreamAccess = {
NONE: 0,
PUBLIC: 1,
CONTACTS_ONLY: 2,
PRIVATE: 3,
} as const;
/** `mode` in `setupstream`: TS6's Connection Mode. */
export const StreamMode = {
NONE: 0,
P2P: 1,
SFU: 2,
} as const;
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;
/** Send the capture's audio track too, when the source has one. */
audio: boolean;
/** One of StreamAccess. */
accessibility: number;
/** One of StreamMode. Only P2P is implemented; SFU needs the mediasoup path. */
mode: number;
/** 0 means unlimited. */
viewerLimit: number;
/** Capture height in pixels; 0 keeps the source's own resolution. */
height: number;
/** Capture frame rate; 0 leaves it to the browser. */
fps: number;
videoBitrateKbps: number;
audioBitrateKbps: number;
/**
* What the encoder should protect when it runs out of bitrate. Slides and
* code want "detail" (keep text sharp, drop frames); a game wants "motion".
*/
contentHint: "motion" | "detail";
}
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;
/** Join requests awaiting a decision, as [clid, message] pairs. */
onPendingChange?: (pending: [number, string][]) => 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>();
/** Requests waiting for the user to decide: clid -> the viewer's message. */
private readonly pending = new Map<number, string>();
/** Clients denied with "block"; they are refused without asking again. */
private readonly blocked = new Set<number>();
private media: MediaStream | null = null;
private state: PublishState = "idle";
private options: StreamPublishOptions | null = null;
/** 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");
this.options = options;
const video: MediaTrackConstraints = {};
if (options.height > 0) video.height = { ideal: options.height };
if (options.fps > 0) video.frameRate = { ideal: options.fps };
try {
this.media = await navigator.mediaDevices.getDisplayMedia({
video: Object.keys(video).length > 0 ? video : true,
audio: options.audio,
});
} catch (err) {
this.setState("idle");
this.fail(`Could not capture the screen: ${describe(err)}`);
return;
}
for (const track of this.media.getVideoTracks()) track.contentHint = options.contentHint;
// 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,
// The browser's own picker decides whether this is a whole screen or a
// single window, so the type is read back off the track rather than
// asked for up front.
streamType: this.detectSourceType(),
bitrate: options.videoBitrateKbps * 1000,
accessibility: options.accessibility,
mode: options.mode,
viewerLimit: options.viewerLimit,
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;
}
}
/**
* Decides what to do with an incoming join request.
*
* This mirrors TS6's own publisher-side rule, which is the only place either
* setting is enforced at all - the server stores `accessibility` and
* `viewer_limit`, echoes them back, and then forwards every request anyway
* (verified live: a PRIVATE stream at viewer_limit=1 still had both viewers
* announced to us).
*
* The important half is what happens to a request we do not take: TS6 leaves
* it *pending* rather than refusing it. A refusal is not sticky - TS6's own
* "block" path is deny plus a ban - so a refused client simply asks again, in
* a loop, and shows its user nothing. Left pending, it asks once and displays
* "waiting for access" until we answer.
*/
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) || this.pending.has(clid)) return;
// Explicitly blocked earlier: refuse without bothering the user again.
if (this.blocked.has(clid)) {
this.refuse(clid, "Blocked");
return;
}
const limit = this.options?.viewerLimit ?? 0;
const full = limit > 0 && this.viewers.size >= limit;
const autoAccept = this.options?.accessibility === StreamAccess.PUBLIC && !full;
if (!autoAccept) {
// CONTACTS_ONLY behaves as PRIVATE here: the contact list is a TS6
// account feature webspeak3 has no access to, so it cannot be consulted.
this.pending.set(clid, args.msg ?? "");
this.notifyPending();
return;
}
await this.openTo(clid);
}
/** Lets a pending viewer in. Called by admit() or by the user. */
async approve(clid: number): Promise<void> {
if (!this.pending.delete(clid)) return;
this.notifyPending();
await this.openTo(clid);
}
/**
* Turns a pending viewer away. `block` also remembers the refusal, which is
* what makes it stick - TS6 pairs its deny with a ban for the same reason.
*/
deny(clid: number, block = false): void {
this.pending.delete(clid);
if (block) this.blocked.add(clid);
this.notifyPending();
this.refuse(clid, block ? "Blocked" : "Denied");
}
private refuse(clid: number, message: string): void {
if (!this.streamId) return;
this.opts.send({
type: "respondJoinStream",
streamId: this.streamId,
clientId: clid,
accept: false,
message,
});
}
/** Builds the peer connection for a viewer we have decided to let in. */
private async openTo(clid: number): Promise<void> {
if (!this.media || !this.streamId || 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);
await this.applySendParameters(pc);
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;
}
}
}
/**
* Caps each sender at the configured bitrate and pins the resolution.
*
* `setupstream`'s `bitrate` is only what the stream *advertises* - the
* server does not even echo our value back unchanged, and it certainly does
* not reach the encoder. The actual limit is a sender parameter, and the
* encodings it lives on only exist once a local description is set.
*
* `degradationPreference` matters just as much. Its default for a track
* hinted "motion" is to protect the frame rate and shrink the picture, which
* for a screen share is exactly backwards: the user picked 1080p, so 1080p is
* the thing to keep. Measured on a 1440x1080 capture at a 6000 kbps cap:
*
* default / maintain-framerate / balanced -> 480x270, a 3x downscale
* maintain-resolution -> 1440x810, no downscale
*
* Without this the encoder collapses within seconds of the connection coming
* up and never recovers, and every resolution setting above 360p is a lie.
*/
private async applySendParameters(pc: RTCPeerConnection): Promise<void> {
const options = this.options;
if (!options) return;
for (const sender of pc.getSenders()) {
if (!sender.track) continue;
const video = sender.track.kind === "video";
const kbps = video ? options.videoBitrateKbps : options.audioBitrateKbps;
const params = sender.getParameters();
if (video) params.degradationPreference = "maintain-resolution";
if (kbps > 0) {
if (!params.encodings || params.encodings.length === 0) params.encodings = [{}];
for (const encoding of params.encodings) encoding.maxBitrate = kbps * 1000;
}
try {
await sender.setParameters(params);
} catch (err) {
// Not fatal - the stream still runs, just uncapped and free to shrink.
console.warn("[publish] could not apply the send parameters:", describe(err));
}
}
}
/**
* Maps the capture to TS6's source enum.
*
* `displaySurface` is what the user actually picked in the browser's own
* share dialog, so it is more truthful than anything we could ask for in
* advance. A browser tab has no TS6 equivalent and reads closest to a window.
*/
private detectSourceType(): number {
const surface = this.media?.getVideoTracks()[0]?.getSettings().displaySurface;
return surface === "monitor" ? StreamSource.SCREEN : StreamSource.WINDOW;
}
private dropViewer(clid: number): void {
// Someone can also leave while their request is still queued - by closing
// TS6, or by giving up on "waiting for access". The row has to go with
// them, or the user is left approving a viewer who is no longer there.
if (this.pending.delete(clid)) this.notifyPending();
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();
this.pending.clear();
this.blocked.clear();
for (const track of this.media?.getTracks() ?? []) track.stop();
this.media = null;
this.streamId = null;
this.options = null;
this.notifyViewers();
this.notifyPending();
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 notifyPending(): void {
this.opts.onPendingChange?.([...this.pending.entries()]);
}
private fail(message: string): void {
this.opts.onError?.(message);
}
}
function describe(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
+315
View File
@@ -0,0 +1,315 @@
// 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.
*
* Each `cmd` names its own key inside `args`, and the key is *not* `sdp`
* except for `iceCandidate`: an answer is `{answer: "<sdp>"}`, an offer
* `{offer: "<sdp>"}`, a candidate `{sdp, mid, mLine}`. Live-verified against
* TS6 6.0.0-beta12.1 - `{sdp: "<sdp>"}` and a bare string are both accepted
* by the server and then silently dropped by the client.
*/
interface SignalingMessage {
cmd: string;
args: 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", { answer: 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 =
typeof msg.args === "object" && msg.args !== null
? candidateFromArgs(msg.args as Record<string, unknown>)
: null;
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.
// `offer` mirrors the `answer` key we send; the other two are cheap
// to tolerate and cost nothing if they never arrive.
const a = msg.args as Record<string, unknown> | string | null;
const sdp =
typeof a === "string"
? a
: typeof a?.offer === "string"
? a.offer
: typeof a?.sdp === "string"
? a.sdp
: null;
if (sdp) await this.acceptOffer(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: 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);
}