@tmhs/screencast-mcp 0.44.2 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +58 -11
  2. package/assets/ui/player.html +9 -0
  3. package/assets/ui/player.js +20 -0
  4. package/dist/index.js +12 -0
  5. package/dist/prompts.js +34 -4
  6. package/dist/server.js +20 -0
  7. package/dist/tools/addMarker.js +89 -0
  8. package/dist/tools/backdrop.js +89 -0
  9. package/dist/tools/bugReport.js +266 -0
  10. package/dist/tools/chapters.js +156 -0
  11. package/dist/tools/contactSheet.js +19 -17
  12. package/dist/tools/cutByTranscript.js +86 -0
  13. package/dist/tools/findText.js +14 -64
  14. package/dist/tools/indexRecording.js +173 -0
  15. package/dist/tools/keystrokeOverlay.js +131 -0
  16. package/dist/tools/pipeline.js +251 -18
  17. package/dist/tools/reviewRecording.js +12 -0
  18. package/dist/tools/saveReplay.js +90 -0
  19. package/dist/tools/searchRecording.js +73 -0
  20. package/dist/tools/startRecording.js +51 -10
  21. package/dist/tools/stepGuide.js +193 -0
  22. package/dist/tools/stopRecording.js +25 -1
  23. package/dist/tools/transcribe.js +4 -3
  24. package/dist/tools/zoom.js +1 -1
  25. package/dist/utils/audio.js +12 -4
  26. package/dist/utils/backdrop.js +151 -0
  27. package/dist/utils/bugReport.js +172 -0
  28. package/dist/utils/captions.js +19 -6
  29. package/dist/utils/chapters.js +227 -0
  30. package/dist/utils/idle.js +10 -3
  31. package/dist/utils/keystrokes.js +155 -0
  32. package/dist/utils/lifecycle.js +11 -2
  33. package/dist/utils/media.js +5 -2
  34. package/dist/utils/ocrScan.js +77 -0
  35. package/dist/utils/pipeline.js +169 -15
  36. package/dist/utils/recipes.js +67 -0
  37. package/dist/utils/recordingIndex.js +266 -0
  38. package/dist/utils/replay.js +278 -0
  39. package/dist/utils/stepGuide.js +205 -0
  40. package/dist/utils/steps.js +88 -0
  41. package/dist/utils/timeline.js +85 -0
  42. package/dist/utils/toolsets.js +32 -6
  43. package/dist/utils/transcriptCut.js +134 -0
  44. package/package.json +1 -1
@@ -14,7 +14,8 @@ import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
14
14
  import { getStore } from "../context.js";
15
15
  import { classifyUnrequestedExit, killPid, serverIdentity } from "../utils/sessions.js";
16
16
  import { rmSync } from "node:fs";
17
- import { basename } from "node:path";
17
+ import { basename, join } from "node:path";
18
+ import { MAX_REPLAY_SEC, MIN_REPLAY_SEC, discardReplay, planReplayBuffer, prepareReplayDir, segmentOutputArgs, } from "../utils/replay.js";
18
19
  import { DEFAULT_KEY_MODE, eventPaths, parseCaptureStart, prepareEventPaths, startEventLogger, stopEventLogger, summarizeEvents, trackFinalizer, writeEventsFile, } from "../utils/events.js";
