@open-take/runtime 0.5.1 → 0.5.3

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.
@@ -1,10 +1,209 @@
1
+ import { readFile } from "node:fs/promises";
1
2
  import { homedir, tmpdir } from "node:os";
2
3
  import { basename, dirname, join, resolve } from "node:path";
3
4
  import { resolveFfmpeg, resolveFfprobe } from "@open-take/compositor";
4
5
  import { spawn } from "node:child_process";
6
+ import { once } from "node:events";
5
7
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, writeFileSync } from "node:fs";
6
8
  import { createRequire } from "node:module";
7
9
 
10
+ //#region src/mjpeg-matroska.ts
11
+ const ID = {
12
+ EBML: 440786851,
13
+ EBMLVersion: 17030,
14
+ EBMLReadVersion: 17143,
15
+ EBMLMaxIDLength: 17138,
16
+ EBMLMaxSizeLength: 17139,
17
+ DocType: 17026,
18
+ DocTypeVersion: 17031,
19
+ DocTypeReadVersion: 17029,
20
+ Segment: 408125543,
21
+ Info: 357149030,
22
+ TimecodeScale: 2807729,
23
+ Duration: 17545,
24
+ MuxingApp: 19840,
25
+ WritingApp: 22337,
26
+ Tracks: 374648427,
27
+ TrackEntry: 174,
28
+ TrackNumber: 215,
29
+ TrackUID: 29637,
30
+ TrackType: 131,
31
+ FlagLacing: 156,
32
+ CodecID: 134,
33
+ Video: 224,
34
+ PixelWidth: 176,
35
+ PixelHeight: 186,
36
+ Cluster: 524531317,
37
+ Timecode: 231,
38
+ SimpleBlock: 163
39
+ };
40
+ /** Element IDs are written with their length marker bits included, so the
41
+ * constant's own big-endian bytes are the encoding. */
42
+ function idBytes(id) {
43
+ const bytes = [];
44
+ for (let v = id; v > 0; v = Math.floor(v / 256)) bytes.unshift(v % 256);
45
+ return Buffer.from(bytes);
46
+ }
47
+ /** EBML variable-size integer: a width-w encoding carries 7w bits and the
48
+ * all-ones pattern of each width is reserved for "size unknown". */
49
+ function sizeBytes(n) {
50
+ for (let width = 1; width <= 8; width++) {
51
+ if (n > 2 ** (7 * width) - 2) continue;
52
+ const out = Buffer.alloc(width);
53
+ let v = BigInt(n) | 1n << BigInt(7 * width);
54
+ for (let i = width - 1; i >= 0; i--) {
55
+ out[i] = Number(v & 0xffn);
56
+ v >>= 8n;
57
+ }
58
+ return out;
59
+ }
60
+ throw new Error(`matroska: element of ${n} bytes exceeds the EBML size range`);
61
+ }
62
+ const UNKNOWN_SIZE = Buffer.from([
63
+ 1,
64
+ 255,
65
+ 255,
66
+ 255,
67
+ 255,
68
+ 255,
69
+ 255,
70
+ 255
71
+ ]);
72
+ const element = (id, payload) => Buffer.concat([
73
+ idBytes(id),
74
+ sizeBytes(payload.length),
75
+ payload
76
+ ]);
77
+ function uint(id, n) {
78
+ if (!Number.isInteger(n) || n < 0) throw new Error(`matroska: ${n} is not an unsigned integer`);
79
+ const bytes = [];
80
+ let v = BigInt(n);
81
+ do {
82
+ bytes.unshift(Number(v & 0xffn));
83
+ v >>= 8n;
84
+ } while (v > 0n);
85
+ return element(id, Buffer.from(bytes));
86
+ }
87
+ const utf8 = (id, s) => element(id, Buffer.from(s, "utf8"));
88
+ function float64(id, x) {
89
+ const b = Buffer.alloc(8);
90
+ b.writeDoubleBE(x);
91
+ return element(id, b);
92
+ }
93
+ /** Pixel size from a JPEG's frame header (any SOF marker: baseline,
94
+ * progressive, lossless…), read past APPn/COM/DQT segments by their lengths. */
95
+ function jpegDimensions(jpeg) {
96
+ if (jpeg.length < 4 || jpeg[0] !== 255 || jpeg[1] !== 216) throw new Error("jpegDimensions: not a JPEG (no SOI marker)");
97
+ let i = 2;
98
+ while (i + 4 <= jpeg.length) {
99
+ if (jpeg[i] !== 255) {
100
+ i++;
101
+ continue;
102
+ }
103
+ const marker = jpeg[i + 1];
104
+ if (marker === 255) {
105
+ i++;
106
+ continue;
107
+ }
108
+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
109
+ i += 2;
110
+ continue;
111
+ }
112
+ const isSof = marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204;
113
+ if (isSof) {
114
+ if (i + 9 > jpeg.length) break;
115
+ return {
116
+ height: jpeg.readUInt16BE(i + 5),
117
+ width: jpeg.readUInt16BE(i + 7)
118
+ };
119
+ }
120
+ if (marker === 218 || marker === 217) break;
121
+ i += 2 + jpeg.readUInt16BE(i + 2);
122
+ }
123
+ throw new Error("jpegDimensions: no SOF marker before scan data");
124
+ }
125
+ /** Everything before the first cluster. `durationMs` is advisory (players and
126
+ * ffprobe report it); the frames themselves carry the timing. */
127
+ function matroskaHead(width, height, durationMs) {
128
+ const header = element(ID.EBML, Buffer.concat([
129
+ uint(ID.EBMLVersion, 1),
130
+ uint(ID.EBMLReadVersion, 1),
131
+ uint(ID.EBMLMaxIDLength, 4),
132
+ uint(ID.EBMLMaxSizeLength, 8),
133
+ utf8(ID.DocType, "matroska"),
134
+ uint(ID.DocTypeVersion, 4),
135
+ uint(ID.DocTypeReadVersion, 2)
136
+ ]));
137
+ const info = element(ID.Info, Buffer.concat([
138
+ uint(ID.TimecodeScale, 1e6),
139
+ float64(ID.Duration, durationMs),
140
+ utf8(ID.MuxingApp, "open-take"),
141
+ utf8(ID.WritingApp, "open-take")
142
+ ]));
143
+ const tracks = element(ID.Tracks, element(ID.TrackEntry, Buffer.concat([
144
+ uint(ID.TrackNumber, 1),
145
+ uint(ID.TrackUID, 1),
146
+ uint(ID.TrackType, 1),
147
+ uint(ID.FlagLacing, 0),
148
+ utf8(ID.CodecID, "V_MJPEG"),
149
+ element(ID.Video, Buffer.concat([uint(ID.PixelWidth, width), uint(ID.PixelHeight, height)]))
150
+ ])));
151
+ return Buffer.concat([
152
+ header,
153
+ idBytes(ID.Segment),
154
+ UNKNOWN_SIZE,
155
+ info,
156
+ tracks
157
+ ]);
158
+ }
159
+ /** One frame: a cluster stamped with its absolute time holding a single
160
+ * keyframe SimpleBlock (track 1, relative timecode 0) around the raw JPEG. */
161
+ function matroskaCluster(tMs, jpeg) {
162
+ const block = element(ID.SimpleBlock, Buffer.concat([Buffer.from([
163
+ 129,
164
+ 0,
165
+ 0,
166
+ 128
167
+ ]), jpeg]));
168
+ return element(ID.Cluster, Buffer.concat([uint(ID.Timecode, tMs), block]));
169
+ }
170
+ /** The whole stream, chunk by chunk, so a minute of Retina frames never sits
171
+ * in memory or on disk twice. Frames must be in non-decreasing tMs order;
172
+ * a file repeated back to back is read once.
173
+ *
174
+ * The track's pixel size comes from the first frame whose header parses.
175
+ * ffmpeg takes the size from each JPEG anyway, so one truncated frame (a
176
+ * write cut short) must not fail the whole encode here when the decoder
177
+ * would have skipped it; only a stream with no readable header at all is an
178
+ * error. */
179
+ async function* mjpegMatroska(frames) {
180
+ if (frames.length === 0) throw new Error("mjpegMatroska: no frames");
181
+ const jpegs = new Map();
182
+ let size;
183
+ for (const { file: file$1 } of frames) {
184
+ if (jpegs.has(file$1)) continue;
185
+ const jpeg$1 = await readFile(file$1);
186
+ jpegs.set(file$1, jpeg$1);
187
+ try {
188
+ size = jpegDimensions(jpeg$1);
189
+ break;
190
+ } catch {}
191
+ }
192
+ if (!size) throw new Error("mjpegMatroska: no frame has a readable JPEG header");
193
+ yield matroskaHead(size.width, size.height, frames[frames.length - 1].tMs);
194
+ let file = "";
195
+ let jpeg = Buffer.alloc(0);
196
+ for (const frame of frames) {
197
+ if (frame.file !== file) {
198
+ file = frame.file;
199
+ jpeg = jpegs.get(file) ?? await readFile(file);
200
+ jpegs.delete(file);
201
+ }
202
+ yield matroskaCluster(frame.tMs, jpeg);
203
+ }
204
+ }
205
+
206
+ //#endregion
8
207
  //#region src/cdp.ts
