tvpipe 0.3.0

Stream a program's frames and sound, files, web pages or the screen to Apple TVs, Chromecasts and browser tabs with low latency, in process
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/**
 * The client side of the party protocol (docs/party-protocol.md): phones
 * and TV pages import it from tvpipe (`/_tvpipe/lib/client.js`). It runs
 * in browsers and in Node ≥ 22 (tests and bots use it as fake phones).
 *
 *   import { PartyClient } from "/_tvpipe/lib/client.js";
 *   const party = PartyClient.fromLocation();
 *   party.on("view", (view) => render(view));
 *   await party.join("Ann");                 // or party.connect() with a saved identity
 *   await party.act("answer", { text: "…" }); // acked, resent after reconnects
 *   party.input({ x: 0.3, y: -1 });          // continuous input, latest wins
 */
export const PROTOCOL = 1;
/** `bye` reasons after which the client does not reconnect. */
const FINAL = new Set([
    "bad-key",
    "no-room",
    "no-player",
    "name-taken",
    "name-invalid",
    "replaced",
    "kicked",
    "room-closed",
    "full",
    "locked",
    "in-progress",
    "protocol",
    "left",
    "rate-limited",
    "too-big",
]);
/**
 * Close codes that are final without a `bye` (tvpipe's own closes:
 * the game ended, too fast, too big; the host's codes when its `bye`
 * got lost).
 */
const FINAL_CODES = {
    1009: "too-big",
    4002: "protocol",
    4003: "bad-key",
    4004: "no-room",
    4005: "no-player",
    4006: "name-taken",
    4007: "name-invalid",
    4008: "rate-limited",
    4009: "replaced",
    4010: "kicked",
    4011: "room-closed",
    4029: "full",
    4030: "in-progress",
};
/** Unacknowledged actions kept at most. */
const MAX_PENDING = 32;
/** `input()` at most this often, ms (latest wins). */
const INPUT_INTERVAL = 100;
/** An action the host refused, or one that could not be sent. */
export class PartyActionError extends Error {
    code;
    constructor(code, message) {
        super(message);
        this.name = "PartyActionError";
        this.code = code;
    }
}
function isObject(v) {
    return typeof v === "object" && v !== null && !Array.isArray(v);
}
/**
 * Applies a `state` diff to a view in place (`set` merges objects,
 * replaces everything else; then `del` paths are removed). The host's
 * `applyDiff` (sync.ts) follows the same rules.
 */
export function applyDiff(view, d) {
    if (d.set)
        merge(view, d.set);
    for (const path of d.del ?? []) {
        let o = view;
        for (let i = 0; i < path.length - 1 && isObject(o); i++)
            o = o[path[i]];
        if (isObject(o))
            delete o[path[path.length - 1]];
    }
    return view;
}
function merge(target, patch) {
    for (const k of Object.keys(patch)) {
        const pv = patch[k];
        if (isObject(pv) && isObject(target[k]))
            merge(target[k], pv);
        else
            target[k] = pv;
    }
}
/**
 * What a TV or host page shows people to type (`view.join` on screens,
 * `party.joinInfo` on the host): the short link without its scheme
 * (`tvpipe.party/BCDF`), or `null` when there is none: then show only the
 * QR code (the direct link is too long to type, and without its key it
 * lets nobody in).
 */
