@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.
- package/README.md +58 -11
- package/assets/ui/player.html +9 -0
- package/assets/ui/player.js +20 -0
- package/dist/index.js +12 -0
- package/dist/prompts.js +34 -4
- package/dist/server.js +20 -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/cutByTranscript.js +86 -0
- package/dist/tools/findText.js +14 -64
- package/dist/tools/indexRecording.js +173 -0
- package/dist/tools/keystrokeOverlay.js +131 -0
- package/dist/tools/pipeline.js +251 -18
- package/dist/tools/reviewRecording.js +12 -0
- package/dist/tools/saveReplay.js +90 -0
- package/dist/tools/searchRecording.js +73 -0
- package/dist/tools/startRecording.js +51 -10
- package/dist/tools/stepGuide.js +193 -0
- package/dist/tools/stopRecording.js +25 -1
- package/dist/tools/transcribe.js +4 -3
- package/dist/tools/zoom.js +1 -1
- package/dist/utils/audio.js +12 -4
- package/dist/utils/backdrop.js +151 -0
- package/dist/utils/bugReport.js +172 -0
- package/dist/utils/captions.js +19 -6
- package/dist/utils/chapters.js +227 -0
- package/dist/utils/idle.js +10 -3
- package/dist/utils/keystrokes.js +155 -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 +169 -15
- package/dist/utils/recipes.js +67 -0
- package/dist/utils/recordingIndex.js +266 -0
- package/dist/utils/replay.js +278 -0
- package/dist/utils/stepGuide.js +205 -0
- package/dist/utils/steps.js +88 -0
- package/dist/utils/timeline.js +85 -0
- package/dist/utils/toolsets.js +32 -6
- package/dist/utils/transcriptCut.js +134 -0
- package/package.json +1 -1
package/dist/tools/pipeline.js
CHANGED
|
@@ -1,19 +1,41 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
5
|
import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
|
|
6
6
|
import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
|
|
7
|
-
import { requireFfmpeg, probeMedia } from "../utils/ffmpeg.js";
|
|
8
|
-
import { runEditJob } from "../utils/jobs.js";
|
|
9
|
-
import { planPipeline, MAX_PIPELINE_STEPS } from "../utils/pipeline.js";
|
|
7
|
+
import { requireFfmpeg, probeMedia, hasFilter, runCapture, runFfmpeg, scriptLongFilters } from "../utils/ffmpeg.js";
|
|
8
|
+
import { jobTimeoutMs, runEditJob } from "../utils/jobs.js";
|
|
9
|
+
import { planPipeline, probeArgs, MAX_PIPELINE_STEPS } from "../utils/pipeline.js";
|
|
10
10
|
import { calloutFonts, prepareCalloutAssets } from "../utils/calloutAssets.js";
|
|
11
11
|
import { exportAnimation } from "../utils/animExport.js";
|
|
12
12
|
import { calloutItemSchema, fontFileSchema } from "./callout.js";
|
|
13
|
-
import { zoomKeyframeSchema } from "./zoom.js";
|
|
13
|
+
import { readClicks, zoomKeyframeSchema } from "./zoom.js";
|
|
14
14
|
import { redactRegionSchema } from "./redactRegion.js";
|
|
15
15
|
import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
|
|
16
16
|
import { PLATFORMS } from "../utils/produce.js";
|
|
17
|
+
import { buildChapters, ffmetadata, markerPoints, markersOrChapters, retimeMarkers, writeMarkers } from "../utils/chapters.js";
|
|
18
|
+
import { backdropOptionsSchema } from "./backdrop.js";
|
|
19
|
+
import { keystrokeOptionsSchema, loadBadges, prepareKeystrokeAssets } from "./keystrokeOverlay.js";
|
|
20
|
+
import { MAX_ZOOM } from "../utils/zoom.js";
|
|
21
|
+
import { buildIdleScanArgs, intersect, parseFreezes, parseSilences, DEFAULT_MIN_IDLE_SEC } from "../utils/idle.js";
|
|
22
|
+
import { buildLoudnessMeasureArgs, buildNoiseFloorArgs, loudnessTarget, parseLoudnorm, parseNoiseFloor } from "../utils/audio.js";
|
|
23
|
+
import { buildTranscribeArgs, formatSrt, normalizeCues, parseSrt, resolveWhisperModel } from "../utils/captions.js";
|
|
24
|
+
import { eventPaths } from "../utils/events.js";
|
|
25
|
+
import { bundledFontPath } from "../utils/fonts.js";
|
|
26
|
+
import { retimeAss, retimeCues } from "../utils/timeline.js";
|
|
27
|
+
import { applyOverrides, recipeSteps, RECIPES } from "../utils/recipes.js";
|
|
28
|
+
function transcribeBlocker() {
|
|
29
|
+
if (!hasFilter("whisper"))
|
|
30
|
+
return "this ffmpeg has no whisper filter (FFmpeg 8 with whisper.cpp).";
|
|
31
|
+
try {
|
|
32
|
+
resolveWhisperModel(undefined);
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return "no whisper model (set SCREENCAST_WHISPER_MODEL).";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
17
39
|
const aspect = z.enum(["16:9", "9:16", "1:1", "4:5"]);
|
|
18
40
|
const fit = z.enum(["pad", "crop"]).optional();
|
|
19
41
|
const step = z.discriminatedUnion("op", [
|
|
@@ -41,7 +63,28 @@ const step = z.discriminatedUnion("op", [
|
|
|
41
63
|
}),
|
|
42
64
|
z.object({ op: z.literal("callout"), items: z.array(calloutItemSchema).min(1).max(50), fontFile: fontFileSchema }),
|
|
43
65
|
z.object({ op: z.literal("reframe"), aspect, fit }),
|
|
44
|
-
z.object({
|
|
66
|
+
z.object({
|
|
67
|
+
op: z.literal("zoom"),
|
|
68
|
+
keyframes: z.array(zoomKeyframeSchema).min(1).max(100).optional(),
|
|
69
|
+
follow: z.literal("clicks").optional(),
|
|
70
|
+
maxZoom: z.number().min(1).max(MAX_ZOOM).optional(),
|
|
71
|
+
holdSec: z.number().positive().max(30).optional(),
|
|
72
|
+
transitionSec: z.number().positive().max(5).optional(),
|
|
73
|
+
}),
|
|
74
|
+
z.object({ op: z.literal("cut_idle"), minIdleSec: z.number().positive().optional(), keepSec: z.number().min(0).optional() }),
|
|
75
|
+
z.object({
|
|
76
|
+
op: z.literal("audio"),
|
|
77
|
+
normalize: z.union([z.enum(["youtube", "podcast", "broadcast"]), z.number().min(-70).max(-5)]).optional(),
|
|
78
|
+
denoise: z.enum(["light", "medium", "strong"]).optional(),
|
|
79
|
+
}),
|
|
80
|
+
z.object({
|
|
81
|
+
op: z.literal("burn_subtitles"),
|
|
82
|
+
subtitles: z.string().optional(),
|
|
83
|
+
transcribe: z.boolean().optional(),
|
|
84
|
+
style: z.enum(["clean", "social"]).optional(),
|
|
85
|
+
}),
|
|
86
|
+
z.object({ op: z.literal("backdrop"), ...backdropOptionsSchema }),
|
|
87
|
+
z.object({ op: z.literal("keystroke_overlay"), ...keystrokeOptionsSchema }),
|
|
45
88
|
z.object({ op: z.literal("export_preset"), platform: z.enum(PLATFORMS), fit }),
|
|
46
89
|
z.object({
|
|
47
90
|
op: z.literal("export_gif"),
|
|
@@ -55,31 +98,57 @@ const inputSchema = {
|
|
|
55
98
|
input: z.string().min(1).describe("Path to the source video."),
|
|
56
99
|
steps: z
|
|
57
100
|
.array(step)
|
|
58
|
-
.min(1)
|
|
59
101
|
.max(MAX_PIPELINE_STEPS)
|
|
102
|
+
.optional()
|
|
60
103
|
.describe("Edits in order, each { op, ...its tool's options }; export_preset/export_gif only last. Times " +
|
|
61
|
-
"and pixels are relative to the video as it is at that step (after earlier trims, speed, crops)."
|
|
104
|
+
"and pixels are relative to the video as it is at that step (after earlier trims, speed, crops). " +
|
|
105
|
+
"zoom follow:\"clicks\" plans from the event log; burn_subtitles takes subtitles or transcribe:true."),
|
|
106
|
+
recipe: z
|
|
107
|
+
.enum(RECIPES)
|
|
108
|
+
.optional()
|
|
109
|
+
.describe("Polish preset expanded to steps (see dryRun): pr_demo = cut_idle, click zoom, GIF <=10 MB; tutorial = " +
|
|
110
|
+
"+ audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step."),
|
|
62
111
|
quality: z.enum(["draft", "standard", "high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),
|
|
63
112
|
dryRun: z.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),
|
|
64
113
|
output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
|
|
65
114
|
overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
|
|
115
|
+
chapters: z
|
|
116
|
+
.boolean()
|
|
117
|
+
.optional()
|
|
118
|
+
.describe("Keep the input's markers as chapters, re-timed through trims and speed."),
|
|
66
119
|
};
|
|
67
120
|
export function register(server) {
|
|
68
121
|
server.registerTool("pipeline", {
|
|
69
122
|
title: "Edit Pipeline",
|
|
70
|
-
description: "Run several edits (trim, crop, scale, speed, redact, callout, reframe, zoom,
|
|
71
|
-
"export_preset or export_gif) in one ffmpeg pass: one re-encode, no
|
|
72
|
-
"over chaining edit tools.",
|
|
123
|
+
description: "Run several edits (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, reframe, zoom, backdrop, " +
|
|
124
|
+
"audio, burn_subtitles, then optionally export_preset or export_gif) in one ffmpeg pass: one re-encode, no " +
|
|
125
|
+
"intermediate files. Prefer it over chaining edit tools; a recipe does the usual polish in one call.",
|
|
73
126
|
inputSchema,
|
|
74
127
|
outputSchema: looseOutput({ processes: z.number().int(), steps: z.array(z.string()) }),
|
|
75
128
|
annotations: WRITES_FILE,
|
|
76
129
|
}, async (args, extra) => {
|
|
77
130
|
try {
|
|
78
|
-
requireFfmpeg();
|
|
131
|
+
const { ffmpeg } = requireFfmpeg();
|
|
79
132
|
if (!existsSync(args.input))
|
|
80
133
|
throw new ScreencastError(`Input file not found: ${args.input}`);
|
|
81
|
-
const steps = args.steps;
|
|
82
134
|
const info = await probeMedia(args.input);
|
|
135
|
+
const hasAudio = info.audioCodec !== null;
|
|
136
|
+
const warnings = [];
|
|
137
|
+
let steps = (args.steps ?? []);
|
|
138
|
+
if (args.recipe) {
|
|
139
|
+
const logged = readClicks(eventPaths(args.input).jsonl);
|
|
140
|
+
const r = recipeSteps(args.recipe, {
|
|
141
|
+
hasAudio,
|
|
142
|
+
hasClicks: !!logged && logged.length > 0,
|
|
143
|
+
transcribeBlocker: hasAudio ? transcribeBlocker() : null,
|
|
144
|
+
});
|
|
145
|
+
steps = applyOverrides(r.steps, steps);
|
|
146
|
+
warnings.push(...r.notes);
|
|
147
|
+
}
|
|
148
|
+
if (steps.length === 0)
|
|
149
|
+
throw new ScreencastError("Give steps, a recipe, or both.");
|
|
150
|
+
if (steps.length > MAX_PIPELINE_STEPS)
|
|
151
|
+
throw new ScreencastError(`At most ${MAX_PIPELINE_STEPS} steps.`);
|
|
83
152
|
if (!info.width || !info.height)
|
|
84
153
|
throw new ScreencastError(`Could not read the size of ${args.input}.`);
|
|
85
154
|
const src = {
|
|
@@ -87,8 +156,50 @@ export function register(server) {
|
|
|
87
156
|
height: info.height,
|
|
88
157
|
fps: info.fps ?? 30,
|
|
89
158
|
durationSec: info.durationSec,
|
|
90
|
-
hasAudio
|
|
159
|
+
hasAudio,
|
|
91
160
|
};
|
|
161
|
+
const timeout = jobTimeoutMs(info.durationSec);
|
|
162
|
+
for (const [i, s] of steps.entries()) {
|
|
163
|
+
if (s.op !== "burn_subtitles")
|
|
164
|
+
continue;
|
|
165
|
+
if (!hasFilter("subtitles")) {
|
|
166
|
+
throw new ScreencastError("This ffmpeg has no subtitles filter (it needs libass).", "Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");
|
|
167
|
+
}
|
|
168
|
+
if (s.subtitles && !existsSync(s.subtitles))
|
|
169
|
+
throw new ScreencastError(`step ${i + 1}: subtitles file not found: ${s.subtitles}`);
|
|
170
|
+
if (s.transcribe) {
|
|
171
|
+
if (!hasFilter("whisper"))
|
|
172
|
+
throw new ScreencastError(`step ${i + 1}: transcribe needs FFmpeg 8 built with whisper.cpp (no whisper filter here).`);
|
|
173
|
+
resolveWhisperModel(undefined);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const clicks = {};
|
|
177
|
+
for (const [i, s] of steps.entries()) {
|
|
178
|
+
if (s.op !== "zoom" || s.follow !== "clicks")
|
|
179
|
+
continue;
|
|
180
|
+
const path = eventPaths(args.input).jsonl;
|
|
181
|
+
const logged = readClicks(path);
|
|
182
|
+
if (!logged)
|
|
183
|
+
throw new ScreencastError(`step ${i + 1}: no event log at ${path}; record with start_recording events: true.`);
|
|
184
|
+
clicks[i] = logged;
|
|
185
|
+
}
|
|
186
|
+
let idle;
|
|
187
|
+
const idleAt = steps.findIndex((s) => s.op === "cut_idle");
|
|
188
|
+
const idleStep = steps[idleAt];
|
|
189
|
+
if (idleStep?.op === "cut_idle") {
|
|
190
|
+
const total = info.durationSec;
|
|
191
|
+
if (total === null)
|
|
192
|
+
throw new ScreencastError(`Could not read the duration of ${args.input}.`);
|
|
193
|
+
const speedUp = steps.slice(0, idleAt).reduce((f, x) => (x.op === "speed" ? f * x.factor : f), 1);
|
|
194
|
+
const useAudio = hasAudio;
|
|
195
|
+
const scan = await runCapture(ffmpeg, buildIdleScanArgs(args.input, (idleStep.minIdleSec ?? DEFAULT_MIN_IDLE_SEC) * speedUp, useAudio), timeout, {
|
|
196
|
+
signal: extra.signal,
|
|
197
|
+
});
|
|
198
|
+
if (scan.code !== 0)
|
|
199
|
+
throw new ScreencastError(`Idle scan failed (exit ${scan.code}): ${scan.stderr.trim().slice(-400)}`);
|
|
200
|
+
const freezes = parseFreezes(scan.stderr, total);
|
|
201
|
+
idle = useAudio ? intersect(freezes, parseSilences(scan.stderr, total)) : freezes;
|
|
202
|
+
}
|
|
92
203
|
const last = steps.at(-1);
|
|
93
204
|
if (!last)
|
|
94
205
|
throw new ScreencastError("Provide at least one step.");
|
|
@@ -98,7 +209,6 @@ export function register(server) {
|
|
|
98
209
|
try {
|
|
99
210
|
const assets = {};
|
|
100
211
|
const fallbackFonts = [];
|
|
101
|
-
const warnings = [];
|
|
102
212
|
for (const [i, s] of steps.entries()) {
|
|
103
213
|
if (s.op !== "callout")
|
|
104
214
|
continue;
|
|
@@ -109,16 +219,121 @@ export function register(server) {
|
|
|
109
219
|
fallbackFonts.push(...a.fallbackFonts.map((f) => ({ step: i, ...f })));
|
|
110
220
|
warnings.push(...a.warnings.map((w) => `Step ${i}, ${w.charAt(0).toLowerCase()}${w.slice(1)}`));
|
|
111
221
|
}
|
|
222
|
+
const keystrokes = {};
|
|
223
|
+
for (const [i, s] of steps.entries()) {
|
|
224
|
+
if (s.op === "backdrop" && s.image && !existsSync(s.image)) {
|
|
225
|
+
throw new ScreencastError(`step ${i + 1}: background image not found: ${s.image}`);
|
|
226
|
+
}
|
|
227
|
+
if (s.op !== "keystroke_overlay")
|
|
228
|
+
continue;
|
|
229
|
+
const { badges } = loadBadges(args.input, s.events, s);
|
|
230
|
+
const labels = [...new Set(badges.map((b) => b.label))];
|
|
231
|
+
const k = prepareKeystrokeAssets(labels, args.dryRun ? null : work, `s${i}_`, s.fontFile);
|
|
232
|
+
keystrokes[i] = { badges, fontFile: k.fontFile, textFiles: k.textFiles };
|
|
233
|
+
warnings.push(...k.warnings.map((w) => `Step ${i}, ${w.charAt(0).toLowerCase()}${w.slice(1)}`));
|
|
234
|
+
}
|
|
112
235
|
const target = last.op === "export_gif" ? (args.dryRun ? "<temporary stage1.mp4>" : join(work, "stage1.mp4")) : output;
|
|
113
|
-
const
|
|
236
|
+
const audioM = {};
|
|
237
|
+
const subtitles = {};
|
|
238
|
+
const fontsDir = dirname(bundledFontPath("regular"));
|
|
239
|
+
const planWith = (chaptersFile) => planPipeline(args.input, target, steps, src, assets, args.quality ?? "standard", {
|
|
240
|
+
keystrokes, idle, clicks, audio: audioM, subtitles, fontsDir, chaptersFile,
|
|
241
|
+
});
|
|
242
|
+
let plan = planWith();
|
|
243
|
+
let transcript;
|
|
244
|
+
for (let n = 0; !args.dryRun && plan.pending.length > 0; n++) {
|
|
245
|
+
const p = plan.pending[0];
|
|
246
|
+
if (n > steps.length * 3)
|
|
247
|
+
throw new ScreencastError(`Internal: step ${p.step + 1} ${p.kind} did not resolve.`);
|
|
248
|
+
const s = steps[p.step];
|
|
249
|
+
const capture = async (base) => {
|
|
250
|
+
const sc = scriptLongFilters(probeArgs(base, p));
|
|
251
|
+
try {
|
|
252
|
+
const r = await runCapture(ffmpeg, sc.args, timeout, { signal: extra.signal });
|
|
253
|
+
if (r.code !== 0)
|
|
254
|
+
throw new ScreencastError(`step ${p.step + 1} ${p.kind} scan failed (exit ${r.code}): ${r.stderr.trim().slice(-400)}`);
|
|
255
|
+
return r;
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
sc.cleanup();
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
if (p.kind === "noisefloor") {
|
|
262
|
+
audioM[p.step] = { ...audioM[p.step], floorDb: parseNoiseFloor((await capture(buildNoiseFloorArgs(args.input))).stdout) };
|
|
263
|
+
}
|
|
264
|
+
else if (p.kind === "loudness" && s.op === "audio") {
|
|
265
|
+
const r = await capture(buildLoudnessMeasureArgs(args.input, loudnessTarget(s.normalize)));
|
|
266
|
+
try {
|
|
267
|
+
audioM[p.step] = { ...audioM[p.step], loudness: parseLoudnorm(r.stderr) };
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
warnings.push(`Step ${p.step + 1}: the audio is silent; not normalized.`);
|
|
271
|
+
audioM[p.step] = { ...audioM[p.step], silent: true };
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
else if (p.kind === "transcribe" && s.op === "burn_subtitles") {
|
|
275
|
+
const raw = join(work, `s${p.step}_raw.srt`);
|
|
276
|
+
await runFfmpeg(probeArgs(buildTranscribeArgs(args.input, resolveWhisperModel(undefined), raw), p), timeout, {
|
|
277
|
+
signal: extra.signal,
|
|
278
|
+
});
|
|
279
|
+
const cues = existsSync(raw) ? normalizeCues(parseSrt(readFileSync(raw, "utf8"))) : [];
|
|
280
|
+
subtitles[p.step] = cues.length > 0 ? join(work, `s${p.step}.srt`) : "";
|
|
281
|
+
if (cues.length > 0) {
|
|
282
|
+
transcript = formatSrt(cues);
|
|
283
|
+
writeFileSync(subtitles[p.step], transcript);
|
|
284
|
+
}
|
|
285
|
+
else
|
|
286
|
+
warnings.push(`Step ${p.step + 1}: no speech was recognised; no captions.`);
|
|
287
|
+
}
|
|
288
|
+
else if (p.kind === "subtitles" && s.op === "burn_subtitles" && s.subtitles) {
|
|
289
|
+
if (p.ops.length === 0)
|
|
290
|
+
subtitles[p.step] = s.subtitles;
|
|
291
|
+
else {
|
|
292
|
+
const text = readFileSync(s.subtitles, "utf8");
|
|
293
|
+
const ass = /\.(ass|ssa)$/i.test(s.subtitles);
|
|
294
|
+
const moved = ass ? retimeAss(text, p.ops) : formatSrt(retimeCues(normalizeCues(parseSrt(text)), p.ops));
|
|
295
|
+
const file = join(work, `s${p.step}${ass ? ".ass" : ".srt"}`);
|
|
296
|
+
writeFileSync(file, moved);
|
|
297
|
+
subtitles[p.step] = ass || moved.trim() ? file : "";
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
else {
|
|
301
|
+
throw new ScreencastError(`Internal: step ${p.step + 1} cannot resolve ${p.kind}.`);
|
|
302
|
+
}
|
|
303
|
+
plan = planWith();
|
|
304
|
+
}
|
|
305
|
+
let chapterList = [];
|
|
306
|
+
let retimed = [];
|
|
307
|
+
if (args.chapters) {
|
|
308
|
+
const found = plan.gif ? null : await markersOrChapters(args.input, extra.signal);
|
|
309
|
+
if (!found)
|
|
310
|
+
warnings.push("chapters: a GIF/WebP cannot hold chapters; none written.");
|
|
311
|
+
else if (found.markers.length === 0)
|
|
312
|
+
warnings.push("chapters: the input has no markers (add_marker) or chapters; none written.");
|
|
313
|
+
else {
|
|
314
|
+
retimed = retimeMarkers(found.markers, plan.timeOps);
|
|
315
|
+
chapterList = plan.durationSec ? buildChapters(markerPoints(retimed), plan.durationSec) : [];
|
|
316
|
+
if (chapterList.length === 0)
|
|
317
|
+
warnings.push("chapters: no marker falls inside the result; none written.");
|
|
318
|
+
else {
|
|
319
|
+
const file = args.dryRun ? "<chapters.txt>" : join(work, "chapters.txt");
|
|
320
|
+
if (!args.dryRun)
|
|
321
|
+
writeFileSync(file, ffmetadata(chapterList));
|
|
322
|
+
plan = planWith(file);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
114
326
|
const result = {
|
|
327
|
+
...(args.recipe && { recipe: args.recipe, expandedSteps: steps }),
|
|
115
328
|
steps: plan.summary,
|
|
329
|
+
...(args.dryRun && plan.pending.length > 0 && { measuredOnRun: plan.pending.map((p) => `step ${p.step + 1}: ${p.kind}`) }),
|
|
116
330
|
processes: plan.gif ? 2 : 1,
|
|
117
331
|
width: plan.width,
|
|
118
332
|
height: plan.height,
|
|
119
333
|
durationSec: plan.durationSec,
|
|
120
334
|
...(fallbackFonts.length > 0 && { fallbackFonts }),
|
|
121
335
|
...(warnings.length > 0 && { warnings }),
|
|
336
|
+
...(chapterList.length > 0 && { chapters: chapterList }),
|
|
122
337
|
};
|
|
123
338
|
if (args.dryRun)
|
|
124
339
|
return okResponse({ dryRun: true, ...result, ffmpegArgs: plan.args });
|
|
@@ -127,7 +342,25 @@ export function register(server) {
|
|
|
127
342
|
const anim = await exportAnimation(target, output, plan.gif, extra);
|
|
128
343
|
return okResponse({ outputPath: output, ...result, animation: anim });
|
|
129
344
|
}
|
|
130
|
-
|
|
345
|
+
let subtitlesPath;
|
|
346
|
+
if (transcript) {
|
|
347
|
+
try {
|
|
348
|
+
subtitlesPath = output.replace(/\.[^./\\]+$/, "") + ".srt";
|
|
349
|
+
writeFileSync(subtitlesPath, transcript);
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
subtitlesPath = undefined;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
let markersPath;
|
|
356
|
+
if (chapterList.length > 0) {
|
|
357
|
+
try {
|
|
358
|
+
markersPath = writeMarkers(output, retimed.filter((m) => m.t < (plan.durationSec ?? Infinity)));
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return okResponse({ outputPath: output, ...result, ...(markersPath && { markersPath }), ...(subtitlesPath && { subtitlesPath }) });
|
|
131
364
|
}
|
|
132
365
|
finally {
|
|
133
366
|
rmSync(work, { recursive: true, force: true });
|
|
@@ -8,6 +8,7 @@ import { jobTimeoutMs } from "../utils/jobs.js";
|
|
|
8
8
|
import { tempPath } from "../utils/paths.js";
|
|
9
9
|
import { buildPlayerFramesArgs, clientSupportsApps, parsePlayerFrameLog, pickPlayerFrames, playerFramePlan, splitJpegs, DEFAULT_PLAYER_FRAMES, DEFAULT_PLAYER_WIDTH, MAX_PLAYER_FRAMES, MCP_APP_MIME, PLAYER_TOOL_META, PLAYER_URI, } from "../utils/player.js";
|
|
10
10
|
import { getStore } from "../context.js";
|
|
11
|
+
import { markersOrChapters, readMarkers } from "../utils/chapters.js";
|
|
11
12
|
const uiAsset = (name) => readFileSync(fileURLToPath(new URL(`../../assets/ui/${name}`, import.meta.url)), "utf8");
|
|
12
13
|
export function playerHtml() {
|
|
13
14
|
const js = uiAsset("player.js");
|
|
@@ -28,6 +29,9 @@ function resolveInput(args) {
|
|
|
28
29
|
return args.input;
|
|
29
30
|
throw new ScreencastError("Pass input or sessionId.");
|
|
30
31
|
}
|
|
32
|
+
function markersField(markers) {
|
|
33
|
+
return markers && markers.length > 0 ? { markers: markers.map(({ t, label }) => ({ t, label })) } : {};
|
|
34
|
+
}
|
|
31
35
|
export function register(server) {
|
|
32
36
|
server.registerResource("review-player", PLAYER_URI, {
|
|
33
37
|
title: "Recording review player",
|
|
@@ -68,6 +72,7 @@ export function register(server) {
|
|
|
68
72
|
height: info.height,
|
|
69
73
|
fps: info.fps,
|
|
70
74
|
hasAudio: info.audioCodec !== null,
|
|
75
|
+
...markersField(args.sessionId ? getStore().get(args.sessionId)?.markers ?? readMarkers(input) : readMarkers(input)),
|
|
71
76
|
note: "Clients with MCP Apps show an inline review player for this result. Without it, " +
|
|
72
77
|
"look with contact_sheet or sample_frames, then trim and redact with pipeline.",
|
|
73
78
|
});
|
|
@@ -116,6 +121,12 @@ export function register(server) {
|
|
|
116
121
|
return frame && jpeg ? [{ frame, jpeg }] : [];
|
|
117
122
|
});
|
|
118
123
|
const t0 = firstFrame.timeSec;
|
|
124
|
+
let markers = [];
|
|
125
|
+
try {
|
|
126
|
+
markers = (await markersOrChapters(args.input, extra.signal)).markers.map(({ t, label }) => ({ t, label }));
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
}
|
|
119
130
|
const frameTimes = keep.map(({ frame }) => Math.round((frame.timeSec - t0) * 1000) / 1000);
|
|
120
131
|
const sceneFrames = keep.flatMap(({ frame }, k) => (frame.scene ? [k] : []));
|
|
121
132
|
return {
|
|
@@ -131,6 +142,7 @@ export function register(server) {
|
|
|
131
142
|
frameTimes,
|
|
132
143
|
intervalSec: plan.intervalSec,
|
|
133
144
|
sceneFrames,
|
|
145
|
+
markers,
|
|
134
146
|
}),
|
|
135
147
|
},
|
|
136
148
|
...keep.map(({ jpeg }) => ({ type: "image", data: jpeg.toString("base64"), mimeType: "image/jpeg" })),
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
|
|
3
|
+
import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
|
|
4
|
+
import { requireFfmpeg } from "../utils/ffmpeg.js";
|
|
5
|
+
import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
|
|
6
|
+
import { eventPaths, prepareEventPaths } from "../utils/events.js";
|
|
7
|
+
import { logMessage } from "../utils/logging.js";
|
|
8
|
+
import { MAX_REPLAY_SEC, replayDiskBytes, saveReplay } from "../utils/replay.js";
|
|
9
|
+
import { getStore } from "../context.js";
|
|
10
|
+
const inputSchema = {
|
|
11
|
+
sessionId: z.string().min(1).describe("Session id of a replay buffer."),
|
|
12
|
+
lastSec: z
|
|
13
|
+
.number()
|
|
14
|
+
.positive()
|
|
15
|
+
.max(MAX_REPLAY_SEC)
|
|
16
|
+
.optional()
|
|
17
|
+
.describe("Seconds back from now (default and max: the buffer length)."),
|
|
18
|
+
output: z.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),
|
|
19
|
+
overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
|
|
20
|
+
reencode: z
|
|
21
|
+
.boolean()
|
|
22
|
+
.optional()
|
|
23
|
+
.describe("Frame-exact re-encode. Default: instant stream copy that may hide up to 2 s of earlier frames."),
|
|
24
|
+
};
|
|
25
|
+
export function register(server) {
|
|
26
|
+
server.registerTool("save_replay", {
|
|
27
|
+
title: "Save Replay",
|
|
28
|
+
description: "Save the last N seconds of a replay buffer (start_recording replayBufferSec) to an mp4; the buffer keeps running.",
|
|
29
|
+
inputSchema,
|
|
30
|
+
outputSchema: looseOutput({
|
|
31
|
+
sessionId: z.string(),
|
|
32
|
+
outputPath: z.string(),
|
|
33
|
+
durationSec: z.number(),
|
|
34
|
+
}),
|
|
35
|
+
annotations: WRITES_FILE,
|
|
36
|
+
}, async (args, extra) => {
|
|
37
|
+
try {
|
|
38
|
+
const record = getStore().get(args.sessionId);
|
|
39
|
+
if (!record)
|
|
40
|
+
throw new ScreencastError(`No session with id "${args.sessionId}".`);
|
|
41
|
+
if (!record.replay) {
|
|
42
|
+
throw new ScreencastError(`Session "${args.sessionId}" is not a replay buffer.`, "Start one with start_recording { replayBufferSec: 60 }; for an ordinary recording use stop_recording and trim.");
|
|
43
|
+
}
|
|
44
|
+
const { ffmpeg, ffprobe } = requireFfmpeg();
|
|
45
|
+
const buf = record.replay;
|
|
46
|
+
const lastSec = Math.min(args.lastSec ?? buf.bufferSec, buf.bufferSec);
|
|
47
|
+
const output = resolveOutput(args.output, subdir("recordings"), `replay-${stamp()}-${rand()}.mp4`, args.overwrite);
|
|
48
|
+
if (buf.events)
|
|
49
|
+
prepareEventPaths(eventPaths(output), args.overwrite);
|
|
50
|
+
const started = Date.now();
|
|
51
|
+
const result = await saveReplay(buf, {
|
|
52
|
+
ffmpeg,
|
|
53
|
+
ffprobe,
|
|
54
|
+
lastSec,
|
|
55
|
+
output,
|
|
56
|
+
reencode: args.reencode,
|
|
57
|
+
quality: record.quality,
|
|
58
|
+
live: record.status === "recording",
|
|
59
|
+
signal: extra.signal,
|
|
60
|
+
});
|
|
61
|
+
const elapsedMs = Date.now() - started;
|
|
62
|
+
logMessage("info", `Saved ${result.durationSec}s of replay ${record.id} to ${output}.`, {
|
|
63
|
+
sessionId: record.id,
|
|
64
|
+
outputPath: output,
|
|
65
|
+
durationSec: result.durationSec,
|
|
66
|
+
});
|
|
67
|
+
const short = result.durationSec + 0.25 < lastSec;
|
|
68
|
+
return okResponse({
|
|
69
|
+
sessionId: record.id,
|
|
70
|
+
...result,
|
|
71
|
+
requestedSec: args.lastSec ?? null,
|
|
72
|
+
bufferSec: buf.bufferSec,
|
|
73
|
+
bufferRunning: record.status === "recording",
|
|
74
|
+
bufferDiskBytes: replayDiskBytes(buf),
|
|
75
|
+
elapsedMs,
|
|
76
|
+
note: (args.lastSec !== undefined && args.lastSec > buf.bufferSec
|
|
77
|
+
? `Capped at the buffer length (${buf.bufferSec}s). `
|
|
78
|
+
: "") +
|
|
79
|
+
(short ? "The buffer held less footage than requested (it started recently). " : "") +
|
|
80
|
+
(result.includesLive ? "" : "The clip ends at the last completed segment, up to 2 s before now. ") +
|
|
81
|
+
(record.status === "recording"
|
|
82
|
+
? "The buffer keeps running; stop_recording discards it unless save: true."
|
|
83
|
+
: "This buffer is no longer recording; stop_recording discards it."),
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
return errorResponse(error);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
|
|
6
|
+
import { READ_ONLY, looseOutput } from "../utils/toolSpec.js";
|
|
7
|
+
import { requireFfmpeg, runFfmpeg } from "../utils/ffmpeg.js";
|
|
8
|
+
import { buildSampleAtTimestampArgs } from "../utils/media.js";
|
|
9
|
+
import { subdir } from "../utils/paths.js";
|
|
10
|
+
import { encodeInlineImages, clampInlineCount, MAX_INLINE_IMAGES } from "../utils/images.js";
|
|
11
|
+
import { DEFAULT_SEARCH_LIMIT, MAX_SEARCH_LIMIT, fingerprintFile, findIndex, keyframeTime, readIndex, resolveRecording, sameFingerprint, searchIndex, } from "../utils/recordingIndex.js";
|
|
12
|
+
const THUMB_WIDTH = 480;
|
|
13
|
+
const inputSchema = {
|
|
14
|
+
input: z.string().optional().describe("Recording path."),
|
|
15
|
+
sessionId: z.string().optional().describe("Or a stopped session id."),
|
|
16
|
+
query: z.string().min(1).describe("Text; tolerates OCR misreads."),
|
|
17
|
+
regex: z.boolean().optional().describe("query is a regex."),
|
|
18
|
+
limit: z.number().int().min(1).max(MAX_SEARCH_LIMIT).optional().describe(`Max hits (default ${DEFAULT_SEARCH_LIMIT}).`),
|
|
19
|
+
images: z.number().int().min(0).max(MAX_INLINE_IMAGES).optional().describe("Thumbnails of the top N hits (default 0)."),
|
|
20
|
+
};
|
|
21
|
+
export function register(server) {
|
|
22
|
+
server.registerTool("search_recording", {
|
|
23
|
+
title: "Search Recording",
|
|
24
|
+
description: "Search an index_recording timeline (screen text, events, markers, transcript): timecoded hits, " +
|
|
25
|
+
"best first, secrets masked. No frames unless asked.",
|
|
26
|
+
inputSchema,
|
|
27
|
+
outputSchema: looseOutput({ total: z.number(), hits: z.array(z.unknown()) }),
|
|
28
|
+
annotations: READ_ONLY,
|
|
29
|
+
}, async (args, extra) => {
|
|
30
|
+
try {
|
|
31
|
+
const source = await resolveRecording(args);
|
|
32
|
+
const indexPath = findIndex(source.path, subdir("edits"));
|
|
33
|
+
const index = indexPath ? readIndex(indexPath) : null;
|
|
34
|
+
if (!indexPath || !index) {
|
|
35
|
+
throw new ScreencastError(`No index for ${source.path}.`, "Run index_recording on it first.");
|
|
36
|
+
}
|
|
37
|
+
const stale = !sameFingerprint(index.fingerprint, fingerprintFile(source.path));
|
|
38
|
+
const { hits, total } = searchIndex(index, args.query, { regex: args.regex === true, limit: args.limit });
|
|
39
|
+
const want = Math.min(clampInlineCount(args.images ?? 0), hits.length);
|
|
40
|
+
let images = [];
|
|
41
|
+
if (want > 0) {
|
|
42
|
+
requireFfmpeg();
|
|
43
|
+
const work = mkdtempSync(join(tmpdir(), "screencast-search-"));
|
|
44
|
+
try {
|
|
45
|
+
const shots = [];
|
|
46
|
+
for (const [i, hit] of hits.slice(0, want).entries()) {
|
|
47
|
+
const at = hit.t === hit.start ? keyframeTime(hit) : hit.t;
|
|
48
|
+
const out = join(work, `hit_${i}.png`);
|
|
49
|
+
await runFfmpeg(buildSampleAtTimestampArgs(source.path, at, out), 60_000, { signal: extra.signal });
|
|
50
|
+
if (existsSync(out))
|
|
51
|
+
shots.push(out);
|
|
52
|
+
}
|
|
53
|
+
images = (await encodeInlineImages(shots, THUMB_WIDTH, want)).images;
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
rmSync(work, { recursive: true, force: true });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return okResponse({
|
|
60
|
+
indexPath,
|
|
61
|
+
query: args.query,
|
|
62
|
+
total,
|
|
63
|
+
hits,
|
|
64
|
+
...(total > hits.length ? { more: total - hits.length } : {}),
|
|
65
|
+
...(index.ocr ? {} : { note: "The index has no screen text (OCR was unavailable when it was built)." }),
|
|
66
|
+
...(stale ? { stale: true, warning: "The recording changed since it was indexed; run index_recording again." } : {}),
|
|
67
|
+
}, images);
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
return errorResponse(error);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
}
|