@tmhs/screencast-mcp 0.49.0 → 0.50.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 (133) hide show
  1. package/README.md +13 -8
  2. package/dist/index.js +550 -106
  3. package/dist/wgcRecorder.js +15 -139
  4. package/package.json +8 -4
  5. package/assets/.gitkeep +0 -0
  6. package/assets/icon.png +0 -0
  7. package/dist/cli.js +0 -516
  8. package/dist/context.js +0 -50
  9. package/dist/prompts.js +0 -95
  10. package/dist/resources.js +0 -93
  11. package/dist/server.js +0 -174
  12. package/dist/setup.js +0 -438
  13. package/dist/tools/addMarker.js +0 -93
  14. package/dist/tools/assembleHighlights.js +0 -69
  15. package/dist/tools/backdrop.js +0 -89
  16. package/dist/tools/bugReport.js +0 -266
  17. package/dist/tools/burnSubtitles.js +0 -56
  18. package/dist/tools/callout.js +0 -103
  19. package/dist/tools/chapters.js +0 -156
  20. package/dist/tools/clip.js +0 -52
  21. package/dist/tools/compress.js +0 -51
  22. package/dist/tools/concat.js +0 -67
  23. package/dist/tools/contactSheet.js +0 -135
  24. package/dist/tools/convert.js +0 -46
  25. package/dist/tools/crop.js +0 -43
  26. package/dist/tools/cursor.js +0 -87
  27. package/dist/tools/cutByTranscript.js +0 -86
  28. package/dist/tools/cutIdle.js +0 -84
  29. package/dist/tools/deleteRecording.js +0 -119
  30. package/dist/tools/denoise.js +0 -60
  31. package/dist/tools/doctor.js +0 -146
  32. package/dist/tools/exportGif.js +0 -57
  33. package/dist/tools/exportPreset.js +0 -48
  34. package/dist/tools/extractAudio.js +0 -65
  35. package/dist/tools/findText.js +0 -196
  36. package/dist/tools/getMediaInfo.js +0 -36
  37. package/dist/tools/getSession.js +0 -40
  38. package/dist/tools/indexRecording.js +0 -195
  39. package/dist/tools/keystrokeOverlay.js +0 -131
  40. package/dist/tools/listAudioDevices.js +0 -35
  41. package/dist/tools/listSessions.js +0 -28
  42. package/dist/tools/listTargets.js +0 -76
  43. package/dist/tools/listVideoDevices.js +0 -26
  44. package/dist/tools/musicBed.js +0 -55
  45. package/dist/tools/narrate.js +0 -86
  46. package/dist/tools/normalizeAudio.js +0 -60
  47. package/dist/tools/overlay.js +0 -62
  48. package/dist/tools/pauseRecording.js +0 -44
  49. package/dist/tools/pipeline.js +0 -400
  50. package/dist/tools/readEvents.js +0 -98
  51. package/dist/tools/redactRegion.js +0 -70
  52. package/dist/tools/reframe.js +0 -46
  53. package/dist/tools/resumeRecording.js +0 -46
  54. package/dist/tools/reviewRecording.js +0 -163
  55. package/dist/tools/sampleFrames.js +0 -200
  56. package/dist/tools/saveReplay.js +0 -90
  57. package/dist/tools/scale.js +0 -44
  58. package/dist/tools/screenDiff.js +0 -86
  59. package/dist/tools/screenshot.js +0 -76
  60. package/dist/tools/searchRecording.js +0 -79
  61. package/dist/tools/speed.js +0 -46
  62. package/dist/tools/startRecording.js +0 -398
  63. package/dist/tools/stepGuide.js +0 -250
  64. package/dist/tools/stopRecording.js +0 -132
  65. package/dist/tools/titleCard.js +0 -67
  66. package/dist/tools/transcribe.js +0 -66
  67. package/dist/tools/trim.js +0 -57
  68. package/dist/tools/waitForChange.js +0 -128
  69. package/dist/tools/xfadeTransition.js +0 -58
  70. package/dist/tools/zoom.js +0 -149
  71. package/dist/utils/anim.js +0 -54
  72. package/dist/utils/animExport.js +0 -56
  73. package/dist/utils/argPaths.js +0 -39
  74. package/dist/utils/audio.js +0 -113
  75. package/dist/utils/audioDevices.js +0 -107
  76. package/dist/utils/backdrop.js +0 -151
  77. package/dist/utils/bugReport.js +0 -172
  78. package/dist/utils/callout.js +0 -90
  79. package/dist/utils/calloutAssets.js +0 -42
  80. package/dist/utils/capabilities.js +0 -96
  81. package/dist/utils/captions.js +0 -103
  82. package/dist/utils/chapters.js +0 -227
  83. package/dist/utils/consent.js +0 -29
  84. package/dist/utils/cursor.js +0 -317
  85. package/dist/utils/diff.js +0 -184
  86. package/dist/utils/errors.js +0 -29
  87. package/dist/utils/events.js +0 -403
  88. package/dist/utils/expr.js +0 -11
  89. package/dist/utils/ffmpeg.js +0 -285
  90. package/dist/utils/fontCoverage.js +0 -177
  91. package/dist/utils/fonts.js +0 -154
  92. package/dist/utils/gpu.js +0 -219
  93. package/dist/utils/idle.js +0 -91
  94. package/dist/utils/images.js +0 -38
  95. package/dist/utils/jobs.js +0 -129
  96. package/dist/utils/keystrokes.js +0 -155
  97. package/dist/utils/lifecycle.js +0 -233
  98. package/dist/utils/logging.js +0 -75
  99. package/dist/utils/media.js +0 -574
  100. package/dist/utils/monitors.js +0 -124
  101. package/dist/utils/narrate.js +0 -233
  102. package/dist/utils/ocr.js +0 -222
  103. package/dist/utils/ocrScan.js +0 -91
  104. package/dist/utils/paths.js +0 -155
  105. package/dist/utils/pause.js +0 -190
  106. package/dist/utils/pipeline.js +0 -361
  107. package/dist/utils/player.js +0 -85
  108. package/dist/utils/pool.js +0 -29
  109. package/dist/utils/produce.js +0 -298
  110. package/dist/utils/recipes.js +0 -71
  111. package/dist/utils/recorder.js +0 -173
  112. package/dist/utils/recordingFiles.js +0 -32
  113. package/dist/utils/recordingIndex.js +0 -312
  114. package/dist/utils/replay.js +0 -283
  115. package/dist/utils/resolveTarget.js +0 -25
  116. package/dist/utils/retention.js +0 -48
  117. package/dist/utils/roots.js +0 -43
  118. package/dist/utils/sessions.js +0 -499
  119. package/dist/utils/sheet.js +0 -59
  120. package/dist/utils/stepGuide.js +0 -231
  121. package/dist/utils/steps.js +0 -88
  122. package/dist/utils/still.js +0 -38
  123. package/dist/utils/targetList.js +0 -64
  124. package/dist/utils/targets.js +0 -265
  125. package/dist/utils/timeline.js +0 -85
  126. package/dist/utils/toolSpec.js +0 -31
  127. package/dist/utils/toolsets.js +0 -134
  128. package/dist/utils/transcriptCut.js +0 -149
  129. package/dist/utils/validate.js +0 -23
  130. package/dist/utils/waitLoop.js +0 -50
  131. package/dist/utils/wgc.js +0 -84
  132. package/dist/utils/windows.js +0 -192
  133. package/dist/utils/zoom.js +0 -234
