@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.
- package/README.md +41 -7
- package/assets/ui/player.html +9 -0
- package/assets/ui/player.js +20 -0
- package/dist/index.js +12 -0
- package/dist/prompts.js +18 -1
- package/dist/server.js +12 -0
- package/dist/tools/addMarker.js +89 -0
- package/dist/tools/backdrop.js +89 -0
- package/dist/tools/bugReport.js +266 -0
- package/dist/tools/chapters.js +156 -0
- package/dist/tools/contactSheet.js +19 -17
- package/dist/tools/findText.js +14 -64
- package/dist/tools/keystrokeOverlay.js +131 -0
- package/dist/tools/pipeline.js +56 -4
- package/dist/tools/reviewRecording.js +12 -0
- package/dist/tools/saveReplay.js +90 -0
- package/dist/tools/startRecording.js +51 -10
- package/dist/tools/stopRecording.js +25 -1
- package/dist/utils/backdrop.js +151 -0
- package/dist/utils/bugReport.js +246 -0
- package/dist/utils/chapters.js +222 -0
- package/dist/utils/keystrokes.js +170 -0
- package/dist/utils/lifecycle.js +11 -2
- package/dist/utils/media.js +5 -2
- package/dist/utils/ocrScan.js +77 -0
- package/dist/utils/pipeline.js +39 -2
- package/dist/utils/replay.js +278 -0
- package/dist/utils/toolsets.js +23 -3
- package/package.json +1 -1
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir, release, version as osVersion } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
|
|
7
|
+
import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
|
|
8
|
+
import { requireFfmpeg, probeMedia } from "../utils/ffmpeg.js";
|
|
9
|
+
import { runEditJob } from "../utils/jobs.js";
|
|
10
|
+
import { planPipeline } from "../utils/pipeline.js";
|
|
11
|
+
import { exportAnimation } from "../utils/animExport.js";
|
|
12
|
+
import { DEFAULT_MAX_BYTES } from "../utils/anim.js";
|
|
13
|
+
import { evenTimes, DEFAULT_SHEET_COUNT, DEFAULT_TILE_WIDTH } from "../utils/sheet.js";
|
|
14
|
+
import { scanVideoFrames, scanMatches } from "../utils/ocrScan.js";
|
|
15
|
+
import { eventPaths, parseEventsJsonl, whenFinalized } from "../utils/events.js";
|
|
16
|
+
import { ocrStatus, parseFfmpegVersion, versionText } from "../utils/capabilities.js";
|
|
17
|
+
import { getMonitors } from "../utils/monitors.js";
|
|
18
|
+
import { resolveOutputDir, subdir, stamp, rand } from "../utils/paths.js";
|
|
19
|
+
import { encodeInlineImages, DEFAULT_MAX_IMAGE_WIDTH } from "../utils/images.js";
|
|
20
|
+
import { getStore } from "../context.js";
|
|
21
|
+
import { redactRegionSchema } from "./redactRegion.js";
|
|
22
|
+
import { renderContactSheet } from "./contactSheet.js";
|
|
23
|
+
import { DEFAULT_SCAN_FRAMES, MAX_SCAN_FRAMES } from "./findText.js";
|
|
24
|
+
import { DEFAULT_CLIP_SEC, DEFAULT_ERROR_PATTERN, DEFAULT_SCAN_EVERY_SEC, DEFAULT_SECRET_PATTERN, MAX_CLIP_SEC, MAX_STEPS, REPORT_FILES, buildReportMarkdown, clipWindow, errorFindings, maskSecrets, mergeRedactions, reconstructSteps, } from "../utils/bugReport.js";
|
|
25
|
+
const { version: serverVersion } = createRequire(import.meta.url)("../../package.json");
|
|
26
|
+
const inputSchema = {
|
|
27
|
+
input: z.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),
|
|
28
|
+
sessionId: z.string().min(1).optional().describe("Or a stopped session's id."),
|
|
29
|
+
title: z.string().max(200).optional().describe("Issue title."),
|
|
30
|
+
actual: z.string().max(4000).optional().describe("What happened."),
|
|
31
|
+
expected: z.string().max(4000).optional().describe("What should happen."),
|
|
32
|
+
start: z.number().nonnegative().optional().describe("Clip start s (default: end - clipSec)."),
|
|
33
|
+
end: z.number().positive().optional().describe("Clip end s (default: recording end)."),
|
|
34
|
+
clipSec: z.number().positive().max(MAX_CLIP_SEC).optional().describe(`Clip length without start (default ${DEFAULT_CLIP_SEC}).`),
|
|
35
|
+
redact: z.boolean().optional().describe("Box out OCR-found secrets in every output (default true; needs Windows OCR)."),
|
|
36
|
+
secretPattern: z.string().optional().describe("Secret regex (default: API keys, tokens, password: values)."),
|
|
37
|
+
regions: z.array(redactRegionSchema).optional().describe("Extra boxes (video px; start/end on the clip clock)."),
|
|
38
|
+
errorPattern: z.string().optional().describe("Error-line regex."),
|
|
39
|
+
scanEverySec: z.number().positive().optional().describe(`OCR every N s (default ${DEFAULT_SCAN_EVERY_SEC}).`),
|
|
40
|
+
maxFrames: z.number().int().min(1).max(MAX_SCAN_FRAMES).optional().describe(`Scan frame cap (default ${DEFAULT_SCAN_FRAMES}).`),
|
|
41
|
+
gif: z.boolean().optional().describe("Also export a GIF (default true)."),
|
|
42
|
+
maxBytes: z.number().int().min(10_000).optional().describe(`GIF size budget (default ${DEFAULT_MAX_BYTES}).`),
|
|
43
|
+
outputDir: z.string().optional().describe("Package folder (default: a new one in SCREENCAST_HOME/edits)."),
|
|
44
|
+
overwrite: z.boolean().optional().describe("Replace a report already in outputDir."),
|
|
45
|
+
};
|
|
46
|
+
const r3 = (n) => Math.round(n * 1000) / 1000;
|
|
47
|
+
async function resolveSource(args) {
|
|
48
|
+
if (args.sessionId !== undefined) {
|
|
49
|
+
const record = getStore().get(args.sessionId);
|
|
50
|
+
if (!record)
|
|
51
|
+
throw new ScreencastError(`No session with id "${args.sessionId}".`);
|
|
52
|
+
if (record.status === "recording") {
|
|
53
|
+
throw new ScreencastError("The recording is still running; stop_recording it first.");
|
|
54
|
+
}
|
|
55
|
+
await whenFinalized(record.id);
|
|
56
|
+
if (!existsSync(record.outputPath))
|
|
57
|
+
throw new ScreencastError(`The session's recording is missing: ${record.outputPath}`);
|
|
58
|
+
const events = record.events?.path;
|
|
59
|
+
return { path: record.outputPath, eventsPath: events && existsSync(events) ? events : null, record };
|
|
60
|
+
}
|
|
61
|
+
const path = args.input;
|
|
62
|
+
if (!existsSync(path))
|
|
63
|
+
throw new ScreencastError(`Input file not found: ${path}`);
|
|
64
|
+
const { jsonl } = eventPaths(path);
|
|
65
|
+
return { path, eventsPath: existsSync(jsonl) ? jsonl : null };
|
|
66
|
+
}
|
|
67
|
+
async function displayRows() {
|
|
68
|
+
if (process.platform !== "win32")
|
|
69
|
+
return null;
|
|
70
|
+
try {
|
|
71
|
+
const monitors = await getMonitors();
|
|
72
|
+
return monitors
|
|
73
|
+
.map((m) => `${m.width}x${m.height}${m.dpi ? ` @${Math.round((m.dpi / 96) * 100)}%` : ""}${m.primary ? " (primary)" : ""}`)
|
|
74
|
+
.join(", ");
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
export function register(server) {
|
|
81
|
+
server.registerTool("bug_report", {
|
|
82
|
+
title: "Bug Report Package",
|
|
83
|
+
description: "Package a recording as a paste-ready repro folder: secret-scanned, redacted clip and GIF, contact " +
|
|
84
|
+
"sheet, steps from the event log, OCR'd errors, environment, report.md for gh issue create --body-file.",
|
|
85
|
+
inputSchema,
|
|
86
|
+
outputSchema: looseOutput({
|
|
87
|
+
outputDir: z.string(),
|
|
88
|
+
reportPath: z.string(),
|
|
89
|
+
jsonPath: z.string(),
|
|
90
|
+
clipPath: z.string(),
|
|
91
|
+
}),
|
|
92
|
+
annotations: WRITES_FILE,
|
|
93
|
+
}, async (args, extra) => {
|
|
94
|
+
let createdDir = null;
|
|
95
|
+
const written = [];
|
|
96
|
+
try {
|
|
97
|
+
if ((args.input === undefined) === (args.sessionId === undefined)) {
|
|
98
|
+
throw new ScreencastError("Provide exactly one of: input (a recording path) or sessionId.");
|
|
99
|
+
}
|
|
100
|
+
const { ffmpeg } = requireFfmpeg();
|
|
101
|
+
const source = await resolveSource(args);
|
|
102
|
+
const info = await probeMedia(source.path);
|
|
103
|
+
if (!info.width || !info.height)
|
|
104
|
+
throw new ScreencastError(`Could not read the size of ${source.path}.`);
|
|
105
|
+
const duration = info.videoDurationSec ?? info.durationSec;
|
|
106
|
+
if (duration === null)
|
|
107
|
+
throw new ScreencastError(`Could not read the duration of ${source.path}.`);
|
|
108
|
+
const window = clipWindow(duration, args);
|
|
109
|
+
const clipLen = r3(window.end - window.start);
|
|
110
|
+
const redact = args.redact !== false;
|
|
111
|
+
const secretPattern = args.secretPattern ?? DEFAULT_SECRET_PATTERN;
|
|
112
|
+
maskSecrets(["x"], secretPattern);
|
|
113
|
+
if (args.errorPattern !== undefined)
|
|
114
|
+
maskSecrets(["x"], args.errorPattern);
|
|
115
|
+
const format = "gif";
|
|
116
|
+
const dir = resolveOutputDir(args.outputDir, subdir("edits")) ?? join(subdir("edits"), `bug-report-${stamp()}-${rand()}`);
|
|
117
|
+
const paths = {
|
|
118
|
+
markdown: join(dir, REPORT_FILES.markdown),
|
|
119
|
+
json: join(dir, REPORT_FILES.json),
|
|
120
|
+
clip: join(dir, REPORT_FILES.clip),
|
|
121
|
+
gif: join(dir, REPORT_FILES.gif(format)),
|
|
122
|
+
sheet: join(dir, REPORT_FILES.contactSheet),
|
|
123
|
+
};
|
|
124
|
+
const clash = Object.values(paths).filter((p) => existsSync(p));
|
|
125
|
+
if (clash.length > 0 && !args.overwrite) {
|
|
126
|
+
throw new ScreencastError(`The folder already holds a report: ${clash.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);
|
|
127
|
+
}
|
|
128
|
+
if (!existsSync(dir)) {
|
|
129
|
+
mkdirSync(dir, { recursive: true });
|
|
130
|
+
createdDir = dir;
|
|
131
|
+
}
|
|
132
|
+
const warnings = [];
|
|
133
|
+
const work = mkdtempSync(join(tmpdir(), "screencast-bug-"));
|
|
134
|
+
try {
|
|
135
|
+
let ocr = "unavailable";
|
|
136
|
+
let scan = null;
|
|
137
|
+
const status = await ocrStatus();
|
|
138
|
+
if (status.available) {
|
|
139
|
+
scan = await scanVideoFrames(source.path, {
|
|
140
|
+
everySec: args.scanEverySec ?? DEFAULT_SCAN_EVERY_SEC,
|
|
141
|
+
maxFrames: args.maxFrames ?? DEFAULT_SCAN_FRAMES,
|
|
142
|
+
range: { start: window.start, duration: clipLen },
|
|
143
|
+
}, work, extra.signal);
|
|
144
|
+
ocr = "read";
|
|
145
|
+
}
|
|
146
|
+
else if (redact) {
|
|
147
|
+
throw new ScreencastError(`The secret scan needs Windows OCR, which is unavailable here${status.error ? ` (${status.error})` : ""}.`, "Pass redact: false to package without it (then check the clip yourself before sharing), or run doctor.");
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
warnings.push("Windows OCR is unavailable, so no error text was read.");
|
|
151
|
+
}
|
|
152
|
+
const found = scan && redact ? mergeRedactions(scanMatches(scan, secretPattern, true, "line").redactRegions) : [];
|
|
153
|
+
const regions = [...found, ...(args.regions ?? [])];
|
|
154
|
+
const errors = scan ? errorFindings(scan.frames, args.errorPattern ?? DEFAULT_ERROR_PATTERN, redact ? secretPattern : null) : [];
|
|
155
|
+
extra.signal.throwIfAborted();
|
|
156
|
+
const steps = [
|
|
157
|
+
{ op: "trim", start: window.start, end: window.end },
|
|
158
|
+
...(regions.length > 0 ? [{ op: "redact", regions, style: "box" }] : []),
|
|
159
|
+
];
|
|
160
|
+
const plan = planPipeline(source.path, paths.clip, steps, {
|
|
161
|
+
width: info.width,
|
|
162
|
+
height: info.height,
|
|
163
|
+
fps: info.fps ?? 30,
|
|
164
|
+
durationSec: info.durationSec,
|
|
165
|
+
hasAudio: info.audioCodec !== null,
|
|
166
|
+
});
|
|
167
|
+
await runEditJob(plan.args, { output: paths.clip, durationSec: plan.durationSec, inputDurationSec: clipLen, extra });
|
|
168
|
+
written.push(paths.clip);
|
|
169
|
+
let anim = null;
|
|
170
|
+
if (args.gif !== false) {
|
|
171
|
+
anim = await exportAnimation(paths.clip, paths.gif, { format, maxBytes: args.maxBytes ?? DEFAULT_MAX_BYTES }, extra);
|
|
172
|
+
written.push(paths.gif);
|
|
173
|
+
if (anim.note)
|
|
174
|
+
warnings.push(anim.note);
|
|
175
|
+
}
|
|
176
|
+
await renderContactSheet(paths.clip, evenTimes(clipLen, DEFAULT_SHEET_COUNT), paths.sheet, { tileWidth: DEFAULT_TILE_WIDTH }, extra.signal);
|
|
177
|
+
written.push(paths.sheet);
|
|
178
|
+
const allSteps = source.eventsPath ? reconstructSteps(parseEventsJsonl(readFileSync(source.eventsPath, "utf8"))) : [];
|
|
179
|
+
const stepsNote = source.eventsPath
|
|
180
|
+
? allSteps.length === 0
|
|
181
|
+
? "The event log has no clicks, shortcuts, typing, or scrolls."
|
|
182
|
+
: undefined
|
|
183
|
+
: "The recording has no input event log (record with start_recording events: true).";
|
|
184
|
+
const ff = parseFfmpegVersion(versionText(ffmpeg) ?? "");
|
|
185
|
+
const displays = await displayRows();
|
|
186
|
+
const record = source.record;
|
|
187
|
+
const mask = (s) => (redact ? (maskSecrets([s], secretPattern)[0] ?? s) : s);
|
|
188
|
+
const environment = [
|
|
189
|
+
["OS", `${osVersion()} (${release()}), ${process.arch}`],
|
|
190
|
+
...(displays ? [["Displays", displays]] : []),
|
|
191
|
+
...(record ? [["Recorded target", mask(record.target)]] : []),
|
|
192
|
+
...(record?.matchedWindow ? [["Window", mask(record.matchedWindow)]] : []),
|
|
193
|
+
...(record?.backend ? [["Capture backend", record.backend]] : []),
|
|
194
|
+
[
|
|
195
|
+
"Recording",
|
|
196
|
+
`${info.width}x${info.height}${info.fps ? ` @ ${Math.round(info.fps * 100) / 100} fps` : ""}, ` +
|
|
197
|
+
`${r3(duration)} s${info.videoCodec ? `, ${info.videoCodec}` : ""}`,
|
|
198
|
+
],
|
|
199
|
+
["ffmpeg", ff.version ?? "unknown"],
|
|
200
|
+
["screencast-mcp", `${serverVersion} (Node ${process.version})`],
|
|
201
|
+
];
|
|
202
|
+
const data = {
|
|
203
|
+
title: args.title?.trim() || "Bug report",
|
|
204
|
+
...(args.expected ? { expected: args.expected } : {}),
|
|
205
|
+
...(args.actual ? { actual: args.actual } : {}),
|
|
206
|
+
createdAt: new Date().toISOString(),
|
|
207
|
+
clip: { start: window.start, end: window.end, recordingDurationSec: r3(duration), width: info.width, height: info.height },
|
|
208
|
+
files: {
|
|
209
|
+
clip: REPORT_FILES.clip,
|
|
210
|
+
...(anim ? { gif: REPORT_FILES.gif(format) } : {}),
|
|
211
|
+
contactSheet: REPORT_FILES.contactSheet,
|
|
212
|
+
},
|
|
213
|
+
...(anim ? { gif: { format, sizeBytes: anim.sizeBytes, withinBudget: anim.withinBudget } } : {}),
|
|
214
|
+
steps: allSteps.slice(0, MAX_STEPS),
|
|
215
|
+
...(allSteps.length > MAX_STEPS ? { stepsOmitted: allSteps.length - MAX_STEPS } : {}),
|
|
216
|
+
...(stepsNote ? { stepsNote } : {}),
|
|
217
|
+
errors,
|
|
218
|
+
ocr,
|
|
219
|
+
redaction: {
|
|
220
|
+
scanned: scan !== null && redact,
|
|
221
|
+
...(scan && redact ? { everySec: r3(scan.step), framesScanned: scan.frames.length } : {}),
|
|
222
|
+
found: found.length,
|
|
223
|
+
manual: args.regions?.length ?? 0,
|
|
224
|
+
},
|
|
225
|
+
environment,
|
|
226
|
+
};
|
|
227
|
+
writeFileSync(paths.markdown, buildReportMarkdown(data));
|
|
228
|
+
written.push(paths.markdown);
|
|
229
|
+
writeFileSync(paths.json, JSON.stringify({ ...data, steps: allSteps, redaction: { ...data.redaction, regions } }, null, 2) + "\n");
|
|
230
|
+
written.push(paths.json);
|
|
231
|
+
if (scan?.clamped) {
|
|
232
|
+
warnings.push(`The scan interval was widened to ${r3(scan.step)} s to fit maxFrames.`);
|
|
233
|
+
}
|
|
234
|
+
const { images } = await encodeInlineImages([paths.sheet], DEFAULT_MAX_IMAGE_WIDTH, 1);
|
|
235
|
+
return okResponse({
|
|
236
|
+
outputDir: dir,
|
|
237
|
+
reportPath: paths.markdown,
|
|
238
|
+
jsonPath: paths.json,
|
|
239
|
+
clipPath: paths.clip,
|
|
240
|
+
...(anim ? { gifPath: paths.gif, gifSizeBytes: anim.sizeBytes, gifWithinBudget: anim.withinBudget } : {}),
|
|
241
|
+
contactSheetPath: paths.sheet,
|
|
242
|
+
clip: { start: window.start, end: window.end },
|
|
243
|
+
steps: allSteps.length,
|
|
244
|
+
errors: errors.map((e) => e.text),
|
|
245
|
+
ocr,
|
|
246
|
+
redaction: data.redaction,
|
|
247
|
+
...(warnings.length > 0 ? { warnings } : {}),
|
|
248
|
+
next: `Review the clip and report.md, then: gh issue create --title ${JSON.stringify(data.title)} ` +
|
|
249
|
+
`--body-file ${JSON.stringify(paths.markdown)} and drag the GIF into the issue.`,
|
|
250
|
+
note: "Redaction is OCR-based and best-effort: look at the clip before posting it anywhere public.",
|
|
251
|
+
}, images);
|
|
252
|
+
}
|
|
253
|
+
finally {
|
|
254
|
+
rmSync(work, { recursive: true, force: true });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
if (createdDir)
|
|
259
|
+
rmSync(createdDir, { recursive: true, force: true });
|
|
260
|
+
else
|
|
261
|
+
for (const p of written)
|
|
262
|
+
rmSync(p, { force: true });
|
|
263
|
+
return errorResponse(error);
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { extname, join } from "node:path";
|
|
3
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
|
|
6
|
+
import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
|
|
7
|
+
import { requireFfmpeg, probeMedia, runCapture } from "../utils/ffmpeg.js";
|
|
8
|
+
import { jobTimeoutMs, runEditJob } from "../utils/jobs.js";
|
|
9
|
+
import { buildSceneScanArgs, parseSceneScan, editOutputExt, DEFAULT_SCENE_THRESHOLD } from "../utils/media.js";
|
|
10
|
+
import { parseSrt } from "../utils/captions.js";
|
|
11
|
+
import { buildChapters, buildChaptersMuxArgs, ffmetadata, markerPoints, markersOrChapters, scenePoints, transcriptPoints, youtubeChapters, YOUTUBE_MIN_CHAPTER_SEC, } from "../utils/chapters.js";
|
|
12
|
+
import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
|
|
13
|
+
import { getStore } from "../context.js";
|
|
14
|
+
const CONTAINERS = new Set([".mp4", ".mkv", ".mov"]);
|
|
15
|
+
const MAX_SCENE_CHAPTERS = 12;
|
|
16
|
+
const inputSchema = {
|
|
17
|
+
input: z.string().min(1).optional().describe("Path to the video."),
|
|
18
|
+
sessionId: z.string().min(1).optional().describe("Or a stopped recording's id."),
|
|
19
|
+
from: z
|
|
20
|
+
.enum(["markers", "scenes", "transcript"])
|
|
21
|
+
.optional()
|
|
22
|
+
.describe("markers (default; add_marker, else the file's chapters), scenes (screen changes), or transcript (SRT sections)."),
|
|
23
|
+
chapters: z
|
|
24
|
+
.array(z.object({ start: z.number().min(0), title: z.string().min(1).max(100) }))
|
|
25
|
+
.min(1)
|
|
26
|
+
.max(200)
|
|
27
|
+
.optional()
|
|
28
|
+
.describe("Or explicit { start, title } chapters."),
|
|
29
|
+
transcript: z.string().optional().describe("The .srt for from: transcript."),
|
|
30
|
+
minChapterSec: z
|
|
31
|
+
.number()
|
|
32
|
+
.min(0)
|
|
33
|
+
.optional()
|
|
34
|
+
.describe(`Shortest chapter (default 1; scenes ${YOUTUBE_MIN_CHAPTER_SEC}, transcript 30).`),
|
|
35
|
+
subtitles: z.string().optional().describe("Also mux this .srt/.vtt/.ass as a soft subtitle track."),
|
|
36
|
+
subtitleLanguage: z.string().regex(/^[a-z]{3}$/).optional().describe('ISO 639-2, e.g. "eng".'),
|
|
37
|
+
textOnly: z.boolean().optional().describe("Return chapters and YouTube text only; write no file."),
|
|
38
|
+
output: z.string().optional().describe("Optional .mp4/.mkv/.mov path. Defaults under SCREENCAST_HOME/edits."),
|
|
39
|
+
overwrite: z.boolean().optional().describe("Allow replacing an existing output file."),
|
|
40
|
+
};
|
|
41
|
+
export function register(server) {
|
|
42
|
+
server.registerTool("chapters", {
|
|
43
|
+
title: "Chapters",
|
|
44
|
+
description: "Write chapters (markers, scene changes, transcript, or a list) into an mp4/mkv/mov copy without " +
|
|
45
|
+
"re-encoding; returns YouTube chapter text. Can mux an SRT as soft subtitles.",
|
|
46
|
+
inputSchema,
|
|
47
|
+
outputSchema: looseOutput({
|
|
48
|
+
chapters: z.array(looseOutput({ start: z.number(), end: z.number(), title: z.string() })),
|
|
49
|
+
youtube: z.string(),
|
|
50
|
+
}),
|
|
51
|
+
annotations: WRITES_FILE,
|
|
52
|
+
}, async (args, extra) => {
|
|
53
|
+
try {
|
|
54
|
+
requireFfmpeg();
|
|
55
|
+
let input = args.input;
|
|
56
|
+
let sessionMarkers;
|
|
57
|
+
if (args.sessionId) {
|
|
58
|
+
const record = getStore().get(args.sessionId);
|
|
59
|
+
if (!record)
|
|
60
|
+
throw new ScreencastError(`No session with id "${args.sessionId}".`);
|
|
61
|
+
if (record.status === "recording")
|
|
62
|
+
throw new ScreencastError("The recording is still running; stop it first.");
|
|
63
|
+
input ??= record.outputPath;
|
|
64
|
+
sessionMarkers = record.markers;
|
|
65
|
+
}
|
|
66
|
+
if (!input)
|
|
67
|
+
throw new ScreencastError("Pass input or sessionId.");
|
|
68
|
+
if (!existsSync(input))
|
|
69
|
+
throw new ScreencastError(`Input file not found: ${input}`);
|
|
70
|
+
for (const f of [args.transcript, args.subtitles]) {
|
|
71
|
+
if (f !== undefined && !existsSync(f))
|
|
72
|
+
throw new ScreencastError(`File not found: ${f}`);
|
|
73
|
+
}
|
|
74
|
+
if (args.subtitles && !/\.(srt|vtt|ass|ssa)$/i.test(args.subtitles)) {
|
|
75
|
+
throw new ScreencastError("subtitles must be an .srt, .vtt, or .ass file.");
|
|
76
|
+
}
|
|
77
|
+
const info = await probeMedia(input);
|
|
78
|
+
const durationSec = info.durationSec;
|
|
79
|
+
if (!durationSec || durationSec <= 0)
|
|
80
|
+
throw new ScreencastError(`Could not read the duration of ${input}.`);
|
|
81
|
+
const from = args.chapters ? "list" : (args.from ?? "markers");
|
|
82
|
+
let points;
|
|
83
|
+
let minDefault = 1;
|
|
84
|
+
let source = from;
|
|
85
|
+
if (args.chapters) {
|
|
86
|
+
points = args.chapters;
|
|
87
|
+
}
|
|
88
|
+
else if (from === "scenes") {
|
|
89
|
+
minDefault = YOUTUBE_MIN_CHAPTER_SEC;
|
|
90
|
+
const { ffmpeg } = requireFfmpeg();
|
|
91
|
+
const scan = await runCapture(ffmpeg, buildSceneScanArgs(input, DEFAULT_SCENE_THRESHOLD), jobTimeoutMs(durationSec), { signal: extra.signal });
|
|
92
|
+
if (scan.code !== 0) {
|
|
93
|
+
throw new ScreencastError(`Scene scan failed (exit ${scan.code}): ${scan.stderr.trim().slice(-400)}`);
|
|
94
|
+
}
|
|
95
|
+
points = scenePoints(parseSceneScan(scan.stdout), args.minChapterSec ?? minDefault, MAX_SCENE_CHAPTERS);
|
|
96
|
+
}
|
|
97
|
+
else if (from === "transcript") {
|
|
98
|
+
if (!args.transcript)
|
|
99
|
+
throw new ScreencastError("from: transcript needs transcript (an .srt path).");
|
|
100
|
+
minDefault = 30;
|
|
101
|
+
points = transcriptPoints(parseSrt(readFileSync(args.transcript, "utf8")), { minChapterSec: args.minChapterSec ?? minDefault });
|
|
102
|
+
if (points.length === 0)
|
|
103
|
+
throw new ScreencastError(`No cues in ${args.transcript}.`);
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
let markers = sessionMarkers ?? [];
|
|
107
|
+
if (markers.length === 0) {
|
|
108
|
+
const found = await markersOrChapters(input, extra.signal);
|
|
109
|
+
markers = found.markers;
|
|
110
|
+
if (found.from === "chapters")
|
|
111
|
+
source = "embedded chapters";
|
|
112
|
+
}
|
|
113
|
+
if (markers.length === 0) {
|
|
114
|
+
throw new ScreencastError(`No markers for ${input}.`, "Add some with add_marker, or use from: scenes / transcript, or pass chapters.");
|
|
115
|
+
}
|
|
116
|
+
points = markerPoints(markers);
|
|
117
|
+
}
|
|
118
|
+
const chapters = buildChapters(points, durationSec, { minChapterSec: args.minChapterSec ?? minDefault });
|
|
119
|
+
if (chapters.length === 0)
|
|
120
|
+
throw new ScreencastError("No chapter falls inside the video.");
|
|
121
|
+
const yt = youtubeChapters(chapters, durationSec);
|
|
122
|
+
const result = {
|
|
123
|
+
source,
|
|
124
|
+
chapters,
|
|
125
|
+
youtube: yt.text,
|
|
126
|
+
...(yt.issues.length > 0 ? { youtubeIssues: yt.issues } : {}),
|
|
127
|
+
};
|
|
128
|
+
if (args.textOnly)
|
|
129
|
+
return okResponse(result);
|
|
130
|
+
const ext = (args.output ? extname(args.output).toLowerCase() : editOutputExt(input));
|
|
131
|
+
if (!CONTAINERS.has(ext)) {
|
|
132
|
+
throw new ScreencastError(`Chapters can be written to .mp4, .mkv, or .mov, not ${ext || "a file without an extension"}.`);
|
|
133
|
+
}
|
|
134
|
+
const output = resolveOutput(args.output, subdir("edits"), `chapters-${stamp()}-${rand()}${ext}`, args.overwrite);
|
|
135
|
+
const work = mkdtempSync(join(tmpdir(), "screencast-chapters-"));
|
|
136
|
+
try {
|
|
137
|
+
const meta = join(work, "chapters.txt");
|
|
138
|
+
writeFileSync(meta, ffmetadata(chapters));
|
|
139
|
+
await runEditJob(buildChaptersMuxArgs(input, meta, output, { container: ext, subtitles: args.subtitles, language: args.subtitleLanguage }), { output, durationSec, extra });
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
rmSync(work, { recursive: true, force: true });
|
|
143
|
+
}
|
|
144
|
+
return okResponse({
|
|
145
|
+
outputPath: output,
|
|
146
|
+
...result,
|
|
147
|
+
...(args.subtitles
|
|
148
|
+
? { subtitleTrack: { file: args.subtitles, codec: ext === ".mkv" ? "copy" : "mov_text", ...(args.subtitleLanguage ? { language: args.subtitleLanguage } : {}) } }
|
|
149
|
+
: {}),
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
return errorResponse(error);
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
}
|
|
@@ -55,6 +55,24 @@ const inputSchema = {
|
|
|
55
55
|
.optional()
|
|
56
56
|
.describe(`Max inline image width (default ${DEFAULT_MAX_IMAGE_WIDTH}).`),
|
|
57
57
|
};
|
|
58
|
+
export async function renderContactSheet(input, times, output, opts, signal) {
|
|
59
|
+
const grid = sheetGrid(times.length, opts.columns);
|
|
60
|
+
const work = mkdtempSync(join(tmpdir(), "screencast-sheet-"));
|
|
61
|
+
try {
|
|
62
|
+
const font = bundledFontPath("bold");
|
|
63
|
+
for (const [i, t] of times.entries()) {
|
|
64
|
+
const labelFile = join(work, `label_${i}.txt`);
|
|
65
|
+
writeFileSync(labelFile, formatTimecode(t));
|
|
66
|
+
const tile = join(work, `tile_${String(i).padStart(3, "0")}.png`);
|
|
67
|
+
await runFfmpeg(buildTileArgs(input, t, tile, opts.tileWidth, font, labelFile), 60_000, { signal });
|
|
68
|
+
}
|
|
69
|
+
await runFfmpeg(buildSheetArgs(sequencePattern(work, "tile_%03d.png"), grid, output), 60_000, { signal });
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
rmSync(work, { recursive: true, force: true });
|
|
73
|
+
}
|
|
74
|
+
return grid;
|
|
75
|
+
}
|
|
58
76
|
export function register(server) {
|
|
59
77
|
server.registerTool("contact_sheet", {
|
|
60
78
|
title: "Contact Sheet",
|
|
@@ -95,23 +113,7 @@ export function register(server) {
|
|
|
95
113
|
else {
|
|
96
114
|
times = evenTimes(durationSec, count);
|
|
97
115
|
}
|
|
98
|
-
const grid =
|
|
99
|
-
const work = mkdtempSync(join(tmpdir(), "screencast-sheet-"));
|
|
100
|
-
try {
|
|
101
|
-
const font = bundledFontPath("bold");
|
|
102
|
-
for (const [i, t] of times.entries()) {
|
|
103
|
-
const labelFile = join(work, `label_${i}.txt`);
|
|
104
|
-
writeFileSync(labelFile, formatTimecode(t));
|
|
105
|
-
const tile = join(work, `tile_${String(i).padStart(3, "0")}.png`);
|
|
106
|
-
await runFfmpeg(buildTileArgs(args.input, t, tile, tileWidth, font, labelFile), 60_000, {
|
|
107
|
-
signal: extra.signal,
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
await runFfmpeg(buildSheetArgs(sequencePattern(work, "tile_%03d.png"), grid, output), 60_000, { signal: extra.signal });
|
|
111
|
-
}
|
|
112
|
-
finally {
|
|
113
|
-
rmSync(work, { recursive: true, force: true });
|
|
114
|
-
}
|
|
116
|
+
const grid = await renderContactSheet(args.input, times, output, { tileWidth, columns: args.columns }, extra.signal);
|
|
115
117
|
result = {
|
|
116
118
|
outputPath: output,
|
|
117
119
|
mode: args.mode ?? "even",
|
package/dist/tools/findText.js
CHANGED
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { extname, join } from "node:path";
|
|
3
|
-
import { existsSync, mkdtempSync,
|
|
3
|
+
import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
5
|
import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
|
|
6
6
|
import { READ_ONLY, looseOutput } from "../utils/toolSpec.js";
|
|
7
|
-
import { requireFfmpeg, runFfmpeg
|
|
8
|
-
import { jobTimeoutMs } from "../utils/jobs.js";
|
|
7
|
+
import { requireFfmpeg, runFfmpeg } from "../utils/ffmpeg.js";
|
|
9
8
|
import { resolveCaptureTarget } from "../utils/resolveTarget.js";
|
|
10
9
|
import { captureStill } from "../utils/still.js";
|
|
11
10
|
import { buildHighlightArgs, targetSize } from "../utils/diff.js";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
11
|
+
import { findMatches, redactionRects } from "../utils/ocr.js";
|
|
12
|
+
import { readFrames, scanVideoFrames, scanMatches } from "../utils/ocrScan.js";
|
|
14
13
|
import { windowMatchReport } from "../utils/windows.js";
|
|
15
14
|
import { confirmCapture, describeTarget } from "../utils/consent.js";
|
|
16
15
|
import { subdir, stamp, rand, stillOutput } from "../utils/paths.js";
|
|
@@ -62,34 +61,6 @@ const inputSchema = {
|
|
|
62
61
|
.optional()
|
|
63
62
|
.describe("Return the image with matches outlined (default: true with a query)."),
|
|
64
63
|
};
|
|
65
|
-
async function readFrames(sources, work, signal) {
|
|
66
|
-
const sized = await Promise.all(sources.map(async (source) => {
|
|
67
|
-
const { width, height } = await probeMedia(source);
|
|
68
|
-
if (!width || !height)
|
|
69
|
-
throw new ScreencastError("Could not read the image size.");
|
|
70
|
-
return { source, width, height };
|
|
71
|
-
}));
|
|
72
|
-
const passes = [];
|
|
73
|
-
const passScaleList = [];
|
|
74
|
-
const owner = [];
|
|
75
|
-
for (const [f, { source, width, height }] of sized.entries()) {
|
|
76
|
-
for (const [i, scale] of passScales(width, height).entries()) {
|
|
77
|
-
const out = join(work, `pass${f}-${i}.png`);
|
|
78
|
-
await runFfmpeg(["-y", "-v", "error", "-i", source, "-vf", `scale=iw*${scale}:ih*${scale}:flags=lanczos`, out], 60_000, {
|
|
79
|
-
signal,
|
|
80
|
-
});
|
|
81
|
-
passes.push(out);
|
|
82
|
-
passScaleList.push(scale);
|
|
83
|
-
owner.push(f);
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
const results = await recognize(passes, passScaleList);
|
|
87
|
-
return sized.map(({ width, height }, f) => ({
|
|
88
|
-
lines: mergePasses(results.filter((_r, i) => owner[i] === f)),
|
|
89
|
-
width,
|
|
90
|
-
height,
|
|
91
|
-
}));
|
|
92
|
-
}
|
|
93
64
|
export function register(server) {
|
|
94
65
|
server.registerTool("find_text", {
|
|
95
66
|
title: "Find Text (OCR)",
|
|
@@ -180,43 +151,22 @@ async function scanClip(args, work, signal) {
|
|
|
180
151
|
if (IMAGE_EXTENSIONS.has(extname(args.input).toLowerCase())) {
|
|
181
152
|
throw new ScreencastError("scanEverySec is for a video input; an image has one frame, so drop scanEverySec.");
|
|
182
153
|
}
|
|
183
|
-
const info = await probeMedia(args.input);
|
|
184
154
|
const maxFrames = args.maxFrames ?? DEFAULT_SCAN_FRAMES;
|
|
185
|
-
const
|
|
186
|
-
|
|
187
|
-
const
|
|
188
|
-
if (frames.length === 0)
|
|
189
|
-
throw new ScreencastError("Could not read any frames from the video.");
|
|
190
|
-
const step = 1 / plan.fps;
|
|
191
|
-
const timeAt = (i) => Math.round(i * step * 1000) / 1000;
|
|
192
|
-
const end = info.videoDurationSec ?? info.durationSec ?? timeAt(frames.length - 1) + step;
|
|
193
|
-
const read = await readFrames(frames, work, signal);
|
|
194
|
-
const [size] = read;
|
|
155
|
+
const scan = await scanVideoFrames(args.input, { everySec: args.scanEverySec, maxFrames }, work, signal);
|
|
156
|
+
const { step } = scan;
|
|
157
|
+
const [size] = scan.frames;
|
|
195
158
|
if (!size)
|
|
196
159
|
throw new ScreencastError("Could not read any frames from the video.");
|
|
197
|
-
const matches = [];
|
|
198
|
-
const redactRegions = [];
|
|
199
160
|
const seenLines = new Set();
|
|
200
|
-
|
|
161
|
+
for (const frame of scan.frames)
|
|
201
162
|
for (const l of frame.lines)
|
|
202
163
|
seenLines.add(l.text);
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
const t = timeAt(i);
|
|
207
|
-
const start = Math.max(0, Math.round((t - step) * 1000) / 1000);
|
|
208
|
-
const stop = Math.min(end, Math.round((t + step) * 1000) / 1000);
|
|
209
|
-
const rects = redactionRects(hits, frame);
|
|
210
|
-
for (const [k, hit] of hits.entries()) {
|
|
211
|
-
matches.push({ t, ...hit });
|
|
212
|
-
const rect = rects[k];
|
|
213
|
-
if (rect)
|
|
214
|
-
redactRegions.push({ ...rect, start, end: stop });
|
|
215
|
-
}
|
|
216
|
-
});
|
|
164
|
+
const { matches, redactRegions } = args.query
|
|
165
|
+
? scanMatches(scan, args.query, args.regex === true)
|
|
166
|
+
: { matches: [], redactRegions: [] };
|
|
217
167
|
const images = [];
|
|
218
168
|
const first = matches[0];
|
|
219
|
-
const firstFrame = first && frames.find((
|
|
169
|
+
const firstFrame = first && scan.frames.find((f) => f.t === first.t)?.path;
|
|
220
170
|
if ((args.returnImage ?? Boolean(args.query)) && first && firstFrame) {
|
|
221
171
|
const shown = join(work, "shown.png");
|
|
222
172
|
await runFfmpeg(buildHighlightArgs(firstFrame, matches.filter((m) => m.t === first.t), shown), 30_000, { signal });
|
|
@@ -228,8 +178,8 @@ async function scanClip(args, work, signal) {
|
|
|
228
178
|
imageSize: { width: size.width, height: size.height },
|
|
229
179
|
scan: {
|
|
230
180
|
everySec: Math.round(step * 1000) / 1000,
|
|
231
|
-
framesScanned: frames.length,
|
|
232
|
-
...(
|
|
181
|
+
framesScanned: scan.frames.length,
|
|
182
|
+
...(scan.clamped ? { note: `Widened from ${args.scanEverySec} s to fit maxFrames ${maxFrames}.` } : {}),
|
|
233
183
|
},
|
|
234
184
|
...(args.query
|
|
235
185
|
? {
|