@tmhs/screencast-mcp 0.49.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +13 -8
  2. package/dist/index.js +550 -106
  3. package/dist/wgcRecorder.js +15 -139
  4. package/package.json +8 -4
  5. package/assets/.gitkeep +0 -0
  6. package/assets/icon.png +0 -0
  7. package/dist/cli.js +0 -516
  8. package/dist/context.js +0 -50
  9. package/dist/prompts.js +0 -95
  10. package/dist/resources.js +0 -93
  11. package/dist/server.js +0 -174
  12. package/dist/setup.js +0 -438
  13. package/dist/tools/addMarker.js +0 -93
  14. package/dist/tools/assembleHighlights.js +0 -69
  15. package/dist/tools/backdrop.js +0 -89
  16. package/dist/tools/bugReport.js +0 -266
  17. package/dist/tools/burnSubtitles.js +0 -56
  18. package/dist/tools/callout.js +0 -103
  19. package/dist/tools/chapters.js +0 -156
  20. package/dist/tools/clip.js +0 -52
  21. package/dist/tools/compress.js +0 -51
  22. package/dist/tools/concat.js +0 -67
  23. package/dist/tools/contactSheet.js +0 -135
  24. package/dist/tools/convert.js +0 -46
  25. package/dist/tools/crop.js +0 -43
  26. package/dist/tools/cursor.js +0 -87
  27. package/dist/tools/cutByTranscript.js +0 -86
  28. package/dist/tools/cutIdle.js +0 -84
  29. package/dist/tools/deleteRecording.js +0 -119
  30. package/dist/tools/denoise.js +0 -60
  31. package/dist/tools/doctor.js +0 -146
  32. package/dist/tools/exportGif.js +0 -57
  33. package/dist/tools/exportPreset.js +0 -48
  34. package/dist/tools/extractAudio.js +0 -65
  35. package/dist/tools/findText.js +0 -196
  36. package/dist/tools/getMediaInfo.js +0 -36
  37. package/dist/tools/getSession.js +0 -40
  38. package/dist/tools/indexRecording.js +0 -195
  39. package/dist/tools/keystrokeOverlay.js +0 -131
  40. package/dist/tools/listAudioDevices.js +0 -35
  41. package/dist/tools/listSessions.js +0 -28
  42. package/dist/tools/listTargets.js +0 -76
  43. package/dist/tools/listVideoDevices.js +0 -26
  44. package/dist/tools/musicBed.js +0 -55
  45. package/dist/tools/narrate.js +0 -86
  46. package/dist/tools/normalizeAudio.js +0 -60
  47. package/dist/tools/overlay.js +0 -62
  48. package/dist/tools/pauseRecording.js +0 -44
  49. package/dist/tools/pipeline.js +0 -400
  50. package/dist/tools/readEvents.js +0 -98
  51. package/dist/tools/redactRegion.js +0 -70
  52. package/dist/tools/reframe.js +0 -46
  53. package/dist/tools/resumeRecording.js +0 -46
  54. package/dist/tools/reviewRecording.js +0 -163
  55. package/dist/tools/sampleFrames.js +0 -200
  56. package/dist/tools/saveReplay.js +0 -90
  57. package/dist/tools/scale.js +0 -44
  58. package/dist/tools/screenDiff.js +0 -86
  59. package/dist/tools/screenshot.js +0 -76
  60. package/dist/tools/searchRecording.js +0 -79
  61. package/dist/tools/speed.js +0 -46
  62. package/dist/tools/startRecording.js +0 -398
  63. package/dist/tools/stepGuide.js +0 -250
  64. package/dist/tools/stopRecording.js +0 -132
  65. package/dist/tools/titleCard.js +0 -67
  66. package/dist/tools/transcribe.js +0 -66
  67. package/dist/tools/trim.js +0 -57
  68. package/dist/tools/waitForChange.js +0 -128
  69. package/dist/tools/xfadeTransition.js +0 -58
  70. package/dist/tools/zoom.js +0 -149
  71. package/dist/utils/anim.js +0 -54
  72. package/dist/utils/animExport.js +0 -56
  73. package/dist/utils/argPaths.js +0 -39
  74. package/dist/utils/audio.js +0 -113
  75. package/dist/utils/audioDevices.js +0 -107
  76. package/dist/utils/backdrop.js +0 -151
  77. package/dist/utils/bugReport.js +0 -172
  78. package/dist/utils/callout.js +0 -90
  79. package/dist/utils/calloutAssets.js +0 -42
  80. package/dist/utils/capabilities.js +0 -96
  81. package/dist/utils/captions.js +0 -103
  82. package/dist/utils/chapters.js +0 -227
  83. package/dist/utils/consent.js +0 -29
  84. package/dist/utils/cursor.js +0 -317
  85. package/dist/utils/diff.js +0 -184
  86. package/dist/utils/errors.js +0 -29
  87. package/dist/utils/events.js +0 -403
  88. package/dist/utils/expr.js +0 -11
  89. package/dist/utils/ffmpeg.js +0 -285
  90. package/dist/utils/fontCoverage.js +0 -177
  91. package/dist/utils/fonts.js +0 -154
  92. package/dist/utils/gpu.js +0 -219
  93. package/dist/utils/idle.js +0 -91
  94. package/dist/utils/images.js +0 -38
  95. package/dist/utils/jobs.js +0 -129
  96. package/dist/utils/keystrokes.js +0 -155
  97. package/dist/utils/lifecycle.js +0 -233
  98. package/dist/utils/logging.js +0 -75
  99. package/dist/utils/media.js +0 -574
  100. package/dist/utils/monitors.js +0 -124
  101. package/dist/utils/narrate.js +0 -233
  102. package/dist/utils/ocr.js +0 -222
  103. package/dist/utils/ocrScan.js +0 -91
  104. package/dist/utils/paths.js +0 -155
  105. package/dist/utils/pause.js +0 -190
  106. package/dist/utils/pipeline.js +0 -361
  107. package/dist/utils/player.js +0 -85
  108. package/dist/utils/pool.js +0 -29
  109. package/dist/utils/produce.js +0 -298
  110. package/dist/utils/recipes.js +0 -71
  111. package/dist/utils/recorder.js +0 -173
  112. package/dist/utils/recordingFiles.js +0 -32
  113. package/dist/utils/recordingIndex.js +0 -312
  114. package/dist/utils/replay.js +0 -283
  115. package/dist/utils/resolveTarget.js +0 -25
  116. package/dist/utils/retention.js +0 -48
  117. package/dist/utils/roots.js +0 -43
  118. package/dist/utils/sessions.js +0 -499
  119. package/dist/utils/sheet.js +0 -59
  120. package/dist/utils/stepGuide.js +0 -231
  121. package/dist/utils/steps.js +0 -88
  122. package/dist/utils/still.js +0 -38
  123. package/dist/utils/targetList.js +0 -64
  124. package/dist/utils/targets.js +0 -265
  125. package/dist/utils/timeline.js +0 -85
  126. package/dist/utils/toolSpec.js +0 -31
  127. package/dist/utils/toolsets.js +0 -134
  128. package/dist/utils/transcriptCut.js +0 -149
  129. package/dist/utils/validate.js +0 -23
  130. package/dist/utils/waitLoop.js +0 -50
  131. package/dist/utils/wgc.js +0 -84
  132. package/dist/utils/windows.js +0 -192
  133. package/dist/utils/zoom.js +0 -234