@@ -1,103 +0,0 @@
1
- import { existsSync } from "node:fs";
2
- import { ScreencastError } from "./errors.js";
3
- import { escapeFilterPath } from "./fonts.js";
4
- import { resolveQuality } from "./targets.js";
5
- export const WHISPER_MODEL_ENV = "SCREENCAST_WHISPER_MODEL";
6
- const MODEL_HINT = `Download a whisper.cpp model (ggml-base.en.bin is a good start; ggml-tiny.en.bin is fastest) from ` +
7
- `https://huggingface.co/ggerganov/whisper.cpp and pass its path as model, or set ${WHISPER_MODEL_ENV}.`;
8
- export function resolveWhisperModel(arg, env = process.env) {
9
- const model = arg ?? env[WHISPER_MODEL_ENV];
10
- if (!model || model.trim().length === 0) {
11
- throw new ScreencastError("No whisper model given.", MODEL_HINT);
12
- }
13
- if (!existsSync(model))
14
- throw new ScreencastError(`Whisper model not found: ${model}`, MODEL_HINT);
15
- return model;
16
- }
17
- export function buildTranscribeArgs(input, model, srtOut, language = "auto", words = false) {
18
- if (!/^[a-z]{2,3}$|^auto$/.test(language)) {
19
- throw new ScreencastError(`language must be a code like "en" or "auto", got "${language}".`);
20
- }
21
- return [
22
- "-y", "-v", "error", "-i", input, "-vn",
23
- "-af",
24
- `aresample=16000,whisper=model=${escapeFilterPath(model)}:language=${language}:format=srt:` +
25
- `destination=${escapeFilterPath(srtOut)}:use_gpu=false` + (words ? ":max_len=1" : ""),
26
- "-f", "null", "-",
27
- ];
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
- }
40
- const TIME = /(\d+):(\d{2}):(\d{2})[,.](\d{3})/;
41
- const toSec = (m) => Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) + Number(m[4]) / 1000;
42
- function fmt(sec) {
43
- const ms = Math.round(sec * 1000);
44
- const h = Math.floor(ms / 3_600_000);
45
- const m = Math.floor((ms % 3_600_000) / 60_000);
46
- const s = Math.floor((ms % 60_000) / 1000);
47
- const pad = (n, w = 2) => String(n).padStart(w, "0");
48
- return `${pad(h)}:${pad(m)}:${pad(s)},${pad(ms % 1000, 3)}`;
49
- }
50
- export function parseSrt(srt, opts = {}) {
51
- const cues = [];
52
- for (const block of srt.replace(/\r\n/g, "\n").split(/\n\s*\n/)) {
53
- const lines = block.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
54
- const i = lines.findIndex((l) => l.includes("-->"));
55
- const header = lines[i];
56
- if (header === undefined)
57
- continue;
58
- const [a, b] = header.split("-->");
59
- const sa = a?.match(TIME);
60
- const sb = b?.match(TIME);
61
- if (!sa || !sb)
62
- continue;
63
- const text = lines.slice(i + 1).join("\n");
64
- if (!text)
65
- continue;
66
- const n = opts.index && i > 0 && /^\d+$/.test(lines[i - 1]) ? Number(lines[i - 1]) : undefined;
67
- cues.push({ start: toSec(sa), end: toSec(sb), text, ...(n !== undefined && { index: n }) });
68
- }
69
- return cues;
70
- }
71
- export function normalizeCues(cues) {
72
- const sorted = [...cues].sort((p, q) => p.start - q.start);
73
- return sorted
74
- .map((c, i) => {
75
- const next = sorted[i + 1];
76
- const end = next ? Math.min(c.end, next.start) : c.end;
77
- return { ...c, end };
78
- })
79
- .filter((c) => c.end > c.start);
80
- }
81
- export function formatSrt(cues) {
82
- return cues.map((c, i) => `${i + 1}\n${fmt(c.start)} --> ${fmt(c.end)}\n${c.text}\n`).join("\n");
83
- }
84
- export const CAPTION_STYLES = {
85
- clean: "FontName=Inter,FontSize=16,PrimaryColour=&H00FFFFFF,OutlineColour=&H00000000,BorderStyle=1,Outline=1.5,Shadow=0,MarginV=16",
86
- social: "FontName=Inter,Bold=1,FontSize=22,PrimaryColour=&H00FFFFFF,BackColour=&H99000000,BorderStyle=3,Outline=6,Shadow=0,MarginV=40",
87
- };
88
- export function subtitlesFilter(subtitles, fontsDir, style = "clean") {
89
- const force = style === null ? null : CAPTION_STYLES[style];
90
- if (force === undefined)
91
- throw new ScreencastError(`Unknown caption style "${style}".`);
92
- return (`subtitles=filename=${escapeFilterPath(subtitles)}:fontsdir=${escapeFilterPath(fontsDir)}` +
93
- (force ? `:force_style='${force}'` : ""));
94
- }
95
- export function buildBurnSubtitlesArgs(input, subtitles, output, fontsDir, style = "clean", quality = "standard") {
96
- return [
97
- "-y", "-i", input,
98
- "-vf", subtitlesFilter(subtitles, fontsDir, style),
99
- ...resolveQuality(quality),
100
- "-c:a", "copy",
101
- output,
102
- ];
103
- }
@@ -1,227 +0,0 @@
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
- }
@@ -1,29 +0,0 @@
1
- import { errorMessage, ScreencastError } from "./errors.js";
2
- export const CONFIRM_CAPTURE_ENV = "SCREENCAST_CONFIRM_CAPTURE";
3
- export const CONFIRM_TIMEOUT_MS = 5 * 60 * 1000;
4
- export function confirmCaptureEnabled(env = process.env) {
5
- return ["1", "true", "yes", "on"].includes((env[CONFIRM_CAPTURE_ENV] ?? "").trim().toLowerCase());
6
- }
7
- export function describeTarget(target, window) {
8
- if (window)
9
- return `window "${window.matchedTitle}"`;
10
- return target === "full" ? "the full screen (all monitors)" : target;
11
- }
12
- export async function confirmCapture(server, request, signal) {
13
- if (!confirmCaptureEnabled())
14
- return;
15
- if (!server.server.getClientCapabilities()?.elicitation?.form) {
16
- throw new ScreencastError(`Capture blocked: ${CONFIRM_CAPTURE_ENV} requires the user to confirm each capture, ` +
17
- "but this client does not support MCP elicitation. Nothing was captured.", `Use a client that supports elicitation, or unset ${CONFIRM_CAPTURE_ENV} to capture without confirmation.`);
18
- }
19
- let action;
20
- try {
21
- ({ action } = await server.server.elicitInput({ message: request, requestedSchema: { type: "object", properties: {} } }, { signal, timeout: CONFIRM_TIMEOUT_MS }));
22
- }
23
- catch (err) {
24
- throw new ScreencastError(`Capture blocked: the confirmation request failed (${errorMessage(err)}). Nothing was captured.`);
25
- }
26
- if (action !== "accept") {
27
- throw new ScreencastError(`Capture ${action === "decline" ? "declined" : "cancelled"} by the user. Nothing was captured.`);
28
- }
29
- }
@@ -1,317 +0,0 @@
1
- import { fileURLToPath } from "node:url";
2
- import { ScreencastError } from "./errors.js";
3
- import { escapeFilterPath } from "./fonts.js";
4
- import { MOVE_SAMPLE_MS } from "./events.js";
5
- import { mapTime, mapWindow } from "./timeline.js";
6
- import { resolveQuality } from "./targets.js";
7
- export const CURSOR_SPRITE = { w: 114, h: 168, hotX: 9, hotY: 9, arrowH: 135 };
8
- export function cursorSpritePath() {
9
- return fileURLToPath(new URL("../../assets/cursor/arrow.png", import.meta.url));
10
- }
11
- export const DEFAULT_SMOOTHING = 0.5;
12
- export const DEFAULT_HIDE_AFTER_SEC = 2;
13
- export const DEFAULT_CURSOR_SIZE = 1.5;
14
- export const RIPPLE_SEC = 0.4;
15
- const SIM_HZ = 240;
16
- const PATH_EVERY = 4;
17
- const SIMPLIFY_PX = 0.35;
18
- const POSITION_TYPES = new Set(["move", "down", "up", "wheel"]);
19
- const r3 = (n) => Math.round(n * 1000) / 1000;
20
- export function springFor(smoothing) {
21
- const omega = 6 + (1 - smoothing) * 34;
22
- return { omega, lead: Math.min(2 / omega, 0.2) };
23
- }
24
- export function targetPath(samples) {
25
- const out = [];
26
- const step = MOVE_SAMPLE_MS / 1000;
27
- for (const s of samples) {
28
- const prev = out.at(-1);
29
- if (prev && s.t - prev.t > step * 2 && (prev.x !== s.x || prev.y !== s.y)) {
30
- out.push({ t: s.t - step, x: prev.x, y: prev.y });
31
- }
32
- if (prev && s.t === prev.t)
33
- out[out.length - 1] = s;
34
- else
35
- out.push(s);
36
- }
37
- return out;
38
- }
39
- export function pathAt(path, t, from = 0) {
40
- if (path.length === 0)
41
- return { x: 0, y: 0, i: 0 };
42
- let i = Math.max(0, Math.min(from, path.length - 1));
43
- while (i > 0 && path[i].t > t)
44
- i--;
45
- while (i < path.length - 1 && path[i + 1].t <= t)
46
- i++;
47
- const a = path[i];
48
- const b = path[i + 1];
49
- if (!b || t <= a.t)
50
- return { x: a.x, y: a.y, i };
51
- const f = (t - a.t) / (b.t - a.t);
52
- return { x: a.x + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f, i };
53
- }
54
- export function springPath(target, omega, lead, from, to) {
55
- if (target.length === 0)
56
- return [];
57
- const dt = 1 / SIM_HZ;
58
- let hint = 0;
59
- const at = (t) => {
60
- const p = pathAt(target, t + lead, hint);
61
- hint = p.i;
62
- return p;
63
- };
64
- const start = at(from);
65
- let x = start.x;
66
- let y = start.y;
67
- let vx = 0;
68
- let vy = 0;
69
- const out = [{ t: r3(from), x, y }];
70
- const e = Math.exp(-omega * dt);
71
- const steps = Math.max(0, Math.ceil((to - from) * SIM_HZ));
72
- for (let n = 1; n <= steps; n++) {
73
- const t = Math.min(to, from + n * dt);
74
- const p = at(t);
75
- const cx = x - p.x;
76
- const cy = y - p.y;
77
- const tx = (vx + omega * cx) * dt;
78
- const ty = (vy + omega * cy) * dt;
79
- vx = (vx - omega * tx) * e;
80
- vy = (vy - omega * ty) * e;
81
- x = p.x + (cx + tx) * e;
82
- y = p.y + (cy + ty) * e;
83
- if (n % PATH_EVERY === 0 || n === steps)
84
- out.push({ t: r3(t), x, y });
85
- }
86
- return out;
87
- }
88
- export function simplifyPath(path, tol = SIMPLIFY_PX) {
89
- if (path.length <= 2)
90
- return [...path];
91
- const keep = new Uint8Array(path.length);
92
- keep[0] = 1;
93
- keep[path.length - 1] = 1;
94
- const stack = [[0, path.length - 1]];
95
- while (stack.length > 0) {
96
- const [a, b] = stack.pop();
97
- const A = path[a];
98
- const B = path[b];
99
- let worst = -1;
100
- let at = -1;
101
- for (let i = a + 1; i < b; i++) {
102
- const P = path[i];
103
- const f = B.t > A.t ? (P.t - A.t) / (B.t - A.t) : 0;
104
- const d = Math.hypot(P.x - (A.x + (B.x - A.x) * f), P.y - (A.y + (B.y - A.y) * f));
105
- if (d > worst) {
106
- worst = d;
107
- at = i;
108
- }
109
- }
110
- if (worst > tol) {
111
- keep[at] = 1;
112
- stack.push([a, at], [at, b]);
113
- }
114
- }
115
- return path.filter((_, i) => keep[i] === 1);
116
- }
117
- function mergeWindows(ws) {
118
- const out = [];
119
- for (const w of [...ws].sort((a, b) => a[0] - b[0])) {
120
- const last = out.at(-1);
121
- if (last && w[0] <= last[1])
122
- last[1] = Math.max(last[1], w[1]);
123
- else
124
- out.push([w[0], w[1]]);
125
- }
126
- return out;
127
- }
128
- export function planCursor(events, opts = {}, endSec = null) {
129
- const smoothing = opts.smoothing ?? DEFAULT_SMOOTHING;
130
- if (!(smoothing >= 0 && smoothing <= 1))
131
- throw new ScreencastError("smoothing must be between 0 and 1.");
132
- const hideAfter = opts.hideAfterSec ?? DEFAULT_HIDE_AFTER_SEC;
133
- if (!(hideAfter >= 0))
134
- throw new ScreencastError("hideAfterSec must be 0 or more.");
135
- const samples = events
136
- .filter((e) => POSITION_TYPES.has(e.type) && Number.isFinite(e.t) && e.t >= 0 && Number.isFinite(e.x) && Number.isFinite(e.y))
137
- .filter((e) => endSec === null || e.t <= endSec)
138
- .sort((a, b) => a.t - b.t);
139
- if (samples.length === 0)
140
- return { path: [], visible: [], clicks: [] };
141
- const target = targetPath(samples.map((e) => ({ t: e.t, x: e.x, y: e.y })));
142
- const first = target[0].t;
143
- const last = target.at(-1).t;
144
- let path;
145
- let lead = 0;
146
- if (smoothing === 0) {
147
- path = target.map((p) => ({ ...p }));
148
- if (endSec !== null && endSec > last)
149
- path.push({ ...target.at(-1), t: endSec });
150
- }
151
- else {
152
- const spring = springFor(smoothing);
153
- lead = spring.lead;
154
- const from = Math.max(0, first - lead);
155
- const to = Math.max(from, endSec ?? last + 8 / spring.omega);
156
- path = springPath(target, spring.omega, lead, from, to);
157
- }
158
- const start = Math.max(0, first - lead);
159
- const visible = hideAfter === 0
160
- ? [[start, endSec ?? Infinity]]
161
- : mergeWindows(samples.map((e) => [Math.max(0, e.t - lead), e.t + hideAfter]));
162
- const clicks = samples.filter((e) => e.type === "down").map((e) => ({ t: e.t, x: e.x, y: e.y }));
163
- return {
164
- path,
165
- visible: visible.map(([a, b]) => [r3(a), endSec !== null ? Math.min(b, endSec) : b]).filter(([a, b]) => b > a),
166
- clicks,
167
- };
168
- }
169
- const IDENTITY = { sx: 1, sy: 1, ox: 0, oy: 0 };
170
- export function transformCursor(plan, ops = [], geo = IDENTITY) {
171
- const move = (p) => {
172
- const t = mapTime(p.t, ops);
173
- return t === null ? null : { t: r3(t), x: p.x * geo.sx + geo.ox, y: p.y * geo.sy + geo.oy };
174
- };
175
- const path = [];
176
- for (const p of plan.path) {
177
- const m = move(p);
178
- if (!m)
179
- continue;
180
- if (path.length > 0 && path.at(-1).t >= m.t)
181
- path[path.length - 1] = { ...m, t: path.at(-1).t };
182
- else
183
- path.push(m);
184
- }
185
- const visible = plan.visible.flatMap(([a, b]) => {
186
- const w = mapWindow(a, b, ops);
187
- return w && w[1] - w[0] >= 0.05 ? [[r3(w[0]), Number.isFinite(w[1]) ? r3(w[1]) : w[1]]] : [];
188
- });
189
- const clicks = plan.clicks.flatMap((c) => {
190
- const m = move(c);
191
- return m ? [m] : [];
192
- });
193
- return { path: simplifyPath(path), visible, clicks };
194
- }
195
- const num = (n, d = 2) => {
196
- const v = Number(n.toFixed(d));
197
- return Object.is(v, -0) ? "0" : String(v);
198
- };
199
- export function linearExpr(v0, t0, k) {
200
- const kk = Number(k.toFixed(3));
201
- if (kk === 0)
202
- return num(v0);
203
- return `${num(v0)}${kk < 0 ? "-" : "+"}(t-${num(t0, 3)})*${num(Math.abs(kk), 3)}`;
204
- }
205
- export function cursorLayout(frameH, size = DEFAULT_CURSOR_SIZE) {
206
- if (!(size >= 0.25 && size <= 8))
207
- throw new ScreencastError("size must be between 0.25 and 8.");
208
- const arrowH = Math.max(8, frameH * 0.025 * size);
209
- const k = arrowH / CURSOR_SPRITE.arrowH;
210
- const d = Math.max(12, Math.round(arrowH * 2.2));
211
- return {
212
- spriteW: Math.max(2, Math.round(CURSOR_SPRITE.w * k)),
213
- spriteH: Math.max(2, Math.round(CURSOR_SPRITE.h * k)),
214
- hotX: CURSOR_SPRITE.hotX * k,
215
- hotY: CURSOR_SPRITE.hotY * k,
216
- ripples: [0.45, 0.72, 1].map((f) => Math.max(6, Math.round((d * f) / 2) * 2)),
217
- spotRadius: Math.max(24, Math.round(frameH * 0.12)),
218
- };
219
- }
220
- export function formatCommands(cmds) {
221
- const byTime = new Map();
222
- for (const c of [...cmds].sort((a, b) => a.t - b.t)) {
223
- const key = num(Math.max(0, c.t), 3);
224
- const list = byTime.get(key) ?? [];
225
- list.push(c.text);
226
- byTime.set(key, list);
227
- }
228
- return [...byTime.entries()].map(([t, list]) => `${t} ${list.join(", ")};`).join("\n") + "\n";
229
- }
230
- function pathCommands(path, target, dx, dy) {
231
- return path.map((p, i) => {
232
- const n = path[i + 1];
233
- const span = n ? n.t - p.t : 0;
234
- const kx = n && span > 0 ? (n.x - p.x) / span : 0;
235
- const ky = n && span > 0 ? (n.y - p.y) / span : 0;
236
- return {
237
- t: p.t,
238
- text: `${target} x ${linearExpr(p.x + dx, p.t, kx)}, ${target} y ${linearExpr(p.y + dy, p.t, ky)}`,
239
- };
240
- });
241
- }
242
- function windowCommands(windows, target) {
243
- return windows.flatMap(([a, b]) => [
244
- { t: a, text: `${target} enable 1` },
245
- ...(Number.isFinite(b) ? [{ t: b, text: `${target} enable 0` }] : []),
246
- ]);
247
- }
248
- export function cursorSteps(plan, style, frame, input, firstInput, tag, sprite, commandsFile) {
249
- if (plan.path.length === 0)
250
- throw new ScreencastError("No cursor positions to draw.");
251
- const L = cursorLayout(frame.height, style.size);
252
- const { width: W, height: H } = frame;
253
- const name = (s) => `overlay@${tag}c${s}`;
254
- const steps = [];
255
- const cmds = [];
256
- const p0 = plan.path[0];
257
- let cur = `[${tag}cm]`;
258
- steps.push(`${input}sendcmd=f=${escapeFilterPath(commandsFile)}${cur}`);
259
- const layer = (src, id, dx, dy, windows) => {
260
- const out = `[${tag}c${id}o]`;
261
- steps.push(`${cur}${src}${name(id)}=x=${num(p0.x + dx)}:y=${num(p0.y + dy)}:enable=0${out}`);
262
- cmds.push(...windowCommands(windows, name(id)));
263
- cur = out;
264
- };
265
- if (style.spotlight) {
266
- const q = 4;
267
- const mw = Math.ceil((2 * W) / q);
268
- const mh = Math.ceil((2 * H) / q);
269
- const r = L.spotRadius / q;
270
- const feather = r * 0.8;
271
- const a = `255*0.55*clip((hypot(X-${num(mw / 2)},Y-${num(mh / 2)})-${num(r)})/${num(feather)},0,1)`;
272
- steps.push(`color=c=black:s=${mw}x${mh}:r=1:d=1,format=rgba,geq=r=0:g=0:b=0:a='${a}',scale=${2 * W}:${2 * H}[${tag}csm]`);
273
- const cx = L.spriteW * 0.25 - W;
274
- const cy = L.spriteH * 0.3 - H;
275
- layer(`[${tag}csm]`, "s", cx, cy, plan.visible);
276
- cmds.push(...pathCommands(plan.path, name("s"), cx, cy));
277
- }
278
- if (style.clicks !== false && plan.clicks.length > 0) {
279
- const third = RIPPLE_SEC / 3;
280
- L.ripples.forEach((d, k) => {
281
- const c = d / 2;
282
- const th = Math.max(1.5, d * 0.05);
283
- const dist = `abs(hypot(X-${num(c - 0.5)},Y-${num(c - 0.5)})-${num(c - th - 1)})`;
284
- const alpha = [0.9, 0.65, 0.4][k];
285
- const white = `255*lt(${dist},${num(th * 0.45)})`;
286
- steps.push(`color=c=black:s=${d}x${d}:r=1:d=1,format=rgba,geq=r='${white}':g='${white}':b='${white}':` +
287
- `a='255*${alpha}*clip(${num(th)}-${dist},0,1)'[${tag}cr${k}]`);
288
- const windows = plan.clicks.map((p) => [p.t + k * third, p.t + (k + 1) * third]);
289
- layer(`[${tag}cr${k}]`, `r${k}`, -c, -c, []);
290
- for (const [i, p] of plan.clicks.entries()) {
291
- const [a, b] = windows[i];
292
- const next = windows[i + 1];
293
- cmds.push({ t: a, text: `${name(`r${k}`)} x ${num(p.x - c)}, ${name(`r${k}`)} y ${num(p.y - c)}, ${name(`r${k}`)} enable 1` });
294
- if (!next || next[0] >= b)
295
- cmds.push({ t: b, text: `${name(`r${k}`)} enable 0` });
296
- }
297
- });
298
- }
299
- steps.push(`[${firstInput}:v]scale=${L.spriteW}:${L.spriteH}:flags=lanczos,format=rgba[${tag}csp]`);
300
- layer(`[${tag}csp]`, "p", -L.hotX, -L.hotY, plan.visible);
301
- cmds.push(...pathCommands(plan.path, name("p"), -L.hotX, -L.hotY));
302
- return { steps, out: cur, extraInputs: ["-i", sprite], commands: formatCommands(cmds) };
303
- }
304
- export function buildCursorArgs(input, output, plan, style, frame, sprite, commandsFile, quality = "standard") {
305
- const { steps, out, extraInputs, commands } = cursorSteps(plan, style, frame, "[0:v]", 1, "", sprite, commandsFile);
306
- return {
307
- args: [
308
- "-y", "-i", input, ...extraInputs,
309
- "-filter_complex", steps.join(";"),
310
- "-map", out, "-map", "0:a?",
311
- ...resolveQuality(quality),
312
- "-c:a", "copy",
313
- output,
314
- ],
315
- commands,
316
- };
317
- }