@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/events.ts ADDED
@@ -0,0 +1,195 @@
1
+ /**
2
+ * The machine interface's events (docs/machine.md), with camelCase fields.
3
+ */
4
+
5
+ export type ReceiverProtocol = "cast" | "airplay" | "browser";
6
+
7
+ /**
8
+ * - `connected`: ready to play.
9
+ * - `failed`: could not resolve, connect or start, or failed mid-stream.
10
+ * - `lost`: the connection broke; reconnecting (`reconnect` seconds).
11
+ * - `reconnected`: back after `lost`.
12
+ * - `gave-up`: reconnecting failed.
13
+ * - `ended`: the receiver's user ended the session.
14
+ * - `stopped`: stopped by tvpipe (the session ended).
15
+ */
16
+ export type ReceiverState =
17
+ | "connected"
18
+ | "failed"
19
+ | "lost"
20
+ | "reconnected"
21
+ | "gave-up"
22
+ | "ended"
23
+ | "stopped";
24
+
25
+ export interface HelloEvent {
26
+ type: "hello";
27
+ protocol: number;
28
+ version: string;
29
+ command: string;
30
+ }
31
+
32
+ export interface LogEvent {
33
+ type: "log";
34
+ level: "error" | "warn" | "info" | "debug" | "trace";
35
+ module: string;
36
+ message: string;
37
+ }
38
+
39
+ export interface ReceiverEvent {
40
+ type: "receiver";
41
+ name: string;
42
+ /** Known on `connected` and on `failed` while connecting. */
43
+ protocol?: ReceiverProtocol;
44
+ state: ReceiverState;
45
+ error?: string;
46
+ /** A stable code, e.g. `pairing-required`. */
47
+ code?: string;
48
+ }
49
+
50
+ export interface PlayerEvent {
51
+ type: "player";
52
+ name: string;
53
+ /** The page of a `browser` receiver: open it in a browser to watch. */
54
+ url: string;
55
+ }
56
+
57
+ export interface ViewerEvent {
58
+ type: "viewer";
59
+ name: string;
60
+ tab: number;
61
+ state: "connected" | "disconnected";
62
+ }
63
+
64
+ export interface SharePageEvent {
65
+ type: "share-page";
66
+ url: string;
67
+ }
68
+
69
+ export interface ConnectedEvent {
70
+ type: "connected";
71
+ receivers: string[];
72
+ }
73
+
74
+ export interface StartedEvent {
75
+ type: "started";
76
+ route: "passthrough" | "ffmpeg" | "builtin" | "encoded" | "browser";
77
+ video: { codec: string; width: number; height: number; fps: number };
78
+ audio: { codec: string; sampleRate: number; channels: number }[];
79
+ latencyMs: number;
80
+ }
81
+
82
+ export interface KeyframeEvent {
83
+ type: "keyframe";
84
+ }
85
+
86
+ export interface ReceiverStats {
87
+ name: string;
88
+ pushed: number;
89
+ dropped: number;
90
+ droppedFull: number;
91
+ droppedWaiting: number;
92
+ }
93
+
94
+ export interface StatsEvent {
95
+ type: "stats";
96
+ elapsedMs: number;
97
+ videoFrames: number;
98
+ audioFrames: number;
99
+ receivers: ReceiverStats[];
100
+ }
101
+
102
+ export interface PinRequiredEvent {
103
+ type: "pin-required";
104
+ name: string;
105
+ address: string;
106
+ }
107
+
108
+ export interface PairedEvent {
109
+ type: "paired";
110
+ name: string;
111
+ model?: string;
112
+ file: string;
113
+ }
114
+
115
+ export interface UnpairedEvent {
116
+ type: "unpaired";
117
+ name: string;
118
+ id: string;
119
+ }
120
+
121
+ export interface DevicesEvent {
122
+ type: "devices";
123
+ devices: RawDevice[];
124
+ }
125
+
126
+ export interface ReceiverEnd extends ReceiverStats {
127
+ end: "stopped" | "ended" | "failed";
128
+ error?: string;
129
+ }
130
+
131
+ export interface EndEvent {
132
+ type: "end";
133
+ reason: "eof" | "stopped" | "receivers-gone" | "error" | "done";
134
+ receivers?: ReceiverEnd[];
135
+ }
136
+
137
+ export interface ErrorEvent {
138
+ type: "error";
139
+ kind: string;
140
+ code?: string;
141
+ message: string;
142
+ device?: string;
143
+ }
144
+
145
+ /** A device as `discover` reports it (camelCased). */
146
+ export interface RawDevice {
147
+ name: string;
148
+ addresses: string[];
149
+ model?: string;
150
+ airplay?: Record<string, unknown>;
151
+ raop?: Record<string, unknown>;
152
+ cast?: Record<string, unknown>;
153
+ }
154
+
155
+ export type TvpipeEvent =
156
+ | HelloEvent
157
+ | LogEvent
158
+ | ReceiverEvent
159
+ | PlayerEvent
160
+ | ViewerEvent
161
+ | SharePageEvent
162
+ | ConnectedEvent
163
+ | StartedEvent
164
+ | KeyframeEvent
165
+ | StatsEvent
166
+ | PinRequiredEvent
167
+ | PairedEvent
168
+ | UnpairedEvent
169
+ | DevicesEvent
170
+ | EndEvent
171
+ | ErrorEvent;
172
+
173
+ /** snake_case keys to camelCase, recursively. */
174
+ export function camelize(value: unknown): unknown {
175
+ if (Array.isArray(value)) return value.map(camelize);
176
+ if (value !== null && typeof value === "object") {
177
+ const out: Record<string, unknown> = {};
178
+ for (const [k, v] of Object.entries(value)) {
179
+ out[k.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase())] = camelize(v);
180
+ }
181
+ return out;
182
+ }
183
+ return value;
184
+ }
185
+
186
+ /** Parses one stdout line; `undefined` for anything that is not an event. */
187
+ export function parseEvent(line: string): TvpipeEvent | undefined {
188
+ if (!line.startsWith("{")) return undefined;
189
+ try {
190
+ const v = camelize(JSON.parse(line)) as { type?: unknown };
191
+ return typeof v.type === "string" ? (v as TvpipeEvent) : undefined;
192
+ } catch {
193
+ return undefined;
194
+ }
195
+ }
package/src/index.ts ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * tvpipe for Node: stream video and audio to AirPlay and Google Cast
3
+ * receivers and browser tabs. See README.md.
4
+ *
5
+ * @module
6
+ */
7
+
8
+ export {
9
+ discover,
10
+ pair,
11
+ unpair,
12
+ play,
13
+ testPattern,
14
+ preview,
15
+ share,
16
+ stream,
17
+ version,
18
+ type Device,
19
+ type DiscoverOptions,
20
+ type PairOptions,
21
+ type PairResult,
22
+ type PinCallback,
23
+ type PinRequest,
24
+ type Target,
25
+ type PlayerOptions,
26
+ type CommonOptions,
27
+ type PlayOptions,
28
+ type ShareOptions,
29
+ type StreamOptions,
30
+ type Encoder,
31
+ type Input,
32
+ } from "./api.ts";
33
+ export { resolveBinary, platformPackage, PLATFORMS, BINARY_ENV, type Platform, type BinaryOptions } from "./binary.ts";
34
+ export type { CanvasLike, Context2DLike, ImageDataLike } from "./canvas.ts";
35
+ export { TvpipeError, type TvpipeErrorCode, type TvpipeErrorOptions } from "./errors.ts";
36
+ export type * from "./events.ts";
37
+ export { PROTOCOL, type ProcessOptions } from "./process.ts";
38
+ export { Session, type EndInfo, type ReceiverInfo, type SessionEvents, type SessionOptions, type StartedInfo } from "./session.ts";
39
+ export {
40
+ StreamSession,
41
+ type AudioSpec,
42
+ type EncodedVideoChunkLike,
43
+ type EncodedVideoChunkMetadataLike,
44
+ type EncodedVideoSpec,
45
+ type PixelFormat,
46
+ type Pts,
47
+ type RawVideoSpec,
48
+ type StreamSessionOptions,
49
+ type VideoSpec,
50
+ } from "./stream.ts";
package/src/process.ts ADDED
@@ -0,0 +1,283 @@
1
+ /**
2
+ * One tvpipe process speaking the machine interface: spawn, events from
3
+ * stdout, records to stdin, and a stop that escalates.
4
+ */
5
+
6
+ import { spawn, type ChildProcess } from "node:child_process";
7
+ import { EventEmitter } from "node:events";
8
+ import { createInterface } from "node:readline";
9
+
10
+ import { resolveBinary } from "./binary.ts";
11
+ import { TvpipeError } from "./errors.ts";
12
+ import { parseEvent, type ErrorEvent, type HelloEvent, type LogEvent, type TvpipeEvent } from "./events.ts";
13
+ import * as slrw from "./slrw.ts";
14
+
15
+ /** The machine-interface version this SDK speaks. */
16
+ export const PROTOCOL = 1;
17
+
18
+ /** How many log lines a process keeps for error messages. */
19
+ const LOG_TAIL = 50;
20
+
21
+ export interface ProcessOptions {
22
+ /** Path of the tvpipe binary (default: `$TVPIPE_BINARY`, then the platform package). */
23
+ binary?: string | undefined;
24
+ /**
25
+ * Where tvpipe keeps AirPlay pairings and the player page's token
26
+ * (`TVPIPE_CONFIG_DIR`; default: the CLI's config directory, so the CLI
27
+ * and the SDK share pairings).
28
+ */
29
+ configDir?: string | undefined;
30
+ /** Extra environment variables for the process. */
31
+ env?: Record<string, string | undefined> | undefined;
32
+ /** Debug logs (`-v`); `"trace"` for protocol traces (`--debug`). */
33
+ verbose?: boolean | "trace" | undefined;
34
+ /**
35
+ * Mirror tvpipe's log to stderr (`true`, or the lowest level: `"info"`
36
+ * by default with `true`), or hand each line to a function. Logs are
37
+ * also `log` events either way.
38
+ */
39
+ logs?: boolean | LogEvent["level"] | ((event: LogEvent) => void) | undefined;
40
+ }
41
+
42
+ export interface Exit {
43
+ code: number | null;
44
+ signal: NodeJS.Signals | null;
45
+ }
46
+
47
+ const LEVELS = ["error", "warn", "info", "debug", "trace"] as const;
48
+
49
+ function logPrinter(logs: ProcessOptions["logs"]): ((e: LogEvent) => void) | undefined {
50
+ if (typeof logs === "function") return logs;
51
+ if (!logs) return undefined;
52
+ const max = LEVELS.indexOf(logs === true ? "info" : logs);
53
+ return (e) => {
54
+ if (LEVELS.indexOf(e.level) <= max) {
55
+ process.stderr.write(`tvpipe ${e.level.toUpperCase().padEnd(5)} ${e.module}: ${e.message}\n`);
56
+ }
57
+ };
58
+ }
59
+
60
+ /**
61
+ * A running tvpipe. Emits `event` (every {@link TvpipeEvent}) and `exit`.
62
+ */
63
+ export class TvpipeProcess extends EventEmitter<{ event: [TvpipeEvent]; exit: [Exit] }> {
64
+ readonly child: ChildProcess;
65
+ readonly exited: Promise<Exit>;
66
+ hello: HelloEvent | undefined;
67
+ /** The last error event, if the command failed. */
68
+ failure: ErrorEvent | undefined;
69
+ /** Whether an `end` event arrived. */
70
+ ended = false;
71
+ #log: string[] = [];
72
+ #stderr: string[] = [];
73
+ #exit: Exit | undefined;
74
+ #spawnError: Error | undefined;
75
+ #inputOpen = true;
76
+
77
+ constructor(args: string[], options: ProcessOptions = {}) {
78
+ super();
79
+ const binary = resolveBinary(options);
80
+ const flags = ["--machine"];
81
+ if (options.verbose === "trace") flags.push("--debug");
82
+ else if (options.verbose) flags.push("-v");
83
+ const env: Record<string, string | undefined> = { ...process.env, ...options.env };
84
+ if (options.configDir) env["TVPIPE_CONFIG_DIR"] = options.configDir;
85
+ this.child = spawn(binary, [...flags, ...args], {
86
+ stdio: ["pipe", "pipe", "pipe"],
87
+ windowsHide: true,
88
+ env,
89
+ });
90
+ const printer = logPrinter(options.logs);
91
+ this.exited = new Promise((resolve) => {
92
+ this.child.once("error", (err) => {
93
+ this.#spawnError = err;
94
+ // `close` does not follow a failed spawn.
95
+ if (this.child.pid === undefined) {
96
+ this.#exit = { code: null, signal: null };
97
+ this.emit("exit", this.#exit);
98
+ resolve(this.#exit);
99
+ }
100
+ });
101
+ // `close`: the process exited and its stdio is drained, so every
102
+ // event was read.
103
+ this.child.once("close", (code, signal) => {
104
+ this.#exit = { code, signal };
105
+ this.emit("exit", this.#exit);
106
+ resolve(this.#exit);
107
+ });
108
+ });
109
+ // A closed pipe (tvpipe exited) is reported through `exit`.
110
+ this.child.stdin?.on("error", () => {
111
+ this.#inputOpen = false;
112
+ });
113
+ this.child.stdin?.write(slrw.MAGIC);
114
+ const lines = createInterface({ input: this.child.stdout!, crlfDelay: Infinity });
115
+ lines.on("line", (line) => {
116
+ const ev = parseEvent(line);
117
+ if (!ev) {
118
+ this.#remember(line);
119
+ return;
120
+ }
121
+ switch (ev.type) {
122
+ case "hello":
123
+ this.hello = ev;
124
+ if (ev.protocol !== PROTOCOL) {
125
+ this.failure = {
126
+ type: "error",
127
+ kind: "usage",
128
+ code: "protocol-mismatch",
129
+ message:
130
+ `tvpipe ${ev.version} speaks machine protocol ${ev.protocol}, this SDK ${PROTOCOL}; ` +
131
+ `install matching versions of @tvpipe/sdk and its binary`,
132
+ };
133
+ this.kill();
134
+ }
135
+ break;
136
+ case "log":
137
+ this.#remember(`${ev.level}: ${ev.message}`);
138
+ printer?.(ev);
139
+ break;
140
+ case "error":
141
+ this.failure ??= ev;
142
+ break;
143
+ case "end":
144
+ this.ended = true;
145
+ break;
146
+ }
147
+ this.emit("event", ev);
148
+ });
149
+ const stderr = createInterface({ input: this.child.stderr!, crlfDelay: Infinity });
150
+ stderr.on("line", (line) => {
151
+ if (line.trim()) {
152
+ this.#remember(line);
153
+ this.#stderr.push(line);
154
+ }
155
+ printer?.({ type: "log", level: "error", module: "stderr", message: line });
156
+ });
157
+ }
158
+
159
+ #remember(line: string): void {
160
+ this.#log.push(line);
161
+ if (this.#log.length > LOG_TAIL) this.#log.shift();
162
+ }
163
+
164
+ /** The last log lines and stderr output. */
165
+ get log(): string[] {
166
+ return [...this.#log];
167
+ }
168
+
169
+ get exit(): Exit | undefined {
170
+ return this.#exit;
171
+ }
172
+
173
+ get running(): boolean {
174
+ return this.#exit === undefined;
175
+ }
176
+
177
+ get pid(): number | undefined {
178
+ return this.child.pid;
179
+ }
180
+
181
+ /** Whether stdin still takes records. */
182
+ get inputOpen(): boolean {
183
+ return this.#inputOpen && this.running && !!this.child.stdin?.writable;
184
+ }
185
+
186
+ /** Bytes written to stdin that the pipe did not take yet. */
187
+ get queuedBytes(): number {
188
+ return this.child.stdin?.writableLength ?? 0;
189
+ }
190
+
191
+ /** Writes to stdin; `false` when the pipe is backed up (or closed). */
192
+ write(data: Uint8Array): boolean {
193
+ if (!this.inputOpen) return false;
194
+ return this.child.stdin!.write(data);
195
+ }
196
+
197
+ /** Sends a command record (`stop`, `pin`). */
198
+ command(cmd: Record<string, unknown>): boolean {
199
+ return this.write(slrw.command(cmd));
200
+ }
201
+
202
+ /** Closes stdin: the end of an SLRW stream, else a stop request. */
203
+ endInput(): void {
204
+ if (this.#inputOpen) {
205
+ this.#inputOpen = false;
206
+ this.child.stdin?.end();
207
+ }
208
+ }
209
+
210
+ /** Resolves once stdin took everything written. */
211
+ drain(): Promise<void> {
212
+ const stdin = this.child.stdin;
213
+ if (!stdin || !this.inputOpen || stdin.writableLength === 0) return Promise.resolve();
214
+ return new Promise((resolve) => {
215
+ const done = () => {
216
+ stdin.off("drain", done);
217
+ this.off("exit", done);
218
+ resolve();
219
+ };
220
+ stdin.on("drain", done);
221
+ this.once("exit", done);
222
+ });
223
+ }
224
+
225
+ kill(signal: NodeJS.Signals = "SIGKILL"): void {
226
+ if (this.running) this.child.kill(signal);
227
+ }
228
+
229
+ /**
230
+ * Stops: the `stop` command, stdin closed; after `timeoutMs` SIGTERM
231
+ * (tvpipe still tears down; on Windows this terminates at once), after
232
+ * 2 s more SIGKILL.
233
+ */
234
+ async stop(timeoutMs = 5000, graceful: "stop" | "end" = "stop"): Promise<Exit> {
235
+ if (!this.running) return this.exited;
236
+ if (graceful === "stop") this.command({ type: "stop" });
237
+ else this.write(slrw.record(slrw.Kind.end, 0, new Uint8Array(0)));
238
+ this.endInput();
239
+ const timer = (ms: number) =>
240
+ new Promise<"timeout">((resolve) => setTimeout(resolve, ms, "timeout").unref());
241
+ if ((await Promise.race([this.exited, timer(timeoutMs)])) !== "timeout") return this.exited;
242
+ this.kill(process.platform === "win32" ? "SIGKILL" : "SIGTERM");
243
+ if ((await Promise.race([this.exited, timer(2000)])) !== "timeout") return this.exited;
244
+ this.kill("SIGKILL");
245
+ return this.exited;
246
+ }
247
+
248
+ /** The error for a process that failed (or exited without saying why). */
249
+ error(fallback = "tvpipe exited unexpectedly"): TvpipeError {
250
+ const exitCode = this.#exit?.code;
251
+ if (this.#spawnError) {
252
+ return new TvpipeError("binary-missing", `cannot run tvpipe: ${this.#spawnError.message}`, {
253
+ cause: this.#spawnError,
254
+ log: this.log,
255
+ });
256
+ }
257
+ const f = this.failure;
258
+ if (f) {
259
+ return new TvpipeError(f.code ?? f.kind, f.message, {
260
+ kind: f.kind,
261
+ device: f.device,
262
+ exitCode,
263
+ log: this.log,
264
+ });
265
+ }
266
+ // The argument parser's errors: `error: ...` on stderr, status 2.
267
+ const parseError = this.#stderr.find((l) => l.startsWith("error:"));
268
+ if (exitCode === 2 && parseError) {
269
+ return new TvpipeError("usage", `tvpipe rejected the arguments: ${parseError.slice(6).trim()}`, {
270
+ kind: "usage",
271
+ exitCode,
272
+ log: this.log,
273
+ });
274
+ }
275
+ const detail = this.#log.filter((l) => !l.startsWith("info:") && !l.startsWith("debug:"));
276
+ const last = detail.at(-1);
277
+ const how = this.#exit?.signal ? `signal ${this.#exit.signal}` : `exit code ${exitCode}`;
278
+ return new TvpipeError("exited", `${fallback} (${how})${last ? `: ${last}` : ""}`, {
279
+ exitCode,
280
+ log: this.log,
281
+ });
282
+ }
283
+ }