@tvpipe/sdk 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +212 -2
  3. package/bin/tvpipe.js +29 -0
  4. package/dist/api.d.ts +169 -0
  5. package/dist/api.d.ts.map +1 -0
  6. package/dist/api.js +327 -0
  7. package/dist/api.js.map +1 -0
  8. package/dist/binary.d.ts +21 -0
  9. package/dist/binary.d.ts.map +1 -0
  10. package/dist/binary.js +73 -0
  11. package/dist/binary.js.map +1 -0
  12. package/dist/canvas.d.ts +21 -0
  13. package/dist/canvas.d.ts.map +1 -0
  14. package/dist/canvas.js +14 -0
  15. package/dist/canvas.js.map +1 -0
  16. package/dist/errors.d.ts +33 -0
  17. package/dist/errors.d.ts.map +1 -0
  18. package/dist/errors.js +23 -0
  19. package/dist/errors.js.map +1 -0
  20. package/dist/events.d.ts +140 -0
  21. package/dist/events.d.ts.map +1 -0
  22. package/dist/events.js +29 -0
  23. package/dist/events.js.map +1 -0
  24. package/dist/index.d.ts +15 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +13 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/process.d.ts +78 -0
  29. package/dist/process.d.ts.map +1 -0
  30. package/dist/process.js +248 -0
  31. package/dist/process.js.map +1 -0
  32. package/dist/session.d.ts +90 -0
  33. package/dist/session.d.ts.map +1 -0
  34. package/dist/session.js +186 -0
  35. package/dist/session.js.map +1 -0
  36. package/dist/slrw.d.ts +40 -0
  37. package/dist/slrw.d.ts.map +1 -0
  38. package/dist/slrw.js +86 -0
  39. package/dist/slrw.js.map +1 -0
  40. package/dist/stream.d.ts +109 -0
  41. package/dist/stream.d.ts.map +1 -0
  42. package/dist/stream.js +230 -0
  43. package/dist/stream.js.map +1 -0
  44. package/package.json +52 -4
  45. package/src/api.ts +501 -0
  46. package/src/binary.ts +92 -0
  47. package/src/canvas.ts +30 -0
  48. package/src/errors.ts +75 -0
  49. package/src/events.ts +195 -0
  50. package/src/index.ts +50 -0
  51. package/src/process.ts +283 -0
  52. package/src/session.ts +254 -0
  53. package/src/slrw.ts +99 -0
  54. package/src/stream.ts +297 -0