export function joinText(join) {
    const s = join?.short;
    if (typeof s !== "string" || !/^https?:\/\/[^/?#\s]+\/[A-Za-z]{1,16}$/.test(s))
        return null;
    return s.replace(/^https?:\/\//, "");
}
/**
 * An SVG document of a QR code (`view.join.qr` on screens): dark modules
 * on a light square with a quiet zone. Insert it as markup (it holds no
 * text from players).
 */
export function qrSvg(qr, opts = {}) {
    if (!qr)
        return "";
    const quiet = opts.quiet ?? 4;
    const n = qr.size + 2 * quiet;
    const color = (c) => (/^[#a-zA-Z0-9(),.% ]+$/.test(c) ? c : "#000");
    let d = "";
    qr.rows.forEach((row, y) => {
        for (let x = 0; x < row.length; x++) {
            if (row[x] !== "1")
                continue;
            let w = 1;
            while (row[x + w] === "1")
                w++;
            d += `M${x + quiet} ${y + quiet}h${w}v1h-${w}z`;
            x += w - 1;
        }
    });
    return (`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n} ${n}" shape-rendering="crispEdges">` +
        `<rect width="${n}" height="${n}" fill="${color(opts.light ?? "#fff")}"/>` +
        `<path d="${d}" fill="${color(opts.dark ?? "#000")}"/></svg>`);
}
/** Draws a QR code into a 2D canvas context: `size` px square including the quiet zone. */
export function drawQr(ctx, qr, x, y, size, opts = {}) {
    if (!qr)
        return;
    const quiet = opts.quiet ?? 4;
    const px = size / (qr.size + 2 * quiet);
    ctx.fillStyle = opts.light ?? "#fff";
    ctx.fillRect(x, y, size, size);
    ctx.fillStyle = opts.dark ?? "#000";
    qr.rows.forEach((row, r) => {
        for (let c = 0; c < row.length; c++) {
            if (row[c] !== "1")
                continue;
            let w = 1;
            while (row[c + w] === "1")
                w++;
            // Snap to whole pixels so neighbouring modules leave no seams.
            const x0 = Math.round(x + (c + quiet) * px);
            const x1 = Math.round(x + (c + w + quiet) * px);
            const y0 = Math.round(y + (r + quiet) * px);
            const y1 = Math.round(y + (r + 1 + quiet) * px);
            ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
            c += w - 1;
        }
    });
}
/** The default socket path on the page's origin. */
export const SOCKET_PATH = "/_tvpipe/ws";
export class PartyClient {
    /**
     * The party of the page's link: `?r=CODE` (or `#r=CODE`), `#k=KEY` and
     * `#role=screen|watch` (players: none).
     */
    static fromLocation(opts = {}) {
        const loc = globalThis.location;
        const q = new URLSearchParams(loc.search);
        const h = new URLSearchParams(loc.hash.replace(/^#/, ""));
        const room = opts.room ?? h.get("r") ?? q.get("r") ?? "";
        const key = opts.key ?? h.get("k") ?? q.get("k") ?? undefined;
        const url = opts.url ?? `${loc.protocol === "https:" ? "wss:" : "ws:"}//${loc.host}${SOCKET_PATH}`;
        const r = opts.role ?? h.get("role") ?? "player";
        const role = r === "screen" || r === "watch" ? r : "player";
        return new PartyClient({ ...opts, url, room, key, role });
    }
    url;
    room;
    key;
    role;
    storage;
    /** The current view (`{ roster, room, me }` or `{ roster, screen, join }`). */
    view = {};
    /** Who this client is, from `welcome`. */
    you = null;
    status = "idle";
    /** The reason of the last `bye`, if any. */
    byeReason = null;
    #WS;
    #listeners = new Map();
    #ws = null;
    #rev = 0;
    #attempt = 0;
    #retry = null;
    #pinger = null;
    #name;
    #nextAct = 1;
    #pending = new Map();
    #inSeq = 0;
    #inLast = 0;
    #inQueued = null;
    #inTimer = null;
    /** Clock: server time = Date.now() + offset. */
    #offset = 0;
    #bestRtt = Infinity;
    #samples = [];
    #waiting = null;
    #onVisible = () => {
        if (globalThis.document?.visibilityState !== "visible")
            return;
        if (this.status === "reconnecting") {
            this.#attempt = 0;
            this.#open();
        }
    };
    constructor(opts) {
        this.url = opts.url;
        this.room = opts.room.toUpperCase();
        this.key = opts.key;
        this.role = opts.role ?? "player";
        this.storage = opts.storage !== undefined ? opts.storage : safeStorage();
        this.#WS = opts.WebSocket ?? globalThis.WebSocket;
    }
    get #storageKey() {
        let host = "";
        try {
            host = new URL(this.url).host;
        }
        catch { }
        return `tvpipe-party:${host}:${this.room}:${this.role}`;
    }
    /** The saved identity (`resume`, `name`) of this room, if any. */
    get saved() {
        try {
            const s = this.storage?.getItem(this.#storageKey);
            const v = s ? JSON.parse(s) : null;
            return isObject(v) ? v : null;
        }
        catch {
            return null;
        }
    }
    /** Whether `connect()` can come back as an earlier player. */
    get canResume() {
        return this.role !== "player" || typeof this.saved?.resume === "string";
    }
    /** Events: `view`, `welcome`, `msg`, `status`, `bye`, `ack`. */
    on(event, fn) {
        let set = this.#listeners.get(event);
        if (!set)
            this.#listeners.set(event, (set = new Set()));
        set.add(fn);
        return () => set.delete(fn);
    }
    off(event, fn) {
        this.#listeners.get(event)?.delete(fn);
    }
    #emit(event, ...args) {
        for (const fn of [...(this.#listeners.get(event) ?? [])]) {
            try {
                fn(...args);
            }
            catch (err) {
                console.error(err);
            }
        }
    }
    /**
     * Joins as a new player with this name (or comes back as the saved one).
     * Rejects with a {@link PartyActionError} (`name-taken`, `full`, …).
     */
    join(name) {
        this.#name = name;
        return this.connect();
    }
    /** Connects: a screen, or a player with a saved identity. Resolves with `welcome`. */
    connect() {
        if (this.#name === undefined)
            this.#name = this.saved?.name;
        return new Promise((resolve, reject) => {
            this.#waiting = { resolve, reject };
            this.byeReason = null;
            this.#attempt = 0;
            globalThis.document?.addEventListener?.("visibilitychange", this.#onVisible);
            this.#open();
        });
    }
    #open() {
        if (this.#retry)
            clearTimeout(this.#retry);
        this.#retry = null;
        if (this.#ws) {
            const old = this.#ws;
            this.#ws = null;
            old.onclose = null;
            try {
                old.close();
            }
            catch { }
        }
        this.#setStatus(this.you ? "reconnecting" : "connecting");
        let ws;
        try {
            ws = new this.#WS(this.url);
        }
        catch (err) {
            return this.#fail("protocol", String(err));
        }
        this.#ws = ws;
        ws.onopen = () => {
            const saved = this.saved;
            const hello = { t: "hello", v: PROTOCOL, room: this.room, role: this.role, key: this.key };
            if (this.role === "player") {
                if (saved?.resume)
                    hello["resume"] = saved.resume;
                if (this.#name !== undefined)
                    hello["name"] = this.#name;
            }
            hello["agent"] = globalThis.navigator?.userAgent ?? "";
            ws.send(JSON.stringify(hello));
        };
        ws.onmessage = (ev) => {
            if (typeof ev.data !== "string")
                return;
            let msg;
            try {
                msg = JSON.parse(ev.data);
            }
            catch {
                return;
            }
            if (isObject(msg))
                this.#onMessage(msg);
        };
        ws.onerror = () => { };
        ws.onclose = (ev) => {
            if (this.#ws !== ws)
                return;
            this.#ws = null;
            this.#stopPing();
            const reason = this.byeReason ?? FINAL_CODES[ev.code] ?? null;
            if (reason && FINAL.has(reason)) {
                if (!this.byeReason) {
                    this.byeReason = reason;
                    this.#emit("bye", reason, ev.reason || undefined);
                }
                return this.#fail(reason, ev.reason || reason);
            }
            if (this.status === "closed")
                return;
            this.#setStatus(this.you ? "reconnecting" : "connecting");
            const delay = Math.min(5000, 250 * 2 ** this.#attempt++) * (0.75 + Math.random() * 0.5);
            this.#retry = setTimeout(() => this.#open(), delay);
        };
    }
    #fail(reason, message) {
        this.#setStatus("closed");
        if (reason === "no-player" || reason === "kicked" || reason === "bad-key")
            this.#forget();
        const err = new PartyActionError(reason, message);
        for (const p of this.#pending.values())
            p.reject(err);
        this.#pending.clear();
        if (this.#waiting) {
            this.#waiting.reject(err);
            this.#waiting = null;
        }
        this.#stopInput();
        globalThis.document?.removeEventListener?.("visibilitychange", this.#onVisible);
    }
    #forget() {
        try {
            this.storage?.removeItem(this.#storageKey);
        }
        catch { }
    }
    #setStatus(s) {
        if (this.status === s)
            return;
        this.status = s;
        this.#emit("status", s);
    }
    #onMessage(msg) {
        switch (msg["t"]) {
            case "welcome": {
                const first = this.you === null;
                this.you = msg["you"];
                this.view = msg["view"] ?? {};
                this.#rev = msg["rev"] ?? 0;
                this.#attempt = 0;
                this.#sample(0, msg["now"]);
                if (this.role === "player" && msg["you"]?.resume) {
                    try {
                        this.storage?.setItem(this.#storageKey, JSON.stringify({ resume: msg["you"].resume, name: msg["you"].name }));
                    }
                    catch { }
                }
                this.#setStatus("open");
                // Continue after what the host has seen; resend what it has not acked.
                const last = Number(msg["you"]?.lastAct ?? 0);
                if (first) {
                    // Actions queued before the first welcome were numbered blindly
                    // (a reloaded page starts at 1): number them after the host's.
                    const queued = [...this.#pending.values()];
                    this.#pending.clear();
                    this.#nextAct = last + 1;
                    for (const p of queued)
                        this.#pending.set(this.#nextAct++, p);
                }
                for (const [id, p] of this.#pending)
                    this.#send({ t: "act", id, type: p.type, data: p.data });
                this.#startPing();
                this.#emit("welcome", msg);
                this.#emit("view", this.view, null);
                if (this.#waiting) {
                    this.#waiting.resolve(msg);
                    this.#waiting = null;
                }
                return;
            }
            case "state": {
                if (typeof msg["rev"] === "number" && msg["rev"] <= this.#rev)
                    return;
                if (msg["full"]) {
                    this.view = msg["full"];
                }
                else {
                    if (msg["rev"] !== this.#rev + 1)
                        this.#send({ t: "resync" });
                    applyDiff(this.view, msg);
                }
                this.#rev = msg["rev"];
                this.#emit("view", this.view, msg);
                return;
            }
            case "ack": {
                const p = this.#pending.get(msg["id"]);
                if (!p)
                    return;
                this.#pending.delete(msg["id"]);
                if (msg["ok"])
                    p.resolve(msg["result"] ?? null);
                else
                    p.reject(new PartyActionError(msg["error"]?.code ?? "error", msg["error"]?.message ?? "refused"));
                this.#emit("ack", msg);
                return;
            }
            case "msg":
                this.#emit("msg", msg["type"], msg["data"]);
                return;
            case "pong":
                this.#sample(msg["c"], msg["now"]);
                return;
            case "bye":
                this.byeReason = String(msg["reason"]);
                this.#emit("bye", this.byeReason, msg["message"]);
                return;
        }
    }
    /**
     * One clock sample: `c` is when the ping left (Date.now()), `now` the
     * host's time when it answered. Keeps the offset of the fastest of the
     * last 16 round trips.
     */
    #sample(c, now) {
        if (typeof now !== "number")
            return;
        const t = Date.now();
        const rtt = c > 0 ? t - c : 1000; // welcome: a rough first guess
        this.#samples.push({ rtt, offset: now - (c > 0 ? (c + t) / 2 : t) });
        if (this.#samples.length > 16)
            this.#samples.shift();
        const best = this.#samples.reduce((a, b) => (b.rtt < a.rtt ? b : a));
        this.#offset = best.offset;
        this.#bestRtt = best.rtt;
    }
    #startPing() {
        this.#stopPing();
        let n = 0;
        const ping = () => this.#send({ t: "ping", c: Date.now() });
        ping();
        this.#pinger = setInterval(() => {
            ping();
            if (++n === 4 && this.#pinger) {
                clearInterval(this.#pinger);
                this.#pinger = setInterval(ping, 10_000);
            }
        }, 300);
    }
    #stopPing() {
        if (this.#pinger)
            clearInterval(this.#pinger);
        this.#pinger = null;
    }
    /** The host's clock (ms since the epoch): deadlines in views use it. */
    now() {
        return Date.now() + this.#offset;
    }
    /** The fastest recent round trip to the host, ms. */
    get rtt() {
        return this.#bestRtt;
    }
    #send(msg) {
        const ws = this.#ws;
        if (!ws || ws.readyState !== 1 || this.status !== "open")
            return false;
        ws.send(JSON.stringify(msg));
        return true;
    }
    /**
     * Sends continuous input (a stick, a tilt): latest wins, never acked,
     * may be lost; at most every 100 ms (the latest data then). The host
     * sees it as `player.input` and the `input` event.
     */
    input(data) {
        if (this.status !== "open")
            return;
        this.#inQueued = { data };
        if (this.#inTimer)
            return;
        const wait = this.#inLast + INPUT_INTERVAL - Date.now();
        if (wait <= 0)
            return this.#flushInput();
        this.#inTimer = setTimeout(() => {
            this.#inTimer = null;
            this.#flushInput();
        }, wait);
    }
    #flushInput() {
        const q = this.#inQueued;
        this.#inQueued = null;
        if (!q || this.status !== "open")
            return;
        this.#inLast = Date.now();
        this.#send({ t: "in", s: ++this.#inSeq, data: q.data });
    }
    #stopInput() {
        if (this.#inTimer)
            clearTimeout(this.#inTimer);
        this.#inTimer = null;
        this.#inQueued = null;
    }
    /**
     * Sends an action; resolves with the host's result, rejects with a
     * {@link PartyActionError} when the host refuses it. Survives reconnects
     * (sent again, applied once).
     */
    act(type, data = null) {
        if (this.status === "closed")
            return Promise.reject(new PartyActionError("closed", "Not connected"));
        if (this.#pending.size >= MAX_PENDING)
            return Promise.reject(new PartyActionError("busy", "Too many actions waiting"));
        const id = this.#nextAct++;
        return new Promise((resolve, reject) => {
            this.#pending.set(id, { type, data, resolve, reject });
            this.#send({ t: "act", id, type, data });
        });
    }
    /** Leaves the party for good (the identity is forgotten). */
    leave() {
        this.#send({ t: "leave" });
        this.byeReason = "left";
        this.#forget();
        this.close();
    }
    /** Closes the connection (no reconnect). */
    close() {
        this.#setStatus("closed");
        if (this.#retry)
            clearTimeout(this.#retry);
        this.#stopPing();
        this.#stopInput();
        const ws = this.#ws;
        this.#ws = null;
        if (ws) {
            ws.onclose = null;
            try {
                ws.close();
            }
            catch { }
        }
        for (const p of this.#pending.values())
            p.reject(new PartyActionError("closed", "Closed"));
        this.#pending.clear();
        globalThis.document?.removeEventListener?.("visibilitychange", this.#onVisible);
    }
    /** For tests: drop the socket as a network loss would (the client reconnects). */
    drop() {
        try {
            this.#ws?.close(4999, "dropped");
        }
        catch { }
    }
}
function safeStorage() {
    try {
        const s = globalThis.localStorage;
        if (!s)
            return null;
        s.getItem("x");
        return s;
    }
    catch {
        return null;
    }
}
/** A tiny in-memory storage (for tests, or browsers that refuse `localStorage`). */
export function memoryStorage() {
    const m = new Map();
    return {
        getItem: (k) => (m.has(k) ? m.get(k) : null),
        setItem: (k, v) => void m.set(k, String(v)),
        removeItem: (k) => void m.delete(k),
    };
}