@tmhs/screencast-mcp 0.44.2 → 0.46.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 (44) hide show
  1. package/README.md +58 -11
  2. package/assets/ui/player.html +9 -0
  3. package/assets/ui/player.js +20 -0
  4. package/dist/index.js +12 -0
  5. package/dist/prompts.js +34 -4
  6. package/dist/server.js +20 -0
  7. package/dist/tools/addMarker.js +89 -0
  8. package/dist/tools/backdrop.js +89 -0
  9. package/dist/tools/bugReport.js +266 -0
  10. package/dist/tools/chapters.js +156 -0
  11. package/dist/tools/contactSheet.js +19 -17
  12. package/dist/tools/cutByTranscript.js +86 -0
  13. package/dist/tools/findText.js +14 -64
  14. package/dist/tools/indexRecording.js +173 -0
  15. package/dist/tools/keystrokeOverlay.js +131 -0
  16. package/dist/tools/pipeline.js +251 -18
  17. package/dist/tools/reviewRecording.js +12 -0
  18. package/dist/tools/saveReplay.js +90 -0
  19. package/dist/tools/searchRecording.js +73 -0
  20. package/dist/tools/startRecording.js +51 -10
  21. package/dist/tools/stepGuide.js +193 -0
  22. package/dist/tools/stopRecording.js +25 -1
  23. package/dist/tools/transcribe.js +4 -3
  24. package/dist/tools/zoom.js +1 -1
  25. package/dist/utils/audio.js +12 -4
  26. package/dist/utils/backdrop.js +151 -0
  27. package/dist/utils/bugReport.js +172 -0
  28. package/dist/utils/captions.js +19 -6
  29. package/dist/utils/chapters.js +227 -0
  30. package/dist/utils/idle.js +10 -3
  31. package/dist/utils/keystrokes.js +155 -0
  32. package/dist/utils/lifecycle.js +11 -2
  33. package/dist/utils/media.js +5 -2
  34. package/dist/utils/ocrScan.js +77 -0
  35. package/dist/utils/pipeline.js +169 -15
  36. package/dist/utils/recipes.js +67 -0
  37. package/dist/utils/recordingIndex.js +266 -0
  38. package/dist/utils/replay.js +278 -0
  39. package/dist/utils/stepGuide.js +205 -0
  40. package/dist/utils/steps.js +88 -0
  41. package/dist/utils/timeline.js +85 -0
  42. package/dist/utils/toolsets.js +32 -6
  43. package/dist/utils/transcriptCut.js +134 -0
  44. package/package.json +1 -1
