@mizchi/vlmkit-core 0.23.2 → 0.28.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 (112) hide show
  1. package/dist/a11y-semantic.d.mts +6 -10
  2. package/dist/a11y-semantic.mjs +3 -4
  3. package/dist/animated-image.d.mts +27 -0
  4. package/dist/animated-image.mjs +112 -0
  5. package/dist/apng.d.mts +5 -9
  6. package/dist/apng.mjs +6 -7
  7. package/dist/arg-reader.d.mts +9 -12
  8. package/dist/arg-reader.mjs +1 -2
  9. package/dist/auth-state.d.mts +6 -9
  10. package/dist/auth-state.mjs +1 -2
  11. package/dist/authored-style-capture.d.mts +7 -10
  12. package/dist/authored-style-capture.mjs +1 -2
  13. package/dist/authored-style-diff.d.mts +8 -12
  14. package/dist/authored-style-diff.mjs +1 -2
  15. package/dist/bitmap-font.d.mts +7 -10
  16. package/dist/bitmap-font.mjs +1 -2
  17. package/dist/browser-launch.d.mts +7 -11
  18. package/dist/browser-launch.mjs +1 -2
  19. package/dist/cli-args.d.mts +8 -11
  20. package/dist/cli-args.mjs +1 -2
  21. package/dist/cli-error.d.mts +10 -13
  22. package/dist/cli-error.mjs +2 -3
  23. package/dist/computed-style-capture.d.mts +20 -23
  24. package/dist/computed-style-capture.mjs +4 -5
  25. package/dist/computed-style-diff.d.mts +8 -11
  26. package/dist/computed-style-diff.mjs +2 -3
  27. package/dist/diff-regions.d.mts +3 -7
  28. package/dist/diff-regions.mjs +1 -2
  29. package/dist/dom-equivalence.d.mts +5 -8
  30. package/dist/dom-equivalence.mjs +1 -2
  31. package/dist/dom-position-styles.d.mts +14 -15
  32. package/dist/dom-position-styles.mjs +4 -5
  33. package/dist/element-compare.d.mts +8 -9
  34. package/dist/element-compare.mjs +5 -5
  35. package/dist/filmstrip.d.mts +60 -9
  36. package/dist/filmstrip.mjs +83 -12
  37. package/dist/gate-config.d.mts +18 -22
  38. package/dist/gate-config.mjs +8 -4
  39. package/dist/gate-exit.d.mts +5 -8
  40. package/dist/gate-exit.mjs +1 -2
  41. package/dist/gif.d.mts +41 -0
  42. package/dist/gif.mjs +73 -0
  43. package/dist/heatmap-regions.d.mts +4 -7
  44. package/dist/heatmap-regions.mjs +1 -2
  45. package/dist/heatmap.d.mts +21 -17
  46. package/dist/heatmap.mjs +23 -11
  47. package/dist/image-resize.d.mts +9 -12
  48. package/dist/image-resize.mjs +1 -2
  49. package/dist/image-timing.d.mts +57 -0
  50. package/dist/image-timing.mjs +166 -0
  51. package/dist/index.d.mts +14 -14
  52. package/dist/index.mjs +11 -11
  53. package/dist/mask.d.mts +5 -9
  54. package/dist/mask.mjs +1 -2
  55. package/dist/motion-spec.d.mts +97 -0
  56. package/dist/motion-spec.mjs +145 -0
  57. package/dist/navigation-redirect.d.mts +1 -4
  58. package/dist/navigation-redirect.mjs +1 -2
  59. package/dist/page-load.d.mts +40 -16
  60. package/dist/page-load.mjs +34 -5
  61. package/dist/page-open.d.mts +15 -15
  62. package/dist/page-open.mjs +4 -3
  63. package/dist/plugin/args.d.mts +16 -12
  64. package/dist/plugin/args.mjs +15 -4
  65. package/dist/plugin/browser.d.mts +3 -3
  66. package/dist/plugin/browser.mjs +2 -2
  67. package/dist/plugin/cli-entry.d.mts +1 -4
  68. package/dist/plugin/cli-entry.mjs +1 -2
  69. package/dist/plugin/contract.d.mts +17 -21
  70. package/dist/plugin/contract.mjs +1 -2
  71. package/dist/plugin/index.d.mts +6 -9
  72. package/dist/plugin/index.mjs +7 -8
  73. package/dist/plugin/load.d.mts +7 -11
  74. package/dist/plugin/load.mjs +1 -2
  75. package/dist/plugin/registry.d.mts +8 -12
  76. package/dist/plugin/registry.mjs +1 -2
  77. package/dist/plugin/rule-prose.d.mts +4 -8
  78. package/dist/plugin/rule-prose.mjs +1 -2
  79. package/dist/plugin/rule-tier.d.mts +7 -11
  80. package/dist/plugin/rule-tier.mjs +1 -2
  81. package/dist/plugin/rules.d.mts +18 -22
  82. package/dist/plugin/rules.mjs +1 -2
  83. package/dist/plugin/runner.d.mts +18 -21
  84. package/dist/plugin/runner.mjs +55 -6
  85. package/dist/png-decode.d.mts +17 -0
  86. package/dist/png-decode.mjs +160 -0
  87. package/dist/png-utils.d.mts +7 -10
  88. package/dist/png-utils.mjs +3 -3
  89. package/dist/project-config.d.mts +7 -10
  90. package/dist/project-config.mjs +1 -2
  91. package/dist/rect-overlap.d.mts +3 -6
  92. package/dist/rect-overlap.mjs +1 -2
  93. package/dist/region-shift.d.mts +3 -6
  94. package/dist/region-shift.mjs +1 -2
  95. package/dist/run-ledger.d.mts +10 -13
  96. package/dist/run-ledger.mjs +4 -4
  97. package/dist/stable-selector.d.mts +1 -4
  98. package/dist/stable-selector.mjs +1 -2
  99. package/dist/terminal-colors.d.mts +8 -11
  100. package/dist/terminal-colors.mjs +1 -2
  101. package/dist/text-rows.d.mts +10 -13
  102. package/dist/text-rows.mjs +1 -2
  103. package/dist/types.d.mts +87 -64
  104. package/dist/version.d.mts +1 -4
  105. package/dist/version.mjs +2 -3
  106. package/dist/video-decode.d.mts +144 -0
  107. package/dist/video-decode.mjs +939 -0
  108. package/dist/video-frames.d.mts +310 -0
  109. package/dist/video-frames.mjs +576 -0
  110. package/dist/webp.d.mts +7 -11
  111. package/dist/webp.mjs +3 -3
  112. package/package.json +7 -7
