@tvpipe/sdk 0.0.0-stage → 0.2.0

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 +231 -2
  3. package/bin/tvpipe.js +29 -0
  4. package/dist/api.d.ts +189 -0
  5. package/dist/api.d.ts.map +1 -0
  6. package/dist/api.js +348 -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 +172 -0
  21. package/dist/events.d.ts.map +1 -0
  22. package/dist/events.js +55 -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 +93 -0
  33. package/dist/session.d.ts.map +1 -0
  34. package/dist/session.js +192 -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 +540 -0
  46. package/src/binary.ts +92 -0
  47. package/src/canvas.ts +30 -0
  48. package/src/errors.ts +77 -0
  49. package/src/events.ts +258 -0
  50. package/src/index.ts +50 -0
  51. package/src/process.ts +283 -0
  52. package/src/session.ts +262 -0
  53. package/src/slrw.ts +99 -0
  54. package/src/stream.ts +297 -0
package/src/session.ts ADDED
@@ -0,0 +1,262 @@
1
+ /**
2
+ * A running session: events, state, stop.
3
+ */
4
+
5
+ import { EventEmitter } from "node:events";
6
+
7
+ import { TvpipeError } from "./errors.ts";
8
+ import type {
9
+ ConnectedEvent,
10
+ EndEvent,
11
+ KeyframeEvent,
12
+ LogEvent,
13
+ PlayerEvent,
14
+ ReceiverEvent,
15
+ ReceiverProtocol,
16
+ ReceiverState,
17
+ SharePageEvent,
18
+ TunnelEvent,
19
+ StartedEvent,
20
+ StatsEvent,
21
+ TvpipeEvent,
22
+ ViewerEvent,
23
+ } from "./events.ts";
24
+ import type { Exit, TvpipeProcess } from "./process.ts";
25
+
26
+ /** How a session ended. */
27
+ export interface EndInfo {
28
+ reason: EndEvent["reason"];
29
+ /** Per receiver: how it ended and what it got. */
30
+ receivers: NonNullable<EndEvent["receivers"]>;
31
+ exitCode: number | null;
32
+ }
33
+
34
+ /** The latest state of a receiver. */
35
+ export interface ReceiverInfo {
36
+ name: string;
37
+ protocol: ReceiverProtocol | undefined;
38
+ state: ReceiverState;
39
+ error: string | undefined;
40
+ code: string | undefined;
41
+ }
42
+
43
+ /** The plan once streaming started. */
44
+ export type StartedInfo = Omit<StartedEvent, "type">;
45
+
46
+ export interface SessionEvents {
47
+ receiver: [ReceiverEvent];
48
+ viewer: [ViewerEvent];
49
+ player: [PlayerEvent];
50
+ "share-page": [SharePageEvent];
51
+ tunnel: [TunnelEvent];
52
+ connected: [ConnectedEvent];
53
+ started: [StartedEvent];
54
+ stats: [StatsEvent];
55
+ keyframe: [KeyframeEvent];
56
+ log: [LogEvent];
57
+ end: [EndInfo];
58
+ /** A failure; also rejects {@link Session.done}. Unhandled, it is not thrown. */
59
+ error: [TvpipeError];
60
+ /** Every event of the machine interface. */
61
+ event: [TvpipeEvent];
62
+ }
63
+
64
+ export interface SessionOptions {
65
+ /** Stops the session when aborted. */
66
+ signal?: AbortSignal | undefined;
67
+ /** How long `stop()` waits before it kills tvpipe (ms, default 5000). */
68
+ stopTimeout?: number | undefined;
69
+ }
70
+
71
+ /**
72
+ * A tvpipe session (`play`, `testPattern`, `preview`, `share`, `stream`).
73
+ * Stop it with {@link Session.stop} or `await using`.
74
+ */
75
+ export class Session extends EventEmitter<SessionEvents> implements AsyncDisposable {
76
+ /** The latest state of each receiver, by name. */
77
+ readonly receivers: Map<string, ReceiverInfo> = new Map();
78
+ /** The page of the `browser` receiver, if there is one. */
79
+ playerUrl: string | undefined;
80
+ /** `share()` without URL: the page to open and share from. */
81
+ shareUrl: string | undefined;
82
+ /** With `tunnel`: the public https link (the player's or the share page's). */
83
+ publicUrl: string | undefined;
84
+ /** The plan, once streaming started. */
85
+ info: StartedInfo | undefined;
86
+ /** The latest statistics (every second while streaming). */
87
+ stats: StatsEvent | undefined;
88
+ /** Resolves when the session ended; rejects with a {@link TvpipeError} when it failed. */
89
+ readonly done: Promise<EndInfo>;
90
+ protected readonly proc: TvpipeProcess;
91
+ #end: EndEvent | undefined;
92
+ #stopTimeout: number;
93
+ #stopping: Promise<EndInfo> | undefined;
94
+ #iterators = new Set<(ev: TvpipeEvent | undefined) => void>();
95
+
96
+ constructor(proc: TvpipeProcess, options: SessionOptions = {}) {
97
+ super();
98
+ this.proc = proc;
99
+ this.#stopTimeout = options.stopTimeout ?? 5000;
100
+ proc.on("event", (ev) => this.#handle(ev));
101
+ this.done = proc.exited.then((exit) => this.#finish(exit));
102
+ // `done` may never be awaited; its rejection is also the `error` event.
103
+ this.done.catch(() => {});
104
+ const signal = options.signal;
105
+ if (signal) {
106
+ const onAbort = () => void this.stop().catch(() => {});
107
+ if (signal.aborted) onAbort();
108
+ else {
109
+ signal.addEventListener("abort", onAbort, { once: true });
110
+ void proc.exited.then(() => signal.removeEventListener("abort", onAbort));
111
+ }
112
+ }
113
+ }
114
+
115
+ /** `error` without listeners is not thrown (failures reject `done`). */
116
+ override emit<K extends keyof SessionEvents>(event: K, ...args: SessionEvents[K]): boolean;
117
+ override emit(event: string, ...args: unknown[]): boolean {
118
+ if (event === "error" && this.listenerCount("error") === 0) return false;
119
+ return super.emit(event as keyof SessionEvents, ...(args as never));
120
+ }
121
+
122
+ /** The process id of tvpipe. */
123
+ get pid(): number | undefined {
124
+ return this.proc.pid;
125
+ }
126
+
127
+ /** Whether tvpipe still runs. */
128
+ get running(): boolean {
129
+ return this.proc.running;
130
+ }
131
+
132
+ /** The last log lines (for diagnostics). */
133
+ get log(): string[] {
134
+ return this.proc.log;
135
+ }
136
+
137
+ #handle(ev: TvpipeEvent): void {
138
+ switch (ev.type) {
139
+ case "receiver": {
140
+ const prev = this.receivers.get(ev.name);
141
+ this.receivers.set(ev.name, {
142
+ name: ev.name,
143
+ protocol: ev.protocol ?? prev?.protocol,
144
+ state: ev.state,
145
+ error: ev.error,
146
+ code: ev.code,
147
+ });
148
+ this.emit("receiver", ev);
149
+ break;
150
+ }
151
+ case "player":
152
+ this.playerUrl ??= ev.url;
153
+ this.emit("player", ev);
154
+ break;
155
+ case "share-page":
156
+ this.shareUrl = ev.url;
157
+ this.emit("share-page", ev);
158
+ break;
159
+ case "tunnel":
160
+ this.publicUrl ??= ev.url;
161
+ this.emit("tunnel", ev);
162
+ break;
163
+ case "viewer":
164
+ this.emit("viewer", ev);
165
+ break;
166
+ case "connected":
167
+ this.emit("connected", ev);
168
+ break;
169
+ case "started": {
170
+ const { type: _, ...info } = ev;
171
+ this.info = info;
172
+ this.emit("started", ev);
173
+ break;
174
+ }
175
+ case "stats":
176
+ this.stats = ev;
177
+ this.emit("stats", ev);
178
+ break;
179
+ case "keyframe":
180
+ this.emit("keyframe", ev);
181
+ break;
182
+ case "log":
183
+ this.emit("log", ev);
184
+ break;
185
+ case "end":
186
+ this.#end = ev;
187
+ break;
188
+ }
189
+ this.emit("event", ev);
190
+ for (const push of this.#iterators) push(ev);
191
+ }
192
+
193
+ #finish(exit: Exit): EndInfo {
194
+ for (const push of this.#iterators) push(undefined);
195
+ const failed = this.proc.failure !== undefined || exit.code !== 0 || !this.#end;
196
+ // 130: stopped by a signal (Ctrl-C reaching tvpipe too), after a
197
+ // clean teardown.
198
+ const signalled = exit.code === 130 && !this.proc.failure;
199
+ if (failed && !signalled && !(this.#stopping && exit.signal)) {
200
+ const err = this.proc.error();
201
+ this.emit("error", err);
202
+ throw err;
203
+ }
204
+ const info: EndInfo = {
205
+ reason: this.#end?.reason ?? "stopped",
206
+ receivers: this.#end?.receivers ?? [],
207
+ exitCode: exit.code,
208
+ };
209
+ this.emit("end", info);
210
+ return info;
211
+ }
212
+
213
+ /**
214
+ * Stops now: receivers get their teardown (the TV leaves mirroring),
215
+ * nothing queued is played. Resolves with the end info; rejects only if
216
+ * the session had failed. Kills tvpipe if it does not exit in time.
217
+ */
218
+ stop(): Promise<EndInfo> {
219
+ this.#stopping ??= this.proc.stop(this.#stopTimeout, "stop").then(() => this.done);
220
+ return this.#stopping;
221
+ }
222
+
223
+ /** Kills tvpipe without a teardown (receivers time out by themselves). */
224
+ kill(): void {
225
+ this.proc.kill("SIGKILL");
226
+ }
227
+
228
+ /** Lets Node exit while the session runs (it then ends with Node). */
229
+ unref(): void {
230
+ this.proc.child.unref();
231
+ for (const s of [this.proc.child.stdin, this.proc.child.stdout, this.proc.child.stderr]) {
232
+ (s as unknown as { unref?: () => void } | null)?.unref?.();
233
+ }
234
+ }
235
+
236
+ /** Every event until the session ends. */
237
+ async *events(): AsyncGenerator<TvpipeEvent, void, undefined> {
238
+ const queue: (TvpipeEvent | undefined)[] = [];
239
+ let wake: (() => void) | undefined;
240
+ const push = (ev: TvpipeEvent | undefined) => {
241
+ queue.push(ev);
242
+ wake?.();
243
+ };
244
+ if (!this.proc.running) return;
245
+ this.#iterators.add(push);
246
+ try {
247
+ for (;;) {
248
+ while (queue.length === 0) await new Promise<void>((r) => (wake = r));
249
+ const ev = queue.shift();
250
+ if (ev === undefined) return;
251
+ yield ev;
252
+ }
253
+ } finally {
254
+ this.#iterators.delete(push);
255
+ }
256
+ }
257
+
258
+ /** `await using`: stops the session (failures are not rethrown here). */
259
+ async [Symbol.asyncDispose](): Promise<void> {
260
+ await this.stop().catch(() => {});
261
+ }
262
+ }
package/src/slrw.ts ADDED
@@ -0,0 +1,99 @@
1
+ /**
2
+ * SLRW records (docs/slrw.md, docs/machine.md): what the SDK writes to the
3
+ * binary's stdin.
4
+ *
5
+ * `u8 kind | u64le pts_us | u32le len | payload`, after the magic `SLRW`.
6
+ */
7
+
8
+ export const MAGIC: Uint8Array = new TextEncoder().encode("SLRW");
9
+
10
+ export const Kind = {
11
+ end: 0,
12
+ video: 1,
13
+ audio: 2,
14
+ h264: 3,
15
+ h264Config: 4,
16
+ control: 5,
17
+ command: 6,
18
+ } as const;
19
+
20
+ export type KindCode = (typeof Kind)[keyof typeof Kind];
21
+
22
+ export const H264_KEYFRAME = 0x01;
23
+ export const H264_ANNEX_B = 0x02;
24
+ export const CONFIG_AVCC = 0;
25
+ export const CONFIG_ANNEX_B = 1;
26
+ export const CONTROL_KEYFRAME_REQUESTS = 0x01;
27
+ export const HEADER_LEN = 13;
28
+
29
+ /** Microseconds as the record's u64. */
30
+ function toPts(ptsUs: number | bigint): bigint {
31
+ if (typeof ptsUs === "bigint") {
32
+ if (ptsUs < 0n) throw new RangeError("pts must not be negative");
33
+ return ptsUs;
34
+ }
35
+ if (!Number.isFinite(ptsUs) || ptsUs < 0) throw new RangeError(`invalid pts ${ptsUs}`);
36
+ return BigInt(Math.round(ptsUs));
37
+ }
38
+
39
+ /**
40
+ * One record in a single new buffer: the header, an optional prefix byte
41
+ * (the flags or format of encoded kinds) and the payload, copied (callers
42
+ * may reuse their buffers right away).
43
+ */
44
+ export function record(
45
+ kind: KindCode,
46
+ ptsUs: number | bigint,
47
+ payload: Uint8Array,
48
+ prefix?: number,
49
+ ): Buffer {
50
+ const extra = prefix === undefined ? 0 : 1;
51
+ const len = payload.byteLength + extra;
52
+ const buf = Buffer.allocUnsafe(HEADER_LEN + len);
53
+ buf.writeUInt8(kind, 0);
54
+ buf.writeBigUInt64LE(toPts(ptsUs), 1);
55
+ buf.writeUInt32LE(len, 9);
56
+ if (prefix !== undefined) buf.writeUInt8(prefix, HEADER_LEN);
57
+ buf.set(payload, HEADER_LEN + extra);
58
+ return buf;
59
+ }
60
+
61
+ /** A `command` record (machine interface). */
62
+ export function command(cmd: Record<string, unknown>): Buffer {
63
+ return record(Kind.command, 0, new TextEncoder().encode(JSON.stringify(cmd)));
64
+ }
65
+
66
+ /** A `control` record. */
67
+ export function control(flags: number): Buffer {
68
+ const payload = new Uint8Array(4);
69
+ new DataView(payload.buffer).setUint32(0, flags >>> 0, true);
70
+ return record(Kind.control, 0, payload);
71
+ }
72
+
73
+ /** Bytes of an `ArrayBufferView` or `ArrayBuffer`, without copying. */
74
+ export function bytes(data: ArrayBufferView | ArrayBuffer): Uint8Array {
75
+ if (data instanceof Uint8Array) return data;
76
+ if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
77
+ return new Uint8Array(data);
78
+ }
79
+
80
+ /** Interleaved float samples (-1..1) as s16le bytes. */
81
+ export function floatToS16(samples: Float32Array | Float64Array): Uint8Array {
82
+ const out = new Uint8Array(samples.length * 2);
83
+ const view = new DataView(out.buffer);
84
+ for (let i = 0; i < samples.length; i++) {
85
+ const s = Math.max(-1, Math.min(1, samples[i] ?? 0));
86
+ view.setInt16(i * 2, Math.round(s < 0 ? s * 0x8000 : s * 0x7fff), true);
87
+ }
88
+ return out;
89
+ }
90
+
91
+ /** Whether an access unit starts with an Annex B start code. */
92
+ export function isAnnexB(au: Uint8Array): boolean {
93
+ return (
94
+ au.length >= 4 &&
95
+ au[0] === 0 &&
96
+ au[1] === 0 &&
97
+ (au[2] === 1 || (au[2] === 0 && au[3] === 1))
98
+ );
99
+ }
package/src/stream.ts ADDED
@@ -0,0 +1,297 @@
1
+ /**
2
+ * `stream()`: frames from code (raw pixels, PCM, a canvas, encoded H.264)
3
+ * through SLRW on tvpipe's stdin.
4
+ */
5
+
6
+ import type { EventEmitter } from "node:events";
7
+
8
+ import { canvasPixels, type CanvasLike, type Context2DLike } from "./canvas.ts";
9
+ import { TvpipeError } from "./errors.ts";
10
+ import type { TvpipeProcess } from "./process.ts";
11
+ import { Session, type EndInfo, type SessionOptions } from "./session.ts";
12
+ import * as slrw from "./slrw.ts";
13
+
14
+ export type PixelFormat = "rgba" | "bgra" | "rgb0" | "bgr0" | "rgb24" | "bgr24" | "nv12" | "yuv420p";
15
+
16
+ /** Raw frames, encoded by tvpipe. */
17
+ export interface RawVideoSpec {
18
+ width: number;
19
+ height: number;
20
+ /** Frames per second (also the pace of {@link StreamSession.drawLoop}). */
21
+ fps: number;
22
+ /** Pixel layout of `writeVideo` frames (default `rgba`; canvases are `rgba`). */
23
+ format?: PixelFormat;
24
+ }
25
+
26
+ /** H.264 encoded by the caller (WebCodecs, a hardware encoder). */
27
+ export interface EncodedVideoSpec {
28
+ width: number;
29
+ height: number;
30
+ fps: number;
31
+ codec: "h264";
32
+ }
33
+
34
+ export type VideoSpec = RawVideoSpec | EncodedVideoSpec;
35
+
36
+ /** Interleaved signed 16-bit PCM (float input is converted). */
37
+ export interface AudioSpec {
38
+ sampleRate: number;
39
+ channels: number;
40
+ }
41
+
42
+ /** A WebCodecs `EncodedVideoChunk`, duck-typed. */
43
+ export interface EncodedVideoChunkLike {
44
+ readonly type: "key" | "delta";
45
+ /** Microseconds. */
46
+ readonly timestamp: number;
47
+ readonly byteLength: number;
48
+ copyTo(destination: Uint8Array | ArrayBuffer): void;
49
+ }
50
+
51
+ /** WebCodecs `EncodedVideoChunkMetadata`, duck-typed. */
52
+ export interface EncodedVideoChunkMetadataLike {
53
+ decoderConfig?: { description?: ArrayBufferView | ArrayBuffer | undefined } | undefined;
54
+ }
55
+
56
+ export type Pts = number | bigint;
57
+
58
+ const BYTES_PER_PIXEL: Record<PixelFormat, number> = {
59
+ rgba: 4,
60
+ bgra: 4,
61
+ rgb0: 4,
62
+ bgr0: 4,
63
+ rgb24: 3,
64
+ bgr24: 3,
65
+ nv12: 1.5,
66
+ yuv420p: 1.5,
67
+ };
68
+
69
+ export interface StreamSessionOptions extends SessionOptions {
70
+ video: VideoSpec;
71
+ audio?: AudioSpec | undefined;
72
+ /**
73
+ * Raw video: frames are dropped (`writeVideo` returns `false`) while
74
+ * this many frames' worth of bytes wait in the pipe (default 2).
75
+ */
76
+ maxQueuedFrames?: number | undefined;
77
+ /** Playout delay (ms), to wait for the tail in `end()`. */
78
+ latencyMs?: number | undefined;
79
+ }
80
+
81
+ /** A session fed by the program: see {@link stream}. */
82
+ export class StreamSession extends Session {
83
+ readonly video: VideoSpec;
84
+ readonly audio: AudioSpec | undefined;
85
+ /** Raw frames skipped because the pipe was backed up. */
86
+ readonly dropped = { video: 0 };
87
+ #t0 = performance.now();
88
+ #lastPts = { video: -1n, audio: -1n };
89
+ #frameBytes: number;
90
+ #maxQueued: number;
91
+ #config: Uint8Array | undefined;
92
+ #latencyMs: number;
93
+ #loops = new Set<() => void>();
94
+ #keyframePending = false;
95
+
96
+ constructor(proc: TvpipeProcess, options: StreamSessionOptions) {
97
+ super(proc, options);
98
+ this.video = options.video;
99
+ this.audio = options.audio;
100
+ this.#maxQueued = options.maxQueuedFrames ?? 2;
101
+ this.#latencyMs = options.latencyMs ?? 300;
102
+ const format = "codec" in this.video ? undefined : (this.video.format ?? "rgba");
103
+ this.#frameBytes = format ? Math.ceil(this.video.width * this.video.height * BYTES_PER_PIXEL[format]) : 0;
104
+ if ("codec" in this.video) {
105
+ // Keyframe requests become `keyframe` events.
106
+ proc.write(slrw.control(slrw.CONTROL_KEYFRAME_REQUESTS));
107
+ // The first request comes right when the input opens, often before
108
+ // the caller had a chance to listen: keep it for the first listener.
109
+ this.on("keyframe", () => {
110
+ if (this.listenerCount("keyframe") === 1) this.#keyframePending = true;
111
+ });
112
+ (this as EventEmitter).on("newListener", (event: string | symbol) => {
113
+ if (event === "keyframe" && this.#keyframePending) {
114
+ this.#keyframePending = false;
115
+ process.nextTick(() => this.emit("keyframe", { type: "keyframe" }));
116
+ }
117
+ });
118
+ }
119
+ void this.done.catch(() => {}).finally(() => {
120
+ for (const stop of this.#loops) stop();
121
+ });
122
+ }
123
+
124
+ /** Microseconds since the stream started. */
125
+ now(): number {
126
+ return Math.round((performance.now() - this.#t0) * 1000);
127
+ }
128
+
129
+ #pts(track: "video" | "audio", pts: Pts | undefined): bigint {
130
+ let p = pts === undefined ? BigInt(this.now()) : typeof pts === "bigint" ? pts : BigInt(Math.round(pts));
131
+ if (p < 0n) throw new TvpipeError("invalid-argument", "pts must not be negative");
132
+ // Defaulted timestamps must increase; given ones are the caller's.
133
+ if (pts === undefined && p <= this.#lastPts[track]) p = this.#lastPts[track] + 1n;
134
+ this.#lastPts[track] = p;
135
+ return p;
136
+ }
137
+
138
+ #raw(): RawVideoSpec {
139
+ if ("codec" in this.video) {
140
+ throw new TvpipeError("invalid-argument", "this stream takes H.264 (writeH264/writeChunk), not raw frames");
141
+ }
142
+ return this.video;
143
+ }
144
+
145
+ #encoded(): void {
146
+ if (!("codec" in this.video)) {
147
+ throw new TvpipeError("invalid-argument", "this stream takes raw frames; use video: { codec: \"h264\" } for H.264");
148
+ }
149
+ }
150
+
151
+ /**
152
+ * One raw frame in the stream's size and pixel format. Returns `false`
153
+ * when the frame was dropped because tvpipe is behind (live sources
154
+ * keep going; see `maxQueuedFrames`) or the stream is over.
155
+ */
156
+ writeVideo(frame: ArrayBufferView | ArrayBuffer, ptsUs?: Pts): boolean {
157
+ this.#raw();
158
+ const data = slrw.bytes(frame);
159
+ if (data.byteLength !== this.#frameBytes) {
160
+ throw new TvpipeError(
161
+ "invalid-argument",
162
+ `a ${this.video.width}x${this.video.height} frame has ${this.#frameBytes} bytes, got ${data.byteLength}`,
163
+ );
164
+ }
165
+ if (!this.proc.inputOpen) return false;
166
+ if (this.proc.queuedBytes >= this.#frameBytes * this.#maxQueued) {
167
+ this.dropped.video++;
168
+ return false;
169
+ }
170
+ this.proc.write(slrw.record(slrw.Kind.video, this.#pts("video", ptsUs), data));
171
+ return true;
172
+ }
173
+
174
+ /**
175
+ * Interleaved PCM: `Int16Array` or s16le bytes, or float samples
176
+ * (-1..1). Never dropped. Returns `false` once the pipe is backed up
177
+ * (the data is queued anyway) or the stream is over.
178
+ */
179
+ writeAudio(pcm: Int16Array | Float32Array | Float64Array | Uint8Array | ArrayBuffer, ptsUs?: Pts): boolean {
180
+ if (!this.audio) throw new TvpipeError("invalid-argument", "the stream has no audio (pass audio: { sampleRate, channels })");
181
+ const data = pcm instanceof Float32Array || pcm instanceof Float64Array ? slrw.floatToS16(pcm) : slrw.bytes(pcm);
182
+ if (data.byteLength % (2 * this.audio.channels) !== 0) {
183
+ throw new TvpipeError("invalid-argument", `PCM must be whole frames of ${this.audio.channels} s16 samples`);
184
+ }
185
+ if (data.byteLength === 0) return true;
186
+ return this.proc.write(slrw.record(slrw.Kind.audio, this.#pts("audio", ptsUs), data));
187
+ }
188
+
189
+ /** The canvas's current picture (via `getImageData`; the stream's format must be `rgba`). */
190
+ writeCanvas(canvas: CanvasLike, ptsUs?: Pts): boolean {
191
+ const raw = this.#raw();
192
+ if ((raw.format ?? "rgba") !== "rgba") {
193
+ throw new TvpipeError("invalid-argument", "canvases give rgba pixels; create the stream with format \"rgba\"");
194
+ }
195
+ if (canvas.width !== raw.width || canvas.height !== raw.height) {
196
+ throw new TvpipeError(
197
+ "invalid-argument",
198
+ `the canvas is ${canvas.width}x${canvas.height}, the stream ${raw.width}x${raw.height}`,
199
+ );
200
+ }
201
+ return this.writeVideo(canvasPixels(canvas).data, ptsUs);
202
+ }
203
+
204
+ /**
205
+ * Calls `draw` at the stream's frame rate and sends the canvas after
206
+ * each call, until `stop()` or the end of the session.
207
+ */
208
+ drawLoop(canvas: CanvasLike, draw: (ctx: Context2DLike, timeMs: number) => void): { stop(): void } {
209
+ const raw = this.#raw();
210
+ const ctx = canvas.getContext("2d");
211
+ if (!ctx) throw new TvpipeError("invalid-argument", "the canvas has no 2D context");
212
+ const interval = 1000 / raw.fps;
213
+ const start = performance.now();
214
+ let n = 0;
215
+ let timer: NodeJS.Timeout | undefined;
216
+ let running = true;
217
+ const stop = () => {
218
+ running = false;
219
+ if (timer) clearTimeout(timer);
220
+ this.#loops.delete(stop);
221
+ };
222
+ const tick = () => {
223
+ if (!running || !this.proc.inputOpen) return stop();
224
+ const t = performance.now() - start;
225
+ try {
226
+ draw(ctx, t);
227
+ this.writeCanvas(canvas);
228
+ } catch (err) {
229
+ stop();
230
+ this.emit("error", err instanceof TvpipeError ? err : new TvpipeError("invalid-argument", String(err), { cause: err }));
231
+ return;
232
+ }
233
+ n++;
234
+ // Skip ticks the drawing could not keep up with.
235
+ const next = Math.max(n, Math.floor((performance.now() - start) / interval) + 1);
236
+ n = next;
237
+ timer = setTimeout(tick, Math.max(0, start + next * interval - performance.now()));
238
+ };
239
+ this.#loops.add(stop);
240
+ timer = setTimeout(tick, 0);
241
+ return { stop };
242
+ }
243
+
244
+ /**
245
+ * One H.264 access unit (all NAL units of one picture; AVCC with 4-byte
246
+ * lengths, or Annex B with start codes, detected unless `annexB` says).
247
+ * Never dropped; `false` means the pipe is backed up (await `drain()`).
248
+ */
249
+ writeH264(au: ArrayBufferView | ArrayBuffer, options: { keyframe: boolean; ptsUs?: Pts; annexB?: boolean }): boolean {
250
+ this.#encoded();
251
+ if (options.keyframe) this.#keyframePending = false;
252
+ const data = slrw.bytes(au);
253
+ const annexB = options.annexB ?? slrw.isAnnexB(data);
254
+ const flags = (options.keyframe ? slrw.H264_KEYFRAME : 0) | (annexB ? slrw.H264_ANNEX_B : 0);
255
+ return this.proc.write(slrw.record(slrw.Kind.h264, this.#pts("video", options.ptsUs), data, flags));
256
+ }
257
+
258
+ /** The decoder configuration: an avcC record, or Annex B SPS + PPS. */
259
+ writeH264Config(config: ArrayBufferView | ArrayBuffer, format: "avcc" | "annexb" = "avcc"): boolean {
260
+ this.#encoded();
261
+ const data = slrw.bytes(config);
262
+ this.#config = data.slice();
263
+ return this.proc.write(
264
+ slrw.record(slrw.Kind.h264Config, 0, data, format === "avcc" ? slrw.CONFIG_AVCC : slrw.CONFIG_ANNEX_B),
265
+ );
266
+ }
267
+
268
+ /** A WebCodecs `VideoEncoder` output: `encoder = new VideoEncoder({ output: (c, m) => s.writeChunk(c, m) })`. */
269
+ writeChunk(chunk: EncodedVideoChunkLike, metadata?: EncodedVideoChunkMetadataLike): boolean {
270
+ this.#encoded();
271
+ const desc = metadata?.decoderConfig?.description;
272
+ if (desc) {
273
+ const d = slrw.bytes(desc);
274
+ if (!this.#config || !sameBytes(this.#config, d)) this.writeH264Config(d, "avcc");
275
+ }
276
+ const data = new Uint8Array(chunk.byteLength);
277
+ chunk.copyTo(data);
278
+ return this.writeH264(data, { keyframe: chunk.type === "key", ptsUs: Math.max(0, chunk.timestamp) });
279
+ }
280
+
281
+ /** Resolves once the pipe took everything written. */
282
+ drain(): Promise<void> {
283
+ return this.proc.drain();
284
+ }
285
+
286
+ /** Ends the stream: what was written plays out, then the teardown. */
287
+ end(): Promise<EndInfo> {
288
+ for (const stop of this.#loops) stop();
289
+ return this.proc.stop(5000 + this.#latencyMs, "end").then(() => this.done);
290
+ }
291
+ }
292
+
293
+ function sameBytes(a: Uint8Array, b: Uint8Array): boolean {
294
+ if (a.byteLength !== b.byteLength) return false;
295
+ for (let i = 0; i < a.byteLength; i++) if (a[i] !== b[i]) return false;
296
+ return true;
297
+ }