@@ -0,0 +1,172 @@
1
+ import { ScreencastError } from "./errors.js";
2
+ import { findMatches, normalizeForMatch, regexRanges } from "./ocr.js";
3
+ import { formatTimecode } from "./sheet.js";
4
+ export const DEFAULT_CLIP_SEC = 30;
5
+ export const MAX_CLIP_SEC = 600;
6
+ export const DEFAULT_SCAN_EVERY_SEC = 1;
7
+ export const MAX_STEPS = 100;
8
+ export const MAX_ERROR_LINES = 20;
9
+ export const DEFAULT_SECRET_PATTERN = [
10
+ "\\b(?:sk|pk|rk)-[a-z0-9_-]{8,}",
11
+ "\\bgh[pousr]_[a-z0-9]{10,}",
12
+ "\\bgithub_pat_[a-z0-9_]{10,}",
13
+ "\\bxox[abprs]-[a-z0-9-]{8,}",
14
+ "\\bAKIA[0-9A-Z]{12,}",
15
+ "\\bAIza[0-9a-z_-]{20,}",
16
+ "\\beyJ[a-z0-9_-]{8,}\\.[a-z0-9_-]{8,}",
17
+ "(?:api.?key|secret|token|passw(?:or)?d|bearer|authorization)\\s*[:=]?\\s*\\S+",
18
+ ].join("|");
19
+ export const DEFAULT_ERROR_PATTERN = "error|exception|fail(?:ed|ure)?|fatal|crash|denied|refused|not found|cannot|can't|unable|invalid|" +
20
+ "timed? ?out|traceback|panic|unhandled|warning";
21
+ export const REPORT_FILES = {
22
+ markdown: "report.md",
23
+ json: "report.json",
24
+ clip: "clip.mp4",
25
+ contactSheet: "contact-sheet.png",
26
+ gif: (format) => `repro.${format}`,
27
+ };
28
+ const r3 = (n) => Math.round(n * 1000) / 1000;
29
+ export function clipWindow(durationSec, opts = {}) {
30
+ if (!(durationSec > 0))
31
+ throw new ScreencastError("Could not read the recording's duration.");
32
+ const end = Math.min(opts.end ?? durationSec, durationSec);
33
+ const clipSec = opts.clipSec ?? DEFAULT_CLIP_SEC;
34
+ const start = opts.start ?? Math.max(0, end - clipSec);
35
+ if (start >= durationSec) {
36
+ throw new ScreencastError(`start ${start}s is past the end of the ${r3(durationSec)}s recording.`);
37
+ }
38
+ if (!(end > start))
39
+ throw new ScreencastError("end must be after start.");
40
+ if (end - start > MAX_CLIP_SEC) {
41
+ throw new ScreencastError(`The clip would be ${r3(end - start)}s; at most ${MAX_CLIP_SEC}s. Narrow start/end.`);
42
+ }
43
+ return { start: r3(start), end: r3(end) };
44
+ }
45
+ export { reconstructSteps } from "./steps.js";
46
+ function mostlyOverlap(a, b) {
47
+ const w = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);
48
+ const h = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);
49
+ if (w <= 0 || h <= 0)
50
+ return false;
51
+ return w * h >= 0.5 * Math.min(a.width * a.height, b.width * b.height);
52
+ }
53
+ export function mergeRedactions(regions) {
54
+ const out = [];
55
+ for (const r of [...regions].sort((a, b) => a.start - b.start)) {
56
+ const into = out.find((o) => r.start <= o.end && mostlyOverlap(o, r));
57
+ if (!into) {
58
+ out.push({ ...r });
59
+ continue;
60
+ }
61
+ const x = Math.min(into.x, r.x);
62
+ const y = Math.min(into.y, r.y);
63
+ into.width = Math.max(into.x + into.width, r.x + r.width) - x;
64
+ into.height = Math.max(into.y + into.height, r.y + r.height) - y;
65
+ into.x = x;
66
+ into.y = y;
67
+ into.start = Math.min(into.start, r.start);
68
+ into.end = Math.max(into.end, r.end);
69
+ }
70
+ return out;
71
+ }
72
+ export const MASK = "[REDACTED]";
73
+ export function maskSecrets(texts, pattern) {
74
+ if (texts.length === 0)
75
+ return [];
76
+ const ranges = regexRanges(texts, pattern);
77
+ return texts.map((text, i) => {
78
+ const spans = [...(ranges[i] ?? [])].sort((a, b) => a[0] - b[0]);
79
+ let out = "";
80
+ let at = 0;
81
+ for (const [s, e] of spans) {
82
+ if (e <= at)
83
+ continue;
84
+ out += text.slice(at, Math.max(at, s)) + (s >= at ? MASK : "");
85
+ at = e;
86
+ }
87
+ return out + text.slice(at);
88
+ });
89
+ }
90
+ export function errorFindings(frames, errorPattern, secretPattern) {
91
+ const found = new Map();
92
+ for (const frame of frames) {
93
+ const hitLines = new Set(findMatches(frame.lines, errorPattern, true).map((m) => m.line));
94
+ for (const line of hitLines) {
95
+ const key = normalizeForMatch(line);
96
+ const seen = found.get(key);
97
+ if (seen)
98
+ seen.lastSeen = frame.t;
99
+ else
100
+ found.set(key, { text: line, firstSeen: frame.t, lastSeen: frame.t });
101
+ }
102
+ }
103
+ const lastT = frames.at(-1)?.t;
104
+ const list = [...found.values()].sort((a, b) => Number(b.lastSeen === lastT) - Number(a.lastSeen === lastT) || a.firstSeen - b.firstSeen).slice(0, MAX_ERROR_LINES);
105
+ if (!secretPattern)
106
+ return list;
107
+ const masked = maskSecrets(list.map((f) => f.text), secretPattern);
108
+ return list.map((f, i) => ({ ...f, text: masked[i] ?? f.text }));
109
+ }
110
+ const code = (s) => `\`${s.replace(/`/g, "'").replace(/\s+/g, " ").trim()}\``;
111
+ const cell = (s) => s.replace(/\|/g, "\\|").replace(/\s*\n\s*/g, " ");
112
+ export function buildReportMarkdown(r) {
113
+ const out = [`# ${r.title.replace(/\s*\n\s*/g, " ")}`, ""];
114
+ const span = `${formatTimecode(r.clip.start)}-${formatTimecode(r.clip.end)}`;
115
+ out.push(`Recorded repro: ${r.clip.width}x${r.clip.height}, clip ${span} of a ${formatTimecode(r.clip.recordingDurationSec)} recording.`, "");
116
+ if (r.actual || r.expected) {
117
+ if (r.actual)
118
+ out.push("**Actual:** " + r.actual.trim(), "");
119
+ if (r.expected)
120
+ out.push("**Expected:** " + r.expected.trim(), "");
121
+ }
122
+ out.push("## Steps to reproduce", "");
123
+ if (r.steps.length === 0) {
124
+ out.push(`_${r.stepsNote ?? "No input events in the recording."} Add the steps by hand._`, "");
125
+ }
126
+ else {
127
+ out.push("From the recording's input event log; times are on the recording's clock, positions in video pixels.", "");
128
+ r.steps.forEach((s, i) => out.push(`${i + 1}. \`${formatTimecode(s.t)}\` ${s.text}`));
129
+ if (r.stepsOmitted)
130
+ out.push("", `_${r.stepsOmitted} more steps not shown (see report.json)._`);
131
+ out.push("");
132
+ }
133
+ out.push("## Error text on screen", "");
134
+ if (r.ocr !== "read") {
135
+ out.push("_Not read: Windows OCR is unavailable here._", "");
136
+ }
137
+ else if (r.errors.length === 0) {
138
+ out.push("_None found by OCR in the clip._", "");
139
+ }
140
+ else {
141
+ out.push("Read by OCR (best-effort, may contain misreads); times from the clip start.", "");
142
+ for (const e of r.errors) {
143
+ const when = e.firstSeen === e.lastSeen ? formatTimecode(e.firstSeen) : `${formatTimecode(e.firstSeen)}-${formatTimecode(e.lastSeen)}`;
144
+ out.push(`- \`${when}\` ${code(e.text)}`);
145
+ }
146
+ out.push("");
147
+ }
148
+ out.push("## Recording", "");
149
+ if (r.files.gif) {
150
+ out.push("<!-- GitHub does not upload local files from --body-file: drag the GIF and clip into the issue, " +
151
+ "or replace these links with the uploaded URLs. -->", `![Repro](${r.files.gif})`, "");
152
+ }
153
+ out.push(`- Clip: [${r.files.clip}](${r.files.clip}) (${r3(r.clip.end - r.clip.start)} s)`);
154
+ if (r.files.gif && r.gif) {
155
+ const mb = (r.gif.sizeBytes / 1_000_000).toFixed(1);
156
+ out.push(`- ${r.gif.format === "gif" ? "GIF" : "WebP"}: [${r.files.gif}](${r.files.gif}) (${mb} MB${r.gif.withinBudget ? "" : ", over the size budget"})`);
157
+ }
158
+ if (r.files.contactSheet)
159
+ out.push(`- Contact sheet: [${r.files.contactSheet}](${r.files.contactSheet})`);
160
+ out.push("");
161
+ out.push("## Environment", "", "| | |", "|---|---|");
162
+ for (const [k, v] of r.environment)
163
+ out.push(`| ${cell(k)} | ${cell(v)} |`);
164
+ out.push("");
165
+ const red = r.redaction;
166
+ const boxes = red.found + red.manual;
167
+ out.push("<sub>", red.scanned
168
+ ? `Secret scan: OCR every ${red.everySec} s over ${red.framesScanned} frames; ${boxes} region${boxes === 1 ? "" : "s"} boxed out of the media. ` +
169
+ "OCR is best-effort: review the clip before posting."
170
+ : `Not scanned for secrets${red.manual > 0 ? ` (${red.manual} region${red.manual === 1 ? "" : "s"} boxed out by hand)` : ""}: review the clip before posting.`, `Generated by screencast-mcp bug_report, ${r.createdAt}.`, "</sub>", "");
171
+ return out.join("\n");
172
+ }
@@ -14,7 +14,7 @@ export function resolveWhisperModel(arg, env = process.env) {
14
14
  throw new ScreencastError(`Whisper model not found: ${model}`, MODEL_HINT);
15
15
  return model;
16
16
  }