@@ -1,79 +0,0 @@
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 fingerprint = fingerprintFile(source.path);
33
- const indexPath = findIndex(source.path, subdir("edits"), fingerprint);
34
- const index = indexPath ? readIndex(indexPath) : null;
35
- if (!indexPath || !index) {
36
- throw new ScreencastError(`No index for ${source.path}.`, "Run index_recording on it first.");
37
- }
38
- const stale = !sameFingerprint(index.fingerprint, fingerprint);
39
- const { hits, total } = searchIndex(index, args.query, {
40
- regex: args.regex === true,
41
- limit: args.limit,
42
- video: source.path,
43
- fingerprint,
44
- });
45
- const want = Math.min(clampInlineCount(args.images ?? 0), hits.length);
46
- let images = [];
47
- if (want > 0) {
48
- requireFfmpeg();
49
- const work = mkdtempSync(join(tmpdir(), "screencast-search-"));
50
- try {
51
- const shots = [];
52
- for (const [i, hit] of hits.slice(0, want).entries()) {
53
- const at = hit.t === hit.start ? keyframeTime(hit) : hit.t;
54
- const out = join(work, `hit_${i}.png`);
55
- await runFfmpeg(buildSampleAtTimestampArgs(source.path, at, out), 60_000, { signal: extra.signal });
56
- if (existsSync(out))
57
- shots.push(out);
58
- }
59
- images = (await encodeInlineImages(shots, THUMB_WIDTH, want)).images;
60
- }
61
- finally {
62
- rmSync(work, { recursive: true, force: true });
63
- }
64
- }
65
- return okResponse({
66
- indexPath,
67
- query: args.query,
68
- total,
69
- hits,
70
- ...(total > hits.length ? { more: total - hits.length } : {}),
71
- ...(index.ocr ? {} : { note: "The index has no screen text (OCR was unavailable when it was built)." }),
72
- ...(stale ? { stale: true, warning: "The recording changed since it was indexed; run index_recording again." } : {}),
73
- }, images);
74
- }
75
- catch (error) {
76
- return errorResponse(error);
77
- }
78
- });
79
- }
@@ -1,46 +0,0 @@
1
- import { z } from "zod";
2
- import { existsSync } from "node:fs";
3
- import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
- import { OUTPUT_PATH, WRITES_FILE } from "../utils/toolSpec.js";
5
- import { requireFfmpeg, probeMedia } from "../utils/ffmpeg.js";
6
- import { runEditJob } from "../utils/jobs.js";
7
- import { buildSpeedArgs, editOutputExt, assertEditContainer } from "../utils/media.js";
8
- import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
9
- const inputSchema = {
10
- input: z.string().min(1).describe("Path to the source video."),
11
- factor: z.number().positive().describe("Speed multiplier: >1 is faster, <1 is slower (e.g. 2 = double speed)."),
12
- output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
13
- overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
14
- };
15
- export function register(server) {
16
- server.registerTool("speed", {
17
- title: "Change Speed",
18
- description: "Change playback speed by a factor (>1 faster, <1 slower) and re-encode. " +
19
- "Audio is retempo'd to match when the source has an audio track.",
20
- inputSchema,
21
- outputSchema: OUTPUT_PATH,
22
- annotations: WRITES_FILE,
23
- }, async (args, extra) => {
24
- try {
25
- requireFfmpeg();
26
- if (!existsSync(args.input)) {
27
- throw new ScreencastError(`Input file not found: ${args.input}`);
28
- }
29
- const { audioCodec, durationSec } = await probeMedia(args.input);
30
- assertEditContainer(args.output);
31
- const ext = editOutputExt(args.input);
32
- const output = resolveOutput(args.output, subdir("edits"), `speed-${stamp()}-${rand()}${ext}`, args.overwrite);
33
- const ffArgs = buildSpeedArgs(args.input, output, args.factor, audioCodec !== null);
34
- await runEditJob(ffArgs, {
35
- output,
36
- durationSec: durationSec !== null ? durationSec / args.factor : null,
37
- inputDurationSec: durationSec,
38
- extra,
39
- });
40
- return okResponse({ outputPath: output, factor: args.factor, audio: audioCodec !== null });
41
- }
42
- catch (error) {
43
- return errorResponse(error);
44
- }
45
- });
46
- }
@@ -1,398 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { z } from "zod";
3
- import { errorMessage, errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
- import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
5
- import { requireFfmpeg, wgcAvailable } from "../utils/ffmpeg.js";
6
- import { fileURLToPath } from "node:url";
7
- import { buildCaptureArgs, captureFrame, DEFAULT_FPS, DEFAULT_QUALITY, DEFAULT_MAX_RECORDING_SEC, MAX_RECORDING_CAP_SEC, resolveMaxDuration, captureKeyframeArgs, } from "../utils/targets.js";
8
- import { resolveCaptureTarget } from "../utils/resolveTarget.js";
9
- import { windowMatchReport } from "../utils/windows.js";
10
- import { resolveLoopbackDevice, resolveVideoDevice } from "../utils/audioDevices.js";
11
- import { confirmCapture, describeTarget } from "../utils/consent.js";
12
- import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
13
- import { beginStart, getStore } from "../context.js";
14
- import { killPid, serverIdentity } from "../utils/sessions.js";
15
- import { mkdirSync, rmSync } from "node:fs";
16
- import { buildDdaInputArgs, ddagrabWorks, encoderArgs, getDxgiOutputs, planDdaSource, resolveEncoder, startWithEncoderFallback, } 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";
19
- import { basename, join } from "node:path";
20
- import { MAX_REPLAY_SEC, MIN_REPLAY_SEC, discardReplay, planReplayBuffer, prepareReplayDir, replayEventRotateSec, resetReplaySegments, segmentOutputArgs, } from "../utils/replay.js";
21
- import { DEFAULT_KEY_MODE, eventPaths, parseCaptureStart, prepareEventPaths, startEventLogger, stopEventLogger, summarizeEvents, trackFinalizer, writeEventsFile, } from "../utils/events.js";
22
- const inputSchema = {
23
- target: z
24
- .string()
25
- .describe("full | monitor:<i> (0 = primary) | window:<title> (or window:exe=<app.exe> / window:hwnd=<n>) | " +
26
- "region:<x>,<y>,<w>,<h>. With gdigrab a window's rectangle is resolved once at start (visible, " +
27
- "on top); it does not follow the window."),
28
- exactTitle: z
29
- .boolean()
30
- .optional()
31
- .describe("window: targets match the whole title only, never a substring (default false)."),
32
- fps: z
33
- .number()
34
- .int()
35
- .min(1)
36
- .max(120)
37
- .optional()
38
- .describe(`Frames per second (default ${DEFAULT_FPS}).`),
39
- quality: z
40
- .enum(["draft", "standard", "high"])
41
- .optional()
42
- .describe(`Encoder preset (default ${DEFAULT_QUALITY}).`),
43
- audio: z
44
- .object({
45
- source: z
46
- .enum(["system", "none"])
47
- .describe("system = what the machine plays (needs a loopback device); none = video only."),
48
- device: z
49
- .string()
50
- .optional()
51
- .describe("dshow loopback device (from list_audio_devices); auto-detected if omitted."),
52
- })
53
- .optional()
54
- .describe("Audio (default none). No microphone capture."),
55
- output: z
56
- .string()
57
- .optional()
58
- .describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),
59
- overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
60
- maxDurationSec: z
61
- .number()
62
- .int()
63
- .min(0)
64
- .max(MAX_RECORDING_CAP_SEC)
65
- .optional()
66
- .describe(`Auto-stop after this many seconds (default ${DEFAULT_MAX_RECORDING_SEC} or ` +
67
- "SCREENCAST_MAX_RECORDING_SEC; max 7 days; 0 = no cap)."),
68
- events: z
69
- .boolean()
70
- .optional()
71
- .describe("Also log clicks, scroll, cursor, and typing (video-timed, video pixels) for read_events " +
72
- "(default false; ~1 s slower start)."),
73
- keys: z
74
- .enum(["masked", "shortcuts"])
75
- .optional()
76
- .describe("With events: masked (default) logs typing only as 0.5 s-grid bursts, never keys; shortcuts " +
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.'),
82
- backend: z
83
- .enum(["gdigrab", "wgc", "ddagrab"])
84
- .optional()
85
- .describe("gdigrab (default): the screen rectangle. wgc (window: targets, FFmpeg 8+): the window's own " +
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."),
100
- replayBufferSec: z
101
- .number()
102
- .int()
103
- .min(MIN_REPLAY_SEC)
104
- .max(MAX_REPLAY_SEC)
105
- .optional()
106
- .describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab or ddagrab, not wgc."),
107
- };
108
- function frameSize(target, monitors) {
109
- try {
110
- const f = captureFrame(target, monitors);
111
- return { width: f.w, height: f.h };
112
- }
113
- catch {
114
- return undefined;
115
- }
116
- }
117
- function webcamStart(watch, audio) {
118
- const ms = parseCaptureStart(watch.head(), audio ? 2 : 1);
119
- return ms !== null ? { webcamStartMs: ms } : {};
120
- }
121
- export function register(server) {
122
- server.registerTool("start_recording", {
123
- title: "Start Recording",
124
- description: "Start a background screen recording. Returns a session id; finalize it with stop_recording. " +
125
- "Never auto-starts.",
126
- inputSchema,
127
- outputSchema: looseOutput({
128
- sessionId: z.string(),
129
- status: z.string(),
130
- backend: z.string(),
131
- outputPath: z.string(),
132
- }),
133
- annotations: WRITES_FILE,
134
- }, async (args, extra) => {
135
- let release = () => { };
136
- try {
137
- release = beginStart();
138
- const { ffmpeg } = requireFfmpeg();
139
- const hideCursor = args.cursor === "events";
140
- if (hideCursor)
141
- args.events = true;
142
- const { target, monitors, window } = await resolveCaptureTarget(args.target, {
143
- exactTitle: args.exactTitle,
144
- backend: args.backend,
145
- });
146
- const backend = args.backend ?? "gdigrab";
147
- if (backend === "wgc") {
148
- if (!window?.hwnd)
149
- throw new ScreencastError('backend "wgc" records one window: use a window: target.');
150
- if (args.audio?.source === "system")
151
- throw new ScreencastError('Audio is not supported with backend "wgc" yet; use gdigrab.');
152
- if (!wgcAvailable()) {
153
- throw new ScreencastError('backend "wgc" needs FFmpeg 8 or newer (the gfxcapture filter). Use gdigrab, or update ffmpeg.');
154
- }
155
- }
156
- if (args.replayBufferSec !== undefined && backend === "wgc") {
157
- throw new ScreencastError('replayBufferSec is not supported with backend "wgc" yet; use gdigrab or ddagrab.');
158
- }
159
- const replay = args.replayBufferSec !== undefined ? planReplayBuffer(args.replayBufferSec) : null;
160
- const fps = args.fps ?? DEFAULT_FPS;
161
- const quality = args.quality ?? DEFAULT_QUALITY;
162
- const maxDurationSec = resolveMaxDuration(args.maxDurationSec);
163
- const output = resolveOutput(args.output, subdir("recordings"), `rec-${stamp()}-${rand()}.mp4`, args.overwrite);
164
- const audio = args.audio?.source === "system"
165
- ? { device: await resolveLoopbackDevice(args.audio.device) }
166
- : undefined;
167
- if (args.webcam && (backend === "wgc" || replay)) {
168
- throw new ScreencastError("webcam works with backend gdigrab or ddagrab, without replayBufferSec.");
169
- }
170
- const webcamDevice = args.webcam ? await resolveVideoDevice(args.webcam.device) : undefined;
171
- const dda = backend === "ddagrab" ? planDdaSource(captureFrame(target, monitors), await getDxgiOutputs()) : null;
172
- await confirmCapture(server, (replay ? `Keep a rolling ${replay.bufferSec} s replay buffer of ` : "Record ") +
173
- `${describeTarget(args.target, window)} ` +
174
- (maxDurationSec > 0 ? `for up to ${maxDurationSec} s` : "with no time limit") +
175
- (audio ? `, with system audio (${audio.device})` : ", without audio") +
176
- (webcamDevice ? `, with the webcam (${webcamDevice})` : "") +
177
- (args.events ? ", logging mouse clicks and typing" : "") +
178
- (replay ? ", kept only until save_replay or stop_recording { save: true } writes it out?" : `, saved to ${output}?`), extra.signal);
179
- let pick = await resolveEncoder(args.encoder ?? (backend === "ddagrab" ? "auto" : "x264"), backend === "ddagrab" ? "ddagrab" : "gdigrab", ffmpeg, undefined, backend === "wgc" ? undefined : frameSize(target, monitors));
180
- const ddaUsable = async (p) => !dda || p.gpuFrames || (await ddagrabWorks(ffmpeg));
181
- if (!(await ddaUsable(pick))) {
182
- throw new ScreencastError("Desktop Duplication (ddagrab) does not capture on this machine (a remote session, or no D3D11 GPU).", 'Use backend "gdigrab".');
183
- }
184
- const webcamRaw = webcamDevice ? webcamPartPath(output, 0) : undefined;
185
- if (webcamRaw)
186
- mkdirSync(partsDir(output), { recursive: true });
187
- const plan = (p) => {
188
- const hw = p.encoder !== "x264";
189
- const captureOpts = {
190
- fps,
191
- quality,
192
- monitors,
193
- audio,
194
- drawMouse: !hideCursor,
195
- ...(dda ? { videoInput: buildDdaInputArgs(dda, fps, { download: !p.gpuFrames, drawMouse: !hideCursor }) } : {}),
196
- ...(hw ? { videoCodec: encoderArgs(p.encoder, quality, { gpuFrames: p.gpuFrames }) } : {}),
197
- };
198
- const webcam = webcamDevice
199
- ? { device: webcamDevice, ...(hw ? { codec: encoderArgs(p.encoder, quality) } : {}) }
200
- : undefined;
201
- const captureArgs = buildCaptureArgs(target, {
202
- ...captureOpts,
203
- output,
204
- maxDurationSec,
205
- ...(webcam && webcamRaw ? { webcam: { ...webcam, output: webcamRaw } } : {}),
206
- });
207
- return { captureOpts, webcam, ffArgs: replay ? segmentOutputArgs(captureArgs, replay) : captureArgs };
208
- };
209
- if (replay)
210
- prepareReplayDir(replay);
211
- const keyMode = args.keys ?? DEFAULT_KEY_MODE;
212
- const evPaths = args.events ? (replay ? { raw: join(replay.dir, "events.raw"), jsonl: "" } : eventPaths(output)) : null;
213
- if (evPaths && !replay)
214
- prepareEventPaths(evPaths, args.overwrite);
215
- let frame = args.events
216
- ? captureFrame(target, monitors)
217
- : null;
218
- const logger = evPaths
219
- ? await startEventLogger(evPaths.raw, keyMode, replay ? { rotateSec: replayEventRotateSec(replay.bufferSec) } : {})
220
- : null;
221
- const id = `rec-${stamp()}-${rand(6)}`;
222
- const launch = async (p) => {
223
- const settings = plan(p);
224
- const spawnedAt = Date.now();
225
- const child = backend === "wgc"
226
- ? spawn(process.execPath, [
227
- fileURLToPath(new URL("../wgcRecorder.js", import.meta.url)),
228
- JSON.stringify({ ffmpeg, hwnd: window.hwnd, fps, encode: [...encoderArgs(p.encoder, quality), ...captureKeyframeArgs(fps)], output, maxDurationSec, cursor: !hideCursor }),
229
- ], { stdio: ["pipe", "ignore", "pipe"], windowsHide: true })
230
- : spawn(ffmpeg, settings.ffArgs, {
231
- stdio: ["pipe", "ignore", "pipe"],
232
- windowsHide: true,
233
- });
234
- const watch = watchStderr(child, id);
235
- const settled = await settleCapture(child, watch, backend);
236
- return { ...settings, child, watch, spawnedAt, settled };
237
- };
238
- const started = await startWithEncoderFallback(pick, launch, {
239
- why: (r) => tailLines(r.watch, 3),
240
- canFallback: () => ddaUsable({ encoder: "x264", gpuFrames: false }),
241
- beforeRetry: () => {
242
- if (replay)
243
- resetReplaySegments(replay);
244
- },
245
- });
246
- const { run, failure: retried } = started;
247
- pick = started.pick;
248
- const { child, watch, spawnedAt, captureOpts, webcam } = run;
249
- if (run.settled === "exited") {
250
- if (logger)
251
- await stopEventLogger(logger);
252
- if (evPaths)
253
- rmSync(evPaths.raw, { force: true });
254
- if (replay)
255
- discardReplay(replay);
256
- if (webcamRaw)
257
- rmSync(partsDir(output), { recursive: true, force: true });
258
- throw new ScreencastError(`Recording failed to start (${backend === "wgc" ? "window capture" : "ffmpeg"} exited immediately):\n${tailLines(watch)}` +
259
- (retried ? `\n(Retried with libx264 after ${retried})` : ""));
260
- }
261
- const startMs = captureStartMs(watch, backend, spawnedAt);
262
- if (backend === "wgc" && frame && window?.client) {
263
- const m = /wgc: (\d+)x(\d+)/.exec(watch.head());
264
- frame = { x: window.client.x, y: window.client.y, w: m ? Number(m[1]) : frame.w, h: m ? Number(m[2]) : frame.h };
265
- }
266
- const record = {
267
- id,
268
- target: args.target,
269
- outputPath: output,
270
- fps,
271
- quality,
272
- pid: child.pid ?? null,
273
- pidSpawnedAt: spawnedAt,
274
- ...serverIdentity(),
275
- status: "recording",
276
- startedAt: new Date().toISOString(),
277
- videoStartMs: startMs,
278
- ...(maxDurationSec > 0 ? { maxDurationSec } : {}),
279
- ...(window ? { matchedWindow: window.matchedTitle } : {}),
280
- ...(evPaths && !replay ? { events: { path: evPaths.jsonl, keys: keyMode } } : {}),
281
- ...(replay
282
- ? {
283
- replay: {
284
- ...replay,
285
- ...(evPaths && frame
286
- ? { events: { raw: evPaths.raw, keys: keyMode, startMs, frame } }
287
- : {}),
288
- },
289
- }
290
- : {}),
291
- backend,
292
- ...(pick.encoder !== "x264" ? { encoder: pick.encoder } : {}),
293
- ...(backend !== "wgc" && !replay
294
- ? {
295
- capture: { target, opts: captureOpts, ...(webcam ? { webcam } : {}) },
296
- segments: {
297
- parts: [],
298
- current: {
299
- path: output,
300
- startMs,
301
- ...(webcamRaw ? { webcamPath: webcamRaw, ...webcamStart(watch, !!audio) } : {}),
302
- },
303
- },
304
- }
305
- : {}),
306
- ...(webcamDevice
307
- ? {
308
- webcam: {
309
- device: webcamDevice,
310
- path: webcamOutputPath(output),
311
- corner: args.webcam?.corner ?? "bottom_right",
312
- size: args.webcam?.size ?? DEFAULT_WEBCAM_SIZE,
313
- shape: args.webcam?.shape ?? "rect",
314
- },
315
- }
316
- : {}),
317
- processImage: backend === "wgc" ? basename(process.execPath).toLowerCase() : "ffmpeg.exe",
318
- };
319
- const store = getStore();
320
- store.attachChild(id, child);
321
- try {
322
- store.create(record);
323
- }
324
- catch (err) {
325
- store.detachChild(id);
326
- if (child.pid !== undefined)
327
- killPid(child.pid);
328
- if (logger)
329
- await stopEventLogger(logger);
330
- if (evPaths)
331
- rmSync(evPaths.raw, { force: true });
332
- if (replay)
333
- discardReplay(replay);
334
- if (webcamRaw)
335
- rmSync(partsDir(output), { recursive: true, force: true });
336
- throw new ScreencastError(`Recording stopped: the session registry could not be written (${errorMessage(err)}).`);
337
- }
338
- if (logger && replay) {
339
- const exited = new Promise((resolve) => child.once("exit", () => resolve()));
340
- trackFinalizer(id, exited.then(() => stopEventLogger(logger)));
341
- }
342
- else if (logger && evPaths && frame) {
343
- trackFinalizer(id, sessionEnded(id).then(async () => {
344
- await stopEventLogger(logger);
345
- try {
346
- const clock = eventClock(store.get(id)?.segments, startMs, Date.now());
347
- const events = writeEventsFile(evPaths, { ...clock, frame });
348
- store.tryUpdate(id, {
349
- events: { path: evPaths.jsonl, keys: keyMode, count: events.length, summary: summarizeEvents(events) },
350
- });
351
- }
352
- catch (err) {
353
- store.tryUpdate(id, {
354
- events: { path: evPaths.jsonl, keys: keyMode, error: errorMessage(err) },
355
- });
356
- }
357
- }).catch((err) => {
358
- process.stderr.write(`Event log for ${id} failed: ${errorMessage(err)}\n`);
359
- }));
360
- }
361
- attachExitHandler(store, id, child, { backend, maxDurationSec, spawnedAt, watch });
362
- return okResponse({
363
- sessionId: id,
364
- status: "recording",
365
- backend,
366
- outputPath: output,
367
- pid: record.pid,
368
- fps,
369
- quality,
370
- audioDevice: audio?.device ?? null,
371
- maxDurationSec: maxDurationSec > 0 ? maxDurationSec : null,
372
- encoder: pick.encoder,
373
- ...(pick.note ? { encoderNote: pick.note } : {}),
374
- ...(dda ? { gpuFrames: pick.gpuFrames } : {}),
375
- ...(webcamDevice ? { webcam: { device: webcamDevice, path: webcamOutputPath(output) } } : {}),
376
- ...(window ? windowMatchReport(window) : {}),
377
- ...(evPaths && !replay ? { eventsPath: evPaths.jsonl, keys: keyMode } : {}),
378
- ...(replay
379
- ? { replay: { bufferSec: replay.bufferSec, segmentSec: replay.segmentSec, dir: replay.dir, events: !!evPaths } }
380
- : {}),
381
- note: (replay
382
- ? `Replay buffer running: save_replay keeps the last seconds (up to ${replay.bufferSec}s) without stopping it; ` +
383
- "stop_recording discards the buffer unless save: true (then it writes outputPath)."
384
- : "Call stop_recording with this sessionId to finalize the file" +
385
- (backend === "wgc" ? "." : " (pause_recording/resume_recording leave stretches out).")) +
386
- (maxDurationSec > 0
387
- ? ` It stops on its own after ${maxDurationSec}s (maxDurationSec).`
388
- : ""),
389
- });
390
- }
391
- catch (error) {
392
- return errorResponse(error);
393
- }
394
- finally {
395
- release();
396
- }
397
- });
398
- }