@tmhs/screencast-mcp 0.46.0 → 0.47.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.
@@ -0,0 +1,84 @@
1
+ import { z } from "zod";
2
+ import { existsSync, mkdtempSync, readFileSync, 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 { OUTPUT_PATH, WRITES_FILE } from "../utils/toolSpec.js";
7
+ import { requireFfmpeg, probeMedia } from "../utils/ffmpeg.js";
8
+ import { runEditJob } from "../utils/jobs.js";
9
+ import { editOutputExt, assertEditContainer } from "../utils/media.js";
10
+ import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
11
+ import { markersOrChapters, readMarkers, writeMarkers } from "../utils/chapters.js";
12
+ import { formatSrt } from "../utils/captions.js";
13
+ import { buildNarrateArgs, narrationCues, placementWarnings, resolveLines, synthesize, wavDurationSec, MAX_RATE, MIN_RATE, } from "../utils/narrate.js";
14
+ const inputSchema = {
15
+ video: z.string().min(1).describe("Path to the video."),
16
+ lines: z
17
+ .array(z.object({
18
+ t: z.number().nonnegative().optional().describe("Seconds."),
19
+ marker: z.string().optional().describe("Or a marker label."),
20
+ text: z.string().min(1),
21
+ }))
22
+ .min(1),
23
+ voice: z.string().optional().describe("Voice name or part (doctor lists them)."),
24
+ rate: z.number().min(MIN_RATE).max(MAX_RATE).optional().describe("Default 1."),
25
+ duck: z.boolean().optional().describe("Duck the original audio (default true)."),
26
+ output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
27
+ overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
28
+ };
29
+ export function register(server) {
30
+ server.registerTool("narrate", {
31
+ title: "Narrate",
32
+ description: "Offline voiceover with the built-in Windows voices: speaks each line at its time or marker " +
33
+ "over the audio, plus an SRT.",
34
+ inputSchema,
35
+ outputSchema: OUTPUT_PATH,
36
+ annotations: WRITES_FILE,
37
+ }, async (args, extra) => {
38
+ let work = null;
39
+ try {
40
+ requireFfmpeg();
41
+ if (!existsSync(args.video))
42
+ throw new ScreencastError(`Input file not found: ${args.video}`);
43
+ const info = await probeMedia(args.video);
44
+ if (info.durationSec === null)
45
+ throw new ScreencastError(`Could not read duration of ${args.video}.`);
46
+ const needsMarkers = args.lines.some((l) => l.marker !== undefined);
47
+ const markers = needsMarkers ? (await markersOrChapters(args.video, extra.signal)).markers : [];
48
+ const lines = resolveLines(args.lines, markers);
49
+ assertEditContainer(args.output);
50
+ const output = resolveOutput(args.output, subdir("edits"), `narrated-${stamp()}-${rand()}${editOutputExt(args.video)}`, args.overwrite);
51
+ work = mkdtempSync(join(tmpdir(), "screencast-tts-"));
52
+ const wavs = lines.map((_, i) => join(work, `line-${i}.wav`));
53
+ const voice = await synthesize(lines.map((l, i) => ({ text: l.text, path: wavs[i] })), { voice: args.voice, rate: args.rate, signal: extra.signal });
54
+ const placed = lines.map((l, i) => ({ ...l, durationSec: wavDurationSec(readFileSync(wavs[i])) }));
55
+ const warnings = placementWarnings(placed, info.durationSec);
56
+ const ffArgs = buildNarrateArgs(args.video, wavs, output, placed, info.durationSec, {
57
+ hasAudio: info.audioCodec !== null,
58
+ channels: info.channels,
59
+ duck: args.duck,
60
+ });
61
+ await runEditJob(ffArgs, { output, durationSec: info.durationSec, extra });
62
+ const srtPath = output.replace(/\.[^./\\]+$/, "") + ".srt";
63
+ writeFileSync(srtPath, formatSrt(narrationCues(placed, info.durationSec)));
64
+ const inputMarkers = readMarkers(args.video);
65
+ if (inputMarkers.length > 0)
66
+ writeMarkers(output, inputMarkers);
67
+ return okResponse({
68
+ outputPath: output,
69
+ srtPath,
70
+ voice,
71
+ lines: placed.map((p) => ({ t: p.t, durationSec: Math.round(p.durationSec * 100) / 100 })),
72
+ mixedWithOriginal: info.audioCodec !== null,
73
+ ...(warnings.length ? { warnings } : {}),
74
+ });
75
+ }
76
+ catch (error) {
77
+ return errorResponse(error);
78
+ }
79
+ finally {
80
+ if (work)
81
+ rmSync(work, { recursive: true, force: true });
82
+ }
83
+ });
84
+ }
@@ -15,6 +15,7 @@ const inputSchema = {
15
15
  height: z.number().int().positive().optional().describe("Scale to this height."),
16
16
  start: z.number().nonnegative().optional().describe("Show from this second."),
17
17
  end: z.number().positive().optional().describe("Hide after this second."),
18
+ shape: z.enum(["rect", "circle"]).optional().describe("circle: centre square masked round (webcam)."),
18
19
  output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
19
20
  overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
20
21
  };
@@ -48,6 +49,7 @@ export function register(server) {
48
49
  start: args.start,
49
50
  end: args.end,
50
51
  scale,
52
+ shape: args.shape,
51
53
  durationSec,
52
54
  });