19
20
  const inputSchema = {
20
21
  target: z
@@ -77,6 +78,13 @@ const inputSchema = {
77
78
  .optional()
78
79
  .describe("gdigrab (default): the screen rectangle. wgc (window: targets, FFmpeg 8+): the window's own " +
79
80
  "surface, even when covered or moved; client area only, no audio."),
81
+ replayBufferSec: z
82
+ .number()
83
+ .int()
84
+ .min(MIN_REPLAY_SEC)
85
+ .max(MAX_REPLAY_SEC)
86
+ .optional()
87
+ .describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab only."),
80
88
  };
81
89
  export function register(server) {
82
90
  server.registerTool("start_recording", {
@@ -108,6 +116,10 @@ export function register(server) {
108
116
  throw new ScreencastError('backend "wgc" needs FFmpeg 8 or newer (the gfxcapture filter). Use gdigrab, or update ffmpeg.');
109
117
  }
110
118
  }
119
+ if (args.replayBufferSec !== undefined && backend === "wgc") {
120
+ throw new ScreencastError('replayBufferSec is not supported with backend "wgc" yet; use gdigrab.');
121
+ }
122
+ const replay = args.replayBufferSec !== undefined ? planReplayBuffer(args.replayBufferSec) : null;
111
123
  const fps = args.fps ?? DEFAULT_FPS;
112
124
  const quality = args.quality ?? DEFAULT_QUALITY;
113
125
  const maxDurationSec = resolveMaxDuration(args.maxDurationSec);
@@ -115,12 +127,13 @@ export function register(server) {
115
127
  const audio = args.audio?.source === "system"
116
128
  ? { device: await resolveLoopbackDevice(args.audio.device) }
117
129
  : undefined;
118
- await confirmCapture(server, `Record ${describeTarget(args.target, window)} ` +
130
+ await confirmCapture(server, (replay ? `Keep a rolling ${replay.bufferSec} s replay buffer of ` : "Record ") +
131
+ `${describeTarget(args.target, window)} ` +
119
132
  (maxDurationSec > 0 ? `for up to ${maxDurationSec} s` : "with no time limit") +
120
133
  (audio ? `, with system audio (${audio.device})` : ", without audio") +
121
134
  (args.events ? ", logging mouse clicks and typing" : "") +
122
- `, saved to ${output}?`, extra.signal);
123
- const ffArgs = buildCaptureArgs(target, {
135
+ (replay ? ", kept only until save_replay or stop_recording { save: true } writes it out?" : `, saved to ${output}?`), extra.signal);
136
+ const captureArgs = buildCaptureArgs(target, {
124
137
  fps,
125
138
  quality,
126
139
  output,
@@ -128,9 +141,12 @@ export function register(server) {
128
141
  audio,
129
142
  maxDurationSec,
130
143
  });
144
+ const ffArgs = replay ? segmentOutputArgs(captureArgs, replay) : captureArgs;
145
+ if (replay)
146
+ prepareReplayDir(replay);
131
147
  const keyMode = args.keys ?? DEFAULT_KEY_MODE;
132
- const evPaths = args.events ? eventPaths(output) : null;
133
- if (evPaths)
148
+ const evPaths = args.events ? (replay ? { raw: join(replay.dir, "events.raw"), jsonl: "" } : eventPaths(output)) : null;
149
+ if (evPaths && !replay)
134
150
  prepareEventPaths(evPaths, args.overwrite);
135
151
  let frame = args.events
136
152
  ? captureFrame(target, monitors)
@@ -182,6 +198,8 @@ export function register(server) {
182
198
  await stopEventLogger(logger);
183
199
  if (evPaths)
184
200
  rmSync(evPaths.raw, { force: true });
201
+ if (replay)
202
+ discardReplay(replay);
185
203
  const tail = stderrTail.trim().split("\n").slice(-6).join("\n");
186
204
  throw new ScreencastError(`Recording failed to start (${backend === "wgc" ? "window capture" : "ffmpeg"} exited immediately):\n${tail}`);
187
205
  }
@@ -199,9 +217,20 @@ export function register(server) {
199
217
  ...serverIdentity(),
200
218
  status: "recording",
201
219
  startedAt: new Date().toISOString(),
220
+ videoStartMs: parseCaptureStart(stderrHead) ?? spawnedAt,
202
221
  ...(maxDurationSec > 0 ? { maxDurationSec } : {}),
203
222
  ...(window ? { matchedWindow: window.matchedTitle } : {}),
204
- ...(evPaths ? { events: { path: evPaths.jsonl, keys: keyMode } } : {}),
223
+ ...(evPaths && !replay ? { events: { path: evPaths.jsonl, keys: keyMode } } : {}),
224
+ ...(replay
225
+ ? {
226
+ replay: {
227
+ ...replay,
228
+ ...(evPaths && frame
229
+ ? { events: { raw: evPaths.raw, keys: keyMode, startMs: parseCaptureStart(stderrHead) ?? spawnedAt, frame } }
230
+ : {}),
231
+ },
232
+ }
233
+ : {}),
205
234
  backend,
206
235
  processImage: backend === "wgc" ? basename(process.execPath).toLowerCase() : "ffmpeg.exe",
207
236
  };
@@ -218,9 +247,15 @@ export function register(server) {
218
247
  await stopEventLogger(logger);
219
248
  if (evPaths)
220
249
  rmSync(evPaths.raw, { force: true });
250
+ if (replay)
251
+ discardReplay(replay);
221
252
  throw new ScreencastError(`Recording stopped: the session registry could not be written (${err.message}).`);
222
253
  }
223
- if (logger && evPaths && frame) {
254
+ if (logger && replay) {
255
+ const exited = new Promise((resolve) => child.once("exit", () => resolve()));
256
+ trackFinalizer(id, exited.then(() => stopEventLogger(logger)));
257
+ }
258
+ else if (logger && evPaths && frame) {
224
259
  const exited = new Promise((resolve) => child.once("exit", () => resolve()));
225
260
  trackFinalizer(id, exited.then(async () => {
226
261
  await stopEventLogger(logger);
@@ -268,8 +303,14 @@ export function register(server) {
268
303
  audioDevice: audio?.device ?? null,
269
304
  maxDurationSec: maxDurationSec > 0 ? maxDurationSec : null,
270
305
  ...(window ? windowMatchReport(window) : {}),
271
- ...(evPaths ? { eventsPath: evPaths.jsonl, keys: keyMode } : {}),
272
- note: "Call stop_recording with this sessionId to finalize the file." +
306
+ ...(evPaths && !replay ? { eventsPath: evPaths.jsonl, keys: keyMode } : {}),
307
+ ...(replay
308
+ ? { replay: { bufferSec: replay.bufferSec, segmentSec: replay.segmentSec, dir: replay.dir, events: !!evPaths } }
309
+ : {}),
310
+ note: (replay
311
+ ? `Replay buffer running: save_replay keeps the last seconds (up to ${replay.bufferSec}s) without stopping it; ` +
312
+ "stop_recording discards the buffer unless save: true (then it writes outputPath)."
313
+ : "Call stop_recording with this sessionId to finalize the file.") +
273
314
  (maxDurationSec > 0
274
315
  ? ` It stops on its own after ${maxDurationSec}s (maxDurationSec).`
275
316
  : ""),
@@ -0,0 +1,193 @@
1
+ import { z } from "zod";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
6
+ import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
7
+ import { requireFfmpeg, probeMedia, runFfmpeg } from "../utils/ffmpeg.js";
8
+ import { progressReporter } from "../utils/jobs.js";
9
+ import { parseEventsJsonl } from "../utils/events.js";
10
+ import { inputSteps } from "../utils/steps.js";
11
+ import { readMarkers } from "../utils/chapters.js";
12
+ import { ocrStatus } from "../utils/capabilities.js";
13
+ import { readFrames, scanMatches } from "../utils/ocrScan.js";
14
+ import { DEFAULT_SECRET_PATTERN } from "../utils/bugReport.js";
15
+ import { resolveOutputDir, subdir, stamp, rand } from "../utils/paths.js";
16
+ import { GUIDE_FILES, MAX_GUIDE_STEPS, assignSections, buildGuideHtml, buildGuideMarkdown, buildStepFrameArgs, buildStepShotArgs, caption, guideSteps, labelAt, shotFilter, } from "../utils/stepGuide.js";
17
+ import { resolveSource } from "./bugReport.js";
18
+ const OCR_BATCH = 10;
19
+ const inputSchema = {
20
+ input: z.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),
21
+ sessionId: z.string().min(1).optional().describe("Or a stopped session's id."),
22
+ title: z.string().max(200).optional().describe("Guide title."),
23
+ format: z.enum(["md", "html", "both"]).optional().describe("md + images/, self-contained html, or both (default)."),
24
+ ocr: z.boolean().optional().describe("OCR shots for captions and secret boxes (default true; needs Windows OCR)."),
25
+ outputDir: z.string().optional().describe("Guide folder (default: new in SCREENCAST_HOME/edits)."),
26
+ overwrite: z.boolean().optional().describe("Replace a guide already in outputDir."),
27
+ };
28
+ export function register(server) {
29
+ server.registerTool("step_guide", {
30
+ title: "Step-by-Step Guide",
31
+ description: "Turn a recording's event log into a numbered how-to: a ringed screenshot and caption per step, marker " +
32
+ "headings; Markdown and/or one HTML file. Never includes typed text.",
33
+ inputSchema,
34
+ outputSchema: looseOutput({ outputDir: z.string() }),
35
+ annotations: WRITES_FILE,
36
+ }, async (args, extra) => {
37
+ let createdDir = null;
38
+ const written = [];
39
+ try {
40
+ if ((args.input === undefined) === (args.sessionId === undefined)) {
41
+ throw new ScreencastError("Provide exactly one of: input (a recording path) or sessionId.");
42
+ }
43
+ requireFfmpeg();
44
+ const source = await resolveSource(args);
45
+ if (!source.eventsPath) {
46
+ throw new ScreencastError("The recording has no input event log, so there are no steps to write.", "Record with start_recording events: true, or pass a recording that has a .events.jsonl beside it.");
47
+ }
48
+ const info = await probeMedia(source.path);
49
+ if (!info.width || !info.height)
50
+ throw new ScreencastError(`Could not read the size of ${source.path}.`);
51
+ const duration = info.videoDurationSec ?? info.durationSec;
52
+ if (duration === null)
53
+ throw new ScreencastError(`Could not read the duration of ${source.path}.`);
54
+ const fps = info.fps ?? 30;
55
+ const format = args.format ?? "both";
56
+ const wantMd = format !== "html";
57
+ const wantHtml = format !== "md";
58
+ const useOcr = args.ocr !== false;
59
+ if (useOcr) {
60
+ const status = await ocrStatus();
61
+ if (!status.available) {
62
+ throw new ScreencastError(`Captions and the secret scan need Windows OCR, which is unavailable here${status.error ? ` (${status.error})` : ""}.`, "Pass ocr: false for a guide without them (then check the screenshots yourself before sharing), or run doctor.");
63
+ }
64
+ }
65
+ const dir = resolveOutputDir(args.outputDir, subdir("edits")) ?? join(subdir("edits"), `step-guide-${stamp()}-${rand()}`);
66
+ const paths = { markdown: join(dir, GUIDE_FILES.markdown), html: join(dir, GUIDE_FILES.html), images: join(dir, GUIDE_FILES.images) };
67
+ const clash = [paths.markdown, paths.html].filter((p) => existsSync(p));
68
+ if (clash.length > 0 && !args.overwrite) {
69
+ throw new ScreencastError(`The folder already holds a guide: ${clash.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);
70
+ }
71
+ const all = inputSteps(parseEventsJsonl(readFileSync(source.eventsPath, "utf8")));
72
+ const kept = all.slice(0, MAX_GUIDE_STEPS);
73
+ const plain = guideSteps(kept, { durationSec: duration, fps });
74
+ const shots = plain.map((s, i) => ({ i, s })).filter(({ s }) => s.shotT !== undefined);
75
+ const warnings = [];
76
+ if (!existsSync(dir)) {
77
+ mkdirSync(dir, { recursive: true });
78
+ createdDir = dir;
79
+ }
80
+ const work = mkdtempSync(join(tmpdir(), "screencast-guide-"));
81
+ try {
82
+ const progress = progressReporter(extra);
83
+ const total = shots.length * (useOcr ? 3 : 2) || 1;
84
+ let done = 0;
85
+ const tick = () => progress?.(++done / total);
86
+ const frames = [];
87
+ for (const { s } of shots) {
88
+ const out = join(work, `frame-${String(s.n).padStart(3, "0")}.png`);
89
+ await runFfmpeg(buildStepFrameArgs(source.path, s.shotT, out), 60_000, { signal: extra.signal });
90
+ frames.push(out);
91
+ tick();
92
+ }
93
+ const read = frames.map(() => null);
94
+ if (useOcr) {
95
+ for (let b = 0; b < frames.length; b += OCR_BATCH) {
96
+ extra.signal.throwIfAborted();
97
+ const batch = await readFrames(frames.slice(b, b + OCR_BATCH), work, extra.signal);
98
+ batch.forEach((f, k) => {
99
+ read[b + k] = f;
100
+ tick();
101
+ });
102
+ }
103
+ }
104
+ const labels = kept.map(() => null);
105
+ const boxes = shots.map(({ i, s }, k) => {
106
+ const frame = read[k];
107
+ if (!frame)
108
+ return [];
109
+ if (s.x !== undefined && s.y !== undefined)
110
+ labels[i] = labelAt(frame.lines, s.x, s.y);
111
+ return scanMatches({ frames: [{ ...frame, t: 0, path: "" }], step: 1, end: 1 }, DEFAULT_SECRET_PATTERN, true, "line")
112
+ .redactRegions;
113
+ });
114
+ const steps = assignSections(guideSteps(kept, { durationSec: duration, fps, labels }), readMarkers(source.path));
115
+ const imageDir = wantMd ? paths.images : join(work, "images");
116
+ if (wantMd && existsSync(imageDir) && args.overwrite) {
117
+ for (const f of readdirSync(imageDir))
118
+ if (/^step-\d+\.png$/.test(f))
119
+ rmSync(join(imageDir, f), { force: true });
120
+ }
121
+ mkdirSync(imageDir, { recursive: true });
122
+ let redactions = 0;
123
+ for (const [k, { i }] of shots.entries()) {
124
+ const step = steps[i];
125
+ const file = GUIDE_FILES.image(step.n);
126
+ const ring = step.x !== undefined && step.y !== undefined ? { x: step.x, y: step.y } : undefined;
127
+ const filter = shotFilter({ width: info.width, height: info.height }, { click: ring, boxes: boxes[k] });
128
+ const out = join(imageDir, file);
129
+ await runFfmpeg(buildStepShotArgs(frames[k], filter, out), 60_000, { signal: extra.signal });
130
+ if (wantMd)
131
+ written.push(out);
132
+ step.image = file;
133
+ redactions += boxes[k].length;
134
+ tick();
135
+ }
136
+ const stepsNote = all.length === 0 ? "The event log has no clicks, shortcuts, typing, or scrolls." : undefined;
137
+ const data = {
138
+ title: args.title?.trim() || "Step-by-step guide",
139
+ createdAt: new Date().toISOString(),
140
+ recording: { durationSec: Math.round(duration * 1000) / 1000, width: info.width, height: info.height },
141
+ steps,
142
+ ...(all.length > MAX_GUIDE_STEPS ? { stepsOmitted: all.length - MAX_GUIDE_STEPS } : {}),
143
+ ...(stepsNote ? { stepsNote } : {}),
144
+ ocr: useOcr ? "read" : "off",
145
+ redactions,
146
+ };
147
+ if (wantMd) {
148
+ writeFileSync(paths.markdown, buildGuideMarkdown(data));
149
+ written.push(paths.markdown);
150
+ }
151
+ if (wantHtml) {
152
+ const src = (file) => `data:image/png;base64,${readFileSync(join(imageDir, file)).toString("base64")}`;
153
+ writeFileSync(paths.html, buildGuideHtml(data, src));
154
+ written.push(paths.html);
155
+ }
156
+ if (data.stepsOmitted)
157
+ warnings.push(`Only the first ${MAX_GUIDE_STEPS} steps were written; ${data.stepsOmitted} more were left out.`);
158
+ if (stepsNote)
159
+ warnings.push(stepsNote);
160
+ return okResponse({
161
+ outputDir: dir,
162
+ ...(wantMd ? { markdownPath: paths.markdown, imagesDir: paths.images } : {}),
163
+ ...(wantHtml ? { htmlPath: paths.html } : {}),
164
+ steps: steps.map((s) => ({
165
+ ...(s.n > 0 ? { n: s.n } : {}),
166
+ t: s.t,
167
+ action: s.action,
168
+ caption: caption(s),
169
+ ...(s.section ? { section: s.section } : {}),
170
+ ...(s.image ? { image: s.image } : {}),
171
+ })),
172
+ ocr: data.ocr,
173
+ redactions,
174
+ ...(warnings.length > 0 ? { warnings } : {}),
175
+ note: useOcr
176
+ ? "Captions are OCR-based templates: rewrite them in guide.md as needed. The secret scan is best-effort: look at the screenshots before sharing."
177
+ : "Not scanned for secrets: look at the screenshots before sharing.",
178
+ });
179
+ }
180
+ finally {
181
+ rmSync(work, { recursive: true, force: true });
182
+ }
183
+ }
184
+ catch (error) {
185
+ if (createdDir)
186
+ rmSync(createdDir, { recursive: true, force: true });
187
+ else
188
+ for (const p of written)
189
+ rmSync(p, { force: true });
190
+ return errorResponse(error);
191
+ }
192
+ });
193
+ }
@@ -5,8 +5,21 @@ import { STOPS_SESSION, looseOutput } from "../utils/toolSpec.js";
5
5
  import { requireFfmpeg } from "../utils/ffmpeg.js";
6
6
  import { probeDuration, stopSession } from "../utils/lifecycle.js";
7
7
  import { getStore } from "../context.js";
8
+ import { finishReplay } from "../utils/replay.js";
9
+ function replayReport(r) {
10
+ return {
11
+ saved: r.saved,
12
+ discarded: r.discarded,
13
+ ...(r.save ? { durationSec: r.save.durationSec, eventsPath: r.save.eventsPath } : {}),
14
+ ...(r.error ? { error: r.error, note: "The buffer was kept; call stop_recording with save: true again, or save_replay." } : {}),
15
+ };
16
+ }
8
17
  const inputSchema = {
9
18
  sessionId: z.string().min(1).describe("Session id returned by start_recording."),
19
+ save: z
20
+ .boolean()
21
+ .optional()
22
+ .describe("Replay buffer: write it all to outputPath first (default: discard)."),
10
23
  };
11
24
  export function register(server) {
12
25
  server.registerTool("stop_recording", {
@@ -28,7 +41,16 @@ export function register(server) {
28
41
  throw new ScreencastError(`No session with id "${args.sessionId}".`);
29
42
  }
30
43
  if (record.status !== "recording") {
44
+ const replay = record.replay && existsSync(record.replay.dir)
45
+ ? await finishReplay(record.replay, {
46
+ save: args.save ?? false,
47
+ output: record.outputPath,
48
+ quality: record.quality,
49
+ tools: requireFfmpeg,
50
+ })
51
+ : undefined;
31
52
  return okResponse({
53
+ ...(replay ? { replay: replayReport(replay) } : {}),
32
54
  sessionId: record.id,
33
55
  status: record.status,
34
56
  outputPath: record.outputPath,
@@ -42,9 +64,10 @@ export function register(server) {
42
64
  });
43
65
  }
44
66
  const { ffprobe } = requireFfmpeg();
45
- const { record: updated, graceful, durationSec } = await stopSession(store, record, {
67
+ const { record: updated, graceful, durationSec, replay } = await stopSession(store, record, {
46
68
  reason: "stopped",
47
69
  probe: (path) => probeDuration(ffprobe, path),
70
+ saveReplay: args.save,
48
71
  });
49
72
  return okResponse({
50
73
  sessionId: record.id,
@@ -52,6 +75,7 @@ export function register(server) {
52
75
  outputPath: record.outputPath,
53
76
  durationSec: durationSec ?? null,
54
77
  finalizedGracefully: graceful,
78
+ ...(replay ? { replay: replayReport(replay) } : {}),
55
79
  ...(updated?.events
56
80
  ? { eventsPath: updated.events.path, events: updated.events.summary ?? {}, ...(updated.events.error ? { eventsError: updated.events.error } : {}) }
57
81
  : {}),
@@ -4,7 +4,7 @@ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
4
  import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
5
5
  import { requireFfmpeg, runFfmpeg, probeMedia, hasFilter } from "../utils/ffmpeg.js";
6
6
  import { jobTimeoutMs } from "../utils/jobs.js";
7
- import { resolveWhisperModel, buildTranscribeArgs, parseSrt, normalizeCues, formatSrt, WHISPER_MODEL_ENV, } from "../utils/captions.js";
7
+ import { resolveWhisperModel, buildTranscribeArgs, parseSrt, normalizeCues, mergePunctuation, formatSrt, WHISPER_MODEL_ENV, } from "../utils/captions.js";
8
8
  import { resolveOutput, subdir, stamp, rand, tempPath } from "../utils/paths.js";
9
9
  const inputSchema = {
10
10
  input: z.string().min(1).describe("Path to the video or audio to transcribe."),
@@ -13,6 +13,7 @@ const inputSchema = {
13
13
  .optional()
14
14
  .describe(`Path to a whisper.cpp model file (ggml-*.bin). Defaults to ${WHISPER_MODEL_ENV}.`),
15
15
  language: z.string().optional().describe("Spoken language code, e.g. 'en', or 'auto' (default)."),
16
+ words: z.boolean().optional().describe("One word per cue, for word timing (cut_by_transcript)."),
16
17
  output: z.string().optional().describe("Optional output .srt path. Defaults under SCREENCAST_HOME/edits."),
17
18
  overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
18
19
  };
@@ -41,10 +42,10 @@ export function register(server) {
41
42
  const output = resolveOutput(args.output, subdir("edits"), `captions-${stamp()}-${rand()}.srt`, args.overwrite);
42
43
  const raw = tempPath(".srt");
43
44
  try {
44
- await runFfmpeg(buildTranscribeArgs(args.input, model, raw, args.language ?? "auto"), jobTimeoutMs(info.durationSec), {
45
+ await runFfmpeg(buildTranscribeArgs(args.input, model, raw, args.language ?? "auto", args.words), jobTimeoutMs(info.durationSec), {
45
46
  signal: extra.signal,
46
47
  });
47
- const cues = existsSync(raw) ? normalizeCues(parseSrt(readFileSync(raw, "utf8"))) : [];
48
+ const cues = existsSync(raw) ? normalizeCues(mergePunctuation(parseSrt(readFileSync(raw, "utf8")))) : [];
48
49
  writeFileSync(output, formatSrt(cues));
49
50
  const text = cues.map((c) => c.text.replace(/\n/g, " ")).join(" ");
50
51
  return okResponse({
@@ -9,7 +9,7 @@ import { keyframesToViews, buildZoomArgs, createAutoZoomPlanner, planClickZoom,
9
9
  import { eventPaths, parseEventsJsonl } from "../utils/events.js";
10
10
  import { validateColor } from "../utils/validate.js";
11
11
  export const MAX_RINGS = 200;
12
- function readClicks(path) {
12
+ export function readClicks(path) {
13
13
  if (!existsSync(path))
14
14
  return null;
15
15
  return parseEventsJsonl(readFileSync(path, "utf8"))
@@ -59,13 +59,18 @@ export function audioCodecFor(output) {
59
59
  return ["-c:a", "aac", "-b:a", "192k"];
60
60
  }
61
61
  }
62
- export function buildLoudnessApplyArgs(input, output, t, m) {
62
+ export function loudnormFilter(t, m) {
63
+ if (!m)
64
+ return `loudnorm=${filterTarget(t)}`;
63
65
  const measured = `measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:` +
64
66
  `measured_thresh=${m.input_thresh}:offset=${m.target_offset}`;
67
+ return `loudnorm=${filterTarget(t)}:${measured}:linear=true`;
68
+ }
69
+ export function buildLoudnessApplyArgs(input, output, t, m) {
65
70
  return [
66
71
  "-y", "-hide_banner", "-i", input,
67
72
  ...keepVideoArgs(output),
68
- "-af", `loudnorm=${filterTarget(t)}:${measured}:linear=true:print_format=json`,
73
+ "-af", `${loudnormFilter(t, m)}:print_format=json`,
69
74
  "-ar", "48000",
70
75
  ...audioCodecFor(output),
71
76
  output,
@@ -91,14 +96,17 @@ export function noiseFloorSetting(floorDb) {
91
96
  return -50;
92
97
  return Math.max(-80, Math.min(-20, Math.round(floorDb + 5)));
93
98
  }
94
- export function buildDenoiseArgs(input, output, strength = "medium", noiseFloorDb = null) {
99
+ export function denoiseFilter(strength, noiseFloorDb) {
95
100
  const nr = DENOISE_NR[strength];
96
101
  if (nr === undefined)
97
102
  throw new ScreencastError(`Unknown denoise strength "${strength}".`);
103
+ return `afftdn=nr=${nr}:nf=${noiseFloorSetting(noiseFloorDb)}`;
104
+ }
105
+ export function buildDenoiseArgs(input, output, strength = "medium", noiseFloorDb = null) {
98
106
  return [
99
107
  "-y", "-i", input,
100
108
  ...keepVideoArgs(output),
101
- "-af", `afftdn=nr=${nr}:nf=${noiseFloorSetting(noiseFloorDb)}`,
109
+ "-af", denoiseFilter(strength, noiseFloorDb),
102
110
  ...audioCodecFor(output),
103
111
  output,
104
112
  ];
@@ -0,0 +1,151 @@
1
+ import { ScreencastError } from "./errors.js";
2
+ import { validateColor } from "./validate.js";
3
+ import { ASPECT_DIMS } from "./produce.js";
4
+ import { resolveQuality } from "./targets.js";
5
+ import { stillOutput } from "./paths.js";
6
+ export const BACKDROP_PRESETS = {
7
+ desktop: ["#1B2330", "#0A0D12"],
8
+ rec: ["#FF4545", "#5C0F1A"],
9
+ amber: ["#FFB454", "#FF4545"],
10
+ light: ["#F4F7FA", "#B9C4D0"],
11
+ };
12
+ export const BACKDROP_PRESET_NAMES = Object.keys(BACKDROP_PRESETS);
13
+ export const DEFAULT_BACKDROP_PRESET = "desktop";
14
+ export const MAX_BACKDROP_COLORS = 4;
15
+ export const DEFAULT_SHADOW_OPACITY = 0.5;
16
+ const even = (n) => 2 * Math.round(n / 2);
17
+ const evenDown = (n) => 2 * Math.floor(n / 2);
18
+ function nonNegInt(v, label, max) {
19
+ if (v === undefined)
20
+ return undefined;
21
+ if (!Number.isFinite(v) || v < 0 || v > max)
22
+ throw new ScreencastError(`${label} must be between 0 and ${max}.`);
23
+ return Math.round(v);
24
+ }
25
+ export function backdropLayout(W, H, opts = {}) {
26
+ if (!(W > 0 && H > 0))
27
+ throw new ScreencastError("The input has no frame size.");
28
+ const padOpt = nonNegInt(opts.padding, "padding", 2000);
29
+ const radiusOpt = nonNegInt(opts.radius, "radius", 1000);
30
+ const shadowOpt = nonNegInt(opts.shadow, "shadow", 200);
31
+ let canvasW;
32
+ let canvasH;
33
+ let contentW = W;
34
+ let contentH = H;
35
+ let x;
36
+ let y;
37
+ let padding;
38
+ let scaled = false;
39
+ if (opts.aspect) {
40
+ const dim = ASPECT_DIMS[opts.aspect];
41
+ if (!dim)
42
+ throw new ScreencastError(`Unknown aspect "${opts.aspect}".`);
43
+ canvasW = dim.w;
44
+ canvasH = dim.h;
45
+ padding = even(padOpt ?? Math.max(canvasW, canvasH) * 0.06);
46
+ const availW = canvasW - 2 * padding;
47
+ const availH = canvasH - 2 * padding;
48
+ if (availW < 16 || availH < 16)
49
+ throw new ScreencastError(`padding ${padding} leaves no room on a ${opts.aspect} canvas.`);
50
+ const s = Math.min(availW / W, availH / H);
51
+ contentW = Math.max(2, evenDown(W * s));
52
+ contentH = Math.max(2, evenDown(H * s));
53
+ scaled = contentW !== W || contentH !== H;
54
+ x = evenDown((canvasW - contentW) / 2);
55
+ y = evenDown((canvasH - contentH) / 2);
56
+ }
57
+ else {
58
+ padding = even(padOpt ?? Math.max(W, H) * 0.06);
59
+ canvasW = W + 2 * padding + (W % 2);
60
+ canvasH = H + 2 * padding + (H % 2);
61
+ x = padding;
62
+ y = padding;
63
+ }
64
+ const longer = Math.max(contentW, contentH);
65
+ const radius = Math.min(radiusOpt ?? Math.round(longer * 0.012), Math.floor(Math.min(contentW, contentH) / 2));
66
+ const shadow = shadowOpt ?? Math.round(longer * 0.025);
67
+ const below = canvasH - y - contentH;
68
+ const shadowOffset = shadow > 0 ? Math.max(0, Math.min(Math.round(shadow / 2), below)) : 0;
69
+ return { canvasW, canvasH, contentW, contentH, x, y, padding, radius, shadow, shadowOffset, scaled };
70
+ }
71
+ export function backdropColors(opts) {
72
+ if (opts.colors !== undefined) {
73
+ if (opts.colors.length < 1 || opts.colors.length > MAX_BACKDROP_COLORS) {
74
+ throw new ScreencastError(`colors takes 1 to ${MAX_BACKDROP_COLORS} colors.`);
75
+ }
76
+ return opts.colors.map((c, i) => validateColor(c, `colors[${i}]`));
77
+ }
78
+ const preset = opts.preset ?? DEFAULT_BACKDROP_PRESET;
79
+ const colors = BACKDROP_PRESETS[preset];
80
+ if (!colors)
81
+ throw new ScreencastError(`Unknown backdrop preset "${preset}".`);
82
+ return [...colors];
83
+ }
84
+ export function roundedMaskExpr(radius, invert = false) {
85
+ const r = radius;
86
+ const dx = `max(max(${r}-X-0.5,X+0.5-(W-${r})),0)`;
87
+ const dy = `max(max(${r}-Y-0.5,Y+0.5-(H-${r})),0)`;
88
+ const inside = `clip(${r}+0.5-hypot(${dx},${dy}),0,1)`;
89
+ return invert ? `255-255*${inside}` : `255*${inside}`;
90
+ }
91
+ export function backdropSteps(opts, src, input, firstInput, tag, still = false) {
92
+ const L = backdropLayout(src.width, src.height, opts);
93
+ if (opts.shadowOpacity !== undefined && !(opts.shadowOpacity >= 0 && opts.shadowOpacity <= 1)) {
94
+ throw new ScreencastError("shadowOpacity must be between 0 and 1.");
95
+ }
96
+ const opacity = opts.shadowOpacity ?? DEFAULT_SHADOW_OPACITY;
97
+ const { canvasW: CW, canvasH: CH, contentW: w, contentH: h, x, y } = L;
98
+ const one = ":r=1:d=1";
99
+ const steps = [];
100
+ const extraInputs = [];
101
+ const bg = `[${tag}bg]`;
102
+ if (opts.image) {
103
+ extraInputs.push("-i", opts.image);
104
+ steps.push(`[${firstInput}:v]scale=${CW}:${CH}:force_original_aspect_ratio=increase,crop=${CW}:${CH},setsar=1,trim=end_frame=1,format=rgba${bg}`);
105
+ }
106
+ else {
107
+ const colors = backdropColors(opts);
108
+ if (colors.length === 1) {
109
+ steps.push(`color=c=${colors[0]}:s=${CW}x${CH}${one},format=rgba${bg}`);
110
+ }
111
+ else {
112
+ const cs = colors.map((c, i) => `c${i}=${c}`).join(":");
113
+ steps.push(`gradients=s=${CW}x${CH}:${cs}:n=${colors.length}:x0=0:y0=0:x1=${CW}:y1=${CH}:r=1,trim=end_frame=1,format=rgba${bg}`);
114
+ }
115
+ }
116
+ let base = bg;
117
+ if (L.shadow > 0 && opacity > 0) {
118
+ const sa = `[${tag}sa]`;
119
+ const sc = `[${tag}sc]`;
120
+ const sh = `[${tag}sh]`;
121
+ const bs = `[${tag}bs]`;
122
+ const shape = L.radius > 0 ? `format=gray,geq=lum='${roundedMaskExpr(L.radius)}'` : "format=gray";
123
+ steps.push(`color=c=white:s=${w}x${h}${one},${shape},pad=${CW}:${CH}:${x}:${y + L.shadowOffset}:color=black,` +
124
+ `gblur=sigma=${(L.shadow / 2).toFixed(2)}${sa}`);
125
+ steps.push(`color=c=black:s=${CW}x${CH}${one}${sc}`);
126
+ steps.push(`${sc}${sa}alphamerge,format=rgba,colorchannelmixer=aa=${opacity}${sh}`);
127
+ steps.push(`${base}${sh}overlay=0:0:format=rgb${bs}`);
128
+ base = bs;
129
+ }
130
+ const hole = `[${tag}hole]`;
131
+ const frame = `[${tag}frame]`;
132
+ const holeShape = L.radius > 0 ? `format=gray,geq=lum='${roundedMaskExpr(L.radius, true)}'` : "format=gray";
133
+ steps.push(`color=c=black:s=${w}x${h}${one},${holeShape},pad=${CW}:${CH}:${x}:${y}:color=white${hole}`);
134
+ steps.push(`${base}${hole}alphamerge,format=rgba${frame}`);
135
+ const padded = `[${tag}pad]`;
136
+ const out = `[${tag}bd]`;
137
+ const fit = L.scaled ? `scale=${w}:${h},setsar=1,` : "";
138
+ steps.push(`${input}${fit}pad=${CW}:${CH}:${x}:${y}:color=black${padded}`);
139
+ steps.push(`${padded}${frame}overlay=0:0${still ? ":format=rgb" : ""}${out}`);
140
+ return { steps, out, extraInputs, layout: L };
141
+ }
142
+ export function buildBackdropArgs(input, output, opts, src, still = false, quality = "standard") {
143
+ const { steps, out, extraInputs, layout } = backdropSteps(opts, src, "[0:v]", 1, "", still);
144
+ const final = "[vout]";
145
+ steps.push(`${out}format=${still ? "rgb24" : "yuv420p"}${final}`);
146
+ const head = ["-y", "-i", input, ...extraInputs, "-filter_complex", steps.join(";"), "-map", final];
147
+ const args = still
148
+ ? [...head, "-frames:v", "1", ...stillOutput(output)]
149
+ : [...head, "-map", "0:a?", ...resolveQuality(quality), "-c:a", "copy", "-movflags", "+faststart", output];
150
+ return { args, layout };
151
+ }