@tmhs/screencast-mcp 0.44.2 → 0.45.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.
@@ -0,0 +1,170 @@
1
+ import { ScreencastError } from "./errors.js";
2
+ import { escapeFilterPath } from "./fonts.js";
3
+ import { sumExpr } from "./expr.js";
4
+ import { resolveQuality } from "./targets.js";
5
+ import { validateColor } from "./validate.js";
6
+ export const BADGE_POSITIONS = ["bottom", "bottom-left", "bottom-right", "top", "top-left", "top-right"];
7
+ export const DEFAULT_LINGER_SEC = 1.2;
8
+ export const DOUBLE_CLICK_SEC = 0.5;
9
+ const DOUBLE_CLICK_PX = 8;
10
+ export const MAX_BADGE_LABELS = 100;
11
+ export const TYPING_LABEL = "Typing…";
12
+ const MODIFIERS = new Set(["Ctrl", "Alt", "Shift", "Win"]);
13
+ const KEY_NAME = /^(?:[A-Z0-9]|F\d{1,2}|Enter|Tab|Esc|Space|Backspace|Delete|Insert|Left|Up|Right|Down|Home|End|PageUp|PageDown|[=\-,./`[\];'\\])$/;
14
+ export function formatChord(keys, display = "shortcuts") {
15
+ const parts = keys.split("+");
16
+ const key = parts.pop();
17
+ if (key === undefined || parts.length === 0 || !KEY_NAME.test(key))
18
+ return null;
19
+ if (!parts.every((p) => MODIFIERS.has(p)) || new Set(parts).size !== parts.length)
20
+ return null;
21
+ return [...parts, display === "masked" ? "…" : key].join(" + ");
22
+ }
23
+ const BUTTON_LABEL = {
24
+ left: "Click",
25
+ right: "Right click",
26
+ middle: "Middle click",
27
+ x1: "Back button",
28
+ x2: "Forward button",
29
+ };
30
+ const r3 = (n) => Math.round(n * 1000) / 1000;
31
+ export function planBadges(events, opts = {}) {
32
+ const linger = opts.lingerSec ?? DEFAULT_LINGER_SEC;
33
+ if (!(linger > 0))
34
+ throw new ScreencastError("lingerSec must be positive.");
35
+ const display = opts.keys ?? "shortcuts";
36
+ const sorted = [...events].filter((e) => Number.isFinite(e.t) && e.t >= 0).sort((a, b) => a.t - b.t);
37
+ const raw = [];
38
+ for (const e of sorted) {
39
+ if (e.type === "key" && e.keys) {
40
+ const label = formatChord(e.keys, display);
41
+ if (!label)
42
+ continue;
43
+ const prev = raw.at(-1);
44
+ if (prev && prev.kind === "shortcut" && prev.base === label && e.t - prev.last <= linger) {
45
+ prev.count++;
46
+ prev.last = e.t;
47
+ prev.label = `${label} ×${prev.count}`;
48
+ prev.to = e.t + linger;
49
+ continue;
50
+ }
51
+ raw.push({ from: e.t, to: e.t + linger, label, base: label, kind: "shortcut", count: 1, last: e.t });
52
+ }
53
+ else if (e.type === "down" && opts.clicks !== false && e.inFrame) {
54
+ const base = BUTTON_LABEL[e.button ?? "left"] ?? "Click";
55
+ const prev = raw.at(-1);
56
+ if (base === "Click" && prev && prev.kind === "click" && prev.base === "Click" && prev.count < 3 &&
57
+ e.t - prev.last <= DOUBLE_CLICK_SEC &&
58
+ Math.abs(e.x - (prev.x ?? e.x)) <= DOUBLE_CLICK_PX && Math.abs(e.y - (prev.y ?? e.y)) <= DOUBLE_CLICK_PX) {
59
+ prev.count++;
60
+ prev.last = e.t;
61
+ prev.label = prev.count === 2 ? "Double click" : "Triple click";
62
+ prev.to = e.t + linger;
63
+ continue;
64
+ }
65
+ raw.push({ from: e.t, to: e.t + linger, label: base, base, kind: "click", count: 1, x: e.x, y: e.y, last: e.t });
66
+ }
67
+ else if (e.type === "typing" && opts.typing !== false) {
68
+ const end = e.t + Math.max(e.durationSec ?? 0, 0);
69
+ const prev = raw.at(-1);
70
+ if (prev && prev.kind === "typing" && e.t <= prev.to) {
71
+ prev.to = Math.max(prev.to, end + linger / 2);
72
+ prev.last = e.t;
73
+ continue;
74
+ }
75
+ raw.push({ from: e.t, to: end + linger / 2, label: TYPING_LABEL, base: TYPING_LABEL, kind: "typing", count: 1, last: e.t });
76
+ }
77
+ }
78
+ const out = [];
79
+ raw.forEach((b, i) => {
80
+ const next = raw[i + 1];
81
+ const to = next ? Math.min(b.to, next.from) : b.to;
82
+ if (to - b.from >= 0.05)
83
+ out.push({ from: r3(b.from), to: r3(to), label: b.label, kind: b.kind });
84
+ });
85
+ return out;
86
+ }
87
+ export function groupBadges(badges) {
88
+ const groups = new Map();
89
+ for (const b of badges) {
90
+ let g = groups.get(b.label);
91
+ if (!g) {
92
+ g = { label: b.label, windows: [] };
93
+ groups.set(b.label, g);
94
+ }
95
+ g.windows.push([b.from, b.to]);
96
+ }
97
+ if (groups.size > MAX_BADGE_LABELS) {
98
+ throw new ScreencastError(`${groups.size} different badges is more than ${MAX_BADGE_LABELS}; trim the video or turn off keys or clicks.`);
99
+ }
100
+ return [...groups.values()];
101
+ }
102
+ export function mapBadges(badges, map) {
103
+ return badges.flatMap((b) => {
104
+ const w = map(b.from, b.to);
105
+ return w && w[1] - w[0] >= 0.05 ? [{ ...b, from: r3(w[0]), to: r3(w[1]) }] : [];
106
+ });
107
+ }
108
+ export function retimeBadges(badges, ops) {
109
+ return mapBadges(badges, (from, to) => {
110
+ let a = from;
111
+ let b = to;
112
+ for (const op of ops) {
113
+ if (op.op === "trim") {
114
+ a = Math.max(a, op.start) - op.start;
115
+ b = Math.min(b, op.end) - op.start;
116
+ if (b <= a)
117
+ return null;
118
+ }
119
+ else {
120
+ a /= op.factor;
121
+ b /= op.factor;
122
+ }
123
+ }
124
+ return [a, b];
125
+ });
126
+ }
127
+ export function badgeSize(frameH, size) {
128
+ if (size !== undefined) {
129
+ if (!(size >= 8 && size <= 400))
130
+ throw new ScreencastError("size must be between 8 and 400.");
131
+ return Math.round(size);
132
+ }
133
+ return Math.max(14, Math.round(frameH * 0.045));
134
+ }
135
+ export function keystrokeSteps(groups, assets, style, frame, input, tag) {
136
+ if (groups.length === 0)
137
+ throw new ScreencastError("No badges to draw.");
138
+ const size = badgeSize(frame.height, style.size);
139
+ const border = Math.round(size / 3);
140
+ const margin = border + Math.round(size * 0.6);
141
+ const pos = style.position ?? "bottom";
142
+ const x = pos.endsWith("left") ? `${margin}` : pos.endsWith("right") ? `w-tw-${margin}` : "(w-tw)/2";
143
+ const y = pos.startsWith("top") ? `${margin}` : `h-lh-${margin}`;
144
+ const color = validateColor(style.color ?? "white");
145
+ const steps = [];
146
+ let cur = input;
147
+ groups.forEach((g, i) => {
148
+ const file = assets.textFiles[g.label];
149
+ if (!file)
150
+ throw new ScreencastError(`Internal: no text file for badge "${g.label}".`);
151
+ const enable = sumExpr(g.windows.map(([a, b]) => `between(t,${a},${b})`));
152
+ const out = `[${tag}k${i}]`;
153
+ steps.push(`${cur}drawtext=fontfile=${escapeFilterPath(assets.fontFile)}:textfile=${escapeFilterPath(file)}:expansion=none` +
154
+ `:fontsize=${size}:fontcolor=${color}:box=1:boxcolor=black@0.6:boxborderw=${border}` +
155
+ `:x=${x}:y=${y}:enable='${enable}'${out}`);
156
+ cur = out;
157
+ });
158
+ return { steps, out: cur };
159
+ }
160
+ export function buildKeystrokeArgs(input, output, groups, assets, style, frame, quality = "standard") {
161
+ const { steps, out } = keystrokeSteps(groups, assets, style, frame, "[0:v]", "");
162
+ return [
163
+ "-y", "-i", input,
164
+ "-filter_complex", steps.join(";"),
165
+ "-map", out, "-map", "0:a?",
166
+ ...resolveQuality(quality),
167
+ "-c:a", "copy",
168
+ output,
169
+ ];
170
+ }
@@ -1,5 +1,6 @@
1
1
  import { existsSync, rmSync, writeFileSync } from "node:fs";
2
- import { runCapture } from "./ffmpeg.js";
2
+ import { requireFfmpeg, runCapture } from "./ffmpeg.js";
3
+ import { finishReplay } from "./replay.js";
3
4
  import { whenFinalized } from "./events.js";
4
5
  import { buildProbeArgs, parseMediaInfo } from "./media.js";
5
6
  import { ScreencastError } from "./errors.js";
@@ -101,6 +102,14 @@ async function runStop(store, record, opts) {
101
102
  }
102
103
  store.detachChild(record.id);
103
104
  await whenFinalized(record.id);
105
+ const replay = record.replay
106
+ ? await finishReplay(record.replay, {
107
+ save: opts.saveReplay ?? false,
108
+ output: record.outputPath,
109
+ quality: record.quality,
110
+ tools: requireFfmpeg,
111
+ })
112
+ : undefined;
104
113
  const durationSec = await opts.probe(record.outputPath);
105
114
  const updated = store.update(record.id, {
106
115
  status: "stopped",
@@ -109,7 +118,7 @@ async function runStop(store, record, opts) {
109
118
  endReason: opts.reason,
110
119
  error: undefined,
111
120
  });
112
- return { record: updated, graceful, durationSec };
121
+ return { record: updated, graceful, durationSec, ...(replay ? { replay } : {}) };
113
122
  }
114
123
  finally {
115
124
  if (stopFile)
@@ -82,11 +82,14 @@ export function planFpsSampling(durationSec, fps, maxFrames) {
82
82
  const clampedFps = Math.max(1e-4, Math.floor((maxFrames / durationSec) * 10_000) / 10_000);
83
83
  return { fps: clampedFps, requestedFrames: requested, clamped: true };
84
84
  }
85
- export function buildSampleByFpsArgs(input, fps, outputPattern, maxFrames = DEFAULT_MAX_FRAMES, dedupe = false) {
85
+ export function buildSampleByFpsArgs(input, fps, outputPattern, maxFrames = DEFAULT_MAX_FRAMES, dedupe = false, range) {
86
86
  validatePositive(fps, "fps");
87
87
  const vf = dedupe ? `fps=${fps},mpdecimate` : `fps=${fps}`;
88
+ const seek = range
89
+ ? ["-ss", String(range.start), ...(range.duration !== undefined ? ["-t", String(range.duration)] : [])]
90
+ : [];
88
91
  return [
89
- "-y", "-i", input, "-vf", vf,
92
+ "-y", ...seek, "-i", input, "-vf", vf,
90
93
  ...(dedupe ? ["-fps_mode", "vfr"] : []),
91
94
  "-frames:v", String(maxFrames), outputPattern,
92
95
  ];
@@ -0,0 +1,77 @@
1
+ import { join } from "node:path";
2
+ import { readdirSync } from "node:fs";
3
+ import { ScreencastError } from "./errors.js";
4
+ import { probeMedia, runFfmpeg } from "./ffmpeg.js";
5
+ import { jobTimeoutMs } from "./jobs.js";
6
+ import { buildSampleByFpsArgs, planFpsSampling } from "./media.js";
7
+ import { recognize, mergePasses, findMatches, redactionRects, passScales } from "./ocr.js";
8
+ export async function readFrames(sources, work, signal) {
9
+ const sized = await Promise.all(sources.map(async (source) => {
10
+ const { width, height } = await probeMedia(source);
11
+ if (!width || !height)
12
+ throw new ScreencastError("Could not read the image size.");
13
+ return { source, width, height };
14
+ }));
15
+ const passes = [];
16
+ const passScaleList = [];
17
+ const owner = [];
18
+ for (const [f, { source, width, height }] of sized.entries()) {
19
+ for (const [i, scale] of passScales(width, height).entries()) {
20
+ const out = join(work, `pass${f}-${i}.png`);
21
+ await runFfmpeg(["-y", "-v", "error", "-i", source, "-vf", `scale=iw*${scale}:ih*${scale}:flags=lanczos`, out], 60_000, {
22
+ signal,
23
+ });
24
+ passes.push(out);
25
+ passScaleList.push(scale);
26
+ owner.push(f);
27
+ }
28
+ }
29
+ const results = await recognize(passes, passScaleList);
30
+ return sized.map(({ width, height }, f) => ({
31
+ lines: mergePasses(results.filter((_r, i) => owner[i] === f)),
32
+ width,
33
+ height,
34
+ }));
35
+ }
36
+ export async function scanVideoFrames(input, opts, work, signal) {
37
+ const info = await probeMedia(input);
38
+ const full = info.videoDurationSec ?? info.durationSec;
39
+ const length = opts.range ? opts.range.duration : full;
40
+ const plan = planFpsSampling(length, 1 / opts.everySec, opts.maxFrames);
41
+ await runFfmpeg(buildSampleByFpsArgs(input, plan.fps, join(work, "scan_%05d.png"), opts.maxFrames, false, opts.range), jobTimeoutMs(info.durationSec), { signal });
42
+ const paths = readdirSync(work).filter((f) => f.startsWith("scan_")).sort().map((f) => join(work, f));
43
+ if (paths.length === 0)
44
+ throw new ScreencastError("Could not read any frames from the video.");
45
+ const step = 1 / plan.fps;
46
+ const timeAt = (i) => Math.round(i * step * 1000) / 1000;
47
+ const end = length ?? timeAt(paths.length - 1) + step;
48
+ const read = await readFrames(paths, work, signal);
49
+ return {
50
+ frames: read.map((frame, i) => ({ ...frame, t: timeAt(i), path: paths[i] ?? "" })),
51
+ step,
52
+ end,
53
+ clamped: plan.clamped,
54
+ };
55
+ }
56
+ export function sampleWindow(t, step, end) {
57
+ return {
58
+ start: Math.max(0, Math.round((t - step) * 1000) / 1000),
59
+ end: Math.min(end, Math.round((t + step) * 1000) / 1000),
60
+ };
61
+ }
62
+ export function scanMatches(scan, query, regex, scope = "match") {
63
+ const matches = [];
64
+ const redactRegions = [];
65
+ for (const frame of scan.frames) {
66
+ const hits = findMatches(frame.lines, query, regex);
67
+ const window = sampleWindow(frame.t, scan.step, scan.end);
68
+ const boxes = scope === "line"
69
+ ? [...new Set(hits.map((h) => frame.lines.find((l) => l.text === h.line) ?? h))]
70
+ : hits;
71
+ for (const hit of hits)
72
+ matches.push({ t: frame.t, ...hit });
73
+ for (const rect of redactionRects(boxes, frame))
74
+ redactRegions.push({ ...rect, ...window });
75
+ }
76
+ return { matches, redactRegions };
77
+ }
@@ -4,9 +4,11 @@ import { calloutSteps } from "./callout.js";
4
4
  import { ASPECT_DIMS, exportPresetParts, reframeFilter } from "./produce.js";
5
5
  import { keyframesToViews, zoomFilter, DEFAULT_TRANSITION_SEC } from "./zoom.js";
6
6
  import { resolveQuality } from "./targets.js";
7
+ import { backdropSteps } from "./backdrop.js";
8
+ import { groupBadges, keystrokeSteps, retimeBadges } from "./keystrokes.js";
7
9
  export const MAX_PIPELINE_STEPS = 30;
8
10
  const r3 = (v) => Math.round(v * 1000) / 1000;
9
- export function planPipeline(input, output, steps, src, assets = {}, quality = "standard") {
11
+ export function planPipeline(input, output, steps, src, assets = {}, quality = "standard", opts = {}) {
10
12
  if (steps.length === 0)
11
13
  throw new ScreencastError("Give at least one step.");
12
14
  if (steps.length > MAX_PIPELINE_STEPS)
@@ -37,6 +39,7 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
37
39
  let encode = null;
38
40
  let gif;
39
41
  const summary = [];
42
+ const timeOps = [];
40
43
  const trimRange = (s, at) => {
41
44
  if (!Number.isFinite(s.start) || s.start < 0)
42
45
  throw new ScreencastError(`step ${at}: trim start must be a non-negative number.`);
@@ -73,6 +76,7 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
73
76
  }
74
77
  audioReencode = true;
75
78
  dur = end - start;
79
+ timeOps.push({ op: "trim", start, end });
76
80
  break;
77
81
  }
78
82
  case "crop":
@@ -96,6 +100,7 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
96
100
  audioReencode = true;
97
101
  if (dur !== null)
98
102
  dur /= s.factor;
103
+ timeOps.push({ op: "speed", factor: s.factor });
99
104
  summary.push(`speed x${s.factor}`);
100
105
  break;
101
106
  case "redact": {
@@ -133,6 +138,33 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
133
138
  summary.push(`zoom ${s.keyframes.length} keyframe(s)`);
134
139
  break;
135
140
  }
141
+ case "backdrop": {
142
+ const { op: _op, ...bo } = s;
143
+ const { steps: st, out: o, extraInputs: ex, layout } = backdropSteps(bo, { width: W, height: H }, cur, nextInput, tag);
144
+ graph.push(...st);
145
+ extraInputs.push(...ex);
146
+ nextInput += ex.length / 2;
147
+ cur = o;
148
+ W = layout.canvasW;
149
+ H = layout.canvasH;
150
+ summary.push(`backdrop to ${W}x${H}`);
151
+ break;
152
+ }
153
+ case "keystroke_overlay": {
154
+ const k = opts.keystrokes?.[i];
155
+ if (!k)
156
+ throw new ScreencastError(`Internal: missing keystroke badges for step ${at}.`);
157
+ const badges = retimeBadges(k.badges, timeOps);
158
+ if (badges.length === 0) {
159
+ summary.push("keystroke_overlay: no badges in this part of the video");
160
+ break;
161
+ }
162
+ const { steps: st, out: o } = keystrokeSteps(groupBadges(badges), k, s, { height: H }, cur, tag);
163
+ graph.push(...st);
164
+ cur = o;
165
+ summary.push(`keystroke_overlay ${badges.length} badge(s)`);
166
+ break;
167
+ }
136
168
  case "export_preset": {
137
169
  const p = exportPresetParts(s.platform, s.fit ?? "pad", tag);
138
170
  chain(p.vf);
@@ -155,6 +187,9 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
155
187
  }
156
188
  });
157
189
  const args = ["-y", ...inputArgs, "-i", input, ...extraInputs];
190
+ const chaptersInput = opts.chaptersFile ? args.filter((a) => a === "-i").length : -1;
191
+ if (opts.chaptersFile)
192
+ args.push("-f", "ffmetadata", "-i", opts.chaptersFile);
158
193
  if (graph.length > 0) {
159
194
  if (src.hasAudio && audio.length > 0)
160
195
  graph.push(`[0:a]${audio.join(",")}[aout]`);
@@ -175,6 +210,8 @@ export function planPipeline(input, output, steps, src, assets = {}, quality = "
175
210
  args.push(...(audioReencode ? ["-c:a", "aac", "-b:a", "160k"] : ["-c:a", "copy"]));
176
211
  args.push("-movflags", "+faststart");
177
212
  }
213
+ if (chaptersInput !== -1)
214
+ args.push("-map_chapters", String(chaptersInput));
178
215
  args.push(output);
179
- return { args, width: W, height: H, fps, durationSec: dur === null ? null : r3(dur), gif, summary };
216
+ return { args, width: W, height: H, fps, durationSec: dur === null ? null : r3(dur), gif, summary, timeOps };
180
217
  }
@@ -0,0 +1,278 @@
1
+ import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { ScreencastError } from "./errors.js";
4
+ import { runCapture } from "./ffmpeg.js";
5
+ import { jobTimeoutMs } from "./jobs.js";
6
+ import { buildProbeArgs, parseMediaInfo } from "./media.js";
7
+ import { homeRoot, rand, sequencePattern, stamp } from "./paths.js";
8
+ import { resolveQuality } from "./targets.js";
9
+ import { convertEvents, eventPaths, formatEventsJsonl, selectEvents, summarizeEvents, } from "./events.js";
10
+ export const REPLAY_SEGMENT_SEC = 2;
11
+ export const REPLAY_SLACK_SEGMENTS = 3;
12
+ export const MIN_REPLAY_SEC = 4;
13
+ export const MAX_REPLAY_SEC = 3600;
14
+ const SEGMENT_PATTERN = "seg%05d.ts";
15
+ const SEGMENT_NAME = /^seg(\d{5})\.ts$/;
16
+ const LIST_NAME = "segments.csv";
17
+ const DIR_NAME = /^buf-[\w-]+$/;
18
+ export function replayRoot() {
19
+ return join(homeRoot(), "replay");
20
+ }
21
+ export function replayWrap(bufferSec, segmentSec = REPLAY_SEGMENT_SEC) {
22
+ return Math.ceil(bufferSec / segmentSec) + REPLAY_SLACK_SEGMENTS;
23
+ }
24
+ export function planReplayBuffer(bufferSec, segmentSec = REPLAY_SEGMENT_SEC) {
25
+ if (!Number.isInteger(bufferSec) || bufferSec < MIN_REPLAY_SEC || bufferSec > MAX_REPLAY_SEC) {
26
+ throw new ScreencastError(`replayBufferSec must be an integer from ${MIN_REPLAY_SEC} to ${MAX_REPLAY_SEC} seconds.`);
27
+ }
28
+ return {
29
+ dir: join(replayRoot(), `buf-${stamp()}-${rand(6)}`),
30
+ bufferSec,
31
+ segmentSec,
32
+ wrap: replayWrap(bufferSec, segmentSec),
33
+ };
34
+ }
35
+ export function segmentListPath(dir) {
36
+ return join(dir, LIST_NAME);
37
+ }
38
+ export function segmentOutputArgs(captureArgs, buf) {
39
+ const args = captureArgs.slice(0, -1);
40
+ const mov = args.indexOf("-movflags");
41
+ if (mov >= 0)
42
+ args.splice(mov, 2);
43
+ return [
44
+ ...args,
45
+ "-force_key_frames", `expr:gte(t,n_forced*${buf.segmentSec})`,
46
+ "-f", "segment",
47
+ "-segment_time", String(buf.segmentSec),
48
+ "-segment_wrap", String(buf.wrap),
49
+ "-segment_list", segmentListPath(buf.dir),
50
+ "-segment_list_type", "csv",
51
+ "-segment_list_size", String(buf.wrap),
52
+ "-segment_format", "mpegts",
53
+ "-segment_format_options", "flush_packets=1",
54
+ sequencePattern(buf.dir, SEGMENT_PATTERN),
55
+ ];
56
+ }
57
+ export function parseSegmentList(csv) {
58
+ const out = [];
59
+ for (const line of csv.split(/\r?\n/)) {
60
+ const [file = "", s, e] = line.trim().split(",");
61
+ const m = SEGMENT_NAME.exec(file);
62
+ const start = Number(s);
63
+ const end = Number(e);
64
+ if (!m || s === undefined || e === undefined || !Number.isFinite(start) || !Number.isFinite(end) || end < start)
65
+ continue;
66
+ out.push({ file, index: Number(m[1]), start, end });
67
+ }
68
+ return out.sort((a, b) => a.start - b.start);
69
+ }
70
+ export function pickSegments(entries, lastSec) {
71
+ const picked = [];
72
+ let covered = 0;
73
+ for (let i = entries.length - 1; i >= 0 && covered < lastSec; i--) {
74
+ const e = entries[i];
75
+ picked.unshift(e);
76
+ covered += e.end - e.start;
77
+ }
78
+ return picked;
79
+ }
80
+ export function liveSegmentFile(entries, wrap) {
81
+ const last = entries.at(-1);
82
+ const index = last ? (last.index + 1) % wrap : 0;
83
+ return `seg${String(index).padStart(5, "0")}.ts`;
84
+ }
85
+ export function concatList(files) {
86
+ return files.map((p) => `file '${p.replace(/'/g, "'\\''")}'`).join("\n") + "\n";
87
+ }
88
+ export function buildReplayJoinArgs(listFile, output) {
89
+ return ["-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", listFile, "-c", "copy", output];
90
+ }
91
+ export function buildReplayCutArgs(input, output, opts) {
92
+ const codec = opts.reencode
93
+ ? [...resolveQuality(opts.quality ?? "standard"), ...(opts.audio ? ["-c:a", "aac", "-b:a", "160k"] : [])]
94
+ : ["-c", "copy"];
95
+ return [
96
+ "-y", "-v", "error",
97
+ "-ss", String(round3(Math.max(0, opts.startSec))),
98
+ "-i", input,
99
+ ...codec,
100
+ "-movflags", "+faststart",
101
+ output,
102
+ ];
103
+ }
104
+ export function sliceEvents(events, from, to) {
105
+ return selectEvents(events, { from, to }).map((e) => ({ ...e, t: round3(e.t - from) }));
106
+ }
107
+ const round3 = (n) => Math.round(n * 1000) / 1000;
108
+ function copyShared(src, dst) {
109
+ const fd = openSync(src, "r");
110
+ try {
111
+ const size = statSync(src).size;
112
+ const buf = Buffer.alloc(size);
113
+ let read = 0;
114
+ while (read < size) {
115
+ const n = readSync(fd, buf, read, size - read, read);
116
+ if (n === 0)
117
+ break;
118
+ read += n;
119
+ }
120
+ writeFileSync(dst, buf.subarray(0, read));
121
+ return read;
122
+ }
123
+ finally {
124
+ closeSync(fd);
125
+ }
126
+ }
127
+ async function probeStart(ffprobe, path, signal) {
128
+ const res = await runCapture(ffprobe, ["-v", "error", "-show_entries", "format=start_time", "-of", "csv=p=0", path], 15_000, { signal });
129
+ const n = Number.parseFloat(res.stdout.trim());
130
+ return res.code === 0 && Number.isFinite(n) ? n : null;
131
+ }
132
+ export async function saveReplay(buf, opts) {
133
+ if (!existsSync(buf.dir)) {
134
+ throw new ScreencastError("This replay buffer has been discarded: its segments are gone.");
135
+ }
136
+ const listPath = segmentListPath(buf.dir);
137
+ const entries = existsSync(listPath) ? parseSegmentList(readFileSync(listPath, "utf8")) : [];
138
+ const picked = pickSegments(entries, opts.lastSec);
139
+ const snap = mkdtempSync(join(buf.dir, "save-"));
140
+ try {
141
+ const files = picked.map((e, i) => {
142
+ const dst = join(snap, `${String(i).padStart(5, "0")}.ts`);
143
+ copyShared(join(buf.dir, e.file), dst);
144
+ return dst;
145
+ });
146
+ let includesLive = false;
147
+ if (opts.live !== false) {
148
+ const src = join(buf.dir, liveSegmentFile(entries, buf.wrap));
149
+ const dst = join(snap, "live.ts");
150
+ if (existsSync(src) && copyShared(src, dst) > 0) {
151
+ const newest = files.at(-1);
152
+ const [liveStart, lastStart] = await Promise.all([
153
+ probeStart(opts.ffprobe, dst, opts.signal),
154
+ newest ? probeStart(opts.ffprobe, newest, opts.signal) : Promise.resolve(-Infinity),
155
+ ]);
156
+ if (liveStart !== null && lastStart !== null && liveStart > lastStart) {
157
+ files.push(dst);
158
+ includesLive = true;
159
+ }
160
+ }
161
+ }
162
+ if (files.length === 0) {
163
+ throw new ScreencastError("The replay buffer has no footage yet: the first segment is still being written. Try again in a couple of seconds.");
164
+ }
165
+ const listFile = join(snap, "join.txt");
166
+ writeFileSync(listFile, concatList(files));
167
+ const joined = join(snap, "joined.mp4");
168
+ const timeout = jobTimeoutMs(opts.lastSec + 2 * buf.segmentSec);
169
+ const join1 = await runCapture(opts.ffmpeg, buildReplayJoinArgs(listFile, joined), timeout, { signal: opts.signal });
170
+ if (join1.code !== 0) {
171
+ throw new ScreencastError(`Joining the replay segments failed:\n${join1.stderr.trim().split("\n").slice(-4).join("\n")}`);
172
+ }
173
+ const probe = await runCapture(opts.ffprobe, buildProbeArgs(joined), 30_000, { signal: opts.signal });
174
+ const info = probe.code === 0 ? parseMediaInfo(JSON.parse(probe.stdout)) : null;
175
+ const total = info?.durationSec ?? null;
176
+ if (!total || !(total > 0))
177
+ throw new ScreencastError("The joined replay has no duration; the segments may be damaged.");
178
+ const startSec = Math.max(0, total - opts.lastSec);
179
+ const cut = await runCapture(opts.ffmpeg, buildReplayCutArgs(joined, opts.output, {
180
+ startSec,
181
+ reencode: opts.reencode,
182
+ quality: opts.quality,
183
+ audio: !!info?.audioCodec,
184
+ }), timeout, { signal: opts.signal });
185
+ if (cut.code !== 0) {
186
+ throw new ScreencastError(`Writing the replay failed:\n${cut.stderr.trim().split("\n").slice(-4).join("\n")}`);
187
+ }
188
+ const origin = picked[0]?.start ?? entries.at(-1)?.end ?? 0;
189
+ const fromSec = round3(origin + startSec);
190
+ const toSec = round3(origin + total);
191
+ const result = {
192
+ outputPath: opts.output,
193
+ durationSec: round3(total - startSec),
194
+ fromSec,
195
+ toSec,
196
+ segments: files.length,
197
+ includesLive,
198
+ };
199
+ if (buf.events) {
200
+ const raw = existsSync(buf.events.raw) ? readFileSync(buf.events.raw, "utf8") : "";
201
+ const events = sliceEvents(convertEvents(raw, { startMs: buf.events.startMs, frame: buf.events.frame }), fromSec, toSec);
202
+ const { jsonl } = eventPaths(opts.output);
203
+ writeFileSync(jsonl, formatEventsJsonl(events));
204
+ result.eventsPath = jsonl;
205
+ result.events = summarizeEvents(events);
206
+ }
207
+ return result;
208
+ }
209
+ finally {
210
+ rmSync(snap, { recursive: true, force: true });
211
+ }
212
+ }
213
+ export function prepareReplayDir(buf) {
214
+ mkdirSync(buf.dir, { recursive: true });
215
+ }
216
+ export function discardReplay(buf) {
217
+ try {
218
+ rmSync(buf.dir, { recursive: true, force: true });
219
+ return !existsSync(buf.dir);
220
+ }
221
+ catch {
222
+ return false;
223
+ }
224
+ }
225
+ export function replayDiskBytes(buf) {
226
+ let total = 0;
227
+ try {
228
+ for (const name of readdirSync(buf.dir)) {
229
+ try {
230
+ const st = statSync(join(buf.dir, name));
231
+ if (st.isFile())
232
+ total += st.size;
233
+ }
234
+ catch {
235
+ }
236
+ }
237
+ }
238
+ catch {
239
+ }
240
+ return total;
241
+ }
242
+ export function cleanupReplayDirs(keep, root = replayRoot()) {
243
+ const keepSet = new Set([...keep].map((d) => d.toLowerCase()));
244
+ let names;
245
+ try {
246
+ names = readdirSync(root);
247
+ }
248
+ catch {
249
+ return 0;
250
+ }
251
+ let removed = 0;
252
+ for (const name of names) {
253
+ const dir = join(root, name);
254
+ if (!DIR_NAME.test(name) || keepSet.has(dir.toLowerCase()))
255
+ continue;
256
+ try {
257
+ rmSync(dir, { recursive: true, force: true });
258
+ removed++;
259
+ }
260
+ catch {
261
+ }
262
+ }
263
+ return removed;
264
+ }
265
+ export async function finishReplay(buf, opts) {
266
+ if (!opts.save)
267
+ return { saved: false, discarded: discardReplay(buf) };
268
+ try {
269
+ const tools = opts.tools?.();
270
+ if (!tools)
271
+ throw new ScreencastError("ffmpeg is not available to save the replay buffer.");
272
+ const save = await saveReplay(buf, { ...tools, lastSec: buf.bufferSec, output: opts.output, quality: opts.quality, live: false });
273
+ return { saved: true, discarded: discardReplay(buf), save };
274
+ }
275
+ catch (err) {
276
+ return { saved: false, discarded: false, error: err instanceof Error ? err.message : String(err) };
277
+ }
278
+ }