53
55
  await runEditJob(ffArgs, { output, durationSec, extra });
@@ -0,0 +1,44 @@
1
+ import { z } from "zod";
2
+ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
3
+ import { STOPS_SESSION, looseOutput } from "../utils/toolSpec.js";
4
+ import { requireFfmpeg } from "../utils/ffmpeg.js";
5
+ import { pauseSession, probeDuration } from "../utils/lifecycle.js";
6
+ import { recordedSec } from "../utils/pause.js";
7
+ import { getStore } from "../context.js";
8
+ const r3 = (n) => Math.round(n * 1000) / 1000;
9
+ export function register(server) {
10
+ server.registerTool("pause_recording", {
11
+ title: "Pause Recording",
12
+ description: "Pause a recording; until resume_recording nothing is captured, and the gap is left out of the file, events, and markers.",
13
+ inputSchema: { sessionId: z.string().min(1).describe("From start_recording.") },
14
+ outputSchema: looseOutput({ sessionId: z.string(), status: z.string(), recordedSec: z.number() }),
15
+ annotations: STOPS_SESSION,
16
+ }, async (args) => {
17
+ try {
18
+ const store = getStore();
19
+ const record = store.get(args.sessionId);
20
+ if (!record)
21
+ throw new ScreencastError(`No session with id "${args.sessionId}".`);
22
+ if (record.status === "paused") {
23
+ return okResponse({
24
+ sessionId: record.id,
25
+ status: "paused",
26
+ recordedSec: r3(recordedSec(record.segments?.parts ?? [])),
27
+ note: "Already paused.",
28
+ });
29
+ }
30
+ const { ffprobe } = requireFfmpeg();
31
+ const res = await pauseSession(store, record, { probe: (p) => probeDuration(ffprobe, p) });
32
+ return okResponse({
33
+ sessionId: record.id,
34
+ status: "paused",
35
+ recordedSec: r3(res.recordedSec),
36
+ segments: res.record?.segments?.parts.length ?? 0,
37
+ note: "Nothing is captured until resume_recording; stop_recording joins what was recorded.",
38
+ });
39
+ }
40
+ catch (error) {
41
+ return errorResponse(error);
42
+ }
43
+ });
44
+ }
@@ -15,6 +15,8 @@ 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
17
  import { buildChapters, ffmetadata, markerPoints, markersOrChapters, retimeMarkers, writeMarkers } from "../utils/chapters.js";
18
+ import { cursorOptionsSchema, loadCursor } from "./cursor.js";
19
+ import { cursorSpritePath } from "../utils/cursor.js";
18
20
  import { backdropOptionsSchema } from "./backdrop.js";
19
21
  import { keystrokeOptionsSchema, loadBadges, prepareKeystrokeAssets } from "./keystrokeOverlay.js";
20
22
  import { MAX_ZOOM } from "../utils/zoom.js";
@@ -85,6 +87,7 @@ const step = z.discriminatedUnion("op", [
85
87
  }),
86
88
  z.object({ op: z.literal("backdrop"), ...backdropOptionsSchema }),
87
89
  z.object({ op: z.literal("keystroke_overlay"), ...keystrokeOptionsSchema }),
90
+ z.object({ op: z.literal("cursor"), ...cursorOptionsSchema }),
88
91
  z.object({ op: z.literal("export_preset"), platform: z.enum(PLATFORMS), fit }),
