import { Emitter } from "./emitter.js";
import { Party } from "./party.js";
import { TvpipeRelay } from "./relay.js";
import { captureAudio, SurfaceEncoder } from "./surface.js";
export class TvpipeError extends Error {
code;
constructor(code, message) {
super(message);
this.name = "TvpipeError";
this.code = code;
}
}
const LAUNCHER = "/_tvpipe/launcher/";
export const PICKER_MESSAGE = "tvpipe:cast-picker";
export class Tvpipe extends Emitter {
static connect(opts = {}) {
let url = opts.url;
if (!url) {
const loc = globalThis.location;
url = `${loc.protocol === "https:" ? "wss:" : "ws:"}//${loc.host}/_tvpipe/api`;
}
if (opts.token)
url += `${url.includes("?") ? "&" : "?"}t=${encodeURIComponent(opts.token)}`;
const WS = opts.WebSocket ?? globalThis.WebSocket;
const ws = new WS(url);
ws.binaryType = "arraybuffer";
return new Promise((resolve, reject) => {
ws.onopen = () => resolve(new Tvpipe(ws));
ws.onerror = () => reject(new TvpipeError("connect", `cannot reach tvpipe at ${url.replace(/t=[^&]*/, "t=…")}`));
});
}
#ws;
#n = 0;
#calls = new Map();
#relay;
#closed = false;
constructor(ws) {
super();
this.#ws = ws;
ws.onerror = null;
ws.onmessage = (ev) => {
if (typeof ev.data === "string")
this.#onText(ev.data);
else if (ev.data instanceof ArrayBuffer)
this.#relay?.handleBinary(new Uint8Array(ev.data));
};
ws.onclose = () => {
this.#closed = true;
const err = new TvpipeError("closed", "the connection to tvpipe closed");
for (const w of this.#calls.values())
w.reject(err);
this.#calls.clear();
this.#relay?.handleDetach();
this.emit("close");
};
}
get closed() {
return this.#closed;
}
#onText(text) {
let msg;
try {
msg = JSON.parse(text);
}
catch {
return;
}
if (typeof msg !== "object" || msg === null)
return;
if (msg["t"] === "reply") {
const w = this.#calls.get(msg["n"]);
if (!w)
return;
this.#calls.delete(msg["n"]);
if (msg["ok"])
w.resolve(msg["value"]);
else
w.reject(new TvpipeError(msg["error"]?.code ?? "failed", msg["error"]?.message ?? "failed"));
return;
}
if (msg["t"] === "event") {
const data = msg["data"];
switch (msg["type"]) {
case "devices":
this.emit("devices", Array.isArray(data) ? data : []);
return;
case "pair":
this.emit("pair", data);
return;
case "cast":
this.emit("cast", data);
return;
case "tunnel":
this.emit("tunnel", data);
return;
case "closing":
this.#relay?.onclosing?.();
this.emit("closing");
return;
case "detached":
this.emit("detached");
return;
case "surface":
this.emit("surface", data);
return;
}
return;
}
this.#relay?.handleControl(msg);
}
call(method, params = {}) {
if (this.#closed)
return Promise.reject(new TvpipeError("closed", "the connection to tvpipe closed"));
const n = ++this.#n;
return new Promise((resolve, reject) => {
this.#calls.set(n, { resolve, reject });
this.#ws.send(JSON.stringify({ t: "call", n, method, params }));
});
}
info() {
return this.call("info");
}
watchDevices(on = true) {
return this.call("devices.watch", { on });
}
async select(devices, opts = {}) {
const params = { devices };
if (opts.resolution)
params["resolution"] = opts.resolution;
return this.call("select", params);
}
async selection() {
return (await this.chosen()).devices;
}
chosen() {
return this.call("selection");
}
async pair(device) {
await this.call("pair.start", { device });
}
async pairPin(device, pin) {
await this.call("pair.pin", { device, pin });
}
async pairCancel(device) {
await this.call("pair.cancel", { device });
}
cast(opts) {
const params = { page: opts.page };
if (opts.to)
params["to"] = opts.to;
if (opts.resolution)
params["resolution"] = opts.resolution;
return this.call("cast.start", params);
}
async showCastPicker() {
const doc = globalThis.document;
if (!doc)
throw new TvpipeError("unsupported", "the cast picker needs a page");
const info = await this.info();
const src = `${info.pages.launcher ?? LAUNCHER}?mode=change`;
return new Promise((resolve) => {
const dialog = doc.createElement("dialog");
dialog.className = "tvpipe-cast-picker";
dialog.style.cssText =
"padding:0;border:0;border-radius:12px;width:min(760px,94vw);height:min(680px,90vh);overflow:hidden;background:transparent;box-shadow:0 20px 60px rgb(0 0 0 / 40%)";
const frame = doc.createElement("iframe");
frame.title = "Change the TVs";
frame.src = src;
frame.style.cssText = "display:block;width:100%;height:100%;border:0";
dialog.append(frame);
const done = (sel) => {
removeEventListener("message", onMessage);
dialog.close();
dialog.remove();
resolve(sel);
};
const onMessage = (ev) => {
if (ev.source !== frame.contentWindow || ev.origin !== globalThis.location.origin)
return;
const d = ev.data;
if (d?.type !== PICKER_MESSAGE)
return;
done(d.selection ?? null);
};
addEventListener("message", onMessage);
dialog.addEventListener("cancel", (ev) => {
ev.preventDefault();
done(null);
});
doc.body.append(dialog);
dialog.showModal();
});
}
async stopCast() {
await this.call("cast.stop");
}
shortLink(url, code) {
return this.call("shortlink", { url, code });
}
qr(text) {
return this.call("qr", { text });
}
openSurface(opts) {
const params = { width: opts.width, height: opts.height, fps: opts.fps ?? 30 };
if (opts.to)
params["to"] = opts.to;
if (opts.audio)
params["audio"] = true;
if (opts.bitrate)
params["bitrate"] = opts.bitrate;
return this.call("surface.open", params);
}
async closeSurface(id) {
await this.call("surface.close", { id });
}
async surface(opts) {
const info = await this.openSurface({
width: opts.canvas.width,
height: opts.canvas.height,
fps: opts.fps,
to: opts.to,
audio: !!opts.audio,
bitrate: opts.bitrate,
});
const enc = new SurfaceEncoder(info, opts.canvas, opts);
if (opts.audio && info.audio) {
const stop = await captureAudio(opts.audio.context, opts.audio.node, info.audio.channels, (pcm, pts) => enc.pushAudio(pcm, pts));
enc.on("end", stop);
}
enc.on("end", () => void this.closeSurface(info.id).catch(() => { }));
await enc.ready;
return enc;
}
async quit() {
await this.call("quit").catch(() => { });
}
async relay() {
const r = await this.call("relay.attach");
const ws = this.#ws;
this.#relay = new TvpipeRelay({
sendText: (t) => ws.send(t),
sendBinary: (d) => ws.send(d),
}, r.public);
return this.#relay;
}
async party(options = {}) {
const info = await this.info();
const relay = await this.relay();
const party = new HostedParty(this, info, relay, options);
await party.refreshJoin();
return party;
}
close() {
this.#ws.close();
}
}
export class HostedParty extends Party {
tvpipe;
info;
relay;
links;
constructor(tvpipe, info, relay, options) {
super({ maxPlayers: info.players.max, ...options });
this.tvpipe = tvpipe;
this.info = info;
this.relay = relay;
this.listen(relay);
const tv = `${info.pages.tv}#r=${this.code}&k=${this.screenKey}&role=screen`;
this.links = {
join: this.#joinUrl(info.phone.url),
tv,
watch: `${info.local}${info.pages.tv}#r=${this.code}&k=${this.watchKey}&role=watch`,
};
tvpipe.on("tunnel", (t) => {
if (t.state === "up" && t.url) {
this.info.phone = { ...this.info.phone, url: t.url, mode: "tunnel" };
void this.refreshJoin();
}
});
}
#joinUrl(base) {
return `${base.endsWith("/") ? base : `${base}/`}?r=${this.code}#k=${this.joinKey}`;
}
#refreshes = 0;
async refreshJoin() {
const n = ++this.#refreshes;
const join = this.#joinUrl(this.info.phone.url);
const mode = this.info.phone.mode;
this.links = { ...this.links, join };
let qr = null;
try {
qr = await this.tvpipe.qr(join);
}
catch { }
if (n !== this.#refreshes)
return;
const keep = this.joinInfo.url === join ? this.joinInfo.short : undefined;
this.joinInfo = { code: this.code, url: join, qr, mode, ...(keep ? { short: keep } : {}) };
if (mode !== "tunnel")
return;
void this.tvpipe.shortLink(join, this.code).then((r) => {
if (n === this.#refreshes && r.url !== this.joinInfo.short)
this.joinInfo = { ...this.joinInfo, short: r.url };
}, () => { });
}
cast(to, opts = {}) {
return this.tvpipe.cast({ page: this.links.tv, to, resolution: opts.resolution });
}
async changeCast() {
const sel = await this.tvpipe.showCastPicker();
if (!sel)
return null;
if (sel.devices.length === 0) {
await this.stopCast();
return { state: "stopped" };
}
return this.cast();
}
stopCast() {
return this.tvpipe.stopCast();
}
}