17
- export function buildTranscribeArgs(input, model, srtOut, language = "auto") {
17
+ export function buildTranscribeArgs(input, model, srtOut, language = "auto", words = false) {
18
18
  if (!/^[a-z]{2,3}$|^auto$/.test(language)) {
19
19
  throw new ScreencastError(`language must be a code like "en" or "auto", got "${language}".`);
20
20
  }
@@ -22,10 +22,21 @@ export function buildTranscribeArgs(input, model, srtOut, language = "auto") {
22
22
  "-y", "-v", "error", "-i", input, "-vn",
23
23
  "-af",
24
24
  `aresample=16000,whisper=model=${escapeFilterPath(model)}:language=${language}:format=srt:` +
25
- `destination=${escapeFilterPath(srtOut)}:use_gpu=false`,
25
+ `destination=${escapeFilterPath(srtOut)}:use_gpu=false` + (words ? ":max_len=1" : ""),
26
26
  "-f", "null", "-",
27
27
  ];
28
28
  }
29
+ export function mergePunctuation(cues) {
30
+ const out = [];
31
+ for (const c of cues) {
32
+ const prev = out[out.length - 1];
33
+ if (prev && !/[\p{L}\p{N}]/u.test(c.text))
34
+ prev.text += c.text.trim();
35
+ else
36
+ out.push({ ...c });
37
+ }
38
+ return out;
39
+ }
29
40
  const TIME = /(\d+):(\d{2}):(\d{2})[,.](\d{3})/;
30
41
  const toSec = (m) => Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) + Number(m[4]) / 1000;