89
92
  z.object({
90
93
  op: z.literal("export_gif"),
@@ -120,7 +123,7 @@ const inputSchema = {
120
123
  export function register(server) {
121
124
  server.registerTool("pipeline", {
122
125
  title: "Edit Pipeline",
123
- description: "Run several edits (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, reframe, zoom, backdrop, " +
126
+ description: "Run several edits (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, cursor, reframe, zoom, backdrop, " +
124
127
  "audio, burn_subtitles, then optionally export_preset or export_gif) in one ffmpeg pass: one re-encode, no " +
125
128
  "intermediate files. Prefer it over chaining edit tools; a recipe does the usual polish in one call.",
126
129
  inputSchema,
@@ -232,12 +235,22 @@ export function register(server) {
232
235
  keystrokes[i] = { badges, fontFile: k.fontFile, textFiles: k.textFiles };
233
236
  warnings.push(...k.warnings.map((w) => `Step ${i}, ${w.charAt(0).toLowerCase()}${w.slice(1)}`));
234
237
  }
238
+ const cursor = {};
239
+ for (const [i, s] of steps.entries()) {
240
+ if (s.op !== "cursor")
241
+ continue;
242
+ cursor[i] = {
243
+ plan: loadCursor(args.input, s.events, s, info.durationSec),
244
+ sprite: cursorSpritePath(),
245
+ commandsFile: args.dryRun ? `<cursor ${i}.cmd>` : join(work, `s${i}_cursor.cmd`),
246
+ };
247
+ }
235
248
  const target = last.op === "export_gif" ? (args.dryRun ? "<temporary stage1.mp4>" : join(work, "stage1.mp4")) : output;
236
249
  const audioM = {};
237
250
  const subtitles = {};
238
251
  const fontsDir = dirname(bundledFontPath("regular"));
239
252
  const planWith = (chaptersFile) => planPipeline(args.input, target, steps, src, assets, args.quality ?? "standard", {
240
- keystrokes, idle, clicks, audio: audioM, subtitles, fontsDir, chaptersFile,
253
+ keystrokes, cursor, idle, clicks, audio: audioM, subtitles, fontsDir, chaptersFile,
241
254
  });
242
255
  let plan = planWith();
243
256
  let transcript;
@@ -337,6 +350,8 @@ export function register(server) {
337
350
  };
338
351
  if (args.dryRun)
339
352
  return okResponse({ dryRun: true, ...result, ffmpegArgs: plan.args });
353
+ for (const f of plan.files)
354
+ writeFileSync(f.path, f.content);
340
355
  await runEditJob(plan.args, { output: target, durationSec: plan.durationSec, inputDurationSec: info.durationSec, extra });
341
356
  if (plan.gif) {
342
357
  const anim = await exportAnimation(target, output, plan.gif, extra);
@@ -53,7 +53,7 @@ export function register(server) {
53
53
  throw new ScreencastError(`Session "${args.sessionId}" was recorded without an event log. ` +
54
54
  "Start the recording with events: true.");
55
55
  }
56
- if (record.status === "recording") {
56
+ if (record.status === "recording" || record.status === "paused") {
57
57
  throw new ScreencastError("The recording is still running; its event log is written when it stops.");
58
58
  }
59
59
  path = record.events.path;
@@ -0,0 +1,46 @@
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 { resumeSession } from "../utils/recorder.js";
6
+ import { logMessage } from "../utils/logging.js";
7
+ import { recordedSec } from "../utils/pause.js";
8
+ import { getStore } from "../context.js";
9
+ const r3 = (n) => Math.round(n * 1000) / 1000;
10
+ export function register(server) {
11
+ server.registerTool("resume_recording", {
12
+ title: "Resume Recording",
13
+ description: "Resume a paused recording (same target and settings).",
14
+ inputSchema: { sessionId: z.string().min(1).describe("From start_recording.") },
15
+ outputSchema: looseOutput({ sessionId: z.string(), status: z.string(), recordedSec: z.number() }),
16
+ annotations: WRITES_FILE,
17
+ }, async (args) => {
18
+ try {
19
+ const store = getStore();
20
+ const record = store.get(args.sessionId);
21
+ if (!record)
22
+ throw new ScreencastError(`No session with id "${args.sessionId}".`);
23
+ if (record.status === "recording") {
24
+ return okResponse({
25
+ sessionId: record.id,
26
+ status: "recording",
27
+ recordedSec: r3(recordedSec(record.segments?.parts ?? [])),
28
+ note: "Already recording.",
29
+ });
30
+ }
31
+ const { ffmpeg } = requireFfmpeg();
32
+ const res = await resumeSession(store, record, ffmpeg);
33
+ logMessage("notice", `Recording ${record.id} resumed.`, { sessionId: record.id });
34
+ return okResponse({
35
+ sessionId: record.id,
36
+ status: "recording",
37
+ recordedSec: r3(res.recordedSec),
38
+ pid: res.record.pid,
39
+ ...(res.capSec > 0 ? { remainingSec: res.capSec } : {}),
40
+ });
41
+ }
42
+ catch (error) {
43
+ return errorResponse(error);
44
+ }
45
+ });
46
+ }
@@ -21,7 +21,7 @@ function resolveInput(args) {
21
21
  const record = getStore().get(args.sessionId);
22
22
  if (!record)
23
23
  throw new ScreencastError(`No session with id "${args.sessionId}".`);
24
- if (record.status === "recording")
24
+ if (record.status === "recording" || record.status === "paused")
25
25
  throw new ScreencastError("The recording is still running; stop it first.");
26
26
  return record.outputPath;
27
27
  }
@@ -4,16 +4,18 @@ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
4
  import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
5
5
  import { requireFfmpeg, wgcAvailable } from "../utils/ffmpeg.js";
6
6
  import { fileURLToPath } from "node:url";
7
- import { buildCaptureArgs, captureFrame, resolveQuality, DEFAULT_FPS, DEFAULT_QUALITY, DEFAULT_MAX_RECORDING_SEC, MAX_RECORDING_CAP_SEC, resolveMaxDuration, captureKeyframeArgs, } from "../utils/targets.js";
7
+ import { buildCaptureArgs, captureFrame, DEFAULT_FPS, DEFAULT_QUALITY, DEFAULT_MAX_RECORDING_SEC, MAX_RECORDING_CAP_SEC, resolveMaxDuration, captureKeyframeArgs, } from "../utils/targets.js";
8
8
  import { resolveCaptureTarget } from "../utils/resolveTarget.js";
9
9
  import { windowMatchReport } from "../utils/windows.js";
10
- import { resolveLoopbackDevice } from "../utils/audioDevices.js";
10
+ import { resolveLoopbackDevice, resolveVideoDevice } from "../utils/audioDevices.js";
11
11
  import { confirmCapture, describeTarget } from "../utils/consent.js";
12
- import { logMessage, StderrWatch } from "../utils/logging.js";
13
12
  import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
14
13
  import { getStore } from "../context.js";
15
- import { classifyUnrequestedExit, killPid, serverIdentity } from "../utils/sessions.js";
16
- import { rmSync } from "node:fs";
14
+ import { killPid, serverIdentity } from "../utils/sessions.js";
15
+ import { mkdirSync, rmSync } from "node:fs";
16
+ import { buildDdaInputArgs, ddagrabWorks, encoderArgs, getDxgiOutputs, planDdaSource, resolveEncoder, } from "../utils/gpu.js";
17
+ import { attachExitHandler, captureStartMs, settleCapture, tailLines, watchStderr, } from "../utils/recorder.js";
18
+ import { DEFAULT_WEBCAM_SIZE, eventClock, partsDir, sessionEnded, webcamOutputPath, webcamPartPath, } from "../utils/pause.js";
17
19
  import { basename, join } from "node:path";
18
20
  import { MAX_REPLAY_SEC, MIN_REPLAY_SEC, discardReplay, planReplayBuffer, prepareReplayDir, segmentOutputArgs, } from "../utils/replay.js";
19
21
  import { DEFAULT_KEY_MODE, eventPaths, parseCaptureStart, prepareEventPaths, startEventLogger, stopEventLogger, summarizeEvents, trackFinalizer, writeEventsFile, } from "../utils/events.js";
@@ -73,11 +75,28 @@ const inputSchema = {
73
75
  .optional()
74
76
  .describe("With events: masked (default) logs typing only as 0.5 s-grid bursts, never keys; shortcuts " +
75
77
  "also names Ctrl/Alt/Win chords. Typed text is never logged."),
78
+ cursor: z
79
+ .enum(["os", "events"])
80
+ .optional()
81
+ .describe('events: leave the OS cursor out and log it (implies events) for the cursor tool to redraw.'),
76
82
  backend: z
77
- .enum(["gdigrab", "wgc"])
83
+ .enum(["gdigrab", "wgc", "ddagrab"])
78
84
  .optional()
79
85
  .describe("gdigrab (default): the screen rectangle. wgc (window: targets, FFmpeg 8+): the window's own " +
80
- "surface, even when covered or moved; client area only, no audio."),
86
+ "surface, even when covered or moved; client area only, no audio. ddagrab: one display on the GPU, low CPU."),
87
+ encoder: z
88
+ .enum(["auto", "x264", "nvenc", "qsv", "amf"])
89
+ .optional()
90
+ .describe("auto = first working GPU encoder, else x264 (default with ddagrab; else x264)."),
91
+ webcam: z
92
+ .object({
93
+ device: z.string().optional().describe("list_video_devices name (default: first)."),
94
+ corner: z.enum(["top_left", "top_right", "bottom_left", "bottom_right"]).optional(),
95
+ size: z.number().min(0.1).max(0.5).optional().describe("Share of width (0.25)."),
96
+ shape: z.enum(["rect", "circle"]).optional(),
97
+ })
98
+ .optional()
99
+ .describe("Also record a camera to <output>.webcam.mp4, aligned for overlay."),
81
100
  replayBufferSec: z
82
101
  .number()
83
102
  .int()
@@ -86,6 +105,10 @@ const inputSchema = {
86
105
  .optional()
87
106
  .describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab only."),
88
107
  };
108
+ function webcamStart(watch, audio) {
109
+ const ms = parseCaptureStart(watch.head(), audio ? 2 : 1);
110
+ return ms !== null ? { webcamStartMs: ms } : {};
111
+ }
89
112
  export function register(server) {
90
113
  server.registerTool("start_recording", {
91
114
  title: "Start Recording",
@@ -102,6 +125,9 @@ export function register(server) {
102
125
  }, async (args, extra) => {
103
126
  try {
104
127
  const { ffmpeg } = requireFfmpeg();
128
+ const hideCursor = args.cursor === "events";
129
+ if (hideCursor)
130
+ args.events = true;
105
131
  const { target, monitors, window } = await resolveCaptureTarget(args.target, {
106
132
  exactTitle: args.exactTitle,
107
133
  backend: args.backend,
@@ -127,19 +153,43 @@ export function register(server) {
127
153
  const audio = args.audio?.source === "system"
128
154
  ? { device: await resolveLoopbackDevice(args.audio.device) }
129
155
  : undefined;
156
+ if (args.webcam && (backend === "wgc" || replay)) {
157
+ throw new ScreencastError("webcam works with backend gdigrab or ddagrab, without replayBufferSec.");
158
+ }
159
+ const webcamDevice = args.webcam ? await resolveVideoDevice(args.webcam.device) : undefined;
160
+ const dda = backend === "ddagrab" ? planDdaSource(captureFrame(target, monitors), await getDxgiOutputs()) : null;
130
161
  await confirmCapture(server, (replay ? `Keep a rolling ${replay.bufferSec} s replay buffer of ` : "Record ") +
131
162
  `${describeTarget(args.target, window)} ` +
132
163
  (maxDurationSec > 0 ? `for up to ${maxDurationSec} s` : "with no time limit") +
133
164
  (audio ? `, with system audio (${audio.device})` : ", without audio") +
165
+ (webcamDevice ? `, with the webcam (${webcamDevice})` : "") +
134
166
  (args.events ? ", logging mouse clicks and typing" : "") +
135
167
  (replay ? ", kept only until save_replay or stop_recording { save: true } writes it out?" : `, saved to ${output}?`), extra.signal);
136
- const captureArgs = buildCaptureArgs(target, {
168
+ const pick = await resolveEncoder(args.encoder ?? (backend === "ddagrab" ? "auto" : "x264"), backend === "ddagrab" ? "ddagrab" : "gdigrab", ffmpeg);
169
+ if (dda && !pick.gpuFrames && !(await ddagrabWorks(ffmpeg))) {
170
+ throw new ScreencastError("Desktop Duplication (ddagrab) does not capture on this machine (a remote session, or no D3D11 GPU).", 'Use backend "gdigrab".');
171
+ }
172
+ const hw = pick.encoder !== "x264";
173
+ const captureOpts = {
137
174
  fps,
138
175
  quality,
139
- output,
140
176
  monitors,
141
177
  audio,
178
+ drawMouse: !hideCursor,
179
+ ...(dda ? { videoInput: buildDdaInputArgs(dda, fps, { download: !pick.gpuFrames, drawMouse: !hideCursor }) } : {}),
180
+ ...(hw ? { videoCodec: encoderArgs(pick.encoder, quality, { gpuFrames: pick.gpuFrames }) } : {}),
181
+ };
182
+ const webcam = webcamDevice
183
+ ? { device: webcamDevice, ...(hw ? { codec: encoderArgs(pick.encoder, quality) } : {}) }
184
+ : undefined;
185
+ const webcamRaw = webcam ? webcamPartPath(output, 0) : undefined;
186
+ if (webcamRaw)
187
+ mkdirSync(partsDir(output), { recursive: true });
188
+ const captureArgs = buildCaptureArgs(target, {
189
+ ...captureOpts,
190
+ output,
142
191
  maxDurationSec,
192
+ ...(webcam && webcamRaw ? { webcam: { ...webcam, output: webcamRaw } } : {}),
143
193
  });
144
194
  const ffArgs = replay ? segmentOutputArgs(captureArgs, replay) : captureArgs;
145
195
  if (replay)
@@ -156,43 +206,15 @@ export function register(server) {
156
206
  const child = backend === "wgc"
157
207
  ? spawn(process.execPath, [
158
208
  fileURLToPath(new URL("../wgcRecorder.js", import.meta.url)),
159
- JSON.stringify({ ffmpeg, hwnd: window.hwnd, fps, encode: [...resolveQuality(quality), ...captureKeyframeArgs(fps)], output, maxDurationSec }),
209
+ JSON.stringify({ ffmpeg, hwnd: window.hwnd, fps, encode: [...encoderArgs(pick.encoder, quality), ...captureKeyframeArgs(fps)], output, maxDurationSec, cursor: !hideCursor }),
160
210
  ], { stdio: ["pipe", "ignore", "pipe"], windowsHide: true })
161
211
  : spawn(ffmpeg, ffArgs, {
162
212
  stdio: ["pipe", "ignore", "pipe"],
163
213
  windowsHide: true,
164
214
  });
165
- let stderrTail = "";
166
- let stderrHead = "";
167
215
  const id = `rec-${stamp()}-${rand(6)}`;
168
- const watch = new StderrWatch(() => ({ sessionId: id }));
169
- child.stderr?.on("data", (d) => {
170
- const text = d.toString();
171
- stderrTail = (stderrTail + text).slice(-2000);
172
- if (stderrHead.length < 8000)
173
- stderrHead += text;
174
- watch.feed(text);
175
- });
176
- const settled = await new Promise((resolve) => {
177
- const timer = setTimeout(() => resolve("running"), backend === "wgc" ? 15_000 : 1200);
178
- if (backend === "wgc") {
179
- child.stderr?.on("data", () => {
180
- if (parseCaptureStart(stderrHead) !== null) {
181
- clearTimeout(timer);
182
- resolve("running");
183
- }
184
- });
185
- }
186
- child.on("error", (err) => {
187
- clearTimeout(timer);
188
- stderrTail += `\n${err.message}`;
189
- resolve("exited");
190
- });
191
- child.on("exit", () => {
192
- clearTimeout(timer);
193
- resolve("exited");
194
- });
195
- });
216
+ const watch = watchStderr(child, id);
217
+ const settled = await settleCapture(child, watch, backend);
196
218
  if (settled === "exited") {
197
219
  if (logger)
198
220
  await stopEventLogger(logger);
@@ -200,11 +222,13 @@ export function register(server) {
200
222
  rmSync(evPaths.raw, { force: true });
201
223
  if (replay)
202
224
  discardReplay(replay);
203
- const tail = stderrTail.trim().split("\n").slice(-6).join("\n");
204
- throw new ScreencastError(`Recording failed to start (${backend === "wgc" ? "window capture" : "ffmpeg"} exited immediately):\n${tail}`);
225
+ if (webcamRaw)
226
+ rmSync(partsDir(output), { recursive: true, force: true });
227
+ throw new ScreencastError(`Recording failed to start (${backend === "wgc" ? "window capture" : "ffmpeg"} exited immediately):\n${tailLines(watch)}`);
205
228
  }
229
+ const startMs = captureStartMs(watch, backend, spawnedAt);
206
230
  if (backend === "wgc" && frame && window?.client) {
207
- const m = /wgc: (\d+)x(\d+)/.exec(stderrHead);
231
+ const m = /wgc: (\d+)x(\d+)/.exec(watch.head());
208
232
  frame = { x: window.client.x, y: window.client.y, w: m ? Number(m[1]) : frame.w, h: m ? Number(m[2]) : frame.h };
209
233
  }
210
234
  const record = {
@@ -217,7 +241,7 @@ export function register(server) {
217
241
  ...serverIdentity(),
218
242
  status: "recording",
219
243
  startedAt: new Date().toISOString(),
220
- videoStartMs: parseCaptureStart(stderrHead) ?? spawnedAt,
244
+ videoStartMs: startMs,
221
245
  ...(maxDurationSec > 0 ? { maxDurationSec } : {}),
222
246
  ...(window ? { matchedWindow: window.matchedTitle } : {}),
223
247
  ...(evPaths && !replay ? { events: { path: evPaths.jsonl, keys: keyMode } } : {}),
@@ -226,12 +250,37 @@ export function register(server) {
226
250
  replay: {
227
251
  ...replay,
228
252
  ...(evPaths && frame
229
- ? { events: { raw: evPaths.raw, keys: keyMode, startMs: parseCaptureStart(stderrHead) ?? spawnedAt, frame } }
253
+ ? { events: { raw: evPaths.raw, keys: keyMode, startMs, frame } }
230
254
  : {}),
231
255
  },
232
256
  }
233
257
  : {}),
234
258
  backend,
259
+ ...(pick.encoder !== "x264" ? { encoder: pick.encoder } : {}),
260
+ ...(backend !== "wgc" && !replay
261
+ ? {
262
+ capture: { target, opts: captureOpts, ...(webcam ? { webcam } : {}) },
263
+ segments: {
264
+ parts: [],
265
+ current: {
266
+ path: output,
267
+ startMs,
268
+ ...(webcamRaw ? { webcamPath: webcamRaw, ...webcamStart(watch, !!audio) } : {}),
269
+ },
270
+ },
271
+ }
272
+ : {}),
273
+ ...(webcamDevice
274
+ ? {
275
+ webcam: {
276
+ device: webcamDevice,
277
+ path: webcamOutputPath(output),
278
+ corner: args.webcam?.corner ?? "bottom_right",
279
+ size: args.webcam?.size ?? DEFAULT_WEBCAM_SIZE,
280
+ shape: args.webcam?.shape ?? "rect",
281
+ },
282
+ }
283
+ : {}),
235
284
  processImage: backend === "wgc" ? basename(process.execPath).toLowerCase() : "ffmpeg.exe",
236
285
  };
237
286
  const store = getStore();
@@ -249,6 +298,8 @@ export function register(server) {
249
298
  rmSync(evPaths.raw, { force: true });
250
299
  if (replay)
251
300
  discardReplay(replay);
301
+ if (webcamRaw)
302
+ rmSync(partsDir(output), { recursive: true, force: true });
252
303
  throw new ScreencastError(`Recording stopped: the session registry could not be written (${err.message}).`);
253
304
  }
254
305
  if (logger && replay) {
@@ -256,12 +307,11 @@ export function register(server) {
256
307
  trackFinalizer(id, exited.then(() => stopEventLogger(logger)));
257
308
  }
258
309
  else if (logger && evPaths && frame) {
259
- const exited = new Promise((resolve) => child.once("exit", () => resolve()));
260
- trackFinalizer(id, exited.then(async () => {
310
+ trackFinalizer(id, sessionEnded(id).then(async () => {
261
311
  await stopEventLogger(logger);
262
- const startMs = parseCaptureStart(stderrHead) ?? spawnedAt;
263
312
  try {
264
- const events = writeEventsFile(evPaths, { startMs, frame, endSec: (Date.now() - startMs) / 1000 });
313
+ const clock = eventClock(store.get(id)?.segments, startMs, Date.now());
314
+ const events = writeEventsFile(evPaths, { ...clock, frame });
265
315
  store.tryUpdate(id, {
266
316
  events: { path: evPaths.jsonl, keys: keyMode, count: events.length, summary: summarizeEvents(events) },
267
317
  });
@@ -275,23 +325,7 @@ export function register(server) {
275
325
  process.stderr.write(`Event log for ${id} failed: ${err instanceof Error ? err.message : String(err)}\n`);
276
326
  }));
277
327
  }
278
- child.on("exit", (code) => {
279
- store.detachChild(id);
280
- const cur = store.get(id);
281
- if (!cur || cur.status !== "recording" || store.isStopping(id))
282
- return;
283
- const verdict = classifyUnrequestedExit({ code, backend, maxDurationSec, elapsedMs: Date.now() - spawnedAt });
284
- logMessage(verdict.status === "failed" ? "error" : "notice", verdict.status === "failed"
285
- ? `Recording ${id} failed: the recorder exited with code ${code}.`
286
- : `Recording ${id} ended on its own (${verdict.endReason}).`, { sessionId: id, ...verdict });
287
- store.tryUpdate(id, {
288
- ...verdict,
289
- stoppedAt: new Date().toISOString(),
290
- ...(verdict.status === "failed"
291
- ? { error: `${backend === "wgc" ? "The window recorder" : "ffmpeg"} exited with code ${code}:\n${stderrTail.trim().split("\n").slice(-6).join("\n")}` }
292
- : {}),
293
- });
294
- });
328
+ attachExitHandler(store, id, child, { backend, maxDurationSec, spawnedAt, watch });
295
329
  return okResponse({
296
330
  sessionId: id,
297
331
  status: "recording",
@@ -302,6 +336,10 @@ export function register(server) {
302
336
  quality,
303
337
  audioDevice: audio?.device ?? null,
304
338
  maxDurationSec: maxDurationSec > 0 ? maxDurationSec : null,
339
+ encoder: pick.encoder,
340
+ ...(pick.note ? { encoderNote: pick.note } : {}),
341
+ ...(dda ? { gpuFrames: pick.gpuFrames } : {}),
342
+ ...(webcamDevice ? { webcam: { device: webcamDevice, path: webcamOutputPath(output) } } : {}),
305
343
  ...(window ? windowMatchReport(window) : {}),
306
344
  ...(evPaths && !replay ? { eventsPath: evPaths.jsonl, keys: keyMode } : {}),
307
345
  ...(replay
@@ -310,7 +348,8 @@ export function register(server) {
310
348
  note: (replay
311
349
  ? `Replay buffer running: save_replay keeps the last seconds (up to ${replay.bufferSec}s) without stopping it; ` +
312
350
  "stop_recording discards the buffer unless save: true (then it writes outputPath)."
313
- : "Call stop_recording with this sessionId to finalize the file.") +
351
+ : "Call stop_recording with this sessionId to finalize the file" +
352
+ (backend === "wgc" ? "." : " (pause_recording/resume_recording leave stretches out).")) +
314
353
  (maxDurationSec > 0
315
354
  ? ` It stops on its own after ${maxDurationSec}s (maxDurationSec).`
316
355
  : ""),
@@ -2,10 +2,11 @@ import { z } from "zod";
2
2
  import { existsSync } from "node:fs";
3
3
  import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
4
  import { STOPS_SESSION, looseOutput } from "../utils/toolSpec.js";
5
- import { requireFfmpeg } from "../utils/ffmpeg.js";
5
+ import { probeMedia, requireFfmpeg } from "../utils/ffmpeg.js";
6
6
  import { probeDuration, stopSession } from "../utils/lifecycle.js";
7
7
  import { getStore } from "../context.js";
8
8
  import { finishReplay } from "../utils/replay.js";
9
+ import { webcamPlacement } from "../utils/pause.js";
9
10
  function replayReport(r) {
10
11
  return {
11
12
  saved: r.saved,
@@ -14,6 +15,37 @@ function replayReport(r) {
14
15
  ...(r.error ? { error: r.error, note: "The buffer was kept; call stop_recording with save: true again, or save_replay." } : {}),
15
16
  };
16
17
  }
18
+ async function webcamReport(cam, output) {
19
+ if (cam.error || !existsSync(cam.path))
20
+ return { error: cam.error ?? `No webcam file was written (${cam.path}).` };
21
+ const size = async (p) => {
22
+ try {
23
+ const info = await probeMedia(p);
24
+ return info.width && info.height ? { width: info.width, height: info.height } : null;
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ };
30
+ const [screen, camSize] = await Promise.all([size(output), size(cam.path)]);
31
+ const circle = cam.shape === "circle";
32
+ const place = screen && camSize ? webcamPlacement(screen, circle ? { width: 1, height: 1 } : camSize, cam.corner, cam.size) : null;
33
+ return {
34
+ path: cam.path,
35
+ ...(place
36
+ ? {
37
+ overlay: {
38
+ input: output,
39
+ overlay: cam.path,
40
+ x: place.x,
41
+ y: place.y,
42
+ ...(circle ? { height: place.height, shape: "circle" } : { width: place.width }),
43
+ },
44
+ note: "Aligned with the recording: pass `overlay` to the overlay tool (any corner or size works).",
45
+ }
46
+ : {}),
47
+ };
48
+ }
17
49
  const inputSchema = {
18
50
  sessionId: z.string().min(1).describe("Session id returned by start_recording."),
19
51
  save: z
@@ -40,7 +72,7 @@ export function register(server) {
40
72
  if (!record) {
41
73
  throw new ScreencastError(`No session with id "${args.sessionId}".`);
42
74
  }
43
- if (record.status !== "recording") {
75
+ if (record.status !== "recording" && record.status !== "paused") {
44
76
  const replay = record.replay && existsSync(record.replay.dir)
45
77
  ? await finishReplay(record.replay, {
46
78
  save: args.save ?? false,
@@ -64,7 +96,7 @@ export function register(server) {
64
96
  });
65
97
  }
66
98
  const { ffprobe } = requireFfmpeg();
67
- const { record: updated, graceful, durationSec, replay } = await stopSession(store, record, {
99
+ const { record: updated, graceful, durationSec, replay, segments } = await stopSession(store, record, {
68
100
  reason: "stopped",
69
101
  probe: (path) => probeDuration(ffprobe, path),
70
102
  saveReplay: args.save,
@@ -76,6 +108,9 @@ export function register(server) {
76
108
  durationSec: durationSec ?? null,
77
109
  finalizedGracefully: graceful,
78
110
  ...(replay ? { replay: replayReport(replay) } : {}),
111
+ ...(segments && segments.count > 1 ? { segmentsJoined: segments.count } : {}),
112
+ ...(segments?.error ? { segmentsError: segments.error } : {}),
113
+ ...(updated?.webcam ? { webcam: await webcamReport(updated.webcam, record.outputPath) } : {}),
79
114
  ...(updated?.events
80
115
  ? { eventsPath: updated.events.path, events: updated.events.summary ?? {}, ...(updated.events.error ? { eventsError: updated.events.error } : {}) }
81
116
  : {}),