9
208
  const sleep$3 = (ms) => new Promise((r) => setTimeout(r, ms));
10
209
  const require = createRequire(import.meta.url);
@@ -216,9 +415,10 @@ function pidAlive(pid) {
216
415
  return false;
217
416
  }
218
417
  }
418
+ const DEVTOOLS_PORT_WAIT_MS = 3e4;
219
419
  async function readDevtoolsPort(userDir, proc) {
220
420
  const file = join(userDir, "DevToolsActivePort");
221
- for (let i = 0; i < 100; i++) {
421
+ for (let i = 0; i < DEVTOOLS_PORT_WAIT_MS / 50; i++) {
222
422
  if (proc.exitCode != null) throw new Error(`chrome exited early (${proc.exitCode})`);
223
423
  if (existsSync(file)) {
224
424
  const line = readFileSync(file, "utf8").split("\n")[0]?.trim();
@@ -227,7 +427,7 @@ async function readDevtoolsPort(userDir, proc) {
227
427
  }
228
428
  await sleep$3(50);
229
429
  }
230
- throw new Error("timed out waiting for DevToolsActivePort");
430
+ throw new Error(`timed out waiting for DevToolsActivePort (${DEVTOOLS_PORT_WAIT_MS / 1e3}s)`);
231
431
  }
232
432
  async function pageTargetWs(port) {
233
433
  for (let i = 0; i < 60; i++) {
@@ -360,24 +560,34 @@ async function pumpIdleRaster(cdp, screencast, active, paused) {
360
560
  await sleep$3(45);
361
561
  }
362
562
  }
563
+ /** Where each frame sits on the video's clock, in whole milliseconds. The
564
+ * first frame is pulled back to 0 so the video timeline starts where event
565
+ * timestamps do; later frames keep their observed offset, nudged forward by
566
+ * 1 ms when two swaps round onto the same millisecond so no frame vanishes
567
+ * under its neighbour. The last frame is repeated at the end time (at least
568
+ * one frame period after it was shown) to give it a duration. */
569
+ function frameTimeline(frames, endMs, fps) {
570
+ const ordered = [...frames].sort((a, b) => a.offMs - b.offMs);
571
+ const timeline = [];
572
+ let tMs = 0;
573
+ for (let i = 0; i < ordered.length; i++) {
574
+ if (i > 0) tMs = Math.max(tMs + 1, Math.round(ordered[i].offMs));
575
+ timeline.push({
576
+ file: ordered[i].file,
577
+ tMs
578
+ });
579
+ }
580
+ const last = ordered[ordered.length - 1];
581
+ timeline.push({
582
+ file: last.file,
583
+ tMs: Math.max(tMs + 1, Math.round(endMs), Math.round(last.offMs + 1e3 / fps))
584
+ });
585
+ return timeline;
586
+ }
363
587
  async function encodeFrames(frames, endMs, outPath, fps, ffmpegBin) {
364
588
  if (frames.length === 0) throw new Error("open-take(hi-fps): no frames captured");
365
- frames = [...frames].sort((a, b) => a.offMs - b.offMs);
589
+ const timeline = frameTimeline(frames, endMs, fps);
366
590
  const bin = ffmpegBin ?? await resolveFfmpeg();
367
- const dir = dirname(frames[0].file);
368
- const listPath = join(dir, "frames.concat");
369
- const lines = [];
370
- const bounds = [
371
- 0,
372
- ...frames.slice(1).map((f) => f.offMs),
373
- Math.max(endMs, frames[frames.length - 1].offMs + 1e3 / fps)
374
- ];
375
- for (let i = 0; i < frames.length; i++) {
376
- const dur = Math.max(.001, (bounds[i + 1] - bounds[i]) / 1e3);
377
- lines.push(`file '${frames[i].file}'`, "option framerate 1000", `duration ${dur.toFixed(6)}`);
378
- }
379
- lines.push(`file '${frames[frames.length - 1].file}'`, "option framerate 1000");
380
- writeFileSync(listPath, lines.join("\n"));
381
591
  const isWebm = /\.webm$/i.test(outPath);
382
592
  const codec = isWebm ? [
383
593
  "-c:v",
@@ -398,7 +608,7 @@ async function encodeFrames(frames, endMs, outPath, fps, ffmpegBin) {
398
608
  "-crf",
399
609
  "18"
400
610
  ];
401
- const colorConvert = isWebm ? "" : ":in_range=full:in_color_matrix=bt470bg:out_range=tv:out_color_matrix=bt709";
611
+ const colorConvert = isWebm ? "" : ":in_range=full:in_color_matrix=bt601:out_range=tv:out_color_matrix=bt709";
402
612
  const colorLabel = isWebm ? "" : ",setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709";
403
613
  return new Promise((resolve$1, reject) => {
404
614
  const args = [
@@ -406,12 +616,10 @@ async function encodeFrames(frames, endMs, outPath, fps, ffmpegBin) {
406
616
  "-loglevel",
407
617
  "error",
408
618
  "-f",
409
- "concat",
410
- "-safe",
411
- "0",
619
+ "matroska",
412
620
  "-i",
413
- listPath,
414
- "-vsync",
621
+ "pipe:0",
622
+ "-fps_mode",
415
623
  "cfr",
416
624
  "-r",
417
625
  String(fps),
@@ -421,18 +629,42 @@ async function encodeFrames(frames, endMs, outPath, fps, ffmpegBin) {
421
629
  outPath
422
630
  ];
423
631
  const c = spawn(bin, args, { stdio: [
424
- "ignore",
632
+ "pipe",
425
633
  "ignore",
426
634
  "pipe"
427
635
  ] });
428
636
  let err = "";
637
+ let feedErr;
429
638
  c.stderr.on("data", (d) => {
430
639
  err += d;
431
640
  });
432
641
  c.on("error", reject);
433
- c.on("close", (code) => code === 0 ? resolve$1() : reject(new Error(`ffmpeg encode exited ${code}: ${err.slice(-800)}`)));
642
+ c.on("close", (code) => {
643
+ if (code !== 0 && code !== null) reject(new Error(`ffmpeg encode exited ${code}: ${err.slice(-800)}`));
644
+ else if (feedErr) reject(feedErr);
645
+ else if (code === 0) resolve$1();
646
+ else reject(new Error(`ffmpeg encode killed: ${err.slice(-800)}`));
647
+ });
648
+ c.stdin.on("error", () => {});
649
+ feedStdin(c.stdin, mjpegMatroska(timeline)).then(() => c.stdin.end(), (e) => {
650
+ feedErr = e;
651
+ c.kill("SIGKILL");
652
+ });
434
653
  });
435
654
  }
655
+ /** Write chunks respecting backpressure. The pipe dying underneath us (ffmpeg
656
+ * exited) simply ends the feed — the process exit explains itself; only the
657
+ * source throwing (a frame that cannot be read) rejects. */
658
+ async function feedStdin(stdin, chunks) {
659
+ for await (const chunk of chunks) {
660
+ if (stdin.destroyed || stdin.writableEnded) return;
661
+ try {
662
+ if (!stdin.write(chunk)) await once(stdin, "drain");
663
+ } catch {
664
+ return;
665
+ }
666
+ }
667
+ }
436
668
  /** A throwaway temp dir for the screencast's per-frame JPEGs. */
437
669
  const makeFrameDir = () => mkdtempSync(join(tmpdir(), "open-take-frames-"));
438
670
  /** Poll `ready` every few milliseconds until it is true or `timeoutMs` has passed.
@@ -618,7 +850,7 @@ async function ffprobe(path) {
618
850
  }
619
851
  /** Drive `plan` against the live app over CDP, return the ground-truth log. */
620
852
  async function captureTake(plan, opts) {
621
- const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-Bm6EPvkE.js");
853
+ const { captureTakeCDP: captureTakeCDP$1 } = await import("./cdp-capture-gux1GPRE.js");
622
854
  return captureTakeCDP$1(plan, {
623
855
  ...opts,
624
856
  fps: opts.fps ?? 60
@@ -2135,4 +2367,4 @@ async function navigate(cdp, url) {
2135
2367
 
2136
2368
  //#endregion
2137
2369
  export { PrecheckRefusal, captureTake, captureTakeCDP, ensureChrome, inspectPage, planTargets, precheckPlan, resolveChrome, resolveNavigateUrl };
2138
- //# sourceMappingURL=cdp-capture-Bl990GzE.js.map
2370
+ //# sourceMappingURL=cdp-capture-MBg9nQy3.js.map