31
42
  function fmt(sec) {
@@ -72,15 +83,17 @@ export const CAPTION_STYLES = {
72
83
  clean: "FontName=Inter,FontSize=16,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=1.5,Shadow=0,MarginV=16",
73
84
  social: "FontName=Inter,Bold=1,FontSize=22,PrimaryColour=&H00FFFFFF,BackColour=&H99000000,BorderStyle=3,Outline=6,Shadow=0,MarginV=40",
74
85
  };
75
- export function buildBurnSubtitlesArgs(input, subtitles, output, fontsDir, style = "clean", quality = "standard") {
86
+ export function subtitlesFilter(subtitles, fontsDir, style = "clean") {
76
87
  const force = style === null ? null : CAPTION_STYLES[style];
77
88
  if (force === undefined)
78
89
  throw new ScreencastError(`Unknown caption style "${style}".`);
90
+ return (`subtitles=filename=${escapeFilterPath(subtitles)}:fontsdir=${escapeFilterPath(fontsDir)}` +
91
+ (force ? `:force_style='${force}'` : ""));
92
+ }
93
+ export function buildBurnSubtitlesArgs(input, subtitles, output, fontsDir, style = "clean", quality = "standard") {
79
94
  return [
80
95
  "-y", "-i", input,
81
- "-vf",
82
- `subtitles=filename=${escapeFilterPath(subtitles)}:fontsdir=${escapeFilterPath(fontsDir)}` +
83
- (force ? `:force_style='${force}'` : ""),
96
+ "-vf", subtitlesFilter(subtitles, fontsDir, style),
84
97
  ...resolveQuality(quality),
85
98
  "-c:a", "copy",
86
99
  output,
@@ -0,0 +1,227 @@
1
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { ScreencastError } from "./errors.js";
3
+ import { requireFfmpeg, runCapture } from "./ffmpeg.js";
4
+ import { cutShift } from "./timeline.js";
5
+ export const MAX_MARKERS = 500;
6
+ export const MAX_LABEL = 200;
7
+ export const YOUTUBE_MIN_CHAPTERS = 3;
8
+ export const YOUTUBE_MIN_CHAPTER_SEC = 10;
9
+ const r3 = (v) => Math.round(v * 1000) / 1000;
10
+ export function markersPath(video) {
11
+ return `${video.replace(/\.[^./\\]+$/, "")}.markers.json`;
12
+ }
13
+ export function markerTimeSec(videoStartMs, nowMs) {
14
+ return Math.max(0, r3((nowMs - videoStartMs) / 1000));
15
+ }
16
+ export function cleanLabel(label, max = MAX_LABEL) {
17
+ const s = label.replace(/\s+/g, " ").trim();
18
+ return s.length > max ? `${s.slice(0, max - 1).trimEnd()}…` : s;
19
+ }
20
+ export function insertMarker(list, marker) {
21
+ if (list.length >= MAX_MARKERS) {
22
+ throw new ScreencastError(`A recording holds at most ${MAX_MARKERS} markers.`);
23
+ }
24
+ const label = cleanLabel(marker.label);
25
+ if (!label)
26
+ throw new ScreencastError("A marker needs a non-empty label.");
27
+ if (!Number.isFinite(marker.t) || marker.t < 0)
28
+ throw new ScreencastError("A marker time must be a non-negative number of seconds.");
29
+ const m = { ...marker, t: r3(marker.t), label };
30
+ const i = list.findIndex((x) => x.t > m.t);
31
+ return i === -1 ? [...list, m] : [...list.slice(0, i), m, ...list.slice(i)];
32
+ }
33
+ function isMarker(v) {
34
+ const m = v;
35
+ return !!m && typeof m.t === "number" && Number.isFinite(m.t) && m.t >= 0 && typeof m.label === "string";
36
+ }
37
+ export function parseMarkerSidecar(text) {
38
+ let data;
39
+ try {
40
+ data = JSON.parse(text);
41
+ }
42
+ catch {
43
+ return [];
44
+ }
45
+ const list = Array.isArray(data) ? data : data?.markers;
46
+ return Array.isArray(list) ? list.filter(isMarker).sort((a, b) => a.t - b.t) : [];
47
+ }
48
+ export function readMarkers(video) {
49
+ const path = markersPath(video);
50
+ if (!existsSync(path))
51
+ return [];
52
+ try {
53
+ return parseMarkerSidecar(readFileSync(path, "utf8"));
54
+ }
55
+ catch {
56
+ return [];
57
+ }
58
+ }
59
+ export function writeMarkers(video, markers, sessionId) {
60
+ const path = markersPath(video);
61
+ const tmp = `${path}.${process.pid}.tmp`;
62
+ writeFileSync(tmp, JSON.stringify({ ...(sessionId ? { sessionId } : {}), markers }, null, 2));
63
+ renameSync(tmp, path);
64
+ return path;
65
+ }
66
+ export function retimeMarkers(markers, ops) {
67
+ let cur = [...markers].sort((a, b) => a.t - b.t);
68
+ for (const op of ops) {
69
+ if (op.op === "speed") {
70
+ cur = cur.map((m) => ({ ...m, t: r3(m.t / op.factor) }));
71
+ continue;
72
+ }
73
+ if (op.op === "cut") {
74
+ cur = cur.map((m) => ({ ...m, t: r3(m.t - cutShift(m.t, op.spans)) }));
75
+ continue;
76
+ }
77
+ const inside = cur.filter((m) => m.t >= op.start && m.t < op.end).map((m) => ({ ...m, t: r3(m.t - op.start) }));
78
+ const carried = cur.filter((m) => m.t < op.start).at(-1);
79
+ cur = carried && !inside.some((m) => m.t < 0.001) ? [{ ...carried, t: 0 }, ...inside] : inside;
80
+ }
81
+ return cur;
82
+ }
83
+ export function buildChapters(points, durationSec, opts = {}) {
84
+ const min = Math.max(0.001, opts.minChapterSec ?? 1);
85
+ const sorted = points
86
+ .filter((p) => Number.isFinite(p.start) && p.start >= 0 && p.start < durationSec)
87
+ .map((p, i) => ({ start: r3(p.start), title: cleanLabel(p.title, 100) || `Chapter ${i + 1}` }))
88
+ .sort((a, b) => a.start - b.start);
89
+ const kept = [];
90
+ for (const p of sorted) {
91
+ const last = kept.at(-1);
92
+ if (!last) {
93
+ if (p.start < min)
94
+ kept.push({ ...p, start: 0 });
95
+ else
96
+ kept.push({ start: 0, title: opts.introTitle ?? "Intro" }, p);
97
+ }
98
+ else if (p.start - last.start >= min) {
99
+ kept.push(p);
100
+ }
101
+ }
102
+ const lastKept = kept.at(-1);
103
+ if (kept.length > 1 && lastKept && durationSec - lastKept.start < min)
104
+ kept.pop();
105
+ return kept.map((p, i) => ({ start: p.start, end: r3(kept[i + 1]?.start ?? durationSec), title: p.title }));
106
+ }
107
+ export function youtubeTimestamp(sec, long) {
108
+ const s = Math.max(0, Math.floor(sec));
109
+ const h = Math.floor(s / 3600);
110
+ const m = Math.floor((s % 3600) / 60);
111
+ const ss = String(s % 60).padStart(2, "0");
112
+ return long ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${Math.floor(s / 60)}:${ss}`;
113
+ }
114
+ export function youtubeChapters(chapters, durationSec) {
115
+ const long = durationSec >= 3600;
116
+ const text = chapters.map((c) => `${youtubeTimestamp(c.start, long)} ${c.title}`).join("\n");
117
+ const issues = [];
118
+ if (chapters.length < YOUTUBE_MIN_CHAPTERS) {
119
+ issues.push(`YouTube needs at least ${YOUTUBE_MIN_CHAPTERS} chapters; there are ${chapters.length}.`);
120
+ }
121
+ if (chapters[0] && chapters[0].start !== 0)
122
+ issues.push("YouTube needs the first chapter at 0:00.");
123
+ const short = chapters.filter((c) => c.end - c.start < YOUTUBE_MIN_CHAPTER_SEC);
124
+ if (short.length > 0) {
125
+ issues.push(`YouTube needs every chapter to be at least ${YOUTUBE_MIN_CHAPTER_SEC} s long; ${short.length} ` +
126
+ `${short.length === 1 ? "is" : "are"} shorter (${short.map((c) => `"${c.title}"`).join(", ")}). ` +
127
+ `Raise minChapterSec to ${YOUTUBE_MIN_CHAPTER_SEC} to merge them.`);
128
+ }
129
+ return { text, issues };
130
+ }
131
+ export function escapeFfmetadata(value) {
132
+ return value.replace(/[=;#\\\n]/g, (c) => `\\${c}`);
133
+ }
134
+ export function ffmetadata(chapters) {
135
+ const lines = [";FFMETADATA1"];
136
+ for (const c of chapters) {
137
+ lines.push("[CHAPTER]", "TIMEBASE=1/1000", `START=${Math.round(c.start * 1000)}`, `END=${Math.round(c.end * 1000)}`, `title=${escapeFfmetadata(c.title)}`);
138
+ }
139
+ return `${lines.join("\n")}\n`;
140
+ }
141
+ export function markerPoints(markers) {
142
+ return markers.map((m) => ({ start: m.t, title: m.label }));
143
+ }
144
+ export function scenePoints(scenes, minChapterSec, maxChapters) {
145
+ const picked = [0];
146
+ for (const s of [...scenes].sort((a, b) => b.score - a.score)) {
147
+ if (picked.length >= maxChapters)
148
+ break;
149
+ if (picked.every((t) => Math.abs(t - s.timeSec) >= minChapterSec))
150
+ picked.push(s.timeSec);
151
+ }
152
+ return picked.sort((a, b) => a - b).map((t, i) => ({ start: t, title: `Scene ${i + 1}` }));
153
+ }
154
+ function cueTitle(text, max = 60) {
155
+ const s = text.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
156
+ if (s.length <= max)
157
+ return s;
158
+ const cut = s.slice(0, max);
159
+ const space = cut.lastIndexOf(" ");
160
+ return `${(space > max / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
161
+ }
162
+ export function transcriptPoints(cues, opts = {}) {
163
+ const gap = opts.gapSec ?? 2;
164
+ const min = opts.minChapterSec ?? 30;
165
+ const sorted = [...cues].sort((a, b) => a.start - b.start);
166
+ const out = [];
167
+ let prevEnd = -Infinity;
168
+ for (const c of sorted) {
169
+ const last = out.at(-1);
170
+ if (!last || (c.start - prevEnd >= gap && c.start - last.start >= min)) {
171
+ out.push({ start: c.start, title: cueTitle(c.text) });
172
+ }
173
+ prevEnd = Math.max(prevEnd, c.end);
174
+ }
175
+ return out;
176
+ }
177
+ export function buildChaptersMuxArgs(input, metaFile, output, opts) {
178
+ const subs = opts.subtitles;
179
+ return [
180
+ "-y",
181
+ "-i", input,
182
+ "-f", "ffmetadata", "-i", metaFile,
183
+ ...(subs ? ["-i", subs] : []),
184
+ "-map", "0:v", "-map", "0:a?",
185
+ ...(subs ? ["-map", "2:s:0"] : ["-map", "0:s?"]),
186
+ "-map_metadata", "0",
187
+ "-map_chapters", "1",
188
+ "-c", "copy",
189
+ ...(subs ? ["-c:s", opts.container === ".mkv" ? "copy" : "mov_text"] : []),
190
+ ...(subs && opts.language ? ["-metadata:s:s:0", `language=${opts.language}`] : []),
191
+ ...(opts.container === ".mkv" ? [] : ["-movflags", "+faststart"]),
192
+ output,
193
+ ];
194
+ }
195
+ export function buildChaptersProbeArgs(input) {
196
+ return ["-v", "quiet", "-print_format", "json", "-show_chapters", input];
197
+ }
198
+ export function parseChaptersProbe(stdout) {
199
+ let data;
200
+ try {
201
+ data = JSON.parse(stdout);
202
+ }
203
+ catch {
204
+ return [];
205
+ }
206
+ return (data.chapters ?? []).flatMap((c, i) => {
207
+ const start = Number(c.start_time);
208
+ const end = Number(c.end_time);
209
+ if (!Number.isFinite(start) || !Number.isFinite(end))
210
+ return [];
211
+ return [{ start: r3(start), end: r3(end), title: c.tags?.title ?? `Chapter ${i + 1}` }];
212
+ });
213
+ }
214
+ export async function probeChapters(input, signal) {
215
+ const { ffprobe } = requireFfmpeg();
216
+ const res = await runCapture(ffprobe, buildChaptersProbeArgs(input), 30_000, { signal });
217
+ return res.code === 0 ? parseChaptersProbe(res.stdout) : [];
218
+ }
219
+ export async function markersOrChapters(video, signal) {
220
+ const sidecar = readMarkers(video);
221
+ if (sidecar.length > 0)
222
+ return { markers: sidecar, from: "sidecar" };
223
+ const embedded = await probeChapters(video, signal);
224
+ if (embedded.length > 0)
225
+ return { markers: embedded.map((c) => ({ t: c.start, label: c.title })), from: "chapters" };
226
+ return { markers: [], from: null };
227
+ }
@@ -66,17 +66,24 @@ export function cutsFor(idle, minIdleSec, keep) {
66
66
  .filter((r) => r.end - r.start > 0.05)
67
67
  .map((r) => ({ start: Number(r.start.toFixed(3)), end: Number(r.end.toFixed(3)) }));
68
68
  }
69
- export function buildCutIdleArgs(input, output, cuts, withAudio, quality = "standard") {
69
+ export function cutFilters(cuts) {
70
70
  if (cuts.length === 0)
71
71
  throw new ScreencastError("Nothing to cut.");
72
72
  if (cuts.length > MAX_CUTS)
73
73
  throw new ScreencastError(`Too many idle stretches (${cuts.length}); raise minIdleSec.`);
74
74
  const drop = sumExpr(cuts.map((c) => `between(t,${c.start},${c.end})`));
75
75
  const removed = sumExpr(cuts.map((c) => `clip(T-${c.start},0,${Number((c.end - c.start).toFixed(3))})`));
76
+ return {
77
+ video: `select='not(${drop})',setpts='(T-(${removed}))/TB'`,
78
+ audio: `asetnsamples=n=256:p=0,aselect='not(${drop})',asetpts=N/SR/TB`,
79
+ };
80
+ }
81
+ export function buildCutIdleArgs(input, output, cuts, withAudio, quality = "standard") {
82
+ const f = cutFilters(cuts);
76
83
  return [
77
84
  "-y", "-i", input,
78
- "-vf", `select='not(${drop})',setpts='(T-(${removed}))/TB'`,
79
- ...(withAudio ? ["-af", `aselect='not(${drop})',asetpts=N/SR/TB`] : ["-an"]),
85
+ "-vf", f.video,
86
+ ...(withAudio ? ["-af", f.audio] : ["-an"]),
80
87
  ...resolveQuality(quality),
81
88
  ...(withAudio ? ["-c:a", "aac", "-b:a", "160k"] : []),
82
89
  output,
@@ -0,0 +1,155 @@
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
+ import { mapWindow } from "./timeline.js";
7
+ export const BADGE_POSITIONS = ["bottom", "bottom-left", "bottom-right", "top", "top-left", "top-right"];
8
+ export const DEFAULT_LINGER_SEC = 1.2;
9
+ export const DOUBLE_CLICK_SEC = 0.5;
10
+ const DOUBLE_CLICK_PX = 8;
11
+ export const MAX_BADGE_LABELS = 100;
12
+ export const TYPING_LABEL = "Typing…";
13
+ const MODIFIERS = new Set(["Ctrl", "Alt", "Shift", "Win"]);
14
+ 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|[=\-,./`[\];'\\])$/;
15
+ export function formatChord(keys, display = "shortcuts") {
16
+ const parts = keys.split("+");
17
+ const key = parts.pop();
18
+ if (key === undefined || parts.length === 0 || !KEY_NAME.test(key))
19
+ return null;
20
+ if (!parts.every((p) => MODIFIERS.has(p)) || new Set(parts).size !== parts.length)
21
+ return null;
22
+ return [...parts, display === "masked" ? "…" : key].join(" + ");
23
+ }
24
+ const BUTTON_LABEL = {
25
+ left: "Click",
26
+ right: "Right click",
27
+ middle: "Middle click",
28
+ x1: "Back button",
29
+ x2: "Forward button",
30
+ };
31
+ const r3 = (n) => Math.round(n * 1000) / 1000;
32
+ export function planBadges(events, opts = {}) {
33
+ const linger = opts.lingerSec ?? DEFAULT_LINGER_SEC;
34
+ if (!(linger > 0))
35
+ throw new ScreencastError("lingerSec must be positive.");
36
+ const display = opts.keys ?? "shortcuts";
37
+ const sorted = [...events].filter((e) => Number.isFinite(e.t) && e.t >= 0).sort((a, b) => a.t - b.t);
38
+ const raw = [];
39
+ for (const e of sorted) {
40
+ if (e.type === "key" && e.keys) {
41
+ const label = formatChord(e.keys, display);
42
+ if (!label)
43
+ continue;
44
+ const prev = raw.at(-1);
45
+ if (prev && prev.kind === "shortcut" && prev.base === label && e.t - prev.last <= linger) {
46
+ prev.count++;
47
+ prev.last = e.t;
48
+ prev.label = `${label} ×${prev.count}`;
49
+ prev.to = e.t + linger;
50
+ continue;
51
+ }
52
+ raw.push({ from: e.t, to: e.t + linger, label, base: label, kind: "shortcut", count: 1, last: e.t });
53
+ }
54
+ else if (e.type === "down" && opts.clicks !== false && e.inFrame) {
55
+ const base = BUTTON_LABEL[e.button ?? "left"] ?? "Click";
56
+ const prev = raw.at(-1);
57
+ if (base === "Click" && prev && prev.kind === "click" && prev.base === "Click" && prev.count < 3 &&
58
+ e.t - prev.last <= DOUBLE_CLICK_SEC &&
59
+ Math.abs(e.x - (prev.x ?? e.x)) <= DOUBLE_CLICK_PX && Math.abs(e.y - (prev.y ?? e.y)) <= DOUBLE_CLICK_PX) {
60
+ prev.count++;
61
+ prev.last = e.t;
62
+ prev.label = prev.count === 2 ? "Double click" : "Triple click";
63
+ prev.to = e.t + linger;
64
+ continue;
65
+ }
66
+ 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 });
67
+ }
68
+ else if (e.type === "typing" && opts.typing !== false) {
69
+ const end = e.t + Math.max(e.durationSec ?? 0, 0);
70
+ const prev = raw.at(-1);
71
+ if (prev && prev.kind === "typing" && e.t <= prev.to) {
72
+ prev.to = Math.max(prev.to, end + linger / 2);
73
+ prev.last = e.t;
74
+ continue;
75
+ }
76
+ raw.push({ from: e.t, to: end + linger / 2, label: TYPING_LABEL, base: TYPING_LABEL, kind: "typing", count: 1, last: e.t });
77
+ }
78
+ }
79
+ const out = [];
80
+ raw.forEach((b, i) => {
81
+ const next = raw[i + 1];
82
+ const to = next ? Math.min(b.to, next.from) : b.to;
83
+ if (to - b.from >= 0.05)
84
+ out.push({ from: r3(b.from), to: r3(to), label: b.label, kind: b.kind });
85
+ });
86
+ return out;
87
+ }
88
+ export function groupBadges(badges) {
89
+ const groups = new Map();
90
+ for (const b of badges) {
91
+ let g = groups.get(b.label);
92
+ if (!g) {
93
+ g = { label: b.label, windows: [] };
94
+ groups.set(b.label, g);
95
+ }
96
+ g.windows.push([b.from, b.to]);
97
+ }
98
+ if (groups.size > MAX_BADGE_LABELS) {
99
+ throw new ScreencastError(`${groups.size} different badges is more than ${MAX_BADGE_LABELS}; trim the video or turn off keys or clicks.`);
100
+ }
101
+ return [...groups.values()];
102
+ }
103
+ export function mapBadges(badges, map) {
104
+ return badges.flatMap((b) => {
105
+ const w = map(b.from, b.to);
106
+ return w && w[1] - w[0] >= 0.05 ? [{ ...b, from: r3(w[0]), to: r3(w[1]) }] : [];
107
+ });
108
+ }
109
+ export function retimeBadges(badges, ops) {
110
+ return mapBadges(badges, (from, to) => mapWindow(from, to, ops));
111
+ }
112
+ export function badgeSize(frameH, size) {
113
+ if (size !== undefined) {
114
+ if (!(size >= 8 && size <= 400))
115
+ throw new ScreencastError("size must be between 8 and 400.");
116
+ return Math.round(size);
117
+ }
118
+ return Math.max(14, Math.round(frameH * 0.045));
119
+ }
120
+ export function keystrokeSteps(groups, assets, style, frame, input, tag) {
121
+ if (groups.length === 0)
122
+ throw new ScreencastError("No badges to draw.");
123
+ const size = badgeSize(frame.height, style.size);
124
+ const border = Math.round(size / 3);
125
+ const margin = border + Math.round(size * 0.6);
126
+ const pos = style.position ?? "bottom";
127
+ const x = pos.endsWith("left") ? `${margin}` : pos.endsWith("right") ? `w-tw-${margin}` : "(w-tw)/2";
128
+ const y = pos.startsWith("top") ? `${margin}` : `h-lh-${margin}`;
129
+ const color = validateColor(style.color ?? "white");
130
+ const steps = [];
131
+ let cur = input;
132
+ groups.forEach((g, i) => {
133
+ const file = assets.textFiles[g.label];
134
+ if (!file)
135
+ throw new ScreencastError(`Internal: no text file for badge "${g.label}".`);
136
+ const enable = sumExpr(g.windows.map(([a, b]) => `between(t,${a},${b})`));
137
+ const out = `[${tag}k${i}]`;
138
+ steps.push(`${cur}drawtext=fontfile=${escapeFilterPath(assets.fontFile)}:textfile=${escapeFilterPath(file)}:expansion=none` +
139
+ `:fontsize=${size}:fontcolor=${color}:box=1:boxcolor=black@0.6:boxborderw=${border}` +
140
+ `:x=${x}:y=${y}:enable='${enable}'${out}`);
141
+ cur = out;
142
+ });
143
+ return { steps, out: cur };
144
+ }
145
+ export function buildKeystrokeArgs(input, output, groups, assets, style, frame, quality = "standard") {
146
+ const { steps, out } = keystrokeSteps(groups, assets, style, frame, "[0:v]", "");
147
+ return [
148
+ "-y", "-i", input,
149
+ "-filter_complex", steps.join(";"),
150
+ "-map", out, "-map", "0:a?",
151
+ ...resolveQuality(quality),
152
+ "-c:a", "copy",
153
+ output,
154
+ ];
155
+ }
@@ -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)