@@ -0,0 +1,939 @@
1
+ import { browserDelayMs, gifCompositingProblem, imageTiming } from "./image-timing.mjs";
2
+ import { LOSSLESS_CODECS, chooseFrames, colorPlan, displayGeometry, filterChain, gopNumbers, imageTimeline, parseFrameTable, parseShowinfoLine, pickVideoStream, recordingEndMs, rotationFilters, videoTimeline } from "./video-frames.mjs";
3
+ import { accessSync, closeSync, constants, existsSync, openSync, readFileSync, readSync, readlinkSync, realpathSync, statSync } from "node:fs";
4
+ import { basename, dirname, extname, isAbsolute, join, posix, resolve, win32 } from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { UsageError } from "@mizchi/vlmkit-judge/errors.ts";
7
+ import { copyFile, mkdir, mkdtemp, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
8
+ import { spawn } from "node:child_process";
9
+ import { hostname } from "node:os";
10
+ import { WINDOW_MS } from "@mizchi/vlmkit-judge/flash.ts";
11
+ import { FRAMES_FORMAT, frameFileName } from "@mizchi/vlmkit-judge/frames.ts";
12
+ // src/video-decode.ts
13
+ /**
14
+ * Decode a recording into a `vlmkit-frames/1` sequence with the user's own ffmpeg and ffprobe.
15
+ *
16
+ * vlmkit ships, depends on and downloads no decoder: the ffmpeg builds on npm are GPL and pull an
17
+ * 80 MB binary, and Playwright's private one decodes VP8 and MJPEG only. The binary is the user's
18
+ * (`--ffmpeg`, `VLMKIT_FFMPEG`, else `ffmpeg` on PATH; ffprobe beside it), spawned as a separate
19
+ * process with arguments, never a shell. Another decoder can write numbered PNGs and a timestamp
20
+ * per line instead, which `importFrames` reads.
21
+ *
22
+ * What is measured rather than trusted (`video-frames.ts` holds the arithmetic):
23
+ * - The frame table comes from ffprobe's decoded frames (`best_effort_timestamp`, which ffmpeg
24
+ * itself gives a decoded frame as its pts), and every frame ffmpeg writes is checked against it
25
+ * through `showinfo`: same count, same timestamp. Frames are chosen by their index in that
26
+ * table (`select`), never by `-ss`, which takes the frame after a time where a player shows the
27
+ * one before it.
28
+ * - Colour goes through a conversion the stream states, or BT.601 limited when it states none
29
+ * (said so in the manifest), never the decoder's default.
30
+ * - Every frame is the same size, or the recording is refused.
31
+ */
32
+ /** Frame files are named `NNNN-…`: past 9999 a glob no longer sorts them in order. */
33
+ const MAX_SCAN_FRAMES = 9999;
34
+ /** Refused above this unless asked for: a minute at 60fps, already gigabytes of PNG at 1080p. */
35
+ const DEFAULT_MAX_FRAMES = 3600;
36
+ /** File extensions `check flash` reads as a recording rather than a page. */
37
+ const VIDEO_EXTENSIONS = /* @__PURE__ */ new Set([
38
+ ".mp4",
39
+ ".m4v",
40
+ ".mov",
41
+ ".qt",
42
+ ".webm",
43
+ ".mkv",
44
+ ".avi",
45
+ ".ogv",
46
+ ".ts",
47
+ ".mts",
48
+ ".m2ts",
49
+ ".mpg",
50
+ ".mpeg",
51
+ ".flv",
52
+ ".wmv",
53
+ ".3gp",
54
+ ".y4m",
55
+ ".gif",
56
+ ".apng"
57
+ ]);
58
+ /** The path without a page's query or hash, when the path as written is not a file. */
59
+ const fileOf = (path) => existsSync(path) ? path : path.replace(/[?#].*$/, "");
60
+ /**
61
+ * Whether `check flash` reads a source as a recording: a local file with a video extension (a
62
+ * page's query or hash is not its extension: `player.html?clip=a.gif` is a page), or a `.png`
63
+ * that is an animated PNG — the APNG spec's own extension, which a page sweep would only report
64
+ * as an unmeasured animated image.
65
+ */
66
+ function isVideoFile(path) {
67
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) return false;
68
+ const file = fileOf(path);
69
+ const ext = extname(file).toLowerCase();
70
+ if (VIDEO_EXTENSIONS.has(ext)) return true;
71
+ if (ext !== ".png" || !existsSync(file)) return false;
72
+ try {
73
+ return (apngDeclaredFrames(file) ?? 0) > 1;
74
+ } catch {
75
+ return false;
76
+ }
77
+ }
78
+ /**
79
+ * An APNG's `acTL` num_frames, read by walking chunk headers (each body seeked over, not read):
80
+ * the spec puts `acTL` before the first `IDAT`, so a frame of any size before the second `fcTL`
81
+ * does not hide it. Null for a still PNG or anything that is not a PNG.
82
+ */
83
+ const apngDeclaredFramesSafe = (file) => {
84
+ try {
85
+ return apngDeclaredFrames(file);
86
+ } catch {
87
+ return null;
88
+ }
89
+ };
90
+ function apngDeclaredFrames(file) {
91
+ const fd = openSync(file, "r");
92
+ try {
93
+ const head = Buffer.alloc(8);
94
+ const read = (at, length) => readSync(fd, head, 0, length, at) === length;
95
+ if (!read(0, 8) || head.readUInt32BE(0) !== 2303741511 || head.readUInt32BE(4) !== 218765834) return null;
96
+ let at = 8;
97
+ for (let chunks = 0; chunks < 1e5 && read(at, 8); chunks++) {
98
+ const length = head.readUInt32BE(0);
99
+ const type = head.toString("latin1", 4, 8);
100
+ if (type === "acTL") return length >= 8 && read(at + 8, 4) ? head.readUInt32BE(0) : null;
101
+ if (type === "IDAT" || type === "IEND") return null;
102
+ at += 12 + length;
103
+ }
104
+ return null;
105
+ } finally {
106
+ closeSync(fd);
107
+ }
108
+ }
109
+ /** ffmpeg colours its log when told to (`AV_LOG_FORCE_COLOR`); the escapes split a showinfo line. */
110
+ const ANSI = /\x1b\[[0-9;]*m/g;
111
+ /**
112
+ * The decoders still running, killed if vlmkit is: an orphaned ffmpeg kept writing gigabytes. The
113
+ * listeners are there only while one runs: a listener takes away a signal's default action, and a
114
+ * judge that holds the event loop for a minute then ignored Ctrl-C for that minute (measured).
115
+ */
116
+ const children = /* @__PURE__ */ new Set();
117
+ const SIGNALS = [
118
+ "SIGINT",
119
+ "SIGTERM",
120
+ "SIGHUP"
121
+ ];
122
+ const onSignal = (signal) => {
123
+ for (const child of children) child.kill("SIGKILL");
124
+ children.clear();
125
+ for (const s of SIGNALS) process.removeListener(s, onSignal);
126
+ process.kill(process.pid, signal);
127
+ };
128
+ function track(child) {
129
+ if (children.size === 0) for (const s of SIGNALS) process.on(s, onSignal);
130
+ children.add(child);
131
+ }
132
+ function untrack(child) {
133
+ if (!children.delete(child)) return;
134
+ if (children.size === 0) for (const s of SIGNALS) process.removeListener(s, onSignal);
135
+ }
136
+ /** Run a binary with arguments (no shell); stderr is handed over line by line as it comes. */
137
+ function run(bin, args, onLine) {
138
+ return new Promise((resolvePromise, reject) => {
139
+ const child = spawn(bin, args, {
140
+ stdio: [
141
+ "ignore",
142
+ "pipe",
143
+ "pipe"
144
+ ],
145
+ env: {
146
+ ...process.env,
147
+ AV_LOG_FORCE_NOCOLOR: "1"
148
+ }
149
+ });
150
+ track(child);
151
+ const out = [];
152
+ const tail = [];
153
+ let partial = "";
154
+ const line = (raw) => {
155
+ const text = raw.replace(ANSI, "");
156
+ onLine?.(text);
157
+ tail.push(text);
158
+ if (tail.length > 40) tail.shift();
159
+ };
160
+ child.stdout.on("data", (chunk) => out.push(chunk));
161
+ child.stderr.setEncoding("utf8");
162
+ child.stderr.on("data", (chunk) => {
163
+ const lines = (partial + chunk).split(/\r?\n/);
164
+ partial = lines.pop() ?? "";
165
+ for (const l of lines) line(l);
166
+ });
167
+ child.on("error", (error) => {
168
+ untrack(child);
169
+ reject(error);
170
+ });
171
+ child.on("close", (code) => {
172
+ untrack(child);
173
+ if (partial) line(partial);
174
+ resolvePromise({
175
+ code,
176
+ stdout: Buffer.concat(out).toString("utf8"),
177
+ stderr: tail
178
+ });
179
+ });
180
+ });
181
+ }
182
+ const NO_DECODER = "vlmkit ships no video decoder: scan video and check flash on a recording run your own ffmpeg and ffprobe, 5.1 or later. Install them (apt install ffmpeg, brew install ffmpeg, https://ffmpeg.org/download.html) or point at them with --ffmpeg /path/to/ffmpeg (ffprobe is looked for beside it) or VLMKIT_FFMPEG / VLMKIT_FFPROBE. Any other decoder works too: write the frames as numbered PNGs and one timestamp per line, then vlmkit scan video <dir> --pts <file>";
183
+ function spawnFailure(error, bin, role) {
184
+ const code = error.code;
185
+ if (code === "ENOENT") throw new UsageError(`${role} not found ("${bin}"). ${NO_DECODER}`);
186
+ if (code === "EACCES") throw new UsageError(`${role} "${bin}" is not executable. ${NO_DECODER}`);
187
+ if (code === "EINVAL") throw new UsageError(`${role} "${bin}" cannot be run without a shell (a .bat or .cmd shim?): point at the .exe. ${NO_DECODER}`);
188
+ throw error;
189
+ }
190
+ const isPath = (bin) => bin.includes("/") || bin.includes("\\");
191
+ /**
192
+ * A bare name resolved on PATH, never in the working directory: Windows' own search tries the
193
+ * current directory first, so an `ffmpeg.exe` dropped beside a folder of recordings would run. Only
194
+ * absolute entries are searched (`.`, `./`, `bin` are the working directory), and only what a spawn
195
+ * without a shell can run: on POSIX an executable file (a non-executable one is skipped, as execvp
196
+ * skips it), on Windows the `.com` / `.exe` libuv runs (not an extensionless npm shim, not a
197
+ * `.bat`), with a quoted entry unquoted. The path returned is absolute, so nothing searches again.
198
+ */
199
+ function onPath(name, env, platform = process.platform) {
200
+ const win = platform === "win32";
201
+ const sep = win ? ";" : ":";
202
+ const exts = win ? /\.[^.\\/]+$/.test(name) ? [""] : [".com", ".exe"] : [""];
203
+ const absolute = win ? win32.isAbsolute : posix.isAbsolute;
204
+ for (const raw of (env.PATH ?? env.Path ?? "").split(sep)) {
205
+ const dir = win ? raw.replace(/^"(.*)"$/, "$1") : raw;
206
+ if (!dir || !absolute(dir)) continue;
207
+ for (const ext of exts) {
208
+ const candidate = join(dir, name + ext);
209
+ try {
210
+ if (!statSync(candidate).isFile()) continue;
211
+ if (!win) accessSync(candidate, constants.X_OK);
212
+ return candidate;
213
+ } catch {}
214
+ }
215
+ }
216
+ return null;
217
+ }
218
+ /** The ffprobe that goes with an ffmpeg given as a path: beside it as given, then beside what a symlink points to. */
219
+ function siblingProbe(ffmpeg) {
220
+ if (!isPath(ffmpeg)) return null;
221
+ const candidates = [ffmpeg];
222
+ try {
223
+ candidates.push(realpathSync(ffmpeg));
224
+ } catch {}
225
+ for (const bin of candidates) {
226
+ const name = basename(bin);
227
+ if (!/ffmpeg/i.test(name)) continue;
228
+ const probe = join(dirname(bin), name.replace(/ffmpeg/i, (m) => m === "FFMPEG" ? "FFPROBE" : "ffprobe"));
229
+ for (const p of [probe, `${probe}.exe`]) if (existsSync(p)) return p;
230
+ }
231
+ return null;
232
+ }
233
+ /** The oldest ffmpeg whose options this uses (`-fps_mode` is 5.1's). */
234
+ const MIN_VERSION = [5, 1];
235
+ /** Find the user's ffmpeg and ffprobe and ask ffmpeg its version. Throws a UsageError naming the remedy. */
236
+ async function findDecoder(paths = {}) {
237
+ const env = paths.env ?? process.env;
238
+ const given = (v) => v === void 0 || v === "" ? void 0 : v;
239
+ const resolveBin = (bin, role) => {
240
+ if (isPath(bin)) return bin;
241
+ const found = onPath(bin, env);
242
+ if (!found) throw new UsageError(`${role} not found on PATH ("${bin}"). ${NO_DECODER}`);
243
+ return found;
244
+ };
245
+ const ffmpeg = resolveBin(given(paths.ffmpeg) ?? given(env.VLMKIT_FFMPEG) ?? "ffmpeg", "ffmpeg");
246
+ const version = await run(ffmpeg, ["-hide_banner", "-version"]).catch((e) => spawnFailure(e, ffmpeg, "ffmpeg"));
247
+ const named = version.stdout.match(/^ffmpeg version (\S+)/m);
248
+ if (version.code !== 0 || !named) throw new UsageError(`"${ffmpeg}" did not answer -version as ffmpeg does. ${NO_DECODER}`);
249
+ const numeric = named[1].match(/^n?(\d+)\.(\d+)/);
250
+ if (numeric) {
251
+ const [major, minor] = [Number(numeric[1]), Number(numeric[2])];
252
+ if (major < MIN_VERSION[0] || major === MIN_VERSION[0] && minor < MIN_VERSION[1]) throw new UsageError(`ffmpeg ${named[1]} is too old: scan video needs ${MIN_VERSION.join(".")} or later (-fps_mode passthrough, which keeps every frame, is 5.1's). ${NO_DECODER}`);
253
+ }
254
+ const ffprobe = resolveBin(given(paths.ffprobe) ?? given(env.VLMKIT_FFPROBE) ?? siblingProbe(ffmpeg) ?? "ffprobe", "ffprobe");
255
+ const probe = await run(ffprobe, ["-hide_banner", "-version"]).catch((e) => spawnFailure(e, ffprobe, "ffprobe"));
256
+ if (probe.code !== 0 || !/^ffprobe version /m.test(probe.stdout)) throw new UsageError(`"${ffprobe}" did not answer -version as ffprobe does. ${NO_DECODER}`);
257
+ return {
258
+ ffmpeg,
259
+ ffprobe,
260
+ name: `ffmpeg ${named[1]}`
261
+ };
262
+ }
263
+ /** The decoder's own words for why it failed: its last lines that are not progress noise. */
264
+ const reason = (stderr) => stderr.map((l) => l.replace(/^(\[[^\]]* @ [^\]]*\] )?\[(info|warning|error|fatal|panic|verbose)\] /, "$1")).filter((l) => l.trim() && !/showinfo|^\s*(frame=|Stream mapping|Press \[q\])/.test(l)).slice(-4).join(" | ").trim() || "no message";
265
+ /** `file:` keeps a path with a colon (`a:b.mp4`) or a leading `-` from being read as a protocol or an option. */
266
+ const asInput = (absolute) => `file:${absolute}`;
267
+ /** `rec.mp4.frames/` beside the recording: the extension stays, so `clip.mp4` and `clip.webm` do not share one. */
268
+ const defaultFramesDir = (file) => `${resolve(file)}.frames`;
269
+ /** What a previous scan wrote, so a re-run replaces it and leaves anything else in the directory. */
270
+ const OWN_FRAME = /^\d{4,}-t\d+\.png$/;
271
+ const WORK_DIR = /^\.scan-video-/;
272
+ /**
273
+ * Before writing into `dir`: refuse a directory that holds another tool's sequence (its
274
+ * `frames.json` and frames would be replaced), and remove the work directories an interrupted
275
+ * run left behind.
276
+ */
277
+ async function prepareOut(dir) {
278
+ const manifest = join(dir, "frames.json");
279
+ if (existsSync(manifest)) {
280
+ let tool;
281
+ try {
282
+ tool = JSON.parse(readFileSync(manifest, "utf8")).source?.tool;
283
+ } catch {
284
+ tool = void 0;
285
+ }
286
+ if (tool !== "scan video") throw new UsageError(`${dir} holds another sequence (${typeof tool === "string" ? tool : "a frames.json scan video did not write"}): give scan video a directory of its own with --out`);
287
+ }
288
+ for (const name of await readdir(dir)) if (WORK_DIR.test(name)) await rm(join(dir, name), {
289
+ recursive: true,
290
+ force: true
291
+ });
292
+ }
293
+ /** Once the new frames are decoded and checked: the previous scan's frames and manifest, never the recording. */
294
+ async function clearPrevious(dir, keep) {
295
+ const kept = realpathSync(keep);
296
+ for (const name of await readdir(dir)) {
297
+ const path = join(dir, name);
298
+ if (!(OWN_FRAME.test(name) || name === "frames.json")) continue;
299
+ if (realpathSync(path) !== kept) await unlink(path);
300
+ }
301
+ }
302
+ const LOCK = ".scan-video.lock";
303
+ /** A lock or temporary directory whose owner cannot be seen is taken as abandoned only this old. */
304
+ const STALE_UNKNOWN_MS = 864e5;
305
+ /** Whether pid is a process this one can see. */
306
+ const alive = (pid) => {
307
+ try {
308
+ process.kill(pid, 0);
309
+ return true;
310
+ } catch (error) {
311
+ return error.code === "EPERM";
312
+ }
313
+ };
314
+ /**
315
+ * Which pids `alive` can judge: this host and PID namespace. A pid from a container sharing the
316
+ * directory, or from `unshare`, reads as dead here (measured: a sandboxed run removed a live
317
+ * one's frames), so an owner of another identity is never taken as gone by its pid.
318
+ */
319
+ function processIdentity() {
320
+ let ns = "";
321
+ try {
322
+ ns = readlinkSync("/proc/self/ns/pid");
323
+ } catch {}
324
+ let h = 2166136261;
325
+ for (const c of `${hostname()}|${ns}`) h = Math.imul(h ^ c.charCodeAt(0), 16777619) >>> 0;
326
+ return h.toString(16).padStart(8, "0");
327
+ }
328
+ /** The output directories this process is scanning into now: a second scan here is refused, not let in. */
329
+ const heldLocks = /* @__PURE__ */ new Set();
330
+ /**
331
+ * Make `outDir` this scan's: a directory (refused when the path is a file), not another tool's
332
+ * sequence, not the place a frame's name would land on the recording itself (renamed over it,
333
+ * measured: an APNG named `0000-t000000.png` scanned into its own directory became frame 0), and
334
+ * not another live scan's — a lock file names the scan writing there, and one whose process is
335
+ * gone is taken over, with the work directories it left.
336
+ */
337
+ async function claimOut(outDir, file, shown) {
338
+ try {
339
+ if (existsSync(outDir) && !statSync(outDir).isDirectory()) throw new UsageError(`--out ${outDir} is a file, not a directory`);
340
+ await mkdir(outDir, { recursive: true });
341
+ } catch (error) {
342
+ if (error instanceof UsageError) throw error;
343
+ const code = error.code;
344
+ if (code === "EEXIST" || code === "ENOTDIR" || code === "EACCES") throw new UsageError(`cannot make the frames directory ${outDir} (${code}): give --out a directory`);
345
+ throw error;
346
+ }
347
+ const out = realpathSync(outDir);
348
+ for (const path of [file, realpathSync(file)]) {
349
+ const name = basename(path);
350
+ if (realpathSync(dirname(path)) === out && (OWN_FRAME.test(name) || name === "frames.json" || name === LOCK || WORK_DIR.test(name))) throw new UsageError(`${shown} is ${path === file ? "" : `a link to ${path}, `}named like a file scan video writes or clears in ${outDir} (${name}): it would be replaced. Rename it, or give --out another directory`);
351
+ }
352
+ const lockPath = join(out, LOCK);
353
+ if (heldLocks.has(lockPath)) throw new UsageError(`another scan in this process is writing into ${outDir}: wait for it, or give --out another directory`);
354
+ heldLocks.add(lockPath);
355
+ const id = processIdentity();
356
+ try {
357
+ for (let attempt = 0;; attempt++) try {
358
+ await writeFile(lockPath, `${JSON.stringify({
359
+ pid: process.pid,
360
+ id
361
+ })}\n`, { flag: "wx" });
362
+ break;
363
+ } catch (error) {
364
+ if (error.code !== "EEXIST" || attempt > 0) throw error;
365
+ let owner = {};
366
+ try {
367
+ owner = JSON.parse(readFileSync(lockPath, "utf8"));
368
+ } catch {}
369
+ const pid = typeof owner.pid === "number" ? owner.pid : NaN;
370
+ const ours = owner.id === id;
371
+ const old = Date.now() - statSync(lockPath).mtimeMs > STALE_UNKNOWN_MS;
372
+ if (ours ? pid !== process.pid && alive(pid) : !old) throw new UsageError(ours ? `another scan (pid ${pid}) is writing into ${outDir}: wait for it, or give --out another directory` : `a scan from another host or container may be writing into ${outDir} (${lockPath}): wait for it, or remove that file if none runs`);
373
+ await rm(lockPath, { force: true });
374
+ }
375
+ } catch (error) {
376
+ heldLocks.delete(lockPath);
377
+ throw error;
378
+ }
379
+ const release = async () => {
380
+ heldLocks.delete(lockPath);
381
+ await rm(lockPath, { force: true });
382
+ };
383
+ try {
384
+ await prepareOut(outDir);
385
+ } catch (error) {
386
+ await release();
387
+ throw error;
388
+ }
389
+ return { release };
390
+ }
391
+ /** The `select` expression for the decoded frames kept (sorted): runs of consecutive indices become `between`. */
392
+ function selectExpression(decoded, total) {
393
+ if (decoded.length === total) return null;
394
+ const runs = [];
395
+ for (const d of decoded) {
396
+ const last = runs[runs.length - 1];
397
+ if (last && d === last[1] + 1) last[1] = d;
398
+ else runs.push([d, d]);
399
+ }
400
+ return `select='${runs.map(([a, b]) => a === b ? `eq(n,${a})` : `between(n,${a},${b})`).join("+")}'`;
401
+ }
402
+ const label = (instants, atMs) => {
403
+ if (!instants) return void 0;
404
+ const fmt = (t) => `${Number(t.toFixed(3))}ms`;
405
+ return instants.length === 1 && Math.abs(instants[0] - atMs) < 1e-6 ? void 0 : `at ${instants.map(fmt).join(", ")}`;
406
+ };
407
+ /**
408
+ * The lines ffmpeg logged at error level or worse (`-loglevel level+info` tags each line), from the
409
+ * input's side — the demuxer and the decoder — not the PNG writer's: it exits 0 on a truncated
410
+ * file. By level, not by wording: Matroska says `File ended prematurely` and HEVC `The cu_qp_delta
411
+ * 80 is outside the valid range`, which no keyword list held, and a title with "corrupt" in it is
412
+ * metadata at info level.
413
+ */
414
+ function decodeErrors(lines) {
415
+ const out = /* @__PURE__ */ new Set();
416
+ for (const line of lines) {
417
+ const m = line.match(/^(?:\[([^\]]*?) @ (?:0x)?[0-9a-fA-F]+\] )?\[(warning|error|fatal|panic)\] (.*)$/);
418
+ if (!m) continue;
419
+ const context = m[1] ?? "";
420
+ if (/^(png|image2|out#|Parsed_|auto_scale|swscaler|graph )/.test(context) || /showinfo/.test(context)) continue;
421
+ if (m[2] === "warning" && !CORRUPT_PACKET.test(m[3])) continue;
422
+ out.add(`${context ? `${context}: ` : ""}${m[3].trim()}`);
423
+ }
424
+ return [...out];
425
+ }
426
+ /** A lost or damaged packet: frames may be missing between the ones decoded. */
427
+ const CORRUPT_PACKET = /packet corrupt|corrupt (input )?packet|corrupt decoded frame/i;
428
+ /**
429
+ * Decode `file` with the user's ffmpeg into `out` (`NNNN-t<ms>.png` + `frames.json`). Refuses
430
+ * (UsageError) a file with no video stream, an HDR one, one that decodes to frames of more than one
431
+ * size, more frames than `maxFrames`, and anything the decoder itself cannot read — never a
432
+ * sequence of black frames standing for a picture that was not decoded.
433
+ */
434
+ async function scanVideo(options) {
435
+ const file = resolve(options.file);
436
+ const shown = options.file;
437
+ if (!existsSync(file)) throw new UsageError(`no such recording: ${shown}`);
438
+ if ((await stat(file)).isDirectory()) throw new UsageError(`${shown} is a directory: to read frames another decoder wrote, give --pts or --fps`);
439
+ const outDir = resolve(options.out ?? defaultFramesDir(file));
440
+ for (let dir = outDir;; dir = dirname(dir)) {
441
+ if (existsSync(dir)) {
442
+ if (!statSync(dir).isDirectory()) throw new UsageError(`the frames directory ${outDir} cannot be made: ${dir} is a file. Give --out a directory`);
443
+ break;
444
+ }
445
+ if (dirname(dir) === dir) break;
446
+ }
447
+ const maxFrames = options.maxFrames ?? 3600;
448
+ if (!(Number.isSafeInteger(maxFrames) && maxFrames >= 1 && maxFrames <= 9999)) throw new UsageError(`--max-frames is 1 to ${MAX_SCAN_FRAMES} (frame files are numbered in four digits)`);
449
+ const decoder = await findDecoder(options);
450
+ const t0 = performance.now();
451
+ const demuxer = (apngDeclaredFramesSafe(file) ?? 0) > 1 ? ["-f", "apng"] : [];
452
+ const probed = await run(decoder.ffprobe, [
453
+ "-v",
454
+ "error",
455
+ "-show_streams",
456
+ "-show_format",
457
+ "-of",
458
+ "json",
459
+ ...demuxer,
460
+ asInput(file)
461
+ ]).catch((e) => spawnFailure(e, decoder.ffprobe, "ffprobe"));
462
+ if (probed.code !== 0) throw new UsageError(`${decoder.ffprobe} cannot read ${shown} as a video container: ${reason(probed.stderr)}`);
463
+ const stream = pickVideoStream(probed.stdout, shown, options.stream);
464
+ const plan = colorPlan(stream, shown, {
465
+ ...options.colorMatrix !== void 0 ? { matrix: options.colorMatrix } : {},
466
+ ...options.colorRange !== void 0 ? { range: options.colorRange } : {}
467
+ });
468
+ const table = await run(decoder.ffprobe, [
469
+ "-v",
470
+ "error",
471
+ "-select_streams",
472
+ String(stream.index),
473
+ "-show_entries",
474
+ "frame=best_effort_timestamp,pts,duration,key_frame,pkt_pos,interlaced_frame,top_field_first,width,height",
475
+ "-of",
476
+ "json",
477
+ ...demuxer,
478
+ asInput(file)
479
+ ]).catch((e) => spawnFailure(e, decoder.ffprobe, "ffprobe"));
480
+ if (table.code !== 0) throw new UsageError(`${decoder.ffprobe} cannot decode ${shown} (${stream.codec}): ${reason(table.stderr)}. Decode it with a build that can, or convert it first: ffmpeg -i ${shown} -c:v ffv1 lossless.mkv`);
481
+ const probedFrames = parseFrameTable(table.stdout, shown);
482
+ const sized = probedFrames.find((f) => f.width !== void 0);
483
+ const resized = sized && probedFrames.find((f) => f.width !== void 0 && (f.width !== sized.width || f.height !== sized.height));
484
+ if (sized && resized) throw new UsageError(`${shown} changes size mid-stream (${sized.width}x${sized.height}, then ${resized.width}x${resized.height} at decoded frame ${resized.index}): a frame sequence has one size. Scale it to one first: ffmpeg -i in -vf scale=W:H out.mkv`);
485
+ const notes = [...plan.notes];
486
+ const sampleAspect = stream.codec === "gif" || stream.codec === "apng" ? void 0 : stream.sampleAspect;
487
+ const image = stream.codec === "gif" || stream.codec === "apng" ? imageTiming(readFileSync(file)) : null;
488
+ const asked = options.selection ?? { kind: "all" };
489
+ const passMs = image ? image.storedMs.map(browserDelayMs).reduce((a, b) => a + b, 0) : 0;
490
+ const until = asked.kind === "span" ? asked.toMs ?? asked.fromMs + passMs + WINDOW_MS : asked.kind === "at" ? Math.max(...asked.atMs) : void 0;
491
+ const importRecipe = image ? `Write every image composited as a browser shows it and import them: magick ${shown} -coalesce -background white -alpha remove frames/%06d.png; magick identify -format "%T\\n" ${shown} | awk '{printf "%.3f\\n", t/1000; d=$1*10; t+=(d<=10?100:d)} END {printf "%.3f\\n", t/1000}' > frames/pts.txt; vlmkit scan video frames --pts frames/pts.txt --lossless --every-frame --loop ${image.plays === null ? "forever" : image.plays}` : "";
492
+ const compositing = image ? gifCompositingProblem(image) : null;
493
+ if (compositing) throw new UsageError(`${shown}: ${compositing}. ${importRecipe}`);
494
+ const imageLine = image ? imageTimeline(probedFrames, image, until) : null;
495
+ if (image && !imageLine) throw new UsageError(image.format === "apng" ? `${shown}: its acTL declares ${image.declaredFrames} frame(s), it holds ${image.storedMs.length} fcTL and ffmpeg decoded ${probedFrames.length}: which a browser plays is not known. Re-save it with one tool (e.g. apngasm) and scan that` : `${shown}: ffmpeg decoded ${probedFrames.length} of the ${image.storedMs.length} images a browser shows (a GIF image with no graphic control extension is merged into the one before). ${importRecipe}`);
496
+ if (image?.declaredFrames !== void 0 && image.declaredFrames < probedFrames.length) notes.push(`its acTL declares ${image.declaredFrames} of the ${probedFrames.length} frames it holds: a browser plays the ${image.declaredFrames} declared, and so does this`);
497
+ const fieldPlan = image ? null : fieldSplit(probedFrames, stream);
498
+ if (fieldPlan?.note) notes.push(fieldPlan.note);
499
+ const split = fieldPlan?.split;
500
+ const timeline = imageLine ?? videoTimeline(probedFrames, stream.timeBase, shown, split ? { split } : {});
501
+ const rotate = timeline.fields ? rotationFilters(stream) : [];
502
+ if (rotate === null) throw new UsageError(`${shown} is interlaced and turned by ${stream.rotation}°, not a quarter turn: its fields cannot be split before it is turned. Scan it unturned (ffmpeg -display_rotation 0 -i ${shown} -c copy unturned.mkv) or deinterlace it first`);
503
+ if (stream.rotation !== void 0 && stream.rotation % 90 !== 0) notes.push(`rotated by ${stream.rotation}°, not a quarter turn: ffmpeg turns it with black corners`);
504
+ if (probedFrames.length === 1 && !image) notes.push(`stream #${stream.index} decodes to one frame: a still or a cover track (--stream picks another)`);
505
+ const background = options.background ?? "white";
506
+ if (stream.alpha) notes.push(`transparent pixels composited over ${background} (--background): the page behind them is not known, and dropping alpha shows whatever colour sits under them`);
507
+ const rows = timeline.rows;
508
+ const statedEnd = !image && stream.durationMs !== void 0 && (stream.startMs ?? 0) >= 0 ? (stream.startMs ?? 0) + stream.durationMs : void 0;
509
+ const framesEnd = recordingEndMs(rows, timeline.endMs);
510
+ const tableErrors = table.stderr.some((l) => l.trim() !== "");
511
+ const gapBefore = rows.length > 1 ? rows[rows.length - 1].atMs - rows[rows.length - 2].atMs : 0;
512
+ const endsShort = statedEnd !== void 0 && framesEnd < statedEnd - Math.max(500, 2 * gapBefore);
513
+ const endMs = image ? until : tableErrors ? framesEnd : Math.max(framesEnd, statedEnd ?? 0);
514
+ const spanEnd = (toMs, fromMs) => Math.max(fromMs, Math.min(toMs ?? Number.POSITIVE_INFINITY, endMs));
515
+ const request = asked.kind === "span" && image && asked.toMs === void 0 ? {
516
+ ...asked,
517
+ toMs: until
518
+ } : asked;
519
+ const chosen = chooseFrames(rows, request, image ? timeline.endMs : endMs);
520
+ const selection = asked.kind === "span" ? {
521
+ kind: "span",
522
+ fromMs: asked.fromMs,
523
+ toMs: spanEnd(asked.toMs, asked.fromMs),
524
+ ...asked.leadInMs !== void 0 ? { leadInMs: asked.leadInMs } : {}
525
+ } : asked;
526
+ if (chosen.length > maxFrames) throw new UsageError(`${shown}: ${chosen.length} frames to write, over --max-frames ${maxFrames}. Choose a span (--from / --to), instants (--at), or raise --max-frames (up to 9999).`);
527
+ const decodedOf = (f) => f.decoded ?? f.index;
528
+ const needed = [...new Set(chosen.map(decodedOf))].sort((a, b) => a - b);
529
+ const isSplit = (d) => timeline.fields === true && split?.(probedFrames[d]) === true;
530
+ const graphs = [{
531
+ name: "fields",
532
+ split: true,
533
+ decoded: needed.filter(isSplit)
534
+ }, {
535
+ name: "frames",
536
+ split: false,
537
+ decoded: needed.filter((d) => !isSplit(d))
538
+ }].filter((g) => g.decoded.length > 0);
539
+ const probeMs = performance.now() - t0;
540
+ const lock = await claimOut(outDir, file, shown);
541
+ let work = "";
542
+ const t1 = performance.now();
543
+ try {
544
+ work = await mkdtemp(join(outDir, ".scan-video-"));
545
+ const outputs = [];
546
+ for (const g of graphs) {
547
+ await mkdir(join(work, g.name));
548
+ const output = [];
549
+ outputs.push(output);
550
+ output.push("-map", `0:${stream.index}`, "-an", "-sn", "-dn", "-fps_mode", "passthrough", "-vf", filterChain({
551
+ select: selectExpression(g.decoded, probedFrames.length),
552
+ fields: g.split,
553
+ ...g.split && fieldPlan?.order ? { fieldOrder: fieldPlan.order } : {},
554
+ ...!g.split && fieldPlan?.lineDouble ? { lineDouble: true } : {},
555
+ ...rotate.length > 0 ? { rotate } : {},
556
+ color: plan,
557
+ ...stream.alpha ? { alpha: { background } } : {},
558
+ sampleAspect: sampleAspect !== void 0,
559
+ name: g.name
560
+ }), "-c:v", "png", "-pred", "none", "-compression_level", "1", "-start_number", "0", "-f", "image2", join(work, g.name, "%06d.png").replace(/%(?!06d\.png$)/g, "%%"));
561
+ }
562
+ const written = new Map(graphs.map((g) => [g.name, []]));
563
+ const showTimeBase = /* @__PURE__ */ new Map();
564
+ const stderrAll = [];
565
+ for (const [gi, g] of graphs.entries()) {
566
+ const decoded = await run(decoder.ffmpeg, [
567
+ "-hide_banner",
568
+ "-nostdin",
569
+ "-nostats",
570
+ "-loglevel",
571
+ "level+info",
572
+ "-sws_flags",
573
+ "accurate_rnd+full_chroma_int",
574
+ "-copyts",
575
+ ...stream.alpha === "libvpx" || stream.alpha === "libvpx-vp9" ? ["-c:v", stream.alpha] : [],
576
+ "-reinit_filter",
577
+ "0",
578
+ ...rotate.length > 0 ? ["-noautorotate"] : [],
579
+ ...demuxer,
580
+ "-i",
581
+ asInput(file),
582
+ ...outputs[gi]
583
+ ], (line) => {
584
+ stderrAll.push(line);
585
+ const parsed = parseShowinfoLine(line);
586
+ if (!parsed) return;
587
+ const name = ("timeBase" in parsed ? parsed.instance : parsed.frame.instance) ?? g.name;
588
+ if ("timeBase" in parsed) {
589
+ if (!showTimeBase.has(name)) showTimeBase.set(name, parsed.timeBase);
590
+ } else written.get(name)?.push(parsed.frame);
591
+ }).catch((e) => spawnFailure(e, decoder.ffmpeg, "ffmpeg"));
592
+ if (decoded.code !== 0) {
593
+ const why = reason(decoded.stderr);
594
+ throw new UsageError(/Unknown decoder|Decoder .* not found/i.test(why) && stream.alpha?.startsWith("libvpx") ? `${shown}: its alpha decodes only with libvpx, which this ffmpeg lacks (${why}); use an ffmpeg built with libvpx` : `${decoder.ffmpeg} cannot decode ${shown} (${stream.codec}): ${why}`);
595
+ }
596
+ }
597
+ for (const g of graphs) checkWritten(written.get(g.name), showTimeBase.get(g.name) ?? null, g.decoded.map((d) => probedFrames[d]), g.split ? 2 : 1, stream, shown);
598
+ const all = graphs.flatMap((g) => written.get(g.name));
599
+ const size = {
600
+ width: all[0].width,
601
+ height: all[0].height
602
+ };
603
+ const odd = all.find((f) => f.width !== size.width || f.height !== size.height);
604
+ if (odd) throw new UsageError(`${shown} changes size mid-stream (${size.width}x${size.height}, then ${odd.width}x${odd.height}): a frame sequence has one size. Scale it to one first: ffmpeg -i in -vf scale=W:H out.mkv`);
605
+ const geometry = displayGeometry(size, options.displayWidth);
606
+ await clearPrevious(outDir, file);
607
+ const position = new Map(graphs.flatMap((g) => g.decoded.map((d, k) => [d, k])));
608
+ const workFile = (f) => {
609
+ const d = decodedOf(f);
610
+ const fields = isSplit(d);
611
+ const at = position.get(d) * (fields ? 2 : 1) + (f.field ?? 0);
612
+ return join(work, fields ? "fields" : "frames", `${String(at).padStart(6, "0")}.png`);
613
+ };
614
+ const lastUse = /* @__PURE__ */ new Map();
615
+ chosen.forEach((f, n) => lastUse.set(workFile(f), n));
616
+ const firstParity = probedFrames[0].topFieldFirst === true;
617
+ const fieldOfPicture = (f) => fieldPlan?.lineDouble ? probedFrames[decodedOf(f)].topFieldFirst === true === firstParity ? 0 : 1 : void 0;
618
+ const frames = [];
619
+ for (const [n, f] of chosen.entries()) {
620
+ const name = frameFileName(n, f.atMs);
621
+ const from = workFile(f);
622
+ if (lastUse.get(from) === n) await rename(from, join(outDir, name));
623
+ else await copyFile(from, join(outDir, name));
624
+ const l = label(f.instants, f.atMs);
625
+ frames.push({
626
+ n,
627
+ file: name,
628
+ atMs: f.atMs,
629
+ stable: true,
630
+ index: f.index,
631
+ key: f.key,
632
+ ...f.gop !== void 0 ? { gop: f.gop } : {},
633
+ ...f.field !== void 0 ? { field: f.field } : fieldOfPicture(f) !== void 0 ? { field: fieldOfPicture(f) } : {},
634
+ ...l ? { label: l } : {}
635
+ });
636
+ }
637
+ const errors = [.../* @__PURE__ */ new Set([...table.stderr.map((l) => l.trim()).filter(Boolean), ...decodeErrors(stderrAll)])];
638
+ const cutShort = endsShort && errors.length > 0;
639
+ const damaged = cutShort || errors.some((l) => CORRUPT_PACKET.test(l));
640
+ if (cutShort) notes.push(`the stream says it runs to ${Number((statedEnd / 1e3).toFixed(3))}s, its frames end at ${Number((framesEnd / 1e3).toFixed(3))}s and the decoder reported errors: the file is cut short`);
641
+ else if (endsShort && !image) notes.push(`its last frame is held to the stream's stated end, ${Number((statedEnd / 1e3).toFixed(3))}s (the frames alone end at ${Number((framesEnd / 1e3).toFixed(3))}s)`);
642
+ const video = {
643
+ file: shown,
644
+ decoder: decoder.name,
645
+ codec: stream.codec,
646
+ lossless: LOSSLESS_CODECS.has(stream.codec),
647
+ streamFrames: rows.length,
648
+ selection,
649
+ color: plan.color,
650
+ pixelFormat: stream.pixelFormat,
651
+ ...timeline.hidden ? { hidden: timeline.hidden } : {},
652
+ ...timeline.timing ? { timing: timeline.timing } : {},
653
+ ...timeline.loop ? { loop: timeline.loop } : {},
654
+ ...timeline.fields || fieldPlan?.lineDouble ? { fields: true } : {},
655
+ ...stream.alpha ? { background } : {},
656
+ ...stream.rotation ? { rotation: stream.rotation } : {},
657
+ ...sampleAspect ? { sampleAspect } : {},
658
+ ...stream.fieldOrder ? { fieldOrder: stream.fieldOrder } : {},
659
+ ...notes.length ? { notes } : {},
660
+ ...errors.length ? { decodeErrors: errors.slice(0, 20) } : {},
661
+ ...damaged ? { damaged: true } : {},
662
+ stream: stream.index
663
+ };
664
+ const manifest = {
665
+ format: FRAMES_FORMAT,
666
+ source: {
667
+ tool: "scan video",
668
+ url: pathToFileURL(file).href,
669
+ ...geometry,
670
+ browser: decoder.name,
671
+ clock: "stream",
672
+ video
673
+ },
674
+ frames
675
+ };
676
+ const manifestPath = join(outDir, "frames.json");
677
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
678
+ return {
679
+ manifestPath,
680
+ manifest,
681
+ stream,
682
+ streamFrames: rows.length,
683
+ timingMs: {
684
+ probe: Math.round(probeMs),
685
+ decode: Math.round(performance.now() - t1)
686
+ }
687
+ };
688
+ } finally {
689
+ if (work) await rm(work, {
690
+ recursive: true,
691
+ force: true
692
+ });
693
+ await lock.release();
694
+ }
695
+ }
696
+ /** Codecs whose decoder flags each frame interlaced or progressive (0 is said, not left unsaid). */
697
+ const FRAME_FLAGGED_CODECS = /* @__PURE__ */ new Set([
698
+ "h264",
699
+ "hevc",
700
+ "mpeg2video",
701
+ "mpeg1video",
702
+ "mpeg4",
703
+ "vc1",
704
+ "wmv3",
705
+ "dvvideo",
706
+ "prores",
707
+ "dnxhd",
708
+ "ffv1"
709
+ ]);
710
+ /**
711
+ * Which decoded frames are two fields. The frames' own flag decides, per frame: a stream can start
712
+ * progressive and turn interlaced (a broadcast capture: 50 woven frames read as one still comb),
713
+ * and a container's field-order tag can sit over frames coded progressive (split, every 1px row
714
+ * of detail strobed at field rate). Only a codec whose frames carry no flag at all is split by the
715
+ * stream's tag.
716
+ */
717
+ function fieldSplit(frames, stream) {
718
+ const flagged = frames.filter((f) => f.interlaced).length;
719
+ if (stream.codec === "hevc" && flagged === frames.length) return {
720
+ lineDouble: true,
721
+ note: "HEVC field pictures: each decoded frame is one field, line-doubled to the picture's height, at the field rate"
722
+ };
723
+ const order = stream.fieldOrder ? ` (${stream.fieldOrder})` : "";
724
+ const how = "split into its two fields, line-doubled, at twice the frame rate (woven, a field-rate flicker is a still comb)";
725
+ if (flagged === frames.length) return {
726
+ split: () => true,
727
+ note: `interlaced${order}: each frame ${how}`
728
+ };
729
+ if (flagged > 0) return {
730
+ split: (f) => f.interlaced === true,
731
+ note: `${flagged} of ${frames.length} frames flagged interlaced: each ${how}; the progressive ones are one frame each`
732
+ };
733
+ if (!stream.fieldOrder) return {};
734
+ if (FRAME_FLAGGED_CODECS.has(stream.codec)) return { note: `the stream is tagged ${stream.fieldOrder}, but ${stream.codec} decodes every frame as progressive: not split` };
735
+ return {
736
+ split: () => true,
737
+ order: stream.fieldOrder === "bb" || stream.fieldOrder === "bt" ? "bff" : "tff",
738
+ note: `interlaced${order} by the stream's tag (${stream.codec} frames carry no flag of their own): each frame ${how}, ${stream.fieldOrder === "bb" || stream.fieldOrder === "bt" ? "bottom" : "top"} field first as tagged`
739
+ };
740
+ }
741
+ /**
742
+ * The frames ffmpeg wrote are the ones the table chose: as many, and each at its timestamp. With
743
+ * `-copyts` showinfo's pts is the decoder's own `best_effort_timestamp`, so a selection one frame
744
+ * off is caught even on a constant rate, where the spacing alone would agree. An interlaced frame
745
+ * is written as its two fields: the first at the frame's time, the second after it.
746
+ */
747
+ function checkWritten(written, timeBase, expected, perFrame, stream, shown) {
748
+ if (written.length !== expected.length * perFrame) throw new Error(`${shown}: ffmpeg wrote ${written.length} ${perFrame === 2 ? "fields" : "frames"} where ffprobe's table chose ${expected.length * perFrame}; the two decoders disagree about the stream`);
749
+ if (!timeBase) throw new Error(`${shown}: ffmpeg's showinfo printed no time base, so its frames cannot be checked`);
750
+ const tb = stream.timeBase;
751
+ const tolerance = Math.max(tb.num / tb.den, timeBase.num / timeBase.den) / 2 + 1e-9;
752
+ for (const [k, want] of expected.entries()) {
753
+ const got = written[k * perFrame].pts * timeBase.num / timeBase.den;
754
+ const at = want.ticks * tb.num / tb.den;
755
+ if (Math.abs(got - at) > tolerance) throw new Error(`${shown}: frame ${k} ffmpeg wrote is at ${got.toFixed(6)}s where ffprobe's table has decoded frame ${want.index} at ${at.toFixed(6)}s; the two decoders disagree`);
756
+ }
757
+ }
758
+ /** A PNG's size from its IHDR, without decoding it. */
759
+ function pngSize(path) {
760
+ const head = readFileSync(path).subarray(0, 24);
761
+ if (head.length < 24 || head.toString("latin1", 1, 4) !== "PNG" || head.toString("latin1", 12, 16) !== "IHDR") throw new UsageError(`${path} is not a PNG`);
762
+ return {
763
+ width: head.readUInt32BE(16),
764
+ height: head.readUInt32BE(20)
765
+ };
766
+ }
767
+ /** Timestamps from a sidecar: one number of seconds per line; ffprobe's csv may end each with a comma. */
768
+ function parsePtsFile(text, file) {
769
+ return parsePtsTable(text, file).seconds;
770
+ }
771
+ /**
772
+ * A timestamp file as ffprobe writes it with `-of csv=p=0`: a time per line (`best_effort_timestamp_time`),
773
+ * or `key_frame,best_effort_timestamp_time[,pkt_pos]` — ffprobe prints a section's fields in its own
774
+ * order, whatever order -show_entries names them in. Trailing commas (side data) are dropped. Every
775
+ * line has the same fields; without the flag there are no keyframes to know.
776
+ */
777
+ function parsePtsTable(text, file) {
778
+ const seconds = [];
779
+ const keys = [];
780
+ const pos = [];
781
+ let fields;
782
+ const number = /^-?\d+(\.\d+)?(e[-+]?\d+)?$/i;
783
+ for (const [i, raw] of text.split(/\r?\n/).entries()) {
784
+ const line = raw.trim().replace(/,+$/, "").trim();
785
+ if (!line) continue;
786
+ const parts = line.split(",").map((p) => p.trim());
787
+ const where = `${file}:${i + 1}`;
788
+ if (parts.length > 3) throw new UsageError(`${where}: "${raw.trim()}" has ${parts.length} fields, at most 3`);
789
+ if (fields !== void 0 && parts.length !== fields) throw new UsageError(`${where}: ${parts.length} field${parts.length === 1 ? "" : "s"}, the lines before have ${fields}`);
790
+ fields = parts.length;
791
+ const time = parts.length === 1 ? parts[0] : parts[1];
792
+ if (!number.test(time) || !Number.isFinite(Number(time))) throw new UsageError(`${where}: "${raw.trim()}" is not a timestamp in seconds` + (/N\/A/i.test(time) ? " (ffprobe prints N/A for pts_time on some streams; ask for best_effort_timestamp_time)" : ""));
793
+ seconds.push(Number(time));
794
+ if (parts.length > 1) {
795
+ if (parts[0] !== "0" && parts[0] !== "1") throw new UsageError(`${where}: "${parts[0]}" is not a keyframe flag (0 or 1, ffprobe's key_frame)`);
796
+ keys.push(parts[0] === "1");
797
+ }
798
+ if (parts.length > 2) {
799
+ const p = parts[2];
800
+ pos.push(/^\d+$/.test(p) ? Number(p) : void 0);
801
+ }
802
+ }
803
+ return {
804
+ seconds,
805
+ keys: fields !== void 0 && fields > 1 ? keys : null,
806
+ pos: fields === 3 ? pos : null
807
+ };
808
+ }
809
+ /** Turn a directory of decoded frames plus their timestamps into a `vlmkit-frames/1` sequence (`frames.json` in that directory). */
810
+ async function importFrames(options) {
811
+ const dir = resolve(options.dir);
812
+ if (options.pts === void 0 === (options.fps === void 0)) throw new UsageError("frames another decoder wrote need their times: give --pts <file> or --fps <rate>, one of them");
813
+ const existing = join(dir, "frames.json");
814
+ if (existsSync(existing)) {
815
+ let source;
816
+ try {
817
+ source = JSON.parse(readFileSync(existing, "utf8")).source;
818
+ } catch {
819
+ source = void 0;
820
+ }
821
+ if (source?.tool !== "scan video" || source.video?.decoder !== "import") {
822
+ const what = typeof source?.tool !== "string" ? "a frames.json scan video did not write" : source.tool === "scan video" ? "a recording scan video decoded" : source.tool;
823
+ throw new UsageError(`${options.dir} already holds a sequence (${what}); importing would replace its frames.json. Import a directory of the decoder's own frames`);
824
+ }
825
+ }
826
+ const names = (await readdir(dir)).filter((n) => /\.png$/i.test(n)).sort((a, b) => a.localeCompare(b, "en", { numeric: true }));
827
+ if (names.length === 0) throw new UsageError(`${options.dir} holds no PNG frames`);
828
+ if (names.length > 9999) throw new UsageError(`${options.dir}: ${names.length} frames, over ${MAX_SCAN_FRAMES}; import a shorter span`);
829
+ let seconds;
830
+ let keys = null;
831
+ let positions = null;
832
+ if (options.pts !== void 0) {
833
+ const ptsPath = isAbsolute(options.pts) ? options.pts : resolve(options.pts);
834
+ if (!existsSync(ptsPath)) throw new UsageError(`no such timestamp file: ${options.pts}`);
835
+ const table = parsePtsTable(readFileSync(ptsPath, "utf8"), options.pts);
836
+ seconds = table.seconds;
837
+ keys = table.keys;
838
+ positions = table.pos;
839
+ const want = names.length + (options.loop !== void 0 ? 1 : 0);
840
+ if (seconds.length !== want) throw new UsageError(`${options.pts} holds ${seconds.length} timestamps for ${names.length} PNGs in ${options.dir}: one per frame, in order` + (options.loop !== void 0 ? ", then the end of the pass (--loop)" : ""));
841
+ } else {
842
+ const fps = options.fps;
843
+ if (!(Number.isFinite(fps) && fps > 0)) throw new UsageError(`--fps is frames a second, above 0 (got ${fps})`);
844
+ seconds = names.map((_, i) => i / fps);
845
+ if (options.loop !== void 0) seconds.push(names.length / fps);
846
+ }
847
+ const passEnd = options.loop !== void 0 ? seconds.pop() : void 0;
848
+ if (passEnd !== void 0 && !(passEnd > seconds[seconds.length - 1])) throw new UsageError(`the pass's end (${passEnd}s, the timestamp file's last line) must come after its last frame`);
849
+ const shown = [];
850
+ let hidden = 0;
851
+ for (let i = 0; i < seconds.length; i++) {
852
+ const next = seconds[i + 1];
853
+ if (next !== void 0 && next < seconds[i]) throw new UsageError(`frame ${i + 1} (${names[i + 1]}) is shown before frame ${i}: timestamps ${seconds[i]}, ${next}`);
854
+ if (next !== void 0 && next === seconds[i]) hidden++;
855
+ else shown.push(i);
856
+ }
857
+ const size = pngSize(join(dir, names[0]));
858
+ for (const name of names) {
859
+ const s = pngSize(join(dir, name));
860
+ if (s.width !== size.width || s.height !== size.height) throw new UsageError(`${name} is ${s.width}x${s.height}, ${names[0]} is ${size.width}x${size.height}: a frame sequence has one size`);
861
+ }
862
+ const origin = Math.min(0, seconds[shown[0]] * 1e3);
863
+ const once = shown.map((i) => {
864
+ const atMs = seconds[i] * 1e3 - origin;
865
+ if (!Number.isFinite(atMs)) throw new UsageError(`${names[i]}'s timestamp ${seconds[i]}s is out of range`);
866
+ return {
867
+ file: names[i],
868
+ atMs
869
+ };
870
+ });
871
+ let loop;
872
+ let played = once;
873
+ if (passEnd !== void 0) {
874
+ const passMs = passEnd * 1e3 - origin - once[0].atMs;
875
+ const plays = options.loop ?? null;
876
+ if (plays !== null && !(Number.isSafeInteger(plays) && plays >= 1)) throw new UsageError(`--loop is how many times the animation plays, 1 or more, or forever (got ${plays})`);
877
+ const passes = plays ?? Math.ceil((passMs + WINDOW_MS) / passMs) + 1;
878
+ if (passes * once.length > 9999) throw new UsageError(`${options.dir}: ${passes} passes of ${once.length} frames is over ${MAX_SCAN_FRAMES} frames`);
879
+ played = [];
880
+ for (let p = 0; p < passes; p++) for (const f of once) played.push({
881
+ file: f.file,
882
+ atMs: f.atMs + p * passMs
883
+ });
884
+ loop = {
885
+ plays,
886
+ passFrames: once.length,
887
+ passMs,
888
+ passes
889
+ };
890
+ }
891
+ const gops = keys && passEnd === void 0 ? gopNumbers(seconds.map((_, i) => ({
892
+ index: i,
893
+ ticks: i,
894
+ key: keys[i],
895
+ ...positions?.[i] !== void 0 ? { pos: positions[i] } : {}
896
+ }))) : null;
897
+ const keyOf = new Map(shown.map((i, k) => [k, i]));
898
+ const frames = played.map((f, n) => {
899
+ const at = gops ? keyOf.get(n) : void 0;
900
+ return {
901
+ n,
902
+ file: f.file,
903
+ atMs: f.atMs,
904
+ stable: true,
905
+ index: n,
906
+ ...gops && at !== void 0 ? {
907
+ key: keys[at],
908
+ gop: gops[at]
909
+ } : {}
910
+ };
911
+ });
912
+ const manifest = {
913
+ format: FRAMES_FORMAT,
914
+ source: {
915
+ tool: "scan video",
916
+ url: pathToFileURL(dir).href,
917
+ ...displayGeometry(size, options.displayWidth),
918
+ clock: "stream",
919
+ video: {
920
+ file: options.dir,
921
+ decoder: "import",
922
+ codec: "unknown",
923
+ lossless: options.lossless ?? false,
924
+ ...options.everyFrame ? { streamFrames: frames.length } : {},
925
+ selection: { kind: "all" },
926
+ ...hidden ? { hidden } : {},
927
+ ...loop ? { loop } : {}
928
+ }
929
+ },
930
+ frames
931
+ };
932
+ const manifestPath = join(dir, "frames.json");
933
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
934
+ return {
935
+ manifestPath,
936
+ manifest
937
+ };
938
+ }
939
+ export { CORRUPT_PACKET, DEFAULT_MAX_FRAMES, MAX_SCAN_FRAMES, STALE_UNKNOWN_MS, VIDEO_EXTENSIONS, alive, apngDeclaredFrames, decodeErrors, defaultFramesDir, findDecoder, importFrames, isVideoFile, onPath, parsePtsFile, parsePtsTable, processIdentity, scanVideo };