package/src/api.ts ADDED
@@ -0,0 +1,501 @@
1
+ /**
2
+ * The functions: discover, pair, unpair, play, testPattern, preview,
3
+ * share, stream, version.
4
+ */
5
+
6
+ import { execFile } from "node:child_process";
7
+
8
+ import { resolveBinary, type BinaryOptions } from "./binary.ts";
9
+ import { TvpipeError } from "./errors.ts";
10
+ import type { DevicesEvent, RawDevice, StartedEvent, TvpipeEvent } from "./events.ts";
11
+ import { TvpipeProcess, type ProcessOptions } from "./process.ts";
12
+ import { Session, type SessionOptions } from "./session.ts";
13
+ import { StreamSession, type AudioSpec, type VideoSpec } from "./stream.ts";
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Devices
17
+
18
+ /** A receiver on the network. */
19
+ export interface Device {
20
+ name: string;
21
+ /** e.g. `AppleTV14,1`, `Chromecast`. */
22
+ model: string | undefined;
23
+ addresses: string[];
24
+ protocols: ("airplay" | "cast")[];
25
+ /** Whether it can show video (Cast video or AirPlay mirroring). */
26
+ video: boolean;
27
+ /** AirPlay: whether tvpipe has a pairing for it (`undefined`: not AirPlay). */
28
+ paired: boolean | undefined;
29
+ /** AirPlay: whether it asks for a PIN (pair it first). */
30
+ pin: boolean | undefined;
31
+ /** What `discover --json` says, camelCased. */
32
+ airplay: Record<string, unknown> | undefined;
33
+ raop: Record<string, unknown> | undefined;
34
+ cast: Record<string, unknown> | undefined;
35
+ }
36
+
37
+ export interface DiscoverOptions extends ProcessOptions {
38
+ /** How long to browse (ms, default 3000). */
39
+ timeout?: number | undefined;
40
+ /** Also browse from these local IPv4 addresses. */
41
+ interfaces?: string[] | undefined;
42
+ signal?: AbortSignal | undefined;
43
+ }
44
+
45
+ function toDevice(d: RawDevice): Device {
46
+ const ap = d.airplay ?? d.raop;
47
+ const protocols: Device["protocols"] = [];
48
+ if (ap) protocols.push("airplay");
49
+ if (d.cast) protocols.push("cast");
50
+ const bool = (o: Record<string, unknown> | undefined, k: string) =>
51
+ typeof o?.[k] === "boolean" ? (o[k] as boolean) : undefined;
52
+ return {
53
+ name: d.name,
54
+ model: d.model,
55
+ addresses: d.addresses ?? [],
56
+ protocols,
57
+ video: bool(d.cast, "video") === true || bool(d.airplay, "mirroring") === true,
58
+ paired: ap ? (bool(d.airplay, "paired") ?? bool(d.raop, "paired") ?? false) : undefined,
59
+ pin: ap ? (bool(d.airplay, "pin") ?? bool(d.raop, "pin")) : undefined,
60
+ airplay: d.airplay,
61
+ raop: d.raop,
62
+ cast: d.cast,
63
+ };
64
+ }
65
+
66
+ /** Receivers on the local network (AirPlay and Cast, merged per device). */
67
+ export async function discover(options: DiscoverOptions = {}): Promise<Device[]> {
68
+ const args = ["discover", "--timeout", String((options.timeout ?? 3000) / 1000)];
69
+ for (const i of options.interfaces ?? []) args.push("--interface", i);
70
+ const proc = new TvpipeProcess(args, options);
71
+ let found: DevicesEvent | undefined;
72
+ proc.on("event", (ev) => {
73
+ if (ev.type === "devices") found = ev;
74
+ });
75
+ const abort = () => proc.stop(1000);
76
+ options.signal?.addEventListener("abort", abort, { once: true });
77
+ try {
78
+ const exit = await proc.exited;
79
+ if (options.signal?.aborted) throw abortError(options.signal);
80
+ if (exit.code !== 0 || !found) throw proc.error("discovery failed");
81
+ return found.devices.map(toDevice);
82
+ } finally {
83
+ options.signal?.removeEventListener("abort", abort);
84
+ }
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // Pairing
89
+
90
+ /** What `onPin` gets: the receiver that shows the PIN. */
91
+ export interface PinRequest {
92
+ name: string;
93
+ address: string;
94
+ }
95
+
96
+ /** Asked for the PIN the TV shows; return it (or throw to cancel). */
97
+ export type PinCallback = (request: PinRequest) => string | Promise<string>;
98
+
99
+ export interface PairOptions extends ProcessOptions {
100
+ /** Asked for the PIN the TV shows. */
101
+ onPin?: PinCallback | undefined;
102
+ /** A receiver with a fixed PIN (no PIN on screen). */
103
+ pin?: string | undefined;
104
+ signal?: AbortSignal | undefined;
105
+ }
106
+
107
+ export interface PairResult {
108
+ name: string;
109
+ model: string | undefined;
110
+ /** The credentials file. */
111
+ file: string;
112
+ }
113
+
114
+ /**
115
+ * Pairs with an AirPlay receiver (Apple TV): the TV shows a PIN, `onPin`
116
+ * returns it. The pairing is stored in tvpipe's config directory (shared
117
+ * with the CLI; see `configDir`).
118
+ */
119
+ export async function pair(target: string | Device, options: PairOptions = {}): Promise<PairResult> {
120
+ const name = typeof target === "string" ? target : target.name;
121
+ if (options.signal?.aborted) throw abortError(options.signal);
122
+ const args = ["pair", name];
123
+ if (options.pin !== undefined) args.push("--pin", options.pin);
124
+ const proc = new TvpipeProcess(args, options);
125
+ let paired: PairResult | undefined;
126
+ let cancelled: unknown;
127
+ proc.on("event", (ev) => {
128
+ if (ev.type === "paired") paired = { name: ev.name, model: ev.model, file: ev.file };
129
+ if (ev.type === "pin-required") {
130
+ const onPin = options.onPin;
131
+ if (!onPin) {
132
+ cancelled = new TvpipeError("pin-missing", `${ev.name} shows a PIN: pass onPin to pair()`, { device: ev.name });
133
+ proc.endInput();
134
+ return;
135
+ }
136
+ Promise.resolve()
137
+ .then(() => onPin({ name: ev.name, address: ev.address }))
138
+ .then(
139
+ (pin) => {
140
+ proc.command({ type: "pin", pin: String(pin).trim() });
141
+ },
142
+ (err: unknown) => {
143
+ cancelled = err;
144
+ proc.endInput();
145
+ },
146
+ );
147
+ }
148
+ });
149
+ const abort = () => {
150
+ cancelled = abortError(options.signal!);
151
+ void proc.stop(1000);
152
+ };
153
+ options.signal?.addEventListener("abort", abort, { once: true });
154
+ try {
155
+ const exit = await proc.exited;
156
+ if (cancelled) throw cancelled;
157
+ if (exit.code !== 0 || !paired) throw proc.error("pairing failed");
158
+ return paired;
159
+ } finally {
160
+ options.signal?.removeEventListener("abort", abort);
161
+ proc.endInput();
162
+ }
163
+ }
164
+
165
+ /** Forgets the pairing with a receiver. Resolves with the names forgotten. */
166
+ export async function unpair(target: string | Device, options: ProcessOptions = {}): Promise<string[]> {
167
+ const proc = new TvpipeProcess(["unpair", typeof target === "string" ? target : target.name], options);
168
+ const names: string[] = [];
169
+ proc.on("event", (ev) => {
170
+ if (ev.type === "unpaired") names.push(ev.name);
171
+ });
172
+ const exit = await proc.exited;
173
+ if (exit.code !== 0) throw proc.error("unpair failed");
174
+ return names;
175
+ }
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // Sessions
179
+
180
+ /** A receiver: a name (`"Living Room"`, a unique prefix), `airplay:NAME`, `cast:NAME`, an address, `"browser"`, or a discovered device. */
181
+ export type Target = string | Device;
182
+
183
+ export interface PlayerOptions {
184
+ /** Port on 127.0.0.1 (default 0: any free port; the CLI's stable one is 8765). */
185
+ port?: number | undefined;
186
+ /** Open the page in the default browser. */
187
+ open?: boolean | undefined;
188
+ /** Start streaming once a tab watches. */
189
+ waitForViewer?: boolean | undefined;
190
+ /** A new URL token (old URLs stop working). */
191
+ newToken?: boolean | undefined;
192
+ }
193
+
194
+ export interface CommonOptions extends ProcessOptions, SessionOptions {
195
+ /**
196
+ * Where to stream. Omitted: the only receiver with video on the
197
+ * network (an error lists them when there are several).
198
+ */
199
+ to?: Target | Target[] | undefined;
200
+ /** Playout delay in ms, the same on every receiver (5–2000). */
201
+ latency?: number | undefined;
202
+ /** Output size limit. */
203
+ size?: string | { width: number; height: number } | undefined;
204
+ fps?: number | undefined;
205
+ /** Video bitrate in kbit/s. */
206
+ bitrate?: number | undefined;
207
+ /** `false`: video only. */
208
+ audio?: boolean | undefined;
209
+ /** Seconds a receiver that dropped out is reconnected (default 120, 0: off). */
210
+ reconnect?: number | undefined;
211
+ /** The `browser` receiver's page. */
212
+ player?: PlayerOptions | undefined;
213
+ /** Asked for an AirPlay PIN when a receiver needs pairing; the session then starts again. */
214
+ onPin?: PinCallback | undefined;
215
+ /** How long to look for a receiver when `to` is omitted (ms, default 3000). */
216
+ discoverTimeout?: number | undefined;
217
+ }
218
+
219
+ export type Encoder = "auto" | "builtin" | "x264" | "videotoolbox" | "nvenc" | "qsv" | "vaapi" | "mf";
220
+
221
+ export interface PlayOptions extends CommonOptions {
222
+ loop?: boolean | undefined;
223
+ /** Pace the input in real time (default: files yes, live sources no). */
224
+ realtime?: boolean | undefined;
225
+ encoder?: Encoder | undefined;
226
+ /** Path to ffmpeg (default: `$TVPIPE_FFMPEG`, then `PATH`). */
227
+ ffmpeg?: string | undefined;
228
+ }
229
+
230
+ /** A file path, a URL, or ffmpeg input arguments (capture devices). */
231
+ export type Input = string | URL | { ffmpeg: string[] };
232
+
233
+ function targetName(t: Target): string {
234
+ return typeof t === "string" ? t : t.name;
235
+ }
236
+
237
+ /** `to` resolved: the only video receiver when none was given. */
238
+ async function targets(options: CommonOptions): Promise<string[]> {
239
+ if (options.to !== undefined) {
240
+ const list = (Array.isArray(options.to) ? options.to : [options.to]).map(targetName);
241
+ if (list.length === 0) throw new TvpipeError("invalid-argument", "`to` is empty");
242
+ return list;
243
+ }
244
+ const devices = (await discover({ ...options, timeout: options.discoverTimeout ?? 3000 })).filter((d) => d.video);
245
+ if (devices.length === 1) return [devices[0]!.name];
246
+ if (devices.length === 0) {
247
+ throw new TvpipeError(
248
+ "no-receivers",
249
+ "no AirPlay or Cast receiver with video found on the network; pass `to` (a name, an address, or \"browser\" for a browser tab)",
250
+ );
251
+ }
252
+ const names = devices.map((d) => d.name);
253
+ throw new TvpipeError(
254
+ "ambiguous-receiver",
255
+ `found ${devices.length} receivers, pass \`to\` to pick one or more: ${names.map((n) => JSON.stringify(n)).join(", ")}`,
256
+ { details: { devices } },
257
+ );
258
+ }
259
+
260
+ function commonArgs(to: string[], o: CommonOptions): string[] {
261
+ const args: string[] = [];
262
+ for (const t of to) args.push("--to", t);
263
+ if (o.latency !== undefined) args.push("--latency", String(Math.round(o.latency)));
264
+ if (o.size !== undefined) args.push("--size", typeof o.size === "string" ? o.size : `${o.size.width}x${o.size.height}`);
265
+ if (o.fps !== undefined) args.push("--fps", String(o.fps));
266
+ if (o.bitrate !== undefined) args.push("--bitrate", String(Math.round(o.bitrate)));
267
+ if (o.audio === false) args.push("--no-audio");
268
+ if (o.reconnect !== undefined) args.push("--reconnect", String(o.reconnect));
269
+ if (to.some((t) => t.toLowerCase() === "browser")) {
270
+ const p = o.player ?? {};
271
+ args.push("--port", String(p.port ?? 0));
272
+ if (p.open) args.push("--open");
273
+ if (p.waitForViewer) args.push("--wait-for-viewer");
274
+ if (p.newToken) args.push("--new-token");
275
+ } else if (o.player) {
276
+ throw new TvpipeError("invalid-argument", "`player` options need a \"browser\" receiver in `to`");
277
+ }
278
+ return args;
279
+ }
280
+
281
+ function playArgs(o: PlayOptions): string[] {
282
+ const args: string[] = [];
283
+ if (o.loop) args.push("--loop");
284
+ if (o.realtime === true) args.push("--realtime");
285
+ if (o.realtime === false) args.push("--no-realtime");
286
+ if (o.encoder) args.push("--encoder", o.encoder);
287
+ if (o.ffmpeg) args.push("--ffmpeg", o.ffmpeg);
288
+ return args;
289
+ }
290
+
291
+ function abortError(signal: AbortSignal): TvpipeError {
292
+ return new TvpipeError("aborted", "aborted", { cause: signal.reason });
293
+ }
294
+
295
+ type Ready = (ev: TvpipeEvent) => boolean;
296
+
297
+ /**
298
+ * Starts a session and resolves once `ready` saw its event; with `onPin`,
299
+ * pairs a receiver that needs it and starts once more.
300
+ */
301
+ async function start<S extends Session>(
302
+ options: CommonOptions,
303
+ build: (to: string[]) => string[],
304
+ make: (proc: TvpipeProcess) => S,
305
+ ready: Ready,
306
+ ): Promise<S> {
307
+ if (options.signal?.aborted) throw abortError(options.signal);
308
+ const to = await targets(options);
309
+ const paired = new Set<string>();
310
+ for (;;) {
311
+ try {
312
+ return await startOnce(options, build(to), make, ready);
313
+ } catch (err) {
314
+ const device = err instanceof TvpipeError && err.code === "pairing-required" ? err.device : undefined;
315
+ if (!device || !options.onPin || paired.has(device)) throw err;
316
+ paired.add(device);
317
+ await pair(device, { ...options, onPin: options.onPin });
318
+ }
319
+ }
320
+ }
321
+
322
+ async function startOnce<S extends Session>(
323
+ options: CommonOptions,
324
+ args: string[],
325
+ make: (proc: TvpipeProcess) => S,
326
+ ready: Ready,
327
+ ): Promise<S> {
328
+ const proc = new TvpipeProcess(args, options);
329
+ const session = make(proc);
330
+ return new Promise<S>((resolve, reject) => {
331
+ let settled = false;
332
+ const settle = (f: () => void) => {
333
+ if (!settled) {
334
+ settled = true;
335
+ session.off("event", onEvent);
336
+ f();
337
+ }
338
+ };
339
+ const onEvent = (ev: TvpipeEvent) => {
340
+ if (ready(ev)) settle(() => resolve(session));
341
+ };
342
+ session.on("event", onEvent);
343
+ session.done.then(
344
+ () =>
345
+ settle(() =>
346
+ reject(
347
+ options.signal?.aborted
348
+ ? abortError(options.signal)
349
+ : new TvpipeError("closed", "the session ended before it started", { log: session.log }),
350
+ ),
351
+ ),
352
+ (err: unknown) => settle(() => reject(options.signal?.aborted ? abortError(options.signal) : err)),
353
+ );
354
+ });
355
+ }
356
+
357
+ const isStarted: Ready = (ev) => ev.type === "started";
358
+
359
+ /**
360
+ * Plays a file, URL or capture device. Resolves once streaming started;
361
+ * the session ends at the end of the input (`done`) or with `stop()`.
362
+ */
363
+ export function play(input: Input, options: PlayOptions = {}): Promise<Session> {
364
+ const inputArgs =
365
+ typeof input === "object" && !(input instanceof URL) ? ["--", ...input.ffmpeg] : [String(input)];
366
+ return start(
367
+ options,
368
+ (to) => ["play", ...commonArgs(to, options), ...playArgs(options), ...inputArgs],
369
+ (proc) => new Session(proc, options),
370
+ isStarted,
371
+ );
372
+ }
373
+
374
+ /** The built-in test pattern (a clock, a frame counter, a beep and flash every second); no ffmpeg needed. */
375
+ export function testPattern(options: PlayOptions = {}): Promise<Session> {
376
+ return start(
377
+ options,
378
+ (to) => ["test-pattern", ...commonArgs(to, options), ...playArgs(options)],
379
+ (proc) => new Session(proc, options),
380
+ isStarted,
381
+ );
382
+ }
383
+
384
+ /**
385
+ * Plays to a browser tab on this computer (`to: "browser"` plus whatever
386
+ * `to` adds); `session.playerUrl` is the page. Without input: the test pattern.
387
+ */
388
+ export function preview(input?: Input, options: PlayOptions = {}): Promise<Session> {
389
+ const extra = options.to === undefined ? [] : Array.isArray(options.to) ? options.to : [options.to];
390
+ const opts = { ...options, to: ["browser", ...extra.filter((t) => targetName(t).toLowerCase() !== "browser")] };
391
+ return input === undefined ? testPattern(opts) : play(input, opts);
392
+ }
393
+
394
+ export interface ShareOptions extends CommonOptions {
395
+ /** Open the share page (without URL) or the `browser` player page. */
396
+ open?: boolean | undefined;
397
+ /** With URL: show the browser window (e.g. to log in). */
398
+ visible?: boolean | undefined;
399
+ /** With URL: keep the browser profile (logins) in this directory. */
400
+ profile?: string | undefined;
401
+ /** With URL: reload the page every this many minutes. */
402
+ reload?: number | undefined;
403
+ /** With URL: the Chromium-based browser to run (default: `$TVPIPE_BROWSER`, Chrome, Edge, …). */
404
+ browser?: string | undefined;
405
+ }
406
+
407
+ /**
408
+ * Shares a web page (rendered by a headless Chromium of tvpipe's own) or,
409
+ * without URL, whatever a person picks on the share page
410
+ * (`session.shareUrl`; resolves once that page listens).
411
+ */
412
+ export function share(url: string | URL, options: ShareOptions): Promise<Session>;
413
+ export function share(options: ShareOptions): Promise<Session>;
414
+ export function share(a: string | URL | ShareOptions, b?: ShareOptions): Promise<Session> {
415
+ const url = typeof a === "string" || a instanceof URL ? String(a) : undefined;
416
+ const options = (url === undefined ? a : b) as ShareOptions;
417
+ const build = (to: string[]) => {
418
+ const args = ["share", ...commonArgs(to, options)];
419
+ if (options.open) args.push("--open");
420
+ if (url !== undefined) {
421
+ if (options.visible) args.push("--visible");
422
+ if (options.profile) args.push("--profile", options.profile);
423
+ if (options.reload !== undefined) args.push("--reload", String(options.reload));
424
+ if (options.browser) args.push("--browser", options.browser);
425
+ args.push(url);
426
+ }
427
+ return args;
428
+ };
429
+ return start(
430
+ options,
431
+ build,
432
+ (proc) => new Session(proc, options),
433
+ url === undefined ? (ev) => ev.type === "share-page" : isStarted,
434
+ );
435
+ }
436
+
437
+ export interface StreamOptions extends Omit<CommonOptions, "audio"> {
438
+ video: VideoSpec;
439
+ audio?: AudioSpec | undefined;
440
+ /**
441
+ * Raw frames: the encoder (default `builtin`: no ffmpeg, keyframes on
442
+ * demand; `auto` and the others use ffmpeg).
443
+ */
444
+ encoder?: Encoder | undefined;
445
+ ffmpeg?: string | undefined;
446
+ /** Raw frames: drop while this many frames wait in the pipe (default 2). */
447
+ maxQueuedFrames?: number | undefined;
448
+ }
449
+
450
+ /**
451
+ * Streams frames the program makes: raw pixels (`writeVideo`, a canvas),
452
+ * PCM (`writeAudio`), or H.264 (`writeH264`, WebCodecs `writeChunk`).
453
+ * Resolves once the receivers are connected; write from then on.
454
+ */
455
+ export async function stream(options: StreamOptions): Promise<StreamSession> {
456
+ const v = options.video;
457
+ if (!(v.width > 0 && v.height > 0 && v.width % 2 === 0 && v.height % 2 === 0)) {
458
+ throw new TvpipeError("invalid-argument", "video width and height must be positive and even");
459
+ }
460
+ if (!(v.fps > 0)) throw new TvpipeError("invalid-argument", "video fps must be positive");
461
+ const encoded = "codec" in v;
462
+ const pixfmt = encoded ? "h264" : (v.format ?? "rgba");
463
+ // `audio` is a spec here, not CommonOptions' boolean.
464
+ const common: CommonOptions = { ...options, audio: undefined };
465
+ const build = (to: string[]) => {
466
+ const args = ["play", ...commonArgs(to, common), "--raw-video", `${v.width}x${v.height}@${v.fps}:${pixfmt}`];
467
+ const a = options.audio;
468
+ if (a) args.push("--raw-audio", `${a.sampleRate}:${a.channels}:s16le`);
469
+ if (!encoded) args.push("--encoder", options.encoder ?? "builtin");
470
+ if (options.ffmpeg) args.push("--ffmpeg", options.ffmpeg);
471
+ args.push("-");
472
+ return args;
473
+ };
474
+ return start(
475
+ common,
476
+ build,
477
+ (proc) =>
478
+ new StreamSession(proc, {
479
+ ...options,
480
+ video: v,
481
+ audio: options.audio,
482
+ latencyMs: options.latency,
483
+ }),
484
+ (ev) => ev.type === "connected",
485
+ );
486
+ }
487
+
488
+ // ---------------------------------------------------------------------------
489
+
490
+ /** The binary's version (`tvpipe --version`). */
491
+ export function version(options: BinaryOptions = {}): Promise<string> {
492
+ const binary = resolveBinary(options);
493
+ return new Promise((resolve, reject) => {
494
+ execFile(binary, ["--version"], { windowsHide: true }, (err, stdout) => {
495
+ if (err) reject(new TvpipeError("binary-missing", `cannot run ${binary}: ${err.message}`, { cause: err }));
496
+ else resolve(stdout.trim().replace(/^tvpipe\s+/, ""));
497
+ });
498
+ });
499
+ }
500
+
501
+ export type { StartedEvent };
package/src/binary.ts ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Finds the tvpipe binary: the `binary` option, `$TVPIPE_BINARY`, or the
3
+ * platform package (`@tvpipe/<os>-<cpu>`) npm installed next to this one.
4
+ */
5
+
6
+ import { accessSync, chmodSync, constants, existsSync } from "node:fs";
7
+ import { createRequire } from "node:module";
8
+ import { dirname, join } from "node:path";
9
+
10
+ import { TvpipeError } from "./errors.ts";
11
+
12
+ /** The platforms with a published binary: `${process.platform}-${process.arch}`. */
13
+ export const PLATFORMS = [
14
+ "darwin-arm64",
15
+ "darwin-x64",
16
+ "linux-arm64",
17
+ "linux-x64",
18
+ "win32-arm64",
19
+ "win32-x64",
20
+ ] as const;
21
+
22
+ export type Platform = (typeof PLATFORMS)[number];
23
+
24
+ /** The npm package with the binary for a platform. */
25
+ export function platformPackage(platform: string = `${process.platform}-${process.arch}`): string {
26
+ return `@tvpipe/${platform}`;
27
+ }
28
+
29
+ export interface BinaryOptions {
30
+ /** Path of a tvpipe binary to use instead of the installed one. */
31
+ binary?: string | undefined;
32
+ }
33
+
34
+ /** The environment variable that names a binary to use. */
35
+ export const BINARY_ENV = "TVPIPE_BINARY";
36
+
37
+ /**
38
+ * The tvpipe binary to run. Throws a {@link TvpipeError} (`binary-missing`
39
+ * or `unsupported-platform`) that says how to fix it.
40
+ */
41
+ export function resolveBinary(options: BinaryOptions = {}): string {
42
+ const explicit = options.binary ?? process.env[BINARY_ENV];
43
+ if (explicit) {
44
+ if (!existsSync(explicit)) {
45
+ throw new TvpipeError(
46
+ "binary-missing",
47
+ `tvpipe binary not found at ${explicit} (from ${options.binary ? "the binary option" : `$${BINARY_ENV}`})`,
48
+ );
49
+ }
50
+ return explicit;
51
+ }
52
+ const platform = `${process.platform}-${process.arch}`;
53
+ if (!(PLATFORMS as readonly string[]).includes(platform)) {
54
+ throw new TvpipeError(
55
+ "unsupported-platform",
56
+ `tvpipe has no binary for ${platform} (supported: ${PLATFORMS.join(", ")}); ` +
57
+ `build it from https://github.com/mitsuhiko/tvpipe and set $${BINARY_ENV} to its path`,
58
+ );
59
+ }
60
+ const pkg = platformPackage(platform);
61
+ const exe = process.platform === "win32" ? "tvpipe.exe" : "tvpipe";
62
+ let path: string;
63
+ try {
64
+ const require = createRequire(import.meta.url);
65
+ path = join(dirname(require.resolve(`${pkg}/package.json`)), "bin", exe);
66
+ } catch (cause) {
67
+ throw new TvpipeError(
68
+ "binary-missing",
69
+ `the tvpipe binary for ${platform} is not installed: npm did not install the optional ` +
70
+ `dependency ${pkg} (installed with --omit=optional or --no-optional, or the lockfile ` +
71
+ `was made on another platform?). Reinstall @tvpipe/sdk with optional dependencies, ` +
72
+ `install ${pkg} explicitly, or set $${BINARY_ENV} to a tvpipe binary`,
73
+ { cause },
74
+ );
75
+ }
76
+ if (!existsSync(path)) {
77
+ throw new TvpipeError("binary-missing", `${pkg} is installed but has no ${join("bin", exe)}`);
78
+ }
79
+ if (process.platform !== "win32") {
80
+ try {
81
+ accessSync(path, constants.X_OK);
82
+ } catch {
83
+ // Some package managers drop the executable bit.
84
+ try {
85
+ chmodSync(path, 0o755);
86
+ } catch {
87
+ // Spawning reports the problem.
88
+ }
89
+ }
90
+ }
91
+ return path;
92
+ }
package/src/canvas.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Canvases, duck-typed: anything with `width`, `height` and a 2D context
3
+ * with `getImageData` (node-canvas, skia-canvas, @napi-rs/canvas,
4
+ * OffscreenCanvas). No dependency on any of them.
5
+ */
6
+
7
+ export interface ImageDataLike {
8
+ readonly width: number;
9
+ readonly height: number;
10
+ readonly data: Uint8ClampedArray | Uint8Array;
11
+ }
12
+
13
+ export interface Context2DLike {
14
+ getImageData(x: number, y: number, width: number, height: number): ImageDataLike;
15
+ }
16
+
17
+ export interface CanvasLike {
18
+ readonly width: number;
19
+ readonly height: number;
20
+ getContext(type: "2d"): Context2DLike | null;
21
+ }
22
+
23
+ /** The canvas's RGBA pixels (a fresh copy, as `getImageData` makes one). */
24
+ export function canvasPixels(canvas: CanvasLike): ImageDataLike {
25
+ const ctx = canvas.getContext("2d");
26
+ if (!ctx || typeof ctx.getImageData !== "function") {
27
+ throw new TypeError("the canvas has no 2D context with getImageData");
28
+ }
29
+ return ctx.getImageData(0, 0, canvas.width, canvas.height);
30
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Errors of the SDK. Every failure is a {@link TvpipeError} with a human
3
+ * message and a stable `code` to branch on.
4
+ */
5
+
6
+ /**
7
+ * Stable error codes. The binary's codes (docs/machine.md) plus the SDK's
8
+ * own; unknown failures use the binary's error kind (`io`, `auth`, …).
9
+ */
10
+ export type TvpipeErrorCode =
11
+ // The binary's (docs/machine.md).
12
+ | "pairing-required"
13
+ | "no-receiver"
14
+ | "input-not-found"
15
+ | "ffmpeg-missing"
16
+ | "pin-missing"
17
+ | "bad-input"
18
+ // The SDK's.
19
+ | "binary-missing"
20
+ | "unsupported-platform"
21
+ | "protocol-mismatch"
22
+ | "no-receivers"
23
+ | "ambiguous-receiver"
24
+ | "pairing-failed"
25
+ | "aborted"
26
+ | "exited"
27
+ | "invalid-argument"
28
+ | "closed"
29
+ // The binary's error kinds, when there is no more specific code.
30
+ | "io"
31
+ | "malformed"
32
+ | "protocol"
33
+ | "crypto"
34
+ | "auth"
35
+ | "unsupported"
36
+ | "timeout"
37
+ | "not-found"
38
+ | "process"
39
+ | "usage"
40
+ | "unimplemented"
41
+ | (string & {});
42
+
43
+ export interface TvpipeErrorOptions {
44
+ /** The binary's error kind (`auth`, `not-found`, …), when it reported one. */
45
+ kind?: string;
46
+ /** The receiver the error is about. */
47
+ device?: string;
48
+ /** The process's exit code, when it exited. */
49
+ exitCode?: number | null;
50
+ /** The last log lines and stderr output of the process. */
51
+ log?: string[];
52
+ cause?: unknown;
53
+ /** Extra data, e.g. the receivers found for `ambiguous-receiver`. */
54
+ details?: Record<string, unknown>;
55
+ }
56
+
57
+ export class TvpipeError extends Error {
58
+ override name = "TvpipeError";
59
+ readonly code: TvpipeErrorCode;
60
+ readonly kind: string | undefined;
61
+ readonly device: string | undefined;
62
+ readonly exitCode: number | null | undefined;
63
+ readonly log: string[];
64
+ readonly details: Record<string, unknown>;
65
+
66
+ constructor(code: TvpipeErrorCode, message: string, options: TvpipeErrorOptions = {}) {
67
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
68
+ this.code = code;
69
+ this.kind = options.kind;
70
+ this.device = options.device;
71
+ this.exitCode = options.exitCode;
72
+ this.log = options.log ?? [];
73
+ this.details = options.details ?? {};
74
+ }
75
+ }